runtime: add main(argv), atomic --output writes, and directory/error guards in xmem_attribute_scan with CLI suite #2421

Merged
Ammmae0x merged 2 commits from upstream-pr/2429 into main 2026-11-25 19:58:29 +00:00
Ammmae0x commented 2026-11-25 16:28:19 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by Ammmae0x on 2026-11-25T16:28:19Z.


Change

Add a testable main(argv=None) -> int entrypoint, upfront directory/collision validation, atomic --output writes, PE handle cleanup, and structured exit-code-2 error handling to tools/xmem_attribute_scan.py, with a standalone pure-Python CLI test suite registered in CMakeLists.txt (xmem_attribute_scan_cli_check).

  • tools/xmem_attribute_scan.py:
    • Accept argv: list[str] | None = None in main, forward argv to parser.parse_args(argv), and invoke raise SystemExit(main()) under __main__.
    • Reject --output pointing to an existing directory or colliding with image (_same_path checking both Path.resolve() and Path.samefile()), and reject image being a directory before scanning.
    • Create parent directories and write --output JSON atomically via tempfile.TemporaryDirectory(dir=destination.parent) + os.replace() (_atomic_write_text), leaving zero temporary directories or partial files on failure.
    • Close pefile.PE handles deterministically in Image.__init__ (on exception) and scan() (finally).
    • Guard (OSError, ValueError, pefile.PEFormatError) across both scanning and output writing via parser.exit(2, f"{type(exc).__name__}: {args.image}: {exc}\n"), keeping exit code 1 strictly reserved for --fail-on-null / --fail-on-unresolved, exit 0 for clean scans, and exit 2 for I/O/PE/output errors with zero raw tracebacks.
  • tests/xmem_attribute_scan_cli_check.py: standalone unittest suite using synthetic x64 PE32+ fixtures covering stdout and nested atomic --output JSON schema, exit 0/1/2 separation, main(None) / __main__ forwarding, and negative/mutation controls (missing/directory/corrupt/x86 PE, --output directory, resolve() & hardlink samefile() collisions, and os.replace OSError leaving zero temp dirs and preserving prior output).
  • CMakeLists.txt: register xmem_attribute_scan_cli_check immediately after xmem_attribute_scan (tests/xmem_attribute_scan_check.py left untouched).

Verification

Verified on rebased commit 9cc402ee (based on upstream/main b442b57f) using out/pe-env/Scripts/python.exe -B:

  • out/pe-env/Scripts/python.exe -B tests/xmem_attribute_scan_cli_check.py -v -> Ran 6 tests, OK (exit 0).
  • out/pe-env/Scripts/python.exe -B tests/xmem_attribute_scan_check.py -> decoding: 16 cases passed + unreadable image exit-2 checks (exit 0).
  • out/pe-env/Scripts/python.exe -B tests/form_coverage_check.py -> form coverage checks passed (exit 0).
  • out/pe-env/Scripts/python.exe -B tests/docs_links_check.py -> Self-test passed. (exit 0).
  • out/pe-env/Scripts/python.exe -B tests/bidi_controls_check.py -> Self-test passed. (exit 0).
  • Spot mutation audit on tools/xmem_attribute_scan.py: 8/8 mutations killed (argv forwarding, --output is_dir(), _same_path resolve(), _same_path samefile(), image.is_dir(), atomic write bypass, PEFormatError guard, exit code 2 vs 1).

Evidence and follow-up

All PE32+ test fixtures in tests/xmem_attribute_scan_cli_check.py are synthetic minimal byte arrays generated in-memory under the repository MIT license; no external binaries or game files are used. Contributors can run the suite directly via out/pe-env/Scripts/python.exe -B tests/xmem_attribute_scan_cli_check.py or through CTest (xmem_attribute_scan_cli_check).

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.

