diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index be7e48c858..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,6 +1021,18 @@ if(BUILD_TESTING) endif() endif() + # 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) + 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 # are linked too so the optional LEONIDA_GAME_DIR run classifies the shipped modules' imports exactly like # gta6rt does (no d3d12.lib is needed: d3d12_xs resolves its host entry points at run time). diff --git a/runtime/test/check_pe_tls_callbacks.py b/runtime/test/check_pe_tls_callbacks.py new file mode 100644 index 0000000000..857b14bce3 --- /dev/null +++ b/runtime/test/check_pe_tls_callbacks.py @@ -0,0 +1,242 @@ +"""gta6rt.exe must have no C++ runtime TLS callbacks (TEST-GTA6RT-NO-TLS-CALLBACKS). + +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. + +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. + +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"))) + +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 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 %d TLS callback(s), all Rust std's thread-local callback" % (exe, len(cbs))) + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv)) diff --git a/tests/test_check_pe_tls_callbacks.py b/tests/test_check_pe_tls_callbacks.py new file mode 100644 index 0000000000..05b04c1597 --- /dev/null +++ b/tests/test_check_pe_tls_callbacks.py @@ -0,0 +1,165 @@ +"""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 + +Standard library only. +""" +import struct +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(ROOT / "runtime" / "test")) +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, 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] + + +def test_empty_list_and_no_directory_are_clean(): + assert chk.tls_callbacks(make_pe([])) == [] + assert chk.tls_callbacks(make_pe([], tls=False)) == [] + + +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(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(junk)]) == 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_rust_symbol_forms() + test_main_cases() + test_explicit_map_and_unreadable_inputs() + print("ok")