decomp work

This commit is contained in:
Maddo 2026-10-12 00:41:16 +02:00
commit b7b60c191a
12 changed files with 1739 additions and 57 deletions

View file

@ -73,6 +73,27 @@ Append a dated row below using the generated ledger-tracked function count and p
| 2026-10-11 | 1,007 / 1,493 (67.4%) | 486 (32.6%) | 336,693 / 499,712 (67.4%) | 399,698 / 499,712 (80.0%) | Added the next 20 report-listed entries from `0045d140` through `0045ed80`, covering static-resource swap files, snap-egg item bounds/overlap, and sound-FLX cache management. |
| 2026-10-11 | 1,027 / 1,493 (68.8%) | 466 (31.2%) | 336,693 / 499,712 (67.4%) | 399,698 / 499,712 (80.0%) | Added the next 20 report-listed entries from `0045ee9c` through `00460044`, covering sound-FLX channel management, spatial sound events, and item-event cleanup. |
| 2026-10-11 | 1,046 / 1,493 (70.1%) | 447 (29.9%) | 336,693 / 499,712 (67.4%) | 399,698 / 499,712 (80.0%) | Added the next 19 report-listed entries from `0046009c` through `004611f4`, covering sound-event maintenance and the sprite manager/render-region paths. |
| 2026-10-11 | 1,066 / 1,493 (71.4%) | 427 (28.6%) | 336,693 / 499,712 (67.4%) | 399,698 / 499,712 (80.0%) | Added the next 20 report-listed entries from `00461230` through `00463350`, covering sprite-process animation, position-query movement, and cursor-state helpers. |
| 2026-10-11 | 1,086 / 1,493 (72.7%) | 407 (27.3%) | 336,693 / 499,712 (67.4%) | 399,698 / 499,712 (80.0%) | Added the next 20 report-listed entries from `00463390` through `00464390`, covering bottom-toolbar state, AVI text/file buffers, shutdown dispatch, and process timing. |
| 2026-10-11 | 1,106 / 1,493 (74.1%) | 387 (25.9%) | 336,693 / 499,712 (67.4%) | 399,698 / 499,712 (80.0%) | Checkpoint for the already documented `00463390`-`00464390` batch; this ledger row was omitted when that batch was first recorded. |
| 2026-10-11 | 1,126 / 1,493 (75.4%) | 367 (24.6%) | 336,693 / 499,712 (67.4%) | 399,698 / 499,712 (80.0%) | Added the next 20 report-listed entries from `00465b88` through `004671b0`, covering mouse/disk helpers, command-line parsing, and Usecode override/resource processing. |
| 2026-10-11 | 1,146 / 1,493 (76.8%) | 347 (23.2%) | 336,693 / 499,712 (67.4%) | 399,698 / 499,712 (80.0%) | Added the next 20 report-listed entries from `00467304` through `0046857c`, covering Usecode process serialization, resource-cache lifetime, random helpers, and bitmap-buffer management. |
| 2026-10-11 | 1,166 / 1,493 (78.1%) | 327 (21.9%) | 336,693 / 499,712 (67.4%) | 399,698 / 499,712 (80.0%) | Added the next 20 report-listed entries from `00468588` through `00469a10`, covering bitmap-buffer operations, clipped drawing/blitting, palette effects, and process setup. |
| 2026-10-11 | 1,186 / 1,493 (79.4%) | 307 (20.6%) | 336,693 / 499,712 (67.4%) | 399,698 / 499,712 (80.0%) | Added 20 report-listed entries from `00469a2c` through `0046e2a0`, covering runtime flags, item-shape interactions, modal UI state, and viewport selection candidates. |
| 2026-10-11 | 1,226 / 1,493 (82.1%) | 267 (17.9%) | 336,693 / 499,712 (67.4%) | 399,698 / 499,712 (80.0%) | Added the next 20 report-listed entries from `0046fc84` through `00471c99`, covering Usecode value-list operations, item-shape selection UI, and indexed-shape blitters. |
| 2026-10-11 | 1,246 / 1,493 (83.5%) | 247 (16.5%) | 336,693 / 499,712 (67.4%) | 399,698 / 499,712 (80.0%) | Added the next 20 report-listed entries from `00471d49` through `004721b4`, covering pixel-effect blitters, tracked-resource management, RNG, config helpers, and x87 trig routines. |
| 2026-10-11 | 1,266 / 1,493 (84.8%) | 227 (15.2%) | 336,693 / 499,712 (67.4%) | 399,698 / 499,712 (80.0%) | Added the next 20 report-listed entries from `004721be` through `0047286a`, covering string/path helpers, heap block release, process exit, file modes, and formatted stream output. |
| 2026-10-12 | 1,286 / 1,493 (86.1%) | 207 (13.9%) | 336,693 / 499,712 (67.4%) | 399,698 / 499,712 (80.0%) | Added the next 20 report-listed entries from `0047286f` through `00472d68`, covering resource release, runtime utilities, handle-table helpers, and Win32 startup. |
| 2026-10-12 | 1,306 / 1,493 (87.5%) | 187 (12.5%) | 336,693 / 499,712 (67.4%) | 399,698 / 499,712 (80.0%) | Added the next 20 report-listed entries from `00472dd0` through `00473d3b`, covering event interpretation, heap allocation, and formatted input/output. |
| 2026-10-12 | 1,326 / 1,493 (88.8%) | 167 (11.2%) | 336,693 / 499,712 (67.4%) | 399,698 / 499,712 (80.0%) | Added the next 20 report-listed entries from `00473d43` through `00475026`, covering formatted-input conversions, DBCS string helpers, runtime frames, and heap block allocation/free. |
| 2026-10-12 | 1,346 / 1,493 (90.2%) | 147 (9.8%) | 336,693 / 499,712 (67.4%) | 399,698 / 499,712 (80.0%) | Added the next 20 report-listed entries from `00475131` through `0047598a`, covering runtime error state, Win32 file operations, buffered streams, and local-time records. |
| 2026-10-12 | 1,366 / 1,493 (91.5%) | 127 (8.5%) | 336,693 / 499,712 (67.4%) | 399,698 / 499,712 (80.0%) | Added the next 20 report-listed entries from `004759ef` through `00476530`, covering timestamp conversion, runtime signal/exception handling, Win32 handle tables, and mutex acquisition. |
| 2026-10-12 | 1,386 / 1,493 (92.8%) | 107 (7.2%) | 336,693 / 499,712 (67.4%) | 399,698 / 499,712 (80.0%) | Added the next 20 report-listed entries from `00476592` through `0047738c`, covering TLS thread contexts, runtime callback dispatch, event records, exception actions, and virtual-region tracking. |
| 2026-10-12 | 1,406 / 1,493 (94.2%) | 87 (5.8%) | 336,693 / 499,712 (67.4%) | 399,698 / 499,712 (80.0%) | Added the next 20 report-listed entries from `00477400` through `00477ba2`, covering virtual-region allocation, numeric conversion, DBCS navigation, and Win32 file/handle helpers. |
| 2026-10-12 | 1,426 / 1,493 (95.5%) | 67 (4.5%) | 336,693 / 499,712 (67.4%) | 399,698 / 499,712 (80.0%) | Added the next 20 report-listed entries from `00477cbf` through `00478a46`, covering buffered file output, runtime math/stack support, calendar conversion, and timezone rules. |
| 2026-10-12 | 1,446 / 1,493 (96.9%) | 47 (3.1%) | 336,693 / 499,712 (67.4%) | 399,698 / 499,712 (80.0%) | Added the next 20 report-listed entries from `00478b56` through `0047998a`, covering heap reallocation, thread-context cleanup, virtual regions, and math-error reporting. |
| 2026-10-12 | 1,466 / 1,493 (98.2%) | 27 (1.8%) | 336,693 / 499,712 (67.4%) | 399,698 / 499,712 (80.0%) | Added the next 20 report-listed entries from `00479991` through `0047ae78`, covering exception dispatch, math diagnostics, string comparison, floating-point helper logic, and Win32 import thunks. |
| 2026-10-11 | 1,206 / 1,493 (80.8%) | 287 (19.2%) | 336,693 / 499,712 (67.4%) | 399,698 / 499,712 (80.0%) | Added the next 20 report-listed entries from `0046e384` through `0046faf0`, covering static-overlay updates, weapon-cache records, and Usecode value heap/list operations. |
Baseline context: Ghidra reported 1,618 total functions across all address spaces, 110 tracked entries with descriptive names and 76 with generated names, 82 descriptive names outside the main progress tables, 3 functions with function comments, and 46 thunks. Five table addresses did not correspond to function entries; these are switch/option addresses, not missed function starts. These supporting values are useful for triage but are not the primary progress percentage.
@ -1481,6 +1502,522 @@ This pass completes the remaining sound-event maintenance helpers, then follows
Caller checks and representative decompiler readbacks confirmed the sound-event/item relationships, sprite-table lifecycle, cached-frame updates, and dirty-region renderer. All 19 entries are documented at exact function-entry addresses with descriptive names and comments. Ghidra changes remain pending; no executable bytes were changed and the project was not saved.
## Address-Ordered Pass: Sprite Processes and Position Queries
This continuation completes sprite-manager accessors and restore controls, documents sprite-process creation/animation, then follows the position-query process through motion setup, collision-checked steps, and related cursor-state helpers.
| JP address | Ghidra name | Evidence and confidence |
|---|---|---|
| `00461230` | `sprite_manager_get_position_component_a` | Returns the 16-bit sprite-record field at offset `+0x0a`; callers include keyboard-facing adjustment and a sprite-state helper. The component's exact axis remains unresolved. |
| `00461250` | `sprite_manager_get_packed_world_xy` | Returns the packed position word at `+0x0c`, which the sprite manager passes to isometric projection; callers include keyboard-facing adjustment and motion setup. |
| `00461270` | `sprite_manager_suppress_updates` | Sets the global flag that makes the sprite render/update pass skip its work; called by a runtime state helper. |
| `00461278` | `sprite_manager_resume_and_mark_all_dirty` | Clears the suppression flag and marks every live sprite record dirty; called during runtime transitions. |
| `004612d8` | `sprite_manager_restore_state_from_stream` | Clears temporary lists, reads a 16-bit array from the supplied stream, and marks live sprite records dirty; called from savegame restoration. |
| `0046159c` | `sprite_process_find_or_create_for_state` | Allocates a sprite process for the requested state; for selected states it checks existing sprite positions and reuses a nearby process before creating another. Callers include item-state, marker, audio-selector, position-state, and Usecode paths. |
| `00461880` | `sprite_process_construct` | Constructs process type `0x249`, installs its dispatch table, creates a sprite-manager entry, and initializes animation fields; called by the state-based creator. |
| `00461b50` | `sprite_process_run` | Advances animation counters at a tick-dependent rate, updates the displayed frame, schedules the next timer, and removes its sprite entry on completion. This is a virtual run method. |
| `00461c9c` | `sprite_manager_offset_world_position` | Reads the selected sprite's position fields, applies two supplied offsets, and writes the updated position; called by item-grid insertion. |
| `00461cfc` | `position_query_process_construct` | Constructs process type `0x250`, initializes collision-query state and position-search fields, and stores its query-state object; called by candidate construction. |
| `00461e30` | `position_query_process_set_position_snapshot` | Copies a five-byte position value into two process snapshots and stores the accompanying field; also initializes an additional snapshot word. |
| `00461e50` | `position_query_process_set_position_snapshot_variant` | Copies the same five-byte position value into both snapshots and stores the accompanying field, without the additional word initialized by the other variant. |
| `00461e68` | `position_query_process_configure_motion` | Derives target deltas and step rates from the requested mode/state, with bounded randomized offsets; called by the position-query candidate builder and thin wrappers. |
| `0046227c` | `position_query_process_configure_motion_from_args` | Adapts its arguments and forwards them to the shared motion configurator; called by the candidate builder. |
| `00462300` | `position_query_process_configure_motion_from_sprite` | Reads stored sprite-manager position fields and forwards them with supplied parameters to the motion configurator; called by the candidate builder. |
| `00462414` | `position_query_process_update` | Updates process state, handles item contacts, synchronizes its sprite entry, advances a mode-specific frame, and may request another sprite process. |
| `004624f0` | `position_query_process_step_toward_target` | Advances toward a target in collision-checked increments, dispatches resulting position state and sound, then terminates or removes the associated item; called by its process update path. |
| `004628c0` | `position_query_update_world_bounds_from_shape` | Decodes shape-related packed fields and tightens supplied world-bound components using the item's outermost X/Y coordinates; called by the collision-checked step. |
| `0046332c` | `cursor_state_disable_and_center` | Sets the cursor-mode state to zero and centers the cursor at horizontal coordinate `0x140`; reached from Usecode dispatch. |
| `00463350` | `cursor_state_enable_and_center` | Sets the cursor-mode state and six related flags, then centers the cursor at horizontal coordinate `0x140`; reached from Usecode dispatch. |
Caller checks and decompiler readbacks confirmed the sprite-process lifecycle, savegame restore path, position-query call chain, and cursor helpers. All 20 entries are listed at exact function-entry addresses with descriptive names and decompiler comments. Ghidra changes remain pending; no executable bytes were changed and the project was not saved.
## Address-Ordered Pass: Bottom Toolbar, AVI Text, and Process Timing
| JP address | Ghidra name | Evidence and confidence |
|---|---|---|
| `00463390` | `bottom_toolbar_initialize` | Initializes five sprite-backed slots from a resource-ID table, spaces their bounds across the lower screen, and stores draw state. The direct caller lookup timed out; the matching five-slot state is consumed by the neighboring event and redraw helpers. |
| `00463520` | `bottom_toolbar_process_events` | Large event dispatcher; tests pointer input against the five stored rectangles, handles active-slot state, and dispatches selected UI/item actions. The exact user-facing meaning of each slot remains unresolved. |
| `00463c40` | `bottom_toolbar_redraw_dirty_slots` | Processes the stored rectangle for each dirty slot and clears its dirty flag when toolbar mode is active. |
| `00463cb0` | `bottom_toolbar_set_enabled` | Sets the toolbar state from the incoming boolean, marks all five slots dirty when enabled, and centers the cursor; called from two runtime helpers and a third unresolved entry. |
| `00463d0c` | `bottom_toolbar_enable_all_slots` | Enables toolbar mode, marks all five slots dirty, and centers the cursor; called by `game_runtime_transition_dispatch`. |
| `00463d4c` | `bottom_toolbar_disable` | Clears toolbar mode and centers the cursor; called by `game_runtime_transition_dispatch`. |
| `00463d70` | `bottom_toolbar_mark_slot_dirty` | Bounds-checks a slot index in the range 0-4 and marks that slot dirty; called by `item_shape_state_assign_linked_item`. |
| `00463dc0` | `avi_stream_file_buffer_init` | Clears stream fields, runs base initialization, then loads a requested file; called by `avi_player_find_video_or_resource_file`. |
| `00463e00` | `avi_stream_file_buffer_release` | Frees and clears the allocated stream-data pointer; called by AVI stream preparation and release paths. |
| `00463e1c` | `avi_stream_file_buffer_load` | Determines file size, allocates a buffer, reads the file through the stream helpers, and stores size and pointer; called by the initializer above. |
| `00463ed4` | `avi_player_get_next_status_record` | Returns the next 12-byte record and advances its index while records remain; called by `avi_player_update_status_text_overlay`. |
| `00463f08` | `avi_player_parse_text_records` | Walks buffered text records, locates `@` markers with DBCS-aware scanning, and fills per-record fields; called during AVI stream preparation. The text format's full semantics are unresolved. |
| `00463ff4` | `avi_player_find_next_text_record` | Finds a record boundary in the buffered text, advances across CR/LF and separators, and terminates parsed text in place; called by the parser above. |
| `004640b8` | `avi_player_find_record_marker` | Scans for `@` while skipping DBCS multibyte characters and returns the marker address; called by the AVI text parser. |
| `004641a0` | `file_stream_insert_at_offset` | Uses stream virtual methods to inspect/copy existing content, extend the stream, write bytes at the requested offset, and flush; called by an AVI-related helper. |
| `00464298` | `callback_noop_00464298` | Empty callback that immediately returns; referenced by an unresolved call site. |
| `0046429c` | `win32_shutdown_once` | Global guard ensures a registered shutdown callback runs once, then conditionally exits the Win32 message loop; called by fatal-report helpers and the main window procedure. |
| `004642f0` | `timer_process_construct` | Constructs a specialized process with type 4 and initializes its timer fields; called by `kernel_process_manager_initialize`. |
| `00464360` | `win32_delay_with_message_pump` | Pumps messages and callbacks until the multimedia timer advances by the requested number of 10 ms units; used by static-overlay loops and scripts. |
| `00464390` | `timer_process_accumulate_elapsed_ticks` | Accumulates elapsed 10 ms units and advances the process's previous timestamp; called by the process-manager loop and timer update helper. |
Caller checks and decompiler readbacks confirmed the AVI preparation/status-text paths, shutdown callback, process constructor, and timing helpers. Direct caller retrieval for the two larger toolbar routines timed out; their names are supported by the five-slot initialization, hit-testing, dirty-state, and cursor behavior in their decompilation/disassembly. All 20 entries are listed at exact function-entry addresses with descriptive names and decompiler comments. Ghidra changes remain pending; no executable bytes were changed and the project was not saved.
## Address-Ordered Pass: Mouse, Command Line, and Usecode Resources
This slice resumes at the next report-listed entry after the timer helpers. It covers small mouse/configuration utilities, Japanese command-line parsing, and resource-cache/process setup for Usecode event dispatch and the optional `-u` override.
| JP address | Ghidra name | Evidence and confidence |
|---|---|---|
| `00465b88` | `usecode_opcode_table_get_9bit_field` | Extracts a 9-bit value from an indexed 9-byte table record; called by `usecode_opcode_dispatch`. The table field's higher-level meaning remains unresolved. |
| `00465bc0` | `filesystem_get_available_disk_space_bytes` | Multiplies the free-cluster count, sectors per cluster, and bytes per sector returned by `GetDiskFreeSpaceA`. |
| `00465c00` | `mouse_controller_initialize_global` | Creates the global mouse-controller object from its resource path, installs its dispatch table, and initializes dimensions to 320 by 200. |
| `00465c64` | `mouse_controller_update_pointer_region_state` | Translates cached pointer-region rectangles with controller dimensions and stores whether the supplied point lies in either region. |
| `00466068` | `process_construct_timed_state_flag_variant` | Builds on the timed no-op process constructor, initializes the process clock, registers state flag `0x04`, and sets another process flag. |
| `004660ac` | `Game_ViolenceEnabled` | Tests whether the configured `VIOLENCE` value contains `'1'` at offset 9; used by item-interaction and Usecode paths. |
| `004660bc` | `Game_CompileIs1` | Tests whether the configured `GAME_COMPILE` value contains `'1'` at offset `0x0d`; queried by Usecode opcode dispatch. |
| `004666d0` | `command_line_next_token` | Advances through the command-line buffer, skips classified separators, and returns the next token after terminating it in place; called by the Japanese argument parser. |
| `00466a1c` | `win32_game_initialize_command_line` | Initializes the Windows game object, sets the Japanese game-title prefix, dispatches Japanese command-line arguments, and invokes virtual cleanup; called from `win32_game_main`. |
| `00466c10` | `usecode_override_stream_open` | Constructs and opens the resource stream used by the optional Japanese Usecode override path; reports a fatal resource error if backing allocation fails. |
| `00466cf8` | `usecode_resource_stream_seek` | Seeks the Usecode resource stream to the requested offset and reports a fatal file error when the stream position is invalid. |
| `00466d30` | `usecode_resource_stream_read` | Forwards a requested byte count to the Usecode resource stream's read operation. |
| `00466d60` | `usecode_resource_cache_entry_initialize` | Initializes a resource-cache entry, allocates its backing data, stores size/resource metadata, and installs its release callback. |
| `00466de0` | `usecode_resource_cache_entry_release` | Releases a cache entry and its resource object, with additional cleanup selected by callback flags. |
| `00466e68` | `usecode_runtime_reset_state` | Resets the active Usecode runtime object and associated state; called during savegame restoration and startup initialization. |
| `00466ebc` | `startup_apply_u_override_if_present` | Applies the Japanese `-u` Usecode override when configured, loads its resource data, and rebuilds associated resource-index state. |
| `00467004` | `usecode_override_shutdown` | Releases the active Japanese Usecode override object, clears its global state, and performs shared runtime cleanup. |
| `00467060` | `usecode_get_item_event_selector` | Derives an item's Usecode event selector from its item flags, shape flags, shape-class state, or shape ID; called by event-selection helpers. |
| `004670b0` | `usecode_start_event_process_if_enabled` | Checks the item's derived selector against the enabled-event mask and creates a Usecode process when that event is enabled; called from item lifecycle paths. |
| `004671b0` | `UsecodeProcess_Create` | Constructs a Usecode process, initializes its program context/function data, and copies supplied argument bytes onto its stack. |
| `00467304` | `UsecodeProcess_Run` | Runs the next Usecode opcode, updates saved execution state on completion, and dispatches the process completion callback. |
| `00467360` | `UsecodeProcess_Callback_67360` | Releases the process state arrays and conditionally performs final cleanup when the process is not in its completed state. |
| `00467380` | `UsecodeProcess_Callback_67380` | Serializes process state arrays, execution offsets, function metadata, and associated data buffers to the save stream. |
| `00467448` | `UsecodeProcess_Callback_67448` | Restores serialized process state and data buffers, then reconnects the process to its active function/resource context. |
| `004676a0` | `usecode_resource_table_release_entries` | Releases both allocated arrays for each of the 128 Usecode resource-table entries, then clears the associated intrusive list. |
| `00467738` | `usecode_resource_table_find_or_select_slot` | Finds a resource-table entry by ID or selects and cleans a reusable slot, returning the selected slot through an output pointer. |
| `004678d4` | `usecode_resource_table_load_metadata` | Reads a resource-table entry header, allocates its metadata arrays, and initializes per-resource reference states. |
| `004679f0` | `usecode_resource_cache_acquire_resource` | Acquires a resource by table and index, loading and caching missing data, updating reference counts, and promoting cache nodes. |
| `00467d50` | `usecode_resource_cache_get_data_pointer` | Returns the data pointer from the cache entry acquired for the supplied resource table and index. |
| `00467d64` | `usecode_reference_table_decrement_refcount` | Decrements the selected resource reference count and reports an underflow. |
| `00467de8` | `usecode_resource_cache_release_if_unused` | Releases a cache node when its resource reference count reaches zero, updates cache accounting, and unlinks the node. |
| `00467ebc` | `usecode_resource_cache_release_matching` | Releases cache entries matching the requested table/resource selector, or drains entries when passed the all-entry sentinel. |
| `004680f0` | `UsecodeProcess_Callback_680F0` | Releases process-owned resource and dynamic-array state, with a separate teardown path selected by callback flags. |
| `004681f0` | `file_path_exists` | Returns whether `GetFileAttributesA` succeeds for the supplied path. |
| `00468208` | `random_range_inclusive` | Advances the shared linear-congruential random state and reduces its 16-bit value modulo the inclusive endpoint span. |
| `00468344` | `random_seed_initialize` | Initializes the shared random state from the supplied seed while forcing the low bit to one. |
| `00468354` | `random_next_modulo` | Advances the shared linear-congruential random state and returns its 16-bit value modulo the supplied nonzero bound. |
| `004683e4` | `surface_bitmap_buffer_initialize` | Initializes bitmap-buffer dimensions and row offsets, allocating backing storage or obtaining the DirectDraw surface pointer according to flags. |
| `00468510` | `surface_bitmap_buffer_release_resources` | Releases owned backing storage and row-offset data; flags select pointer-only clearing or preservation of externally managed storage. |
| `0046857c` | `surface_bitmap_buffer_release` | Thin cleanup wrapper that delegates bitmap-buffer release to the shared resource-release routine. |
| `00468588` | `surface_bitmap_buffer_copy_descriptor` | Releases the destination buffer's current resources, copies the supplied bitmap-buffer descriptor, and marks the copied buffer as externally managed. |
| `004685b8` | `surface_bitmap_buffer_get_pixel_address` | Computes a pixel address as the buffer base plus row times stride plus column. |
| `004685d4` | `surface_draw_line_bresenham` | Draws a clipped line between two coordinates using an integer Bresenham-style raster walk. |
| `00468964` | `surface_draw_horizontal_line` | Draws a horizontal span clipped to the bitmap-buffer bounds; an unsupported buffer mode takes the not-implemented error path. |
| `00468a78` | `surface_draw_rectangle_outline` | Draws a rectangle outline by composing clipped horizontal and vertical spans, defaulting zero bounds to the full buffer. |
| `00468c7c` | `surface_bitmap_buffer_copy_rect` | Copies a clipped rectangular pixel region between bitmap buffers, temporarily locking and unlocking a DirectDraw surface when its backing pointer is unavailable. Confirmed from disassembly after decompilation failed. |
| `004692e0` | `surface_draw_vertical_line` | Draws a clipped vertical span by writing the requested pixel value at each row using the buffer stride. |
| `00469338` | `surface_set_pixel` | Writes one pixel when its coordinates fall within the bitmap-buffer bounds. |
| `00469390` | `surface_blit_indexed_shape` | Blits a clipped indexed shape into the destination buffer, selecting the pixel-copy routine from the source encoding flag. |
| `00469488` | `surface_blit_indexed_shape_flipped` | Blits a clipped indexed shape with its source rows reversed horizontally, selecting the copy routine from the source encoding flag. |
| `00469598` | `render_flip_skip_translucent_not_implemented` | Reports the unsupported flipped skip-translucent draw mode through the fatal message-box path. |
| `004695a8` | `surface_blit_indexed_shape_with_pixel_effect` | Blits a clipped indexed shape through one of two pixel-effect routines selected by the source encoding flag. |
| `004696ac` | `render_flip_skip_transform_not_implemented` | Reports the unsupported flipped skip-transform draw mode through the fatal message-box path. |
| `004696bc` | `packed_shape_find_pixel_data_at_position` | Walks packed shape row data to locate source pixel data at a translated coordinate. |
| `0046974c` | `surface_blit_indexed_shape_with_mapping` | Blits a clipped indexed shape through one of two mapping/effect routines selected by the source encoding flag. |
| `00469850` | `surface_blit_shape_effect_mode_dispatch` | Dispatches the indexed-shape effect blit; the skip-translucent mode reports an unsupported-operation error. |
| `0046988c` | `surface_apply_yiq_palette_effect` | Transforms each buffer pixel using palette RGB-to-YIQ values, then releases the temporary palette buffer. |
| `004699fc` | `usecode_runtime_mode_flag_set` | Sets a shared runtime mode byte to one; its higher-level meaning is not yet established. |
| `00469a04` | `usecode_runtime_mode_flag_clear` | Clears the shared runtime mode byte; its higher-level meaning is not yet established. |
| `00469a10` | `usecode_process_create_special_type` | Allocates and initializes a process base object, then installs the derived process vtable at `004804e4`. |
## Address-Ordered Pass: Item Interactions and Selection
| JP address | Ghidra name | Evidence and confidence |
|---|---|---|
| `00469a2c` | `usecode_runtime_flag_set_00495834` | Sets runtime byte `00495834`; called from Usecode opcode dispatch. |
| `00469a34` | `usecode_runtime_flag_clear_00495834` | Clears runtime byte `00495834`; called from Usecode opcode dispatch. |
| `00469a40` | `item_action_advance_shape_entry` | Resets the current item-action shape entry, updates its sprite state, and advances the active entry list. |
| `00469af8` | `input_state_clear_and_reset` | Clears pending input-state fields and invokes the shared input-event reset routine. |
| `00469b18` | `runtime_flag_00482698_is_clear` | Returns whether runtime byte `00482698` is zero; exposed through Usecode opcode dispatch. |
| `00469b28` | `gump_item_shape_is_eligible` | Checks shape/category-specific slot and state constraints before the caller adds an item through its gump flow. |
| `00469d50` | `item_shape_interaction_apply_state` | Dispatches shape-specific interaction logic, updating category-dependent item slots and counters; selected paths also remove an item or refresh its selection state. |
| `0046a5a8` | `item_record_cycle_field_15_slot` | Cycles item-record field 15 through slots 1-5, skipping empty slots, then refreshes the toolbar and related shape state. |
| `0046a714` | `item_record_cycle_field_19_slot` | Cycles item-record field 19 through slots `0x0b`-`0x18`, skipping empty slots, and marks the toolbar slot dirty. |
| `0046a780` | `usecode_runtime_flag_clear_00495837` | Clears runtime byte `00495837`; called from Usecode opcode dispatch. |
| `0046a78c` | `usecode_runtime_flag_get_00495837` | Returns runtime byte `00495837` to Usecode opcode dispatch. |
| `0046a794` | `usecode_runtime_flag_set_00495837` | Sets runtime byte `00495837`; called from Usecode opcode dispatch. |
| `0046a7f4` | `modal_ui_suspend_world_rendering` | Stops audio, disables toolbar updates, suppresses sprite updates, and redraws the pointer for modal UI. |
| `0046a864` | `modal_ui_resume_world_rendering` | Restores sprite and toolbar updates, redraws the pointer, and resets input state after modal UI. |
| `0046a8e4` | `runtime_transition_noop_stub` | Decompiles to an immediate return and is called during runtime transition dispatch; unreachable-block warnings leave its original intent unclear. |
| `0046a940` | `item_shape_filter_gump_create` | Creates linked resource record type `0x11e`, initializes its UI fields and surface-derived bounds, and configures its shape filter. |
| `0046dc44` | `viewport_select_spatial_item_node` | Picks a viewport spatial node at the supplied point; for node type 2, updates item-shape state and clicked coordinates. |
| `0046ddec` | `item_shape_selection_candidates_rebuild` | Scans item IDs below `0x2800`, filters candidates by flags, shape/category, height, and distance, sorts by distance, and updates the active sprite entry. |
| `0046e154` | `item_shape_selection_advance_candidate` | Advances through the current item-shape candidate list while updating the associated sprite-manager entry. |
| `0046e2a0` | `item_shape_selection_clear_candidate` | Clears the current candidate and advances the list, removing the sprite entry when the active list ends. |
## Address-Ordered Pass: Static Overlay and Usecode Values
| JP address | Ghidra name | Evidence and confidence |
|---|---|---|
| `0046e384` | `sprite_manager_remove_shape_entry_if_active` | Calls sprite-manager shape-entry removal only when the global shape-entry index is active. |
| `0046e870` | `static_overlay_process_update` | Advances a static-overlay frame, updates and imports its palette, notifies matching processes, releases the stream, and renders the gump tree; selected modes delegate to a virtual handler. |
| `0046ed00` | `item_shape_selection_get_current_head` | Returns the first pointer-sized field from the supplied selection-list object; used as the initial candidate by the item-action path. |
| `0046ed3c` | `weapon_cache_load_records_for_type` | Loads the selected weapon-cache type from the static indexed resource, allocating cache buffers and reading records marked for caching. |
| `0046efb4` | `weapon_cache_get_shape_render_metadata` | Looks up cached shape render metadata and fills the caller's dimensions/offset outputs; reloads the cache when the active type changes and returns zeroed outputs for unsupported or absent entries. |
| `0046f0b0` | `weapon_cache_has_shape_records` | Ensures the selected weapon-cache type is loaded, then reports whether the requested shape slot has cached records. |
| `0046f0d4` | `weapon_cache_get_type_shape_value` | Finds the selected type in the weapon-cache table and returns its associated 16-bit shape value. |
| `0046f160` | `usecode_value_heap_initialize` | Allocates the Usecode value heap backing storage and installs its initial free-block metadata. |
| `0046f200` | `usecode_value_heap_shutdown` | Releases the backing storage for the Usecode value heap and clears its global base pointer. |
| `0046f220` | `usecode_value_heap_copy_string` | Allocates space in the Usecode value heap for a NUL-terminated string, copies it, and returns its heap offset. |
| `0046f274` | `usecode_value_heap_allocate` | Allocates a block from the Usecode value heap, splitting a larger free block when enough space remains. |
| `0046f394` | `usecode_value_heap_free_owner_values` | Releases Usecode heap values associated with the supplied owner ID by passing each matching allocation to `Usecode_FreeVal`. |
| `0046f3e8` | `Usecode_FreeVal` | Releases an allocated Usecode heap value and coalesces adjacent free blocks. |
| `0046f4d4` | `usecode_value_heap_reset` | Resets the Usecode value heap by replacing its backing allocation and restoring the empty-list sentinel. |
| `0046f588` | `Usecode_FreeList` | Traverses a Usecode value list and frees each value, including nested payload values when the list flag is set. |
| `0046f608` | `usecode_value_list_copy` | Copies a Usecode value list and duplicates each element's inline or string payload into the destination list. |
| `0046f79c` | `usecode_value_list_get_element` | Returns a pointer to the requested element's payload in a Usecode value list, or zero when the index is out of range. |
| `0046f850` | `usecode_value_list_append` | Appends a value offset to the end of a Usecode value list. |
| `0046f8c4` | `usecode_value_list_insert_sorted` | Inserts a value into a Usecode list in sorted order, comparing strings or value data according to the list type. |
| `0046faf0` | `usecode_value_list_remove_value` | Removes matching values from a Usecode list and releases their payload and heap allocations. |
Caller and decompiler readbacks confirmed the static indexed weapon-cache path, its viewport-bound metadata lookups, and Usecode heap/list operations used by opcode processing and runtime reset. All 20 entries have exact-address table rows and decompiler comments. Ghidra changes remain pending; no executable bytes were changed and the project was not saved.
Caller and decompiler readbacks confirmed Usecode list membership/replacement helpers, the modal item-shape selection gump and event handler, selection limits and costs, and the indexed-shape row decoder variants used by the surface blitters. All 20 entries have exact-address table rows and decompiler comments. Ghidra changes remain pending; no executable bytes were changed and the project was not saved.
## Address-Ordered Pass: Usecode Lists and Item-Shape Selection
| JP address | Ghidra name | Evidence and confidence |
|---|---|---|
| `0046fc84` | `usecode_value_list_contains_value` | Searches a Usecode value list for a matching value; string lists compare referenced strings, while other entries compare the stored value bytes. |
| `0046fd58` | `usecode_value_list_replace_element` | Replaces the zero-based list element with the supplied value, freeing the old string payload when applicable; returns zero if the index is out of range. |
| `0046fe18` | `usecode_value_list_set_heap_metadata` | Writes the supplied 16-bit value to the allocator header immediately before each list element and, for string lists, each referenced string block; header semantics are unresolved. |
| `0046fed0` | `item_shape_selection_show_modal` | Creates the item-shape selection gump when resource allocation succeeds, runs the event loop until it exits, invokes a virtual completion callback, and toggles the transition flag. |
| `0046ff30` | `item_shape_selection_gump_create` | Builds the item-shape selection gump and indexed-resource child controls, positions them relative to the screen, loads the requested record, queues setup, sets allowed shape IDs, and suspends modal world rendering. |
| `00470400` | `item_shape_gump_initialize_tag_groups_a` | Finds child controls with tags 2 through 8 and extends their state flags, adjusts the scale fields for tags 1 and 0, then renders the gump tree. |
| `004704b0` | `item_shape_gump_initialize_tag_groups_b` | Finds child controls with tags 1 and 0 and extends their state flags, adjusts scale fields for tags 2 through 7, renders the gump tree, and clears a state byte. |
| `00470994` | `item_shape_selection_load_record_by_index` | Loads the indexed fixed-size 0x142-byte selection record, clears type-specific fields for lower record classes, and advances the current cursor past entries with zero shape IDs. |
| `00470b50` | `flic_play_random_transition` | When the transition guard is clear, chooses a random FLIC path, runs it with the selected AVI profile, restores the palette and display region, and redraws the pointer. |
| `00470ee4` | `item_shape_selection_handle_input_action` | Dispatches item-shape selection UI actions 0 through 8, updating the current record and selection, handling navigation, and queuing follow-up events. |
| `0047155c` | `item_shape_selection_check_add_limit` | Counts existing selections of the requested shape, includes its item-slot/state cost when present, and checks the resulting count against a shape-class-specific limit. |
| `00471640` | `item_shape_selection_try_add_current` | Attempts to add the current shape to the selection: checks the remaining budget and gump eligibility, applies the per-shape limit, updates selection state, and removes the temporary item. |
| `00471748` | `item_shape_selection_clear_selected` | Clears selected shape state by restoring each selected item, refreshes the special shape 0x4ed state when present, then resets the selected count. |
| `00471914` | `item_shape_get_selection_cost` | Maps a shape record's class to a small selection-cost/category value; observed results include 3, 4, and 5, with 0 for unhandled classes. |
| `00471a44` | `surface_blit_indexed_shape_decode_rows` | Decodes one indexed-shape row stream into the destination surface using the supplied source and destination strides. |
| `00471aa2` | `surface_blit_indexed_shape_decode_rle_rows` | Decodes an indexed-shape row stream with literal and repeated-run forms into the destination surface. |
| `00471b27` | `surface_blit_indexed_shape_decode_rows_flipped` | Decodes an indexed-shape row stream into a horizontally reversed destination, as used by the flipped indexed-shape blitter. |
| `00471b8d` | `surface_blit_indexed_shape_decode_rle_rows_flipped` | Decodes an indexed-shape row stream with literal and repeated-run forms into a horizontally reversed destination. |
| `00471c20` | `surface_blit_indexed_shape_decode_rows_mapped` | Decodes indexed-shape rows into the destination while applying the supplied two-stage palette mapping to each output pixel. |
| `00471c99` | `surface_blit_indexed_shape_decode_rle_rows_mapped` | Decodes indexed-shape rows with literal and repeated-run forms while applying the supplied two-stage palette mapping to each output pixel. |
Caller and helper decompilations confirmed pixel-effect row decoding, resource-object cleanup, deferred tracked-resource callbacks, allocation retries, configuration parsing, and x87 range-reduction loops. All 20 entries have exact-address table rows and decompiler comments. Ghidra changes remain pending; no executable bytes were changed and the project was not saved.
## Address-Ordered Pass: Pixel Effects, Resource Memory, and Config Helpers
| JP address | Ghidra name | Evidence and confidence |
|---|---|---|
| `00471d49` | `surface_blit_indexed_shape_decode_rows_pixel_effect` | Decodes indexed-shape rows and applies the supplied pixel-effect lookup to each destination pixel. |
| `00471db9` | `surface_blit_indexed_shape_decode_rle_rows_pixel_effect` | Decodes indexed-shape rows with literal and repeated-run forms, applying the supplied pixel-effect lookup to each destination pixel. |
| `00471ea4` | `resource_object_release_owned_allocation` | Releases the allocation associated with a non-null resource-object data pointer through the shared resource cleanup path. |
| `00471ec4` | `tracked_resource_release_thunk` | Thunk entry used by resource-object cleanup paths to reach `tracked_resource_release`. |
| `00471ec9` | `random_seed_get_pointer` | Returns the random-generator state pointer from a virtual method's state field. |
| `00471ed3` | `random_next_15bit` | Advances the generator state with the observed 0x41c64e6d/0x3039 recurrence and returns bits 16 through 30. |
| `00471f20` | `memory_fill_byte_value` | Fills the destination with the supplied byte value by replicating it across a word-sized fill operation. |
| `00471f38` | `tracked_resource_process_deferred_queue` | Drains the global deferred resource-callback queue, invokes each saved callback record, and unlinks the processed entry. |
| `00471fc0` | `tracked_resource_release` | Releases a tracked-resource allocation, updates the owning range metadata, and invokes the resource object's cleanup callbacks. |
| `00471fcc` | `tracked_resource_allocate_wait_thunk` | Thunk entry to the tracked-resource allocation retry routine. |
| `00471fd4` | `tracked_resource_allocate_with_retries` | Retries tracked-resource allocation, servicing configured frame-skip and callback hooks between attempts; a zero requested size is promoted to one. |
| `00472000` | `tracked_resource_allocate_retry_worker` | Allocation retry continuation that pumps the configured callbacks and frame-skip hook until allocation succeeds or no callback remains. |
| `00472033` | `string_format_into_buffer` | Formats the supplied text into the destination buffer through the shared output callback, then writes a terminating NUL. |
| `00472050` | `string_compare_lexicographic` | Compares two NUL-terminated strings lexicographically and returns zero on equality, otherwise a signed ordering result. |
| `0047211e` | `config_parse_value_using_pattern` | Parses the supplied configuration text with a fixed format pattern through the shared formatted-input parser. |
| `00472145` | `config_parse_value_string_method` | Configuration-value method wrapper that forwards its input string to `config_parse_value_using_pattern`. |
| `00472166` | `string_lowercase_ascii` | Converts ASCII uppercase letters in the NUL-terminated input string to lowercase in place. |
| `0047218c` | `float80_return_passthrough` | Returns the supplied extended-precision floating-point value unchanged through the hidden return-storage pointer. |
| `004721aa` | `x87_cosine_reduce_argument` | Executes x87 FCOS and repeats while the FPU range-reduction status bit remains set. |
| `004721b4` | `x87_sine_reduce_argument` | Executes x87 FSIN and repeats while the FPU range-reduction status bit remains set. |
Caller and decompiler/disassembly readbacks confirmed Usecode flag dispatch, input reset, modal UI suspend/resume, gump item eligibility, shape-specific item updates, viewport node selection, and distance-ordered item-shape candidates. All 20 entries have descriptive names and decompiler comments. Ghidra changes remain pending; no executable bytes were changed and the project was not saved.
Caller and decompiler readbacks confirmed opcode dispatch, Japanese command-line parsing, override-stream operations, savegame/runtime reset, item-event process creation, resource-cache lifecycle, bitmap-buffer cleanup, clipped drawing, and indexed-shape rendering. The latest 60 entries are documented at exact function-entry addresses with descriptive names and comments. Ghidra changes remain pending; no executable bytes were changed and the project was not saved.
## Address-Ordered Pass: Timed Processes, String Tables, and Item Selection
## Address-Ordered Pass: Path, Heap, and File Runtime Helpers
| JP address | Ghidra name | Evidence and confidence |
|---|---|---|
| `004721be` | `x87_wait_until_not_busy` | Polls x87 status bit 10 until clear, then returns the status word with AX. |
| `00472224` | `ascii_uppercase_char` | Converts one ASCII lowercase letter to uppercase; leaves other byte values unchanged. |
| `00472234` | `array_construct_elements_with_callback` | Initializes array-allocation metadata and invokes the element constructor callback once per requested element. |
| `0047227c` | `string_copy_dbcs_bounded` | Copies a bounded string/path component with DBCS-aware length handling and a terminating NUL. |
| `004722b2` | `path_split_drive_and_components` | Extracts an optional drive prefix and scans path separators and extension dots while respecting DBCS pairs. |
| `0047238b` | `string_find_last_character` | Scans through the string terminator and returns the last matching byte, or null when absent. |
| `004723a5` | `string_copy_with_zero_padding` | Copies up to the destination capacity and zero-fills the unused remainder. |
| `004723ef` | `uint_to_string_radix` | Converts an unsigned value to digits in a radix through 36 and writes them in forward order. |
| `00472439` | `int_to_string_radix` | Formats a signed value in the requested radix, adding a minus sign for negative base-10 values. |
| `00472454` | `memory_move_bytes` | Moves a byte range and copies backward when the higher-address destination overlaps the source. |
| `004724a1` | `heap_free_block_and_coalesce` | Selects the containing heap under lock, frees/coalesces the block, and refreshes cached free-block sizes. |
| `00472542` | `string_vformat_into_buffer` | Runs the custom varargs formatter through a buffer-writing callback and null-terminates the produced text. |
| `00472572` | `runtime_noop_callback` | Empty callback reached by the process-exit dispatch sequence. |
| `00472573` | `win32_process_exit_with_cleanup` | Runs configured shutdown callbacks and transfers control to the termination routine. |
| `0047258b` | `win32_process_exit_terminate` | Runs termination hooks and runtime cleanup, then exits through `ExitProcess`. |
| `004725b0` | `file_parse_open_mode_flags` | Parses `r`, `w`, or `a` mode strings and optional `+`, `b`, or `t` modifiers into access flags. |
| `00472681` | `file_object_open_with_mode_flags` | Opens the backing file using parsed flags and initializes or cleans up file-object state. |
| `00472745` | `file_object_open_with_mode_string` | Parses the mode string, obtains or reuses a file object, and opens the requested path. |
| `0047277e` | `file_object_open_mode_thunk` | Forwarding wrapper to the file-object mode-string opener. |
| `0047286a` | `file_stream_vformat_thunk` | Thunk to the formatted file-stream writer at `004755d9`. |
| `0047286f` | `resource_list_find_and_release_by_key` | Searches the global resource list by key, releases a matching entry, and returns -1 when no key matches. |
| `004728ae` | `resource_list_release_and_relink_entry` | Releases the matched resource object's state, then unlinks and relinks its list entry through the shared list helper. |
| `004728c3` | `hex_digit_to_lowercase_ascii` | Maps a hexadecimal nibble to its lowercase ASCII digit. |
| `004728cf` | `temporary_filename_build` | Builds a process-specific temporary filename in the observed `t..._....tmp` form. |
| `00472934` | `resource_object_release_owned_state` | Releases resource-object buffers and handles according to state flags, clears freed storage, and unregisters its runtime handle. |
| `00472a60` | `x87_log2_positive_input` | Computes x87 log2 for positive input; nonpositive or NaN input goes through the runtime domain-error helper. |
| `00472aa1` | `x87_log2_positive_input_thunk` | Forwarding thunk to the checked x87 log2 routine. |
| `00472ac1` | `audio_timing_log2_wrapper` | Audio timing callers forward an extended-precision value through the checked log2 routine. |
| `00472acd` | `string_uppercase_ascii` | Converts ASCII lowercase letters to uppercase in the input string in place. |
| `00472af2` | `string_to_signed_decimal` | Skips classified whitespace, accepts an optional sign, and accumulates decimal digits into a signed integer. |
| `00472b5f` | `local_time_to_timestamp` | Reads local calendar time, converts the populated time record to a timestamp, and stores an auxiliary result when requested. |
| `00472b8e` | `string_compare_case_insensitive_ascii` | Compares two NUL-terminated strings lexicographically after folding ASCII uppercase letters to lowercase. |
| `00472bd8` | `win32_runtime_fatal_error` | Triggers a debugger break when configured; otherwise writes the message, runs cleanup hooks, and exits with the supplied code. |
| `00472bf8` | `runtime_event_execute_nested_frame` | Pushes a temporary event/runtime frame, invokes the event interpreter, then restores the prior frame. |
| `00472c31` | `win32_runtime_get_current_thread_context` | Returns the current thread's runtime-context pointer captured during Win32 process initialization. |
| `00472c36` | `win32_process_exit_noop_callback` | Empty callback used by the process-exit dispatch path. |
| `00472c37` | `win32_handle_table_register_thunk` | Registers a Win32 handle in the runtime handle table and returns its slot index. |
| `00472c3c` | `win32_handle_table_unregister_thunk` | Clears a runtime handle-table slot by index. |
| `00472c41` | `win32_runtime_capture_process_context` | Captures environment strings, module path, command line, and GetVersion fields, then initializes per-thread runtime context. |
| `00472d68` | `win32_runtime_startup_initialize` | Captures process context, establishes exception-chain metadata, runs a startup callback, and invokes final runtime initialization. |
| `00472dd0` | `memory_fill_bytes` | Fills a byte range with a repeated byte value, handling destination alignment, dword stores, and trailing bytes. |
| `00472e07` | `memory_fill_dwords` | Writes a repeated 32-bit value using alignment handling and unrolled dword stores. |
| `00472e74` | `runtime_event_resolve_next_record` | Resolves the next runtime event record, follows conditional records, and routes invalid record types through the error path. |
| `00472ebe` | `runtime_event_call_if_flag_clear` | Tests event-state flags against a mask and invokes the record callback only when those bits are clear. |
| `00472f08` | `runtime_event_interpreter_execute` | Interprets runtime event records, dispatching callbacks and control records, including conditional flow and nested frames. |
| `00473038` | `runtime_event_interpreter_thunk` | Thunk forwarding to the event interpreter with the current register-provided context. |
| `00473042` | `runtime_event_run_global_sequence` | Runs the event interpreter against the global runtime sequence at `00495c80`. |
| `00473067` | `runtime_heap_allocate_with_retry` | Scans runtime heap regions and retries allocation after requesting additional storage; returns null when no region can satisfy the request. |
| `00473156` | `string_vformat_emit` | Custom variadic formatter that emits literal characters and converted arguments through an output callback. |
| `004734f5` | `format_spec_parse_width_precision` | Parses field width, optional precision, and length modifiers; width and precision may be supplied as arguments. |
| `00473633` | `format_spec_parse_flags` | Parses the `-`, `#`, `+`, space, and `0` conversion flags. |
| `00473692` | `format_count_narrow_string_limited` | Counts narrow-string characters up to NUL or the active field-width limit. |
| `004736b6` | `format_count_wide_string_limited` | Counts 16-bit string characters up to NUL or the active field-width limit. |
| `004736d9` | `format_integer_zero_padded_width` | Formats an integer in decimal and fills leading positions with zeroes to meet the requested width. |
| `00473737` | `format_fixed_point_decimal` | Formats a signed fixed-point value with the requested decimal precision and rounds the final fractional digit. |
| `0047382c` | `format_emit_character_callback` | Emits one character through the configured formatter output callback. |
| `00473833` | `format_emit_argument_conversion` | Fetches conversion arguments, applies parsed width/precision and flags, and dispatches supported conversions. |
| `00473d1c` | `string_copy_uppercase_ascii` | Copies a NUL-terminated string while converting each ASCII character to uppercase. |
| `00473d34` | `input_callback_read_character` | Invokes the input-stream callback at offset zero to fetch the next character. |
| `00473d3b` | `input_callback_unread_character` | Invokes the input-stream callback at offset four to return or unread the current character. |
| `00473d43` | `input_vformat_scan` | Shared callback-backed scanf-style parser; matches literals and whitespace, parses conversion specifications, and dispatches input conversions. |
| `00473f8a` | `input_scan_spec_parse` | Parses assignment suppression, field width, allocation and length flags, and the conversion length modifier. |
| `0047407f` | `input_scan_skip_whitespace` | Consumes classified whitespace through the input callback, leaving the first non-whitespace character unread. |
| `004740be` | `input_scan_read_character_field` | Reads a bounded character field and stores byte or wide-character values when assignment is enabled. |
| `00474153` | `input_scan_read_string_field` | Reads a width-limited string field until whitespace or input exhaustion and terminates an assigned result. |
| `00474276` | `input_scan_store_consumed_count` | Stores the number of input characters consumed through the next variadic destination. |
| `004742d4` | `input_scan_build_character_class_bitmap` | Builds a character-membership bitmap from the conversion class up to its closing bracket. |
| `00474317` | `input_scan_read_character_class` | Reads a bounded character-class field, supports initial negation, and NUL-terminates an assigned result. |
| `00474411` | `input_scan_read_float_field` | Collects a bounded signed decimal/fraction/exponent token, converts it, and stores the result using the requested width. |
| `00474728` | `input_scan_read_integer_field` | Parses a signed integer field, recognizes radix prefixes where applicable, and stores the result at the requested width. |
| `00474918` | `ascii_digit_to_hex_value` | Converts an ASCII decimal or hexadecimal digit to its value; returns 16 for bytes outside those ranges. |
| `0047493f` | `input_callback_read_with_width` | Reads one callback character while decrementing field width; returns -1 when width is exhausted or input ends. |
| `00474af1` | `runtime_context_frame_push` | Initializes a temporary runtime frame from the current context and invokes the frame setup helper. |
| `00474b21` | `dbcs_adjust_offset_to_character_boundary` | Adjusts a byte offset to a DBCS character boundary by walking character starts up to the requested address. |
| `00474b5f` | `dbcs_byte_length_for_character_count` | Measures the byte span of up to the requested number of DBCS characters. |
| `00474dee` | `string_copy_dbcs_bounded_dispatch` | Adjusts a bounded source span to a DBCS character boundary, then copies it with zero padding. |
| `00474e0d` | `string_copy_dbcs_with_zero_padding` | Copies with zero padding; in DBCS mode it preserves character pairs and avoids ending on a lead byte. |
| `00474ec1` | `dbcs_read_character` | Reads one string character as a byte or a two-byte DBCS value when the first byte is a lead byte. |
| `00474f7e` | `heap_region_allocate_block` | Finds a suitably aligned free block, splits it when possible, and updates runtime heap metadata. |
| `00475026` | `heap_region_free_block_and_coalesce` | Returns a block to the runtime heap, coalesces adjacent free blocks, and updates free-list counters. |
| `00475131` | `ascii_lowercase_char` | Converts one ASCII uppercase letter to lowercase; disassembly confirms the operation where decompiler output is empty. |
| `0047513f` | `runtime_context_set_error_code_0d` | Stores fixed runtime error code `0x0d` in the current thread context; higher-level meaning is unresolved. |
| `00475144` | `runtime_context_set_error_code` | Stores the supplied runtime error code at offset `+4` in the current thread context. |
| `00475152` | `runtime_context_set_error_code_0e` | Stores fixed runtime error code `0x0e` through the shared context setter. |
| `00475169` | `runtime_context_set_aux_error_value` | Stores the supplied auxiliary error value at offset `+8` in the current thread context. |
| `0047519b` | `win32_file_open_with_mode_flags` | Opens through `CreateFileA`, registers the resulting handle, and returns its runtime handle-table index. |
| `00475352` | `file_object_allocate_and_link` | Allocates and initializes a runtime file/object record, then links it into the active list. |
| `0047540a` | `runtime_object_release_to_free_pool` | Removes a matching runtime object from the active list, marks it released, and links it into the free pool. |
| `00475461` | `file_stream_update_buffer_cursor` | Repositions the buffered cursor when the offset is in range; otherwise resets it and signals an OS seek. |
| `004754a3` | `file_stream_seek` | Reconciles buffered state or flushes output before `SetFilePointer`; returns a failure sentinel on error. |
| `00475597` | `file_stream_initialize_mode_state` | Initializes file-stream state from its runtime descriptor and applies the observed mode-flag updates. |
| `004755d9` | `file_stream_vformat_write` | Formats variadic output through the stream callback, flushes when required, and restores status bits. |
| `0047566a` | `win32_get_current_process_id` | Wrapper for `GetCurrentProcessId`. |
| `00475674` | `file_stream_flush_buffer` | Writes pending stream data to the backing file, updates buffer state, and marks errors. |
| `0047575e` | `file_stream_get_position` | Gets the backing file position and adjusts it for buffered read/write offsets. |
| `004757af` | `win32_file_set_pointer` | Calls `SetFilePointer` for a registered handle and records the runtime error on failure. |
| `004757e9` | `win32_file_close_handle` | Closes a registered Win32 handle through the configured path and clears its runtime handle entry. |
| `00475858` | `win32_delete_file_a_thunk` | Calls `DeleteFileA` and records the Win32 error when deletion fails. |
| `0047594e` | `runtime_math_domain_error_dispatch` | Argument-forwarding wrapper to the math-error path, called by the checked x87 log2 routine. |
| `0047598a` | `local_time_record_read_system_time` | Reads `GetLocalTime` into the runtime calendar record and returns milliseconds. |
| `004759ef` | `local_time_record_to_timestamp` | Normalizes calendar fields, accounts for leap days and runtime timezone adjustments, and returns a timestamp or -1. |
| `00475b43` | `runtime_debug_break_if_enabled` | Executes an INT 3 breakpoint when the runtime debug-break flag is enabled; otherwise returns zero. |
| `00475b69` | `runtime_fatal_write_message_and_exit` | Writes the fatal message to the error-output handle, performs exception cleanup, and terminates the process. |
| `00475ba0` | `runtime_fatal_error_dispatch` | Attempts the configured debug break and otherwise routes to fatal output and process termination. |
| `00475be1` | `runtime_exception_dispatch_result_check` | Returns false for signal-dispatch status values 2 or 3 and true for other results. |
| `00475c16` | `runtime_exception_slots_are_idle` | Tests two thread-context exception status fields for values other than 2 and 3. |
| `00475c81` | `runtime_console_ctrl_handler_unregister` | Unregisters the installed console control handler and reports whether it is inactive. |
| `00475cbd` | `runtime_control_signal_dispatch` | Dispatches a control signal through the current thread's handler table and updates runtime state. |
| `00475cf6` | `runtime_thread_signal_handler_invoke` | Invokes the current thread's signal handler unless its slot contains a default/special sentinel. |
| `00475e22` | `runtime_thread_signal_table_initialize` | Copies global default signal-handler entries into the current thread's runtime context table. |
| `00475e4f` | `runtime_default_signal_handler_noop` | Empty default callback used as a runtime signal-handler target. |
| `00476220` | `win32_exception_handler_install` | Links a stack-based structured-exception frame into FS:[0] and assigns the runtime handler. |
| `0047625e` | `win32_exception_handler_remove` | Restores the prior FS:[0] frame, clears the context pointer, and resets idle signal/control state. |
| `004762ad` | `win32_handle_table_is_full` | Checks the registered-handle table capacity and searches for an empty slot. |
| `004762f2` | `win32_handle_table_register` | Registers a Win32 handle, expands the table when needed, and returns its slot index. |
| `00476407` | `win32_handle_table_unregister` | Clears an in-range handle-table slot. |
| `00476433` | `win32_standard_handle_table_initialize` | Initializes the handle table and registers standard input, output, and error handles. |
| `0047646a` | `win32_custom_handle_next_id` | Increments and returns the identifier used by the custom Win32 handle path. |
| `0047647d` | `win32_file_state_close_handles` | Closes the stored Win32 handle when present and clears associated object fields. |
| `00476530` | `runtime_recursive_mutex_acquire` | Lazily creates and acquires the mutex, records its owner thread, and increments the recursive lock count. |
| `00476592` | `runtime_recursive_mutex_release` | Decrements the recursive mutex count and releases the Win32 mutex when it reaches zero. |
| `004765d7` | `win32_runtime_thread_context_create` | Creates or initializes the current thread runtime context and records the current thread ID. |
| `00476616` | `win32_tls_alloc_with_win9x_guard` | Allocates a TLS index and, on Win9x, retries indices below 3 to avoid reserved slots. |
| `00476662` | `win32_runtime_thread_context_create_and_set_tls` | Creates and validates the current thread context, then stores it in the allocated TLS slot. |
| `004766af` | `win32_runtime_thread_context_destroy_current` | Releases the current thread's TLS context and optionally closes its associated Win32 handle. |
| `00476726` | `win32_runtime_support_initialize` | Initializes runtime callback pointers, the mutex, initial thread context, and context accessor. |
| `004768aa` | `runtime_strdup_with_retry` | Allocates space through the runtime heap retry helper and copies a string including its terminator. |
| `004768f0` | `runtime_startup_callback_dispatch` | Invokes pending startup callbacks by priority and marks each table entry complete. |
| `0047693b` | `runtime_process_exit_callback_dispatch` | Invokes eligible process-exit callbacks in priority order and marks each entry complete. |
| `0047698c` | `runtime_event_record_resolve` | Resolves runtime event-record size/position through a dispatch entry selected by record type. |
| `004769ba` | `runtime_event_cursor_initialize` | Initializes an event cursor from the supplied record/source and calls its type-specific setup routine. |
| `004769db` | `runtime_event_cursor_retreat` | Moves the runtime event cursor backward by one record-unit step. |
| `004769e0` | `runtime_event_cursor_find_predecessor` | Walks backward through event records, follows conditional branches, and returns a matching predecessor. |
| `00476a65` | `runtime_event_cursor_find_next_record` | Advances through event records, follows conditional branches, and routes unsupported types to the fatal path. |
| `00476af8` | `runtime_event_mark_frame_complete` | Marks the current event frame complete, sets its flag, and invokes its cleanup callback. |
| `00476b0f` | `runtime_event_stack_corruption_fatal` | Sets the stack-corruption diagnostic and enters the runtime event fatal-error path. |
| `00476be3` | `runtime_function_exception_specification_violation` | Sets the exception-specification violation diagnostic, dispatches a handler if present, then enters the fatal path. |
| `00476c1f` | `runtime_event_record_get_payload` | Returns the current event payload, skipping its leading tag byte for the tagged form. |
| `00476cd0` | `runtime_exception_event_action_interpret` | Interprets encoded exception/event actions, updates the active frame, and uses `RtlUnwind` as needed. |
| `0047738c` | `runtime_virtual_region_register` | Inserts a virtual region into an address-sorted doubly linked list and initializes its metadata. |
| `00477400` | `runtime_virtual_region_allocate` | Allocates and registers a page-backed virtual region, then initializes its metadata. |
| `00477490` | `runtime_heap_virtual_region_fallback` | Computes a rounded region size and attempts VirtualAlloc as a fallback for runtime heap allocation. |
| `004774a1` | `runtime_virtual_region_round_size` | Rounds a requested region size for metadata overhead, configured minimums, and page allocation. |
| `004774eb` | `runtime_allocation_failure_return_zero` | Returns zero as the allocation-failure fallback callback. |
| `004774ee` | `runtime_fatal_error_callback` | Forwards the runtime error state to the fatal-error dispatcher. |
| `00477525` | `runtime_uint_to_base_string` | Formats an unsigned integer as a NUL-terminated string in the selected radix. |
| `0047756f` | `runtime_signed_int_to_base_string` | Adds a minus sign for negative decimal values, then formats the integer in the selected radix. |
| `0047758a` | `runtime_decimal_to_float32_bits` | Converts the parsed decimal mantissa/exponent representation to IEEE-754 single-precision bits. |
| `004777d0` | `runtime_event_record_get_length` | Returns the payload length for an encoded event-record tag, routing invalid tags to the fatal path. |
| `00477814` | `runtime_context_exception_frame_link` | Links a runtime exception/context frame into the global frame chain and returns runtime state. |
| `0047783a` | `dbcs_decode_next_character` | Decodes the next character through the active multibyte lead-byte table and advances one or two bytes. |
| `0047793f` | `dbcs_previous_character_boundary` | Finds the previous character boundary, accounting for multibyte lead/trail-byte pairs. |
| `00477a31` | `win32_open_mode_to_access_flags` | Maps runtime open modes to Win32 generic read/write access and the associated share-mode value. |
| `00477a5d` | `win32_open_mode_to_creation_disposition` | Maps runtime open/create mode bits to the CreateFile creation-disposition value. |
| `00477a97` | `win32_last_error_set_runtime_status` | Stores a Win32 error in runtime context and maps it to a runtime error code. |
| `00477ae8` | `win32_last_error_to_runtime_status` | Reads GetLastError and forwards it to the runtime error-code mapping helper. |
| `00477af7` | `win32_handle_is_character_device` | Tests whether a registered Win32 handle is FILE_TYPE_CHAR and releases temporary handle access. |
| `00477b38` | `win32_handle_table_get` | Retrieves a registered handle and lazily records character-device state for standard handles. |
| `00477b8d` | `win32_handle_table_set_flags` | Updates the registered handle entry's runtime mode/status flags. |
| `00477ba2` | `win32_file_get_current_position` | Queries the file position with SetFilePointer(FILE_CURRENT) and records errors on failure. |
| `00477cbf` | `file_stream_write_character` | Writes one character to a buffered stream, handles newline translation, and flushes when stream flags or buffer capacity require it. |
| `00477d82` | `file_stream_initialize_buffer` | Selects a buffer size from stream mode flags and allocates or configures the stream buffer. |
| `00477df9` | `win32_file_write_buffer` | Writes pending bytes to a Win32 file handle, handles append mode, and maps short writes or API failures to runtime status. |
| `00477e9f` | `file_stream_flush_buffered_data` | Flushes buffered output or synchronizes the file position, then resets stream pointers and records errors. |
| `00477eaf` | `win32_delete_file_a` | Calls DeleteFileA and translates a Win32 failure into runtime error status. |
| `00477edd` | `runtime_thread_stack_update_and_measure` | Reads current-thread stack bounds, updates the tracked boundary when needed, and returns a stack-distance value. |
| `00477f0c` | `runtime_heap_initialize_region_size` | Sets the runtime region-size global to `0x8000` during startup. |
| `00477f18` | `runtime_math_fpu_control_dispatch` | Forwards a math/FPU control request to the floating-point status dispatcher. |
| `00477f22` | `runtime_fpu_apply_control_flags` | Maps floating-point exception/control bits to runtime categories and dispatches the resulting math status. |
| `00477ffd` | `runtime_is_leap_year` | Applies the Gregorian 4/100/400-year rule and returns whether the supplied year is a leap year. |
| `00478038` | `runtime_timezone_rule_day_of_year` | Converts a timezone transition-rule record to a zero-based day-of-year position, accounting for leap years and rule format. |
| `0047811d` | `runtime_timezone_transition_rule_compare` | Orders transition rules by year and then by their computed day-of-year positions. |
| `00478151` | `runtime_timezone_daylight_rule_active` | Tests a calendar record against the configured daylight-transition interval and stores the active-state result. |
| `00478414` | `runtime_calendar_fields_compare` | Compares calendar fields lexicographically in year, month, then day order. |
| `00478444` | `timestamp_to_calendar_record` | Applies a seconds offset to a timestamp and fills the calendar record's time, date, weekday, and year fields. |
| `004786d8` | `runtime_timezone_initialize` | Initializes timezone names, offsets, and transition rules from the runtime setting or Windows timezone data. |
| `00478721` | `runtime_parse_decimal_component` | Consumes consecutive decimal digits from the input and stores the resulting integer. |
| `00478745` | `runtime_timezone_parse_name_and_offset` | Parses a timezone name and signed hour/minute/second offset, returning the first unconsumed character. |
| `0047886e` | `runtime_timezone_parse_transition_rule` | Parses a POSIX transition rule in Julian-day or month/week/weekday form, including an optional transition time. |
| `00478a46` | `runtime_control_signal_fatal_callback` | Routes the fatal control-signal callback to the runtime fatal-error dispatcher with status `0xff`. |
| `00478b56` | `runtime_heap_reallocate` | Handles null/free cases, attempts an in-place resize, and falls back to allocate-copy-free when the block must move. |
| `00478bd0` | `win32_runtime_thread_context_get_or_create` | Ensures the current thread has a runtime context in TLS, routing initialization failure to the fatal path. |
| `00478c07` | `win32_runtime_thread_context_register_cleanup` | Allocates and links cleanup metadata for a newly created thread context, retaining its pointer and cleanup flag. |
| `00478c68` | `win32_runtime_thread_context_unregister_cleanup` | Removes the current thread context's cleanup record and releases its optional owned allocation. |
| `00478cdb` | `runtime_heap_allocate_zeroed` | Allocates the requested runtime heap size and zero-fills it when allocation succeeds. |
| `00478cf8` | `runtime_event_cursor_test_record_flag` | Tests an indexed event-record flag using the runtime bit-mask table. |
| `00478d18` | `runtime_unhandled_exception_handler_thunk` | Thunk to the unhandled-exception path, which invokes a configured handler or performs fatal cleanup and exits. |
| `00478ff0` | `runtime_noop_callback` | Empty callback that returns without changing state. |
| `00479012` | `runtime_heap_reclaim_matching_virtual_regions` | Scans virtual-region metadata and releases matching region records before another virtual allocation. |
| `00479026` | `runtime_virtual_region_release_memory` | Calls VirtualFree and updates allocator globals and stale path metadata after successful release. |
| `00479084` | `runtime_virtual_region_release_record` | Releases a region's memory, then unlinks its record from the allocator's doubly linked list. |
| `00479681` | `file_stream_flush_matching` | Flushes pending output buffers for registered streams whose mode/status flags match the supplied mask. |
| `004796c7` | `runtime_math_error_format_output` | Formats and emits the runtime math-error diagnostic through configured output callbacks. |
| `0047970f` | `runtime_math_error_dispatch` | Invokes the configured math-error handler or emits the diagnostic and stores the corresponding runtime error code. |
| `0047973e` | `runtime_environment_find_value` | Searches the runtime environment-string table for a named variable and returns the value after `=`. |
| `0047979f` | `runtime_heap_block_get_usable_size` | Returns the usable allocation size recorded in the heap block header, excluding allocator metadata. |
| `004797a8` | `runtime_heap_resize_block_locked` | Acquires the runtime heap lock, resizes a block in place, and releases the lock. |
| `004797e2` | `runtime_heap_resize_block_in_place` | Coalesces following free blocks when growing or splits excess space when shrinking a heap block. |
| `00479980` | `runtime_zero_result_callback` | Returns zero as a no-op/default result callback. |
| `0047998a` | `runtime_configured_callback_dispatch` | Invokes the callback currently stored in the runtime callback slot. |
| `00479991` | `runtime_callback_dispatch_return_value` | Invokes the callback stored in `PTR_runtime_zero_result_callback_0047c648`, returning its value through the call result registers. |
| `004799d8` | `runtime_unhandled_exception_dispatch` | Invokes a configured unhandled-exception handler when present; otherwise removes exception state, runs fatal cleanup, and exits the process. |
| `00479a0d` | `runtime_unhandled_exception_fatal_fallback` | Forwards the no-handler unhandled-exception path to the runtime fatal-error handler. |
| `00479a41` | `runtime_exception_specification_fatal_handler` | Routes an exception-specification violation to the runtime fatal-error handler with status 1. |
| `00479f8e` | `runtime_math_error_default_handler_thunk` | Thunk to the default runtime math-error handler at `0047abab`. |
| `00479f93` | `runtime_math_error_message_by_index` | Returns a 26-byte runtime math-error message record for indices 0-3; larger indices produce null/zero. |
| `00479fb2` | `file_stream_write_c_string` | Writes a NUL-terminated string to a runtime stream, initializing its buffer as needed and flushing when requested. |
| `0047a040` | `string_compare_case_insensitive_ascii` | Compares two strings with ASCII case folding, stopping at a mismatch, NUL, or the supplied length. |
| `0047a213` | `runtime_thread_exit_dispatch` | Dispatches configured thread-exit cleanup, removes exception-handler state, conditionally destroys the runtime thread context, then calls `ExitThread(0)`. |
| `0047a420` | `runtime_extended_float_classify_helper` | Processes extended-precision floating-point fields with exponent/significand checks and runtime tables; exact status-bit meanings remain unresolved. |
| `0047abab` | `runtime_math_error_default_handler` | Default runtime math-error callback; returns zero without side effects. |
| `0047ae48` | `ExitThread` | Win32 import thunk for `ExitThread`. |
| `0047ae4e` | `CreateThread` | Win32 import thunk for `CreateThread`. |
| `0047ae54` | `CreateEventA` | Win32 import thunk for `CreateEventA`. |
| `0047ae5a` | `GetCurrentThread` | Win32 import thunk for `GetCurrentThread`. |
| `0047ae60` | `SetEvent` | Win32 import thunk for `SetEvent`. |
| `0047ae66` | `VirtualFree` | Win32 import thunk for `VirtualFree`. |
| `0047ae6c` | `RtlUnwind` | Win32 import thunk for `RtlUnwind`. |
| `0047ae72` | `GetTimeZoneInformation` | Win32 import thunk for `GetTimeZoneInformation`. |
| `0047ae78` | `DeleteFileA` | Win32 import thunk for `DeleteFileA`. |
| `0047ae7e` | `GetFileType` | Win32 import thunk for `GetFileType`. |
| `0047ae84` | `GetLastError` | Win32 import thunk for `GetLastError`. |
| `0047ae8a` | `VirtualAlloc` | Win32 import thunk for `VirtualAlloc`. |
| `0047ae90` | `TlsFree` | Win32 import thunk for `TlsFree`. |
| `0047ae96` | `TlsSetValue` | Win32 import thunk for `TlsSetValue`. |
| `0047ae9c` | `TlsAlloc` | Win32 import thunk for `TlsAlloc`. |
| `0047aea2` | `TlsGetValue` | Win32 import thunk for `TlsGetValue`. |
| `0047aea8` | `ReleaseMutex` | Win32 import thunk for `ReleaseMutex`. |
| `0047aeae` | `WaitForSingleObject` | Win32 import thunk for `WaitForSingleObject`. |
| `0047aeb4` | `CreateMutexA` | Win32 import thunk for `CreateMutexA`. |
| `0047aeba` | `GetCurrentThreadId` | Win32 import thunk for `GetCurrentThreadId`. |
| `0047aec0` | `GetStdHandle` | Win32 import thunk for `GetStdHandle`. |
| `0047aee4` | `SetConsoleCtrlHandler` | Win32 import thunk for `SetConsoleCtrlHandler`. |
| `0047aeea` | `WriteFile` | Win32 import thunk for `WriteFile`. |
| `0047aef0` | `GetLocalTime` | Win32 import thunk for `GetLocalTime`. |
| `0047aef6` | `CloseHandle` | Win32 import thunk for `CloseHandle`. |
| `0047aefc` | `SetFilePointer` | Win32 import thunk for `SetFilePointer`. |
| `0047af02` | `GetCurrentProcessId` | Win32 import thunk for `GetCurrentProcessId`. |
| `0047af08` | `CreateFileA` | Win32 import thunk for `CreateFileA`. |
| `0047af14` | `GetModuleHandleA` | Win32 import thunk for `GetModuleHandleA`. |
| `0047af1a` | `GetVersion` | Win32 import thunk for `GetVersion`. |
| `0047af20` | `GetCommandLineA` | Win32 import thunk for `GetCommandLineA`. |
| `0047af26` | `GetModuleFileNameA` | Win32 import thunk for `GetModuleFileNameA`. |
| `0047af2c` | `GetEnvironmentStrings` | Win32 import thunk for `GetEnvironmentStrings`. |
| `0047af32` | `ExitProcess` | Win32 import thunk for `ExitProcess`. |
| `0047af56` | `WINNLSEnableIME` | Win32 import thunk for `WINNLSEnableIME`. |
| `0047af5c` | `DirectSoundCreate` | DirectSound import thunk for `DirectSoundCreate`. |
| 2026-10-12 | 1,486 / 1,493 (99.5%) | 7 (0.5%) | 336,693 / 499,712 (67.4%) | 399,698 / 499,712 (80.0%) | Added the next 20 report-listed Win32 import thunks from `0047ae7e` through `0047af14`. |
Readbacks confirmed DBCS-aware path/file helpers and heap/exit paths in the first slice, resource and Win32 runtime helpers in the second, event interpretation, heap allocation, and custom formatting/input callbacks in the third, scanf-style conversions, DBCS string handling, runtime frames, and heap block management in the fourth, runtime error state, file streams, Win32 file operations, and local-time records in the fifth, timestamp conversion, runtime signal/exception handling, handle-table operations, and mutex acquisition in the sixth, TLS contexts, callback dispatch, event records, exception actions, and virtual-region tracking in the seventh, virtual-region allocation, numeric conversions, DBCS navigation, file-mode mapping, and Win32 handle operations in the eighth, buffered stream output, stack/FPU support, calendar conversion, and POSIX timezone parsing in the ninth, heap reallocation, thread-context cleanup, virtual-region management, environment parsing, and math-error reporting in the tenth, exception dispatch, case-insensitive comparison, floating-point helper logic, and Win32 import thunks in the eleventh, additional Win32 runtime API imports in the twelfth, and final Win32/DirectSound import thunks in the thirteenth. The float helper's exact status-bit meanings remain unresolved. All 247 entries in this section have descriptive names and decompiler comments. Ghidra edits remain pending; executable bytes were not changed and the project was not saved.
| 2026-10-12 | 1,493 / 1,493 (100.0%) | 0 (0.0%) | 336,693 / 499,712 (67.4%) | 399,698 / 499,712 (80.0%) | Added the final 7 report-listed imports from `0047af1a` through `0047af5c`; the exact-entry ledger now covers every executable function. |
## Address-Ordered Pass: Timed Processes, String Tables, and Item Selection
| JP address | Ghidra name | Evidence and confidence |
|---|---|---|
| `004643cc` | `timer_process_accumulate_global_elapsed_ticks` | Updates the global timer object's accumulated elapsed value in 10 ms units and advances its last-sample timestamp. |
| `0046440c` | `timed_item_process_construct` | Constructs process type 10, associates the supplied item number, seeds its elapsed-time fields from the global timer, and initializes process flags. |
| `004644a0` | `timed_item_process_update` | Updates the global timer state, stores the elapsed value on this process, then invokes a timer-state helper. |
| `004646b0` | `string_table_construct` | Initializes the string-table object's vtables, counters, capacity, and entry-index array. |
| `00464840` | `string_table_load_from_stream` | Reads and terminates stream contents, allocates per-entry storage and an index array, then parses string records. Identifiers and record semantics are not fully recovered. |
| `00464b9c` | `string_table_clear_entries` | Frees each allocated entry, then releases the entry array and auxiliary buffer. |
| `00464c14` | `string_table_initialize_entries` | Reinitializes entry and index arrays for the supplied mode/count, initializes index order, and seeds records with the string `INVALID`. |
| `00464d48` | `string_table_write_selected_entries` | Builds an output buffer from selected entries and writes it at offset zero through `file_stream_insert_at_offset`. |
| `00464e60` | `string_table_sort_entries_by_key` | Compares entry strings and sorts by swapping entry pointers and their associated index values. |
| `00465120` | `text_overlay_construct` | Constructs a text-overlay object and uses the DBCS-aware multiline text-width helper to store measured dimensions and flags. |
| `00465300` | `tracked_item_id_set_initialize` | Allocates and zeroes a 100-element 16-bit item-ID array, resetting the tracked count. |
| `0046537c` | `tracked_item_id_set_release` | Frees the tracked-ID array and resets its capacity and count globals. |
| `004653ac` | `tracked_item_id_set_add` | Inserts the incoming ID in the first empty slot when capacity is available and increments the active count. |
| `0046540c` | `tracked_item_id_set_remove` | Finds the incoming ID, clears its slot, and decrements the active count. |
| `00465468` | `tracked_item_find_nearest_in_direction` | Searches tracked items in 8-way or 16-way direction, applies item/shape and overlap filters, and returns the nearest qualifying ID within the observed bound. |
| `004656dc` | `position_state_dispatch_for_nearby_items` | Begins a rectangular item query around the supplied position, filters results, and dispatches the requested position state for qualifying items. |
| `004658b8` | `tracked_item_id_set_save` | Writes tracked-ID capacity, active count, and the 16-bit ID array through the supplied stream object's write method. |
| `004659a0` | `resource_buffer_load` | Allocates a 0x4800-byte working area and initializes/loads resource-backed data through file/resource helpers. The resource's higher-level role remains unresolved. |
| `00465a68` | `resource_buffer_release` | Releases the object's working buffer and resource handle, clearing both fields. |
| `00465b54` | `fixed_record_copy_by_index` | Copies one fixed 9-byte record selected by index from the object's record array to the output buffer. |
Decompiler and disassembly readbacks confirmed the timer, string-table, tracked-ID, spatial-selection, and fixed-record operations. All 20 entries are listed at exact function-entry addresses with descriptive names and decompiler comments. Ghidra changes remain pending; no executable bytes were changed and the project was not saved.
## Verified Batch: Process Startup
| JP address | Ghidra name | Evidence and confidence |
@ -1695,25 +2232,28 @@ The reviewed process helpers now have operation-level names; selector, table, an
Current coverage establishes JP-specific item-state, spatial-search, process-manager lifecycle, Windows keyboard/event behavior, and native Windows startup/window lifecycle, but not a Japanese-versus-Western behavior difference. The process IDs, item record layout, dispatch tables, and function addresses documented here are JP-specific until matched against a verified Western implementation. Existing Japanese executable and platform findings are summarized in [JP Windows 9x investigation](jp-remorse-windows9x-investigation.md); broader JP/Western format and modding boundaries are in [JP Windows modding feasibility](jp-remorse-windows-modding-feasibility.md).
## Semantic-Gap Analysis Checkpoint (2026-10-12)
This is a read-only static pass over the five requested areas. No Ghidra database changes or executable-byte writes were made; the live Ghidra project remains under the user's control.
| Area | Verified findings | Remaining analysis |
|---|---|---|
| Action and process behavior | `item_action_process_dispatch` cases `0`, `4`, `0x21`, `0x39`, and `0x3b` all construct type `0xf0` through `process_0x0f0_construct_for_item`, then install distinct callback tables. Type `0x259` is constructed by `AttackProcess_0040af20`. The direction helper's `0xff` path requires the current item to differ from `DAT_0047b1d6`, a type-`0x259` process with nonzero `+0x64`, shape-bounds overlap, and a successful packed-position query before dispatching selector `0`; it then sets process byte `+0x7d` and updates `+0x4a/+0x49`. | Identify the callback-table methods behind each selector; establish the meanings of `DAT_0047b1d6`, AttackProcess `+0x64`, and process `+0x7d`; confirm the caller-level result contract. |
| Data schemas | The keyed cache has ten rotating key slots and 256 entry pointers per slot. Its 16-bit key is looked up at file offset `key * 4`; descriptor low byte `+4` sets entry count and bit `0x40` at `+7` selects `0x40` versus `0x80` bytes per entry. The pair reader copies two dwords. The main item record stride is `0x79`; its separate 16-byte snapshot record maps X/Y words at `+0/+2`, Z at `+4`, shape at `+5`, packed byte at `+7`, flags at `+8`, an auxiliary word at `+0x0a`, auxiliary bytes at `+0x0c/+0x0d`, and next-item ID at `+0x0e`. | Resolve the cache key/resource and two-dword entry contract, auxiliary item-field and shape-profile flag meanings, and Western-build field correspondences. |
| Animation and spatial queries | AnimationProcess construction sets type `0x230`, vtable `0047e7a8`, and byte `+0x52` to zero; `animation_process_set_flag_52` writes one, and its only xref is the direct call at `00411fcd`, which has no owning function in Ghidra. Sixteen vtable slots were inspected; seven currently target defined functions and nine remain non-function/LAB targets. The spatial grid is indexed as 64 two-byte cells per `0x80`-byte row; selector coordinates advance by `0x200` and are converted with `>> 9`. | Establish the `+0x52` contract and unowned caller boundary; map remaining vtable slots, selector-mode tokens, and 8-way direction-sector encodings. |
| Input and presentation | Joystick polling uses `joyGetPosEx`; configured action IDs `4`-`8` emit `u/g/s/m/e`, action `9` maps directions to `q/w/i/o`, and process byte `+0x62` selects distinct handling paths. Startup opens dialog resource `0x71` only when joystick polling returns a nonzero direction; a zero dialog result aborts startup. The DirectDraw surface helper calls vtable offset `+0x60`, then locks at `+0x64` only on a zero result; that helper has no restore branch. The debug timeline helper has one caller at unowned address `00455bb6`. | Trace joystick configuration and mode semantics, decode resource `0x71` text/button intent, find any surface-restore path, and identify the timeline consumer/fields `+0xeb/+0xef/+0xf3/+0xf7` plus the writer for `DAT_004955e8`. |
| Unclassified bytes and boundaries | The latest report tracks all `1,493 / 1,493` function entries with zero untracked or generated names; function bodies cover `67.4%` and defined instructions cover `80.0%` of the `499,712` executable bytes. The remaining `100,014` bytes outside defined instructions may be data, padding, or unanalyzed code. Both `00411fcd` and `00455bb6` are confirmed code call sites without an owning function; five unmatched table addresses are not function entries. | Classify executable gaps by references and control flow before creating functions; prioritize the two confirmed unowned call sites and keep data/padding distinct from missed code. |
## Next Work
1. Continue at the lowest untracked executable function reported by `tools/jp_executable_documentation_report.py` (`00425b70` at the latest checkpoint), inspecting entries in ascending address order.
2. Determine the keyed-entry cache's 16-bit key domain, descriptor mode/count fields, and two-dword entry schema from the loader and pair-reader without assuming a specific resource class.
3. Map the remaining JP process dispatch behavior around type `0x259`, and reconcile it with the now-verified common and Stand, Surrender, Pace, Guard, and Loiter process types.
4. Recover process flag meanings and the related-process list used by `0043d574`, `0043d640`, and `0043d7a4`; distinguish bit `0x20` at record bytes `+0x59` and `+0x14`, and verify the overlapping `Process_Terminate`/`process_terminate_set_flag_20` boundaries.
5. Recover the AnimationProcess function-pointer table and trace the flag at `+0x52` from its call site near `00411fcd`.
6. Continue `item_shape_dispatch_interaction_rules` through its callers and tables to identify the violence-gated behavior and its relationship to target adjacency.
7. Resolve the violence-gated tables at `0047b074` and `0047b084` used by `00407304`, including their callers and selected effects.
8. After sequential coverage reaches `00440bf4`, resume the deferred subsystem-specific questions below; treat the existing later-address notes as prior evidence, not as a reason to skip the lower-address pass.
9. Compare the 16-byte JP item-state record and item allocation/free lifecycle against the Western build by semantic field mapping.
10. Compare the JP spatial selector record, grid scale, scan modes, and direction-sector encodings against the Western build by behavior and data role.
11. Resolve the configured joystick action IDs and mode bit; identify the startup dialog's prompt/response and the DirectDraw recovery transitions.
12. Once the JP NPC, animation, and joystick paths are mapped, inspect corresponding Western process behavior in its own active Ghidra target and document only verified semantic differences.
13. Keep future batches evidence-backed: add Ghidra comments for mapped names, preserve uncertain functions as `FUN_...`, and leave project saving to the user.
14. Identify the owner and presentation path for the debug timeline buffer around `00455ae4`-`00455ce4`; resolve the meanings and units of object fields `+0xeb`, `+0xef`, `+0xf3`, and `+0xf7`.
15. Map the remaining actions in `key_handle_option_cheats_jp`, identify the exact trigger for its immortality toggle, and determine the destination semantics of the type-`0xf0` process created for `-egg`.
16. Establish what state completes the `-demo` polling loop, then trace `-?`, `-u`, `DAT_00482620`, and `DAT_004957d9`.
17. Compare the confirmed JP `-debug` gate, `JASSICA16` cheat sequence, and developer switches with the Western executable by behavior, after opening the correct Western Ghidra target; do not infer a difference from addresses or strings alone.
18. Trace the `process_choose_direction_to_coords` `0xff` branch through `DAT_0047b1d6`, the type-`0x259` record at `+0x64`, `0041b798`, and `0041bb7c`; resolve the query contract and the meaning of byte `+0x7d` set by `process_set_byte_7d_one`.
19. Map the individual selectors of `item_action_process_dispatch`, prioritizing `0`, `4`, `0x21`, `0x39`, and `0x3b`; the shared dispatcher role is verified, but case-specific behavior remains unresolved.
20. Find the writer and usage context of `DAT_004955e8` to establish what state gates the `DebugBreak` sites in `process_choose_direction_to_coords`.
1. Classify the report's remaining executable-byte gaps as code, data, or padding using references and control flow; do not infer functions from coverage percentages alone.
2. Resolve the action callback tables and the `process_choose_direction_to_coords` `0xff` contract, including `DAT_0047b1d6`, AttackProcess `+0x64`, and process byte `+0x7d`.
3. Finish the keyed-cache resource/entry schema and label unresolved item snapshot, auxiliary-field, and shape-profile semantics; compare the verified `0x79` and 16-byte layouts against the Western build.
4. Map AnimationProcess vtable slots and the caller/boundary around `00411fcd`; resolve `+0x52`, selector-mode tokens, and 8-way direction-sector encodings.
5. Trace joystick configuration and `+0x62` mode behavior; identify the text/response meaning of startup dialog resource `0x71`, any DirectDraw surface-restore path, the debug timeline consumer/fields, and the writer of `DAT_004955e8`.
6. Recover process flag meanings and the related-process list used by `0043d574`, `0043d640`, and `0043d7a4`; distinguish bit `0x20` at record bytes `+0x59` and `+0x14`, and verify the overlapping `Process_Terminate`/`process_terminate_set_flag_20` boundaries.
7. Continue `item_shape_dispatch_interaction_rules` through its callers and resolve the violence-gated tables at `0047b074` and `0047b084`, including their selected effects and relationship to target adjacency.
8. Compare JP and Western process, animation, joystick, item-record, spatial-query, `-debug`, `JASSICA16`, and developer-switch behavior only after opening the correct Western Ghidra target; document semantic differences, not address differences.
9. Map the remaining actions in `key_handle_option_cheats_jp`, identify the immortality-toggle trigger, and determine the destination semantics of the type-`0xf0` process created for `-egg`.
10. Establish what state completes the `-demo` polling loop, then trace `-?`, `-u`, `DAT_00482620`, and `DAT_004957d9`.
11. Keep future batches evidence-backed, add Ghidra comments for mapped names, preserve uncertain functions as `FUN_...`, and leave project saving to the user.

