ffx: harden device-init dispatch lookup and CLI error handling with unit suite #1926

Merged
Ammmae0x merged 1 commit from upstream-pr/1933 into main 2026-11-24 21:54:21 +00:00
Ammmae0x commented 2026-11-24 21:40:08 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by Ammmae0x on 2026-11-24T21:40:08Z.


Change

Harden tools/ffx_device_init.py and add a synthetic AMD64 PE32+ unit and refusal suite in tests/ffx_device_init_check.py, registered in CTest as ffx_device_init_check:

  • Replace raw dictionary indexing on ins.memory_displacement in generate() with a methods.get(...) check that raises a contextual ValueError (including the displacement and instruction IP) instead of a KeyError on unexpected indirect calls.
  • Extract main(argv=None) -> int in tools/ffx_device_init.py and catch (OSError, ValueError, pefile.PEFormatError, struct.error) with parser.exit(1, ...) so missing files, malformed PE/struct inputs, non-.cpp output paths, and matching image/output paths exit cleanly with code 1 and no traceback.
  • Add tests/ffx_device_init_check.py (9 tests: synthetic PE32+ generate()/main() output checks, mocked checked_image, .pdata interval check, non-RAX base call refusal, unexpected RAX displacement refusal, mismatched heap UUID refusal, missing/non-PE refusal, struct.error handling, and .cpp/same-file CLI checks) and register ffx_device_init_check in CMakeLists.txt.

AI-assisted.

Verification

  • python.exe -B tests/ffx_device_init_check.py -v: Ran 9 tests in 2.607s — OK (with tools/ffx_device_init.py reverted as a mutation sanity check, 5/9 tests fail as expected).
  • cmake --preset dev & ctest --preset dev -N: Total Tests: 1217.
  • ctest --preset dev --no-tests=error -R "^(ffx_device_init_check|ffx_create_context_check|ffx_dispatch_profile_check)$" -V: 3/3 passed (ffx_dispatch_profile_check 10/10, ffx_create_context_check 6/6, ffx_device_init_check 9/9).
  • cmake --preset release & ctest --preset release -N: Total Tests: 1217.
  • ctest --preset release --no-tests=error -R "^(ffx_device_init_check|ffx_create_context_check|ffx_dispatch_profile_check)$" -V: 3/3 passed (ffx_dispatch_profile_check 10/10, ffx_create_context_check 6/6, ffx_device_init_check 9/9).
  • python.exe -B tests/form_coverage_check.py, python.exe -B tests/docs_links_check.py, python.exe -B tests/bidi_controls_check.py: all exited 0.

Evidence and follow-up

All fixtures in tests/ffx_device_init_check.py are synthetic AMD64 PE32+ images constructed in-memory; no packaged binary files are required or included.

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.
  • I did not include game files, dumps, distribution links or secrets.
