Skip to content

Native scene scripts

The port runs the scene scripts as native code. The C in src/scripts/LEVEL/ and src/scripts/Alllevels/, which rebuilds the 14 PS2 modules byte for byte (docs/internals/scripts/scene-scripts.md), is compiled with the host compiler into the port's executable, all 14 levels side by side. The engine's script core works on real pointers. There is no MIPS emulator, guest memory or wasm step any more; they were removed on 24 November 2026.

Build

port/CMakeLists.txt compiles every .c in src/scripts/LEVEL/, the shared src/scripts/Alllevels/*.c files listed for that level in src/scripts/shared-scripts.json, and port/engine/zstdlib/_sdl/scriptlibrarysdl.c into an object library per level and links the objects into openbloodmoney; there are no script libraries to ship or load. The script flags pin the PS2 meaning of the C: -std=gnu99 -fwrapv -fno-strict-aliasing -fno-delete-null-pointer-checks -ftrivial-auto-var-init=zero -ffp-contract=off -fsigned-char -fno-common. make port builds them with the executable.

All 34 shared Alllevels_*.c scripts live once in src/scripts/Alllevels/ and compile into every level that lists them in src/scripts/shared-scripts.json, with src/scripts/LEVEL/shared-scripts.h holding per-level helper-ownership flags (the PS2 modules shipped the same shared script code; only which translation unit defines a few helpers varies per level). Because each level compiles its own objects from those shared sources — each with its own statics, metadata records and references into the level's module-support.c — M00 and M01 alone still define 2,112 of the same global names. Before the link, tools/port/script_level_objects.py rewrites each level's objects (ELF64 or x86-64 COFF; the sources stay as they are, so they still rebuild the PS2 modules):

  • every global symbol the level defines, and every reference to one, gets the prefix __obm_LEVEL_ (__obm_M00_Alllevels_Human_root). References to the engine (memcpy) keep their names.
  • the level's constants, variables and zero-initialised data (ELF .rodata*, .data*, .bss*; COFF .rdata, .data, .bss) move to one writable section, with zero contents where they were .bss: obm_scripts_LEVEL on ELF, between the linker's __start_ and __stop_ symbols, and .data$obm_scripts_LEVEL_m on COFF, between the _a and _z markers scriptlevelsdl.cpp defines. The merge flags go, as lld refuses a writable mergeable section; the level's constants are no longer write-protected. Code stays in .text.

tools/tests/test_script_level_objects.py checks both formats with clang objects and links and runs an ELF program that reads its data through the range.

scriptlibrarysdl.c defines OpenBloodScriptLibrary() (__obm_LEVEL_OpenBloodScriptLibrary after the rewrite), which returns a ScriptLibraryTables record (scriptlibrarysdl.h): the counts of interfaces (716) and services (27), the level's creator table (__ob_scene_creators), and the addresses of the level's ScriptImports and SF tables for the engine to fill.

Loading

ScriptEngine::AttachSceneScripts (src/engine/zstdlib/zscriptc.cpp, native branch) calls ScriptLevelAttach (port/engine/zstdlib/_sdl/scriptlevelsdl.cpp). It finds the level in the table SCRIPT_LEVELS lists, checks the two counts and that the creator table lies in the level's data, restores the level's data, fills ScriptImports and SF, and logs Scripts: LEVEL as native code, built into the executable.

The level's data range is its "script code": a saved game stores a controller, a state, a fixup table or a script string as an offset into it, as the PS2 stores one into the module. The range holds only the level's own data, so the offsets do not move when the engine changes. Every pointer the save test (OPENBLOOD_SAVE_TEST_FRAME=300) converted in M00, M01, M05 and M10 lay in it, apart from four values that are no address at all (0x6300000000 in M10, 0x615400000000 in M05: a zero lower half, like the stale uptr slots under Risks left).

The PS2 reads the whole module image, its statics included, from the disc each time it attaches a level, so every load starts with fresh statics. The executable keeps one copy of each level, so ScriptLevelAttach copies the range aside the first time and copies it back on each later attach. Without memory for the copy the level does not attach (Scripts: LEVEL: no memory for a copy of its N bytes of data): run once, it could not be given fresh statics again. The shared-library build did not reset them: a scene reload calls ScriptEngine::NukeAndRestart, which clears the attach count without detaching, and loading the still-open library again gave back the same image with the last load's statics (M00 then reloads its scene with the sniper's animation already resolved). Four loads of M00 in one run (OPENBLOOD_DEBUG_UI_TRACE=1 OPENBLOOD_DEBUG_SCENE_TEST=M00/M00_Main OPENBLOOD_DEBUG_SCENE_TEST_FRAMES=500) give the library build's 1,352,064 events when the restore is left out, and 1,352,073 with it.

Script patches

The port can change a level script without touching src/scripts, which must go on rebuilding the PS2 modules and meaning the same to ee-gcc and the host compiler. A script patch replaces one pointer in the level's script data when the level attaches; the PC version's five script changes (pc-data.md) are the first patches, and the mechanism is meant for later script fixes too.

The code. A patch is C written as the scripts are (the SDK headers, SF, ScriptImports, the runtime's __ob_rt_ functions, SC_EXIT, frames with a LocalVarEntry header), in port/engine/zstdlib/_sdl/pcscripts/. scriptlibrarysdl.c includes the files, so every level compiles them with the script flags, and tools/port/script_level_objects.py prefixes them with the level's other objects: a name every level defines (__ob_rt_call, SF, Alllevels_Basefunc_SendDelayedMessageInFork_fc, a shared script's creator) binds to the attaching level's own. The patches' controllers, records and statics are in the level's data range like the scripts' own data, so a saved game can store a frame that runs a patch's function as it stores any other, and the level's restore resets their statics.

Both builds compile scriptlibrarysdl.c once per level with the same command line, so the file cannot tell which level it is built for. Two rules follow:

  • Another level's symbol is written SCRIPT_LEVEL_SYMBOL(M02, M02_M02_Grothobunny_SitDownState) (scriptpatchsdl.h), the name __obm_level_M02__M02_M02_Grothobunny_SitDownState. The rewriter turns it into __obm_M02_M02_M02_Grothobunny_SitDownState in M02's objects, where M02 must define it (it stops with level M02 defines no ... otherwise), and into the level's OpenBloodScriptAbsent everywhere else; tools/tests/test_script_level_objects.py links and runs both on ELF and checks the COFF names. A level's own symbol needs it only when other levels do not define it.
  • Types come only from headers every level can include together: the SDK, the shared headers such as src/scripts/Alllevels/Civilian.h (whose variables are the same in every level) and a script's _Variables.h, which holds its variables and those of its bases and includes nothing else. The level headers (for example src/scripts/M10/M10_M10_Civilian.h) define the same type names differently in each level, and two levels' sets in one file do not compile. A patch that needs a script's variables moves them out of the script's .c or header into such a header first: M02_M02_Grothobunny_Variables.h, M02_M02_Jacuzzigirl_Variables.h, M03_M03_Levelcontrol_Variables.h, M10_M10_Civilian_Variables.h, M10_M10_Civilian_Room_Variables.h and M10_M10_Scientist_Variables.h were made that way. The move changes no object (match_scripts.py, compiled_digests.py check).

The records. Each patch file ends with its ScriptPatch records (scriptpatchsdl.h), which scriptlibrarysdl.c gathers into the table OpenBloodScriptLibrary returns. A record names a patch set (SCRIPT_PATCH_SET_PC), the level (or none for a shared script, which every level gets), one of three kinds of pointer and the replacement:

Kind Target Pointer replaced
SCRIPT_PATCH_MESSAGES a SCRIPTCREATOR its ProcessMessage. The replacement handles the messages it changes and calls the PS2 handler, which the record stores in a static of the patch, for the rest. The engine and every derived script reach a script's handler through that pointer (a derived script's handler walks m_pMessageHandler's creators), so the change holds for derived scripts too.
SCRIPT_PATCH_FUNCTION_SLOT a SCRIPTCREATOR and a slot the slot of its root state's functions table, which all its states share (SC_VIRTUAL_FUNCTION)
SCRIPT_PATCH_ENTRY_POINT a FUNCTIONCONTROLLER its entry point. The replacement does what the PC added at one resume index and returns the PS2 function's result for the frame.

A record may name the PS2 pointer the slot must hold; the applier then refuses a slot that holds anything else.

Applying. ScriptLevelAttach restores the level's data and then calls ScriptPatchesApply (port/engine/zstdlib/_sdl/scriptpatchsdl.cpp), which applies the records of the sets the settings turn on (ScriptPatchSets: pc_scripts turns on the PC set) and of the attaching level, and logs each: Scripts: M02: pc_scripts patch: M02_M02_Targetbunny OnKnockedUnconscious. A level attached without the set runs the PS2 scripts as before: its data is the restored copy, which the patches never touched. With OPENBLOOD_TRACE_SCRIPT_PATCHES=1 the patches log what they do (Scripts: patch in M02_M02_Grothobunny (1cc1): evm02_trygovson again in 20 s) through ScriptPatchNote, an engine function the patch code calls by its plain name.

A new patch. Write the function from the listing of the behaviour it follows (for the PC changes, the PC DLL's), with real types and named fields; a frame the callee writes is the sizeof of the callee's frame type, as everywhere in the scripts (frame sizes); add its records to the file's ..._PATCHES macro and the macro to s_aScriptPatches. The Windows build (build.py) rebuilds scriptlibrarysdl.c only when that file changes, so touch it, or build with --force, after editing a patch file.

tools/port/mods/pcscripts is the test mod for the PC set (a Lua mod, run with OPENBLOOD_MODS_DIR=tools/port/mods, OPENBLOOD_ENABLE_MOD=pcscripts and OPENBLOOD_ONLY_MODS=1): it logs the messages and interface calls of the five changes with the frame and the game time, and sets up their situations in M02, M03 and M10.

Calls between scripts and engine

  • Interfaces. tools/port/script_thunks.py generates port/engine/ScriptInterfaces/_sdl/scriptthunkssdl.cpp. Each of the 716 interfaces gets an adapter with the script-side C signature from decompiled.h. The adapter fills a ScriptCall record (scriptcallsdl.h) and calls ScriptDispatch, which counts and traces the call and offers it to the Lua hook (g_pScriptCallHook, port/engine/mods/_sdl/modlua.cpp) before the engine thunk runs. tools/tests/test_native_scripts.py checks every adapter against its declaration.
  • Services. port/engine/zstdlib/_sdl/scriptfunctionssdl.cpp fills the 27 SF entries. Most forward to ScriptEngine. GetAlienVirtualTableEntry takes the EE's byte offset (slot × 4) and returns host slot × 8. CheckTimeout returns int. SendCommand and SendScriptCommand convert the payload in both directions.
  • REF widths. The engine's REF is pointer-sized on the host; the scripts keep it as a u32. Message payloads are converted between the two layouts with the tables in scriptmessagessdl.cpp and scriptmessagesrecovered.cpp, whose script offsets are those of the 64-bit script build (docs/internals/scripts/payload-layouts.md). A REF that does not fit 32 bits is logged as an error.
  • Engine structs. src/engine/eventsbase/scriptc.h keeps the PS2 layouts under OPENBLOOD_TARGET_PS2. On the host, ScriptState, LocalVarEntry and the controllers hold real pointers, m_rThis stays a uint32, and the size checks give the host sizes (0x80, 0x68, 0x40, 0x20). FixupData and PrepareData in scriptc.cpp have native branches that walk pointer-width slots.

Two cheap checks stay on in every build: ScriptCheckImports logs a script that read more or fewer property bytes than its table holds, and ScriptCheckFrame logs a frame smaller than its controller's input size and a controller outside the script image (with as many of the frame's first twelve words as its block holds, and the caller's offset only when the caller's controller lies in the image).

What the script sources do to work on 64 bits

All 707 script units (450 source files) compile for x86_64 with clang and still rebuild the 14 modules byte for byte. Every edit is the same type or constant on the EE:

  • Layout checks carry a sizeof(void *) != 4 || escape. ZDebugBreak is the MIPS break 0 only under __mips__.
  • No size is a byte count. Function controllers give sizeof(<Function>_Frame) and SC_LOCALS_SIZE(frame, firstLocal). A child frame is sizeof(<Function>_Children), a union of the frames of every function it serves (virtual slots and ScriptStateTransitionFrame included). Script and state blocks are sizeof(<Script>_Variables) and sizeof(<Script>_StateVariables). Saved statics are sizeof the variable. Save fixup tables give FIXUP_* codes with SC_MEMBER_OFFSET and SC_MEMBER_END of the fields they cover.
  • Pointer widths. sptr and uptr are s32 and u32 on the EE and pointer-sized elsewhere. SC_POINTER_TYPED_WORD(type) is the pointer type on the EE and u32 elsewhere: a four-byte word (an imported SIT_REF handle, a move result) that the original accessed with a pointer's alias set. SC_POINTER_SLOT(type) is the type on the EE and uptr elsewhere. A store the original makes as a four-byte word into a pointer field goes through it, so the host writes the whole pointer: the followUp controller of the movement helpers, which 374 calls clear with *(volatile SC_POINTER_SLOT(s32) *)&...->followUp = 0, the guards' trespass response, which clears it with a float zero, and the M04 coffee drinker's view of its three speech-line pointers. Written as four bytes, they left the pointer's upper half as heap garbage, and a guard checking on a trespassing 47, a civilian walking to a waypoint or the basement guard complaining about the coffee crashed the game. SC_ARGUMENT_SLOT and SC_ARGUMENT_WORD(lvalue) copy a four-byte word into a pointer-width argument slot: *(volatile SC_ARGUMENT_SLOT *)&args->target = SC_ARGUMENT_WORD(vars->spot); is the original's ScriptArgumentWord copy on the EE (alias set 0, which its instruction order needs) and a store of the whole uptr slot, zero-extended, elsewhere. SC_HOST_ALIGN4 is empty on the EE and __attribute__((packed, aligned(4))) on the host; it keeps the kissing couple's returnState2 where the flirters', which share its EE layout and functions, sit, and every view of those variables uses it too.
  • Views follow the structs they overlay. A view of a callee frame takes the callee's widths; a view shared by callees of different widths is split per callee. Views of a function's own frame and of script and state variables size their padding from the real struct (SC_MEMBER_OFFSET/SC_MEMBER_END). A function that runs on another script's variables uses that script's struct. A local view that also has to cover a callee frame is a union (typedef union { View view; Callee member0; } ViewCover;).
  • An event or task passed by value to an interface pointer is declared ScriptEventArgument or ScriptTaskArgument, and an interface called with an event goes through its _with_event entry.
  • Float constants that ee-gcc folds by truncation are written SC_FOLDED(source, value), so both compilers use the PS2 value.
  • Bitfields follow GCC's layout on every target. MinGW (x86_64-windows-gnu, the Windows build) lays bitfields out as MSVC does: a field that follows bitfields of another type starts a new storage unit, so struct { s32 entering : 1; u8 touristCount; REF tourists; REF entrant; } puts entrant at 12 instead of 8. SC_GCC_LAYOUT (__attribute__((gcc_struct)) on Windows, empty everywhere else) on such a struct gives it the layout the EE and Linux have. Twelve views carry it (Windows layout).

Views that are wrong on 64 bits

A script function often reaches memory it does not own through a view: a struct declared in the function that lays out only the fields it touches, with padding in between, or another function's frame type used to fill a callee's arguments. Views overlay the script's variables (pSS->m_pScriptVariables), the state's variables (pSS->m_pStateVariables), the next frame (pFrame->m_pNextVariables, or a frame a message handler allocates with SF.Alloc), the function's own frame, a message payload or another script's variables (alien->m_pScriptVariables). The PS2 rebuild proves that every view meets the real struct on the EE. It proves nothing about the host, where the real struct grows at every pointer and uptr slot. A view goes wrong there in four ways:

  • Offset. Padding written as an EE byte count (u8 pad_000[0x2B0];), or a 4-byte field where the real struct has a pointer, moves every later field. M04's coffee warden crashed this way (M04_Useable_Drinkcoffeeandrefill_UseObject, enum IdleChoice idleChoices[4] over four const char * complaint lines; fixed with SC_POINTER_SLOT), and so did an NPC kneeling at a body (KneelAnimArgs in Alllevels_Civilian_InvestigateBody).
  • Narrow store. A u32 or s32 stored into a slot the callee reads as uptr or as a pointer writes the low half only, and the upper half keeps whatever the frame held before. args->options = 0 meant to clear a followUp pointer; a REF stored into a uptr target reads back with a stale upper half wherever the callee compares or forwards the full value. A narrow load is harmless: the low half of a little-endian slot is the same value.
  • Wide field. A uptr or pointer field over a 32-bit real one reads or writes the next field too (uptr toolboxItem over the carpenter's REF toolbox gave itemRef == vars->toolboxItem a garbage upper half).
  • Windows layout. A view with bitfields followed by a field of another type lines up on Linux and not on Windows (see SC_GCC_LAYOUT above).

Three relatives have no view at all, only the real struct:

  • A frame sized for the EE. A caller allocates its callee's frame, and when the size is a byte count (u16 capacity = 0x18;, enum { MinimumChildFrame = 0x6C };, sizeof(LocalVarEntry) + 4) or the sizeof of a local view or union that is smaller than the callee's frame on the host, the callee writes past the block into the next allocation: its header word first, then the start of whatever the next block holds. The bird's LandedWatchState_run crashed M00 this way (the crashes). A message handler that changes state needs a whole ScriptStateTransitionFrame (0x24 bytes on the EE, 64 on the host): __ob_rt_call_state writes its previousState at host offset 56 and the queued call copies all 64 bytes, so a union of ScriptStateChangeArguments (56 bytes) is too small.

  • An int store to a pointer. The original stored many pointers through an int for its alias set, and the sources keep it: *(volatile s32 *)&args->followUp = 0;, *(s32 *)&vars->turnTowardSource = (s32)vars->savedTurnTowardSource;. On the host that is a narrow store into the pointer whatever the struct. M10's civilian next to the scientist (M10_M10_Civilian_Nexttoscientistguy_PutBackFoodState_run) cleared WalkToWaypointAndUseObject's followUp this way, the upper half kept all ones, and Alllevels_Basefunc_WalkToWaypointAndUseObject crashed reading followUp->m_lInputSize (at 0xffffffffffffffff) at frame 2462 of a plain M10 run, in the build before and after the view fixes.

  • A pointer in an int field. A field the save fixup table walks as a code pointer, string or script state (FIXUP_CODEPOINTERS, FIXUP_STRINGS, FIXUP_SCRIPTSTATES) holds a pointer, so it must be pointer-width on the host; s32 behaviorState in Alllevels_Perceptionconverter_SaveThenSetAllBehaviorStates_Frame kept the low half of a STATECONTROLLER *, and (s32)vframe->nextState truncated the state a waypoint list ends in. The executable sits at 0x7ff6xxxxxxxx or 0x7ff7xxxxxxxx on Windows, so a truncated pointer is never valid.

The survey

tools/port/script_views.py finds all seven. It needs a clang that can dump record layouts for the three targets:

python3 tools/port/script_views.py [LEVEL ...] [--jobs N] [--unresolved [--unresolved]]
python -I tools/port/script_views.py --clang "<path-to-clang>"   # Windows

It copies each script file to build/script-views/LEVEL/ with every function-local struct, union and typedef name made unique, and compiles the copy three times with -Xclang -fdump-record-layouts-canonical and the code generator (-S -o /dev/null): for mipsel-linux-gnu, which is the EE layout (4-byte pointers, 8-byte aligned 64-bit types, __mips__ defined, so uptr and SC_POINTER_SLOT are 32 bits), for x86_64-linux-gnu and for x86_64-windows-gnu. Under -fsyntax-only, which the first version used, clang computes a record's layout only when the front end needs it, and that differs between the targets: on mipsel nothing needs the size of a frame union that only SF.Alloc(sizeof(...)) uses (on x86_64 the size_t-to-u32 conversion check does), and many local views were never laid out at all. The survey skipped every view without a layout, silently: it checked 95,144 uses where there are 158,417. The dumps are cached by a hash of the source, the headers and the flags; all 14 levels take a few minutes in parallel, and a level alone about twenty seconds once its dumps exist.

Each use of a view is checked on its own: a cast followed by ->member, or a member reached through a pointer variable typed as the view, from the variable's assignment to the next. For the member chain the use names (args.setIdle.idleSlot), the survey looks up the real field at the same EE offset and reports [offset] when the view's field starts at another host offset (an offset inside an array of pointers scales with the element), [narrow] for a store narrower than the real field on the host, [wide] for a field wider than the real one and [past end] for a field beyond the real struct. A *(T *)&view->member access, and a load converted to a 32-bit type at once ((REF)view->member), are as wide as T. Two more checks need no target: [narrow] for a *(s32 *)&p->member store to a member that is pointer-width on the host, whatever struct p is, and [fixup] for a save fixup range of code pointers, strings or script states over a field that is not pointer-width on the host. Two check what no view shows:

  • [frame size]: every X = SF.Alloc(size) (or SF.AllocNM) whose block a call then uses as its callee's frame (pFrame->m_pNextVariables, a message handler's own frame, a child stored there). The size's smallest value is evaluated on both targets from its literals, sizeof terms (sizeof(*frame) through the variable's declaration), the constants the function assigns to the variable before the allocation and enumerators of the function or the file; a term read from a controller at run time counts as 0. Each statically known callee's frame (&X_fc, __ob_rt_change_state's ScriptStateTransitionFrame) must fit on the host when it fits on the EE. A virtual slot whose m_lInputSize the allocation reads (SC_VIRTUAL_FUNCTION(pSS, Slot) or controllers[Slot]) is sized at run time and skipped. SCRIPT_VIEWS_FRAME_CALLEES=1 adds every callee the block serves with its EE and host sizes, the members of the union to write; SCRIPT_VIEWS_FRAME_SKIPPED=1 lists the allocations whose size could not be evaluated.
  • [windows layout]: every record laid out differently for x86_64-windows-gnu than for x86_64-linux-gnu.

Enumerators written as expressions (SlotMoveToPos = 0x70 / 4) are evaluated; the first version read that one as slot 0x70 and paired the hunt's MoveToPosArgs with AimWeaponAtObject. It finds the real struct from what the view points at:

View of Real struct
pSS->m_pScriptVariables the variables struct the file's SCRIPTCREATOR names. A view padded with SC_MEMBER_OFFSET(X_Variables, ...) overlays X_Variables. A module-support function runs on the variables of the scripts whose function tables hold it, of the files that call it, and of the scripts an alien call to it is made on (the smallest of them, a base whose derived scripts share its fields). A field past the end of that struct is looked up in the struct whose fields agree with the view's (a useable's function that runs on the actor).
pSS->m_pStateVariables <State>_Variables, for the longest prefix of the function's name that names one
the next frame the frame of the callee. A store fills the first call after it in the same case. A load reads that frame, the call just before it in the same case (a message handler's calls return in place) or the calls made with the resume index of the case labels that lead to it. A callee is a &Controller_fc; a virtual slot (SC_VIRTUAL_FUNCTION, m_pFunctionsVirtualTable[slot]) of the file's table and of every table that extends it; an alien call's SF.GetAlienVirtualTableEntry(script, offset) where the script was found by name (SF.FindScriptStateByRef(..., "alllevels.human"), directly, through a variable or through a member the level stores a found script in); or a controller held in a variable or in a member the level stores &Controller_fc in (hold->whileHeld). The use is fine when any candidate's frame agrees.
pFrame the function's own frame, from its controller's sizeof (through typedef aliases)
pData MSG_<message>_Payload of an _on_<message> handler. A message with no payload struct travels as EE words, so its view must have the same layout on both, which the survey checks.
x->m_pScriptVariables the level's variables struct whose fields agree with the view's (reported as a guess)

Named views of SDK types and of *_Variables structs are taken as real. A use whose target the survey cannot find is counted by reason; --unresolved lists the local ones, and given twice the named ones too. The exit status is 1 when a problem is found.

What the survey found and what was fixed

On 25 November 2026 the survey checked 95,213 view uses of the sources as they were and reported 521 problems in 110 files (260 offsets, 233 narrow stores, 28 wide fields); after all the fixes below it checks 95,144 uses and reports none. Every edit is the same type on the EE (uptr and sptr are u32 and s32 there, SC_POINTER_SLOT(T) and SC_POINTER_TYPED_WORD(T) are T, SC_MEMBER_OFFSET padding has the same size, and a callee's own frame type has the same member at the same offset), and all 14 modules still rebuild byte for byte. Shared files carry one copy per level; the count says how many levels had the bug.

File Function Was Fix
Alllevels_Guard.c (14) Alllevels_Guard_DenyAccess, Alllevels_Guard_CheckAndDenyAccess denyStage behind u8 beforeDenyStage[0x28D] / [0x28E]: host 0x291 instead of byte 1 or 2 of guardOptions (0x2f1) padding from SC_MEMBER_OFFSET(Alllevels_Guard_Variables, guardOptions)
Alllevels_Guard.c (14) Alllevels_Guard_SuitcaseCheckState_run ApproachItemArgs.item a REF over RunToWaypoint's uptr target: narrow store uptr item
Alllevels_Guard.c (13) Alllevels_Guard_DeliverItemToStorageState_run DetachItemArgs.item a uptr over DetachItemFromLeftHand's REF: wide store REF item
Alllevels_Human.c (14) Alllevels_Human_EngageTargetState_run, Alllevels_Human_AimAtTargetOrPosition strafePos and collisionPos behind [0x80] padding: host 0x27c instead of 0x294 (in unknown232) padding from SC_MEMBER_OFFSET(Alllevels_Human_Variables, unknown232) + 2 - SC_MEMBER_END(..., strafeMode)
Alllevels_Armed.c (14) Alllevels_Armed_WarnAboutTrespassing TurnArguments.target REF over TurnToFaceObject's uptr; ApproachArguments.options an s32 over FollowObjectRunning's followUp pointer (options = 0 cleared half of it) uptr target, sptr options
Alllevels_Civilian.c (14), M05_M05_Gardener.c ..._WarnAboutTrespassing the same, and WaypointArguments.waypoint (RunToWaypoint) and TargetArguments.target (LookAtIfNotAlready, M12_LookAtTarget) REFs over uptr slots uptr, sptr
M12/Alllevels_Civilian.c Alllevels_Civilian_InvestigateFootstepsState_run LookArguments.target REF store into M12_LookAtTarget's uptr refObject store through M12_LookAtTarget_Frame
Alllevels_Perceptionconverter.c (14) Alllevels_Perceptionconverter_on_perception args->value.target (a REF in a union that must stay 4 bytes for the perception after it) stored into LookAtIfNotAlready's (M12: M12_LookAtTarget's) uptr the two stores go through the callee's frame type
Alllevels_Useable_Useable_Consumeobject.c (5) ..._Consumeobject_UseObject targets for WalkToWaypoint and TurnToFaceObject stored through ReleaseConsumedObject_Frame's REF stores through the callees' frame types
Alllevels_Poodle.c (M02, M12) Alllevels_Poodle_AlertBarkState_run owner a pointer over the poodle's REF owner (wide load); MoveTargetArgs.target/mode 4-byte over RunToWaypoint's uptr target and followUp; LookTargetArgs.target a pointer over TurnTowardsObject's REF SC_POINTER_TYPED_WORD(PoodleOwnerRef), SC_POINTER_SLOT(PoodleOwnerRef), sptr mode
M01/Alllevels_Useable_Useable_Riflestandguard.c ..._Riflestandguard_UseObject ReactArguments.delaySeconds an s32 over PlayStandAnimationByTension's sptr duration sptr
M00_M00_Gateguard.c M00_M00_Gateguard_on_m00_triggergateguardbackup NotifyArgs.result an s32 over SendDelayedMessageInFork's ScriptState *result: radius, sender and event one slot early sptr result
M00_M00_Sniper.c M00_M00_Sniper_AimAtTargetState_on_perception AimArguments.target REF at host 0x24, AimWeaponAtObject's uptr target at 0x28 uptr target
M00_Scoop.c, M03_M03_Bodyguardsleeping.c, M03_M03_Wardrobeguard.c M00_Scoop_SpeakAttackingPain, ..._PlayWarningSpeech, ..._HitmanAsksQuestionState_run a counter byte behind [0x2dd]: host 0x2dd instead of byte 1 of the flag word at 0x345 padding from SC_MEMBER_OFFSET(..., scoopFlags / sleepFlags / wardrobeFlags) + 1
M09_M09_Civilian.c ..._CoupleChatState_run, _on_m09_chatcouple, _destroy chat bytes behind [0x2A2] / [0x2A3 - 0x290] padding from SC_MEMBER_OFFSET(M09_M09_Civilian_Variables, civilianWeddingFlags)
M11_M11_Agentcia.c M11_M11_Agentcia_root_enter checkCounter/subState behind [0x2A2] padding from SC_MEMBER_OFFSET(..., projectorFlags) + 2
M11_M11_Agentcia.c M11_M11_Agentcia_SitDownState_run PreSitArgs.result a void * over M11_RunFollowUpAfterMove's 4-byte result SC_POINTER_TYPED_WORD(void *), and the frame's sitResult with it
M11_M11_Partygirlassassin.c M11_M11_Partygirlassassin_TurnByAngle turn animations behind [0xCA] padding from SC_MEMBER_OFFSET(..., unknown36C) + 2 - SC_MEMBER_END(..., checkAreaFlags)
M11_M11_Partygirlassassin.c ..._PickUpMicrophoneState_run, _PutDownMicState_run, _WaitInChapelState_run MoveToSpotArgs.result a void * over WalkToWaypoint's 4-byte result, which moved flags and target SC_POINTER_TYPED_WORD(void *), uptr target
M11_M11_Baseguard.c, M11_M11_Cameraguard.c, M11_M11_Entranceguard.c ..._on_perception, ..._on_evm11_specialrestrictedzoneenter, ..._WatchEntranceState_on_perception the state change's target behind u8 padding[7]: host 0x28 instead of 0x30, so the guard changed to whatever state the frame held padding from SC_MEMBER_OFFSET(ScriptStateChangeArguments, target) - sizeof(LocalVarEntry) - 1
M01_M01_Phototourists.c, M03_M03_Lobbyphototourists.c, M10_M10_Lobbyphototourists.c ..._TouristAPoseState_run, ..._PoseForPhotoState_run, ..._SmokerPoseForPhotoState_run an s32 over PlayInterpolatedAnimationAndWait's followUp pointer moved the clip, direction and position sptr
M01_M01_Useable_Moviestar.c ..._Moviestar_UseObject slot 50's REF target written through a view's uptr store through Alllevels_Basefunc_CopyActorToReference_Frame
M02_M02_Balconyguy.c, M02_M02_Casanova.c, M09_M09_Useable_Ambientsmoking.c, M12_M12_Marinecameraguard.c, M12_M12_Museumstaffinshower.c, M09_M09_Blackwiddow.c moves, turns and looks a REF over the callee's uptr target (M02_MoveToTarget, RunToWaypoint, WalkToWaypoint, M12_LookAtTarget, TurnToFaceObject, PlayInterpolatedAnimationAtObjectAndWaitForEnd) uptr
M09_M09_Crapganggroom.c ..._EatItemState_run a ScriptArgumentWord copied into WalkToWaypoint's uptr target uptr importArgument, stored as *(const u32 *)&
M06_M06_Chef.c, M09_M09_Drinkwaiter.c, M13_Secretservice.c ..._CutVegetablesState_run, ..._FindNextGuestState_run, ..._RadioCheckAndPlayIdleAnimation an s32 over PlayStandAnimationByTension's sptr duration sptr
M03_M03_Carpenter.c four functions uptr toolboxItem over REF toolbox: wide load REF
M08_M08_Buffetwaiter.c ..._WalkToBuffetState_run serviceAction stored through BuffetWaiterArguments, whose 8-byte result put it at host 0x28, for M08_GetBurgerInElevatorSlot's slot at 0x24 store through the file's GetBurgerInElevatorSlotArgs (a union member like the original's; a plain M08_GetBurgerInElevatorSlot_Frame store changed the EE code)
M09_M09_Blackwiddow.c, M09_M09_Drinkwaiter.c, M09_M09_Guardteahouse.c, M09_M09_Piershooter.c, M11_M11_Agentcia.c, M11_M11_Partyarranger.c, M11_M11_Partygirlassassin.c, M11/module-support.h state run frames, M11_RunBartenderRoutine_Frame the frame typedef's move result a void * where the function's own view (and the callee) has a 4-byte word SC_POINTER_TYPED_WORD(void *) in the typedef

The two checks that need no view were added after these fixes and found 875 int stores to pointer-width members in 212 files and 40 pointer fields typed as integers (90 with the level copies). They were fixed by rule, again with the same EE types:

  • *(Q s32 *)&p->slot = v; became *(Q sptr *)&p->slot = v; (u32 became uptr), with a leading (s32)/(u32) cast of the value and a load of the same member through *(Q s32 *)& widened the same way (729 lines: followUp, callback and followCallback cleared to 0, pendingState, infectionThread, the perception converter's saved behaviour states, stateBeforeCar, event.pData, refObject and target slots).
  • *(volatile ScriptArgumentWord *)&p->target = *(ScriptArgumentWord *)&src; became *(volatile SC_ARGUMENT_SLOT *)&p->target = SC_ARGUMENT_WORD(src); (146 lines, waypoint and target words copied into uptr slots). A plain uptr store of *(const u32 *)&src changed the EE instruction order in three HIDEOUT functions, because ScriptArgumentWord is may_alias; the macros keep the original's copy on the EE.
  • The fields became sptr or uptr: stateBeforeCar (Alllevels_Human_ReserveSeatAndEnterCar_Frame, M05_ReserveSeatAndEnterCar_Frame, M13_ReserveCarSeatThenEnterCar_Frame), unknown14 (Alllevels_Human_ReturnToPreviousState_Frame), interruptedState (Alllevels_Human_SaveInterruptedState_Frame), behaviorState (Alllevels_Perceptionconverter_SaveThenSetAllBehaviorStates_Frame), nextState of every level's waypoint-list function in module-support (HIDEOUT_FollowExternalWaypoints, M00_FollowExternalWaypoints, M02/M03_FollowExternalWaypointList, M05/M06/M08_FollowWaypointList, M09_FollowPathOneWay, M10_FollowWaypointListOnce, M11/M13_FollowWaypointListOneWay), the delayed-message handles replyResult1 to replyResult5 (M02_M02_Drinkingvipguest), timerResult (M02_M02_Governorson, M08_Chef), delayedMessageHandle (M02_M02_Grothobunny), lookAtResult (M09_M09_Guard), waitResult (M09_M09_Weddinggangboss), the suits currentSuit (M03_M03_Operatourist, M05_M05_Witnesswife), the states returnState (M10_M10_Afrikaaner), rememberedState (M10_M10_Sheikbodyguard), newState (M11_M11_Agentcia) and the state slots unknown2E8/unknown2EC (M01_M01_Sittingguard), unknown2EC (M04_M04_Bodyguardbase), unknown2A8/unknown2AC (M04_M04_Therapist), unknown300 (M11_M11_Entranceguard) and unknown3B8 (M11_M11_Partyarranger). The own-frame views of two of them followed (ChefState7Frame, WaitEventFrame), and four assignments that cast the value to s32 (pathEndState = (s32)vframe->nextState in the waypoint-list functions, rememberedState, lookAtResult, delayedMessageHandle) cast it to sptr.

M09_M09_Civilian_Variables.savedResult, a delayed-message handle the fixups walk as a script state, was left at four bytes in this pass: made pointer-width, it crashed M09 on its first frame (the frame of M09_M09_Civilian_root_enter had the low half of its controller cleared). After the second pass it is sptr (with the CivilianVariables view of M09_M09_Civilian_on_m09_weddingbell's neighbour, which also carries SC_GCC_LAYOUT now), M09 runs 4,500 frames of the view test with every check on, and the survey has no known exceptions left (KNOWN is empty). The likeliest cause of the first-frame crash is one of the frame-size or Windows-layout bugs below; it was not reproduced to tell which.

Not every row changed what a run does: a narrow store into a slot that was zero, or a wide load whose value is truncated to a REF at once, gives the same result. The table lists them all because each is wrong for some frame contents.

The first survey (24 November, build/pc-only/sound/script_views.txt in the main checkout) compared every definition of a view name with the script's variables and listed 25 files. Most of its entries were not bugs: 32 of the 135 local definitions it named are declared and never used (the generator kept them), and its comparison paired the first definition of a name with every use. Of its 25 files, the M04 coffee refill, the M09 civilian's couple chat, the party girl's TurnByAngle, the carpenter (its toolbox, not the hammer it named) and the CIA agent (its byte fields, not the suitcase) had real bugs; the rest had none.

The uses the survey cannot resolve were read by hand: payload views of messages without a payload struct (1,270 uses, all with the same layout on both); a view of a local or global of its own type (&msg, &savedStates, &kDoorArgs); SniperDifficultySettings over the engine's sDifficultySettings (floats); M11_M11_Partygirlassassin_SingKaraoke, a function that reads SingKaraokeState's variables (two s16 and an f32, the same on both); M12_M12_Touristwithsuitcase_UseSuitcaseState_run's alien calls (the same Useable_Object slots and argument shapes as M10_M10_Pokerplayer's, which the survey resolves); and 64 uses in module-support functions nothing calls (M10_RetrieveItem, M10_FetchItem, M10_GoPickUpItem, M10_RetrieveItem2, M11_PlaceAndActivateTarget), whose hard-coded padding would be wrong on the host if they ever ran.

Second pass, 25 November 2026

The survey above missed three kinds of bug: views clang never laid out under -fsyntax-only, frames sized for the EE, and the Windows bitfield layout. With the code-generator dumps, the [frame size] and [windows layout] checks and enumerator expressions it checked 158,417 view uses and found 1,097 more view problems in 69 groups, then 88 frame-size problems, then 12 Windows layouts. After the fixes it checks 158,417 uses and reports none. As before, every edit is the same type or constant on the EE, and all 14 modules rebuild byte for byte (functions, data, header and linker tables, image; compiled_digests.py check and script_sdk.py headers --check agree).

Frames sized for the EE. Each size became the sizeof of the callee's frame, or of <Function>_Children, a file-scope union of the frames of the statically known callees the survey lists (the EE size of the union is the old literal in every case; the virtual-slot callees stay sized at run time). The ones that ran in the view test are in bold:

File (levels) Function Was Host need
Alllevels_Bird.c (5) LandedWatchState_run u16 capacity = 0x18 40 (PlayRandomStandingAnimation, PlaySecondaryAnimationClipUntilDone)
Alllevels_Bird.c (5), M00_Entrancebird.c three _on_stopcheckforhitmanthread/_on_scarysound handlers lSize = 0x14U 32 (PlaySecondSound)
Alllevels_Basefunc.c (14) on_actordamage, on_resumescript, HeldAsHumanShieldState_on_resumefromzombie 0x18U, 0x24U 40 (StartInfectionCountdown), 48 (StorePerception)
Alllevels_Human.c (14) AimAndShootState_on_reloaddone, ShoutForHelpState_on_firealarm, RagdollWaitState_on_resumefromzombie 0x1CU, 0x18U, sizeof(ScriptPerceptionArguments) 48, 40, 64
Alllevels_Guard.c (14) ConfrontIntruderState_run, PickUpSuitcaseState_run, PickUpConfiscatedWeaponState_run 0x30, MinimumCallFrame = 0x34 72 (TurnToFaceObject), 72 (RunToWaypoint)
Alllevels_Armed.c, Alllevels_Civilian.c (14 each), M05_M05_Gardener.c WarnAboutTrespassing MinimumChildFrame = 0x6C, 0x54 104 (FollowObjectRunning)
M00_M00_Druglabgangster.c RepairUtilityBoxState_run 0x4CU 88 (M00_SendPerception)
M06_M06_Hotelroom2Boyfriend.c, ..Girlfriend.c PickUpBeerState_run, ListenToBoyfriendState_run 0x40, 0x2C
M11_M11_Levelcontrol.c, M11_M11_Partyarranger.c, M11_M11_Partygirlassassin.c on_evm11_enterheaven/enterhell, BackStepState_run, SingKaraoke sizeof of local views 56, 64
M01_M01_Sittingguard.c, M06_M06_Politician.c, M09_M09_Civilian.c state changes in on_actordamage, on_m09_weddingbell 0x24U 64 (ScriptStateTransitionFrame)
Alllevels_Poodle.c (2), M05_M05_Witness.c, M12_M12_Entrancecontroller.c, M12_M12_Tourguide.c, M09_M09_Weddinggangboss.c state changes in message handlers unions of ScriptStateChangeArguments or u8 changeStateFrameSize[0x24] 64: the unions hold a ScriptStateTransitionFrame stateChange

Views the survey had never seen (one copy per level where shared):

  • Hard-coded padding over script variables: the human's cover search (FindCoverState_run, RunToHidingCoverState_enter, u8 beforeCover[0x154]) wrote its sCover at host 0x154 instead of 0x19c, over the actor's REFs, the infection thread and the path end state; beforeThreat[0x4C] (and ChaseAndFireState_run's TargetVariables) read the threat REF from 0x4c instead of 0x64; RepositionAndFireState_F161's HumanWeaponState read the aiming flag from 0x17c instead of 0x1c4. Level views did the same in M03 (opera singer, tour guide, tourist), M04 (EscortVipState_run), M05 (camera guard), M06 (waiter), M08 (the chef's PreparePlate, which runs on the food-cycle controller's variables, not the chef's), M11 (party arranger, reception guard) and M12 (GetDistanceToHitman). All are SC_MEMBER_OFFSET now.
  • A four-byte 0 into a callee's followUp pointer, which keeps the upper half (the M10 crash's pattern): the dog (ChaseAndBiteTargetState_run, ReactToSoundState_run, InspectItemState_run), the poodle (two states), Alllevels_Guard_RespondToTrespassingHitman (walkThreshold = 0.0f), the hunt's MoveToClosetArgs, M01's cellar couple and M03's light technician (reserved, extra), M03's secretary's bodyguard (stopDist), the consumable useable and M11's pyro show. The fields are sptr, uptr or SC_POINTER_SLOT(f32). The play-animation useable and M01's movie star agent stored an s32 into PlayStandAnimationByTension's sptr duration the same way.
  • A REF stored into a uptr target: AimWeaponAtObject's target was read at host 0x28 while AimAndFireAtTarget, AttackTargetState_run and RepositionAndFireState_F161 wrote it at 0x24, so every guard that aimed aimed at whatever the frame held; also LookAtIfNotAlready, TurnToFaceObject, WalkToWaypoint, M12_LookAtTarget and RunToWaypoint targets in the armed, civilian, guard, dog, look-around useable and nine level scripts.
  • The reverse, a uptr over a REF: FollowObjectWalking's own frame, M06 Raymond's event camera, M03's put-down, M10's scientist, M12's multi-talk and M04's coffee refill (slot 50 of the actor table is CopyActorToReference, so the coffee useable got its own ActorReferenceArgs); and a pointer over the event camera's lookAt (M08). The dog's BarkArgs.mode had been widened to sptr over PlayBarkSound's int, and the frame typedefs of M02's VIP guest and governor's son had been widened under their own views; both are back in step.
  • WeaponCheckFrame (HelpRequestAcceptedState_on_perception) wrote the next state at host 0x28 for the state change's target at 0x30: padding from SC_MEMBER_OFFSET(ScriptStateTransitionFrame, target), zero bytes on the EE.

Windows layout: the views EntranceVariables (M12), LaserbeamguardVariables (M02), ActorStageVariables and two ActorStageStateVariables (M03), PokerRatVariables (M03), the caterer's flag bits (M05), three BarfighterVariables and two CivilianVariables (M09) take SC_GCC_LAYOUT.

How the fixes were checked

On the PS2 side, every level was rebuilt with match_scripts.py match LEVEL --data --image after each group of fixes: all 14 rebuild their modules byte for byte, functions, metadata records and images. compiled_digests.py check reports that the 1,046 unit objects and 707 script objects compile as the verified build did, and script_sdk.py headers --check reports decompiled.h up to date. tools/tests/test_script_views.py tests the survey.

In the port, the Windows build from before the fixes and the build with them each ran every level in deterministic mode with the script trace, and compare found the first event the two differ at:

  • M04, the guard who refills his coffee. With only the coffee fix reverted, the run crashes at frame 435 in Zhm3Actor__Playlocaleresourceasspeech (locale.cpp line 296), called with a pointer whose upper half was stale. With it the level ran 9,000 frames, and the guard went through his idle choice (Engine__Randomrange 0 3), his line, the refill and Zusepoint__Unlock five times.
  • M10. Without input, a civilian's PutBackFoodState stores a four-byte 0 into WalkToWaypointAndUseObject's pointer-width followUp, and the walk calls the stale upper half at frame 2,462. Both the build from before the fixes and the build with only the view fixes crash there. With the int-store fixes, the level runs 3,000 and 4,500 frames.
  • M09. A drink waiter's PlayStandAnimationByTension used to get a four-byte duration in an eight-byte slot and waited on Engine__Gettime for a garbage time. Now it plays the animation at once. The traces differ from event 1,097,076 on.
  • After 3,000 frames without input, HIDEOUT, M00, M01, M03, M04, M05, M06, M08, M11, M12 and M13 give the same events in both builds. M02 differs at event 31.3 million in one SendCommand from evm02_serveguestreq, which passes a REF from stale state memory (a GoToBartenderState variable left by a message's duration). The REF names nothing in either build, so nothing follows from it.

Running into the scripted situations needs input. A test mod moved 47 next to one actor after another, every 150 frames from frame 450 on (guards first, in obm.world.actors() order), and made a noise there, so that perception, trespass warnings, access checks and alarms ran on many actors. Each build ran 4,500 frames of every level with it:

Level Before the fixes With them
HIDEOUT, M01, M03, M04, M05, M06, M08, M13 runs identical events (4.4, 19.3, 7.5, 3.9, 72.4, 7.3, 9.3 and 4.0 million)
M00 in three runs, crashed twice in three runs, crashed twice; identical events up to 3,703,201 every time, where the run that goes on runs a script whose m_rThis reads 0 and the run that stops crashes (frames 3,911 to 3,956, in ScriptTakesMessageNow or ScriptRunningObject)
M09 runs the drink waiter's difference above, no crash
M10 crashes (the followUp store) runs
M11 runs runs; the CIA agent (one of the fixed scripts) skips a command to its controller from event 24.5 million on and goes on to its speech and animation
M02 crashes at frame 3,610 crashes at frame 4,498 at the same place: Item__Clearfooddrinkinfection (item.si.cpp line 451, a null read) from the party guest's drink routine
M12 crashes at frame 4,450 identical events (10.2 million) and the same crash: Scene__Objecthascontroller (scriptc.cpp line 2045) reads a script creator 0xffffffffffffffff while it walks a geom's scripts

These were the builds before and after the first pass. The M00, M02 and M12 crashes, which both had, were found and fixed in the second pass: the crashes the view test found.

The crashes the view test found

The view test (tools/port/mods/viewtest, run with native_scripts.py stress) moves 47 next to one actor after another every 150 frames from frame 450 and makes a noise there. Before the second pass three levels crashed within 4,500 frames, in both the build before the view fixes and the build with them. Each crash had a different cause; none was a view the first survey could see.

M00: a callee frame sized for the EE. The crash was in ScriptTakesMessageNow (the port's copy of ZScriptC::Command) or ScriptRunningObject, reading a ScriptState field through a heap pointer whose low half was a small number (0x0000029900000010, 0x000001f300000042). The frame check that every build runs (ScriptCheckFrame) had logged the writer just before: function at +0x56d1f0 runs in a 32-byte frame but needs 40 (caller +0x56c800, script M00_M00_Basebird); pdb_symbol.py names the two offsets Alllevels_Bird_PlayRandomStandingAnimation and Alllevels_Bird_LandedWatchState_run. The caller allocated u16 capacity = 0x18 bytes (the callees' EE frame size, raised to a virtual slot's 32 on the host) and the callee's 40-byte frame ran 8 bytes into the next block: its allocator header and the low half of its first word, which in the crashing runs was a ScriptStateInfo's root state pointer. Whether the run stops depends on whether the damaged address is mapped, which is why it crashed in two runs of three. The fix is capacity = sizeof(Alllevels_Bird_LandedWatchState_run_Children), and the same class was then fixed everywhere with the survey's [frame size] check. Three M00 runs of 4,500 frames no longer crash.

M12: the Windows bitfield layout. The crash was in ScriptEngine::FindScriptStateByRef (scriptc.cpp line 2045; the first report named Scene__Objecthascontroller, which the same caller calls just before, in Alllevels_Basefunc.c's check for a useable on the current waypoint): a ScriptC on the waypoint had a root state whose creator chain read 0xffffffffffffffff. OPENBLOOD_SCRIPT_CHECK=1 showed that thirty scripts loaded one after another (M12_M12_Securitycheckpoint and the useables Wait, Sitdown, Lookaround, Smoking, Playanim that follow it) had state infos holding floats and red-zone bytes long before the crash, and its free check found the moment: SchedUpdate (run frame) frees the 9014-byte block ... (script M12_M12_Entrancecontroller, 160644 script calls), which holds the state info ... of script 45f (M12_M12_Securitycheckpoint). A run frame of 9,014 bytes (0x2336, not a multiple of 4) is a damaged allocator header: freeing it handed the next 9 KB, all those scripts' infos and states, back to the allocator. OPENBLOOD_SCRIPT_CHECK=3 narrowed the damage to the entrance controller's m12_iwanttoenter handler, and OPENBLOOD_SCRIPT_WATCH=M12_M12_Entrancecontroller caught the write: 00000024 -> 00002336 at +0xb60962, M12_M12_Entrancecontroller.c line 261, the handler inlined into ProcessMessage, storing the tourist's REF 0x2336. The handler's view struct { s32 entering : 1; ...; u8 touristCount; REF tourists; REF entrant; } puts entrant at 8 on Linux and the EE and at 12 under MinGW, whose bitfield rule is MSVC's; at 12 it is past the 12-byte variables block, on the header of the controller's own first frame. The fix is SC_GCC_LAYOUT, and the survey's [windows layout] check found eleven more such views. M12 runs 4,500 frames.

M02: a payload with no layout. The crash was a null read in Item__Clearfooddrinkinfection (item.si.cpp line 451) from the party guest's ConsumeItemState_run, with the REF 0x187a: GetValidItem returns 0 for a geom that is no item, and IsGeomType then calls through the null pointer (the EE would too). 0x187a is a waypoint. The guest was given it as its glass by evM02_PartyDrink (0x9a1), which ZM02_PartyController sends as SDrink { bool bOnPier; REF rDrinkPos; REF rGlass; REF rBartender; }; with 8-byte REFs and no layout the guest read the drink position as the glass and padding as the drink position. The rest of the party controller's records (evM02_PartyController_Init, evM02_WalkToParty, evM02_Party_Talk), the guests' evM02_ActionFinished back to it and the doors' DoorProtect/DoorProtectOpen had no layout either; all have one now (payload layouts). SDrink fills only one of the glass and the bartender, so those two are SCRIPT_FIELD_LOOSE_REF: the script gets the low half of whatever the sender's stack held, as on the PS2, instead of an abort. M02 runs 4,500 frames. This one is no layout problem in the scripts, so neither survey could see it; payload_layout_audit.py lists it now.

M10 (a deterministic run from the disc that crashed at about frame 4,000) was the WalkToWaypointAndUseObject followUp store fixed in the first pass: M10 runs 4,500 frames without the mod (5.3 million trace events) and with it.

After the second pass every level ran 4,500 frames of the view test with no crash, twice: with OPENBLOOD_SCRIPT_CHECK=1 and OPENBLOOD_SCRIPT_REDZONE=1 (no check or red-zone report on any level) and without them; M00 three times. 47 was moved 28 times on each level but M13 (13) and HIDEOUT (none: the hideout has no actors for it).

Checking for new ones

Run the survey after any change to a script source, and before a mod or a new level relies on a script function that has not run in a traced game; run native_scripts.py stress --check 1 --redzone on the levels it touches. A [frame size] problem is fixed with the sizeof of the callee's frame or of a <Function>_Children union of the callees' frames (SCRIPT_VIEWS_FRAME_CALLEES=1 lists them; the union's EE size must be the old literal), a [windows layout] one with SC_GCC_LAYOUT on the struct. A view problem names the file, line and function, the view, what it overlays and the field: fix it with the type the real struct has (uptr/sptr for a 32-bit EE word in a pointer-width slot, SC_POINTER_SLOT(T) when the EE type matters to the code, SC_POINTER_TYPED_WORD(T) for a 4-byte word the original accessed as a pointer), with padding from SC_MEMBER_OFFSET/SC_MEMBER_END, or by storing through the callee's own frame type, then rebuild the modules (match_scripts.py match LEVEL --data --image). A change of struct type can change the EE code even at the same offset (a union member's store takes a different alias set from a struct member's), so the rebuild decides.

Finding a damaged pointer

There is no debugger with watchpoints in the usual Windows setup, so the port has its own, all off unless their environment variable is set (port/engine/eventsbase/_sdl/scriptcoverridesdl.cpp, port/engine/zstdlib/_sdl/scriptfunctionssdl.cpp, scriptcallsdl.cpp). The M12 crash above was found with them in this order.

Variable What it does
OPENBLOOD_SCRIPT_CHECK=1 Remembers every script that loads, runs or takes a message. After each SchedUpdate and each outermost Command it checks every thread of every remembered script: the creator chain, state controllers, message handler and virtual table lie in the level's image; the variables, frames, alien call, async calls and message cue are 0 or have the script heap's upper half (a pointer whose low half was overwritten keeps it, one whose upper half was overwritten does not); each frame's and the variables block's allocator header (the word before the block) is a 4-byte multiple at least the block's size. The first damage of each script is logged once: Scripts: check N (update of REF NAME, ...): script REF NAME (load name, loaded with state info P) thread T: FIELD VALUE (...). Every free in the port's SchedUpdate and every SF.Free/SF.FreeNM is also checked against the remembered scripts' state infos and root states: Scripts: check: WHO frees the N-byte block P ..., which holds the state info P of script REF (NAME).
OPENBLOOD_SCRIPT_CHECK=2 The same after every script function run in SchedUpdate, naming the function's offset in the executable (function +0x..., for pdb_symbol.py).
OPENBLOOD_SCRIPT_CHECK=3 The same also after every interface call and before every script service, messages included (their frames on the message allocator's stack are accepted), naming the call. Slow: every check walks every remembered script.
OPENBLOOD_SCRIPT_REDZONE=1 Every block a script allocates (SF.Alloc, SF.AllocNM) is 32 bytes longer, filled with 0xfd; SF.Free/SF.FreeNM check the bytes and log Scripts: red zone of a N-byte block written at +A to +B (allocated by SCRIPT at call C, freed by SCRIPT at call D): words. It catches a callee that writes past the frame its caller allocated. Blocks the engine frees itself are not checked, and the extra bytes move every later allocation, so a run's addresses differ from a run without it (its events do not).
OPENBLOOD_SCRIPT_WATCH=NAME (Windows) A hardware write watchpoint (debug register 0, through a vectored exception handler) on the allocator header of the first frame of the first script named NAME, armed on the thread that runs the scripts at their first update. Each write that changes the word is logged with the instruction after it and the code addresses on the stack: Scripts: watch P: OLD -> NEW at +0x... (script ..., N script calls); stack: +0x... .... pdb_symbol.py build/port/windows/openbloodmoney.exe 0x... names the lines. The address and size are fixed in the source; another target is a one-line change in ScriptWatch.

Every report carries the script call count (g_ScriptCallCount), which is the same in every run of a deterministic build, so a run with OPENBLOOD_TRACE_SCRIPT_CALLS=1 shows the calls around it.

native_scripts.py stress LEVEL... [--frames 4500] [--jobs 4] [--check N] [--redzone] [--watch NAME] [--trace] runs the view test on each level in parallel and prints, per level, whether it crashed, how often the mod moved 47 and the first report lines; native_scripts.py run --viewtest does one traced run with the mod. The mod is tools/port/mods/viewtest (a Lua mod, loaded with OPENBLOOD_MODS_DIR, OPENBLOOD_ENABLE_MOD=viewtest and OPENBLOOD_ONLY_MODS=1): from frame 450 (VIEWTEST_START) and every 150 frames (VIEWTEST_EVERY) it moves 47 120 units from the next living human actor, guards and police first in obm.world.actors() order, and calls obm.world.distract there.

Checking a run

tools/third_party/venv/bin/python tools/port/native_scripts.py run M00 [--frames 200] [--log FILE] [--port EXE] [--iso ISO] [--input FILE]
tools/third_party/venv/bin/python tools/port/native_scripts.py compare a.log b.log [--ignore-allocs]
tools/third_party/venv/bin/python tools/port/native_scripts.py stress [LEVEL ...] [--frames 4500] [--jobs 4] [--check N] [--redzone] [--trace]

run also takes --viewtest, --check N, --redzone and --watch SCRIPT (finding a damaged pointer). stress runs the view test on each level (all 14 by default) without the trace unless --trace, keeps the logs in build/port/native-runs/LEVEL/stress.log, and exits with 1 when a level crashed or a check reported anything.

--port defaults to the CMake build (build/port/cmake/openbloodmoney) and --iso to the disc image in the checkout; the Windows build is build/port/windows/openbloodmoney.exe. A run keeps its settings and saves in build/port/native-runs/LEVEL/user (OPENBLOOD_USER_DIR), never in the player's folder.

run starts the level in deterministic mode with OPENBLOOD_TRACE_SCRIPT_CALLS=1 and OPENBLOOD_TRACE_SCRIPT_RUNS=1 and a fixed input script, using the offscreen SDL video driver unless SDL_VIDEO_DRIVER is set. The trace has one line per event:

script call <object> <interface> <arguments...> <script>   pointer arguments print as p
script sf <object> <service> <a> <b>
script ran <object> f|v|m <result>

Two runs of one build give the same events, so compare shows the first event a change moved. --ignore-allocs drops Alloc events, whose sizes change whenever a frame does.

Acceptance, 24 November 2026: before the emulator was removed, each level ran for 200 frames on the old build's emulated CPU, with its random number calls traced and the cue payloads it had failed to convert fixed. Every level's native run then gave the same events, arguments and return values:

Level Events
HIDEOUT 198,640
M00 76,383
M01 878,985
M02 4,037,033
M03 333,075
M04 190,731
M05 3,230,485
M06 388,264
M08 1,454,211
M09 235,518
M10 268,892
M11 1,315,223
M12 249,260
M13 177,794
Total 13,034,494

Pointer arguments, allocation sizes and random-number lines were masked, and GetAlienVirtualTableEntry offsets compared as slots. The emulated build no longer exists, so a future change is checked against an earlier native trace with compare. Moving the scripts from shared libraries into the executable (24 November 2026) left M00, M01 and M10 at the library build's events for 200 frames (79,011, 884,435 and 276,396).

Fixes found on the way that still matter:

  • A deterministic run does not redraw the loading screen, which moved the virtual clock (loadersequencesdl.cpp).
  • ZActor::MoveToPosition reads the EE cycle count (HostCycleCount), which is the virtual clock in a deterministic run, not the host's cycle counter.
  • The platform sources build with -fno-sized-deallocation, because the game does not define the sized operator delete and libstdc++ would free a game block with free().
  • The crash handler calls backtrace() once when it is installed, because glibc's first call allocates and deadlocked an abort from inside malloc.

Risks left

  • uptr slots written through a four-byte view leave a stale upper half. The survey finds every such store through a view and none is left; it does not see a store through a frame's own typed field, or a view use whose callee it cannot resolve.
  • The view test covers what 47's presence next to each actor sets off within 4,500 frames; script functions that never ran there are covered by the survey only. The [frame size] check sees sizes it can evaluate and callees it can name: SCRIPT_VIEWS_FRAME_SKIPPED=1 lists the allocations it skipped, nearly all sized only from a virtual slot's m_lInputSize at run time, which is right on both targets as long as the slot's own frame covers what the caller writes.
  • Engine-to-script payloads are converted only where a layout exists. payload_layout_audit.py finds a SendCommand(..., &record) whose record holds a REF or pointer; it does not see a record built in a buffer or passed through a pointer variable, and a script-to-engine message whose engine receiver reads *static_cast<REF *>(pData) is found only by reading the receivers (the second pass added DoorProtect and evM02_ActionFinished that way).
  • Calls into another script (SF.GetAlienVirtualTableEntry, a controller held in a variable) are resolved by the survey where the script was found by name or the controller stored from a known &Controller_fc; the local view uses it still cannot resolve were read by hand (listed under the survey). A virtual slot is checked against the override in every table that extends the caller's, and a use passes when one of them agrees, so a view that is right for one override and wrong for another passes.
  • Saved games use the native fixup walker. OPENBLOOD_SAVE_TEST_FRAME=300 in M00 saves (16,392 control and 262,272 data bytes), but loading it back under the offscreen SDL driver crashes in DrawListSubmit while the scene unloads, in the emulator build too, so a native load has not been run. A save from the PS2 or from an emulator build of the port does not load in this one.
  • The casino test (tools/port/tests/casino_stock.py) runs the stock M10 objectives under LLDB; it was not rerun after the switch.
  • Script patches depend on the PS2 code they wrap: M10's patch acts at resume index 12 of M10_M10_Scientist_InspectSuitcaseState_run, and the message-handler patches replace whole handlers. Nothing checks them when src/scripts changes, as check_overrides.py checks the engine's overrides; the applier only checks that each slot still holds the PS2 function the record names.
  • Mods compiled for the PS2 (script_sdk.py mod and build) are gone with the emulator. The levels' scripts are part of the executable, so native scripts from a mod would need a loader of their own: a library with its own creator table, listed in front of the level's. It is not written.
  • The Windows (COFF) objects and their link order were checked with clang and LLD 22's lld-link on Linux, with M00 and M01 linked together; the Windows port itself was not built or run.