fix(relinker): ignore segment overrides on fixed-ES string instructions #11276

Merged
plexerPK merged 1 commit from upstream-pr/11276 into main 2026-10-27 02:02:00 +00:00
plexerPK commented 2026-10-25 23:32:27 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by plexerPK on 2026-10-25T23:32:27Z.


What

Ignore ineffective FS/GS overrides on the fixed-ES INS, STOS and SCAS opcode families while retaining their implicit memory-operand classification. Main currently rejects FS-prefixed forms as unsupported TLS accesses or replaces GS-prefixed forms with UD2. Source-string forms keep their existing segment handling.

This follows Intel SDM Volume 2, the INS, STOS and SCAS instruction descriptions, which specify the fixed ES destination/access. It follows merged #9719 as agreed with its author and preserves that change's LEA/NOP memory classification. #9719 merged at 2026-10-25T23:15:59Z as 2b5225605bd58c91fff82a7dafcb8c6e9a33d569.

Tested

macOS arm64, AppleClang 21.0.0.21000334, Python 3.9.6, CMake 4.4.4 and Ninja 1.13.2.git.kitware.jobserver-pipe-1. Prepared head bb45d3315d276b8aae4ca6eba705ea4b4d6a31e9 on main 2b5225605bd58c91fff82a7dafcb8c6e9a33d569.

The focused tests ran at c01f2f6f8a494d2e31bf2817b5564ad4af663290 before relocating the three-line CTest registration to avoid an insertion conflict with #10946. All production and test-source blobs are byte-identical at the prepared head; CMake regeneration reports Ninja has no work, and the eight selected test names, commands and properties are unchanged.

Built fresh relinker-only Release binaries and decoder_length_tests from both pinned source trees (90 Ninja steps each). Head passes 8/8 focused CTests: decoder_length, ignored_string_segments, macos_gs_traps, tls_diagnostics and the rejected/gs_traps/gs_traps_implicit/gs_non_memory TLS coverage groups. The matching seven existing groups pass 7/7 on main, including merged #9719's LEA/NOP coverage. The new conversion regression fails on main at windows-646c with the expected unsupported TLS diagnostic and passes all 96 byte-preservation conversion cases with the fix.

An additional 16 real CLI conversions compare FS INS, GS STOS and FS/GS MOVSB controls across Windows/macOS outputs on both binaries. Main rejects FS INS and emits UD2 for GS STOS; head preserves both fixed-ES forms. Source-string controls retain their previous rejection/trap behavior. Decoder coverage checks 28 FS/GS fixed-ES and neighboring source-string combinations retain their implicit memory classification and effective segment.

Conventions and whitespace checks pass. Fresh title/text/actual-file checks found no competing fixed-ES implementation; the initial official scan found only a CMake registration insertion collision with #10946, a distinct macOS TLS-export fix. Relocation removes it, and exact heads combine cleanly. The final official scan reports no detected overlapping compared regions and only the two old-base incomparable warnings below. The authored shared-CMake diffs for old-base #5021 and #6713 are unrelated fixture registrations; no full combined integration is claimed.

These are synthetic conversion, byte inspection and native arm64 tooling/metadata tests. No converted x86 guest execution, native Linux/Windows runtime, physical x86/console, title, GPU or hosted-CI result is claimed.

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: #9719 (merged)
  • Fixes: none
  • Unblocks: none
  • GPUs tested: n/a
  • AI-assisted: yes
