fix(relinker): reject Windows executable imports bound into the TLS template #10947

Merged
roboterspinne merged 2 commits from upstream-pr/10947 into main 2026-10-27 06:59:13 +00:00
roboterspinne commented 2026-10-25 11:18:32 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by roboterspinne on 2026-10-25T11:18:32Z.


What

An executable R_X86_64_64 or R_X86_64_GLOB_DAT relocation against a named import whose 8-byte target overlaps the PT_TLS initialization image converted for Windows: on untouched c7d6660ef8, relinker --skip-sce-module --windows (with or without --lazy-binding) exited 0 with an empty stderr for targets at the template start, crossing its end and crossing its start, and in the --windows output for the template-start target the .gtls template, which the Windows loader copies into the main thread's TLS block before the entry point and into each later thread's block, held 0 in that slot instead of the original bytes 01..08. WindowsRelocationBuilder::Apply writes 0 to the slot and queues the import for the entry stub, which binds only the image copy; WindowsTlsTemplateBuilder then copies the zeroed bytes into .gtls and mirrors only base relocations. In ELF, ld.so relocates the image before it copies it into a thread's TLS block, so every thread reads the bound value; the input passes ElfReader's PT_TLS bounds check, the relocation type checks, Apply's import checks and the entry stub's DT_NEEDED check, and the Windows guest module writer already refuses the same case (Runtime-bound guest TLS template relocation is not supported).

  • Rule. WindowsPePatcher::Patch throws Runtime-bound executable TLS template relocation is not supported right after WindowsRelocationBuilder::Apply, before the sections and the TLS template are built, when an executable import's [r_offset, r_offset + 8) overlaps [p_vaddr, p_vaddr + p_filesz) of a PT_TLS with p_filesz != 0, and reports the ELF target address; the CLI exits 2 and writes no output. At that point relocations.Imports holds only executable imports: guest-module imports are appended later, and the guest writer already refuses those that target a guest's TLS template. Targets in the zero-filled part [p_filesz, p_memsz), RELATIVE relocations (mirrored as base relocations), TPOFF64/DTPOFF64 (written statically) and empty-name weak imports (addend written statically) are not affected. The check is not in WindowsRelocationBuilder::Apply because macOS shares it and handles the case: dyld binds the in-image slot and the TLS descriptor points at the in-image template. A title whose PT_TLS initialization image holds a named-import relocation now stops converting for Windows instead of producing a build whose guest threads read 0 there; no such title is known: no issue or debt entry reports one, and no issue reports the guest-module refusal of the same case. The gap is recorded in docs/dev/debt/relinker.md: binding would require the entry stub to write the value into both the .gtls template and the main thread's TLS block, which the loader has already allocated.
  • Tests. test_executable_tls_relocations.py gets an STT_FUNC import and a needing() helper that adds DT_NEEDED, which the Windows entry stub requires. R_X86_64_64 at 0x1800 (template start) and 0x1804 (crossing the end) and GLOB_DAT at 0x1800 and 0x17fc (crossing the start) must fail for --windows and --windows --lazy-binding with FAIL: Runtime-bound executable TLS template relocation is not supported (offset <target>) and no output, and still convert for Linux, Linux --lazy-binding and --macos; the import at 0x1100 (outside the TLS image), at 0x17f8 (ending at the template start) and at 0x1808 (in [p_filesz, p_memsz)) still converts for both Windows modes. On untouched code all four Windows refusal inputs exit 0 with an output file in both modes; the first failing assertion is ('template-import-1800-1-1', 0, ''). The block sits before the failures table rather than after its loop, ahead of the block #10730 added after that loop.
  • Overlap. Checked by hand against main f95acfc948; #8076, #9408 and #10647, which the first check could not compare, have merged since. Open pull requests that touch the files of this PR: #6713, #10861 and #11432 (WindowsPePatcher.cpp), #10390 and #11038 (test_executable_tls_relocations.py), and 22 for docs/dev/debt/relinker.md. Merged onto main together with this change, each of them adds no conflict in these three files beyond the one it already has with main. #5021, #6713, #10479 and #10861 already conflict with main, so they were compared by hand. #6713 adds an empty .procpar section after the process-parameter loop, below the Apply call this check follows, and its WindowsPePatcher.cpp change merges cleanly with this one. Its only conflict with main is in docs/dev/debt/libc.md, which this PR does not touch, so the conflict is the same with or without this PR. #10861 adds an argument to the later WindowsTlsBuilder::Build call. In the debt file it rewrites the PT_SCE_DYNLIBDATA layout, sce_module syscall scan and code analysis entries and adds one entry after the code analysis entry and one at the end of the file. #10479 inserts after the read-only data entry. #5021 inserts a macOS TLS entry above the --trace-imports entry. This PR inserts between the null-symbol relocation entry and the macOS GS entry. #11432 adds an export directory, and neither it nor #10861 changes relocations.Imports.