View file

@ -0,0 +1,47 @@
# JP Semantic-Gap Investigation Handoff
Date: 2026-10-12
## Resume Context
- Workspace: `Crusader_Decomp`
- Live Ghidra target: `/ja/CRUSADER.EXE`, image base `00400000`
- Main ledger and active backlog: [JP decompilation progress](jp-remorse-decompilation-progress.md), under `Semantic-Gap Analysis Checkpoint` and `Next Work`
- Coverage script: `tools/jp_executable_documentation_report.py`
The user asked to investigate five semantic-gap areas and add follow-up tasks to the JP ledger. That static pass is recorded in the progress document. The current investigation made no Ghidra database edits, saved no Ghidra state, and changed no executable bytes. Any pre-existing pending Ghidra changes were left untouched.
## Verified Baseline
The latest read-only coverage report for the active JP program reports:
- Function entries tracked: `1,493 / 1,493` (100%); untracked: `0`; generated names: `0`
- Function-body coverage: `336,693 / 499,712` bytes (67.4%)
- Defined-instruction coverage: `399,698 / 499,712` bytes (80.0%)
- Executable bytes outside defined instructions: `100,014`; these may be data, padding, or unanalyzed code
- Five ledger table addresses are not function entries: `004811f3`, `004811f9`, `00481200`, `00481208`, `0048120d`
Do not treat the remaining byte percentage or those five table addresses as proof of missing functions.
## Findings So Far
- Action dispatch: selectors `0`, `4`, `0x21`, `0x39`, and `0x3b` all construct a type-`0xf0` process through `process_0x0f0_construct_for_item`, then install distinct callback tables. The selector callbacks still need semantic names.
- Attack process: type `0x259` is constructed by `AttackProcess_0040af20`. The `process_choose_direction_to_coords` `0xff` path checks a nonzero `+0x64` value, shape overlap, and a packed-position query before dispatching selector `0`; the meanings of `DAT_0047b1d6`, `+0x64`, and process byte `+0x7d` remain open.
- Cache and records: the keyed cache has ten rotating key slots and 256 entry pointers per slot. The 16-bit key is looked up at file offset `key * 4`; descriptor low byte `+4` controls count and bit `0x40` at `+7` selects `0x40`/`0x80` bytes per entry. The pair reader copies two dwords. The separate 16-byte item snapshot layout is mapped in the progress ledger; the main item table has stride `0x79`.
- Animation and spatial search: AnimationProcess uses type `0x230` and vtable `0047e7a8`; its constructor clears `+0x52`, and a helper sets it to one. Its sole caller, `00411fcd`, is code with no owning Ghidra function. The spatial grid uses 64 two-byte cells per `0x80`-byte row; selector coordinates step by `0x200` and use `>> 9` for grid indexing.
- Input and presentation: joystick actions `4`-`8` emit `u/g/s/m/e`; action `9` maps directions to `q/w/i/o`; process byte `+0x62` selects distinct handling. Startup dialog resource `0x71` opens only for positive direction flags; a zero dialog result aborts startup. The DirectDraw lock helper has no restore branch. The debug timeline helper's sole caller is unowned code at `00455bb6`.
- Boundaries/debug: `00411fcd` and `00455bb6` are confirmed call sites but have no containing function. The timeline consumer/fields and writer for `DAT_004955e8` remain unresolved.
No runtime test of the joystick dialog or presentation paths was performed, and no JP/Western semantic comparison was made.
## First Steps Tomorrow
1. Open or confirm the live `/ja/CRUSADER.EXE` target before using Ghidra MCP. Use MCP-only analysis; do not use the offline PyGhidra CLI.
2. Read the `Semantic-Gap Analysis Checkpoint` and `Next Work` sections in the [JP decompilation progress ledger](jp-remorse-decompilation-progress.md).
3. Start with boundary triage around `00411fcd` and `00455bb6`: inspect surrounding disassembly, control flow, and references to determine whether each belongs to a larger routine. Do not create or name a function until bounds are supported.
4. Continue with the prioritized backlog in the ledger: action callback/type-`0x259` contracts, cache and field semantics, animation/spatial details, then joystick/dialog/DirectDraw/debug-timeline paths.
5. Re-run the read-only coverage script when useful to confirm the exact-entry baseline. Leave Ghidra project saving to the user and never patch bytes in the reference executable.
## Worktree Note
`docs/jp-remorse-decompilation-progress.md` was already locally modified before this investigation. Those existing edits were preserved; this work updated the bottom checkpoint/backlog and corrected its heading structure. The current changes have not been committed.

