Skip to content

Stability: the stress harness, crash reports and what they found

The stability pass of 15 and 16 November 2026 made the native port survive real play through the debug overlay's Scenarios and Save states tabs. It was a series of crash hunts driven by tools/port/stress_port.py, with every shared-source change kept type-identical on the PlayStation 2 so make match stays exact.

Crash-finding harness

tools/port/stress_port.py:

  • scenes — one process per scene with DefaultScene, kept alive for --seconds; the run is a crash when the process dies or the log carries a fatal signal/AddressSanitizer report.
  • cycle — one process that switches through every disc scene, one per OPENBLOOD_DEBUG_SCENE_TEST_FRAMES frames, wrapping around.
  • states — one process that saves and reloads a save state every 600 frames.
  • mixed — cycle + state cycle + giving the first item templates.

The scene names come from the ISO (the .SUP member of each archive), and each run keeps its log, a copy of the matching .ips report and a crash signature built from the top stack symbols. --binary points it at the AddressSanitizer build.

Debug hooks (all need OPENBLOOD_DEBUG_UI_TRACE=1, and now work with OPENBLOOD_DEBUG_UI=0):

  • OPENBLOOD_DEBUG_SCENE_TEST=a,b,c loads one scene per period, wrapping.
  • OPENBLOOD_DEBUG_STATE_TEST=cycle saves at frame 60 and reloads at 180, then every 600 frames.
  • OPENBLOOD_DEBUG_ITEM_TEST=1 gives the scene's first item templates.

Crash reporting

The crash handler now writes, before the backtrace:

  • context: scene "...", frame N, game time T s from the main loop;
  • the last 64 user-visible actions (scene loads, state saves/loads, item gives) through port/engine/system/_sdl/crashcontext.cpp;
  • the running script and its object;
  • the last script message id and the eight most frequent message ids (ScriptDeliverMessage counters).

A crash log therefore shows what the overlay did, which scene and frame it happened in, and which script messages were active. SIGTRAP is reported as well (fatal signal SIGTRAP (ZDebugBreak)), so a ZDebugBreak() in recovered code leaves a crash file and a backtrace instead of ending the process silently.

Fixed in this pass

  • Security camera visibility payload (849ab8bc4). UpdateVisible sends three 32-bit words; ZSecurityCamera::OnObjectVisible and the SendSecurityCameraObject* helpers addressed them through REF*. REF is pointer-sized natively, so the extra-flags write landed past the 12-byte message and smashed UpdateVisible's stack canary. The payload now uses endian_REF, and SObjectVisibleUpdate does too, so the three words line up natively. Seen as SIGABRT in ZCheckVisible::UpdateVisible after a guard first saw Hitman.
  • Scheduled event reaping (e9bd6760e). A forked script thread could be reaped after its event was freed; ZScheduledEvent::~ZScheduledEvent then called SetEvent(nullptr, ...) and faulted at 0x40. The write is skipped when the event is gone (native only) and a one-shot scheduledevent: line reports it. Seen as SIGSEGV in ZScheduledUpdate::SetEvent.
  • Perception payload (ac249955f). sPerception is copied to the guest verbatim; its REF fields widened the native struct and shifted level, dress, time and info, so scripts sent commands to bogus objects. The two slots are endian_REF now. Seen as SIGSEGV in ScriptEngine::SendScriptCommand from a script's perception handler.
  • Message cue payload size (36f136820). A script state in a message handler queues the message; the cue copied the guest body size out of the native struct, which is too small when the payload has REF fields. The cue now copies the native size and converts on delivery.
  • Null item creation (0f27f300f). Giving a template whose item cannot be created dereferenced a null item in the inventory; it returns 0 now.
  • Script command targets (1726d1e69). ScriptSendCommand and ScriptEngine::SendScriptCommand now return when the target geom has no event list instead of reading through a pointer that is never null.
  • Pool capacity (2b2a1ddf6, 598aeb815). The item pool ran out while a save state was restored (REFTAB::Add wrote through a null block from ZPoolAllocRefTab::NewBlock). Native tables cost about 2.5x the PS2's per item and a native lazily created free stack costs 632 bytes against 144; the five static pool buffers now hold eight times the PS2 size on the host.
  • Check-inside payload (598aeb815). CCheckInside::SendMessage sent one REF to messages that declare two; the native build sends both (actor zero).
  • Door CanPenetrate payload (8c5d8e5c6). Shooting a gate in M00_main crashed in CDoorBase::Command with a fault address of 0x7500000001. The projectile sends an SHM3ProjectilePenetrate built on its stack (weapon template, projectile, answer, hit count, weapon) and reads the answer and hit count back out of it. The door declared its own SDoorPenetrateQuery with the same member order, which is identical on the PS2 but not on the host: SProjectilePenetrate ends with a bool, so as a base class it rounds up to a pointer boundary, putting the sender's nHitCount at 0x18 and pWeapon at 0x20 while the door's record had pOperator at 0x18. The door read the hit count plus the stale upper half of the stack slot as a weapon pointer, which is where 0x7500000001 came from. The handler now uses the sender's type and its pWeapon/nHitCount names; the PS2 offsets are unchanged and make match stays exact.
  • Save-state item counts and the debug hooks. The periodic N items figure is the port's g_DebugLiveItems, and ZItem::NukeIt resets the item pool at every scene change without running a destructor, so the counter kept the previous scene's total. A save/load cycle therefore looked as if every load duplicated the world (83, 166, 249, ...) while the geom buffer was matching the scene's objects correctly. The counter and the restored-state reference count now reset with the pool, and a cycle keeps the scene's own count. The inventory-menu debug break after loading the long state1 test state came from OPENBLOOD_DEBUG_ITEM_TEST: it gave the player the same four templates every 600 frames, so that state's inventory grew past the menu's 192 entries. The hook now gives one template per call, in a cycle, and skips templates the player already carries.
  • Bomb target sort stride (3a4af69d0). Throwing a bomb in M02_main crashed in QSortCompareFunc (fault 0xb7ebcbf0000000b3). ZHM3ItemBomb::Explode and CExplosionController sorted their ZBaseGeom* target arrays with an element size of 4, the PS2 pointer size, so the comparator read 8-byte pointers at a 4-byte stride. Both calls pass sizeof(m_pTargets[0]) now, which is 4 on the PS2 and 8 on the host.
  • Level table bounds (598aeb815). ZLevelLinking walked past its 13-row table because the table has no empty terminator; the native loops are bounded and reject a null name.

