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 withDefaultScene, kept alive for--seconds; the run is a crash when the process dies or the log carries afatal signal/AddressSanitizer report.cycle— one process that switches through every disc scene, one perOPENBLOOD_DEBUG_SCENE_TEST_FRAMESframes, 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,cloads one scene per period, wrapping.OPENBLOOD_DEBUG_STATE_TEST=cyclesaves at frame 60 and reloads at 180, then every 600 frames.OPENBLOOD_DEBUG_ITEM_TEST=1gives the scene's first item templates.
Crash reporting¶
The crash handler now writes, before the backtrace:
context: scene "...", frame N, game time T sfrom 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
(
ScriptDeliverMessagecounters).
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).UpdateVisiblesends three 32-bit words;ZSecurityCamera::OnObjectVisibleand theSendSecurityCameraObject*helpers addressed them throughREF*.REFis pointer-sized natively, so the extra-flags write landed past the 12-byte message and smashedUpdateVisible's stack canary. The payload now usesendian_REF, andSObjectVisibleUpdatedoes too, so the three words line up natively. Seen asSIGABRTinZCheckVisible::UpdateVisibleafter a guard first saw Hitman. - Scheduled event reaping (
e9bd6760e). A forked script thread could be reaped after its event was freed;ZScheduledEvent::~ZScheduledEventthen calledSetEvent(nullptr, ...)and faulted at 0x40. The write is skipped when the event is gone (native only) and a one-shotscheduledevent:line reports it. Seen asSIGSEGVinZScheduledUpdate::SetEvent. - Perception payload (
ac249955f).sPerceptionis copied to the guest verbatim; itsREFfields widened the native struct and shiftedlevel,dress,timeandinfo, so scripts sent commands to bogus objects. The two slots areendian_REFnow. Seen asSIGSEGVinScriptEngine::SendScriptCommandfrom 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).ScriptSendCommandandScriptEngine::SendScriptCommandnow 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::SendMessagesent one REF to messages that declare two; the native build sends both (actor zero). - Door CanPenetrate payload (
8c5d8e5c6). Shooting a gate inM00_maincrashed inCDoorBase::Commandwith a fault address of0x7500000001. The projectile sends anSHM3ProjectilePenetratebuilt 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 ownSDoorPenetrateQuerywith the same member order, which is identical on the PS2 but not on the host:SProjectilePenetrateends with a bool, so as a base class it rounds up to a pointer boundary, putting the sender'snHitCountat 0x18 andpWeaponat 0x20 while the door's record hadpOperatorat 0x18. The door read the hit count plus the stale upper half of the stack slot as a weapon pointer, which is where0x7500000001came from. The handler now uses the sender's type and itspWeapon/nHitCountnames; the PS2 offsets are unchanged andmake matchstays exact. - Save-state item counts and the debug hooks. The periodic
N itemsfigure is the port'sg_DebugLiveItems, andZItem::NukeItresets 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 longstate1test state came fromOPENBLOOD_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 inM02_maincrashed inQSortCompareFunc(fault0xb7ebcbf0000000b3).ZHM3ItemBomb::ExplodeandCExplosionControllersorted theirZBaseGeom*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 passsizeof(m_pTargets[0])now, which is 4 on the PS2 and 8 on the host. - Level table bounds (
598aeb815).ZLevelLinkingwalked 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 andZSysInterface::Randmultiplied a signed int until it wrapped. Both now go throughuint32on the host.ZKeysDepack::ReadOffsetshifted 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
int32first. - 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. ComValueInforecords are packed on the host (24 to 16 bytes) because CCom hands out four-byte-aligned records.ZPoolAllocatorpads its nativeZAllocHeaderand rounds sizes to eight for the same reason, and the five static pool buffers are aligned explicitly.ZCONTROL::SetNextFocusandZWINDOWS::SetFocusedControlno 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::Clearfilled every camera viewport with the camera'sBackCol, and the item view's is0xff0000. The PS2'sZOldViewPS2::Clearonly fills for letterbox (4), perspective (0) and ortho-2D (5) camera types, and the ortho-2D fill usesGS_TEST_CLEAR_COLORwith 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'sBackCol(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=1keeps 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; seedocs/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,ActorDamageandRemoveNamedActionnow haveSScriptMessageLayoutentries, 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::ZItemnow 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::CreateFreeStackdoes the same; a removed entry without a free stack is unlinked and dropped. One-shot warnings name the first failure.OPENBLOOD_POOL_STATS=1prints every pool's current, size and peak bytes every 300 frames and at each scene unload, and the periodicdebug statsline 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::AddEventcompares 11 bytes of a shorter event name (the original does the same); run withASAN_OPTIONS=strict_memcmp=0.CCheckInside::SendMessagepasses one REF tocheckinsideenter, 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_DIRplus 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_slowbecause 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.
ZHM3CameraEventCameraClassadds its cameras to view 2 when the PIP opens and removes them when it closes.AddCameraandRemoveCameracallZOldDrawBase::Invalidate, so the nextZRender::BeginScenerunsZOldDrawBase::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 (
BackCol7d6243) 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 0for all four entries.
- Why the PS2 never shows it.
- Its VIF chain references transforms and bones by address.
- That chain is sent in
Flip, afterUpdateDynamichas 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 ofUpdateLight, 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.
- Reproduced with
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
TimeStampCounterran on the host counter, which ticks at 24 MHz on Apple Silicon.ZScheduledUpdate::ScheduleEventsruns scheduled scripts for up tom_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_CheckTimeoutandZScriptC::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::TimeStampCounternow converts the host counter to the EE clock (294.912 MHz), andCycSecis that rate.StepTimeuses the constant rather thanCycSec, because save states storeCycSec, 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_01and_16_02are the same dot3 prim at the same position, but16_01is 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_dot3renderrunsbackface_cullingon every batch (strip_adc_distrib, with no flag), so the upside-down copy is never drawn from above. - Fix.
SDrawStateSDL::lCulladds 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_TransferMatrixHomogeneousScaleBiasand 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, asVColClip(0x523 to 0x538) and the dot3normplanesblock 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) andhm_icn.cpp(the save icon). Below it, the port emulates the card in the user directory (mc0/):sceMcGetInforeports a formatted 8 MB PS2 card that has not been swapped.sceMcDeletereturns the library's codes (0, or -4 for a missing file).McFileExistsalso finds directories. The save code tests a profile folder asBESLES-53028Hitman0/.ZSysFilePS2::CreateIconFileswritesicon.syswith Sony'sMakeIconSysand the Shift JIS title conversion, then the icon.SaveProgress_InitandSaveProgress_Endonly reset the byte counters. The PS2 draws its progress bar from a GS vblank callback, and saves to disk finish at once.ReadPS2SystemFilereadsSYSTEM.CNFas the PS2 startup does. That gives the save folder its product code and sets the US-build flag.- One portability fix in shared source:
ZMCCheckFileCRCaligns its directory buffer throughuintptrinstead ofuint32. 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/.datapairs (0x6400 and 0xA3000 bytes),SaveGameInfo(0x400),icon.sys(964 bytes,PS2D) andHM_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.
- Creating a profile writes the folder and files the PS2 writes, at the PS2 sizes: the profile (0x8800 bytes), three
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_testfailed on that diagonal. - Fix. The port now builds every unit with
-ffp-contract=off(flagsinport/port.json), so its float results follow the EE's rounding order.checklines.cppandspherecheckssdl.cppkeep 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.
BiasToScalegives 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:
DrawNormalMappedalways usesVU_dot3render, its Z and the strips' Z come from the same near and far planes, and both programs store it withftoi4. As far as the code shows, the original has this artefact too.
- The poster is an ordinary strips prim with bias 0.
- Fix.
StripsUniformstakes a dot3 flag instead of the bias switch. Dot3 passes now useDot3BiasScale(): 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.
NewItemStateTableleaves a table null when the item pool is full (the case "Pool capacity" above describes), and every user tests it except the port copies ofZItem::~ZItem, which calledClearthrough all four, andZItem::PostLoad, which added tom_pStateRemoveuntested (diagnosticsoverridesdl.cpp). Both test it now. - Unset weapon prims.
ZEngineDataBase::PurgePrimBuffer(the game's text and the port copy inenginedata/_sdl/gamedataoverridesdl.cpp) leaves theWeaponPrimsentry 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::GetZipFileserves a PC-data scene's converted.PRPthrough one of eight wrapper slots, keyed by the archive. Slots were never given back whenRemoveBigdeleted 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_TESTover the premission and postmission scenes of M01 to M06) the archives reused one address and every.PRPwas 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_ADDEDevent for it.ZGameControlDeviceSDL::Closeopens it. - ISO records.
IsoFindInDirectoryandIsoListDirectoryread 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::Pushread its argument afterReserve'srealloc, andPcMergeCharacterModelspushes 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), andpc_prims_teststill 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):ParseChunkwalked 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"), andCheckVariationsaccepted template offsets that do not start a list, from which the merge'sBuildVariationswould 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 ofpc_prims_testandpc_models_testdo 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::EnableOSDElementwas not the game's. The port copy (hitman3/gui/_sdl/hudlayoutoverridesdl.cpp, added withpc_hud_size) ended with the tail ofZOSD::LoadInit, storingm_rWestOutlineinm_aCornersOutline[3]and enabling the frame update, instead of the game's: forOSDELEM_HINTthe hintm00/Tutorials/H01_GetToPierwhen no text shows, thenm_bShowOSDElement = trueandm_fLastOSDElemShow, which start the element's blinking (src/hitman3/gui/osd.cpp). The PS2 code at 0x3a5d60 has theAddHintcall, the twosb 1at 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 toPortModScriptLoadedwhen a script'sImportsread fewer bytes than its import list describes, the caseScriptCheckImportslogs;PushScriptImportswalks 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.ScriptLevelDetachnow empties the list (ScriptCheckForget), and a reported script stays listed, marked.PortLiveRatingStats(hitman3/levelcontrol/_sdl/levelcontroloverridesdl.cpp), which the debug overlay andobm.rating.livecall, dereferenced 47 without a check while a scene loads, and the preferred weapon's kill count without the test the game'sMissionCompleted2makes.- 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_codebased 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 aspc_installpassed 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.
ModManagerIsModActiveandModManagerActiveOrderGetreturned nothing in safe mode, soOPENBLOOD_NO_MODS=1also 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_testnow checks the load order. - Forged refs.
ModRefToBaseGeomchecked static refs against the base-geometry memory manager but passed dynamic ones on.ZFixedSizeMemoryManagerBase::REF2Ptrcompares a block's id with the ref's generation cut toint16, and a free block's id is negative, so65535 * N + i + 1reached free blockiand its stalem_pExtraGeom. Dynamic refs must now name an allocated block. obm.storage.writeof 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] = tnever 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 asnil).- Engine buffers.
obm.scene.load(ZScene::m_SceneName[260]),obm.mission.failandset_objective_text(ResourceCollection::GetResourceText'skey[200], the briefing's 128-byte texts) andobm.scripts.send(RegisterZMsgpastm_pZMsgStrings[1024]) wrote past fixed buffers for long or many strings. - ImGui from Lua.
slider_floatpassed the mod's format string to ImGui's printf;combogave ImGui strings converted from numbers that nothing referenced;end_disabledwithoutbegin_disabled, and a window left open inside a popup after an error, unbalanced ImGui's stacks.obm.uinow 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/clearandobm.models.replace/clearfromhud_draworui_drawreleased 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.glbafter their replacements ended.obm.hud.load_imagehad no size limit; it now shares the.glbtexture upload (4096 x 4096). - NaN and infinity. They passed
SDL_clampinto 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
recvfromfail withWSAECONNRESET, which endedobm.net.pollfor 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 hasSIO_UDP_CONNRESEToff, and datagrams over 1,400 bytes are dropped instead of being delivered cut (POSIX) or ending the poll (Windows). - Debug test drivers. The
pctuning climbguide, themodels closeupactor order, theOPENBLOOD_SCENEFX_WALKstart and thepcfixeswater 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.apicalls 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 pastm_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_killedfromobm.world.explode,mission_outcomefromobm.mission.complete). Near the 256 MB limit such a push raises through the engine's C++ frames to the mod'spcall. - The copies of strings passed to
obm.apiare 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
.glbtexture 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::Updatedraws the bloom list into its own bloom target through a pass added with no owner (DrawListAddPass(pList, 0, 0, bloom, true)).~ZPostFilterSDLcancelled 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.
StaticProjectionFlushreset the frame's camera, so a second view drawn after the main view's flush recorded its characters overs_aMeshes, which the queued pass reads at submit, and replaceds_Pass. Nothing is recorded after the frame's flush now, asshadowmapsdl.cppandhighlightsdl.cppalready keep their first camera. - Mirrored cameras and mods.
MirrorCameraFromSpacecalledZCameraViewEntrySDL::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.
DrawWaterPcskipped 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_fNoiseMaxandm_fNoiseScaleand 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'sBlurdivides 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.PostBlurdraws no taps below a sigma of 0.1, where they add less than 1e-21. - Overflow and allocation failures.
DrawListAddMeshreturns 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 thatCalcScissorarmed 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,TextureReleaseAllandMeshCacheCleardo not drop the uploads still queued for what they release. Uploads are queued while the views draw and sent by the same frame'sPresent, 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
normalizevectors that can be zero in degenerate cases (PSBonePixel's decoded normal,surface.hlsl's andshadowmap.hlsl's derivative normals, a few inpcmaterial.hlslandstaticprojection.hlsl), andSafePow,AlphaPasses,VSFullandGS_COLOR_SCALEare copied between.hlslfiles; changing them means regeneratingshaderssdl_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.