tooling: harden bounds in bink_heap_aot and add synthetic PE32+ unit and refusal suite #1901

Merged
Ammmae0x merged 2 commits from upstream-pr/1908 into main 2026-11-24 21:17:07 +00:00
Ammmae0x commented 2026-11-24 20:49:09 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by Ammmae0x on 2026-11-24T20:49:09Z.


Change

Harden bounds and CLI error handling in tools/bink_heap_aot.py and add a synthetic AMD64 PE32+ unit and refusal suite in tests/bink_heap_aot_check.py registered as bink_heap_aot_check in CMakeLists.txt:

  • Guard missing DIRECTORY_ENTRY_IMPORT in translate() with a clear ValueError("image has no import directory") instead of raising AttributeError.
  • Validate executable thunk bytes up front in import_name() via image_bytes(pe, target, 6, executable=True) before decoding the IAT thunk jump.
  • Extract main(argv=None) in tools/bink_heap_aot.py and handle ValueError, OSError, and pefile.PEFormatError via parser.exit(1, ...) instead of emitting raw tracebacks.
  • Add tests/bink_heap_aot_check.py with positive lowering controls (callback_setter(), translate(), group_caller(), generate(), --entries / --group-entry CLI mode) and negative refusal controls (non-writable, truncated, non-null, and duplicate callback slots; unexpected heap imports; missing import directory; unmapped, non-executable, and truncated IAT thunk targets; missing or duplicate heap transfers; non-AMD64/PE32 inputs; invalid CLI output/input paths).

Verification

  • python -B tests/bink_heap_aot_check.py -v: Ran 12 tests in 2.244s — OK.
  • cmake --preset dev + cmake --build --preset dev --target cpu_bink_heap_lifted cpu_bink_heap cpu_bink_heap_provider + ctest --preset dev --no-tests=error -R "^(bink_heap_aot_check|cpu_aot_bink_heap|cpu_aot_bink_group)$" --output-on-failure: 3/3 passed (cpu_aot_bink_heap, cpu_aot_bink_group, bink_heap_aot_check).
  • cmake --preset release + cmake --build --preset release --target cpu_bink_heap_lifted cpu_bink_heap cpu_bink_heap_provider + ctest --preset release --no-tests=error -R "^(bink_heap_aot_check|cpu_aot_bink_heap|cpu_aot_bink_group)$" --output-on-failure: 3/3 passed (cpu_aot_bink_heap, cpu_aot_bink_group, bink_heap_aot_check).
  • python -B tests/form_coverage_check.py: passed.
  • python -B tests/docs_links_check.py: passed (Checked 18 Markdown files and 377 links.).
  • python -B tests/bidi_controls_check.py: passed (Checked 1338 tracked source, script and build/CI files: no bidirectional controls.).

Evidence and follow-up

  • tests/bink_heap_aot_check.py synthesizes 100% self-contained in-memory AMD64 PE32+ images with struct/pefile; no external binaries or proprietary files are used.
  • Mutation sanity checks reverting the DIRECTORY_ENTRY_IMPORT guard and pre-decode image_bytes() check confirmed test_missing_import_directory_raises_value_error and test_import_name_thunk_bounds_rejected fail without the hardening.

Checklist

  • This pull request covers one reviewable behavior.
  • I included the exact command and result for every check I ran.
  • I considered a negative control or failure case for a new fixture.
  • I updated README/docs when a capability or build requirement changed. (N/A: test and bounds-hardening only)
  • I did not include game files, dumps, distribution links or secrets.