Native-width and undefined-behaviour fixes from UndefinedBehaviorSanitizer

A -fsanitize=undefined build (recovering mode) on a mission load and 30 seconds of play found these; all are port-only branches so the PS2 code and make match are untouched.

  • TIMETYPE(int) shifted a negative value and ZSysInterface::Rand multiplied a signed int until it wrapped. Both now go through uint32 on the host.
  • ZKeysDepack::ReadOffset shifted by a negative count (-bits - bit), which the EE masks to five bits; the host masks explicitly.
  • The OSD alpha ramp converts a negative float to a byte; the host truncates through int32 first.
  • The string manager's blocks start with ZFreeHeader (list pointers). The first block is now eight-aligned and allocation sizes round to eight; the footer stays four bytes because the string terminator clears its last byte (m_NonZero) to mark a block allocated.
  • ComValueInfo records are packed on the host (24 to 16 bytes) because CCom hands out four-byte-aligned records. ZPoolAllocator pads its native ZAllocHeader and rounds sizes to eight for the same reason, and the five static pool buffers are aligned explicitly.
  • ZCONTROL::SetNextFocus and ZWINDOWS::SetFocusedControl no longer dereference a null control when a menu has no focus target yet.

Still reported by UBSan but benign on the host (unaligned loads on arm64/x86; the original data is four-byte aligned by design): ZRawStrip's STempStripsUniqueId and ZActiveImpactPrim in collision data, the ZBinTreeNode-like arrays in old collision boxes, one V3 loop index in ZHM3OverlayCameraClass::Setup (the original writes four V3s through vertex[0][v]), and an enum load in ZHitman3Movement that reads a raw byte.

Cut sequences and the fog screen

The first cutscene in M00 (the guard at the gate) ran its first shot and then froze on a flat fog colour. ZCutSequenceCamera::Init reads the CUTS chunk, which stores PlayStation 2 SCut records: 0x34 bytes each, ending in a four-byte keyframe pointer. The native SCut widens that pointer to eight bytes, so pCuts + m_iCutNum (native units) skipped four bytes per record and put the keyframe block in the wrong place: the first cut read a keyframe 144 frames long but with a garbage first iFrame, m_fStartFrame became -1126130944, the cut never advanced and the camera stayed on the first shot while the script spun. The native build now copies the records with the on-disc 0x34-byte stride into an owned SCut array and points each record's pKeyFrame into the keyframe block. Verified on the user's state1: both cuts play, the camera deactivates, and gameplay resumes. make match stays exact.