<!-- greyfinch-sync:R0Y00/Xbox2Windows:issue:6591954352 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1933). Originally posted by [Ammmae0x](https://github.com/Ammmae0x) on 2026-11-24T21:40:08Z. --- ## Change Harden `tools/ffx_device_init.py` and add a synthetic AMD64 PE32+ unit and refusal suite in `tests/ffx_device_init_check.py`, registered in CTest as `ffx_device_init_check`: - Replace raw dictionary indexing on `ins.memory_displacement` in `generate()` with a `methods.get(...)` check that raises a contextual `ValueError` (including the displacement and instruction IP) instead of a `KeyError` on unexpected indirect calls. - Extract `main(argv=None) -> int` in `tools/ffx_device_init.py` and catch `(OSError, ValueError, pefile.PEFormatError, struct.error)` with `parser.exit(1, ...)` so missing files, malformed PE/struct inputs, non-`.cpp` output paths, and matching image/output paths exit cleanly with code `1` and no traceback. - Add `tests/ffx_device_init_check.py` (9 tests: synthetic PE32+ `generate()`/`main()` output checks, mocked `checked_image`, `.pdata` interval check, non-`RAX` base call refusal, unexpected `RAX` displacement refusal, mismatched heap UUID refusal, missing/non-PE refusal, `struct.error` handling, and `.cpp`/same-file CLI checks) and register `ffx_device_init_check` in `CMakeLists.txt`. AI-assisted. ## Verification - `python.exe -B tests/ffx_device_init_check.py -v`: `Ran 9 tests in 2.607s` — `OK` (with `tools/ffx_device_init.py` reverted as a mutation sanity check, 5/9 tests fail as expected). - `cmake --preset dev` & `ctest --preset dev -N`: `Total Tests: 1217`. - `ctest --preset dev --no-tests=error -R "^(ffx_device_init_check|ffx_create_context_check|ffx_dispatch_profile_check)$" -V`: `3/3` passed (`ffx_dispatch_profile_check` 10/10, `ffx_create_context_check` 6/6, `ffx_device_init_check` 9/9). - `cmake --preset release` & `ctest --preset release -N`: `Total Tests: 1217`. - `ctest --preset release --no-tests=error -R "^(ffx_device_init_check|ffx_create_context_check|ffx_dispatch_profile_check)$" -V`: `3/3` passed (`ffx_dispatch_profile_check` 10/10, `ffx_create_context_check` 6/6, `ffx_device_init_check` 9/9). - `python.exe -B tests/form_coverage_check.py`, `python.exe -B tests/docs_links_check.py`, `python.exe -B tests/bidi_controls_check.py`: all exited `0`. ## Evidence and follow-up All fixtures in `tests/ffx_device_init_check.py` are synthetic AMD64 PE32+ images constructed in-memory; no packaged binary files are required or included. ## 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. - [x] I did not include game files, dumps, distribution links or secrets.
upstream-sync closed this pull request 2026-11-24 22:00:56 +00:00
tedin7 commented 2026-11-24 22:00:57 +00:00 (Migrated from github.com)

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

Review: COMMENTED


Review of head 6bd3e3d2c9835a862ca7e847b44a430c7c15befc.

Result: no P1, no P2, one P3.

Commands run locally, with results:

  • HEAD check: git rev-parse HEAD matches the head above.
  • Conflicts: git merge-tree --write-tree --name-only origin/main HEAD gave a clean tree, no conflicts.
  • CI: gh pr checks 1933: Linux checks, Windows build and gfx1013 fixtures pass. The /O2 job and chart publish are skipped.
  • git diff --check origin/main...HEAD: clean.
  • python3 tests/bidi_controls_check.py: pass.
  • python3 tests/docs_links_check.py: pass.
  • python3 -B tests/ffx_device_init_check.py in a venv from requirements-dev.txt: 9 tests OK. The system python has no pefile, so the test needs the dev requirements, as CI has.
  • python3 $P win2025 1933 --wait 900: Debug and Release /O2 both pass. Build and ctest -R ^ffx_device_init_check$ passed 1/1 in each.

Mutation: I removed pefile.PEFormatError from the except tuple in main(). The suite failed (1 error), so the change is covered. I then restored the file with git checkout -- ..

Findings:

  • P3 tools/ffx_device_init.py:66-71: the bad suffix and same-file checks used parser.error, which exits 2. They now go through ValueError and exit 1. The only consumer, the CMake custom command at CMakeLists.txt:1926, only checks for nonzero, so nothing breaks. The test pins exit 1. Worth a line in the PR description.

Checked and fine:

  • The unknown-displacement path raises ValueError with the displacement and address, instead of a bare KeyError. A test covers it.
  • main(argv) is testable, and the output is not created when generation fails. Tests assert this.
  • The new add_test sits inside the existing INTAKE_PYTHON guard.

AI-assisted; commands listed were executed locally.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review:6048020091 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1933#pullrequestreview-6048020091). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T21:54:31Z. **Review:** COMMENTED --- Review of head `6bd3e3d2c9835a862ca7e847b44a430c7c15befc`. Result: no P1, no P2, one P3. Commands run locally, with results: - HEAD check: `git rev-parse HEAD` matches the head above. - Conflicts: `git merge-tree --write-tree --name-only origin/main HEAD` gave a clean tree, no conflicts. - CI: `gh pr checks 1933`: Linux checks, Windows build and gfx1013 fixtures pass. The /O2 job and chart publish are skipped. - `git diff --check origin/main...HEAD`: clean. - `python3 tests/bidi_controls_check.py`: pass. - `python3 tests/docs_links_check.py`: pass. - `python3 -B tests/ffx_device_init_check.py` in a venv from `requirements-dev.txt`: 9 tests OK. The system python has no `pefile`, so the test needs the dev requirements, as CI has. - `python3 $P win2025 1933 --wait 900`: Debug and Release /O2 both pass. Build and `ctest -R ^ffx_device_init_check$` passed 1/1 in each. Mutation: I removed `pefile.PEFormatError` from the `except` tuple in `main()`. The suite failed (1 error), so the change is covered. I then restored the file with `git checkout -- .`. Findings: - P3 `tools/ffx_device_init.py:66-71`: the bad suffix and same-file checks used `parser.error`, which exits 2. They now go through `ValueError` and exit 1. The only consumer, the CMake custom command at `CMakeLists.txt:1926`, only checks for nonzero, so nothing breaks. The test pins exit 1. Worth a line in the PR description. Checked and fine: - The unknown-displacement path raises `ValueError` with the displacement and address, instead of a bare `KeyError`. A test covers it. - `main(argv)` is testable, and the output is not created when generation fails. Tests assert this. - The new `add_test` sits inside the existing `INTAKE_PYTHON` guard. AI-assisted; commands listed were executed locally.
ChazY11 commented 2026-11-24 22:01:06 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by ChazY11 on 2026-11-24T21:59:14Z.


Ran the suite, broke four paths, one guard turns out not to be the one being tested

Windows 11 build 26300.9974:

out/pe-env/Scripts/python.exe -B tests/ffx_device_init_check.py
Ran 9 tests in 3.422s
OK      exit 0

Mutations to tools/ffx_device_init.py, each reverted:

mutation result
back to {8: …, 0x70: …}[ins.memory_displacement] (raw KeyError) caught
except (OSError, ValueError, pefile.PEFormatError, struct.error) → except (KeyboardInterrupt,) caught
parser.exit(1, …) → parser.exit(0, …) caught
raise ValueError("choose a distinct .cpp output") → pass not caught

The same-file guard is not what makes that test pass

test_non_cpp_suffix_and_same_file_exit_1_cleanly uses same.cpp for both image and output and asserts returncode == 1 plus
same.read_bytes() == raw. With the guard removed, it still passes — because generate() fails first, on a different error:

# guard present
returncode = 1
stderr     = ['choose a distinct .cpp output']
content kept = True

# guard replaced by pass
returncode = 1
stderr     = ['unrecognized same.cpp version-query profile']
content kept = True

Same exit code, same untouched file, different reason. So the test asserts the outcome but not the cause, and --output pointing at
the input image would be a real overwrite if generate() ever succeeded on that input (their in-process tests mock
checked_image, which is why the subprocess case never reaches a successful generate).

Minimal way to pin it, in the style the file already uses:

def test_same_file_is_refused_before_generate_runs(self):
    raw = build_synthetic_upscaler()
    with tempfile.TemporaryDirectory() as tmp:
        same = Path(tmp) / "same.cpp"
        same.write_bytes(raw)
        with patch.object(ffx_device_init, "generate", return_value="// generated\n") as gen:
            with self.assertRaises(SystemExit) as caught:
                ffx_device_init.main([str(same), str(same)])
        self.assertEqual(caught.exception.code, 1)
        gen.assert_not_called()
        self.assertEqual(same.read_bytes(), raw)

gen.assert_not_called() is the part that distinguishes this from what the current test observes.

What is good here

  • The methods.get change adds the displacement and the instruction IP to the message; losing the KeyError is the difference
    between "a dict lookup failed somewhere" and "a call at 0x… used displacement 0x…".
  • main(argv=None) -> int with SystemExit from parser.exit is the right shape: the exit code is 1 for every refusal, and
    the traceback is gone, which is what the subprocess assertions check.
  • Catching pefile.PEFormatError and struct.error at the boundary rather than deep inside is the right place — the synthetic
    PE builder is what made those reachable.

Verdict

Reviewed. Three of the four behaviours are pinned; the fourth is asserted by outcome only and would regress silently. One small
test closes it.

Notes

  • AI-assisted review.
<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7145650947 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1933#issuecomment-7145650947). Originally posted by [ChazY11](https://github.com/ChazY11) on 2026-11-24T21:59:14Z. --- ## Ran the suite, broke four paths, one guard turns out not to be the one being tested Windows 11 build 26300.9974: ```powershell out/pe-env/Scripts/python.exe -B tests/ffx_device_init_check.py Ran 9 tests in 3.422s OK exit 0 ``` Mutations to `tools/ffx_device_init.py`, each reverted: | mutation | result | |---|---| | back to `{8: …, 0x70: …}[ins.memory_displacement]` (raw `KeyError`) | **caught** | | `except (OSError, ValueError, pefile.PEFormatError, struct.error)` → `except (KeyboardInterrupt,)` | **caught** | | `parser.exit(1, …)` → `parser.exit(0, …)` | **caught** | | **`raise ValueError("choose a distinct .cpp output")` → `pass`** | **not caught** | ## The same-file guard is not what makes that test pass `test_non_cpp_suffix_and_same_file_exit_1_cleanly` uses `same.cpp` for both image and output and asserts `returncode == 1` plus `same.read_bytes() == raw`. With the guard removed, it still passes — because `generate()` fails first, on a *different* error: ```powershell # guard present returncode = 1 stderr = ['choose a distinct .cpp output'] content kept = True # guard replaced by pass returncode = 1 stderr = ['unrecognized same.cpp version-query profile'] content kept = True ``` Same exit code, same untouched file, different reason. So the test asserts the outcome but not the cause, and `--output` pointing at the input image would be a real overwrite if `generate()` ever succeeded on that input (their in-process tests mock `checked_image`, which is why the subprocess case never reaches a successful `generate`). Minimal way to pin it, in the style the file already uses: ```python def test_same_file_is_refused_before_generate_runs(self): raw = build_synthetic_upscaler() with tempfile.TemporaryDirectory() as tmp: same = Path(tmp) / "same.cpp" same.write_bytes(raw) with patch.object(ffx_device_init, "generate", return_value="// generated\n") as gen: with self.assertRaises(SystemExit) as caught: ffx_device_init.main([str(same), str(same)]) self.assertEqual(caught.exception.code, 1) gen.assert_not_called() self.assertEqual(same.read_bytes(), raw) ``` `gen.assert_not_called()` is the part that distinguishes this from what the current test observes. ## What is good here - The `methods.get` change adds the displacement and the instruction IP to the message; losing the `KeyError` is the difference between "a dict lookup failed somewhere" and "a call at `0x…` used displacement `0x…`". - `main(argv=None) -> int` with `SystemExit` from `parser.exit` is the right shape: the exit code is `1` for every refusal, and the traceback is gone, which is what the subprocess assertions check. - Catching `pefile.PEFormatError` and `struct.error` at the boundary rather than deep inside is the right place — the synthetic PE builder is what made those reachable. ## Verdict Reviewed. Three of the four behaviours are pinned; the fourth is asserted by outcome only and would regress silently. One small test closes it. ## Notes - AI-assisted review.
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!1926
No description provided.