598
docs/spice86/README.md Normal file
View file

@ -0,0 +1,598 @@
# Spice86 - A PC emulator for real mode reverse engineering
![Linux](https://img.shields.io/badge/-Linux-grey?logo=linux)
![macOS](https://img.shields.io/badge/-OSX-black?logo=apple)
![Windows](https://img.shields.io/badge/-Windows-red?logo=windows)
[![.NET Build](https://github.com/OpenRakis/Spice86/actions/workflows/prerelease.yml/badge.svg)](https://github.com/OpenRakis/Spice86/actions/workflows/prerelease.yml)
[![NuGet](https://img.shields.io/nuget/v/Spice86.svg)](https://www.nuget.org/packages/Spice86)
![Licence](https://img.shields.io/badge/License-Apache_2.0-44cc11.svg)
[![downloads](https://img.shields.io/nuget/dt/Spice86)](https://www.nuget.org/packages/Spice86)
Spice86 is a tool to execute, reverse engineer and rewrite real mode DOS programs for which source code is not available.
Releases are available [on Nuget](https://www.nuget.org/packages/Spice86/).
Pre-releases are also available [on the Release page](https://github.com/OpenRakis/Spice86/releases/tag/latest)
NOTE: This is a port, and a continuation from the [original Java Spice86](https://github.com/kevinferrare/spice86).
It requires [.NET 10](https://dotnet.microsoft.com/en-us/download/dotnet/10.0) and runs on Windows, macOS, and Linux.
## Approach
Rewriting a program from only the binary is a hard task.
Spice86 is a tool that helps you do so with a methodic divide and conquer approach.
General process:
- You start by emulating the program in the Spice86 emulator.
- As the program runs, Spice86 builds a Control Flow Graph (CFG) of the executed code.
- At the end of each run, the emulator dumps some runtime data (memory dump, execution flow and the CFG).
- From that CFG, Spice86 **directly generates a self-contained, runnable C# project** that overrides the original assembly with equivalent C# code.
- You then gradually rewrite the generated C# functions, replacing the mechanical translation with readable, intentful code (a task an LLM can help with).
- This is helpful because:
- Small sequences of assembly can be statically analyzed and are generally easy to translate to a higher level language.
- You work all the time with a fully working version of the program so it is relatively easy to catch mistakes early.
- Rewriting code function by function allows you to discover the intent of the author.
Spice86 also dumps Ghidra-compatible symbols, so you can **optionally** load the memory dump into [Ghidra](https://github.com/NationalSecurityAgency/ghidra) via the [spice86-ghidra-plugin](https://github.com/OpenRakis/spice86-ghidra-plugin) for deeper static analysis. This is no longer required to produce C# overrides; it is just an extra analysis aid.
## Running your exe
| Command | Description |
|---------|-------------|
| `Spice86 -e file.exe` | Run the specified executable |
| `Spice86 -e file.com` | Run a COM file |
| `Spice86 -e file.bat` | Run a DOS batch file |
| `Spice86 -e file.bin` | Run a BIOS file |
## Dumping data
| Setting | Description |
|---------|-------------|
| Environment Variable | `SPICE86_DUMPS_FOLDER` - Set this to control the base directory where data is dumped |
| Command Line | Use `--RecordedDataDirectory` to specify the base dump location |
| Default Location | Current directory if neither of the above is specified |
**Note:** Regardless of the base directory setting, dumps are always placed in a subdirectory named with the program's SHA-256 hash. This ensures that multiple executables from the same game (e.g., SETUP.EXE, GAME.EXE) have isolated dump folders.
The emulator dumps the following files:
- **spice86dumpMemoryDump.bin**: Snapshot of the real mode address space
- **spice86dumpExecutionFlow.json**: Contains function addresses, labels, and executed instructions
- **spice86dumpGhidraSymbols.txt**: Ghidra-compatible symbols (function and label addresses), for optional import into Ghidra
- **spice86dumpCfgBlocks.json**: The explored CFG as basic blocks with execution-context metadata
- **spice86dumpCfgPartitions.json**: The recovered function/helper partitions and inter-partition transfers, derived from the block graph
- **spice86dumpCfgGeneratedOverrides.cs**: C# overrides generated from the explored CFG
- **GeneratedProject/**: A self-contained, runnable C# override project (see [Generated C# override project](#generated-c-override-project))
When there is already data in the specified location, the emulator will load it first and complement it.
**CFG graph reload:** The CFG instruction graph is also dumped (**spice86dumpCfgReload.json**) and, by default, reloaded from the recorded data directory at startup so previously explored program structure is preserved across runs. Disable with `--ReloadCfgGraph false`. It is a no-op if the file is absent.
**Code overrides:** When code overrides are active (`--UseCodeOverride true` with an `--OverrideSupplierClassName`), the CFG and execution flow dumps (**spice86dumpExecutionFlow.json**, **spice86dumpCfgBlocks.json**, **spice86dumpCfgPartitions.json**, **spice86dumpCfgReload.json**) are not written. Overrides replace the emulated asm, so the recorded graph would jump between overrides and no longer reflect the program.
### CPU Heavy Logging
For detailed debugging, you can enable CPU heavy logging which records every executed instruction to a file.
**⚠️ Warning:** This feature has a significant performance impact and should only be used for debugging purposes.
| Setting | Description |
|---------|-------------|
| `--CpuHeavyLog` | Enables CPU heavy logging (default: false) |
| `--CpuHeavyLogDumpFile` | Custom path for the log file (optional). If set, will enable CpuHeavyLog as well. Default Location: `{DumpDirectory}/cpu_heavy.log` |
| `--CpuHeavyLogExpressions` | Named expressions appended to every CPU heavy log line. Repeat the option for each expression to append (for example: `--CpuHeavyLogExpressions "life=AX+1" --CpuHeavyLogExpressions "myvalue=word ptr DS:[0x456]"`). Only active when `--CpuHeavyLog` is true. |
**Log Format:** Each line contains: `SegmentedAddress InstructionString`
**Example:**
```
017D:0000 mov AX,0xDD1D
017D:0003 call near 0xE4AD
017D:E4AD mov SI,0x0080
```
**Usage:**
```bash
# Enable with default location
Spice86 -e program.exe --CpuHeavyLog
# Use custom log file path
Spice86 -e program.exe --CpuHeavyLog --CpuHeavyLogDumpFile "C:\logs\cpu.log"
# Append named expressions to each log line (example)
Spice86 -e program.exe --CpuHeavyLog \
--CpuHeavyLogExpressions "life=AX+1" \
--CpuHeavyLogExpressions "myvalue=word ptr DS:[0x456]"
```
## Command line options
```
--Debug (Default: false) Starts the program paused and pauses once again when stopping.
--Cycles (Default: null) Target CPU cycles per ms, for the rare speed sensitive game. 3000 by default. Overrides Instructions per second option below if used.
--Xms (Default: true) Enables 15 MB of XMS memory.
--Ems (Default: true) Enables EMS memory. EMS adds 8 MB of memory accessible to DOS programs through the EMM Page Frame.
--A20Gate (Default: false) Disables the 20th address line to support programs relying on the rollover of memory addresses above the HMA (slightly above 1 MB).
-m, --Mt32RomsPath Zip file or directory containing the MT-32 ROM files
-c, --CDrive Path to C drive, default is exe parent
-r, --RecordedDataDirectory Directory to dump data to when not specified otherwise. If blank dumps to SPICE86_DUMPS_FOLDER, and if not defined dumps to a sub directory named with the program SHA 256 signature
-e, --Exe Required. Path to executable
-a, --ExeArgs List of parameters to give to the emulated program
-x, --ExpectedChecksum Hexadecimal string representing the expected SHA256 checksum of the emulated program
-f, --FailOnUnhandledPort (Default: false) If true, will fail when encountering an unhandled IO port. Useful to check for unimplemented hardware. false by default.
-g, --GdbPort GDB port. If 0, GDB server will be disabled. Default is 10000.
-o, --OverrideSupplierClassName Name of a class that will generate the initial function information. See documentation for more information.
-p, --ProgramEntryPointSegment (Default: 4096) Segment where to load the program. DOS PSP and MCB will be created before it.
-u, --UseCodeOverride (Default: true) <true or false> if false it will use the names provided by overrideSupplierClassName but not the code
-i, --InstructionTimeScale <number of instructions that have to be executed by the emulator to consider a second passed> if blank will use time based timer.
--ClockJitterSeed <CLOCKJITTERSEED> Optional integer seed enabling small deterministic clock jitter (±0.01 ms). Omit to disable.
--ClockStartTime <CLOCKSTARTTIME> Optional UTC start date/time for the emulated clock (parseable by DateTime.Parse, e.g. 1993-06-01T00:00:00Z). When omitted defaults to the current UTC time.
-t, --TimeMultiplier (Default: 1) <time multiplier> if >1 will go faster, if <1 will go slower.
-h, --HeadlessMode [Mode] (Default: false) Headless mode. The mode 'Minimal' does not use any UI components, 'Avalonia' uses the full UI and consumes a bit more memory.
-l, --VerboseLogs (Default: false) Enable verbose level logs
-w, --WarningLogs (Default: false) Enable warning level logs
-s, --SilencedLogs (Default: false) Disable all logs
-i, --InitializeDOS (Default: true) Install DOS interrupt vectors or not.
--CpuHeavyLog (Default: false) Enable CPU heavy logging. Logs every executed instruction to a file. Warning: significant performance impact.
--CpuHeavyLogDumpFile Custom file path for CPU heavy log output. If not specified, defaults to {DumpDirectory}/cpu_heavy.log
--CpuHeavyLogExpressions (Default: none) Named expressions appended to every CPU heavy log line. Repeat the option for each expression to append (for example: --CpuHeavyLogExpressions "life=AX+1"). Only active when --CpuHeavyLog is true.
--ReloadCfgGraph (Default: true) Reload the previously dumped CFG instruction graph (spice86dumpCfgReload.json) at startup so explored program structure is preserved across runs. No-op if the file is absent.
--AsmRenderingStyle Style of the ASM rendering. Spice86 or DosBox.
--StructureFile Path to a C header file that describes the structures in the application. Works best with exports from IDA or Ghidra
--mcp-http-port (Default: 8081) Port for the MCP HTTP server
--RenderingMode (Default: Async) Selects the VGA rendering mode. Sync fires VGA events on the emulation thread for determinism; The default mode is for performance.
--JitMode (Default: InterpretedThenCompiled) Controls how the JIT compiler handles instruction execution delegates.
--AllowIvtAddress0 (Default: false) Controls whether an INT instruction whose IVT entry is 0:0 is treated as valid.
--version Display version information.
```
### Sound Blaster and OPL/Adlib Gold Options
- SbType: Sound Blaster card type. Values: None, SB1, SB2, SBPro1, SBPro2, Sb16, GameBlaster, AdlibGold.
- SbIrq: Sound Blaster IRQ line. Default is 7. Common values: 5, 7, 9, 10.
- SbDma: Sound Blaster 8-bit DMA channel. Default is 1. Common values: 0, 1, 3.
- SbHdma: Sound Blaster 16-bit high DMA channel. Default is 5. Common values: 5, 6, 7.
- SbBase: Sound Blaster base I/O address (hex). Default is 0x220. Common values: 0x220, 0x240, 0x260, 0x280.
- OplMode: OPL synthesis mode. Values: None, Opl2, DualOpl2, Opl3, Opl3Gold. Default is Opl3.
- SbMixer: Enable Sound Blaster mixer control of OPL voices. Default is true.
## Dynamic analysis
Spice86 speaks the [GDB](https://www.gnu.org/software/gdb/) remote protocol:
- it supports most of the commands you need to debug.
- it also provides custom GDB commands to do dynamic analysis.
### Connecting to GDB
The GDB server is always started along with the program to execute unless option is set to 0.
Default port is 10000.
If you want to pause before starting execution to setup breakpoints and so on, use the --Debug option.
Here is how to connect from GDB command line client and how to set the architecture:
```
(gdb) target remote localhost:10000
(gdb) set architecture i8086
```
### Vanilla GDB
You can add breakpoints, step, view memory and so on.
Example with a breakpoint on VGA VRAM writes:
```
(gdb) watch *0xA0000
```
Viewing assembly:
```
(gdb) layout asm
```
Removing a breakpoint:
```
(gdb) remove 1
```
Searching for a sequence of bytes in memory (start address 0, length F0000, ascii bytes of 'Spice86' string):
```
(gdb) find /b 0x0, 0xF0000, 0x53, 0x70, 0x69, 0x63, 0x65, 0x38, 0x36
```
GDB does not support x86 real mode segmented addressing, so pointers need to refer to the actual physical address in memory. VRAM at address A000:0000 would be 0xA0000 in GDB.
Similarly, The $pc variable in GDB will be exposed by Spice86 as the physical address pointed by CS:IP.
### Custom GDB commands (where the magic happens)
The list of custom commands can be displayed like this:
```
(gdb) monitor help
```
#### Dump information about current run
```
(gdb) monitor dumpall
```
Dumps everything described below in one shot. Files are created in the dump folder as explained [here](https://github.com/OpenRakis/Spice86#dumping-data)
Several files are produced:
- spice86dumpMemoryDump.bin: Snapshot of the real mode address space. Contains the instructions that are actually loaded and executed. They may differ from the exe you are running because DOS programs can rewrite some of their instructions / load additional modules in memory.
- spice86dumpExecutionFlow.json: Contains information about the run such as addresses of the functions, the labels, and the instructions that have been executed. Also consumed by the optional [spice86-ghidra-plugin](https://github.com/OpenRakis/spice86-ghidra-plugin).
- spice86dumpCfgBlocks.json and spice86dumpCfgPartitions.json: the explored CFG as basic blocks, and the function/helper partitions plus transfers derived from those blocks.
- spice86dumpCfgGeneratedOverrides.cs and GeneratedProject/: the C# overrides and runnable project generated from the explored CFG (see [Generated C# override project](#generated-c-override-project)).
#### Special breakpoints
Break after x emulated CPU Cycles:
```
(gdb) monitor breakCycles 1000
```
Break at the end of the emulated program:
```
(gdb) monitor breakStop
```
## Seer
For a pleasing and productive experience with GDB, the
[seerGDB](https://github.com/epasveer/seer) client is highly recommended.
At best, use the configuration file `spice86.seer` provided in the `doc` directory ([here](doc/spice86.seer)): run Seer with `seergdb --project spice86.seer`.
If you use a different port for gdb, adjust `spice86.seer` correspondingly.
Also, while in Seer, set Settings/Configuration/Assembly/Disassembly Mode to
“Length”, otherwise the Assembly View won't work.
## Emulator features
| Component | Support Level |
|-----------|--------------|
| **CPU** | 8086/8088 fully implemented and tested |
| | 80186 (BOUND instruction missing) |
| | 80286 (protected mode not implemented) |
| | 80386 (partial support, protected mode not implemented) |
| | Only 16-bit instructions fully supported |
| | Most 32-bit instructions implemented but not fully tested |
| | No FPU except detection instructions |
| **Memory** | 1MB address space with segmented addressing |
| | A20 Gate support |
| | EMS 3.2 implemented |
| | XMS 4.0 is implemented |
| | HMA is implemented |
| | No paging support |
| **Graphics** | Text modes, VGA, EGA, and CGA implemented |
| | EGA and CGA modes are best effort (you may find bugs) |
| | VESA VBE 1.2 is supported |
| **DOS** | Largely complete DOS and INT 21h implementation (DOS 5.0) |
| **Input** | Keyboard and mouse supported |
| | No joystick support |
| **CD-ROM** | MSCDEX and CDDA support is implemented, including CD images |
| **Floppy** | Floppy disk emulation is implemented, including floppy images and booting on a floppy image |
## Sound support
| Sound Type | Support Level | Notes |
|------------|---------------|-------|
| PC Speaker | ✅ Full | Implemented |
| Adlib/SB OPL | ✅ Full | Ported from DOSBox Staging |
| SoundBlaster | ✅ Full | Ported from DOSBox Staging |
| Adlib Gold | ✅ Full | Ported from DOSBox Staging |
| MT-32 | ⚠️ Partial | Not available on macOS |
| Gravis Ultrasound | ❌ None | Not implemented yet |
| General MIDI | ✅ Full | Supported |
## Misc
| Feature | Details |
|---------|---------|
| **C Drive** | Configurable with `--CDrive`, defaults to current folder |
| **Program Arguments** | Pass up to 127 chars with `--ExeArgs` |
| **Time Handling** | Real elapsed time (adjustable with `--TimeMultiplier`) or instruction-based timing with `--InstructionTimeScale` |
| **Screen Refresh** | 30 FPS and on VGA retrace wait detection |
| **Structure Viewer** | Requires C header file (`--StructureFile`) to display memory structures |
## Reverse engineering process
Concrete example with Cryo Dune [here](https://github.com/OpenRakis/Cryogenic).
First run your program and make sure everything works fine in Spice86. If you encounter issues it could be due to unimplemented hardware / DOS / BIOS features.
When Spice86 exits, it dumps its data (memory dump, execution flow, CFG) and generates a C# override project in the dump folder (current folder, or the folder specified by the `SPICE86_DUMPS_FOLDER` env variable / `--RecordedDataDirectory`).
The generated project under `GeneratedProject/` is immediately runnable and already overrides the explored assembly with equivalent C#. From there you rewrite the generated functions, function by function, to discover and document the program's intent. This is well suited to LLM assistance.
See [Generated C# override project](#generated-c-override-project) for how to run it and [Overriding emulated code with C# code](#overriding-emulated-code-with-c-code) for the override API.
Optionally, you can also open the memory dump in [Ghidra](https://github.com/NationalSecurityAgency/ghidra) with the [spice86-ghidra-plugin](https://github.com/OpenRakis/spice86-ghidra-plugin) for additional static analysis (see [Ghidra plugin](#ghidra-plugin)).
## Generated C# override project
On every dump (when not already running with overrides), Spice86 turns the explored CFG into a ready-to-run C# project, so you do not need any external tool to start rewriting the program in C#.
Two artifacts are produced in the dump folder:
- **spice86dumpCfgGeneratedOverrides.cs**: the generated overrides on their own (a `CfgGeneratedOverrideSupplier` plus a `CfgGeneratedOverrides : CSharpOverrideHelper` mapping every discovered function via `DefineFunction`).
- **GeneratedProject/**: a self-contained, runnable project wrapping those overrides:
- `Spice86.Generated.csproj` references the Spice86 GUI project, so the build always matches the running emulator.
- `Program.cs` forwards all your arguments to Spice86 and defaults in `--OverrideSupplierClassName`, `--UseCodeOverride true`, and the program's `--ExpectedChecksum` (so the overrides cannot run against a different binary).
- `CfgGeneratedOverrides.cs` contains the generated overrides.
Run it like a normal .NET project, passing the path to your executable:
```bash
cd <dump folder>/GeneratedProject
dotnet run -- -e /path/to/PROGRAM.EXE
```
Then progressively replace the mechanically generated function bodies with your own readable C# implementations.
> **Note:** while running with overrides active (`--UseCodeOverride true`), the CFG and execution-flow dumps are not rewritten, so regenerating from scratch should be done from a plain (non-override) run.
## Overriding emulated code with C# code
You can provide your own C# code to override the program original assembly code. This is exactly what the [generated project](#generated-c-override-project) does for you automatically; the section below explains the API so you (or an LLM) can write or refine overrides.
### Defining overrides
Spice86 can take in input an instance of Spice86.Core.Emulator.Function.IOverrideSupplier that builds a mapping between the memory address of functions and their C# overrides.
For a complete example you can check the source code of [Cryogenic](https://github.com/OpenRakis/Cryogenic).
Here is a simple example of how it would look like:
```csharp
namespace My.Program;
// This class is responsible for providing the overrides to spice86.
// There is only one per program you reimplement.
public class MyProgramOverrideSupplier : IOverrideSupplier {
public IDictionary<SegmentedAddress, FunctionInformation> GenerateFunctionInformations(
ILoggerService loggerService, Configuration configuration, ushort programStartSegment, Machine machine) {
return new MyOverrides(new Dictionary<SegmentedAddress, FunctionInformation>(),
machine, loggerService, configuration).FunctionInformations;
}
public override string ToString() {
return "Overrides My program exe. class is " + GetType().FullName;
}
}
// This class contains the actual overrides. As the project grows, you will probably need to split the reverse engineered code in several classes.
public class MyOverrides : CSharpOverrideHelper {
private readonly MyOverridesGlobalsOnDs globalsOnDs;
public MyOverrides(IDictionary<SegmentedAddress, FunctionInformation> functionInformations,
Machine machine, ILoggerService loggerService, Configuration configuration)
: base(functionInformations, machine, loggerService, configuration) {
globalsOnDs = new MyOverridesGlobalsOnDs(Memory, State.SegmentRegisters);
// IncDialogueCount47A8 will get executed instead of the assembly code when a call to 017D:A1E8 is performed.
// The override method receives the load offset (segment where the program was loaded) as parameter.
DefineFunction(0x017D, 0xA1E8, IncDialogueCount47A8_017D_A1E8_0C0B8);
DefineFunction(0x017D, 0x0100, AddOneToAX_017D_0100_01FD0);
}
public Action IncDialogueCount47A8_017D_A1E8_0C0B8(int loadOffset) {
// Accessing the memory via accessors
globalsOnDs.SetDialogueCount47A8(globalsOnDs.GetDialogueCount47A8() + 1);
// Depends on the actual return instruction performed by the function, needed to be called from the emulated code as
// some programs like to mess with the stack ...
return NearRet();
}
public Action AddOneToAX_017D_0100_01FD0(int loadOffset) {
// Assembly for this would be
// INC AX
// RETN
// Note that you can access the whole emulator to change the state in the overrides.
State.AX++;
return NearRet();
}
}
// Memory accesses can be encapsulated into classes like this to give names to addresses and make the code shorter.
public class GlobalsOnDs : MemoryBasedDataStructureWithDsBaseAddress {
public GlobalsOnDs(IByteReaderWriter memory, SegmentRegisters segmentRegisters) : base(memory, segmentRegisters) {
}
// Getters and Setters for address 0x1DD:0x2/0x1DD2.
// Was accessed via the following registers: DS
public int Get01DD_0002_Word16() {
return UInt16[0x2];
}
public void Set01DD_0002_Word16(ushort value) {
UInt16[0x2] = value;
}
// Getters and Setters for address 0x1138:0x0/0x11380.
public int Get1138_0000_Word16() {
return UInt16[0x0];
}
}
```
The override method name encodes the address (`Name_<segment>_<offset>_<linear>`) so it can be parsed back into a `FunctionInformation`; pass an explicit `name` argument to `DefineFunction` if you prefer not to follow that convention.
*Remember*: You must tell Spice86 to use your C# code overrides with the command line argument "--UseCodeOverride true" when debugging your project, along with the mandatory path to your DOS program passed with the "-e" / "--Exe" argument.
## Debugger
Spice86 comes with a [built-in debugger](https://github.com/OpenRakis/Spice86/wiki/Spice86-internal-debugger). that can be used to debug the emulated program. It is a simple debugger that allows you to inspect the memory, the disassembly, the registers, and the stack.
### Structure viewer
The structure viewer allows you to inspect the memory in a structured way. It is useful to inspect the memory as a structure, like the DOS PSP, the DOS MCB, the VGA registers, etc.
First you need a C header file that describes the structures in the application. You can generate one with Ghidra or IDA. Then you can load it with the `--StructureFile` commandline argument.
This will enable the "Structure view" button in the Memory tab of the debugger.
There you enter a segment:offset address and choose the structure you want to view. The structure will be displayed in a tree view and the memory in a hex view.
The display updates whenever the application is paused, so you can step through the program and see how the structure changes.
Exporting a new C header file from Ghidra or IDA will also update the structure viewer with the new information real-time.
You can also enter the Structure view by selecting a range of bytes in the Memory tab and right-clicking on it.
## HTTP server
Spice86 includes a built-in HTTP server for quick runtime inspection and memory access.
- The HTTP server is **disabled by default**. Enable it by specifying a port with `--HttpApiPort`.
Available endpoints:
| Method | Route | Description |
|--------|-------|-------------|
| `GET` | `/api` | API metadata and endpoint list |
| `GET` | `/api/status` | Current emulator status (pause state, CPU state, CS:IP, cycles, memory size) |
| `GET` | `/api/memory/{address}/byte` | Read one byte at address |
| `PUT` | `/api/memory/{address}/byte` | Write one byte at address |
| `GET` | `/api/memory/{address}/range/{length}` | Read a memory range |
## Misc details
### C Drive
It is possible to provide a C: Drive for emulated DOS functions with the option **--CDrive**. Default is executed program folder. For some games you may need to set the C drive to the parent folder.
### Emulated program arguments
You can pass arguments (max 127 chars!) to the emulated program with the option **--ExeArgs**. Default is empty.
### Time
The emulated Timer hardware of the PC (Intel 8259) supports measuring time from either:
- The real elapsed time. Speed can be altered with parameter **--TimeMultiplier**.
- The number of instructions the emulated CPU executed. This is the behaviour that is activated with parameter **--InstructionTimeScale** and is forced when in GDB mode so that you can debug with peace of mind without the timer triggering.
Compatibility list available [here](COMPATIBILITY.md).
### How to build on your machine
- Install the [.NET 10 SDK](https://dotnet.microsoft.com/en-us/download/dotnet/10.0) (once)
- clone the repo
- run this where Spice86.sln is located:
```bash
dotnet build
```
### How to run
```bash
Spice86 -e <path to executable>
```
or use this where Spice86.csproj is located:
```bash
dotnet run -e <path to executable>
```
if you don't want to manually build and run separately, use the helper script at the root of the repository which builds and runs the app, passing all arguments through:
```bash
./run.sh -e <path to executable>
```
### Ghidra plugin
Importing the dump into Ghidra is **optional**. Spice86 already generates a runnable C# override project on its own (see [Generated C# override project](#generated-c-override-project)); the Ghidra plugin is only useful if you additionally want to explore the dump inside Ghidra (static analysis, labeling, or producing a `--StructureFile` C header for the [structure viewer](#structure-viewer)).
This uses Ghidra and Java 17.
Before using it, define an environnement variable named SPICE86_DUMPS_FOLDER pointing to a folder where the Spice86 dumps are located.
They are generated on exit.
General procedure, in order:
1.Ghidra's own script 'ImportSymbolScript.py' (input used is "spice86dumpGhidraSymbols.txt")
2.Ghidra's Auto-Analyze (only enable 'Dissasemble Entry Points')
3.Now, you can use the plugin.
Remember: if Ghidra displays SUBROUTINES, use the 'f' key to convert them into functions.
Also, if you have any weird behaviour, make sure you have Java 17 and ONLY Java 17. That's how Ghidra likes it.
### Cfg Cpu
Doc [here](doc/cfgcpuReadme.md)
### MCP
MCP server documentation is available in [doc/mcp.md](doc/mcp.md).
### Some screenshots
Cryo dune:
![](doc/cryodune_duke.png)
![](doc/cryodune_worm.png)
![](doc/cryodune_orni.png)
Prince of persia:
![](doc/prince_of_persia.PNG)
Stunts:
![](doc/stunts_menu.PNG)
![](doc/stunts_loop.png)
![](doc/stunts_crash.PNG)
![](doc/stunts_skid.PNG)
Betrayal at Krondor:
![](doc/BaK.png)
## Credits
The SoundBlaster and Adlib Gold implementations are fully ported from [dosbox-staging](https://github.com/dosbox-staging/dosbox-staging), replacing the previous one which was modified from the Aeon emulator. This includes PCM and OPL sound quality improvements, far greater emulation accuracy, SB/OPL compatibility, mixer thread logic, audio events, audio hardware delays, and a complete audio re-architecture.
The NukedOpl3 port to C# was done by codeEngine. It is bit-accurate. Thanks a lot!
The DOS implementation is heavily inspired by the clean code from FreeDOS, and DOSBox Staging.
The implementations of MSCDEX, CDDA, Floppy emulation, CD images support, CD drive emulation all used DOSBox Staging as a model (even if the architecture is different), escpecially for conformance about expected behavior (ie. IOCTL).
The BIOS implementation draws heavily from SeaBIOS, IBM PC BIOS reconstructionns, and sometimes DOSBox Staging.
EMS was written with the help of the specs.
XMS was written with the help of the specs, but a lot had to be rewritten by looking at [the real HIMEM driver](https://github.com/neozeed/himem.sys-2.06), and by reproducing the XMS tests from Microsoft.
Additionally, the project no longer relies on PortAudio. Instead, it uses a fully cross-platform C# port of the SDL2 audio APIs.
We only depend on WASAPI (Windows), ALSA (Linux), or CoreAudio (macOS).
This project uses JetBrains Rider licenses, thanks to JetBrains' [Open Source Community Support](https://www.jetbrains.com/community/opensource/#support).
![](jetbrainsrider.svg)
The UI is powered by [Avalonia UI](https://avaloniaui.net/).
![](avalonia.png)

402
docs/spice86/mcp.md Normal file
View file

@ -0,0 +1,402 @@
# Spice86 MCP HTTP Server
## Overview
Spice86 exposes a **Model Context Protocol (MCP) server** over HTTP, enabling structured programmatic control of the emulator. AI clients, automation scripts, and external tooling can use MCP to inspect, manipulate, and drive execution of DOS programs running in Spice86.
This server provides **65+ built-in tools** covering:
- CPU state inspection (registers, flags, instruction pointer)
- Memory read/write/search/disassembly
- I/O port read/write
- Execution control (pause, resume, step, step-over)
- Breakpoint management (execution, memory read/write)
- Function discovery and CFG (Control Flow Graph) traversal
- Video state inspection and screenshot capture
- Sound device state (SoundBlaster, OPL, MIDI, PC Speaker)
- DOS structures (PSP, MCB, File handle table)
- EMS and XMS memory management
The HTTP transport is **stateless** by default to maximize compatibility with real-world AI clients that may skip session negotiation or reuse connection state unpredictably.
---
## Endpoints
Video inspection and PNG captures use the last completed logical framebuffer.
Mode 13h produces 320x200 pixels; a program can change VGA registers without
changing the BIOS mode record (for example, 256x224 unchained graphics).
Pixel and scanline doubling are presentation concerns, not duplicate pixels
in the returned framebuffer. GUI graphics retain 4:3 aspect correction.
| Endpoint | Description |
|----------|-------------|
| `http://localhost:<port>/mcp` | MCP protocol endpoint (JSON-RPC over HTTP) |
| `http://localhost:<port>/health` | Health check endpoint returning `{"status":"ok"}` |
**Default port:** `8081`
**CLI option:** `--mcp-http-port <port>`
---
## Quick Start
### 1. Start Spice86 with MCP enabled (enabled by default)
```bash
Spice86 -e program.exe --mcp-http-port 8081
```
### 2. Connect your MCP client
Point your MCP client to:
```
http://localhost:8081/mcp
```
### 3. Discover available tools
```json
POST /mcp
Content-Type: application/json
{
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2024-11-05",
"capabilities": {},
"clientInfo": { "name": "MyClient", "version": "1.0" }
}
}
```
Then call `tools/list` to enumerate all available tools, or call `mcp_about` for high-level capability metadata.
---
## Protocol Behavior
- **Transport:** HTTP (stateless by default)
- **Protocol:** JSON-RPC 2.0
- **Session management:** The server does **not** issue `Mcp-Session-Id` headers by default (`options.Stateless = true`). This prevents 404 errors when AI clients reuse session IDs from fresh TCP connections or skip the `notifications/initialized` handshake.
- **Standard MCP flow:** `initialize` → `tools/list` → `tools/call`
**Stateless mode** is recommended for AI agents and automated workflows. If you need stateful sessions (e.g., for long-lived interactive clients), you can modify `McpHttpHost.cs` to set `options.Stateless = false`.
---
## Built-in Tool Categories
Spice86 ships with **65+ MCP tools** organized into these capability scopes:
### CPU State & Execution Control
- `read_cpu_state`: Read all general-purpose registers, segment registers, IP, flags, and cycle count
- `pause`: Pause emulation
- `resume`: Resume emulation
- `step`: Execute one instruction and pause
- `step_over`: Step over CALL instructions (run until RET)
- `get_pause_status`: Check if emulator is paused
### Memory Operations
- `read_memory`: Read a memory range (segment, offset, length) as hex bytes
- `write_memory`: Write hex bytes to memory
- `search_memory`: Search for a hex pattern in conventional RAM
- `read_disassembly`: Disassemble instructions at a given address
### I/O Ports
- `read_io_port`: Read from an I/O port
- `write_io_port`: Write to an I/O port
### Breakpoints
- `add_execution_breakpoint`: Break when CS:IP reaches an address
- `add_memory_read_breakpoint`: Break on memory read
- `add_memory_write_breakpoint`: Break on memory write
- `remove_execution_breakpoint`
- `remove_memory_read_breakpoint`
- `remove_memory_write_breakpoint`
- `list_execution_breakpoints`
- `list_memory_breakpoints`
### Functions & CFG
- `list_functions`: List discovered functions sorted by call count
- `read_cfg_cpu_graph`: Dump the Control Flow Graph (CFG) built by `CfgCpu`
### Video
- `read_video_state`: Current video mode, resolution, text/graphics flag, cursor position
- `read_video_state_detailed`: Full VGA register dump
- `video_set_mode`: Change video mode
- `read_vga_memory`: Read VGA VRAM
- `write_vga_memory`: Write VGA VRAM
- `vga_set_palette_entry`: Set VGA palette color
- `capture_screenshot`: Save a screenshot to disk and return the path
### Sound Devices
- **SoundBlaster:** `read_sound_blaster_state`, `sound_blaster_set_speaker`, `read_sound_blaster_dsp_version`, `sound_blaster_write_mixer_register`, etc.
- **OPL (Adlib/SB OPL2/OPL3):** `read_opl_state`, `opl_write_register`
- **PC Speaker:** `read_pc_speaker_state`, `pc_speaker_set_control`
- **MIDI:** `read_midi_state`, `midi_reset`, `midi_enter_uart_mode`, `midi_send_bytes`
### Input Automation
- `send_keyboard_key`: Send a keystroke (press + release or hold)
- `send_mouse_packet`: Send raw mouse data packet
- `send_mouse_move`: Move mouse cursor
- `send_mouse_button`: Press/release mouse button
### DOS & BIOS Structures
- `read_dos_psp`: Read the DOS Program Segment Prefix
- `read_dos_mcb_chain`: Dump the DOS Memory Control Block chain
- `read_dos_file_handle_table`: List open file handles
- `read_dos_current_directory`: Get current drive and directory path
- `read_bios_equipment_word`: Read BIOS equipment flags
### EMS & XMS
- `read_ems_state`: EMS handle allocation, page frame mapping
- `read_xms_state`: XMS handle allocation, HMA usage
- `read_ems_page_frame`: Dump EMS page frame content
- `read_xms_block`: Read an XMS memory block
### Metadata & Diagnostics
- `mcp_about`: High-level server metadata, capability scopes, extension points, tool count
For a complete tool list with parameter details, call `tools/list` via the MCP endpoint.
---
## Tool Invocation & Auto-Pause
Most tools automatically **pause** the emulator before execution and **resume** after. This ensures consistent state during inspection and prevents race conditions. A few tools (marked with `[McpManualControl]`) skip auto-pause and require the client to explicitly call `pause` if needed.
**Example: Reading CPU state**
```json
POST /mcp
Content-Type: application/json
{
"jsonrpc": "2.0",
"id": 2,
"method": "tools/call",
"params": {
"name": "read_cpu_state",
"arguments": {}
}
}
```
**Response:**
```json
{
"jsonrpc": "2.0",
"id": 2,
"result": {
"content": [
{
"type": "resource",
"resource": {
"uri": "data:application/json;base64,eyJFQVgiOjEyMywgIkVCWCI6NDU2LCAuLi59"
}
}
]
}
}
```
The structured content (JSON) is base64-encoded in the resource field.
**Example: Writing memory**
```json
POST /mcp
{
"jsonrpc": "2.0",
"id": 3,
"method": "tools/call",
"params": {
"name": "write_memory",
"arguments": {
"segment": 4096,
"offset": 256,
"data": "B80200CD21"
}
}
}
```
---
## Extending MCP from User Projects
Spice86 supports **external MCP tool registration**. You can add project-specific tools for game-specific operations (e.g., reading player stats, manipulating inventory, triggering events).
### Extension Model
1. **Implement `IMcpToolSupplier`** in your project to provide custom tool assemblies and injectable services.
2. **Mark your tool classes with `[McpServerToolType]`** and individual methods with `[McpServerTool(Name = "...")]`.
3. **Register your tools at startup** by passing additional assemblies and services to `McpHttpHost.Start`.
### Extension Entry Points
| Method | Purpose |
|--------|---------|
| `IMcpToolSupplier.GetMcpToolAssemblies()` | Return additional assemblies containing `[McpServerToolType]` classes |
| `IMcpToolSupplier.GetMcpServices()` | Return injectable services used by custom tools |
| `McpHttpHost.Start(additionalToolAssemblies, additionalServices)` | Register external tools at server start |
### Minimal Extension Example
```csharp
using Spice86.Core.Emulator.Mcp;
using ModelContextProtocol.Server;
// 1. Implement IMcpToolSupplier in your override project
public class MyGameMcpToolSupplier : IMcpToolSupplier {
public IEnumerable<Assembly> GetMcpToolAssemblies() {
return [typeof(MyGameMcpTools).Assembly];
}
public IEnumerable<object> GetMcpServices() {
return [new MyGameContext(...)];
}
}
// 2. Define your custom tools
[McpServerToolType]
public sealed class MyGameMcpTools {
private readonly MyGameContext _context;
public MyGameMcpTools(MyGameContext context, EmulatorMcpServices emulatorServices) {
_context = context;
}
[McpServerTool(Name = "read_player_health", UseStructuredContent = true)]
public object ReadPlayerHealth() {
// Read from memory via _context or emulatorServices
int health = _context.GetPlayerHealth();
return new { Health = health, MaxHealth = 100 };
}
[McpServerTool(Name = "set_player_gold", UseStructuredContent = true)]
public object SetPlayerGold(int amount) {
_context.SetPlayerGold(amount);
return new { Success = true, Gold = amount };
}
}
```
### Registering Custom Tools at Startup
Modify your startup wiring (typically in `Spice86DependencyInjection.cs` or a custom entry point):
```csharp
IMcpToolSupplier supplier = new MyGameMcpToolSupplier();
McpHttpHost host = new(loggerService);
host.Start(
services: emulatorMcpServices,
port: configuration.McpHttpPort,
additionalToolAssemblies: supplier.GetMcpToolAssemblies(),
additionalServices: supplier.GetMcpServices()
);
```
**Note:** The default `Spice86` startup does **not** load external tool assemblies. You must wire them explicitly if you want project-specific tools.
---
## Practical Guidance for Extension Authors
### Tool Design Best Practices
1. **Keep tools deterministic:** Avoid relying on global mutable state outside the emulator.
2. **Prefer semantic tools:** Expose high-level operations (e.g., `read_player_inventory`) instead of raw memory offsets.
3. **Keep low-level tools available:** Also provide `read_memory_at_player_inventory_address` for diagnostics when the semantic tool breaks.
4. **Return compact structured payloads:** Avoid dumping large arrays unless necessary. Use pagination or limits.
5. **Add integration tests:** Write real MCP `tools/call` tests that verify your tools work end-to-end.
### Debugging Extension Tools
- **Check the MCP log:** `logs/mcp.log` contains startup and invocation errors.
- **Verify tool registration:** Call `tools/list` and ensure your custom tools appear.
- **Test auto-pause behavior:** If your tool accesses emulator state, ensure it pauses correctly or mark it with `[McpManualControl]`.
---
## Common Use Cases
### AI-Driven Reverse Engineering
An AI agent can:
1. Call `read_cpu_state` to see where the program is stuck.
2. Call `read_disassembly` to inspect the next 10 instructions.
3. Call `search_memory` to find a string or data pattern.
4. Call `add_execution_breakpoint` to pause at a suspect function.
5. Call `list_functions` to see which functions are called most often.
6. Call `capture_screenshot` to see the current video output.
### Automated Testing
A test script can:
1. Call `pause` to halt execution.
2. Call `write_memory` to inject test data.
3. Call `resume` and wait for a breakpoint.
4. Call `read_dos_file_handle_table` to verify the program opened the expected file.
5. Call `capture_screenshot` and compare against a baseline image.
### Game Trainer / Cheat Tool
A trainer tool can:
1. Call `read_dos_psp` to locate the game's data segment.
2. Call `search_memory` to find the player's health value.
3. Call `write_memory` to set health to max.
4. Call `add_memory_write_breakpoint` to detect when the game decrements health.
### Live Debugging Dashboard
A web dashboard can:
1. Poll `read_cpu_state` every 500ms to display registers.
2. Call `read_video_state` to show current video mode.
3. Call `read_sound_blaster_state` to visualize audio channels.
4. Call `list_functions` to show a live call-count heatmap.
---
## Logs & Troubleshooting
- **MCP server log:** `logs/mcp.log` (warning level by default)
- **Emulator logs:** Console or file (controlled by `--VerboseLogs`, `--WarningLogs`, `--SilencedLogs`)
- **Health check:** `GET http://localhost:8081/health` should return `{"status":"ok","service":"Spice86 MCP Server"}`
**Common issues:**
| Problem | Solution |
|---------|----------|
| Client gets 404 on `/mcp` | Check that `--mcp-http-port` is set and the server started successfully |
| Tools return "Tool disabled" error | Some tools may be disabled if the emulator is not in the expected state (e.g., video tools when no VGA card is initialized) |
| Tools time out | If emulator is not responding to pause requests, ensure the emulation loop is running and not deadlocked |
| Client skips session ID and gets 404 | Ensure stateless mode is enabled (default); if using stateful mode, ensure client sends `Mcp-Session-Id` header |
---
## Reference
### Related Files
- `Spice86.Core/Emulator/Mcp/McpHttpHost.cs` - HTTP server setup and lifecycle
- `Spice86.Core/Emulator/Mcp/EmulatorMcpTools.cs` - Built-in tool implementations
- `Spice86.Core/Emulator/Mcp/EmulatorMcpServices.cs` - Injected services for built-in tools
- `Spice86.Core/Emulator/Mcp/IMcpToolSupplier.cs` - Extension interface for custom tools
- `Spice86.Core/Emulator/Mcp/Response/McpAboutResponse.cs` - Metadata response structure
### Further Reading
- [Model Context Protocol Specification](https://modelcontextprotocol.io/)
- [Spice86 CFG CPU Documentation](cfgcpuReadme.md)
- [Spice86 Internal Debugger Wiki](https://github.com/OpenRakis/Spice86/wiki/Spice86-internal-debugger)
- [Cryogenic Project (MCP Extension Example)](https://github.com/OpenRakis/Cryogenic)
**Quick links:**
- Health check: `http://localhost:8081/health`
- MCP endpoint: `http://localhost:8081/mcp`
- Tool discovery: Call `tools/list` or `mcp_about`

99
docs/spice86/spice86.md Normal file
View file

@ -0,0 +1,99 @@
## Setup
- Spice86 executable: `I:\Apps\Spice86\win-x64\Spice86.exe`
- Test installation: `G:\games\Crusader No Remorse`
- MCP endpoint: `http://localhost:8281/mcp`
- Spice86 HTTP API: `http://127.0.0.1:20000` (started by the tested launch)
- GDB server: `localhost:10000` (started by the tested launch)
- Recorded-data root: `K:\ghidra\Crusader_Decomp\spice86`
Use the installed GOG game directory as the emulated C: drive. The standalone
repository executable is not a substitute for this installation when testing
game startup.
## Launch
Run from PowerShell:
```powershell
& 'I:\Apps\Spice86\win-x64\Spice86.exe' `
-c 'G:\games\Crusader No Remorse' `
-e 'G:\games\Crusader No Remorse\CRUSADER.EXE' `
-a '-warp 0 23807 25343 0 -mapoff 13' `
-r 'K:\ghidra\Crusader_Decomp\spice86' `
--McpHttpPort 8281
```
The arguments match `dosboxCRUSADER_single.conf`. Spice86 creates a
program-SHA-256 subdirectory beneath the `-r` root. Dumps are written on a
completed emulator run; a directory by itself is not evidence that a dump was
produced.
## First Debug
1. Start the command above and confirm the log says the MCP HTTP server is
listening on port `8281`.
2. Check `http://localhost:8281/health`; the tested response was
`{"status":"ok"}`.
3. Send MCP JSON-RPC requests to `/mcp` with both
`Content-Type: application/json` and
`Accept: application/json, text/event-stream`. Without the `Accept` header,
the initialize request returned HTTP 406. Use the documented sequence:
`initialize`, then `tools/list`.
4. For the first guest stop, call `read_cpu_state` and
`read_disassembly` at the reported `CS:IP`. Check `get_pause_status` before
trying execution controls. Use `read_video_state` or `capture_screenshot`
only if the guest reaches a useful screen.
5. Save the terminal error and MCP state with the run notes. Do not interpret a
healthy MCP endpoint as proof that the game started.
## Test Log
- Spice86 and its HTTP API, MCP endpoint, and GDB server all started with the
installed game. MCP health, initialization, tool discovery, CPU-state reads,
and disassembly reads worked on port `8281`.
- Both the default CPU model and `--CpuModel INTEL_80386` halted before the
game screen at `0257:23D4` with `Invalid opcode 0xF01`. The startup log also
reports an unsuccessful open of `386MAX$$` at `0257:C6F0`; its relationship
to the opcode fault is not confirmed.
- The Spice86 README says 80286 protected mode is not implemented and 80386
support is partial, with protected mode not implemented. This is a likely
compatibility barrier for the game's Phar Lap DOS extender, not yet a
proven explanation for this exact fault.
- A diagnostic retry with `--FailOnInvalidOpcode false` moved the fault to an
uninitialized interrupt vector at `0:0`. Adding `--AllowIvtAddress0` did
not recover: execution repeatedly reported `CALL STACK DEPTH EXCEEDED 1000`
at `0000:002F`. That run was stopped. Do not use these flags as a startup
workaround.
- `--CpuModel INTEL_80386 --Ems false --Xms false` also halted at
`0257:23D4` with the same invalid opcode. It additionally logged an
unhandled `INT 2Fh` subfunction `1687` (DPMI host detection) and missing
`EMMXXXX0`, `EMMQXXX0`, and `$MMXXXX0` names. The memory toggles do not
resolve the CPU/DPMI startup barrier.
- `--CpuModel INTEL_80286 --Ems false --Xms false` produced the same DPMI
probe and opcode halt. Together with the default-memory runs, both CPU
models have now been tested with EMS/XMS on and off; none booted the game.
- A read-only hash check found the installed `CRUSADER.EXE.BAK` has the same
SHA-256 as the standalone executable tried earlier, so it is not a new
binary variant to test.
- The DOSBox profile mounts `GAME.GOG` as D:, while the tested Spice86 command
provides only C:. CD-drive parity remains untested, but it is separate from
the current early CPU/DPMI halt.
- The recorded-data directory
`spice86\97317993EFFE2FAB37C4C10105B3388E5948ECB8001E3340DF87FA0E743214C9`
was created, but was empty when checked. No generated CFG, memory dump, or
C# project has been verified yet.
## Next Run
1. Keep the default invalid-opcode behavior; the ignored-fault path loops at
`0000:002F` rather than booting the game.
2. Further progress with Spice86 likely requires DPMI/protected-mode support;
both CPU models, with EMS/XMS enabled and disabled, stop at the same
instruction. Do not attribute the exact opcode fault to protected mode
without confirming the instruction semantics in a compatible emulator.
3. If the CPU/DPMI barrier is resolved, next test the profile's `GAME.GOG` as
D: because the current Spice86 launch maps only the installed C: directory.
4. Only record generated output as successful after verifying files appear in
the hash subdirectory. The current confirmed success is MCP-based runtime
inspection, not Crusader gameplay or dump generation.