Angel Miranda

Max Payne: forensic reconciliation book

Forensic log · November 2026

Before pushing the next production release of maxpayne.cc, I ran a full forensic audit across ~23,800 lines spanning all five layers of the stack: the x86-to-C static recompiler, the Win32/FS/threads host, the D3D8/DirectSound/DirectInput host, the web/mobile/Safari frontend, and the Cloudflare R2 packaging pipeline. The audit named 89 concrete findings (36 real bugs, 16 swallowed errors, 8 implicit state machines, 12 structural hurdles, and 17 cross-layer inconsistencies) and reconciled them in four waves across 36 files (+618 / -443 lines), gated by two default principles: every UI change ships for both desktop and phone, and a phone always plays the light version (2001 textures, 640 MB low memory, 30 fps).

89 findingsnamed & line-verified across 5 layers
36 filesreconciled in 4 waves (+618 / -443)
2,000 funcs7,940 cases vs Unicorn, 0 crashes (difftest.py pass)
2 defaultsdual desktop+phone UI · mandatory phone light version

01 · Wave 1 — Safari OPFS, AudioWorklet, phone sharpness & save integrity

Real phone tests showed blurry text/HUD/comics, touch lag, and Safari hazards. Auditing the web and save layers exposed the exact mechanisms:

SiteRoot causeReconciliation
web/launcher-controls.jscreateWritable() throws on Safari OPFS (only createSyncAccessHandle() in a Worker exists)Routed OPFS writes through MPFiles.save('PUT', 'registry.tsv', false, bytes)
web/opfs.jssave() posted whole backing ArrayBuffer (ignoring byteOffset/byteLength); Worker lacked onerrorCopied exact view slice into a fresh ArrayBuffer; added onerror/onmessageerror rejecting pending promises
web/audio.jst = w - target went negative at startup (NaN output + u32 wraparound resync storm); 44.1 kHz hardcoded against 48 kHz iOS/BT audioClamped t = Math.max(0, w - target); added ratio = 44100 / ctx.sampleRate linear resampler; revoked blob: URL; added touchend unlock & .catch()
web/index.html & web/gpu.jsplaySize() crushed 19.5:9 phones to 2:1 960×480; touching Gamma cleared the 30 fps phone cap; 9-tap FXAA blurred phone HUD; showQueued() could deadlock gpu_wait()Preserved true landscape phone aspect at 480–540p; hard-enforced 30 fps on non-desktop; disabled FXAA on phones; wrapped showQueued() in try/finally; cached rect via ResizeObserver; destroyed grown GPU buffers
web/touch.js & web/input.jsMenu tap() waited 3 rAFs (25 ms on 120 Hz < 33.3 ms game frame); double-tap released held trigger; app switch clicked menus; NaN poisoned remX/remYWaited on real game frames (RN_PACE.shown); cleared pending MIN_PRESS timer on re-press; called cancel() on visibilitychange; locked single stickId; guarded Number.isFinite and moved mouseup to window
host/files.c & host/win32.cUnchecked malloc in save_send() risked truncating saves to 0 bytes; reg_flush() cleared reg_dirty before layer_store(); unchecked strchr on truncated listingsAborted save_send() and triggered rnSaveFailed on OOM; cleared reg_dirty only on layer_store() == 0; guarded all strchr/save_get against NULL

In plain termsOn a 120 Hz phone capped to 30 fps, waiting three display frames was faster than a single game frame — so menu taps landed in the top-left corner. And touching brightness in the launcher quietly deleted the 30 fps phone cap. Both are now structural invariants.

02 · Wave 2 — Cloudflare R2 deploy & local serve contract

Four cross-layer drifts lived between the packager, the uploader, and the local dev server:

// tools/build_public.py, tools/upload_r2.py, tools/serve.py
--dist default: build/public (build_public.py) vs build/public-cdn (upload_r2.py)
upload_r2.py: .css in assets (24 h cache), manifest.json uploaded
serve.py: self._cache leaked across HTTP/1.1 keep-alive; missing CORP header
--cdn defaults to build/public-cdn; atomic tmp + os.replace on game-z/*.gz
.css moved to page (no-cache); manifest.json skipped; standard R2 headers only
serve.py resets _cache per request, sends CORP: same-origin, safe Range + PUT tmp

Reconciled. CSS updates ship atomically with HTML/JS under no-cache, internal build manifests never leak to R2, parallel game-z/ compression can no longer produce truncated .gz pieces, and local serve.py matches the production COOP/COEP/CORP contract.

03 · Wave 3 — D3D8, DirectSound, DirectInput, Win32, Threads & Lifter

SubsystemBugs & leaks closed
host/d3d8.c, sm1.c, ffp.cReleased VB/IB refs in DrawPrimitiveUP*; fixed vram_used accounting and emitted GPU_FREE on released render targets; refcounted SetRenderTarget; freed deleted shaders/stateblocks; allowed COLORWRITEENABLE = 0; fixed OP_TEXKILL to read interpolated texcoords; clamped VS constants to GPU_NVC (84); masked spotlight falloff == 0 outside the cone.
host/dsound.c, dinput8.cMarked shared PCM flag on src in DuplicateSoundBuffer (closing a live UAF); avoided double 4-tap Hermite on mono voices; checked pthread_create and OOM slot cleanup; fixed C operator precedence (&& vs |) in BuildActionMap; fixed DIGDD_PEEK trace index; freed temporary Enum* guest structs.
host/win32.c, files.c, threads.cAdded GFile.refs + gf_retain() for CreateFileMappingA (closing UAF/double-free); fixed uint32_t wraparound in heap_alloc/VirtualAlloc_; replaced 7.3 s 100% CPU busy-spin retry with Atomics.wait; detached exited threads + 4 MB stack under RN_LOWMEM; monotonic timer_id without aliasing; counted main-thread Sleep_ in idle_main_ms; removed closed mutexes from named[16].
tools/recomp/lift.py, build.py, images.py, fast.c, dispatch.cGuarded 32-bit idiv (INT64_MIN / -1), x87 fscale NaN/Inf/range traps, and 16-bit bt* memory+reg stride; included host.h/images.h/funcs.h in incremental mtimes and failed hard when brotli is missing under RN_BR>0; preserved duplicate export aliases and #ordinal forwarders; added guest_ok() checks across fast.c/dispatch.c and slot reuse in busy[64].

In plain termsA 640 MB phone tab cannot afford 16 MB leaked thread stacks, 7-second busy-spins holding the GIL, or D3D8 shaders/buffers that never decrement their counters. Closing these leaks together makes long multi-level sessions stay flat in memory.

04 · Wave 4 — Explicit state machines, launcher cleanup & orphan removal

  • Lifecycle state machine: Consolidated boot, launcher, live backdrop, pause handoff, and reload in web/index.html into one explicit appPhase with a single writer setPhase(); stopped F2 from leaking into the game.
  • Host state & orphans: Synced F3/F6 cheat toggles in host/cheats.c to live player bits; split gamestate_frame() memcpy around pub.nav_req so JS requests are never clobbered; fixed user32.c dead-window lookup, CreateWindowExA_ frees, and GetKeyState_ high bit (0xffff8000); removed orphan NFSU1 files host/bridge.c and host/net.c.
  • Launcher & telemetry polish: Dynamic guestLimit from RN_GUEST_MB in web/telemetry.js; blur handler in web/ffwd.js to clear 4× turbo; fixed multi-char typeahead in web/launcher.js; fixed overlapping duck() gain drift and resume(offset) in web/launcher-audio.js; released WebGL context in web/launcher-tear.js and revoked thumbnail blob: URLs; cleaned residual Spanish UI strings.

Verified. All 12 modified JS files + 2 inline scripts in web/index.html pass vm.Script; all 6 Python tools pass py_compile and contract assertions; all 14 modified C files pass both native cc and emcc -pthread with zero new warnings; difftest.py passes 2,000 functions / 7,940 cases with 0 crashes; production RN_BR=11 build and R2 upload verified live. The Bullet Time plate at the top is painted stroke by stroke on Canvas 2D: layered washes and dry-brush ink over cold-press paper tooth (click it to watch it repaint).

Links: repo · Max Payne in a browser tab · maxpayne.cc

Antes de subir la siguiente versión a producción de maxpayne.cc, corrí una auditoría forense completa sobre ~23,800 líneas en las cinco capas del proyecto: el recompilador estático x86→C, el host Win32/FS/hilos, el host D3D8/DirectSound/DirectInput, la capa web/móvil/Safari y el pipeline de empaquetado a Cloudflare R2. La auditoría nombró 89 hallazgos concretos (36 bugs reales, 16 errores tragados, 8 máquinas de estado implícitas, 12 hurdles estructurales y 17 inconsistencias entre capas) y los reconcilió en cuatro oleadas sobre 36 archivos (+618 / -443 líneas), gobernadas por dos principios de default: todo cambio de UI se hace para escritorio y teléfono, y el teléfono siempre juega la versión ligera (texturas 2001, 640 MB de memoria baja, 30 fps).

89 hallazgosnombrados y verificados con línea en 5 capas
36 archivosreconciliados en 4 oleadas (+618 / -443)
2,000 funcs7,940 casos vs Unicorn, 0 crashes (difftest.py pass)
2 defaultsUI dual escritorio+teléfono · versión ligera obligatoria en móvil

01 · Oleada 1 — Safari OPFS, AudioWorklet, nitidez en teléfono e integridad de saves

Las pruebas reales en teléfono mostraron texto/HUD/cómics borrosos, input lag táctil y trampas de Safari. Auditar la capa web y de guardado expuso las causas exactas:

SitioCausa raízReconciliación
web/launcher-controls.jscreateWritable() truena en Safari OPFS (solo existe createSyncAccessHandle() en Worker)Se enrutaron las escrituras OPFS por MPFiles.save('PUT', 'registry.tsv', false, bytes)
web/opfs.jssave() mandaba el ArrayBuffer completo (ignorando byteOffset/byteLength); el Worker no tenía onerrorSe copia la rebanada exacta a un ArrayBuffer limpio; onerror/onmessageerror rechazan promesas pendientes
web/audio.jst = w - target quedaba negativo al arrancar (NaN + tormenta de resyncs); 44.1 kHz fijo frente a 48 kHz en iOS/Bluetootht = Math.max(0, w - target); remuestreador lineal por ratio = 44100 / ctx.sampleRate; revocación de blob:; desbloqueo con touchend y .catch()
web/index.html y web/gpu.jsplaySize() aplastaba teléfonos 19.5:9 a 2:1 960×480; tocar Gamma quitaba el tope de 30 fps; FXAA 9-tap emborronaba el HUD móvil; showQueued() podía deadloquear gpu_wait()Se conserva el aspecto real en paisaje a 480–540p; tope duro de 30 fps en móvil; FXAA apagado en teléfono; try/finally en showQueued(); rect cacheado con ResizeObserver; .destroy() al crecer buffers GPU
web/touch.js y web/input.jstap() esperaba 3 rAFs (25 ms en 120 Hz < 33.3 ms de un frame a 30 fps); doble toque soltaba el gatillo; cambiar de app daba click; NaN envenenaba remX/remYEspera frames reales del juego (RN_PACE.shown); cancela MIN_PRESS al re-presionar; cancel() en visibilitychange; candado stickId; guarda Number.isFinite y mouseup en window
host/files.c y host/win32.cmalloc sin validar en save_send() podía truncar saves a 0 bytes; reg_flush() limpiaba reg_dirty antes de layer_store(); strchr sin guarda ante listados truncadosAborta save_send() y llama rnSaveFailed en OOM; limpia reg_dirty solo cuando layer_store() == 0; guardas contra NULL en strchr/save_get

En simpleEn un teléfono de 120 Hz con el juego a 30 fps, esperar tres cuadros de pantalla era más rápido que un solo cuadro del juego: los toques en menús aterrizaban en la esquina superior izquierda. Y mover el brillo en el launcher borraba en silencio el tope de 30 fps. Ahora ambos son invariantes estructurales.

02 · Oleada 2 — Contrato de deploy a Cloudflare R2 y servidor local

Cuatro desfases entre el empaquetador, el uploader y el servidor de desarrollo local:

// tools/build_public.py, tools/upload_r2.py, tools/serve.py
--dist default: build/public (build_public.py) vs build/public-cdn (upload_r2.py)
upload_r2.py: .css en assets (caché 24 h), manifest.json subido
serve.py: self._cache se filtraba en keep-alive HTTP/1.1; faltaba header CORP
--cdn apunta a build/public-cdn; tmp atómico + os.replace en game-z/*.gz
.css movido a page (no-cache); manifest.json excluido; solo headers estándar en R2
serve.py limpia _cache por petición, envía CORP: same-origin, Range y PUT seguros

Reconciliado. El CSS se despliega atómicamente con HTML/JS bajo no-cache, el inventario interno ya no se sube a R2, la compresión paralela de game-z/ ya no puede dejar piezas .gz truncadas y serve.py local coincide con el contrato COOP/COEP/CORP de producción.

03 · Oleada 3 — D3D8, DirectSound, DirectInput, Win32, hilos y lifter

SubsistemaBugs y fugas cerradas
host/d3d8.c, sm1.c, ffp.cLiberación de refs VB/IB en DrawPrimitiveUP*; contabilidad de vram_used y GPU_FREE en render targets liberados; refcount en SetRenderTarget; liberación de shaders/stateblocks borrados; soporte de COLORWRITEENABLE = 0; OP_TEXKILL sobre coordenadas interpoladas; tope GPU_NVC (84) en constantes VS; máscara de spotlight con falloff == 0 fuera del cono.
host/dsound.c, dinput8.cMarca compartida 0x80000000u también en src al duplicar buffers (cierra UAF); evita doble Hermite 4-tap en voces mono; chequeo de pthread_create y limpieza de slot en OOM; paréntesis de precedencia (&& vs |) en BuildActionMap; índice correcto en DIGDD_PEEK; guest_free en Enum*.
host/win32.c, files.c, threads.cGFile.refs + gf_retain() para CreateFileMappingA (cierra UAF/double-free); corrección de wraparound uint32_t en heap_alloc/VirtualAlloc_; reemplazo del busy-spin de 7.3 s al 100% CPU por Atomics.wait; pthread_detach + pila de 4 MB bajo RN_LOWMEM; timer_id monotónico sin aliasing; Sleep_ contabilizado en idle_main_ms; limpieza de mutexes cerrados en named[16].
tools/recomp/lift.py, build.py, images.py, fast.c, dispatch.cGuardas en idiv 32-bit (INT64_MIN / -1), fscale NaN/Inf/rango y bt* de 16 bits; dependencias de headers (host.h/images.h/funcs.h) y error explícito si falta brotli con RN_BR>0; preservación de alias de exports y forwarders #ordinal; guardas guest_ok() en fast.c/dispatch.c y reciclaje de busy[64].

En simpleUna pestaña móvil de 640 MB no puede permitirse pilas de hilo de 16 MB fugadas, esperas de 7 segundos quemando CPU con el GIL tomado ni shaders/buffers de D3D8 que nunca restan su contador. Cerrar todas esas fugas juntas mantiene plana la memoria en sesiones largas.

04 · Oleada 4 — Máquinas de estado explícitas, pulido del launcher y limpieza

  • Máquina de estado de ciclo de vida: Se consolidaron boot, launcher, backdrop vivo, pausa y recarga en web/index.html bajo un único appPhase con escritor único setPhase(); F2 ya no se filtra al juego.
  • Estado del host y huérfanos: Los toggles F3/F6 en host/cheats.c ahora leen los bits vivos del jugador; gamestate_frame() divide el memcpy alrededor de pub.nav_req para no pisar órdenes de JS; se arreglaron ventanas muertas, liberaciones y GetKeyState_ (0xffff8000) en user32.c; y se eliminaron los archivos huérfanos de NFSU1 host/bridge.c y host/net.c.
  • Pulido de launcher y telemetría: guestLimit dinámico según RN_GUEST_MB en web/telemetry.js; handler blur en web/ffwd.js para soltar el turbo 4×; typeahead multi-carácter corregido en web/launcher.js; duck() con ganancia base canónica y resume(offset) inmediato en web/launcher-audio.js; WEBGL_lose_context en web/launcher-tear.js y revocación de blob: URLs de miniaturas; limpieza de cadenas residuales en español.

Verificado. Los 12 archivos JS modificados + 2 scripts inline de web/index.html pasan vm.Script; las 6 herramientas Python pasan py_compile y aserciones; los 14 archivos C pasan cc nativo y emcc -pthread sin warnings nuevos; difftest.py pasa 2,000 funciones / 7,940 casos con 0 crashes; build de producción RN_BR=11 y despliegue en R2 verificados en vivo. La lámina de Bullet Time de arriba se pinta pincelada a pincelada en Canvas 2D: aguadas por capas y tinta seca sobre grano de papel algodón (haz clic para volver a verla pintarse).

Enlaces: repo · Max Payne en una pestaña del navegador · maxpayne.cc