AI-assisted.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:issue:6608915453 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/2429). Originally posted by [Ammmae0x](https://github.com/Ammmae0x) on 2026-11-25T16:28:19Z. --- ## Change Add a testable `main(argv=None) -> int` entrypoint, upfront directory/collision validation, atomic `--output` writes, PE handle cleanup, and structured exit-code-2 error handling to `tools/xmem_attribute_scan.py`, with a standalone pure-Python CLI test suite registered in `CMakeLists.txt` (`xmem_attribute_scan_cli_check`). - `tools/xmem_attribute_scan.py`: - Accept `argv: list[str] | None = None` in `main`, forward `argv` to `parser.parse_args(argv)`, and invoke `raise SystemExit(main())` under `__main__`. - Reject `--output` pointing to an existing directory or colliding with `image` (`_same_path` checking both `Path.resolve()` and `Path.samefile()`), and reject `image` being a directory before scanning. - Create parent directories and write `--output` JSON atomically via `tempfile.TemporaryDirectory(dir=destination.parent)` + `os.replace()` (`_atomic_write_text`), leaving zero temporary directories or partial files on failure. - Close `pefile.PE` handles deterministically in `Image.__init__` (on exception) and `scan()` (`finally`). - Guard `(OSError, ValueError, pefile.PEFormatError)` across both scanning and output writing via `parser.exit(2, f"{type(exc).__name__}: {args.image}: {exc}\n")`, keeping exit code `1` strictly reserved for `--fail-on-null` / `--fail-on-unresolved`, exit `0` for clean scans, and exit `2` for I/O/PE/output errors with zero raw tracebacks. - `tests/xmem_attribute_scan_cli_check.py`: standalone unittest suite using synthetic x64 PE32+ fixtures covering stdout and nested atomic `--output` JSON schema, exit 0/1/2 separation, `main(None)` / `__main__` forwarding, and negative/mutation controls (missing/directory/corrupt/x86 PE, `--output` directory, `resolve()` & hardlink `samefile()` collisions, and `os.replace` `OSError` leaving zero temp dirs and preserving prior output). - `CMakeLists.txt`: register `xmem_attribute_scan_cli_check` immediately after `xmem_attribute_scan` (`tests/xmem_attribute_scan_check.py` left untouched). ## Verification Verified on rebased commit `9cc402ee` (based on `upstream/main` `b442b57f`) using `out/pe-env/Scripts/python.exe -B`: - `out/pe-env/Scripts/python.exe -B tests/xmem_attribute_scan_cli_check.py -v` -> `Ran 6 tests`, `OK` (exit 0). - `out/pe-env/Scripts/python.exe -B tests/xmem_attribute_scan_check.py` -> `decoding: 16 cases passed` + unreadable image exit-2 checks (exit 0). - `out/pe-env/Scripts/python.exe -B tests/form_coverage_check.py` -> `form coverage checks passed` (exit 0). - `out/pe-env/Scripts/python.exe -B tests/docs_links_check.py` -> `Self-test passed.` (exit 0). - `out/pe-env/Scripts/python.exe -B tests/bidi_controls_check.py` -> `Self-test passed.` (exit 0). - Spot mutation audit on `tools/xmem_attribute_scan.py`: 8/8 mutations killed (`argv` forwarding, `--output` `is_dir()`, `_same_path` `resolve()`, `_same_path` `samefile()`, `image.is_dir()`, atomic write bypass, `PEFormatError` guard, exit code `2` vs `1`). ## Evidence and follow-up All PE32+ test fixtures in `tests/xmem_attribute_scan_cli_check.py` are synthetic minimal byte arrays generated in-memory under the repository MIT license; no external binaries or game files are used. Contributors can run the suite directly via `out/pe-env/Scripts/python.exe -B tests/xmem_attribute_scan_cli_check.py` or through CTest (`xmem_attribute_scan_cli_check`). ## 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. - [x] I updated README/docs when a capability or build requirement changed. - [x] I did not include game files, dumps, distribution links or secrets. AI-assisted.
tedin7 commented 2026-11-25 19:03:41 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-25T18:22:28Z.

Review: COMMENTED


Review of head 9cc402ee (tooling only, 3 files: tools/xmem_attribute_scan.py, new tests/xmem_attribute_scan_cli_check.py, CMakeLists.txt).

No author Windows results are posted on this PR, so none were checked. I ran no Windows tests.

What I checked:

  • main(argv), the directory/collision guards and the atomic --output write read correctly. Exit code 2 for errors and 1 for the --fail-on-* gates is kept.
  • The try/finally around scan() and the try/except in Image.__init__ close the PE handle on every path. Most of the 275-line diff is re-indentation. git diff -w is the easier way to read it.
  • No other open or merged PR covers this. #663 (unreadable images) and #1830 (word masks) touch other behavior of the same tool.
  • python3 -B tests/xmem_attribute_scan_cli_check.py with the pefile venv: 6 tests, OK.
  • tests/xmem_attribute_scan_check.py: decoding cases pass.
  • python3 tests/docs_links_check.py, python3 tests/bidi_controls_check.py and git diff --check origin/main...HEAD pass.

Mutations I tried (each reverted with git checkout -- .):

  • Disable the image/output collision check: the suite fails.
  • Replace os.replace with a direct write_text: the suite fails (2 failures).
  • Remove self.pe.close() in Image.__init__'s error path: the suite still passes (see P2).

Findings:

  • P2: the handle-close fix in Image.__init__ and scan() has no test. Add a test that mocks pefile.PE, forces a failure after construction (for example a wrong machine type) and asserts close() was called. Without it the fix can be reverted silently.
  • P2: docs/experiments.md (around line 9384, the xmem_attribute_scan table row) lists the existing suite only. Mention the new xmem_attribute_scan_cli_check test and the new stderr format ValueError: <image>: <message>.
  • Nit: the new CTest does not need the built fixtures, so it could also run in the Linux Python job like the decoding cases.

No blocking bug found.

AI-assisted; commands listed were executed locally.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review:6062810990 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/2429#pullrequestreview-6062810990). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-25T18:22:28Z. **Review:** COMMENTED --- Review of head 9cc402ee (tooling only, 3 files: `tools/xmem_attribute_scan.py`, new `tests/xmem_attribute_scan_cli_check.py`, `CMakeLists.txt`). No author Windows results are posted on this PR, so none were checked. I ran no Windows tests. What I checked: - `main(argv)`, the directory/collision guards and the atomic `--output` write read correctly. Exit code 2 for errors and 1 for the `--fail-on-*` gates is kept. - The `try/finally` around `scan()` and the `try/except` in `Image.__init__` close the PE handle on every path. Most of the 275-line diff is re-indentation. `git diff -w` is the easier way to read it. - No other open or merged PR covers this. #663 (unreadable images) and #1830 (word masks) touch other behavior of the same tool. - `python3 -B tests/xmem_attribute_scan_cli_check.py` with the pefile venv: 6 tests, OK. - `tests/xmem_attribute_scan_check.py`: decoding cases pass. - `python3 tests/docs_links_check.py`, `python3 tests/bidi_controls_check.py` and `git diff --check origin/main...HEAD` pass. Mutations I tried (each reverted with `git checkout -- .`): - Disable the image/output collision check: the suite fails. - Replace `os.replace` with a direct `write_text`: the suite fails (2 failures). - Remove `self.pe.close()` in `Image.__init__`'s error path: the suite still passes (see P2). Findings: - P2: the handle-close fix in `Image.__init__` and `scan()` has no test. Add a test that mocks `pefile.PE`, forces a failure after construction (for example a wrong machine type) and asserts `close()` was called. Without it the fix can be reverted silently. - P2: `docs/experiments.md` (around line 9384, the `xmem_attribute_scan` table row) lists the existing suite only. Mention the new `xmem_attribute_scan_cli_check` test and the new stderr format `ValueError: <image>: <message>`. - Nit: the new CTest does not need the built fixtures, so it could also run in the Linux Python job like the decoding cases. No blocking bug found. AI-assisted; commands listed were executed locally.
upstream-sync closed this pull request 2026-11-25 20:04:10 +00:00
tedin7 commented 2026-11-25 20:04:11 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-25T19:54:47Z.

Review: COMMENTED


Review of head 4791df9e (the merge of main into the PR branch; the PR's own change is the one @tedin7 reviewed at 9cc402ee). Comment only.

Result: sound. One non-blocking note.

What I checked

  • tools/xmem_attribute_scan.py: main(argv) forwards to parse_args. The directory and collision checks (resolve() and samefile()) run before scanning. --output is written through a sibling temp dir plus os.replace. Exit 2 covers OSError, ValueError and PEFormatError. Exit 1 stays only for the --fail-on-* gates.
  • The body of scan and Image.__init__ is re-indented into try/finally blocks that close the PE handle. git diff -w shows no other logic change there.
  • The error line now starts with the exception type name. The existing xmem_attribute_scan_check.py does not depend on the old wording.
  • CMake: xmem_attribute_scan_cli_check is registered next to xmem_attribute_scan, and the new test is pure Python with synthetic PE files.
  • No other open or merged PR covers this slice (#663 added the earlier no-traceback path; this builds on it).

Commands run locally (Linux, venv with pefile 2024.8.26 and iced-x86 1.21.0, as in requirements-dev.txt)

  • python -B tests/xmem_attribute_scan_cli_check.py: 6 tests, OK
  • python3 tests/docs_links_check.py: ok
  • python3 tests/bidi_controls_check.py: ok
  • git diff --check origin/main...HEAD: clean
  • Mutations, each makes the new suite fail: os.replace swapped for a direct write; exit 2 changed to 1; the --output vs image collision check disabled.

Non-blocking note

  • Removing either pe.close() (in Image.__init__ on error, or in the scan finally) leaves the suite green. The PE handle cleanup in the description has no test that guards it. Not a blocker for this tool; a small test that checks the handle is closed would close the gap.

AI-assisted; commands listed were executed locally.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review:6064058960 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/2429#pullrequestreview-6064058960). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-25T19:54:47Z. **Review:** COMMENTED --- Review of head 4791df9e (the merge of main into the PR branch; the PR's own change is the one @tedin7 reviewed at 9cc402ee). Comment only. Result: sound. One non-blocking note. What I checked - `tools/xmem_attribute_scan.py`: `main(argv)` forwards to `parse_args`. The directory and collision checks (`resolve()` and `samefile()`) run before scanning. `--output` is written through a sibling temp dir plus `os.replace`. Exit 2 covers `OSError`, `ValueError` and `PEFormatError`. Exit 1 stays only for the `--fail-on-*` gates. - The body of `scan` and `Image.__init__` is re-indented into `try/finally` blocks that close the PE handle. `git diff -w` shows no other logic change there. - The error line now starts with the exception type name. The existing `xmem_attribute_scan_check.py` does not depend on the old wording. - CMake: `xmem_attribute_scan_cli_check` is registered next to `xmem_attribute_scan`, and the new test is pure Python with synthetic PE files. - No other open or merged PR covers this slice (#663 added the earlier no-traceback path; this builds on it). Commands run locally (Linux, venv with pefile 2024.8.26 and iced-x86 1.21.0, as in requirements-dev.txt) - `python -B tests/xmem_attribute_scan_cli_check.py`: 6 tests, OK - `python3 tests/docs_links_check.py`: ok - `python3 tests/bidi_controls_check.py`: ok - `git diff --check origin/main...HEAD`: clean - Mutations, each makes the new suite fail: `os.replace` swapped for a direct write; exit 2 changed to 1; the `--output` vs image collision check disabled. Non-blocking note - Removing either `pe.close()` (in `Image.__init__` on error, or in the `scan` `finally`) leaves the suite green. The PE handle cleanup in the description has no test that guards it. Not a blocker for this tool; a small test that checks the handle is closed would close the gap. AI-assisted; commands listed were executed locally.
tedin7 commented 2026-11-25 20:04:47 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-25T19:57:59Z.


Win2025 WARP receipt for head 4791df9e after updating with main.

Verified on Windows Server 2025 (Build 26100, MSVC 14.44.35207 + D3D12 WARP) at commit 4791df9edb82fb5885b7b8eeed44b9fe7ceee317:

  • Debug (--preset dev):
    • Build (cmake --build --preset dev --target cpu_xmem_attributes cpu_xmem_delay -- -j 2): 0.15s (configure 3.59s)
    • Test (ctest --preset dev -R 'xmem_attribute_scan' --parallel 2 --no-tests=error --output-on-failure): 2/2 passed (10.13s: xmem_attribute_scan 8.47s, xmem_attribute_scan_cli_check 9.45s)
  • Release /O2 (--preset release):
    • Build (cmake --build --preset release --target cpu_xmem_attributes cpu_xmem_delay -- -j 2): 10.14s (configure 3.47s)
    • Test (ctest --preset release -R 'xmem_attribute_scan' --parallel 2 --no-tests=error --output-on-failure): 2/2 passed (15.64s: xmem_attribute_scan_cli_check 13.25s, xmem_attribute_scan 14.81s)
  • Windows Python checks: tests/xmem_attribute_scan_check.py ok (3.0s)
  • sccache: 264/279 hits; wall 57.1s

AI-assisted; commands listed were executed locally.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7173002134 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/2429#issuecomment-7173002134). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-25T19:57:59Z. --- Win2025 WARP receipt for head 4791df9e after updating with main. Verified on Windows Server 2025 (Build 26100, MSVC 14.44.35207 + D3D12 WARP) at commit `4791df9edb82fb5885b7b8eeed44b9fe7ceee317`: - **Debug (`--preset dev`)**: - Build (`cmake --build --preset dev --target cpu_xmem_attributes cpu_xmem_delay -- -j 2`): `0.15s` (configure `3.59s`) - Test (`ctest --preset dev -R 'xmem_attribute_scan' --parallel 2 --no-tests=error --output-on-failure`): **2/2 passed** (`10.13s`: `xmem_attribute_scan` `8.47s`, `xmem_attribute_scan_cli_check` `9.45s`) - **Release `/O2` (`--preset release`)**: - Build (`cmake --build --preset release --target cpu_xmem_attributes cpu_xmem_delay -- -j 2`): `10.14s` (configure `3.47s`) - Test (`ctest --preset release -R 'xmem_attribute_scan' --parallel 2 --no-tests=error --output-on-failure`): **2/2 passed** (`15.64s`: `xmem_attribute_scan_cli_check` `13.25s`, `xmem_attribute_scan` `14.81s`) - **Windows Python checks**: `tests/xmem_attribute_scan_check.py` ok (`3.0s`) - `sccache`: 264/279 hits; wall `57.1s` 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!2421
No description provided.