Crusader_Decomp/docs/regret-crudebug-investigation.md

121 lines
18 KiB
Markdown
Raw Normal View History

# CRUDEBUG in No Remorse and No Regret
## Finding
`CRUDEBUG` is a DOS environment variable read during kernel initialization. If its value is `TRUE` (case-insensitive), the game sets byte `1480:4415`. That byte gates a kernel-level breakpoint path and, together with Scroll Lock, two debug-conditional update paths.
This is distinct from the hidden usecode debugger object at `1480:712c/712e`, and distinct from the cheat-state globals. The shipped launch configuration passes `-debug` to `REGRET.EXE`, and the executable contains that switch string, but the static analysis found no code reference connecting the argument to `CRUDEBUG` or `1480:4415`. The effect of `-debug` itself remains unresolved; this is not proof that the argument is ignored.
## Initialization
`game_startup_main` (`1058:0521`) calls `kernel_initialize` (`11e8:000c`). That routine:
1. Calls `dos_environment_get_variable` (`1000:6173`) to look up `CRUDEBUG` in the DOS environment.
2. If present, compares the value with the string `TRUE` at `1480:44d1` using case-insensitive comparison.
3. Writes `1` to `1480:4415` only when the value matches.
The data-use scan found exactly one write to `1480:4415`, at `11e8:005e`, and two reads. No other writer or reset was found. The installed `dosbox-automation.conf` and `dosboxREGRET_single.conf` launch the game with `-debug`; neither sets `CRUDEBUG`. The dedicated test config omits `-debug` and sets `CRUDEBUG=TRUE` immediately before `REGRET.EXE -warp 1 -egg 250`.
To request this kernel gate in a DOS session, the relevant mechanism is an environment assignment such as `SET CRUDEBUG=TRUE` before launching the game. The command-line token is not equivalent on the evidence currently recovered.
## What The Flag Gates
### Breakpoint Interrupt
`Key_HandleOptionKeys` (`1148:09fd`) handles an Escape key event (scancode `1`) with event modifier bits `0x04` and `0x08` both set. These positions match the BIOS keyboard shift-byte flags for Ctrl and Alt, making the intended chord Ctrl+Alt+Esc. The event-field producer was not traced end to end, so the physical-key interpretation is strong but not runtime-verified. Scroll Lock is not required for this branch. The handler first calls `keyboard_flush_pending_events_and_sync_modifiers` (`11e8:33e3`), then checks `1480:4415` at `1148:0cac`:
- If the flag is clear, control reaches the shared false-return epilogue at `1148:1608` and returns `0` without trapping.
- If set, it writes `1` to `g_cycleProcess+0x40` and executes `INT 3` at `1148:0cbf`.
This is a software interrupt path, not a call to the hidden usecode debugger's open functions. No reference from this branch to the debugger global, UI, or bootstrap was found. `INT 3` asks the CPU to dispatch vector 3. In DOSBox's real mode, DOS setup points IVT vector 3 at `0070:00f4`, a one-instruction `IRET` stub. In protected mode, DOSBox instead dispatches through IDT entry 3, which belongs to the guest runtime or extender. `REGRET.EXE` is a 16-bit NE image, and the extender's protected-mode IDT setup is outside the loaded Ghidra image; no game-image vector-3 setter was recovered. Therefore the real-mode IRET result cannot be assumed for this protected-mode game. If the handler returns, execution resumes after `INT 3`; DOSBox's optional emulator debugger can intercept first only when compiled in and a matching emulator breakpoint exists. The installed executable's build options and actual IDT handler were not verified. Relevant implementation: [prefix_none.h](../../dosbox-automation/src/cpu/core_normal/prefix_none.h), [cpu.cpp](../../dosbox-automation/src/cpu/cpu.cpp), and [dos_memory.cpp](../../dosbox-automation/src/dos/dos_memory.cpp).
The returning path is also meaningful. Because `g_cycleProcess+0x40` was just set, the handler takes the path at `1148:0ccd` through `1148:0cf4`. If the current controlled NPC is not number `1`, it calls `Engine_ClearUnkFlagA1_ProbablyCruStasis`, which clears `g_cruStasis` and flushes pending keyboard events. It then calls `World_SetControlledNPCNum(1)` and returns `1`, consuming the key event. That routine switches control/camera to NPC `1` when needed and clears the previous NPC's combat state. So, if vector 3 returns, the game-side effect is to return control to NPC `1` (and clear CruStasis when switching away from another NPC), after setting the cycle-process byte. It still does not open the usecode debugger. If vector 3 does not return, this continuation does not run.
### Conditional Update Paths
`kernel_debug_shift_gate_active` (`11e8:343c`) returns true only when both `g_keyboardShiftState & 0x10` and `1480:4415` are nonzero. `Keyboard_GetShiftState` (`11e8:3456`) reads BIOS data byte `0040:0017`, where bit `0x10` is the Scroll Lock toggle; the keyboard synchronization path copies that state into `g_keyboardShiftState`. So both update gates require `CRUDEBUG=TRUE` and Scroll Lock active.
Two routines call this predicate:
- `keyboard_process_dispatch_timed_callbacks` (`11d0:00f4`) has a keyed-dispatch path before the gate. On its timed-event path, the predicate is checked before it scans two `0x80`-slot, six-byte event tables at `DS:3db4` and `DS:40b4`. When true, those timed entries are not scanned or dispatched on that invocation. This does not pause the whole game or block the earlier keyed-dispatch path. The table entries are untouched before the gate, but whether overdue callbacks are replayed or skipped as time advances has not been runtime-tested. Its function pointer occurs at `1480:371e`, adjacent to the `KeyboardProcess` class label at `1480:3733`; no direct call xref was recovered.
- `fade_process_update_palette` (`1410:011b`) checks it before its palette-cycle callback. When allowed to run, it rotates game-palette entries `1..7` one position (`1 <- 2`, ..., `6 <- 7`, `7 <- 1`). It also advances seven persistent RGB states for palette entries `8..14`: entries `8` and `10` step red by 2; `9` and `11` step blue by 2; `12` steps all three channels; `13` and `14` step green. The channels wrap to zero after exceeding `63` (VGA's 6-bit DAC range). Entry `13` additionally adds an independent random value from `0..9` to each channel whenever its green channel wraps, masking each result back into `0..63`. The initial state starts entries `10` red and `11` blue at `31`; the other channels start at zero.
After updating the game-palette buffer, `fade_palette_write_vga_dac_entry` (`1410:0366`) writes each color in entries `1..14` to VGA DAC ports `0x3c8/0x3c9`. The installed `GAMEPAL.PAL` starts entries `8..14` at `(0,0,63)`, `(63,17,63)`, `(21,20,19)`, `(41,20,0)`, `(29,47,63)`, `(63,51,63)`, and `(63,50,63)`, respectively. The callback begins replacing these stock blue, magenta, gray, orange, and cyan shades with the animated states on its first update. When the CRUDEBUG+Scroll Lock predicate is true, it returns before rotating colors, advancing the RGB states, or writing the DAC. Those entries therefore remain at their last uploaded colors for this callback. This is a local palette-cycle freeze, not a pause of rendering or every palette operation; the separate full-palette interpolation routine `FadeProcess_1418_03d5` does not check this predicate. The callback pointer at `1480:745f` is adjacent to the `FadeProcess` label at `1480:7466`.
These are kernel/input/timing and palette behaviors. They do not open the usecode debugger.
## No Remorse Comparison (`CRUSADER.EXE`)
The DOS No Remorse image loaded in Ghidra also implements `CRUDEBUG`; this is not merely a string left beside the separate hidden usecode debugger.
### Initialization And Breakpoint Path
`Kernel_Init` (`11d0:000c`) calls `dos_environment_get_variable` (`1000:61ff`) with `CRUDEBUG` at `1478:3a62`. If the variable exists, it compares the returned value case-insensitively with `TRUE` at `1478:3a6b`, then sets `g_cruDebugEnabled` at `1478:39af` when they match. The data-use scan found one write to this flag in `Kernel_Init` and reads in `Key_HandleOptionKeys` and `kernel_debug_shift_gate_active`.
`Key_HandleOptionKeys` (`1130:0896`) has the same Ctrl+Alt+Esc structure as No Regret: it checks Escape plus event modifier bits `0x04` and `0x08`, tests `g_cruDebugEnabled`, sets the cycle-process byte at `+0x40`, and executes `INT3` at `1130:0a03`. Scroll Lock is not part of this branch. If the interrupt returns, the continuation switches control to NPC 1 when necessary and consumes the event. The protected-mode vector-3 destination remains unverified for this build too.
**Runtime breakpoint capture (2026-10-08):** A live byte-signature match established selector `0x1130`'s physical base as `0x1D1EE0` for this session. The address converter maps `1130:0A03` to physical `0x1D28E3` (`mcp_offset=1911011`); the surrounding bytes matched Ghidra, and a direct read at that address returned `CC`. With native breakpoint `BP 0000 001D28E3` armed, Ctrl+Alt+Esc opened the DOSBox debugger. `BPLIST` returned `0000 1D28E3`, confirming the listed breakpoint is at the translated target. Initially, the code overview showed `02AF:0A03 CC int 03`, while the register panel showed `CS=02AF`, `EIP=00000003`. This was a code-view cursor mismatch, not an address-translation error: the native debugger's `C` command sets only `codeViewData.useCS/useEIP`; it does not change the guest CPU registers. The view had been left at the breakpoint site. Entering `C 02AF 00000003` aligned the view with the register IP and showed `push word [bp+06]; nop; push cs; call 02AF:2C09; add sp,0002; pop bp; retf`. This handler-like stub is consistent with protected-mode vector-3 dispatch, but the IDT mapping is not yet verified. The output included `DEBUG: Internal error while deactivating breakpoint.` DOSBox emits this warning when removing a breakpoint whose saved original byte is already `0xCC`; the native breakpoint still triggered. MCP reported `features.debugger=false`, and `mem_read` returned HTTP 500 while the debugger was paused. This base is session-specific and must be re-established after a restart.
### Scroll Lock Consumers
No Remorse's `kernel_debug_shift_gate_active` (`11d0:3412`) returns true when both `g_keyboardShiftState & 0x10` and `g_cruDebugEnabled` are set. `read_bios_keyboard_shift_cache` (`11d0:39e6`) refreshes that word through BIOS `INT 16h`, function `12h`.
The predicate gates two paths in the inspected No Remorse image:
- `CycleProcess_Update` (`1438:014a`) advances the rotating palette entries and seven RGB cycle states only when the predicate is false. When it runs, it updates game-palette entries `1..14` and uploads them to the VGA palette. At this broad level it matches No Regret's `fade_process_update_palette`: `CRUDEBUG=TRUE` plus Scroll Lock active suppresses the global cycle update.
- `KeyboardProcess_GenerateHeldKeyRepeatEvents` (`11b8:00f4`) calls the predicate at `11b8:015e` and exits the repeat-generation path when it is true. This is a verified difference from the No Regret callers documented above: No Remorse suppresses synthesized held-key repeats here, while No Regret's corresponding gate skips scans of two timed-event tables.
The user directly verified that the shield item's lights stop blinking with Scroll Lock disabled and resume blinking when it is enabled; screenshots do not reveal this animation. That object-specific observation is not explained by the global palette gate alone: with `CRUDEBUG` enabled, the static predicate suppresses `CycleProcess_Update` when Scroll Lock is active. The inspected code does not yet establish that the shield lights use this palette cycle, so keep the observation separate until their update path is traced.
Runtime testing disproved a whole-game pause in the No Remorse test room. With `CRUDEBUG=TRUE` confirmed in guest memory and BIOS shift-state byte `0040:0017` equal to `0x30` (Scroll Lock bit `0x10` set), a mouse click moved the player and the scene updated. The gate suppresses the specific cycle and held-key-repeat paths above; it does not stop all simulation or input processing.
### Summary Of Differences
The environment lookup, case-insensitive `TRUE` test, debug flag, and Ctrl+Alt+Esc/`INT3` path are present in both DOS builds. Their segment offsets and flag addresses differ, as expected. The meaningful behavior difference recovered so far is the Scroll Lock consumer: No Remorse suppresses held-key repeat generation; No Regret suppresses timed-event table scans. Both builds also gate their global palette-cycle updater. This pass does not determine whether No Remorse's `-debug` command-line switch also enables `CRUDEBUG`.
## Cheat-System Relationship
There is limited adjacency, but no shared activation state was found. The `INT 3` check is inside the same broad `Key_HandleOptionKeys` routine that also handles ordinary game option keys. Later in that routine, the F10 cheat path reads `1480:0adc` and checks the separate cheat latch at `1480:009b` before continuing into cheat handling.
The secret-sequence handler `Key_CheckSecretCodeSequences` reads and writes the cheat-active state at `1480:0ac0` and writes `1480:009b`. Neither it nor the F10 path references `1480:4415`. Conversely, the only direct references to `1480:4415` are the environment initialization, the Escape/`INT 3` branch, and `kernel_debug_shift_gate_active`.
So `CRUDEBUG` is not a cheat code, does not enable the secret-sequence system, and does not share its latches. Its breakpoint check merely coexists with cheat handling in the game's keyboard subsystem.
## Relationship To `-debug`
The argument string `-debug` exists at `1480:0b43` in a far-pointer/string pool alongside switches such as `-warp`, `-skill`, and `-egg`. The installed launch configs pass it directly to the game:
- `F:\Apps\Crusader No Regret\dosbox-automation.conf`: `REGRET.EXE -warp 1 -egg 250 -debug`
- `F:\Apps\Crusader No Regret\dosboxREGRET_single.conf`: same game arguments
- `F:\Apps\Crusader No Regret\dosbox-automation-test.conf`: omits `-debug`; sets `CRUDEBUG=TRUE` before the game command
The `-debug` string at `1480:0b43` is referenced by a far pointer at `1480:0af1` in the static switch-string table. No code xref or other recovered code use of that entry was found. The table pointer itself is not referenced by a recovered instruction scan as a command-line parser input. The other nearby switch strings likewise lack recovered direct consumers. The only writer to the kernel flag remains the environment comparison at `11e8:005e`; no command-line path to that write was recovered.
One startup routine initially looked like an argument parser: `test_dos_file_handle_capacity` (`1058:024f`) reads a static `FHACK%d` template, exercises DOS file create/close operations, and checks the configured file-handle limit. It is not evidence that `-debug` is parsed or that it sets `CRUDEBUG`.
The defensible conclusion is **no static link found**. `-debug` may be handled by a runtime/loader path or may control a separate game debug mode, but its consumer and effect are not established by the current Ghidra references. In particular, the fact that both names contain “debug” does not establish that `-debug` sets `CRUDEBUG`.
## `DEBUGGER.C` String
The bytes at `1480:7130` spell `DEBUGGER.C`, adjacent to the hidden debugger global at `1480:712c/712e` and the base vtable at `1480:713b`. Ghidra reports no data uses or xrefs to the string. It may be a compiler/assertion source-file marker, but its purpose is not proven; it is not evidence of a command-line handler or an active C source file in the executable.
## Verification And Open Questions
The live Ghidra databases now name the verified No Remorse helpers `dos_environment_get_variable` (`1000:61ff`) and `kernel_debug_shift_gate_active` (`11d0:3412`), alongside the previously named No Regret helpers. No executable bytes were changed.
No Regret runtime testing used its dedicated profile: guest memory contained `CRUDEBUG=TRUE`, and the game reached the Mission 1 staging room. One Ctrl+Alt+Esc sequence with Scroll Lock active was followed by another staging-room frame; DOSBox continued to report `REGRET` running with no shutdown request. This rules out an immediate visible trap but does not establish the protected-mode vector-3 handler's exact behavior.
No Remorse runtime testing used `dosbox-automation-crudebug-test.conf` and the debug-named DOSBox build `dosbox-automation-debugger.exe` (`0.85.1 (6d100)`). The profile set `CRUDEBUG=TRUE` and launched `CRUSADER.EXE -warp 1 -egg 250`; guest memory confirmed the environment string and the game reached the test room. MCP input toggled the BIOS Scroll Lock bit from clear to set, confirming that events reached the guest. Before a native breakpoint was armed, Ctrl+Alt+Esc left the game visible and running; the player appeared at a different position, consistent with the game's returning control-switch path, though the NPC index was not independently read. After the verified breakpoint at physical `0x1D28E3` was armed, sending the chord opened the native DOSBox debugger. A subsequent mouse click had already confirmed that the game continued processing input with Scroll Lock active.
Although the running executable was the debug-named build, MCP reported `features.debugger=false`, so debugger pause state could not be queried through MCP. An MCP memory read returned HTTP 500 while the native debugger was paused. The DOSBox `is_booted`/`is_shell` status fields also remained inaccurate for the visible graphics session. The protected-mode vector-3 destination and exact NPC-switch result remain unverified. The shield-light update path is still open.
### Next Checks
1. Trace the shield item's light animation to its update/render path and determine whether it shares `CycleProcess_Update` palette entries or another timer.
2. Sample VGA DAC entries `1..14` in No Remorse with the Scroll Lock gate active and inactive to test the cycle updater directly.
3. Inspect the call target `02AF:2C09` to identify the handler work and verify whether the `02AF:0003` stub is the protected-mode vector-3 entry.
4. Inspect the No Remorse controlled-NPC value before and after Ctrl+Alt+Esc to confirm whether the observed player change is the static NPC-1 path.
5. Hold a repeating key with `CRUDEBUG` and Scroll Lock enabled to verify the No Remorse repeat-suppression branch.
6. Use the native debugger to inspect protected-mode vector 3 and determine whether its return reaches the NPC-1 continuation.
Related: [regret-hidden-debugger-investigation.md](regret-hidden-debugger-investigation.md).