From 74bab76c91b9341835855a0a192f9dda83fe1a2e Mon Sep 17 00:00:00 2001 From: MoonEyes <14891700+MoonEyes@users.noreply.github.com> Date: Thu, 26 Nov 2026 08:19:26 +0100 Subject: [PATCH 1/3] tests: fail when gta6rt.exe has TLS callbacks (TEST-GTA6RT-NO-TLS-CALLBACKS) A thread_local with a destructor gives gta6rt.exe __dyn_tls_init/__dyn_tls_dtor callbacks; the title's own _register_thread_local_exe_atexit_callback then fast-fails (0xC0000409). check_pe_tls_callbacks.py reads the PE TLS directory and fails on a non-empty list; a stdlib test checks it on two in-memory PE32+ images. Co-Authored-By: Claude Fable 5.2 --- runtime/CMakeLists.txt | 6 ++ runtime/test/check_pe_tls_callbacks.py | 84 ++++++++++++++++++++++++++ tests/test_check_pe_tls_callbacks.py | 68 +++++++++++++++++++++ 3 files changed, 158 insertions(+) create mode 100644 runtime/test/check_pe_tls_callbacks.py create mode 100644 tests/test_check_pe_tls_callbacks.py diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 10ee582b12..1be7ba3d11 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -945,6 +945,12 @@ if(BUILD_TESTING) "--report=${CMAKE_CURRENT_BINARY_DIR}/module-names-results.json") set_tests_properties(run_module_names PROPERTIES TIMEOUT 90) endif() + # TEST-GTA6RT-NO-TLS-CALLBACKS: a thread_local with a destructor gives gta6rt.exe TLS callbacks, and the game + # then fast-fails (0xC0000409) in its own _register_thread_local_exe_atexit_callback (RT-XMEM-STARTUP-FASTFAIL). + if(Python3_FOUND) + add_test(NAME gta6rt_no_tls_callbacks COMMAND "${Python3_EXECUTABLE}" -I + "${CMAKE_CURRENT_SOURCE_DIR}/test/check_pe_tls_callbacks.py" "$") + endif() endif() # pe_loader.cpp needs the shim registry for shims::find/make_unimplemented_thunk. The xmem and d3d12_xs tables diff --git a/runtime/test/check_pe_tls_callbacks.py b/runtime/test/check_pe_tls_callbacks.py new file mode 100644 index 0000000000..8ff468810c --- /dev/null +++ b/runtime/test/check_pe_tls_callbacks.py @@ -0,0 +1,84 @@ +"""gta6rt.exe must have no TLS callbacks (TEST-GTA6RT-NO-TLS-CALLBACKS). + +A thread_local with a destructor in gta6rt makes the linker emit two callbacks (__dyn_tls_init, __dyn_tls_dtor). The +UCRT then accepts only one _register_thread_local_exe_atexit_callback per process, the title registers its own, and +the game fast-fails at startup with 0xC0000409 (RT-XMEM-STARTUP-FASTFAIL). Trivially destructible thread_local data is +fine: it adds no callback. + + python -I check_pe_tls_callbacks.py + +Exit 0 when the PE has no TLS directory or an empty AddressOfCallBacks list, 1 when the list has an entry or the file +is not a readable PE32+. Standard library only; reads the file, so it also runs where gta6rt cannot. +""" +import struct +import sys + +TLS_DIR_INDEX = 9 + + +def tls_callbacks(data): + """RVAs (not VAs) of the TLS callbacks of a PE32+ image, in list order. [] when there is no TLS directory.""" + if data[:2] != b"MZ" or len(data) < 0x40: + raise ValueError("not a PE (no MZ header)") + pe = struct.unpack_from(" Date: Thu, 26 Nov 2026 11:23:07 +0100 Subject: [PATCH 2/3] tests: register gta6rt_no_tls_callbacks for cross-compiled builds too The checker only reads the PE file with the host's Python, so it does not need the run_module_names guard (NOT CMAKE_CROSSCOMPILING). Move the registration out of it, with its own host Python lookup. runtime/cmake/clang-cl-xwin.cmake builds the same MSVC ABI and UCRT, so the same callbacks would appear; MinGW is not a supported gta6rt toolchain. Co-Authored-By: Claude Fable 5.2 --- runtime/CMakeLists.txt | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 1be7ba3d11..36c9943d0c 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -945,12 +945,16 @@ if(BUILD_TESTING) "--report=${CMAKE_CURRENT_BINARY_DIR}/module-names-results.json") set_tests_properties(run_module_names PROPERTIES TIMEOUT 90) endif() - # TEST-GTA6RT-NO-TLS-CALLBACKS: a thread_local with a destructor gives gta6rt.exe TLS callbacks, and the game - # then fast-fails (0xC0000409) in its own _register_thread_local_exe_atexit_callback (RT-XMEM-STARTUP-FASTFAIL). - if(Python3_FOUND) - add_test(NAME gta6rt_no_tls_callbacks COMMAND "${Python3_EXECUTABLE}" -I - "${CMAKE_CURRENT_SOURCE_DIR}/test/check_pe_tls_callbacks.py" "$") - endif() + endif() + + # TEST-GTA6RT-NO-TLS-CALLBACKS: a thread_local with a destructor gives gta6rt.exe TLS callbacks, and the game + # then fast-fails (0xC0000409) in its own _register_thread_local_exe_atexit_callback (RT-XMEM-STARTUP-FASTFAIL). + # The checker only reads the PE file with the host's Python, so unlike run_module_names it is registered for a + # cross build too (runtime/cmake/clang-cl-xwin.cmake, same MSVC ABI and UCRT). + find_package(Python3 COMPONENTS Interpreter QUIET) + if(Python3_FOUND) + add_test(NAME gta6rt_no_tls_callbacks COMMAND "${Python3_EXECUTABLE}" -I + "${CMAKE_CURRENT_SOURCE_DIR}/test/check_pe_tls_callbacks.py" "$") endif() # pe_loader.cpp needs the shim registry for shims::find/make_unimplemented_thunk. The xmem and d3d12_xs tables From 8e3f4c6b8281c117fa1b1871fca6d74f3c6900ea Mon Sep 17 00:00:00 2001 From: MoonEyes <14891700+MoonEyes@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:51:01 +0100 Subject: [PATCH 3/3] test: name gta6rt's TLS callbacks from the linker map Link gta6rt with /MAP and read gta6rt.map to name each TLS callback. Fail on the C++ runtime's __dyn_tls_init (tlsdyn.obj) and __dyn_tls_dtor (tlsdtor.obj), allow Rust std's thread-local callback, fail on the rest. A callback the map does not name, a missing map or a stale map fails with a message. Co-Authored-By: Claude Fable 5.2 --- runtime/CMakeLists.txt | 11 +- runtime/test/check_pe_tls_callbacks.py | 224 +++++++++++++++++++++---- tests/test_check_pe_tls_callbacks.py | 129 ++++++++++++-- 3 files changed, 312 insertions(+), 52 deletions(-) diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 97583f0ce5..943e8c5eb3 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -269,7 +269,10 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) # the entry thread 8 MB (shims/process_shim.h); this is the same number for the others. Keep it in step with # scripts/build_runtime.ps1. set(GTA6RT_STACK 8388608) - target_link_options(gta6rt PRIVATE /OPT:NOREF ${GTA6RT_HOST_BASE} /STACK:${GTA6RT_STACK}) + # /MAP writes gta6rt.map next to the exe (link.exe and lld-link): gta6rt_no_tls_callbacks names each TLS callback from + # it, to tell the C++ runtime's __dyn_tls_init (tlsdyn.obj) and __dyn_tls_dtor (tlsdtor.obj) from Rust std's own + # callback. It does not change the exe. + target_link_options(gta6rt PRIVATE /OPT:NOREF ${GTA6RT_HOST_BASE} /STACK:${GTA6RT_STACK} /MAP) target_link_libraries(gta6rt PRIVATE gta6rt_bcpack gta6rt_d3d12_xs_rootsig gta6rt_xtaskqueue psapi) # Root-signature forwarding test: needs a real PC d3d12.lib to serialize the synthetic descriptors. @@ -1018,8 +1021,10 @@ if(BUILD_TESTING) endif() endif() - # TEST-GTA6RT-NO-TLS-CALLBACKS: a thread_local with a destructor gives gta6rt.exe TLS callbacks, and the game - # then fast-fails (0xC0000409) in its own _register_thread_local_exe_atexit_callback (RT-XMEM-STARTUP-FASTFAIL). + # TEST-GTA6RT-NO-TLS-CALLBACKS: a thread_local with a destructor gives gta6rt.exe the C++ runtime's TLS callbacks, + # and the game then fast-fails (0xC0000409) in its own _register_thread_local_exe_atexit_callback + # (RT-XMEM-STARTUP-FASTFAIL). The checker names the callbacks from gta6rt.map (/MAP above), so Rust std's callback, + # linked in with the audio decoders when cargo is found, passes. # The checker only reads the PE file with the host's Python, so unlike run_module_names it is registered for a # cross build too (runtime/cmake/clang-cl-xwin.cmake, same MSVC ABI and UCRT). find_package(Python3 COMPONENTS Interpreter QUIET) diff --git a/runtime/test/check_pe_tls_callbacks.py b/runtime/test/check_pe_tls_callbacks.py index 8ff468810c..857b14bce3 100644 --- a/runtime/test/check_pe_tls_callbacks.py +++ b/runtime/test/check_pe_tls_callbacks.py @@ -1,58 +1,87 @@ -"""gta6rt.exe must have no TLS callbacks (TEST-GTA6RT-NO-TLS-CALLBACKS). +"""gta6rt.exe must have no C++ runtime TLS callbacks (TEST-GTA6RT-NO-TLS-CALLBACKS). -A thread_local with a destructor in gta6rt makes the linker emit two callbacks (__dyn_tls_init, __dyn_tls_dtor). The -UCRT then accepts only one _register_thread_local_exe_atexit_callback per process, the title registers its own, and -the game fast-fails at startup with 0xC0000409 (RT-XMEM-STARTUP-FASTFAIL). Trivially destructible thread_local data is -fine: it adds no callback. +A thread_local with a dynamic initializer or destructor in gta6rt makes the MSVC C++ runtime add two TLS callbacks, +__dyn_tls_init (tlsdyn.obj) and __dyn_tls_dtor (tlsdtor.obj). The CRT startup then registers __dyn_tls_dtor with +_register_thread_local_exe_atexit_callback, the UCRT accepts that only once per process, the title registers its own, +and the game fast-fails at startup with 0xC0000409 (RT-XMEM-STARTUP-FASTFAIL). Trivially destructible thread_local data +is fine: it adds no callback. - python -I check_pe_tls_callbacks.py +Other components may bring their own TLS callback. Rust's std has one (std::sys::thread_local::guard::windows:: +tls_callback; std::sys::windows::thread_local_key::on_tls_callback in older toolchains) that runs Rust thread-local +destructors; it is linked in with the Rust audio decoders and does not touch the CRT's atexit registration. -Exit 0 when the PE has no TLS directory or an empty AddressOfCallBacks list, 1 when the list has an entry or the file -is not a readable PE32+. Standard library only; reads the file, so it also runs where gta6rt cannot. +So each callback is named from the linker's map file (gta6rt links with /MAP) and sorted: + - __dyn_tls_init, __dyn_tls_dtor, or anything from tlsdyn.obj or tlsdtor.obj: fail, this is the startup fast-fail; + - Rust std's thread-local callback: allowed; + - anything else, or a callback the map does not name: fail, until someone checks what it does and adds it here. +Without a map, an image with no callbacks passes and one with callbacks fails, saying what to provide. + + python -I check_pe_tls_callbacks.py [--map ] + +The map defaults to the image's path with .map. Exit 0 when every callback is allowed (or there is none), 1 otherwise or +when the files cannot be read. Standard library only; reads the files, so it also runs where gta6rt cannot. """ +import os +import re import struct import sys TLS_DIR_INDEX = 9 +MAX_THUNK_HOPS = 4 +CRT_DYN_TLS = frozenset(("__dyn_tls_init", "__dyn_tls_dtor")) +CRT_DYN_TLS_OBJECTS = ("tlsdyn.obj", "tlsdtor.obj") +RUST_STD_TLS_CALLBACKS = frozenset((("std", "sys", "thread_local", "guard", "windows", "tls_callback"), + ("std", "sys", "windows", "thread_local_key", "on_tls_callback"))) -def tls_callbacks(data): - """RVAs (not VAs) of the TLS callbacks of a PE32+ image, in list order. [] when there is no TLS directory.""" +DANGEROUS, ALLOWED, UNKNOWN = "dangerous", "allowed", "unknown" + + +def _image(data): + """(image_base, TimeDateStamp, sections as (va, size, raw)) of a PE32+ image.""" if data[:2] != b"MZ" or len(data) < 0x40: raise ValueError("not a PE (no MZ header)") pe = struct.unpack_from(" len(data): + break + rel, = struct.unpack_from("." + % (exe, len(cbs), rvas, map_path)) + return 1 + if base is None or base != image_base or map_stamp is None or map_stamp != timestamp: + print("FAIL: %s is not the map of %s (load address or timestamp differ); relink and run again." + % (map_path, exe)) + return 1 + try: + results = judge(data, symbols) + except (ValueError, struct.error) as e: + print("check_pe_tls_callbacks: cannot read %s: %s" % (exe, e)) + return 1 + for rva, verdict, named in results: + print(" TLS callback at RVA 0x%x: %s (%s)" % (rva, verdict, "; ".join( + "%s in %s" % (n, o or "?") for n, o in named) or "no symbol at this address in the map")) + bad = [r for r in results if r[1] != ALLOWED] + if any(v == DANGEROUS for _, v, _ in bad): + print("FAIL: %s has the C++ runtime's thread_local callbacks (__dyn_tls_init/__dyn_tls_dtor): a thread_local " + "with a dynamic initializer or destructor was linked in, and the game's own " + "_register_thread_local_exe_atexit_callback then fast-fails (0xC0000409)." % exe) return 1 - if cbs: - print("FAIL: %s has %d TLS callback(s) (RVAs %s). A thread_local with a destructor was linked in; the " - "game's own _register_thread_local_exe_atexit_callback then fast-fails (0xC0000409)." - % (argv[1], len(cbs), ", ".join("0x%x" % c for c in cbs))) + if bad: + print("FAIL: %s has TLS callback(s) this check does not know. Find out what each one does; if it is not a " + "C++ thread_local with a destructor, add it to the allowed callbacks in check_pe_tls_callbacks.py " + "with the reason." % exe) return 1 - print("ok: %s has no TLS callbacks" % argv[1]) + print("ok: %s has %d TLS callback(s), all Rust std's thread-local callback" % (exe, len(cbs))) return 0 diff --git a/tests/test_check_pe_tls_callbacks.py b/tests/test_check_pe_tls_callbacks.py index 85c67ef55b..05b04c1597 100644 --- a/tests/test_check_pe_tls_callbacks.py +++ b/tests/test_check_pe_tls_callbacks.py @@ -1,4 +1,4 @@ -"""runtime/test/check_pe_tls_callbacks.py on two PE32+ images built in memory (no MSVC, no game data). +"""runtime/test/check_pe_tls_callbacks.py on PE32+ images and linker maps built in memory (no MSVC, no game data). python -I tests/test_check_pe_tls_callbacks.py @@ -14,16 +14,21 @@ import check_pe_tls_callbacks as chk # noqa: E402 BASE = 0x140000000 +STAMP = 0x6745A1B2 +CRT_INIT, CRT_DTOR, RUST_CB, OTHER_CB, THUNK = 0x1100, 0x1180, 0x1200, 0x1280, 0x1300 +RUST_LEGACY = "_ZN3std3sys12thread_local5guard7windows12tls_callback17h0123456789abcdefE" -def make_pe(callbacks, tls=True): - """One .rdata section (RVA 0x1000, file offset 0x200): TLS directory at +0, callback list at +0x40.""" - data = bytearray(0x200 + 0x200) +def make_pe(callbacks, tls=True, thunks=()): + """One section (RVA 0x1000, file offset 0x200): TLS directory at +0, callback list at +0x40, code from +0x100. + + thunks: (rva, target) pairs written as `jmp rel32`, as an /INCREMENTAL link does.""" + data = bytearray(0x200 + 0x400) data[0:2] = b"MZ" struct.pack_into(""] + out += [line(*s) for s in symbols] + out += ["", " entry point at 0001:00000000", "", " Static symbols", ""] + out += [line(*s) for s in static] + return "\n".join(out) + "\n" + + +CRT_SYMBOLS = [(CRT_INIT, "__dyn_tls_init", "MSVCRT:tlsdyn.obj"), (CRT_DTOR, "__dyn_tls_dtor", "MSVCRT:tlsdtor.obj")] +RUST_SYMBOL = [(RUST_CB, RUST_LEGACY, "leonida_xma2_decoder.lib:std-0123.std.4567-cgu.0.rcgu.o")] + + +def run(tmp, pe, map_text=None): + exe = tmp / "app.exe" + exe.write_bytes(pe) + map_file = tmp / "app.map" + if map_file.exists(): + map_file.unlink() + if map_text is not None: + map_file.write_text(map_text, encoding="utf-8", newline="\n") + return chk.main(["x", str(exe)]) + + def test_two_callbacks_are_listed(): assert chk.tls_callbacks(make_pe([0x1100, 0x1200])) == [0x1100, 0x1200] @@ -48,21 +88,78 @@ def test_empty_list_and_no_directory_are_clean(): assert chk.tls_callbacks(make_pe([], tls=False)) == [] -def test_main_exit_codes(): +def test_rust_symbol_forms(): + for name in (RUST_LEGACY, "std::sys::thread_local::guard::windows::tls_callback::h0123456789abcdef", + "_ZN3std3sys7windows16thread_local_key15on_tls_callback17h0123456789abcdefE", + "_RNvNtNtNtNtCs1a2B3c_3std3sys12thread_local5guard7windows12tls_callback"): + assert chk.classify(name, "x.lib:y.o") == chk.ALLOWED, name + for name in ("_ZN4core3sys12thread_local12tls_callback17h0123456789abcdefE", + "_ZN3std6thread5local12tls_callback17h0123456789abcdefE", "tls_callback", "?cb@@YAXPEAXK0@Z"): + assert chk.classify(name, "x.lib:y.o") == chk.UNKNOWN, name + assert chk.classify("__dyn_tls_init", "MSVCRT:tlsdyn.obj") == chk.DANGEROUS + assert chk.classify("renamed", "LIBCMT:tlsdyn.obj") == chk.DANGEROUS + assert chk.classify("__dyn_tls_dtor", "MSVCRT:tlsdtor.obj") == chk.DANGEROUS + assert chk.classify("renamed", "MSVCRT:tlsdtor.obj") == chk.DANGEROUS + # Only the two exact std paths; a look-alike path is not vetted. + assert chk.classify("std::evil::thread_local_x::tls_callback", "x.lib:y.o") == chk.UNKNOWN + assert chk.classify("_ZN3std4evil14thread_local_x12tls_callback17h0123456789abcdefE", "x.lib:y.o") == chk.UNKNOWN + # Malformed v0 names are not Rust std's callback, and do not raise. + for name in ("_RNvNtCs1_3std12thread_local12tls_callbackB5_", "_RNvCs_3std1ab"): + assert chk.rust_path(name) == [], name + assert chk.classify(name, "x.lib:y.o") == chk.UNKNOWN, name + + +def test_main_cases(): + with tempfile.TemporaryDirectory() as d: + tmp = Path(d) + rust_map = make_map(CRT_SYMBOLS, static=RUST_SYMBOL) + # None: no map needed. + assert run(tmp, make_pe([])) == 0 + assert run(tmp, make_pe([], tls=False)) == 0 + # The C++ runtime's pair alone: the startup fast-fail. + assert run(tmp, make_pe([CRT_INIT, CRT_DTOR]), rust_map) == 1 + # Rust std's callback alone: allowed (the old check failed here). + assert run(tmp, make_pe([RUST_CB]), rust_map) == 0 + # Both: still the fast-fail. + assert run(tmp, make_pe([RUST_CB, CRT_INIT, CRT_DTOR]), rust_map) == 1 + assert run(tmp, make_pe([RUST_CB, CRT_DTOR]), rust_map) == 1 + # Two Rust decoders, each with its own std: no count to keep in step. + two = make_map([], static=RUST_SYMBOL + [(OTHER_CB, RUST_LEGACY.replace("0123", "fedc"), "opus.lib:std.o")]) + assert run(tmp, make_pe([RUST_CB, OTHER_CB]), two) == 0 + # Through an /INCREMENTAL thunk. + assert run(tmp, make_pe([THUNK], thunks=[(THUNK, RUST_CB)]), rust_map) == 0 + assert run(tmp, make_pe([THUNK], thunks=[(THUNK, CRT_DTOR)]), rust_map) == 1 + # Unknown: no map, an address the map does not name, a symbol nobody vetted. + assert run(tmp, make_pe([RUST_CB])) == 1 + assert run(tmp, make_pe([OTHER_CB]), rust_map) == 1 + assert run(tmp, make_pe([OTHER_CB]), make_map([(OTHER_CB, "some_tls_callback", "x.lib:y.obj")])) == 1 + # A map from another link. + assert run(tmp, make_pe([RUST_CB]), make_map([], stamp=STAMP + 1, static=RUST_SYMBOL)) == 1 + assert run(tmp, make_pe([RUST_CB]), make_map([], base=0x10000000000, static=RUST_SYMBOL)) == 1 + no_stamp = "\n".join(l for l in rust_map.splitlines() if "Timestamp is" not in l) + "\n" + assert run(tmp, make_pe([RUST_CB]), no_stamp) == 1 + + +def test_explicit_map_and_unreadable_inputs(): with tempfile.TemporaryDirectory() as d: - tmp_path = Path(d) - bad, good, junk = tmp_path / "bad.exe", tmp_path / "good.exe", tmp_path / "junk.exe" - bad.write_bytes(make_pe([0x1100])) - good.write_bytes(make_pe([])) + tmp = Path(d) + exe, other = tmp / "a.exe", tmp / "elsewhere.map" + exe.write_bytes(make_pe([RUST_CB])) + other.write_text(make_map([], static=RUST_SYMBOL), encoding="utf-8", newline="\n") + assert chk.main(["x", str(exe), "--map", str(other)]) == 0 + assert chk.main(["x", str(exe), "--map=" + str(other)]) == 0 + assert chk.main(["x", str(exe)]) == 1 + junk = tmp / "junk.exe" junk.write_bytes(b"not a pe") - assert chk.main(["x", str(bad)]) == 1 - assert chk.main(["x", str(good)]) == 0 assert chk.main(["x", str(junk)]) == 1 - assert chk.main(["x", str(tmp_path / "missing.exe")]) == 1 + assert chk.main(["x", str(tmp / "missing.exe")]) == 1 + assert chk.main(["x"]) == 1 if __name__ == "__main__": test_two_callbacks_are_listed() test_empty_list_and_no_directory_are_clean() - test_main_exit_codes() + test_rust_symbol_forms() + test_main_cases() + test_explicit_map_and_unreadable_inputs() print("ok")