Max Payne: forensic reconciliation book
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).
+618 / -443)difftest.py pass)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:
| Site | Root cause | Reconciliation |
|---|---|---|
web/launcher-controls.js | createWritable() throws on Safari OPFS (only createSyncAccessHandle() in a Worker exists) | Routed OPFS writes through MPFiles.save('PUT', 'registry.tsv', false, bytes) |
web/opfs.js | save() posted whole backing ArrayBuffer (ignoring byteOffset/byteLength); Worker lacked onerror | Copied exact view slice into a fresh ArrayBuffer; added onerror/onmessageerror rejecting pending promises |
web/audio.js | t = w - target went negative at startup (NaN output + u32 wraparound resync storm); 44.1 kHz hardcoded against 48 kHz iOS/BT audio | Clamped 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.js | playSize() 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.js | Menu 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/remY | Waited 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.c | Unchecked malloc in save_send() risked truncating saves to 0 bytes; reg_flush() cleared reg_dirty before layer_store(); unchecked strchr on truncated listings | Aborted 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
| Subsystem | Bugs & leaks closed |
|---|---|
host/d3d8.c, sm1.c, ffp.c | Released 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.c | Marked 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.c | Added 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.c | Guarded 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.htmlinto one explicitappPhasewith a single writersetPhase(); stoppedF2from leaking into the game. - Host state & orphans: Synced
F3/F6cheat toggles inhost/cheats.cto live player bits; splitgamestate_frame()memcpyaroundpub.nav_reqso JS requests are never clobbered; fixeduser32.cdead-window lookup,CreateWindowExA_frees, andGetKeyState_high bit (0xffff8000); removed orphan NFSU1 fileshost/bridge.candhost/net.c. - Launcher & telemetry polish: Dynamic
guestLimitfromRN_GUEST_MBinweb/telemetry.js;blurhandler inweb/ffwd.jsto clear 4× turbo; fixed multi-char typeahead inweb/launcher.js; fixed overlappingduck()gain drift andresume(offset)inweb/launcher-audio.js; released WebGL context inweb/launcher-tear.jsand revoked thumbnailblob: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).
+618 / -443)difftest.py pass)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:
| Sitio | Causa raíz | Reconciliación |
|---|---|---|
web/launcher-controls.js | createWritable() truena en Safari OPFS (solo existe createSyncAccessHandle() en Worker) | Se enrutaron las escrituras OPFS por MPFiles.save('PUT', 'registry.tsv', false, bytes) |
web/opfs.js | save() mandaba el ArrayBuffer completo (ignorando byteOffset/byteLength); el Worker no tenía onerror | Se copia la rebanada exacta a un ArrayBuffer limpio; onerror/onmessageerror rechazan promesas pendientes |
web/audio.js | t = w - target quedaba negativo al arrancar (NaN + tormenta de resyncs); 44.1 kHz fijo frente a 48 kHz en iOS/Bluetooth | t = 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.js | playSize() 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.js | tap() 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/remY | Espera 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.c | malloc 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 truncados | Aborta 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
| Subsistema | Bugs y fugas cerradas |
|---|---|
host/d3d8.c, sm1.c, ffp.c | Liberació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.c | Marca 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.c | GFile.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.c | Guardas 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.htmlbajo un únicoappPhasecon escritor únicosetPhase();F2ya no se filtra al juego. - Estado del host y huérfanos: Los toggles
F3/F6enhost/cheats.cahora leen los bits vivos del jugador;gamestate_frame()divide elmemcpyalrededor depub.nav_reqpara no pisar órdenes de JS; se arreglaron ventanas muertas, liberaciones yGetKeyState_(0xffff8000) enuser32.c; y se eliminaron los archivos huérfanos de NFSU1host/bridge.cyhost/net.c. - Pulido de launcher y telemetría:
guestLimitdinámico segúnRN_GUEST_MBenweb/telemetry.js; handlerblurenweb/ffwd.jspara soltar el turbo 4×; typeahead multi-carácter corregido enweb/launcher.js;duck()con ganancia base canónica yresume(offset)inmediato enweb/launcher-audio.js;WEBGL_lose_contextenweb/launcher-tear.jsy revocación deblob: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