feat(relinker): support Windows guest TLS reads by ALU register-address instructions #1651

Merged
emirplus merged 2 commits from upstream-pr/1651 into main 2026-10-10 05:58:53 +00:00
emirplus commented 2026-10-08 15:40:43 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by emirplus on 2026-10-08T15:40:43Z.


What

Recognize read-direction ALU forms (add, or, adc, sbb, and, sub, xor, cmp) reading from fs:[mem] where mem has a base or index register (such as 64 48 33 03, xor rax, fs:[rbx], reported on NHL 27 in #217).

Following the approach from #767 (for disp32 ALU) and #1233 (for register-addressed MOV loads):

  • Recognizes ALU read opcodes combined with register-based memory operands.
  • Generates a Windows TLS stub that computes the offset via lea, loads the thread pointer, performs the ALU operation against [thread_pointer + offset], and restores scratch registers without disturbing arithmetic flags.
  • Handles destination registers rax, rcx, and general/extended registers (rbx..r15), for both 64-bit and 32-bit forms.
  • Re-relocates sequential instructions when the TLS instruction is shorter than the 5-byte jump.

Tested

  • Extended core/relinker/relinker/tests/test_tls_function_coverage.py with:
    • Execution cases for xor rax, fs:[rbx], xor rcx, fs:[rax], xor rbx, fs:[rax], add rax, fs:[rbx], cmp rax, fs:[rbx], xor r13, fs:[rbx + rcx - 0x10] (SIB + disp8), and 32-bit xor edx, fs:[rbx].
    • Self-checking verification of computed results, register preservation across all 16 registers, and flag states (ZF, CF).
    • Stub disassembly/byte sequence matching.
    • Short-instruction relocation error verification (short-alu-before-return).
    • Removed register-address-alu from the rejected list.
  • All 4 TLS tests (empty_tls, tls_function_coverage, tls_diagnostics, guest_tls) pass 100% under ctest.
  • check_conventions.py passes with zero violations.

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 in TechnicalDebt
  • 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
  • AI-assisted: yes

Refs #217

Co-Authored-By: Claude Opus 5.5 [email protected]

<!-- greyfinch-sync:boykopovar/AnyPS5:issue:4789255510 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/1651). Originally posted by [emirplus](https://github.com/emirplus) on 2026-10-08T15:40:43Z. --- ### What Recognize read-direction ALU forms (`add`, `or`, `adc`, `sbb`, `and`, `sub`, `xor`, `cmp`) reading from `fs:[mem]` where `mem` has a base or index register (such as `64 48 33 03`, `xor rax, fs:[rbx]`, reported on NHL 27 in #217). Following the approach from #767 (for disp32 ALU) and #1233 (for register-addressed MOV loads): - Recognizes ALU read opcodes combined with register-based memory operands. - Generates a Windows TLS stub that computes the offset via `lea`, loads the thread pointer, performs the ALU operation against `[thread_pointer + offset]`, and restores scratch registers without disturbing arithmetic flags. - Handles destination registers `rax`, `rcx`, and general/extended registers (`rbx`..`r15`), for both 64-bit and 32-bit forms. - Re-relocates sequential instructions when the TLS instruction is shorter than the 5-byte jump. ### Tested - Extended `core/relinker/relinker/tests/test_tls_function_coverage.py` with: - Execution cases for `xor rax, fs:[rbx]`, `xor rcx, fs:[rax]`, `xor rbx, fs:[rax]`, `add rax, fs:[rbx]`, `cmp rax, fs:[rbx]`, `xor r13, fs:[rbx + rcx - 0x10]` (SIB + disp8), and 32-bit `xor edx, fs:[rbx]`. - Self-checking verification of computed results, register preservation across all 16 registers, and flag states (ZF, CF). - Stub disassembly/byte sequence matching. - Short-instruction relocation error verification (`short-alu-before-return`). - Removed `register-address-alu` from the rejected list. - All 4 TLS tests (`empty_tls`, `tls_function_coverage`, `tls_diagnostics`, `guest_tls`) pass 100% under ctest. - `check_conventions.py` passes with zero violations. ### 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 in [TechnicalDebt](https://github.com/boykopovar/AnyPS5/blob/main/docs/dev/TechnicalDebt.md#silent-stubs) - [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: none - [x] AI-assisted: yes Refs #217 Co-Authored-By: Claude Opus 5.5 <[email protected]>
hashaam1217 commented 2026-10-08 17:50:44 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by hashaam1217 on 2026-10-08T17:50:44Z.


Tested on Linux x86-64 (Ubuntu 24.04.5, GCC 13.3.0), merged onto 6b56175a. windows_image_runner.py executes every converted case there. tls_function_coverage, tls_diagnostics, empty_tls and guest_tls pass.

One bug, in the 32-bit rcx path. It restores rcx with mov ecx, [rsp+8], which zeroes rcx's upper half. For the ops that write ecx that doesn't matter, since the 32-bit result zero-extends anyway. cmp writes nothing, though, so cmp ecx, fs:[rax] (64 3b 08) comes back with rcx's upper 32 bits cleared. The test doesn't catch it because register_alu_body also sets the expected value of a 32-bit cmp destination to res & 0xffffffff.

With the case below and cmp keeping the full register in the expectation, register-alu-cmp-ecx-rax-202 fails (the runner exits 1). Restoring the full rcx before the 32-bit op fixes it.

I also added adc and sbb cases, run with both of the existing flag values (CF clear and set). They pass, so the stubs keep the incoming carry. Note that the flags the ALU op produces aren't compared after it; only registers are. Everything after the op in these stubs is pop/lea, so they survive, but nothing guards that.

--- a/core/relinker/elfpatcher/src/windows/WindowsTlsBuilder.cpp
+++ b/core/relinker/elfpatcher/src/windows/WindowsTlsBuilder.cpp
@@ -261,5 +261,5 @@
                     code.Emit({0x48, 0x8b, 0x4c, 0x24, 0x08, 0x48, access.AluOpcode, 0xc8});
                 else
-                    code.Emit({0x8b, 0x4c, 0x24, 0x08, access.AluOpcode, 0xc8});
+                    code.Emit({0x48, 0x8b, 0x4c, 0x24, 0x08, access.AluOpcode, 0xc8});
                 code.Emit({0x58});
--- a/core/relinker/relinker/tests/test_tls_function_coverage.py
+++ b/core/relinker/relinker/tests/test_tls_function_coverage.py
@@ -243,4 +243,7 @@ REGISTER_ALUS = (
     ("xor-r13-rbx-rcx-disp8", bytes.fromhex("64 4c 33 6c 0b f0"), 0x33, 13, True, {3: 0x18, 1: -0x10}, -8),
     ("xor-edx-rbx", bytes.fromhex("64 33 13"), 0x33, 2, False, {3: 0x10}, 0x10),
+    ("cmp-ecx-rax", bytes.fromhex("64 3b 08"), 0x3b, 1, False, {0: 0x10}, 0x10),
+    ("adc-rax-rbx", bytes.fromhex("64 48 13 03"), 0x13, 0, True, {3: -8}, -8),
+    ("sbb-rcx-rax", bytes.fromhex("64 48 1b 08"), 0x1b, 1, True, {0: 0x10}, 0x10),
 )
 
@@ -379,7 +382,12 @@ def register_alu_body(instruction, opcode, register, wide, address, offset, flag
     elif opcode == 0x3b:
         res = base_val
+    elif opcode == 0x13:
+        res = (base_val + operand_val + (flags & 1)) & (mask if wide else 0xffffffff)
+    elif opcode == 0x1b:
+        res = (base_val - operand_val - (flags & 1)) & (mask if wide else 0xffffffff)
     else:
         raise ValueError(f"Unknown opcode: {opcode}")
-    expected[register] = res if wide else res & 0xffffffff
+    if opcode != 0x3b:
+        expected[register] = res if wide else res & 0xffffffff
     emit(b"\x68" + struct.pack("<I", flags) + b"\x9d")
     load_offset = len(code)
@@ -426,5 +434,5 @@ def register_alu_stub(instruction, opcode, register, wide):
     elif register == 1:
         load = (b"\x48" if wide else b"") + bytes.fromhex("8b 04 08")
-        restore_rcx = bytes.fromhex("48 8b 4c 24 08 48") + bytes([opcode, 0xc8]) if wide else bytes.fromhex("8b 4c 24 08") + bytes([opcode, 0xc8])
+        restore_rcx = bytes.fromhex("48 8b 4c 24 08 48") + bytes([opcode, 0xc8]) if wide else bytes.fromhex("48 8b 4c 24 08") + bytes([opcode, 0xc8])
         return bytes.fromhex("48 8d 64 24 80 51 50") + address + b"\x50", b"\x59" + load + restore_rcx + bytes.fromhex("58 48 8d 64 24 08 48 8d a4 24 80 00 00 00")
     else:

With both changes, all four tests pass on Linux.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6065805163 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/1651#issuecomment-6065805163). Originally posted by [hashaam1217](https://github.com/hashaam1217) on 2026-10-08T17:50:44Z. --- Tested on Linux x86-64 (Ubuntu 24.04.5, GCC 13.3.0), merged onto 6b56175a. `windows_image_runner.py` executes every converted case there. `tls_function_coverage`, `tls_diagnostics`, `empty_tls` and `guest_tls` pass. One bug, in the 32-bit `rcx` path. It restores rcx with `mov ecx, [rsp+8]`, which zeroes rcx's upper half. For the ops that write ecx that doesn't matter, since the 32-bit result zero-extends anyway. `cmp` writes nothing, though, so `cmp ecx, fs:[rax]` (`64 3b 08`) comes back with rcx's upper 32 bits cleared. The test doesn't catch it because `register_alu_body` also sets the expected value of a 32-bit `cmp` destination to `res & 0xffffffff`. With the case below and `cmp` keeping the full register in the expectation, `register-alu-cmp-ecx-rax-202` fails (the runner exits 1). Restoring the full rcx before the 32-bit op fixes it. I also added `adc` and `sbb` cases, run with both of the existing flag values (CF clear and set). They pass, so the stubs keep the incoming carry. Note that the flags the ALU op produces aren't compared after it; only registers are. Everything after the op in these stubs is `pop`/`lea`, so they survive, but nothing guards that. ```diff --- a/core/relinker/elfpatcher/src/windows/WindowsTlsBuilder.cpp +++ b/core/relinker/elfpatcher/src/windows/WindowsTlsBuilder.cpp @@ -261,5 +261,5 @@ code.Emit({0x48, 0x8b, 0x4c, 0x24, 0x08, 0x48, access.AluOpcode, 0xc8}); else - code.Emit({0x8b, 0x4c, 0x24, 0x08, access.AluOpcode, 0xc8}); + code.Emit({0x48, 0x8b, 0x4c, 0x24, 0x08, access.AluOpcode, 0xc8}); code.Emit({0x58}); --- a/core/relinker/relinker/tests/test_tls_function_coverage.py +++ b/core/relinker/relinker/tests/test_tls_function_coverage.py @@ -243,4 +243,7 @@ REGISTER_ALUS = ( ("xor-r13-rbx-rcx-disp8", bytes.fromhex("64 4c 33 6c 0b f0"), 0x33, 13, True, {3: 0x18, 1: -0x10}, -8), ("xor-edx-rbx", bytes.fromhex("64 33 13"), 0x33, 2, False, {3: 0x10}, 0x10), + ("cmp-ecx-rax", bytes.fromhex("64 3b 08"), 0x3b, 1, False, {0: 0x10}, 0x10), + ("adc-rax-rbx", bytes.fromhex("64 48 13 03"), 0x13, 0, True, {3: -8}, -8), + ("sbb-rcx-rax", bytes.fromhex("64 48 1b 08"), 0x1b, 1, True, {0: 0x10}, 0x10), ) @@ -379,7 +382,12 @@ def register_alu_body(instruction, opcode, register, wide, address, offset, flag elif opcode == 0x3b: res = base_val + elif opcode == 0x13: + res = (base_val + operand_val + (flags & 1)) & (mask if wide else 0xffffffff) + elif opcode == 0x1b: + res = (base_val - operand_val - (flags & 1)) & (mask if wide else 0xffffffff) else: raise ValueError(f"Unknown opcode: {opcode}") - expected[register] = res if wide else res & 0xffffffff + if opcode != 0x3b: + expected[register] = res if wide else res & 0xffffffff emit(b"\x68" + struct.pack("<I", flags) + b"\x9d") load_offset = len(code) @@ -426,5 +434,5 @@ def register_alu_stub(instruction, opcode, register, wide): elif register == 1: load = (b"\x48" if wide else b"") + bytes.fromhex("8b 04 08") - restore_rcx = bytes.fromhex("48 8b 4c 24 08 48") + bytes([opcode, 0xc8]) if wide else bytes.fromhex("8b 4c 24 08") + bytes([opcode, 0xc8]) + restore_rcx = bytes.fromhex("48 8b 4c 24 08 48") + bytes([opcode, 0xc8]) if wide else bytes.fromhex("48 8b 4c 24 08") + bytes([opcode, 0xc8]) return bytes.fromhex("48 8d 64 24 80 51 50") + address + b"\x50", b"\x59" + load + restore_rcx + bytes.fromhex("58 48 8d 64 24 08 48 8d a4 24 80 00 00 00") else: ``` With both changes, all four tests pass on Linux.
emirplus commented 2026-10-08 19:02:08 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by emirplus on 2026-10-08T19:02:08Z.


Thanks @hashaam1217 for catching the 32-bit
cx preservation bug and providing the regression cases.

Pushed 8c45db71:

  • Emits full 64-bit mov rcx, [rsp+8] (48 8b 4c 24 08) before the 32-bit ALU operation so non-writing instructions like cmp ecx, fs:[rax] preserve the upper 32 bits of
    cx intact (while writing ops zero-extend naturally).
  • Added cmp-ecx-rax, dc-rax-rbx, and sbb-rcx-rax test cases to REGISTER_ALUS.
  • Updated est_tls_function_coverage.py expectations to retain the full 64-bit value for cmp (opcode != 0x3b).
  • Verified that est_tls_function_coverage.py reproduces the failure prior to the fix (AssertionError: ('register-alu-cmp-ecx-rax-202', 1, b'')) and now passes 100% across all 4 TLS test suites (empty_tls, ls_function_coverage, ls_diagnostics, guest_tls).
<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6067006749 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/1651#issuecomment-6067006749). Originally posted by [emirplus](https://github.com/emirplus) on 2026-10-08T19:02:08Z. --- Thanks @hashaam1217 for catching the 32-bit cx preservation bug and providing the regression cases. Pushed 8c45db71: - Emits full 64-bit mov rcx, [rsp+8] (48 8b 4c 24 08) before the 32-bit ALU operation so non-writing instructions like cmp ecx, fs:[rax] preserve the upper 32 bits of cx intact (while writing ops zero-extend naturally). - Added cmp-ecx-rax, dc-rax-rbx, and sbb-rcx-rax test cases to REGISTER_ALUS. - Updated est_tls_function_coverage.py expectations to retain the full 64-bit value for cmp (opcode != 0x3b). - Verified that est_tls_function_coverage.py reproduces the failure prior to the fix (AssertionError: ('register-alu-cmp-ecx-rax-202', 1, b'')) and now passes 100% across all 4 TLS test suites (empty_tls, ls_function_coverage, ls_diagnostics, guest_tls).
oneandonlydean commented 2026-10-09 09:22:25 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-09T09:22:25Z.


The conventions job fails on the description: it needs the template's ### What, ### Tested and ### Checklist sections (## Testing isn't picked up). Editing the body is enough; the code jobs are green.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6078122683 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/1651#issuecomment-6078122683). Originally posted by [oneandonlydean](https://github.com/oneandonlydean) on 2026-10-09T09:22:25Z. --- The conventions job fails on the description: it needs the template's `### What`, `### Tested` and `### Checklist` sections (`## Testing` isn't picked up). Editing the body is enough; the code jobs are green.
adriadam10 commented 2026-10-10 05:58:50 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-10T05:58:50Z.


Checked the register/rax/rcx stub paths (64/32-bit, REX.R destinations): flags are untouched after the ALU op, scratch registers are restored, and cmp ecx, fs:[rax] keeps rcx's upper half. Local build and relinker ctest green; tls_function_coverage fails without the WindowsTlsBuilder.cpp change. Linux/Windows CI green.

I rewrote the PR body under the template headings (### What / ### Tested / ### Checklist) so the conventions check passes; your text is unchanged. Note #1913 also edits test_tls_function_coverage.py, so whichever lands second will need a rebase. Merging.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6094433656 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/1651#issuecomment-6094433656). Originally posted by [adriadam10](https://github.com/adriadam10) on 2026-10-10T05:58:50Z. --- Checked the register/rax/rcx stub paths (64/32-bit, REX.R destinations): flags are untouched after the ALU op, scratch registers are restored, and `cmp ecx, fs:[rax]` keeps rcx's upper half. Local build and relinker ctest green; `tls_function_coverage` fails without the `WindowsTlsBuilder.cpp` change. Linux/Windows CI green. I rewrote the PR body under the template headings (`### What` / `### Tested` / `### Checklist`) so the conventions check passes; your text is unchanged. Note #1913 also edits `test_tls_function_coverage.py`, so whichever lands second will need a rebase. Merging.
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!1651
No description provided.