Tested

Windows 11, GCC 15.2.0 (WinLibs UCRT), relinker-only Release build (-DANYPS5_RELINKER_ONLY=ON -DBUILD_TESTING=ON); synthetic fixtures only, no title or homebrew, relinked outputs not run.

  • Counter-check: executable_tls_relocations with the new cases on untouched c7d6660ef8 fails with AssertionError: ('template-import-1800-1-1', 0, ''); all 20 Windows refusal, Linux, Linux lazy and macOS runs of the four inputs exited 0 with an output file, as did the six Windows control runs. With the change it passes in 2.4 s.
  • ctest -R 'executable_tls_relocations|windows_tls|tls_function_coverage|macos_tls|guest_tls': 40 tests passed in 114.1 s: executable_tls_relocations, windows_tls_zero_fill, windows_tls_protected_entries, windows_tls_thread_pointer, macos_tls_alu, macos_tls_overlap, guest_tls and the 33 tls_function_coverage_* tests.
  • Rebased onto 16ff208dc3 (#10646 merged) and rebuilt: the 39 tests matching executable_tls_relocations|windows_tls|tls_function_coverage|guest_tls|executable_export_bounds passed again.
  • Merged current main (f95acfc948) into the branch without conflicts (ca8e16751c); main had also changed test_executable_tls_relocations.py and docs/dev/debt/relinker.md, which merged automatically. On ca8e16751c, ctest -R 'executable_tls_relocations|windows_tls|tls_function_coverage|macos_tls|guest_tls' -j 6: 42 tests passed: executable_tls_relocations (5.8 s), windows_tls_zero_fill, windows_tls_protected_entries, windows_tls_thread_pointer, macos_tls_alu, macos_tls_overlap, guest_tls, guest_tls_export_references and the 34 tls_function_coverage_* tests.
  • Full suite on ca8e16751c: ctest --test-dir build-relinker -j 6: 310 tests, 307 passed, long_paths skipped; failures known on this machine on main as well: select_tests (Windows symlink fixture) and patch_advisor_unit (path with spaces, which open #10667 fixes); both failed again alone.
  • python tools/check_conventions.py --base upstream/main with this title and description passed on ca8e16751c.
  • Not tested on Linux or macOS; CI runs the tests on all three hosts.

Checklist

  • Based on current main; no other open PR implements the same functions
  • One topic per PR; follow-ups go in a new PR
  • No comments in code except technical debt
  • Unimplemented paths throw (NotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file
  • No notes, investigation .md files or images added to the repository (attach them to this PR)
  • New third-party code is a submodule built from source
  • Generic behaviour, not specific to one title
  • Depends on: none
  • Fixes: none
  • Unblocks: none
  • GPUs tested: n/a
  • AI-assisted: yes (Claude Code)
<!-- greyfinch-sync:boykopovar/AnyPS5:issue:5004230467 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/10947). Originally posted by [roboterspinne](https://github.com/roboterspinne) on 2026-10-25T11:18:32Z. --- ### What An executable `R_X86_64_64` or `R_X86_64_GLOB_DAT` relocation against a named import whose 8-byte target overlaps the `PT_TLS` initialization image converted for Windows: on untouched c7d6660ef8, `relinker --skip-sce-module --windows` (with or without `--lazy-binding`) exited 0 with an empty stderr for targets at the template start, crossing its end and crossing its start, and in the `--windows` output for the template-start target the `.gtls` template, which the Windows loader copies into the main thread's TLS block before the entry point and into each later thread's block, held 0 in that slot instead of the original bytes `01..08`. `WindowsRelocationBuilder::Apply` writes 0 to the slot and queues the import for the entry stub, which binds only the image copy; `WindowsTlsTemplateBuilder` then copies the zeroed bytes into `.gtls` and mirrors only base relocations. In ELF, ld.so relocates the image before it copies it into a thread's TLS block, so every thread reads the bound value; the input passes `ElfReader`'s `PT_TLS` bounds check, the relocation type checks, `Apply`'s import checks and the entry stub's `DT_NEEDED` check, and the Windows guest module writer already refuses the same case (`Runtime-bound guest TLS template relocation is not supported`). - **Rule.** `WindowsPePatcher::Patch` throws `Runtime-bound executable TLS template relocation is not supported` right after `WindowsRelocationBuilder::Apply`, before the sections and the TLS template are built, when an executable import's `[r_offset, r_offset + 8)` overlaps `[p_vaddr, p_vaddr + p_filesz)` of a `PT_TLS` with `p_filesz != 0`, and reports the ELF target address; the CLI exits 2 and writes no output. At that point `relocations.Imports` holds only executable imports: guest-module imports are appended later, and the guest writer already refuses those that target a guest's TLS template. Targets in the zero-filled part `[p_filesz, p_memsz)`, `RELATIVE` relocations (mirrored as base relocations), `TPOFF64`/`DTPOFF64` (written statically) and empty-name weak imports (addend written statically) are not affected. The check is not in `WindowsRelocationBuilder::Apply` because macOS shares it and handles the case: dyld binds the in-image slot and the TLS descriptor points at the in-image template. A title whose `PT_TLS` initialization image holds a named-import relocation now stops converting for Windows instead of producing a build whose guest threads read 0 there; no such title is known: no issue or debt entry reports one, and no issue reports the guest-module refusal of the same case. The gap is recorded in `docs/dev/debt/relinker.md`: binding would require the entry stub to write the value into both the `.gtls` template and the main thread's TLS block, which the loader has already allocated. - **Tests.** `test_executable_tls_relocations.py` gets an `STT_FUNC` import and a `needing()` helper that adds `DT_NEEDED`, which the Windows entry stub requires. `R_X86_64_64` at 0x1800 (template start) and 0x1804 (crossing the end) and `GLOB_DAT` at 0x1800 and 0x17fc (crossing the start) must fail for `--windows` and `--windows --lazy-binding` with `FAIL: Runtime-bound executable TLS template relocation is not supported (offset <target>)` and no output, and still convert for Linux, Linux `--lazy-binding` and `--macos`; the import at 0x1100 (outside the TLS image), at 0x17f8 (ending at the template start) and at 0x1808 (in `[p_filesz, p_memsz)`) still converts for both Windows modes. On untouched code all four Windows refusal inputs exit 0 with an output file in both modes; the first failing assertion is `('template-import-1800-1-1', 0, '')`. The block sits before the `failures` table rather than after its loop, ahead of the block #10730 added after that loop. - **Overlap.** Checked by hand against `main` f95acfc948; #8076, #9408 and #10647, which the first check could not compare, have merged since. Open pull requests that touch the files of this PR: #6713, #10861 and #11432 (`WindowsPePatcher.cpp`), #10390 and #11038 (`test_executable_tls_relocations.py`), and 22 for `docs/dev/debt/relinker.md`. Merged onto `main` together with this change, each of them adds no conflict in these three files beyond the one it already has with `main`. #5021, #6713, #10479 and #10861 already conflict with `main`, so they were compared by hand. #6713 adds an empty `.procpar` section after the process-parameter loop, below the `Apply` call this check follows, and its `WindowsPePatcher.cpp` change merges cleanly with this one. Its only conflict with `main` is in `docs/dev/debt/libc.md`, which this PR does not touch, so the conflict is the same with or without this PR. #10861 adds an argument to the later `WindowsTlsBuilder::Build` call. In the debt file it rewrites the `PT_SCE_DYNLIBDATA` layout, `sce_module` syscall scan and code analysis entries and adds one entry after the code analysis entry and one at the end of the file. #10479 inserts after the read-only data entry. #5021 inserts a macOS TLS entry above the `--trace-imports` entry. This PR inserts between the null-symbol relocation entry and the macOS GS entry. #11432 adds an export directory, and neither it nor #10861 changes `relocations.Imports`. ### Tested <!-- OS, title or homebrew, what was checked. "Not tested" is a valid answer. A performance change: the summary lines of main and of this PR from the same machine and scene, with the traces attached, captured as the Performance report issue form describes. --> Windows 11, GCC 15.2.0 (WinLibs UCRT), relinker-only Release build (`-DANYPS5_RELINKER_ONLY=ON -DBUILD_TESTING=ON`); synthetic fixtures only, no title or homebrew, relinked outputs not run. - Counter-check: `executable_tls_relocations` with the new cases on untouched c7d6660ef8 fails with `AssertionError: ('template-import-1800-1-1', 0, '')`; all 20 Windows refusal, Linux, Linux lazy and macOS runs of the four inputs exited 0 with an output file, as did the six Windows control runs. With the change it passes in 2.4 s. - `ctest -R 'executable_tls_relocations|windows_tls|tls_function_coverage|macos_tls|guest_tls'`: 40 tests passed in 114.1 s: `executable_tls_relocations`, `windows_tls_zero_fill`, `windows_tls_protected_entries`, `windows_tls_thread_pointer`, `macos_tls_alu`, `macos_tls_overlap`, `guest_tls` and the 33 `tls_function_coverage_*` tests. - Rebased onto `16ff208dc3` (#10646 merged) and rebuilt: the 39 tests matching `executable_tls_relocations|windows_tls|tls_function_coverage|guest_tls|executable_export_bounds` passed again. - Merged current `main` (f95acfc948) into the branch without conflicts (ca8e16751c); `main` had also changed `test_executable_tls_relocations.py` and `docs/dev/debt/relinker.md`, which merged automatically. On ca8e16751c, `ctest -R 'executable_tls_relocations|windows_tls|tls_function_coverage|macos_tls|guest_tls' -j 6`: 42 tests passed: `executable_tls_relocations` (5.8 s), `windows_tls_zero_fill`, `windows_tls_protected_entries`, `windows_tls_thread_pointer`, `macos_tls_alu`, `macos_tls_overlap`, `guest_tls`, `guest_tls_export_references` and the 34 `tls_function_coverage_*` tests. - Full suite on ca8e16751c: `ctest --test-dir build-relinker -j 6`: 310 tests, 307 passed, `long_paths` skipped; failures known on this machine on `main` as well: `select_tests` (Windows symlink fixture) and `patch_advisor_unit` (path with spaces, which open #10667 fixes); both failed again alone. - `python tools/check_conventions.py --base upstream/main` with this title and description passed on ca8e16751c. - Not tested on Linux or macOS; CI runs the tests on all three hosts. ### Checklist <!-- Rules behind each item: https://github.com/boykopovar/AnyPS5/blob/main/CONTRIBUTING.md --> - [x] Based on current `main`; no other open PR implements the same functions - [x] One topic per PR; follow-ups go in a new PR - [x] No comments in code except [technical debt](https://github.com/boykopovar/AnyPS5/blob/main/docs/dev/CONVENTIONS.md) - [x] Unimplemented paths throw (`NotImplemented_nid_no_patch`); silent stubs are listed under Silent stubs in their library's [technical debt](https://github.com/boykopovar/AnyPS5/tree/main/docs/dev/debt) file - [x] No notes, investigation `.md` files or images added to the repository (attach them to this PR) - [x] New third-party code is a submodule built from source - [x] Generic behaviour, not specific to one title - [x] Depends on: <!-- #PR, or none --> none - [x] Fixes: <!-- issue it closes as Fixes #N, or none --> none - [x] Unblocks: <!-- title ID and Game bring-up discussion, e.g. PPSA01325 #3232, or none --> none - [x] GPUs tested: <!-- for AGC, shader recompiler or VideoOut changes: vendor, model, driver and OS of each GPU the GPU tests ran on; otherwise n/a --> n/a - [x] AI-assisted: <!-- yes / no --> yes (Claude Code)
MarcZX10 commented 2026-10-25 11:26:43 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-25T11:26:43Z.

Review: APPROVED


Reviewed exact head a54a939. The check is placed after relocation classification and before section/TLS-template construction, where the import list contains executable named imports; it checks overlap of the full 8-byte relocation slot with the initialized PT_TLS range and rejects only Windows output. The fixtures cover both relocation types, both overlap directions, the TLS start/end boundaries, BSS-only TLS, and cross-platform/lazy-binding controls. Local diff and conventions checks passed. The author reports the focused 39-test rerun on current main and the Windows test environment; all hosted Linux, Windows, macOS, x86_64 and ASan relinker checks are green. I did not independently rerun the full relinker suite.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5642930757 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/10947#pullrequestreview-5642930757). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-25T11:26:43Z. **Review:** APPROVED --- Reviewed exact head a54a939. The check is placed after relocation classification and before section/TLS-template construction, where the import list contains executable named imports; it checks overlap of the full 8-byte relocation slot with the initialized PT_TLS range and rejects only Windows output. The fixtures cover both relocation types, both overlap directions, the TLS start/end boundaries, BSS-only TLS, and cross-platform/lazy-binding controls. Local diff and conventions checks passed. The author reports the focused 39-test rerun on current main and the Windows test environment; all hosted Linux, Windows, macOS, x86_64 and ASan relinker checks are green. I did not independently rerun the full relinker suite.
ahmadmuj commented 2026-10-25 11:54:15 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by ahmadmuj on 2026-10-25T11:54:15Z.

Review: APPROVED


Reviewed head a54a939924 merged onto main a5a780eaaa (clean merge). Linux x86_64, GCC 13.3, Release, relinker-only build.

What I ran:

  • executable_tls_relocations (this PR's version) with main's relinker: fails at ('template-import-1800-1-1', 0, ''), same as your Windows counter-check. With the merged relinker: pass. Main's version of the test passes on both.
  • The silent corruption on main, read back from the PE: an R_X86_64_64 or GLOB_DAT import at 0x1800 converts with --windows at exit 0, no stderr, and the first 8 bytes of the .gtls template (found via the TLS directory) are 00 instead of 01..08. A control import at 0x1100 keeps 0102030405060708. Same with --windows --lazy-binding. On the merge both 0x1800 cases exit 2 with FAIL: Runtime-bound executable TLS template relocation is not supported (offset 0x1800), and the control is unchanged.
  • ctest -R 'executable_tls_relocations|windows_tls|tls_function_coverage|macos_tls|guest_tls|executable_export_bounds' on the merge: 41/41 pass.
  • tools/check_conventions.py --base origin/main: pass.

Code read:

  • Overlap math: TargetRva and GetRva are both uint32_t and get widened before the add, so no wrap. The half-open test leaves out 0x17f8 and 0x1808, and the reported offset is the ELF vaddr.
  • At that point Imports only holds named executable imports of types 1/6/7 (WindowsRelocationBuilder.cpp:73). RELATIVE, TPOFF64/DTPOFF64 and empty-name weak imports are written statically, so no false positives.
  • Lazy mode needs the check too: the lazy GOT stubs go into the image slot after WindowsTlsBuilder has already copied the template (WindowsPePatcher.cpp:109 vs :78).
  • Same rule as the existing guest refusal in WindowsGuestModuleWriter.cpp:38.

Small non-blocking note: none of the fixtures use a JUMP_SLOT in .rela.plt. The check doesn't look at the type, so it's covered anyway.

Looks good to me.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5643097896 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/10947#pullrequestreview-5643097896). Originally posted by [ahmadmuj](https://github.com/ahmadmuj) on 2026-10-25T11:54:15Z. **Review:** APPROVED --- Reviewed head `a54a939924` merged onto main `a5a780eaaa` (clean merge). Linux x86_64, GCC 13.3, Release, relinker-only build. What I ran: - `executable_tls_relocations` (this PR's version) with main's relinker: fails at `('template-import-1800-1-1', 0, '')`, same as your Windows counter-check. With the merged relinker: pass. Main's version of the test passes on both. - The silent corruption on main, read back from the PE: an `R_X86_64_64` or `GLOB_DAT` import at 0x1800 converts with `--windows` at exit 0, no stderr, and the first 8 bytes of the `.gtls` template (found via the TLS directory) are `00` instead of `01..08`. A control import at 0x1100 keeps `0102030405060708`. Same with `--windows --lazy-binding`. On the merge both 0x1800 cases exit 2 with `FAIL: Runtime-bound executable TLS template relocation is not supported (offset 0x1800)`, and the control is unchanged. - `ctest -R 'executable_tls_relocations|windows_tls|tls_function_coverage|macos_tls|guest_tls|executable_export_bounds'` on the merge: 41/41 pass. - `tools/check_conventions.py --base origin/main`: pass. Code read: - Overlap math: `TargetRva` and `GetRva` are both `uint32_t` and get widened before the add, so no wrap. The half-open test leaves out 0x17f8 and 0x1808, and the reported offset is the ELF vaddr. - At that point `Imports` only holds named executable imports of types 1/6/7 (`WindowsRelocationBuilder.cpp:73`). RELATIVE, TPOFF64/DTPOFF64 and empty-name weak imports are written statically, so no false positives. - Lazy mode needs the check too: the lazy GOT stubs go into the image slot after `WindowsTlsBuilder` has already copied the template (`WindowsPePatcher.cpp:109` vs `:78`). - Same rule as the existing guest refusal in `WindowsGuestModuleWriter.cpp:38`. Small non-blocking note: none of the fixtures use a `JUMP_SLOT` in `.rela.plt`. The check doesn't look at the type, so it's covered anyway. Looks good to me.
MarcZX10 commented 2026-10-25 13:34:51 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-25T13:34:51Z.

Review: DISMISSED


Follow-up after manually merging the two PRs for the overlap check: #6713 changes the nearbyintf debt note from #10947’s console-observed MXCSR behavior to “uses the host rounding mode, not the console’s,” and changes _Thrd_sleep from retrying through EINTR on Windows/POSIX details to a POSIX cancellation-point description. These are separate entries from this PR’s added TLS-relocation debt note, but the combined file currently has contradictory nearbyintf observations and duplicate _Thrd_sleep entries with differing behavior. Please coordinate with #6713’s author and resolve/update the debt entries so the merge preserves both the TLS note and one evidence-consistent description for each libc behavior; update the overlap/dependency checklist as needed. I have not found a conflict in the code paths, and this request is limited to the documentation state when the branches are combined.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5643417581 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/10947#pullrequestreview-5643417581). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-25T13:34:51Z. **Review:** DISMISSED --- Follow-up after manually merging the two PRs for the overlap check: #6713 changes the `nearbyintf` debt note from #10947’s console-observed MXCSR behavior to “uses the host rounding mode, not the console’s,” and changes `_Thrd_sleep` from retrying through `EINTR` on Windows/POSIX details to a POSIX cancellation-point description. These are separate entries from this PR’s added TLS-relocation debt note, but the combined file currently has contradictory `nearbyintf` observations and duplicate `_Thrd_sleep` entries with differing behavior. Please coordinate with #6713’s author and resolve/update the debt entries so the merge preserves both the TLS note and one evidence-consistent description for each libc behavior; update the overlap/dependency checklist as needed. I have not found a conflict in the code paths, and this request is limited to the documentation state when the branches are combined.
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
boykopovar/AnyPS5!10947
No description provided.