AI-assisted.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:issue:6591120045 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1908). Originally posted by [Ammmae0x](https://github.com/Ammmae0x) on 2026-11-24T20:49:09Z. --- ## Change Harden bounds and CLI error handling in `tools/bink_heap_aot.py` and add a synthetic AMD64 PE32+ unit and refusal suite in `tests/bink_heap_aot_check.py` registered as `bink_heap_aot_check` in `CMakeLists.txt`: - Guard missing `DIRECTORY_ENTRY_IMPORT` in `translate()` with a clear `ValueError("image has no import directory")` instead of raising `AttributeError`. - Validate executable thunk bytes up front in `import_name()` via `image_bytes(pe, target, 6, executable=True)` before decoding the IAT thunk jump. - Extract `main(argv=None)` in `tools/bink_heap_aot.py` and handle `ValueError`, `OSError`, and `pefile.PEFormatError` via `parser.exit(1, ...)` instead of emitting raw tracebacks. - Add `tests/bink_heap_aot_check.py` with positive lowering controls (`callback_setter()`, `translate()`, `group_caller()`, `generate()`, `--entries` / `--group-entry` CLI mode) and negative refusal controls (non-writable, truncated, non-null, and duplicate callback slots; unexpected heap imports; missing import directory; unmapped, non-executable, and truncated IAT thunk targets; missing or duplicate heap transfers; non-AMD64/PE32 inputs; invalid CLI output/input paths). ## Verification - `python -B tests/bink_heap_aot_check.py -v`: `Ran 12 tests in 2.244s` — `OK`. - `cmake --preset dev` + `cmake --build --preset dev --target cpu_bink_heap_lifted cpu_bink_heap cpu_bink_heap_provider` + `ctest --preset dev --no-tests=error -R "^(bink_heap_aot_check|cpu_aot_bink_heap|cpu_aot_bink_group)$" --output-on-failure`: `3/3` passed (`cpu_aot_bink_heap`, `cpu_aot_bink_group`, `bink_heap_aot_check`). - `cmake --preset release` + `cmake --build --preset release --target cpu_bink_heap_lifted cpu_bink_heap cpu_bink_heap_provider` + `ctest --preset release --no-tests=error -R "^(bink_heap_aot_check|cpu_aot_bink_heap|cpu_aot_bink_group)$" --output-on-failure`: `3/3` passed (`cpu_aot_bink_heap`, `cpu_aot_bink_group`, `bink_heap_aot_check`). - `python -B tests/form_coverage_check.py`: passed. - `python -B tests/docs_links_check.py`: passed (`Checked 18 Markdown files and 377 links.`). - `python -B tests/bidi_controls_check.py`: passed (`Checked 1338 tracked source, script and build/CI files: no bidirectional controls.`). ## Evidence and follow-up - `tests/bink_heap_aot_check.py` synthesizes 100% self-contained in-memory AMD64 PE32+ images with `struct`/`pefile`; no external binaries or proprietary files are used. - Mutation sanity checks reverting the `DIRECTORY_ENTRY_IMPORT` guard and pre-decode `image_bytes()` check confirmed `test_missing_import_directory_raises_value_error` and `test_import_name_thunk_bounds_rejected` fail without the hardening. ## Checklist - [x] This pull request covers one reviewable behavior. - [x] I included the exact command and result for every check I ran. - [x] I considered a negative control or failure case for a new fixture. - [ ] I updated README/docs when a capability or build requirement changed. (N/A: test and bounds-hardening only) - [x] I did not include game files, dumps, distribution links or secrets. AI-assisted.
upstream-sync closed this pull request 2026-11-24 21:27:31 +00:00
tedin7 commented 2026-11-24 21:27:32 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T21:02:06Z.

Review: COMMENTED


Review of exact head fd8dfcf1400725be8cb3fb3accf37eadc77e1a6c (base main). Scope: tools/bink_heap_aot.py (+21/-6), new tests/bink_heap_aot_check.py (+495), CMakeLists.txt (+2). Comment only, no approval.

Verdict: no P1/P2 found. Looks good to me from a correctness and test-strength standpoint; one P3 behaviour note below.

Clean-room / title

  • Title is neutral and describes the change. Fixtures are synthetic PE32+ images built byte by byte in the test (no vendor bytes, no extracted data). Names used (XMemAlloc, XMemFree, BinkSetMemory) already exist in the tool.

What I checked in the diff

  • import_name (tools/bink_heap_aot.py:19-22): the 6-byte thunk read now goes through image_bytes(..., executable=True) BEFORE decoding. Previously pe.get_data ran first and the bounds check only ran after a successful jmp [rip+x] match, so an unmapped, non-executable or section-truncated branch target was decoded silently. The old post-hoc image_bytes(pe, target, thunk.len, ...) is correctly removed (it was redundant, since 6 bytes are now covered).
  • translate: getattr(pe, "DIRECTORY_ENTRY_IMPORT", None) plus a ValueError replaces an AttributeError traceback on images without an import directory. Correct.
  • main(argv=None): exits 1 with a message on ValueError/OSError/PEFormatError; parser.error paths still exit 2. The output file is only written after generate succeeds (the write_text argument is evaluated first), so a failure leaves no partial .cpp. The test asserts this (assertFalse(out_cpp.exists())).

Commands run locally (venv x2w-rev-venv, worktree at the exact SHA, git rev-parse HEAD == headRefOid)

  • git diff --check origin/main...HEAD -> exit 0, no output
  • python -B tests/bink_heap_aot_check.py -v -> Ran 12 tests ... OK
  • python -B tests/bidi_controls_check.py -> Self-test passed. Checked 1339 tracked ... files: no bidirectional controls.
  • python -B tests/docs_links_check.py -> Self-test passed. Checked 18 Markdown files and 377 links.
  • x2w_pipe.py win2025 1908 --targets cpu_bink_descriptors,...,xmem_shim --regex '^(bink_heap_aot_check|cpu_aot_bink_group|cpu_aot_bink_heap|cpu_bink_descriptors|cpu_bink_frame_planes|cpu_bink_frame_to_heap)$' (Windows Server 2025, MSVC 14.44.35207): Debug and Release both 6/6 passed, including the new bink_heap_aot_check (ctest #1161, ~1.8 s) and the real-image cpu_aot_bink_heap / cpu_aot_bink_group, so the generated output for real inputs is unchanged in practice.

Mutation testing (each applied to the PR head, suite re-run, then git checkout -- .)

# Mutation Result
M1 import_name back to pe.get_data(target, 6) FAILED: test_import_name_thunk_bounds_rejected
M2 drop executable=True on the thunk read FAILED: same test
M3 if not imports: -> if False: FAILED: test_missing_import_directory_raises_value_error
M4 main() except clause narrowed to KeyError FAILED: test_cli_rejects_invalid_output_and_missing_input
M5 check_callback_slot bound offset + 8 -> offset + 4 FAILED: test_truncated_callback_slot_rejected
M6 CLI error exit code 1 -> 0 FAILED: test_cli_rejects_invalid_output_and_missing_input

All six mutants are killed, so the new tests do guard the hardened behaviour (including the three thunk-bound cases: unmapped, non-executable, truncated).

P3 (non-blocking) tools/bink_heap_aot.py:19

import_name is called for every CALL/JMP with a near-branch operand in leaf_body and translate, not only for IAT thunks. Because the 6-byte read now raises instead of returning None, a perfectly valid internal call/jmp whose target is a tiny function in the last 1 to 5 file-backed bytes of an executable section (e.g. a 3-byte xor eax,eax; ret at the end of .text) now aborts generation with ValueError: invalid file-backed range at RVA ... instead of being treated as "not an import". I reproduced it on a synthetic image (text_vsize=0x300, target TEXT_RVA+0x2fd -> ValueError ... 0x12fd). It fails closed (a clear error, never wrong output) and the real Bink images in CI are unaffected (tests above pass), so I would not block on it. If you want to keep the old tolerance, read min(6, available) bytes for the probe and only enforce the full range once a jmp [rip+x] has decoded. Otherwise a one-line comment stating that stricter behaviour is intended would help.

Nits

  • main() catches ValueError/OSError/PEFormatError only; other malformed-image failures (e.g. struct.error, IndexError from pefile) would still print a traceback. A truncated-file probe I ran exits 1 cleanly, so this is only a robustness remark.
  • add_test(NAME bink_heap_aot_check ...) has no TIMEOUT, unlike the neighbouring Python tests (e.g. pe_run_package_trap_missing sets 60). The test runs in ~1.9 s, so this is cosmetic.
  • test_import_name_thunk_bounds_rejected only asserts ValueError without a message; the three sub-cases could pass for the wrong reason if another ValueError were raised. Mutations M1/M2 show they currently do fail for the right reason.

AI-assisted; commands listed were executed locally.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review:6047347836 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1908#pullrequestreview-6047347836). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T21:02:06Z. **Review:** COMMENTED --- Review of exact head `fd8dfcf1400725be8cb3fb3accf37eadc77e1a6c` (base `main`). Scope: `tools/bink_heap_aot.py` (+21/-6), new `tests/bink_heap_aot_check.py` (+495), `CMakeLists.txt` (+2). Comment only, no approval. **Verdict: no P1/P2 found. Looks good to me from a correctness and test-strength standpoint; one P3 behaviour note below.** ### Clean-room / title - Title is neutral and describes the change. Fixtures are synthetic PE32+ images built byte by byte in the test (no vendor bytes, no extracted data). Names used (`XMemAlloc`, `XMemFree`, `BinkSetMemory`) already exist in the tool. ### What I checked in the diff - `import_name` (tools/bink_heap_aot.py:19-22): the 6-byte thunk read now goes through `image_bytes(..., executable=True)` BEFORE decoding. Previously `pe.get_data` ran first and the bounds check only ran after a successful `jmp [rip+x]` match, so an unmapped, non-executable or section-truncated branch target was decoded silently. The old post-hoc `image_bytes(pe, target, thunk.len, ...)` is correctly removed (it was redundant, since 6 bytes are now covered). - `translate`: `getattr(pe, "DIRECTORY_ENTRY_IMPORT", None)` plus a `ValueError` replaces an `AttributeError` traceback on images without an import directory. Correct. - `main(argv=None)`: exits 1 with a message on `ValueError/OSError/PEFormatError`; `parser.error` paths still exit 2. The output file is only written after `generate` succeeds (the `write_text` argument is evaluated first), so a failure leaves no partial `.cpp`. The test asserts this (`assertFalse(out_cpp.exists())`). ### Commands run locally (venv `x2w-rev-venv`, worktree at the exact SHA, `git rev-parse HEAD` == `headRefOid`) - `git diff --check origin/main...HEAD` -> exit 0, no output - `python -B tests/bink_heap_aot_check.py -v` -> `Ran 12 tests ... OK` - `python -B tests/bidi_controls_check.py` -> `Self-test passed. Checked 1339 tracked ... files: no bidirectional controls.` - `python -B tests/docs_links_check.py` -> `Self-test passed. Checked 18 Markdown files and 377 links.` - `x2w_pipe.py win2025 1908 --targets cpu_bink_descriptors,...,xmem_shim --regex '^(bink_heap_aot_check|cpu_aot_bink_group|cpu_aot_bink_heap|cpu_bink_descriptors|cpu_bink_frame_planes|cpu_bink_frame_to_heap)$'` (Windows Server 2025, MSVC 14.44.35207): Debug and Release both **6/6 passed**, including the new `bink_heap_aot_check` (ctest #1161, ~1.8 s) and the real-image `cpu_aot_bink_heap` / `cpu_aot_bink_group`, so the generated output for real inputs is unchanged in practice. ### Mutation testing (each applied to the PR head, suite re-run, then `git checkout -- .`) | # | Mutation | Result | |---|---|---| | M1 | `import_name` back to `pe.get_data(target, 6)` | FAILED: `test_import_name_thunk_bounds_rejected` | | M2 | drop `executable=True` on the thunk read | FAILED: same test | | M3 | `if not imports:` -> `if False:` | FAILED: `test_missing_import_directory_raises_value_error` | | M4 | `main()` except clause narrowed to `KeyError` | FAILED: `test_cli_rejects_invalid_output_and_missing_input` | | M5 | `check_callback_slot` bound `offset + 8` -> `offset + 4` | FAILED: `test_truncated_callback_slot_rejected` | | M6 | CLI error exit code 1 -> 0 | FAILED: `test_cli_rejects_invalid_output_and_missing_input` | All six mutants are killed, so the new tests do guard the hardened behaviour (including the three thunk-bound cases: unmapped, non-executable, truncated). ### P3 (non-blocking) `tools/bink_heap_aot.py:19` `import_name` is called for every `CALL`/`JMP` with a near-branch operand in `leaf_body` and `translate`, not only for IAT thunks. Because the 6-byte read now raises instead of returning `None`, a perfectly valid internal call/jmp whose target is a tiny function in the last 1 to 5 file-backed bytes of an executable section (e.g. a 3-byte `xor eax,eax; ret` at the end of `.text`) now aborts generation with `ValueError: invalid file-backed range at RVA ...` instead of being treated as "not an import". I reproduced it on a synthetic image (`text_vsize=0x300`, target `TEXT_RVA+0x2fd` -> `ValueError ... 0x12fd`). It fails closed (a clear error, never wrong output) and the real Bink images in CI are unaffected (tests above pass), so I would not block on it. If you want to keep the old tolerance, read `min(6, available)` bytes for the probe and only enforce the full range once a `jmp [rip+x]` has decoded. Otherwise a one-line comment stating that stricter behaviour is intended would help. ### Nits - `main()` catches `ValueError/OSError/PEFormatError` only; other malformed-image failures (e.g. `struct.error`, `IndexError` from `pefile`) would still print a traceback. A truncated-file probe I ran exits 1 cleanly, so this is only a robustness remark. - `add_test(NAME bink_heap_aot_check ...)` has no `TIMEOUT`, unlike the neighbouring Python tests (e.g. `pe_run_package_trap_missing` sets 60). The test runs in ~1.9 s, so this is cosmetic. - `test_import_name_thunk_bounds_rejected` only asserts `ValueError` without a message; the three sub-cases could pass for the wrong reason if another `ValueError` were raised. Mutations M1/M2 show they currently do fail for the right reason. AI-assisted; commands listed were executed locally.
tedin7 commented 2026-11-24 21:27:32 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T21:12:05Z.

Review: COMMENTED


Review of head 66f7013599e84be2a58b81d2ad3d624509fda597.

Verdict: no P1. Two P2 test gaps, nothing blocking.

Diff read

  • tools/bink_heap_aot.py: the IAT-thunk read now goes through image_bytes(..., executable=True) before decoding (so an unmapped, non-executable or truncated thunk target raises ValueError instead of reading garbage or returning short data); a missing import directory raises ValueError; main(argv) maps ValueError/OSError/PEFormatError to exit 1 with a message. Semantics and bounds look right; the old post-decode image_bytes(pe, target, thunk.len, ...) check is correctly subsumed by checking all 6 bytes first.
  • CMakeLists.txt: one add_test in the Windows pe-env block. tests/bink_heap_aot_check.py: synthetic PE32+ builder with positive and refusal cases.
  • Clean-room and title: neutral, synthetic images only, no external material.

P2 (test gaps)

  1. tools/bink_heap_aot.py (the new except (ValueError, OSError, pefile.PEFormatError) in main): no test makes the CLI hit a ValueError. Removing ValueError from that tuple leaves all 12 tests green, so a bad image would again end in a traceback unnoticed. A CLI case with a refusal image (e.g. the no-import-directory one) asserting exit code 1 and no "Traceback" would pin it.
  2. import_name (thunk.mnemonic != M.JMP or not thunk.is_ip_rel_memory_operand): weakening it to thunk.mnemonic != M.JMP is not caught; no case has a jmp thunk with a non-RIP-relative operand. This line is not new in the PR, so it is only a suggestion.

Commands run locally (Linux, venv python)

  • git diff --check origin/main...HEAD: exit 0.
  • tests/bink_heap_aot_check.py: 12 tests, OK (1.1 s).
  • tests/docs_links_check.py: 18 files, 380 links. tests/bidi_controls_check.py: 1343 files, clean.
  • Windows Server 2025 via the pipeline, ^bink_heap_aot_check$: Debug 1/1 and Release /O2 1/1 passed.

Mutations (each reverted with git checkout -- .)

Mutation Result
thunk read back to pe.get_data(target, 6) caught (test_import_name_thunk_bounds_rejected)
drop the "no import directory" check caught (test_missing_import_directory_raises_value_error)
remove ValueError from the CLI except NOT caught (P2 #1)
weaken the thunk operand check to mnemonic != JMP NOT caught (P2 #2)

AI-assisted; commands listed were executed locally.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review:6047487322 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1908#pullrequestreview-6047487322). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T21:12:05Z. **Review:** COMMENTED --- Review of head `66f7013599e84be2a58b81d2ad3d624509fda597`. **Verdict: no P1. Two P2 test gaps, nothing blocking.** ### Diff read - `tools/bink_heap_aot.py`: the IAT-thunk read now goes through `image_bytes(..., executable=True)` before decoding (so an unmapped, non-executable or truncated thunk target raises `ValueError` instead of reading garbage or returning short data); a missing import directory raises `ValueError`; `main(argv)` maps `ValueError`/`OSError`/`PEFormatError` to exit 1 with a message. Semantics and bounds look right; the old post-decode `image_bytes(pe, target, thunk.len, ...)` check is correctly subsumed by checking all 6 bytes first. - `CMakeLists.txt`: one `add_test` in the Windows pe-env block. `tests/bink_heap_aot_check.py`: synthetic PE32+ builder with positive and refusal cases. - Clean-room and title: neutral, synthetic images only, no external material. ### P2 (test gaps) 1. `tools/bink_heap_aot.py` (the new `except (ValueError, OSError, pefile.PEFormatError)` in `main`): no test makes the CLI hit a `ValueError`. Removing `ValueError` from that tuple leaves all 12 tests green, so a bad image would again end in a traceback unnoticed. A CLI case with a refusal image (e.g. the no-import-directory one) asserting exit code 1 and no "Traceback" would pin it. 2. `import_name` (`thunk.mnemonic != M.JMP or not thunk.is_ip_rel_memory_operand`): weakening it to `thunk.mnemonic != M.JMP` is not caught; no case has a `jmp` thunk with a non-RIP-relative operand. This line is not new in the PR, so it is only a suggestion. ### Commands run locally (Linux, venv python) - `git diff --check origin/main...HEAD`: exit 0. - `tests/bink_heap_aot_check.py`: 12 tests, OK (1.1 s). - `tests/docs_links_check.py`: 18 files, 380 links. `tests/bidi_controls_check.py`: 1343 files, clean. - Windows Server 2025 via the pipeline, `^bink_heap_aot_check$`: Debug 1/1 and Release /O2 1/1 passed. ### Mutations (each reverted with `git checkout -- .`) | Mutation | Result | |---|---| | thunk read back to `pe.get_data(target, 6)` | caught (`test_import_name_thunk_bounds_rejected`) | | drop the "no import directory" check | caught (`test_missing_import_directory_raises_value_error`) | | remove `ValueError` from the CLI `except` | NOT caught (P2 #1) | | weaken the thunk operand check to `mnemonic != JMP` | NOT caught (P2 #2) | AI-assisted; commands listed were executed locally.
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
R0Y00/Xbox2Windows!1901
No description provided.