Remaining visual gaps (found while playing, 15 November 2026)

  • Inventory background was flat red (fixed). Holding Square opens the inventory, whose item view is a separate ortho-2D camera (view 666, ItemViewCamera, CameraType = 5). ZOldViewSDL::Clear filled every camera viewport with the camera's BackCol, and the item view's is 0xff0000. The PS2's ZOldViewPS2::Clear only fills for letterbox (4), perspective (0) and ortho-2D (5) camera types, and the ortho-2D fill uses GS_TEST_CLEAR_COLOR with a zero-alpha clear sprite, so the alpha test rejects it and the frame under the view survives: the inventory's blurred background is the main view's post-filtered frame. The port now fills only for perspective cameras, which restores the blurred inventory and the M00 briefing background.
  • Tutorial picture-in-picture was grey (fixed by the camera-clear rule below). The PIP is the event camera (ZHM3CameraEventCameraClass), which creates its own view (id 2) with a right-hand viewport. Its camera is ortho-2D (CameraType 5), so on the PS2 its clear is rejected by the alpha test and its own scene draws over the frame; the port's unconditional clear painted the camera's BackCol (0x7f865e) over it first. With the perspective- only clear the PIP shows the live event camera view (the guard at the gate). OPENBLOOD_TRACE_VIEWS=1 keeps the view/camera/post-effect trace.
  • The training mission's video clips are PlayStation 2 .PSS (MPEG-2) streams. They now play (video with FFmpeg, the stream's PCM audio through SDL), and the game's own sound bank is mixed as well; see docs/development/port/sound-and-movies.md. Without FFmpeg at build time the movie player falls back to the skip-everything stub.
  • Host payloads without a guest layout (fixed in 2d16a4fe2). ProjectileHit, CanPenetrate, BiteAttack, Action_GetActionList, ActorDamage and RemoveNamedAction now have SScriptMessageLayout entries, so a script state receives the PS2 record and no message is dropped. The layouts and the two field kinds (SCRIPT_FIELD_STRING, See Message payload layouts for the native conversion and its layout checks.

Pools and long sessions

The port keeps IOI's static pools. Their sizes are PS2 byte counts, so the native buffers scale with sizeof(uintptr), but that only doubles them while a native table object is about 1.7 times the PS2's and a save state can bring several hundred runtime items back. Scene loads and state restores therefore ran the item pool dry, and REFTAB::Add wrote through the null block that ZPoolAllocRefTab::NewBlock returned.

  • The five buffers (items, rooms, link actions, animation callbacks, scheduled events) hold eight times the PS2 bytes; the item pool holds sixteen (1.5 MB), because a restored save state measured 770 KB of live tables.
  • ZItem::ZItem now keeps a state-table member null when the pool cannot afford it, as the shipped code does (the compiler's null check around placement new skips the construction), and the save, load and command paths test the members. ZPoolAllocLinkSortRefTab::CreateFreeStack does the same; a removed entry without a free stack is unlinked and dropped. One-shot warnings name the first failure.
  • OPENBLOOD_POOL_STATS=1 prints every pool's current, size and peak bytes every 300 frames and at each scene unload, and the periodic debug stats line carries the game heap, live items, live free stacks and restored state references. A pool whose peak climbs from scene to scene is a leak; one that settles is at capacity.

Known pre-existing AddressSanitizer reports

  • ZDllSound::AddEvent compares 11 bytes of a shorter event name (the original does the same); run with ASAN_OPTIONS=strict_memcmp=0.
  • CCheckInside::SendMessage passes one REF to checkinsideenter, whose script message declares two; ASan reports an 8-byte read past the 4-byte local. The PS2 original has the same over-read, so it is not fixed here.

Target PIP: one-frame flash and GPU hang

The scripted target PIP (the ZHM3CameraEventCameraClass inset that appears while Diana speaks in the training mission) has two symptoms that share one cause:

  • on the frame it opens and the frame it closes, the whole picture is a flat sepia fill (RGB 131,109,67), HUD included. The frame capture (OPENBLOOD_CAPTURE_DIR plus a burst of captures that a view's scissor-override change armed; that burst was removed once the fix below held) shows it on the two transition frames;
  • the same frame can wedge the GPU: the main thread blocks in SDL_AcquireGPUCommandBuffer -> -[_MTLCommandBuffer init...] -> _dispatch_semaphore_wait_slow because a submitted command buffer never completes, and the game freezes.

The event camera renders through CreateView(2, SCREEN) and sets the view's override scissor from its slide-in viewport. On the activation frame the override scissor is still zero, so the camera's view reports the full main viewport and it paints its backdrop over the finished frame; the same unbounded draw is the likely GPU hang.

Stopgap: ZSysInterfaceSDL::InitConfiguration sets the game's own PipCamEnabled option to false. The PIP is then skipped entirely (the event camera's push is gated on it in ZHM3CameraEventCameraClass::UpdateView*), so the mission is playable. Re-enable it once the second view's viewport and scissor are handled: the open/close frame should clear only the PIP rectangle.

PIP flash: latest evidence

OPENBLOOD_TRACE_DRAW=1 logs every fill and clear with its frame number, and a per-call dump (scissor, vertex count, texture, target, first vertex and colour) for the frames around the scissor-override change.

On a flashing frame the dump shows a normal frame: about 865 textured calls with the main camera's scissor 0,0-502,448, 21 with the PIP strip 502,0-512,448, three render passes, no overflow. The captured image of that same frame is a flat backdrop colour (7d6243) plus the 10 px strip (7f865e). So the scene draws are recorded with the right scissor yet do not appear; the frame reads as the camera's clear colour.

Ruled out so far: the camera clear fill (a "first clear only" guard changed nothing and was reverted), the finish/fade pass (OPENBLOOD_NO_FINISH), the post-filter viewport/scissor (implemented and seeded), oversized sprites, and the swapchain acquire. A Metal frame capture of that frame (Xcode's GPU capture) is the next step: it will show whether the draws are discarded by a pipeline/depth state or landed in another attachment.

PIP flash: cause and fix (16 November 2026)

For one frame, every camera drew with zero transforms, which left a flat fill.

  • Cause.
    • ZHM3CameraEventCameraClass adds its cameras to view 2 when the PIP opens and removes them when it closes.
    • AddCamera and RemoveCamera call ZOldDrawBase::Invalidate, so the next ZRender::BeginScene runs ZOldDrawBase::Flush, which destroys and re-adds the camera entries of every view.
    • The port fills a rebuilt entry's matrices (and the bones and light sets of rebuilt geoms) in UpdateDynamic. That ran after the frame was presented, to prepare the next frame.
    • So on the flush frame, every camera entry (main, event, overlay and OSD) was recorded with zero matrices.
  • What the frame showed.
    • Every mesh and sprite collapsed, and the HUD vanished with them.
    • Only the screen-space fills survived: the main camera's clear (BackCol 7d6243) through the curves, finish and noise passes, plus the PIP's own 10-pixel clear.
    • A per-camera log on that frame showed c2s 0 0 r2c 0 0 for all four entries.
  • Why the PS2 never shows it.
    • Its VIF chain references transforms and bones by address.
    • That chain is sent in Flip, after UpdateDynamic has filled them.
    • The port copies transforms and bones into the draw list when it records a draw.
  • Fix. The pop-in fix, ZOldDrawSDL::UpdateDynamicBeforeDraw, now runs at the end of UpdateLight, between visibility and building the draw list. It fills the rebuilt entries before they are drawn.
  • Verification.
    • Reproduced with OPENBLOOD_DEBUG_STATE_TEST=load:state2, an input script that dismisses the load dialog and walks forward (240 270 cross 1, 300 10000000 lefty -1.0 0 0), and the capture burst.
    • The opening and closing frames of the PIP show the scene, the HUD and Hitman. Before the fix, both were flat 160 KB captures.

Script time budget (16 November 2026)

Gameplay frames took 44 ms, 42 ms of it in the engine update, at about 150,000 guest calls a frame.

  • Cause. The engine's script budgets are in EE cycles, but the port's TimeStampCounter ran on the host counter, which ticks at 24 MHz on Apple Silicon.
    • ZScheduledUpdate::ScheduleEvents runs scheduled scripts for up to m_lMaxCyclesToRun (1,000,000 cycles, 3.4 ms on the PS2). On the 24 MHz counter that was 42 ms.
    • A script yields after 5,000 cycles (SF_CheckTimeout and ZScriptC::SchedUpdate), 17 µs on the PS2 and 208 µs on the port.
    • Polling scripts stayed runnable and used up the whole budget every frame.
  • Fix.
    • ZSysInterfaceSDL::TimeStampCounter now converts the host counter to the EE clock (294.912 MHz), and CycSec is that rate.
    • StepTime uses the constant rather than CycSec, because save states store CycSec, and one written before this change would otherwise run game time 12 times fast.
  • Result. With the same save-state walk, the engine update is about 4.5 ms and about 7,000 guest calls a frame, and frames sit at the 33 ms cap. The target PIP still opens and closes on schedule.

Courtyard floor patches in M04 (16 November 2026)

Dark patches on M04's courtyard floor (save state hospital) changed shape as the camera moved.

  • Cause. So04B_TerrasseFloor_16_01 and _16_02 are the same dot3 prim at the same position, but 16_01 is upside down. It is the slab reused as a ceiling, with its normals facing down, so the light from above leaves it dark. The port drew both copies at the same depth, and they fought.
  • What the PS2 does. VU_dot3render runs backface_culling on every batch (strip_adc_distrib, with no flag), so the upside-down copy is never drawn from above.
  • Fix.
    • SDrawStateSDL::lCull adds back-face culling, and every dot3 pass sets it. The GS's y axis points down, so a triangle whose winding agrees with its normals is clockwise in clip space, and the pipeline therefore culls its counter-clockwise faces.
    • Two other differences from the PS2 code came up while reading it, and both are fixed:
    • Dot3 surfaces are drawn without the strips' depth bias, because the dot3 program projects with m_TransferMatrixHomogeneousScaleBias and has no bias. (Changed on 23 November 2026, see "Posters sinking into normal-mapped walls".)
    • Strip and dot3 prims with normal planes (GetNormalPlanes) are skipped when the camera is behind both planes, as VColClip (0x523 to 0x538) and the dot3 normplanes block do.
  • Checked.
    • The courtyard pan shows an even floor, and the static shadows such as the bench's still draw.
    • An M00 walk looks the same with and without the culling.

Memory card saves (16 November 2026)

At boot the game showed "Memory Card (8MB) (for PlayStation 2) is not inserted", and no profile or save could be created.

  • Cause. The port replaced ZHM3SavePS2 (saveps2.cpp) with a stub that answered "no device" (status 8) to every call.
  • Change. The port now compiles the decompiled save code itself: saveps2.cpp, savegamefilestreamsps2.cpp (the CRC-padded card streams) and hm_icn.cpp (the save icon). Below it, the port emulates the card in the user directory (mc0/):
    • sceMcGetInfo reports a formatted 8 MB PS2 card that has not been swapped.
    • sceMcDelete returns the library's codes (0, or -4 for a missing file).
    • McFileExists also finds directories. The save code tests a profile folder as BESLES-53028Hitman0/.
    • ZSysFilePS2::CreateIconFiles writes icon.sys with Sony's MakeIconSys and the Shift JIS title conversion, then the icon.
    • SaveProgress_Init and SaveProgress_End only reset the byte counters. The PS2 draws its progress bar from a GS vblank callback, and saves to disk finish at once.
    • ReadPS2SystemFile reads SYSTEM.CNF as the PS2 startup does. That gives the save folder its product code and sets the US-build flag.
    • One portability fix in shared source: ZMCCheckFileCRC aligns its directory buffer through uintptr instead of uint32. The unit stays exact.
  • Checked with scripted input:
    • Creating a profile writes the folder and files the PS2 writes, at the PS2 sizes: the profile (0x8800 bytes), three SaveGameN.control/.data pairs (0x6400 and 0xA3000 bytes), SaveGameInfo (0x400), icon.sys (964 bytes, PS2D) and HM_Icon1.ICN.
    • The game then goes on to the main menu.
    • On the next boot, the profile is listed under Load, loads, and reaches the main menu.
    • An in-mission save and load uses the same streams, but has not been played through yet.

No fused multiply-add (16 November 2026)

The Emotion Engine has no fused multiply-add: madd.s and msub.s round the product before they add. Host compilers fuse a + b * c into one fmadd (Apple clang does so by default on arm64), which rounds once and can give a slightly different result.

  • What it broke. The fused form of CheckLineOct's box test turned an exact 0 into a tiny negative number for a line passing through a box corner, so the box was missed. native_asm_test failed on that diagonal.
  • Fix. The port now builds every unit with -ffp-contract=off (flags in port/port.json), so its float results follow the EE's rounding order. checklines.cpp and spherecheckssdl.cpp keep their #pragma STDC FP_CONTRACT OFF, which records why those units depend on it.
  • Checked. Frame times are unchanged: an engine update of about 4.4 ms at the 33 ms frame, in M04 and M00. A capture of the M04 rooftop matches the one from before the change.

Posters sinking into normal-mapped walls (23 November 2026)

In M03's corridors (save state render_bug) the opera poster Pc03A_PosterA_02 and most of its frame were missing from a distance. They popped in when 47 was about 1.5 metres away.

  • Cause.
    • The poster is an ordinary strips prim with bias 0. BiasToScale gives it a scale of 1.0078, so it is drawn as if 0.8% farther away.
    • The wall behind it, Si03C_WallEnd_A_02, is a dot3 prim at every LOD, and the dot3 program takes no bias.
    • The poster hangs about a centimetre off the wall. Beyond about 1.3 metres, 0.8% of the distance is more than that gap, so the wall passed the depth test over the poster.
    • The PS2 code does the same: DrawNormalMapped always uses VU_dot3render, its Z and the strips' Z come from the same near and far planes, and both programs store it with ftoi4. As far as the code shows, the original has this artefact too.
  • Fix. StripsUniforms takes a dot3 flag instead of the bias switch. Dot3 passes now use Dot3BiasScale(): the bias 0 scale less a quarter of one bias step, 1 + 0.2 × 9.75 / 255. A dot3 surface still wins over a coplanar bias 0 strip, as on the PS2, but anything more than 0.02% of the distance in front of it stays in front. A poster 1 cm off the wall now shows out to about 50 metres.
  • Checked. The same walk shows the poster and its whole frame from the far end of the corridor, with no depth fighting on the walls or the skirting.

Review of the system code (26 November 2026)

A review of port/engine/system/ (with the PC data converters in _sdl/pcdata/), port/engine/startup/, port/engine/serializerlib/ and port/engine/enginedata/ found these, all fixed. None showed in the 13-mission sweeps; each was found by reading and, where a test can reach it, confirmed with one.

  • Null item state tables. NewItemStateTable leaves a table null when the item pool is full (the case "Pool capacity" above describes), and every user tests it except the port copies of ZItem::~ZItem, which called Clear through all four, and ZItem::PostLoad, which added to m_pStateRemove untested (diagnosticsoverridesdl.cpp). Both test it now.
  • Unset weapon prims. ZEngineDataBase::PurgePrimBuffer (the game's text and the port copy in enginedata/_sdl/gamedataoverridesdl.cpp) leaves the WeaponPrims entry of a loadout hash that no prim matches unset, then compares it with every prim. The port copy starts them at 0, which matches only entries already cleared.
  • PC-data property wrappers. ZSysFileSDL::GetZipFile serves a PC-data scene's converted .PRP through one of eight wrapper slots, keyed by the archive. Slots were never given back when RemoveBig deleted the archive, so a ninth archive at a new address would have read the raw PC member. In a 15-scene cycle (OPENBLOOD_DEBUG_SCENE_TEST over the premission and postmission scenes of M01 to M06) the archives reused one address and every .PRP was converted, so this was latent; a slot whose archive is no longer mounted is now reused.
  • Gamepad hot-plug. When the open gamepad was removed, a second one already connected stayed unused until it was replugged, because SDL sends no new GAMEPAD_ADDED event for it. ZGameControlDeviceSDL::Close opens it.
  • ISO records. IsoFindInDirectory and IsoListDirectory read a directory record's name without checking that it lies inside its sector; a damaged image could read past the 2,048-byte buffer. Records are bounded now.
  • Prim converter (pcprims.cpp): TArray::Push read its argument after Reserve's realloc, and PcMergeCharacterModels pushes an element of the same array (FirstNew.Push(FirstNew[lSame])), a use after free at 16, 32, ... entries. The root temp header's reference count started at 1 for a record that never names it, so every header holding only a static shadow kept an unreferenced temp header, and a shadow root's words at 0x38 and 0x3c (triangle count and lerp flag) were counted as stream handles. With the fix 25 of the 68 PC archives have 1,997 handles fewer in all (M06_main's table 36,595 to 36,484), and pc_prims_test still matches every triangle, shadow, decal, water patch and scatter field. Bone chains now drop the mirror bit a Mirror-class material gives them, since their temp header has no mirror fields (none of the 68 archives has such a chain). Tweened objects need their 0x34-byte record, and the scatter master tiles' sums are checked in 64 bits.
  • Animation checks (pcanimations.cpp): ParseChunk walked past the member when a parent's data offset lay before its children's start (a 40-byte member that claims 1,500 children read about 12 KB past its end; it is now rejected as "truncated"), and CheckVariations accepted template offsets that do not start a list, from which the merge's BuildVariations would read pairs out of step. The 68 PC members and their PS2 twins pass as before, and the merge keeps all 11,381 state streams byte-identical.
  • Test builds. A guarded function-local static in pcprims.cpp (OPENBLOOD_TRACE_MATERIAL) needed __cxa_guard_acquire, which the -nostdinc++ build lines of pc_prims_test and pc_models_test do not link. It is read once without a guard now.

Review of the game overrides (26 November 2026)

A review of the port copies in port/hitman3/ and port/engine/{zwindows,geomsbase,eventsbase,fysix}/ against their src/ originals (port/overrides.json) found these, all fixed:

  • ZOSD::EnableOSDElement was not the game's. The port copy (hitman3/gui/_sdl/hudlayoutoverridesdl.cpp, added with pc_hud_size) ended with the tail of ZOSD::LoadInit, storing m_rWestOutline in m_aCornersOutline[3] and enabling the frame update, instead of the game's: for OSDELEM_HINT the hint m00/Tutorials/H01_GetToPier when no text shows, then m_bShowOSDElement = true and m_fLastOSDElemShow, which start the element's blinking (src/hitman3/gui/osd.cpp). The PS2 code at 0x3a5d60 has the AddHint call, the two sb 1 at 0x8f4 and 0x8f5 and the time store at 0x8f0, and no outline store; the PC's 0x660780 is the same. With the PS2 layout every briefing's close (EnableOSDElement(OSDELEM_ALL)) put West's shadow in East's compass slot, and the blinking element started in whatever phase it was left. The docs that described the store as the PS2's and the hint as the PC's are corrected.
  • Tables keyed by object pointers filled up. The key labels of the action, pickup and drop menus (ingamemenusoverridesdl.cpp, eight entries) and the ragdoll frame guard (engine/fysix/_sdl/ragdolloverridesdl.cpp, eight entries) never free an entry, and each scene makes new menus and a new ragdoll container. Once eight addresses had been seen, a new menu got no label (no key cap, no [G], no PC-data pad glyph), and every new ragdoll shared entry 0, reset on each call: two such ragdolls active at once took it from each other and the guard never skipped a frame, so above 30 fps they stepped 0.025 s every frame. Both now give a new object the entry used longest ago; objects in use touch theirs every frame.
  • The Lua mods could read past the captured script imports. ScriptLoaded (engine/eventsbase/_sdl/scriptcoverridesdl.cpp) passed the capture buffer to PortModScriptLoaded when a script's Imports read fewer bytes than its import list describes, the case ScriptCheckImports logs; PushScriptImports walks the whole list, so it read the previous script's bytes or past the buffer. Only a complete capture is passed on now.
  • OPENBLOOD_SCRIPT_CHECK's list outlived the level. It kept the names (pointers into the unloaded level image) and REFs of earlier scenes' scripts, and a reported script, whose REF was cleared, was added again nameless by its next update and reported anew. ScriptLevelDetach now empties the list (ScriptCheckForget), and a reported script stays listed, marked.
  • PortLiveRatingStats (hitman3/levelcontrol/_sdl/levelcontroloverridesdl.cpp), which the debug overlay and obm.rating.live call, dereferenced 47 without a check while a scene loads, and the preferred weapon's kill count without the test the game's MissionCompleted2 makes.
  • Launcher. A key rebind swallowed every key release while it waited, so ImGui kept the Enter that started it held and missed the next press of Enter; releases now reach ImGui. A custom level with a scene_code based on M00 or M13 renamed slot 1 or 11 but started slot 0's or 12's briefing; both now use one slot (CustomLevelSlot). A frame rate between the listed ones (the ini takes 30 to 240) showed as 30 and now shows the listed rate below it. The mission page reopened on Requiem when the last choice was a mod level. With the PC version, a PS2 disc image set as pc_install passed the check and played the disc with the PC version's settings; the PC version now needs a PC installation (CheckPcInstall). The capture hook (OPENBLOOD_LAUNCHER_CAPTURE) leaked its texture or readback buffer when the other failed and did not check the map.

Mod runtime and debug overlay review (26 November 2026)

A review of port/engine/mods/, port/engine/debug/ and the mod API against what a hostile or broken mod can pass. Each bug below was reproduced with a test mod or read from the engine code it calls, and fixed; the test mods are in the review worktree's build/review/mods-* (storage, networking, API abuse, props).

  • Safe mode ran no built-in mod. ModManagerIsModActive and ModManagerActiveOrderGet returned nothing in safe mode, so OPENBLOOD_NO_MODS=1 also stopped the rating, cheats and the other built-in mods (builtin.md says they run). Safe mode never scans an installed mod, so the active set is the built-in mods alone; mod_parsers_test now checks the load order.
  • Forged refs. ModRefToBaseGeom checked static refs against the base-geometry memory manager but passed dynamic ones on. ZFixedSizeMemoryManagerBase::REF2Ptr compares a block's id with the ref's generation cut to int16, and a free block's id is negative, so 65535 * N + i + 1 reached free block i and its stale m_pExtraGeom. Dynamic refs must now name an allocated block.
  • obm.storage.write of a table that holds itself. The conversion visited a table once per path to it, to a depth of 32, in C and outside the instruction budget, with every node allocated outside the Lua heap: t[1..4] = t never returned. It now stops at the reader's limits (131,072 values, 1,024 keys per object) and raises an error, which also keeps every stored value readable (a larger one was written and then read back as nil).
  • Engine buffers. obm.scene.load (ZScene::m_SceneName[260]), obm.mission.fail and set_objective_text (ResourceCollection::GetResourceText's key[200], the briefing's 128-byte texts) and obm.scripts.send (RegisterZMsg past m_pZMsgStrings[1024]) wrote past fixed buffers for long or many strings.
  • ImGui from Lua. slider_float passed the mod's format string to ImGui's printf; combo gave ImGui strings converted from numbers that nothing referenced; end_disabled without begin_disabled, and a window left open inside a popup after an error, unbalanced ImGui's stacks. obm.ui now keeps one stack of the windows, popups and disabled blocks a listener begins and ends what is left, innermost first, after each listener.
  • GPU resources. obm.props.remove/clear and obm.models.replace/clear from hud_draw or ui_draw released buffers that the scene's draw list, already built for the frame, still bound at submit; those releases now wait for the next frame start (ModGlbReleaseDeferred, ModLuaModelsChanged). Re-spawning a prop with another model leaked its two buffers each time. A hot reload kept meshes built from a mod's .glb after their replacements ended. obm.hud.load_image had no size limit; it now shares the .glb texture upload (4096 x 4096).
  • NaN and infinity. They passed SDL_clamp into time and look scales, light colours (an undefined float-to-int conversion), prop scales and 47's position. The functions that keep such values now raise an argument error for them.
  • Networking. On Windows a datagram sent to a gone peer made the next recvfrom fail with WSAECONNRESET, which ended obm.net.poll for the frame, so a mod that sent to every peer never read the live ones (reproduced: a send to a closed port, then to itself, polled 0 packets; now 1). The socket has SIO_UDP_CONNRESET off, and datagrams over 1,400 bytes are dropped instead of being delivered cut (POSIX) or ending the poll (Windows).
  • Debug test drivers. The pctuning climb guide, the models closeup actor order, the OPENBLOOD_SCENEFX_WALK start and the pcfixes water frame were kept from the first run in a session, so a restart used the first scene's freed objects or the wrong place (debug-ui.md).

Left as they are, for a decision:

  • obm.api calls the script interfaces as the compiled scripts do, and they trust their arguments: refs are not checked against the class an interface expects, nor indices against their tables (Silevelcontrol__Settargetnum(ref, 100000) writes past m_arTargets). Closing it needs per-interface argument metadata or an allowlist; lua.md now says so.
  • The heap limit applies to every allocation while a mod's call is running, also to the runtime's own pushes in engine hooks that a mod's call triggers (actor_killed from obm.world.explode, mission_outcome from obm.mission.complete). Near the 256 MB limit such a push raises through the engine's C++ frames to the mod's pcall.
  • The copies of strings passed to obm.api are freed by a hot reload while the scene's scripts may still hold them.
  • Lua's pattern matching runs in C, outside the instruction budget (lua.md).
  • The .glb texture cache keeps up to 64 models' textures for the session and is not cleared by a hot reload.

Renderer review (26 November 2026)

A review of port/engine/drawing/ and port/shaders/. The draw list records the frame's calls and passes and binds their textures and buffers only in DrawListSubmit, so a GPU object released between a DrawListAdd* and the submit is bound after SDL has freed it; most of the bugs below are that kind or a per-frame static that a second view overwrote. None showed in the 13-mission sweeps; each was found by reading and, where a run can reach it, checked with one.

  • Post filter bloom target. ZPostFilterSDL::Update draws the bloom list into its own bloom target through a pass added with no owner (DrawListAddPass(pList, 0, 0, bloom, true)). ~ZPostFilterSDL cancelled only the passes carrying the filter and then released the targets, so a filter destroyed mid-frame left the frame drawing into a freed texture. The pass carries the filter now, and a cancelled pass that drew into a target of its own skips its calls (SDrawPassSDL::bSkipCalls). Instrumenting the destructor showed no filter destroyed mid-frame in the M01 movie case or the sweeps.
  • Static projections and a picture-in-picture. StaticProjectionFlush reset the frame's camera, so a second view drawn after the main view's flush recorded its characters over s_aMeshes, which the queued pass reads at submit, and replaced s_Pass. Nothing is recorded after the frame's flush now, as shadowmapsdl.cpp and highlightsdl.cpp already keep their first camera.
  • Mirrored cameras and mods. MirrorCameraFromSpace called ZCameraViewEntrySDL::UpdateMatrices, which applies a mod's camera override and records the pose mods read to the main perspective camera, so with an override the mirror or PC water reflection showed the unmirrored override view, and the recorded pose ended each frame mirrored. A mirrored camera skips the hooks.
  • PC water groups. DrawWaterPc skipped water patches of mirror group 16 and up altogether, not only their reflection; they draw without a reflected view now.
  • Mod post filter presets. The atmosphere and shader presets raised m_fNoiseMax and m_fNoiseScale and never put them back, so a preset's film grain stayed after it was turned off. The custom post shader bound the depth target as a sampler where the device has no sampleable depth format (bDepthSampler), wrote alpha because its write mask was not enabled, and leaked the buffer of an empty shader file.
  • Blur. postfilter.hlsl's Blur divides by the sum of a tap pair's Gaussian weights; with a sigma under about 0.076 taps both underflow to 0 and the tap offset is 0/0. PostBlur draws no taps below a sigma of 0.1, where they add less than 1e-21.
  • Overflow and allocation failures. DrawListAddMesh returns whether it added a call, so the PC material no longer gives its eight maps to whatever call was last when the list was full. The dot3 scratch buffer kept its capacity after a failed allocation and was then written through null. The movie upload and the capture readback check their transfer buffers and fence.
  • Cleanup. One ShaderBlobSDL / ShaderIndexSDL / ShaderCreateSDL (shaderssdl.cpp) replaces the copies of the shader lookup and creation in eleven files. Debug switches read on every fill, clear, scatter entry, mirror, water group, character or post filter frame are read once. The capture burst that CalcScissor armed on a scissor-override change (the aid for the PIP flash above) is gone.

Checked and found sound: every uniform block in port/shaders lines up with the C++ that fills it (SDrawUniformsSDL, SFragmentUniformsSDL, the PC material and PC water rows, SModSurfaceLights, the enhance, shadow map, static projection, highlight and post filter blocks), and every program is drawn with the samplers shaders.json declares (the PC material always gets its eight extra maps). Render targets are made once when the GPU opens and never resized. Over the 13 missions in both versions no texture was released while its upload was pending or while the frame's calls used it, and no mesh buffer either.

Left as they are:

  • TextureRelease, TextureReleaseAll and MeshCacheClear do not drop the uploads still queued for what they release. Uploads are queued while the views draw and sent by the same frame's Present, and textures and meshes are released only when a scene's buffers are installed, between frames, so nothing reaches it today.
  • InstanceBuffer (zoldviewpcmaterialsdl.cpp) releases a PC-material instance's lit vertex buffer when its lights or matrix change, which would free a buffer the frame already uses if that happened twice in one frame; lights are gathered before drawing, so it does not.
  • Shaders still normalize vectors that can be zero in degenerate cases (PSBonePixel's decoded normal, surface.hlsl's and shadowmap.hlsl's derivative normals, a few in pcmaterial.hlsl and staticprojection.hlsl), and SafePow, AlphaPasses, VSFull and GS_COLOR_SCALE are copied between .hlsl files; changing them means regenerating shaderssdl_generated.cpp.
  • The PC material's white cube and the mod's custom post shader and pipeline are not released at shutdown.

The M01 movie crash

One of three runs of the M01 opening movie from the disc (M01_Esta.pss, launcher mission 1, movies on) ended in an access violation in the NVIDIA Vulkan driver (nvoglv64.dll, DrvPresentBuffers, reading 0x4c230) under vkQueuePresentKHR, reached from GpuEndFrame's SDL_SubmitGPUCommandBuffer. What the frame does during a movie: GpuMovieUpload copies the decoded frame into one movie texture, recreated only when the movie's size changes, with a transfer buffer released after the copy is recorded, and BlitPicture blits it to the swapchain in the same command buffer. Nothing in that path or in the draw list releases an object the frame still uses: instrumented runs logged no texture or mesh released with its upload pending or in use by the frame's calls and no post filter destroyed mid-frame, and render targets are never resized. The crash was not reproduced in 23 further runs of the same case, most of them beside other instances of the port (14 with the code the review started from, two of them instrumented, and 9 with its fixes). It is not attributable to the port's rendering from what the code and the runs show; the post filter fix above is the only lifetime bug found that could free a texture a frame binds.