<!-- greyfinch-sync:boykopovar/AnyPS5:issue:5009784123 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/11276). Originally posted by [plexerPK](https://github.com/plexerPK) on 2026-10-25T23:32:27Z. --- ### What Ignore ineffective FS/GS overrides on the fixed-ES INS, STOS and SCAS opcode families while retaining their implicit memory-operand classification. Main currently rejects FS-prefixed forms as unsupported TLS accesses or replaces GS-prefixed forms with UD2. Source-string forms keep their existing segment handling. This follows [Intel SDM Volume 2](https://cdrdv2-public.intel.com/774492/325383-sdm-vol-2abcd.pdf), the INS, STOS and SCAS instruction descriptions, which specify the fixed ES destination/access. It follows merged #9719 as agreed with its author and preserves that change's LEA/NOP memory classification. #9719 merged at 2026-10-25T23:15:59Z as `2b5225605bd58c91fff82a7dafcb8c6e9a33d569`. ### Tested macOS arm64, AppleClang 21.0.0.21000334, Python 3.9.6, CMake 4.4.4 and Ninja 1.13.2.git.kitware.jobserver-pipe-1. Prepared head `bb45d3315d276b8aae4ca6eba705ea4b4d6a31e9` on main `2b5225605bd58c91fff82a7dafcb8c6e9a33d569`. The focused tests ran at `c01f2f6f8a494d2e31bf2817b5564ad4af663290` before relocating the three-line CTest registration to avoid an insertion conflict with #10946. All production and test-source blobs are byte-identical at the prepared head; CMake regeneration reports Ninja has no work, and the eight selected test names, commands and properties are unchanged. Built fresh relinker-only Release binaries and decoder_length_tests from both pinned source trees (90 Ninja steps each). Head passes 8/8 focused CTests: decoder_length, ignored_string_segments, macos_gs_traps, tls_diagnostics and the rejected/gs_traps/gs_traps_implicit/gs_non_memory TLS coverage groups. The matching seven existing groups pass 7/7 on main, including merged #9719's LEA/NOP coverage. The new conversion regression fails on main at windows-646c with the expected unsupported TLS diagnostic and passes all 96 byte-preservation conversion cases with the fix. An additional 16 real CLI conversions compare FS INS, GS STOS and FS/GS MOVSB controls across Windows/macOS outputs on both binaries. Main rejects FS INS and emits UD2 for GS STOS; head preserves both fixed-ES forms. Source-string controls retain their previous rejection/trap behavior. Decoder coverage checks 28 FS/GS fixed-ES and neighboring source-string combinations retain their implicit memory classification and effective segment. Conventions and whitespace checks pass. Fresh title/text/actual-file checks found no competing fixed-ES implementation; the initial official scan found only a CMake registration insertion collision with #10946, a distinct macOS TLS-export fix. Relocation removes it, and exact heads combine cleanly. The final official scan reports no detected overlapping compared regions and only the two old-base incomparable warnings below. The authored shared-CMake diffs for old-base #5021 and #6713 are unrelated fixture registrations; no full combined integration is claimed. These are synthetic conversion, byte inspection and native arm64 tooling/metadata tests. No converted x86 guest execution, native Linux/Windows runtime, physical x86/console, title, GPU or hosted-CI result is claimed. <!-- 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. --> ### 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 --> #9719 (merged) - [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
MarcZX10 commented 2026-10-25 23:45:27 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-25T23:45:27Z.

Review: APPROVED


Reviewed exact head bb45d3315d276b8aae4ca6eba705ea4b4d6a31e9. The fixed-ES decoder change preserves implicit memory classification while ignoring ineffective FS/GS overrides for INS/STOS/SCAS; the added conversion and decoder cases cover neighboring source-string controls. The author reports the focused native macOS arm64 tooling suite, 8/8 head tests and 7/7 baseline tests, plus cross-format conversion checks. Hosted Ubuntu/Windows relinker and ASan checks pass; macOS relinker jobs remain queued, and product jobs are skipped by path policy. No blocking code issue found.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5645975849 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/11276#pullrequestreview-5645975849). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-25T23:45:27Z. **Review:** APPROVED --- Reviewed exact head `bb45d3315d276b8aae4ca6eba705ea4b4d6a31e9`. The fixed-ES decoder change preserves implicit memory classification while ignoring ineffective FS/GS overrides for INS/STOS/SCAS; the added conversion and decoder cases cover neighboring source-string controls. The author reports the focused native macOS arm64 tooling suite, 8/8 head tests and 7/7 baseline tests, plus cross-format conversion checks. Hosted Ubuntu/Windows relinker and ASan checks pass; macOS relinker jobs remain queued, and product jobs are skipped by path policy. No blocking code issue found.
thepoppfish commented 2026-10-26 00:41:59 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by thepoppfish on 2026-10-26T00:41:59Z.

Review: APPROVED


Reviewed exact head bb45d3315d276b8aae4ca6eba705ea4b4d6a31e9 and independently validated this on Windows 11 build 26200, Intel Core Ultra 7 268V, with GCC 16.2.0-6 UCRT64, CMake 4.3.1, Ninja 1.13.2 and Python 3.14.7. No blocking issue found.

The change keeps the implicit-memory classification and clears only the ineffective segment metadata for the six fixed-ES opcodes. Neighboring source-string instructions retain their segment handling; vector encodings return through their existing path before this new opcode check. Intel's XED instruction definitions at 0bcb623 also use the fixed ES operand for INS/STOS/SCAS.

I built fresh relinker-only Release relinker and decoder_length_tests binaries from all three trees (92 Ninja steps each): this head, main 97d33464c5ae244079d0e36d27340fc4aac276a0, and their clean local integration f4f8b17885440d04c50d786405ec93e2f4910cb7 (tree 93a9d8f952c81e8212a9a165bcc0d0a8ae3403bb). Relinker sources in the integration are byte-identical to this head, and each tree was built separately with its own headers.

  • Exact head: 8/8 focused CTests pass, 30.45s total, zero skips.
  • Main: 7/7 matching existing tests pass, 8.98s total, zero skips. Running the new conversion regression against this binary fails at windows-646c with Unsupported Windows guest TLS instruction (bytes: 64 6c).
  • Integration: 8/8 focused CTests pass, 15.42s total, zero skips. Both positive runs include all 96 new PE/Mach-O byte-preservation cases. Each individual test remains below 30 seconds.
  • An additional 84 real CLI conversions (28 per tree) cover FS/GS × Windows/macOS × the six fixed-ES opcodes plus MOVSB. On main, the 12 fixed-ES FS cases are rejected and the 12 GS cases become UD2. Both positive trees preserve those 24 instruction bodies. All three trees retain the MOVSB controls: two FS rejections and two GS traps per tree.
  • Conventions against the pinned main and whitespace checks pass for head and integration. Builds emitted no compiler warnings. This checks integration with the pinned main; it does not assert compatibility with every other open PR or repeat the canonical overlap scan.

Physical x86 check: I executed bounded STOS/SCAS byte sequences directly on this Intel CPU using a small Windows/Python ctypes probe, independently of the relinker. 5,040 executions, 20,160 independent state checks, and 3,360 FS/GS-versus-plain comparisons pass across 120 encodings. The probe checks all 512 data bytes, RDI, RCX and arithmetic flags against a separate Python model, rather than only comparing prefixed forms to each other. It covers byte/word/dword/qword widths, REP/REPE/REPNE where applicable, address-size override with memory at 0x10000000, counts 0/1/4, five accumulator values, and equal/mismatching scan patterns. Direction is forward (DF=0). GS:[0x30] returned a nonzero Windows TEB pointer. The probe restores nonvolatile RDI, does not change FS/GS bases, and performs no privileged I/O.

INS/OUTS were not executed on hardware; INS is covered here by source inspection, decoder tests and conversion-byte checks. The hardware probe executes the instruction sequences directly, not a converted guest executable. No complete AnyPS5 product runtime, console/title, Linux/macOS execution, GPU, performance or hosted-CI result is claimed. AI-assisted: yes.

Focused replay (select the corresponding checkout/build directory; omit ignored_string_segments on main):

cmake -S <checkout> -B <build> -G Ninja -DCMAKE_BUILD_TYPE=Release -DANYPS5_RELINKER_ONLY=ON -DBUILD_TESTING=ON
cmake --build <build> --target relinker decoder_length_tests -j 4
ctest --test-dir <build> -R '^(decoder_length|ignored_string_segments|macos_gs_traps|tls_diagnostics|tls_function_coverage_(rejected|gs_traps|gs_traps_implicit|gs_non_memory))$' --output-on-failure
Reproducible Windows x86 hardware probe (Python standard library)

Save as probe.py and run python probe.py hardware.json using 64-bit Windows Python. The generated function uses the Windows x64 ABI. No INS/OUTS instructions are present.

import ctypes as C
import json
from pathlib import Path
import platform
import sys

k = C.WinDLL('kernel32', use_last_error=True)
k.VirtualAlloc.argtypes = [C.c_void_p, C.c_size_t, C.c_ulong, C.c_ulong]
k.VirtualAlloc.restype = C.c_void_p
k.VirtualFree.argtypes = [C.c_void_p, C.c_size_t, C.c_ulong]
k.FlushInstructionCache.argtypes = [C.c_void_p, C.c_void_p, C.c_size_t]
k.GetCurrentProcess.restype = C.c_void_p
data = next((p for hint in range(0x10000000, 0x70000000, 0x1000000)
             if (p := k.VirtualAlloc(hint, 4096, 0x3000, 4))), None)
assert data and data + 4096 < 2**32
code = k.VirtualAlloc(None, 4096, 0x3000, 0x40)
assert code
buffer = (C.c_ubyte * 512).from_address(data)
out = (C.c_uint64 * 3)()
fn = C.WINFUNCTYPE(None, C.c_void_p, C.c_uint64, C.c_uint64, C.c_void_p)(code)
maskflags = 0x8d5
checks = runs = comparisons = 0
forms = set()

def putcode(b):
    C.memmove(code, b, len(b))
    assert k.FlushInstructionCache(k.GetCurrentProcess(), code, len(b))

putcode(bytes.fromhex('65 48 8b 04 25 30 00 00 00 c3'))
teb = C.WINFUNCTYPE(C.c_uint64)(code)()
assert teb

def flags(a, b, width):
    bit = 1 << (8 * width - 1)
    d = (a - b) & (bit * 2 - 1)
    return ((a < b) | ((d & 255).bit_count() % 2 == 0) << 2
            | bool((a ^ b ^ d) & 16) << 4 | (d == 0) << 6
            | bool(d & bit) << 7 | bool((a ^ b) & (a ^ d) & bit) << 11)

def execute(op, prefixes, segment, accumulator, count, pattern):
    global checks, runs
    width = 1 if op in (0xaa, 0xae) else 8 if 0x48 in prefixes else 2 if 0x66 in prefixes else 4
    a = accumulator & ((1 << (width * 8)) - 1)
    initial = bytearray([0x5a] * 512)
    if op in (0xae, 0xaf):
        for i in range(8):
            equal = pattern == 0 or (pattern == 2 and i < 2) or (pattern == 3 and i >= 2)
            value = a if equal else a ^ ((1 << (width * 8)) - 1)
            initial[64+i*width:64+(i+1)*width] = value.to_bytes(width, 'little')
    expected = initial.copy()
    rep = 0xf3 if 0xf3 in prefixes else 0xf2 if 0xf2 in prefixes else 0
    iterations, f = 0, 0x44
    for i in range(count if rep else 1):
        iterations += 1
        off = 64 + i * width
        if op in (0xaa, 0xab):
            expected[off:off+width] = a.to_bytes(width, 'little')
        else:
            b = int.from_bytes(initial[off:off+width], 'little')
            f = flags(a, b, width)
            if rep and ((rep == 0xf3 and a != b) or (rep == 0xf2 and a == b)):
                break
    instruction = bytes([segment] if segment else []) + bytes(prefixes) + bytes([op])
    forms.add(instruction.hex())
    putcode(bytes.fromhex('57 48 89 cf 48 89 d0 4c 89 c1 48 39 c0 fc') + instruction
            + bytes.fromhex('49 89 39 49 89 49 08 9c 58 49 89 41 10 5f c3'))
    buffer[:] = initial
    out[:] = (0, 0, 0)
    fn(data + 64, accumulator, count, C.addressof(out))
    runs += 1
    observed = (bytes(buffer), out[0], out[1], out[2] & maskflags)
    wanted = (bytes(expected), data + 64 + iterations * width, count - iterations if rep else count, f)
    for n, (got, want) in enumerate(zip(observed, wanted)):
        checks += 1
        assert got == want, (instruction.hex(), hex(accumulator), count, pattern, n, str(got), str(want))
    return observed

try:
    base_forms = [[], [0x66], [0x48], [0xf3], [0xf3, 0x66], [0xf3, 0x48], [0x67], [0xf3, 0x67]]
    for op in (0xaa, 0xab, 0xae, 0xaf):
        prefixes_forms = base_forms + ([[0xf2], [0xf2, 0x66], [0xf2, 0x48], [0xf2, 0x67]] if op >= 0xae else [])
        for prefixes in prefixes_forms:
            for acc in (0, 1, 0x8123456789abcdef, 0x8000000000000000, 0x7fffffffffffffff):
                for count in (0, 1, 4):
                    for pattern in (range(4) if op >= 0xae else [0]):
                        baseline = execute(op, prefixes, 0, acc, count, pattern)
                        for segment in (0x64, 0x65):
                            actual = execute(op, prefixes, segment, acc, count, pattern)
                            comparisons += 1
                            assert actual == baseline
    result = dict(platform=platform.platform(), python=platform.python_version(),
                  data_address=hex(data), gs_teb_address=hex(teb), instruction_forms=len(forms),
                  executions=runs, independent_state_checks=checks,
                  segment_vs_plain_comparisons=comparisons, failures=0,
                  instructions='STOSB/STOSW/STOSD/STOSQ and SCASB/SCASW/SCASD/SCASQ',
                  not_executed='INS and OUTS; no privileged port I/O')
    Path(sys.argv[1]).write_text(json.dumps(result, indent=2) + '\n')
    print(json.dumps(result))
finally:
    k.VirtualFree(code, 0, 0x8000)
    k.VirtualFree(data, 0, 0x8000)
Additional 84-conversion replay

Save as check_cli.py and run python check_cli.py <head-checkout> <main-relinker.exe> <head-relinker.exe> <merged-relinker.exe> cli.json. This reuses the committed ELF and output parsers without modifying them.

import json
from pathlib import Path
import subprocess
import sys
import tempfile

sys.path.insert(0, str(Path(sys.argv[1]).resolve() / 'core/relinker/relinker/tests'))
from test_macos_output import MachO
from test_tls_function_coverage import make_image, pe_bytes_at

rows = []
with tempfile.TemporaryDirectory(prefix='anyps5-review11276-') as directory:
    root = Path(directory)
    for variant, binary in zip(('main', 'head', 'merged'), sys.argv[2:5]):
        for target in ('windows', 'macos'):
            for segment in (0x64, 0x65):
                for opcode in (0x6c, 0x6d, 0xaa, 0xab, 0xae, 0xaf, 0xa4):
                    name = f'{variant}-{target}-{segment:02x}{opcode:02x}'
                    body = bytes([segment, opcode, 0xc3])
                    source, output = root / (name + '.elf'), root / name
                    source.write_bytes(make_image('register', 'unwind', body=body))
                    result = subprocess.run([str(Path(binary).resolve()), '--' + target, '--skip-sce-module', str(source), str(output)],
                                            capture_output=True, text=True, timeout=20)
                    if result.returncode:
                        text = result.stdout + result.stderr
                        assert segment == 0x64 and (variant == 'main' or opcode == 0xa4), (name, text)
                        assert 'Unsupported' in text and 'TLS instruction' in text, (name, text)
                        actual, status = None, 'rejected-fs'
                    else:
                        data = output.read_bytes()
                        if target == 'windows':
                            actual = pe_bytes_at(data, 0x11240, len(body))
                        else:
                            s = next(s for s in MachO(data).segments if s['vmaddr'] <= 0x140011240 < s['vmaddr'] + s['filesize'])
                            off = s['fileoff'] + 0x140011240 - s['vmaddr']
                            actual = data[off:off+len(body)]
                        expected = body if variant != 'main' and opcode != 0xa4 else bytes.fromhex('0f0bc3')
                        assert actual == expected, (name, actual.hex(), expected.hex())
                        status = 'preserved' if actual == body else 'trapped-gs'
                    rows.append(dict(variant=variant, target=target, instruction=body[:-1].hex(), status=status,
                                     returncode=result.returncode, bytes=None if actual is None else actual.hex()))
Path(sys.argv[5]).write_text(json.dumps(rows, indent=2) + '\n')
from collections import Counter
print(json.dumps(dict(conversions=len(rows), outcomes=dict(Counter(r['variant'] + ':' + r['status'] for r in rows)))))
<!-- greyfinch-sync:boykopovar/AnyPS5:review:5646216034 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/11276#pullrequestreview-5646216034). Originally posted by [thepoppfish](https://github.com/thepoppfish) on 2026-10-26T00:41:59Z. **Review:** APPROVED --- Reviewed exact head `bb45d3315d276b8aae4ca6eba705ea4b4d6a31e9` and independently validated this on Windows 11 build 26200, Intel Core Ultra 7 268V, with GCC 16.2.0-6 UCRT64, CMake 4.3.1, Ninja 1.13.2 and Python 3.14.7. No blocking issue found. The change keeps the implicit-memory classification and clears only the ineffective segment metadata for the six fixed-ES opcodes. Neighboring source-string instructions retain their segment handling; vector encodings return through their existing path before this new opcode check. Intel's [XED instruction definitions at 0bcb623](https://github.com/intelxed/xed/blob/0bcb6237345c5066726dcc08b3d87928df3b5b26/datafiles/xed-isa.txt#L6513) also use the fixed ES operand for INS/STOS/SCAS. I built fresh relinker-only Release `relinker` and `decoder_length_tests` binaries from all three trees (92 Ninja steps each): this head, main `97d33464c5ae244079d0e36d27340fc4aac276a0`, and their clean local integration `f4f8b17885440d04c50d786405ec93e2f4910cb7` (tree `93a9d8f952c81e8212a9a165bcc0d0a8ae3403bb`). Relinker sources in the integration are byte-identical to this head, and each tree was built separately with its own headers. - Exact head: **8/8 focused CTests pass**, 30.45s total, zero skips. - Main: **7/7 matching existing tests pass**, 8.98s total, zero skips. Running the new conversion regression against this binary fails at `windows-646c` with `Unsupported Windows guest TLS instruction (bytes: 64 6c)`. - Integration: **8/8 focused CTests pass**, 15.42s total, zero skips. Both positive runs include all 96 new PE/Mach-O byte-preservation cases. Each individual test remains below 30 seconds. - An additional **84 real CLI conversions** (28 per tree) cover FS/GS × Windows/macOS × the six fixed-ES opcodes plus MOVSB. On main, the 12 fixed-ES FS cases are rejected and the 12 GS cases become UD2. Both positive trees preserve those 24 instruction bodies. All three trees retain the MOVSB controls: two FS rejections and two GS traps per tree. - Conventions against the pinned main and whitespace checks pass for head and integration. Builds emitted no compiler warnings. This checks integration with the pinned main; it does not assert compatibility with every other open PR or repeat the canonical overlap scan. **Physical x86 check:** I executed bounded STOS/SCAS byte sequences directly on this Intel CPU using a small Windows/Python ctypes probe, independently of the relinker. **5,040 executions, 20,160 independent state checks, and 3,360 FS/GS-versus-plain comparisons pass** across 120 encodings. The probe checks all 512 data bytes, RDI, RCX and arithmetic flags against a separate Python model, rather than only comparing prefixed forms to each other. It covers byte/word/dword/qword widths, REP/REPE/REPNE where applicable, address-size override with memory at `0x10000000`, counts 0/1/4, five accumulator values, and equal/mismatching scan patterns. Direction is forward (DF=0). GS:[0x30] returned a nonzero Windows TEB pointer. The probe restores nonvolatile RDI, does not change FS/GS bases, and performs no privileged I/O. INS/OUTS were **not executed on hardware**; INS is covered here by source inspection, decoder tests and conversion-byte checks. The hardware probe executes the instruction sequences directly, not a converted guest executable. No complete AnyPS5 product runtime, console/title, Linux/macOS execution, GPU, performance or hosted-CI result is claimed. AI-assisted: yes. Focused replay (select the corresponding checkout/build directory; omit `ignored_string_segments` on main): ```powershell cmake -S <checkout> -B <build> -G Ninja -DCMAKE_BUILD_TYPE=Release -DANYPS5_RELINKER_ONLY=ON -DBUILD_TESTING=ON cmake --build <build> --target relinker decoder_length_tests -j 4 ctest --test-dir <build> -R '^(decoder_length|ignored_string_segments|macos_gs_traps|tls_diagnostics|tls_function_coverage_(rejected|gs_traps|gs_traps_implicit|gs_non_memory))$' --output-on-failure ``` <details><summary>Reproducible Windows x86 hardware probe (Python standard library)</summary> Save as `probe.py` and run `python probe.py hardware.json` using 64-bit Windows Python. The generated function uses the Windows x64 ABI. No INS/OUTS instructions are present. ```python import ctypes as C import json from pathlib import Path import platform import sys k = C.WinDLL('kernel32', use_last_error=True) k.VirtualAlloc.argtypes = [C.c_void_p, C.c_size_t, C.c_ulong, C.c_ulong] k.VirtualAlloc.restype = C.c_void_p k.VirtualFree.argtypes = [C.c_void_p, C.c_size_t, C.c_ulong] k.FlushInstructionCache.argtypes = [C.c_void_p, C.c_void_p, C.c_size_t] k.GetCurrentProcess.restype = C.c_void_p data = next((p for hint in range(0x10000000, 0x70000000, 0x1000000) if (p := k.VirtualAlloc(hint, 4096, 0x3000, 4))), None) assert data and data + 4096 < 2**32 code = k.VirtualAlloc(None, 4096, 0x3000, 0x40) assert code buffer = (C.c_ubyte * 512).from_address(data) out = (C.c_uint64 * 3)() fn = C.WINFUNCTYPE(None, C.c_void_p, C.c_uint64, C.c_uint64, C.c_void_p)(code) maskflags = 0x8d5 checks = runs = comparisons = 0 forms = set() def putcode(b): C.memmove(code, b, len(b)) assert k.FlushInstructionCache(k.GetCurrentProcess(), code, len(b)) putcode(bytes.fromhex('65 48 8b 04 25 30 00 00 00 c3')) teb = C.WINFUNCTYPE(C.c_uint64)(code)() assert teb def flags(a, b, width): bit = 1 << (8 * width - 1) d = (a - b) & (bit * 2 - 1) return ((a < b) | ((d & 255).bit_count() % 2 == 0) << 2 | bool((a ^ b ^ d) & 16) << 4 | (d == 0) << 6 | bool(d & bit) << 7 | bool((a ^ b) & (a ^ d) & bit) << 11) def execute(op, prefixes, segment, accumulator, count, pattern): global checks, runs width = 1 if op in (0xaa, 0xae) else 8 if 0x48 in prefixes else 2 if 0x66 in prefixes else 4 a = accumulator & ((1 << (width * 8)) - 1) initial = bytearray([0x5a] * 512) if op in (0xae, 0xaf): for i in range(8): equal = pattern == 0 or (pattern == 2 and i < 2) or (pattern == 3 and i >= 2) value = a if equal else a ^ ((1 << (width * 8)) - 1) initial[64+i*width:64+(i+1)*width] = value.to_bytes(width, 'little') expected = initial.copy() rep = 0xf3 if 0xf3 in prefixes else 0xf2 if 0xf2 in prefixes else 0 iterations, f = 0, 0x44 for i in range(count if rep else 1): iterations += 1 off = 64 + i * width if op in (0xaa, 0xab): expected[off:off+width] = a.to_bytes(width, 'little') else: b = int.from_bytes(initial[off:off+width], 'little') f = flags(a, b, width) if rep and ((rep == 0xf3 and a != b) or (rep == 0xf2 and a == b)): break instruction = bytes([segment] if segment else []) + bytes(prefixes) + bytes([op]) forms.add(instruction.hex()) putcode(bytes.fromhex('57 48 89 cf 48 89 d0 4c 89 c1 48 39 c0 fc') + instruction + bytes.fromhex('49 89 39 49 89 49 08 9c 58 49 89 41 10 5f c3')) buffer[:] = initial out[:] = (0, 0, 0) fn(data + 64, accumulator, count, C.addressof(out)) runs += 1 observed = (bytes(buffer), out[0], out[1], out[2] & maskflags) wanted = (bytes(expected), data + 64 + iterations * width, count - iterations if rep else count, f) for n, (got, want) in enumerate(zip(observed, wanted)): checks += 1 assert got == want, (instruction.hex(), hex(accumulator), count, pattern, n, str(got), str(want)) return observed try: base_forms = [[], [0x66], [0x48], [0xf3], [0xf3, 0x66], [0xf3, 0x48], [0x67], [0xf3, 0x67]] for op in (0xaa, 0xab, 0xae, 0xaf): prefixes_forms = base_forms + ([[0xf2], [0xf2, 0x66], [0xf2, 0x48], [0xf2, 0x67]] if op >= 0xae else []) for prefixes in prefixes_forms: for acc in (0, 1, 0x8123456789abcdef, 0x8000000000000000, 0x7fffffffffffffff): for count in (0, 1, 4): for pattern in (range(4) if op >= 0xae else [0]): baseline = execute(op, prefixes, 0, acc, count, pattern) for segment in (0x64, 0x65): actual = execute(op, prefixes, segment, acc, count, pattern) comparisons += 1 assert actual == baseline result = dict(platform=platform.platform(), python=platform.python_version(), data_address=hex(data), gs_teb_address=hex(teb), instruction_forms=len(forms), executions=runs, independent_state_checks=checks, segment_vs_plain_comparisons=comparisons, failures=0, instructions='STOSB/STOSW/STOSD/STOSQ and SCASB/SCASW/SCASD/SCASQ', not_executed='INS and OUTS; no privileged port I/O') Path(sys.argv[1]).write_text(json.dumps(result, indent=2) + '\n') print(json.dumps(result)) finally: k.VirtualFree(code, 0, 0x8000) k.VirtualFree(data, 0, 0x8000) ``` </details> <details><summary>Additional 84-conversion replay</summary> Save as `check_cli.py` and run `python check_cli.py <head-checkout> <main-relinker.exe> <head-relinker.exe> <merged-relinker.exe> cli.json`. This reuses the committed ELF and output parsers without modifying them. ```python import json from pathlib import Path import subprocess import sys import tempfile sys.path.insert(0, str(Path(sys.argv[1]).resolve() / 'core/relinker/relinker/tests')) from test_macos_output import MachO from test_tls_function_coverage import make_image, pe_bytes_at rows = [] with tempfile.TemporaryDirectory(prefix='anyps5-review11276-') as directory: root = Path(directory) for variant, binary in zip(('main', 'head', 'merged'), sys.argv[2:5]): for target in ('windows', 'macos'): for segment in (0x64, 0x65): for opcode in (0x6c, 0x6d, 0xaa, 0xab, 0xae, 0xaf, 0xa4): name = f'{variant}-{target}-{segment:02x}{opcode:02x}' body = bytes([segment, opcode, 0xc3]) source, output = root / (name + '.elf'), root / name source.write_bytes(make_image('register', 'unwind', body=body)) result = subprocess.run([str(Path(binary).resolve()), '--' + target, '--skip-sce-module', str(source), str(output)], capture_output=True, text=True, timeout=20) if result.returncode: text = result.stdout + result.stderr assert segment == 0x64 and (variant == 'main' or opcode == 0xa4), (name, text) assert 'Unsupported' in text and 'TLS instruction' in text, (name, text) actual, status = None, 'rejected-fs' else: data = output.read_bytes() if target == 'windows': actual = pe_bytes_at(data, 0x11240, len(body)) else: s = next(s for s in MachO(data).segments if s['vmaddr'] <= 0x140011240 < s['vmaddr'] + s['filesize']) off = s['fileoff'] + 0x140011240 - s['vmaddr'] actual = data[off:off+len(body)] expected = body if variant != 'main' and opcode != 0xa4 else bytes.fromhex('0f0bc3') assert actual == expected, (name, actual.hex(), expected.hex()) status = 'preserved' if actual == body else 'trapped-gs' rows.append(dict(variant=variant, target=target, instruction=body[:-1].hex(), status=status, returncode=result.returncode, bytes=None if actual is None else actual.hex())) Path(sys.argv[5]).write_text(json.dumps(rows, indent=2) + '\n') from collections import Counter print(json.dumps(dict(conversions=len(rows), outcomes=dict(Counter(r['variant'] + ':' + r['status'] for r in rows))))) ``` </details>
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!11276
No description provided.