Crusader_Decomp/docs/usecode-unk-format.md
Maddo ffb1918f35 Add tests for controller fire attempt suppression and usecode interpreter functionality
- Enhanced isometric_controls_tests.cpp to include assertions for controller fire attempt suppression under various conditions.
- Added tests for the Usecode interpreter in usecode_vm_tests.cpp, verifying script execution and stack manipulation.
- Introduced a new PowerShell script, clean-old-build-artifacts.ps1, to facilitate the cleanup of old build artifacts in specified directories.
2026-10-08 09:01:31 +02:00

121 lines
No EOL
14 KiB
Markdown

# Crusader USECODE `.unk` Format and Reverse-Engineering Plan
**Status:** Evidence-backed working note; original file grammar remains unresolved
**Last reviewed:** 2026-10-07
**Scope:** Per-unit `.unk` files consumed by the hidden USECODE debugger in No Remorse and No Regret
## Executive Summary
There was no document dedicated to `.unk` reverse engineering. This is now the canonical summary and investigation plan. The most important current conclusion is that `<unit>.unk` is a line-oriented text sidecar loaded by the debugger's source pane, not compiled USECODE and not the input that the game's `RUN` command executes.
The game's loader behavior is much better understood than the contents of an authentic `.unk` file. No authentic retail `.unk` sample is currently documented in the workspace. Existing map-viewer `.unk` outputs are synthesized from extracted bytecode and pseudocode; they prove that the file loader can display suitable text, but they do not recover the original source grammar or conventions.
The immediate goal should be to recover the loader contract and obtain or construct controlled samples. Keep source-display format work separate from VM execution, interpreter state, and any proposed bytecode line-marker injection.
## Current Understanding
### `.unk` is a per-unit text sidecar
The debugger's current-unit path obtains the active unit name from its break-state callstack, appends `.unk`, and resolves the result under the `s_usecode` root. The expected name is therefore of the form `USECODE\\<unitname>.unk`, rather than a fixed shared filename such as `UNKDS.DAT`.
The recovered source-loading path opens the file, reads it into a memory buffer, checks that it looks like text, splits it into lines, and keeps pointers for indexed line access. The source pane, search, go-to-line, click handling, and breakpoint marks use that line table.
This is direct evidence for a text viewer. It is not evidence that `.unk` contains executable bytecode or that the debugger compiles it. In the recovered debugger event handler, `RUN` clears break/step state and resumes the live interpreter; it does not parse the visible `.unk` text.
### Related files are distinct
| File | Current evidence-backed interpretation | Confidence and open point |
|---|---|---|
| `<unit>.unk` | Per-unit text loaded by the debugger source pane. | Text-loading behavior and filename construction are directly recovered; original grammar is unknown. |
| `UNKCOFF.DAT` | Fixed table of 4-byte values interpreted by existing `tools/unkcoffs` scripts as NE far addresses, aligned with intrinsic/function name tables. Remorse is 1,244 bytes (311 entries); Regret is 1,400 bytes (350 entries). | The representation and tool use are observed. Its exact runtime role and full relationship to USECODE remain to be confirmed. It is not the per-unit text file. |
| `UNKDS.DAT` | Small file opened by a separate fixed-name loader in the older usecode/debug support path. Remorse is 66 bytes; Regret is 36 bytes. | Separate loading path and sizes are observed; its internal structure and role remain unknown. It is not a substitute for `<unit>.unk`. |
| `UNKOFF.DAT` | No separate file with this exact name is evidenced in the inspected workspace/game files. | Likely a typo or shorthand for `UNKCOFF.DAT`; keep the names distinct until a sample proves otherwise. |
### Loader behavior and safe-file constraints
The following points are known or strongly supported by recovered loader code and the existing controlled experiments:
- The debugger reads the whole source file into memory and rejects content that fails a text-like sanity check.
- The line splitter searches for `LF` and writes a NUL byte to the byte immediately before each `LF`.
- `CRLF` is the safe observed form: the overwritten byte is `CR`, leaving the line text intact. With bare `LF`, the preceding visible character is overwritten. A file beginning with bare `LF` can write before the start of the input buffer.
- The source-line table is bounded at 5,999 lines in the current debugger/exporter analysis.
- Existing Regret testing reports rejection near an average line length of `0x84` bytes. The exact check, whether this is a strict average, and its relation to total file size still need to be verified.
- The current JS exporter writes ASCII with `CRLF`, avoids a leading blank line, and keeps generated output under the 5,999-line limit. This is a conservative compatibility profile, not a proven complete specification.
Do not infer that all printable DOS bytes, tabs, empty lines, or line-ending styles are accepted merely because the loader has a text path. Their acceptance has not been systematically tested.
## Existing `.unk` Experiments
The map-viewer implementation is the active generated-file path:
- [usecode-unk-exporter.js](../../crusader_map_viewer/map_renderer/src/lib/usecode-unk-exporter.js) constructs per-class text files.
- [usecode-decompiler.js](../../crusader_map_viewer/map_renderer/src/lib/usecode-decompiler.js) writes them under `.cache/usecode/<game>/<source>/.data/` and indexes them in the usecode cache.
- [test-usecode-structuring.mjs](../../crusader_map_viewer/map_renderer/scripts/test-usecode-structuring.mjs) tests generated sparse-line and no-debug-line cases, including `CRLF` and the no-leading-newline safety condition.
- [generate_usecode_unk.py](../tools/generate_usecode_unk.py) is the earlier Python generator and remains useful as historical reference; ongoing changes should follow the JS exporter.
The current generated layout is a research format, not recovered original source:
1. The file name is the uppercased class/unit name, sanitized to at most eight characters, plus `.unk`.
2. Where compiled `LINE_NUMBER` operations are available, the exporter groups decoded instruction summaries by line number and emits sparse line entries. Missing lines are filled with `//` placeholders.
3. The exporter appends a clearly labeled pseudocode appendix for the class's event bodies.
4. Where no line markers exist, a requested dense synthetic line floor can be emitted before the appendix. Regret currently uses a 2,991-line floor for debugger experiments.
5. A generated manifest records whether the line table is recovered, synthetic, or appendix-only.
The current Regret cache contains 477 generated `.unk` files. The manufactured files open in the tested Regret debugger path when the synthetic line floor is present. That confirms useful text-loader compatibility for those files only. `RUN` still crashes because the debugger lacks a valid interpreter-seeded current-entry record and runtime context; changing `.unk` text alone does not fix that separate state problem.
### Compiled line metadata differs by game
The current parser pass finds:
- Remorse: `LINE_NUMBER` operations in all 977 parsed event bodies, with a highest recovered line number of 2,991.
- Regret: no recovered `LINE_NUMBER` operations in the 1,152 parsed event bodies.
Consequently, Remorse can currently provide a bytecode-derived line-number basis, while Regret's generated dense line floor is synthetic. Do not present synthetic Regret rows as original source lines or claim exact source correspondence.
Adding `LINE_NUMBER` opcodes to Regret bytecode is a separate possible experiment, not `.unk` format reconstruction. It would require decoding and rewriting event bodies, adjusting relative branches and event offsets, rebuilding the archive, and testing behavior. Even correct line markers would not create the missing live debugger callstack/runtime state required by `RUN`.
## What Remains Unknown
### File and text representation
- Whether an authentic file uses source code, assembly-like listings, annotated decompilation, or multiple sections.
- Accepted character encodings/code pages, high-bit bytes, tabs, control characters, embedded NULs, and maximum individual-line length.
- Whether `CRLF` is required or merely the safe option implied by the splitter; whether a final newline, blank first/last lines, empty file, or LF-only input is accepted.
- Exact limits and checks for total bytes, line count, average line length, and the reported `0x84` threshold.
- Whether the loader recognizes directives or structured records, or treats every line as display text.
### Source mapping and debugger semantics
- How a compiled `LINE_NUMBER` value maps to a particular row in an authentic `.unk` file.
- How sparse, duplicate, repeated, or out-of-order line markers are represented and resolved.
- Whether several class event slots share one unit listing and how generated/source lines are partitioned among those slots.
- Which operations use file path plus 1-based row, which store a zero-based current-line value, and how that relates to the interpreter's line marker. The break-state stores the current line minus one in at least one recovered path; verify all conversions end to end.
- Whether watch/inspect expressions are parsed from `.unk` text, from compiled debug descriptors, or from both. The formatter also consumes live interpreter frame/source pointers, so file text alone is not sufficient for evaluation.
- The exact relationship between `.unk`, `UNKCOFF.DAT`, `UNKDS.DAT`, symbols, and the current compiled archive.
- Whether original `.unk` files were shipped in any retail, demo, regional, or development release, or were produced only by an internal toolchain.
## Reverse-Engineering Plan
Keep every result qualified by game, executable/archive version, and evidence type. Preserve authentic files unchanged and run file-mutation experiments only against disposable copies.
1. **Find authentic samples.** Search retail, demo, regional, patch, and development media/install layouts for `USECODE\\*.unk`, archives containing `.unk` entries, and build-tool outputs. Record exact provenance, path, size, hash, timestamps if meaningful, and the matching executable/archive. If none are found, explicitly limit conclusions to the game's text-loader contract.
2. **Close the static loader path.** In both available executable families, trace path construction, open/read, text sanity checks, line splitting, line-pointer lookup, drawing, search, go-to-line, breakpoint display/toggle, and source-buffer destruction. Recover exact arithmetic and bounds for file size, line count, average/individual line lengths, allocation, terminators, and error cases.
3. **Build a controlled input matrix.** In a disposable game copy, vary one property at a time: ASCII/high-bit bytes, CRLF/LF, final newline, empty file, leading/trailing blank lines, tabs, embedded NUL, long lines, line count, average length, and total size. Record whether the file opens, renders without corruption, supports search/navigation, and survives breakpoint operations. An open-only test is not full acceptance.
4. **Recover the line contract.** Use Remorse bytecode with known `LINE_NUMBER` markers and controlled debugger breakpoints. Compare the runtime marker, break-state line field, requested source row, highlighted row, and breakpoint row. Verify zero/one-based conversions, gaps, duplicate markers, and behavior past the final mapped line.
5. **Separate source text from expression/debug metadata.** Trace watch, inspect, symbol lookup, and current-frame formatting. Identify which inputs come from `.unk`, which come from compiled descriptors or tables, and which require live frame pointers. Do not invent source directives to explain data that is actually held elsewhere.
6. **Use Regret as a distinct case.** First establish whether authentic Regret `.unk` samples or debug-line metadata exist. Keep the current synthetic 2,991-line scaffold labeled as synthetic. If testing injected `LINE_NUMBER` opcodes, use a separate bytecode-rewriter experiment and verify branch/event relocation independently.
7. **Implement a validator and fixtures.** Add a small parser/validator in the map-viewer tooling only after the observed grammar is stable. Fixtures should cover accepted and rejected files, exact line offsets, encoding/newline cases, limits, and provenance (`authentic`, `generated`, `synthetic`). Continue testing generated output separately from authentic-file compatibility.
8. **Publish a versioned format note.** Record confirmed rules, unresolved hypotheses, sample hashes, and test results. Promote a rule from “inferred” to “observed” only when supported by an authentic sample, direct executable behavior, or a repeatable runtime test.
### First-pass effort
The first loader-and-source-mapping pass is estimated at **1-2 engineer-weeks** with access to the existing Ghidra analysis and a controllable game test. Authentic sample discovery is the main schedule risk. If original samples remain unavailable, static and black-box work can still establish safe text constraints, but cannot recover the original source grammar, symbol naming, or compiler conventions.
## Evidence and Related Work
- [Regret hidden debugger investigation](./regret-hidden-debugger-investigation.md): source loader, generated corpus, Regret open/RUN experiments, and debugger-state boundary.
- [Retail debugger entry options](./retail-debugger-entry-options.md): Remorse source pane, line navigation, breakpoint, and watch behavior.
- [Standalone debugger proposal](./standalone-usecode-debugger.md): map-viewer integration and VM effort plan.
- [USECODE format specification](./usecode-format-specification.md): archive, class/event, bytecode, and `LINE_NUMBER` evidence.
- [USECODE decompiler/recompiler roadmap](./usecode-roundtrip-ir.md): source snapshots, archive round trips, and current tooling limits.
- [UNKCOFF translation utility](../tools/unkcoffs/unk_translate.py): interpretation of `UNKCOFF.DAT` entries as far addresses.