Skip to content

Loader: the mapped game executable owns module TLS index 0 (RT-259) - #4313

Open
mariuslozo-boop wants to merge 4 commits into
ItsNotRexed:mainfrom
mariuslozo-boop:rt/exe-tls-slot0
Open

mariuslozo-boop wants to merge 4 commits into
ItsNotRexed:mainfrom
mariuslozo-boop:rt/exe-tls-slot0

Conversation

@mariuslozo-boop

Copy link
Copy Markdown

Claimed in the coordination issue as: RT-259 (claim).

What and why

Code built with MSVC /GA (optimised for an executable) reads its thread-local storage as gs:[58h] → [0], without loading _tls_index. That is correct on Windows, because the process executable always gets module TLS index 0. Under gta6rt, though, index 0 belongs to gta6rt.exe itself, and the mapped game executable got a helper index. /GA code in the game then read and wrote gta6rt's own block.

Reproduced with a 20-line /GA program that sets a thread_local to 42:

  • native: tls_index=0 value=42;
  • under gta6rt --run on main: tls_index=6 value=0, exit code 1;
  • with this PR: tls_index=0 value=42, exit code 0.

The change (runtime/src/pe_loader.cpp, main.cpp, tls_host.cpp):

  • rt::reserve_tls_index0() runs once, from a .CRT$XCT initializer in main.cpp. That is before any of gta6rt's own static initializers and threads; checked against the map file and the disassembly.
  • It loads a "home" clone of gta6rt_tls_host.dll. The clone's TLS directory points at a 16 KiB export, gta6rt_tls_home_template, filled with a copy of gta6rt.exe's TLS template.
  • It then swaps slot 0 and the home slot on the main thread, and rewrites gta6rt.exe's _tls_index to the home index.
  • From then on, every new thread gets a full, correctly sized copy of gta6rt's TLS at the home index from ntdll. Slot 0 is free for the mapped executable (kMainImageSlot), through the existing install, thread-event and ~Loader paths.
  • On thread attach, every module's copy is installed first, then the TLS callbacks run, DLLs first and the executable last (Windows' order).
  • An executable with TLS that does not get index 0 is refused under --run and --init with the reason, and --dry-run prints a note. Before, such a /GA executable silently corrupted gta6rt's own block.
  • A primary helper without the gta6rt_tls_host_set_thread_event export is refused.
  • Helper clone files are deleted at exit again. The next run's sweep now also removes files of processes that ended while another process still held a handle to them.

Measured facts this relies on are in the comments and in runtime/README.md:

  • ntdll copies only the raw TLS template and ignores SizeOfZeroFill, hence the 16 KiB array instead of a zero-fill;
  • a mapped DLL's file cannot be deleted at exit;
  • DLL DllMain runs before the executable's TLS callbacks.

Known limits (in the README):

  • Only one executable holds index 0.
  • Other programs that use Loader must call reserve_tls_index0() at process start.
  • The home clone file stays in %TEMP% until the next run's sweep.
  • Not run under Wine here: the Wine CI job runs run_tiny_game, whose image has TLS.

Tested

Windows 11 (build 26300), RTX 5070 Ti (driver 616.92), MSVC 19.44, Vulkan SDK 1.4.363.0, RelWithDebInfo, on main 03b09a08.

  • Full ctest: 142/142 passed, both serial and -j 8. The skips are the usual ones that need game data, SDL3 or GPU tools.
  • -R "loader_tls|run_tiny" --repeat until-fail:30: all 30 rounds passed.
  • New tests:
    • loader_tls_index0: a real /GA /MD fixture, tiny_tls_ga.dll, checked from its machine code. It reads 42 at slot 0 on the loading thread, an older thread and new threads. It also checks that the EXE's own block moved by pointer identity, and the home template's size and content.
    • loader_tls_index0_threads: a reservation while another thread keeps creating threads, a thread with no TLS array yet, and code that runs before the helper's thread attach (tiny_thread_hook.dll).
    • loader_tls_index0_noreserve: a map without the reservation gets a helper index.
    • run_tiny_tls_ga: --run and --init on the fixture, and the refusal path (TMP and TEMP naming a missing folder).
    • run_tiny_tls_clone_cleanup: no clone files are left after --dry-run and --init, and the next run sweeps the home clone.
  • Against main: the new index-0 test fails 14 of 39 checks with main's loader. The cleanup test fails with the old cleanup.
  • Python: every tests/test_*.py that CI runs passed, except 5 that fail identically on clean main on this machine (Wine, llvm-mc, the game-data scan, saves and the progress dashboard).

Reviewed twice by an independent reviewer before this PR.

  • The first review found a TLS slot address that MSVC keeps across DLL calls in zlib_inflate, which made the original lazy move unsafe. That led to the startup reservation.
  • The second review found the exit-cleanup regression, now fixed and tested.

Checklist

  • No game data, keys or decryption (CONTRIBUTING.md), including in logs or reports quoted here.
  • A new translator rule is in the contract table of docs/design.md, with how it was confirmed. (Not applicable: no translator change.)

AI-assisted (Claude Code). No game files.

🤖 Generated with Claude Code

mariuslozo-boop and others added 3 commits November 23, 2026 01:38
Windows gives the process executable module TLS index 0, and MSVC code built
with /GA reads TEB->ThreadLocalStoragePointer[0] without loading _tls_index.
The loader gave a mapped EXE a gta6rt_tls_host.dll clone's index instead, so a
thread_local int v = 42 EXE built /O2 /GA /MD printed tls_index=6 value=0
under gta6rt --run (natively tls_index=0 value=42).

Index 0 belongs to gta6rt.exe itself (and to each test EXE that links
pe_loader.cpp): measured through _tls_index == 0 before any mapping and the
new tls_index0 trace event. All of its own TLS reads go through _tls_index,
so the first time an executable is mapped the loader loads one more helper
clone (leonida_tls_host_<pid>_home.dll), stops the other threads, swaps
slots 0 and the clone's index on every thread and writes that index into the
owner's _tls_index. Threads started later swap their own slots first thing
in the helper's DLL_THREAD_ATTACH. Both pointers are OS-allocated blocks of
that thread and the OS frees every slot at thread exit, so the swap is
permanent and nothing is restored. The executable then takes slot 0
(kMainImageSlot) through the existing per-thread install, thread events and
~Loader paths; DLLs keep the helper indices. A second executable mapped
while one is live, or a move that cannot be made (a thread kept running in
the owner's code for 250 ms), gets a helper index and a stderr note.

Measured on Windows 11 26300 to make the swap safe: a new thread publishes
its TLS array in the TEB only once it is filled (LdrpAllocateTls), an ending
one clears it before freeing the blocks (LdrpFreeTls), LoadLibrary of a TLS
DLL updates other threads in one NtSetInformationProcess call, and an EXE's
TLS callbacks run after every DllMain for thread attach and detach.

Tests: loader_tls_index0 maps tiny_tls_ga.exe (built /GA, code shape
checked) next to tiny_tls.dll: 42 on the loading thread, a pre-existing
thread and new threads, this EXE's own TLS intact on all of them, two runs
in a row, a second executable at once, and a busy thread holding the move
off. run_tiny_tls_ga runs it under gta6rt --run and --init and checks the
trace names gta6rt.exe.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…s the EXE's

Fixes from the review of the index-0 change:

- The lazy move at the first executable map stopped other threads and swapped
  their slots, guarded by a "thread is inside gta6rt.exe" check. That is not
  enough: MSVC keeps &ThreadLocalStoragePointer[_tls_index] across calls
  (zlib_inflate saves it at [rbp-80h] across memset, push_back and
  inflate_codes, then reads _Init_thread_epoch through it), so a thread
  stopped in the heap or memset still reads the wrong slot afterwards. The
  move is now rt::reserve_tls_index0(), done once at process start: gta6rt
  calls it from a .CRT$XCT initializer, before its own static initializers
  and before any of its threads; the CRT startup frames above it hold no TLS
  slot address (checked in the disassembly). It swaps slots 0 and home on the
  calling thread only; no thread enumeration, suspension, TEB writes or
  TlsAlloc mark are left.
- The home clone's block was the helper's 514 bytes, smaller than
  gta6rt.exe's 1398-byte TLS. The home clone is now written from
  gta6rt_tls_host.dll with its TLS directory pointed at a new 16 KiB export,
  gta6rt_tls_home_template, filled with a copy of the EXE's template and its
  alignment (LdrpAllocateTls copies End - Start and ignores SizeOfZeroFill,
  so the zero fill is part of the range). Every new thread then has a fresh
  copy of gta6rt.exe's TLS at the home index from its first instruction, so
  no adoption step or window before the helper's DLL_THREAD_ATTACH is left.
  The mapped template is checked against the EXE's after the load.
- The owner is GetModuleHandleW(nullptr) with _tls_index 0, not any module
  whose index reads 0.
- A primary helper without gta6rt_tls_host_set_thread_event is refused.
- An executable that does not get index 0 (no reservation, or another
  executable holds it) is refused by --run and --init with an error; its /GA
  code would read and write another module's TLS through slot 0. The README
  no longer says it "reads the first one's slot 0".
- Thread attach installs every module's copy before any TLS callback runs,
  as Windows allocates all blocks before the first DllMain.
- Tests: loader_tls_index0 (runs) checks this EXE's block moving from slot 0
  to the home index by identity, the home template's size and content, and
  that the getter reads slot 0 with its _tls_index pointing elsewhere (fails
  for a non-/GA build of the fixture); loader_tls_index0_threads reserves
  while threads are being created, with one suspended thread that has no TLS
  array yet and tiny_thread_hook.dll running test code before the helper's
  DLL_THREAD_ATTACH; loader_tls_index0_noreserve maps without the
  reservation. The tiny_tls_ga.cpp comment names the real test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ils cleanly

From the second review of 89cec3b8:

- The first load_tls_host_clone call is now the home clone, from .CRT$XCT,
  and it registered cleanup_tls_clones_at_exit with atexit before
  g_tls_clones was dynamically initialized in .CRT$XCU. The vector's
  destructor then ran first and the cleanup walked a destroyed vector, so
  --dry-run, --init and every return-1 path left the slot clones'
  leonida_tls_host_<pid>_<slot>.dll files in %TEMP%. g_tls_clones is now
  allocated with the first record and never destroyed, and the atexit
  handler is registered there. The home clone cannot be deleted while it is
  mapped (DeleteFileW and a POSIX-semantics delete both fail with
  ERROR_ACCESS_DENIED), so it is left for the next run's sweep, as the
  README says.
- process_alive() took an ended process as alive while another process
  still held a handle to it (CMake's execute_process does), so the next
  run's sweep skipped its files; it now reads the exit code.
- reserve_tls_index0 catches what reserve_index0 throws (for example
  std::filesystem::temp_directory_path) and stores it as the reason, so the
  reservation fails before main with a message instead of ending gta6rt.
  The owner's file name is taken before the move, so nothing can throw
  between the move and recording it.
- Tests: run_tiny_tls_clone_cleanup runs gta6rt --dry-run, --init and
  --dry-run on tiny_tls_clones.exe (three TLS modules, so one slot clone)
  and checks that each run's PID leaves no clone file but its home clone and
  that the next run deletes that one; it fails with the old cleanup.
  run_tiny_tls_ga also runs with TMP and TEMP naming a missing folder: the
  reservation fails, --run and --init refuse the image with the reason and
  run none of it, --dry-run maps it with the note.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@SweatierKey

Copy link
Copy Markdown
Contributor

Independent code read + build/hygiene check at 9366e54f on Linux (WSL2, Python 3.13.5, no Windows/MSVC host, no game files): pass (Windows MSVC build & live loader TLS CTest execution still needed).

  • Code read (runtime/src/tls_host.cpp, runtime/src/pe_loader.cpp, runtime/README.md, runtime/shims/startup_trace.h):
    • Sound design for MSVC /GA executables that bypass _tls_index and read TEB->ThreadLocalStoragePointer[0] directly: moves gta6rt.exe's own TLS off index 0 into a dedicated leonida_tls_host_<pid>_home.dll clone (backed by the 16 KiB gta6rt_tls_home_template export) via an early CRT initializer before static initializers or worker threads cache slot addresses, leaving slot 0 free for the mapped executable (kMainImageSlot).
    • Fail-closed guarantees are well-scoped: refuses moving if the host EXE's TLS exceeds 16 KiB, refuses --run/--init with exit 1 if index 0 was not reserved or is already held by another mapped executable, and records the move via the new tls_index0 startup-trace event.
  • Hygiene (clean worktree on 03b09a08): git diff --check, test_ctest_registration.py (4/4), test_docs_links.py (6/6), test_docs_repo_paths.py (2/2), test_text_write_line_endings.py (3/3), test_text_encoding.py (2/2) all pass.
  • Not run here: Windows MSVC build and CTest execution (loader_tls_index0_test, check_tls_index0.cmake, check_tls_clone_cleanup.cmake).

AI-assisted review.

@Kam471 Kam471 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Built the new fixtures and ran the TLS suite at 9366e54f on Windows 11, RTX 5070 Ti:

  • loader_tls_index0 -> passed; loader_tls_index0_threads -> passed; loader_tls_index0_noreserve -> passed.
  • run_tiny_game_tls -> passed (after building the tiny_game fixture); run_tiny_tls_ga -> passed; run_tiny_tls_clone_cleanup -> passed.
  • ctest -R tls -> 7/7 passed, 0.80 s total.
  • loader_tls_index0_test.exe needs its fixture arguments, as documented; the CTest entries supply them.

No blocking issue.

@Hanioe2

Hanioe2 commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Native Windows/MSVC verification at 9366e54f on Windows 11 build 26200, MSVC 19.44.35227, SDK 10.0.26100.0, Visual Studio 17 2022 generator, RelWithDebInfo.

All eight focused CTests passed: loader_tls, loader_tls_index0, loader_tls_index0_threads, loader_tls_index0_noreserve, run_tiny_game, run_tiny_game_tls, run_tiny_tls_ga, and run_tiny_tls_clone_cleanup.

I then repeated the thread-index, /GA guest, and clone cleanup CTests 20 times each in a fresh test temp folder. All 60 repeated runs passed. Synthetic CPU fixtures only.

AI-assisted.

@2-CD

2-CD commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Windows + GPU check (complements the Linux code-read above; this is the Windows/MSVC + GPU dimension). NVIDIA GeForce RTX 5080 (driver 621.01) + AMD Radeon 610M iGPU (driver 32.0.13018.6), Windows 11, MSVC (VS BuildTools 18) + Ninja, RelWithDebInfo, Vulkan SDK headers fetched. Tested head 9366e54f (base 03b09a08).

Build: clean (a transient LNK1163 invalid selection for COMDAT section on one link cleared on a Ninja retry; no source error).

Targeted, --repeat until-fail:3:

  • loader_tls_index0, loader_tls_index0_threads, loader_tls_index0_noreserve, run_tiny_tls_ga, run_tiny_tls_clone_cleanup: all pass x3.
  • Existing loader_tls, loader, pe_loader, pe_loader_bounds: pass x3 (no regression in the PE loader / TLS path this PR rewrites).

Full suite (ctest -C RelWithDebInfo -j 6, excluding the 4 window-showing tests dxgi_swapchain|d3d12_present|vk_presenter_sync|xbox_present):

  • NVIDIA RTX 5080: 155/155 passed, 0 failed.
  • AMD Radeon 610M iGPU (LEONIDA_VK_DEVICE=Radeon): 155/155 passed, 0 failed.

The PR's unstable CI state did not reproduce locally.

Synthetic fixtures only, no game files. AI-assisted (opencode); runs on my machine.

@Exopus-0x65f7ad0

Copy link
Copy Markdown
Contributor

Tested 9366e54f on Windows 11 (26300), RTX 5060 Ti / 621.14, MSVC 14.51 (VS 2026), Vulkan SDK 1.4.363.0, RelWithDebInfo, built from an empty folder with -DLEONIDA_LLVM_MC.

  • -R "loader|tls|run_tiny" --repeat until-fail:30 (serial): passes, 20/20 each round.

  • Full ctest -j4 (with LEONIDA_VK_VALIDATION=1): loader_tls fails, and it does so deterministically under -j: ctest -R "loader|tls|run_tiny" -j4 --repeat until-fail:10 failed 3 runs out of 3 on this branch, always at

    FAIL the purge skipped the clone whose owner process is still alive

    The same command on main passed 3 out of 3.

Cause: the test's "live" owner isn't alive. It's cmd.exe /c timeout /t 30 /nobreak > nul, and timeout.exe exits at once when its input is redirected ("Error: input redirection is not supported, exiting the process immediately", 40 ms, exit 1, checked here with a redirected-stdin Process.Start), which is what ctest's children get under -j. On main, process_alive only needed OpenProcess to succeed, and the test holds the child's handle, so the dead "live" child still counted as alive. This PR's exit-code check is right and exposes it.

Fix in the test (not in the purge): create the live child suspended, so it's alive until the destructor terminates it, whatever its input:

diff --git a/runtime/test/loader_tls_test.cpp b/runtime/test/loader_tls_test.cpp
index 6d5a06dd..4fcedf98 100644
--- a/runtime/test/loader_tls_test.cpp
+++ b/runtime/test/loader_tls_test.cpp
@@ -492,17 +492,20 @@ void test_orphan_slot_generation_reuse(const fs::path& dll) {
     check(td() == 0, "orphaned worker exit does not dispatch DLL_THREAD_DETACH to the new generation's module");
 }
 
-// Spawns cmd.exe to obtain one guaranteed-dead PID and one guaranteed-live one for the purge-ownership checks.
+// Spawns cmd.exe to obtain one guaranteed-dead PID and one guaranteed-live one for the purge-ownership checks. The
+// live one is created suspended: it stays alive until the destructor ends it, whatever its standard input is. (A
+// `timeout /t 30` child is not: timeout.exe exits at once, "input redirection is not supported", when ctest runs the
+// test with redirected input, as it does under -j, so the "live" owner was already dead.)
 struct ChildProcess {
     HANDLE process = nullptr;
     DWORD pid = 0;
-    explicit ChildProcess(const wchar_t* args) {
+    explicit ChildProcess(const wchar_t* args, bool suspended = false) {
         STARTUPINFOW si{};
         si.cb = sizeof(si);
         PROCESS_INFORMATION pi{};
         std::wstring cmd = std::wstring(L"cmd.exe ") + args;
-        if (!CreateProcessW(nullptr, cmd.data(), nullptr, nullptr, FALSE, CREATE_NO_WINDOW, nullptr, nullptr, &si,
-                            &pi))
+        if (!CreateProcessW(nullptr, cmd.data(), nullptr, nullptr, FALSE,
+                            CREATE_NO_WINDOW | (suspended ? CREATE_SUSPENDED : 0), nullptr, nullptr, &si, &pi))
             throw std::runtime_error("CreateProcessW for cmd.exe failed");
         CloseHandle(pi.hThread);
         process = pi.hProcess;
@@ -546,7 +549,7 @@ void test_purge_ownership_scoping(const fs::path& dll, const fs::path& temp) {
     std::printf("\n-- startup purge deletes only ownerless clones --\n");
     ChildProcess dead(L"/c exit 0");
     dead.wait_exit();
-    ChildProcess live(L"/c timeout /t 30 /nobreak > nul");
+    ChildProcess live(L"/c exit 0", true);  // suspended: alive until the end of the test
 
     const fs::path clone_root = fs::temp_directory_path();
     // An own-PID name stands in for a leftover of a dead run whose PID this process reused: the sweep runs before

With it, -R "loader|tls|run_tiny" -j4 --repeat until-fail:10: 3 runs out of 3 pass (20/20). I haven't pushed anything to your branch; take it if you agree.

Everything else in the full run passed (the usual skips: shader_library_corpus, bink_*, gameinput, d3d12_rgb9e5_rtv, d3d12_first_light), 0 VUIDs.

AI-assisted (Claude Code).

@Hanioe2

Hanioe2 commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

I checked whether the existing TEST-899 fixture fix (#4091) also works with RT-259 on native Windows 11 (26200), MSVC 19.44.35227, and the VS 2022 generator (RelWithDebInfo).

This confirms that the already-open #4091 fixture change is compatible with the process-liveness check in RT-259 on this MSVC setup. Native Windows and synthetic fixtures only.

AI-assisted.

@FZNull

FZNull commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Tested 9366e54f on NVIDIA GeForce RTX 4060, Windows 11 build 26300 (loader-only change, no GPU path): pass.

Clean worktree at 9366e54f on main 03b09a08. MSVC 19.50.35726 + CMake/Ninja, RelWithDebInfo; cmake --build runtime/build --parallel 6 -> rc 0, 791.8 s.

  • ctest --test-dir runtime/build --no-tests=error --output-on-failure: 100% tests passed out of 160, 0 failed (161 registered: 8 environment skips and 1 disabled gameinput), 346.4 s, exit 0. loader_tls_index0, loader_tls_index0_threads, loader_tls_index0_noreserve, run_tiny_tls_ga and run_tiny_tls_clone_cleanup pass, as does every run_tiny_* test.
  • ctest ... -R "loader_tls|run_tiny" --repeat until-fail:30: 100% of 17 tests, 30/30 rounds, 77.0 s, exit 0.
  • Parallel ctest -j 8: 160/160 passed, 88.5 s, exit 0. An earlier -j 8 run had xbox_present fail transiently with VK_ERROR_FORMAT_NOT_SUPPORTED while other GPU/swapchain tests ran concurrently; it passes serially and the rerun is clean, so it is unrelated to this change.
  • The standard-library Python loop from .github/workflows/ci.yml: 295 of 297 files pass; tests/test_check_no_game_data.py (PermissionError WinError 5 removing a temp .git object) and tests/test_saves.py (os.readlink returns the \\?\ prefix) fail identically on clean main 03b09a08.

The PR's negative control (the new test failing against main's loader) was not reproduced here because that needs a main-loader build of the test binary; the new tests pass on this one. No game data is involved; the fixtures are the checked-in synthetic tiny_* ones.

AI-assisted.

@mariuslozo-boop

Copy link
Copy Markdown
Author

Thanks for the test reports.

AI-assisted (Claude Code).

@Ayinaki

Ayinaki commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Tested 28ea6b9 on Windows 10.0.26200, MSVC 14.52 (Visual Studio 18 2026, x64, RelWithDebInfo): pass. No GPU path in these targets.

Built loader_tls_index0_test, tiny_tls_ga, tiny_tls, tiny_thread_hook, gta6rt_tls_host and gta6rt from this head, then ran ctest -R "loader_tls_index0|run_tiny_tls":

1/5 loader_tls_index0 ............ Passed
2/5 loader_tls_index0_threads .... Passed
3/5 loader_tls_index0_noreserve .. Passed
4/5 run_tiny_tls_ga .............. Passed
5/5 run_tiny_tls_clone_cleanup ... Passed
100% tests passed, 0 tests failed out of 5

That is 5/5 on three consecutive runs of the same set (the reservation is once per process, so the runs/threads/noreserve scenarios are separate processes as intended).

@abilliontokens

Copy link
Copy Markdown
Contributor

Tested 28ea6b971ba229e8caeb7bf4a50f263224b448fb on NVIDIA GeForce RTX 5060 Ti (621.24, Windows 11): pass.

Worktree at the PR head, runtime built with scripts/build_runtime.ps1 (MSVC 14.44, RelWithDebInfo). This is a loader/TLS change with no GPU path; the affected CTest subset is the loader and tiny-game set, run on Windows (the RTX 5060 Ti was pinned for the session but these tests do not touch Vulkan).

Commands and results:

ctest --test-dir runtime/build -R 'loader_tls|run_tiny' --output-on-failure
  -> 19/19 passed (incl. run_tiny_tls_ga, run_tiny_tls_clone_cleanup, run_tiny_game_tls)
ctest --test-dir runtime/build -R 'loader_tls_index0' --output-on-failure
  -> 3/3 passed (loader_tls_index0, loader_tls_index0_threads, loader_tls_index0_noreserve)

python -I -m compileall -q make_game.py tools tests is clean. Synthetic fixtures only, no game files.

@erickbobd

Copy link
Copy Markdown
Contributor

Additional executable-startup validation, AI-assisted with Codex.

Tested snapshot 9366e54f9744bbcd7df428c602ce1e775a9b9001 on base 03b09a08, in an isolated local worktree, using a local Series Minecraft Preview executable as a functional probe.

  • Eight focused TLS/runtime CTests passed.
  • The same synthetic MSVC /GA executable failed on the baseline loader (assigned TLS index 6, template value read as 0 on main and worker threads) and passed with this PR (TLS index 0, value 42 on both).
  • With this PR alone, the title no longer hit its previous early allocator access violation. It reached its executable startup and then exited with code 1 at the missing dynamic xgameruntime.dll!XErrorReport lookup. This title result was recorded before adding the local GDK adaptation below.

The minimal local adaptation used in subsequent tests was a named export forwarding to the existing error-report implementation:

HRESULT WINAPI XErrorReport(HRESULT hr, const char* message) {
    return error_report(nullptr, hr, message);
}

plus XGR(XErrorReport) in the shim table. This is the same fix now proposed in #5312; its mapped-thunk regression tests are also integrated locally. The export is required in addition to the COM slot already served by the runtime.

Combining that with the reviewed module-identity changes from #2075 let the title progress to a strict stop at xmem.dll!XMemTransferMemory. A later integration also includes merged #4551, #4239's activation objects, and only #3476's analytics class. No menu, rendered frame or gameplay is established. These results support reviewing #4313, #5312 and #2075 together for real executable bring-up; they are general loader/GDK contracts.

Environment: Windows 11 build 26200, MSVC 14.51, Ninja RelWithDebInfo, Vulkan SDK 1.4.363.0, NVIDIA RTX 5070 Ti / driver 617.14. Offline functional tests only; no GPU performance measurement. Disposable local inputs and diagnostics remain outside git; no game artifacts are attached.

@sneylol

sneylol commented Nov 23, 2026

Copy link
Copy Markdown

Tested 28ea6b9 against the retail exe: needed for boot.

The game's allocator reads its per-thread state from TLS slot 0 directly (/GA-style codegen). Under main that slot belongs to the host, so an early static constructor dereferences a garbage allocator pointer (the value changes from run to run). With this PR (stacked on #6709, #4531 and #6582), static initialisation completes and startup reaches XCRDAPI.dll!DStorageGetFactory (#4348).

The PR conflicts with main in runtime/src/pe_loader.cpp (the thread attach/detach try blocks added since), runtime/CMakeLists.txt and runtime/README.md. Keeping both sides builds, and loader_tls_index0, loader_tls_index0_threads, loader_tls_index0_noreserve, run_tiny_tls_ga and run_tiny_tls_clone_cleanup pass.

Windows 11 26200, AMD RX 9070 XT, MSVC 14.44, Windows SDK 10.0.26100, own Xbox 1.0.2.1 package (with game_scarlett_master.exe). gta6rt --run with --overlay, inspected under cdb. Outcomes only; no game data, RVAs or traces.

AI-assisted (Claude Code).

@Etoile-Bleu

Copy link
Copy Markdown
Contributor

This PR conflicts with main now (runtime/CMakeLists.txt and runtime/README.md, one hunk each) and it is the stop right after the memory reservations in the retail boot: without it the title reads TLS slot 0 and faults (0xc0000005 at exe+0x51d1adc, read 0x4426e4); with it the trace has a tls_index0 event and the boot goes on to the DirectStorage factory. A conflict-free merge of main (c25b9f28) into this head is on my fork: Etoile-Bleu/Leonida, branch rebase-pr4313, commit 064276899 (https://github.com/Etoile-Bleu/Leonida/tree/rebase-pr4313). git fetch https://github.com/Etoile-Bleu/Leonida rebase-pr4313; I did not touch your branch.

Both sides' CMake tests and README paragraphs are kept. pe_loader.cpp auto-merged cleanly this time (an earlier base had two hunks in thread attach/detach: main's forget_ended_thread_id() and release_existing_blocks_of_this_thread() pre-steps go before your kTlsSlotCount / kMainImageSlot loops, which is how I kept it).

Tested at 064276899 on Windows 11 26200, MSVC 14.44, RTX 5070 Ti: full runtime build, then ctest -R 'tls|tiny_game|loader|xgameruntime': 27 of 27 pass, including run_tiny_tls_ga and run_tiny_tls_clone_cleanup. No game data in this comment. AI-assisted: yes.

kett1m added a commit to kett1m/Leonida that referenced this pull request Nov 23, 2026
The chain in this page is Windows-only. This adds the first pass on Linux: the cross build, Wine 11.22, an RTX 3090.

With a folder that holds only the executable, --dry-run maps it at its preferred base with 53 shim, 432 host and 102
unimplemented imports; --init exits 0 and the trace holds a handled access violation inside the second TLS callback;
--run stops in the runtime before the title's first static initializer finishes, in the runtime's own static TLS at
module index 0. That is RT-259's subject, and ItsNotRexed#4313 is its fix.

Counts and error classes only, no addresses, offsets or bytes from the executable.
kett1m added a commit to kett1m/Leonida that referenced this pull request Nov 23, 2026
The chain in this page is Windows-only. This adds the first pass on Linux: the cross build, Wine 11.22, an RTX 3090.

With a folder that holds only the executable, --dry-run maps it at its preferred base with 53 shim, 432 host and 102
unimplemented imports; --init exits 0 and the trace holds a handled access violation inside the second TLS callback;
--run stops in the runtime before the title's first static initializer finishes, in the runtime's own static TLS at
module index 0. That is RT-259's subject, and ItsNotRexed#4313 is its fix.

Counts and error classes only, no addresses, offsets or bytes from the executable.
@jtrudeau1530

Copy link
Copy Markdown

Independent bounded retail comparison on Arch Linux / Wine 11.18, clang-cl 23.1.6 + xwin SDK 10.0.26100, Ninja RelWithDebInfo, Vulkan and SDL3 enabled. Ryzen 7 9800X3D / RX 7900 XT, RADV Mesa 26.2.3; no GPU work reached.

Pinned base: main 8575d36edc479218972497a7bded8651a42856c0 + #6919 36936f3bf43e33a60e36cff942fa0862e7474645.

Runtime Measured outcome
Base without #4313 Host access violation in library_loader.cpp:75, host_module_name map lookup; zero xmem_attributes events
Base + #4313 28ea6b971ba229e8caeb7bf4a50f263224b448fb One tls_index0 event, five XMemVirtualAlloc attribute events, then the missing xgameruntime.dll!XErrorReport lookup and a breakpoint; no preceding host access violation

The second arm was built by a cooperating local tester from the cleanly merged source, and I independently snapshotted and ran its executable/DLL with matching PDB. Local merge revision 1d15a1a1627442132a3c3017a29344b7c7918022. Same package, Wine prefix, Vulkan/stop policy and network-isolated runner for both arms; each run was bounded to 30 seconds.

No #2490, #7175, or library-loader guard workaround is present in the successful second arm. In this setup, this PR alone is sufficient to clear the earlier host-module-cache fault and expose the next missing export. #6582 has not been applied to this comparison. This is startup progress, not a claim that the title runs or renders.

No game files or raw traces attached. AI-assisted.

@tugasky

tugasky commented Nov 23, 2026

Copy link
Copy Markdown

Independent check with the retail executable on Windows 11 (MSVC 19.44, AMD 26.11.2): this PR clears the chain's stop 4 here.

Merged onto current main 8575d36ed, which refactored the same thread-event code (install_on_existing_threads, release_existing_blocks_of_this_thread(), forget_ended_thread_id()), the only code conflict is two hunks in on_host_thread_event() in runtime/src/pe_loader.cpp. Resolved the way #6824 describes — main's forget_ended_thread_id() on attach and release_existing_blocks_of_this_thread() on detach stay in front, then your two-pass kTlsSlotCount loops with kMainImageSlot last — the tree builds and the 17 tls/xmem/tiny_game tests pass, including run_tiny_tls_ga and run_tiny_tls_clone_cleanup. That resolution is worth folding into the rebase.

Effect on the boot, same machine and base (main + #6919):

  • without this PR: four runs gave three different crashes in the title's static-initializer thread (near-null reads twice, one execute-AV), i.e. nondeterministic;
  • with it: 3/3 runs stop at the same deliberate int3 further into startup.

I also confirmed the premise on this box: built gta6rt.exe carries its own TLS directory (a 40-byte TLS dir), so it does take module TLS index 0.

Details in #7154 (comment)

AI-assisted: yes (Cline).

@Roberto0953

Copy link
Copy Markdown
Contributor

@mariuslozo-boop, a branch you can pull, with @Zunraz's and @tugasky's resolution already in it: Roberto0953:rebase/4313-on-042c5f378. It is your head 28ea6b971 plus three commits, with main 042c5f378 (which already has #6919) merged in:

  1. 3dbde4295, the merge. In on_host_thread_event, main's forget_ended_thread_id() and release_existing_blocks_of_this_thread() come first, then your two-pass kTlsSlotCount loops. CMakeLists.txt keeps both sets of tests.
  2. 5a8dc9af6, runtime/README.md. The merged text said both that a thread older than load() "gets its copy from load() itself" (main) and that it "gets nothing" (this branch). It now keeps main's sentence plus your ordering sentence and the index-0 bullets.
  3. b2902830d, Zunraz's finding: install_on_existing_threads is bounded by kTlsSlotCount, so a thread that was already running gets the executable's slot-0 block from load(). The early thread in loader_tls_index0 now checks that it reads 42 before any install call, and that install/uninstall are no-ops there. Fail-first: with only the pe_loader.cpp line reverted, the two new checks fail (41 checks, 2 failures).

Windows 11 (build 26300), i7-14700K, MSVC 14.44 RelWithDebInfo: loader_tls, loader_tls_index0, loader_tls_index0_threads, loader_tls_index0_noreserve, run_tiny_tls_ga, run_tiny_tls_clone_cleanup and run_tiny_game_tls all pass (7/7). So do pe_loader and the run_tiny_game* cases that were built.

Retail 1.0.2.1 executable (own copy), stacked with #4531 / #6919: without this PR, --run faults reading near null in the title's startup. With it, the trace has the tls_index0 event and the title reaches XErrorReport (#6582), then DStorageGetFactory (#4348). Same as the results above.

git pull https://github.com/Roberto0953/Leonida rebase/4313-on-042c5f378 fast-forwards your branch. AI-assisted (Claude Code). No game files.

@Tymon3310

Copy link
Copy Markdown

Tested on Linux under Wine 11.22 (AMD Radeon RX 6800 XT, RADV, Mesa 26.3.1; clang-cl 23.1.5 + xwin cross-build), merged onto main 2236919f7 (a later merge of origin/main as well): pass for the case it targets, with conflicts to resolve.

  • It fixes the Wine fault in --run of the retail executable. On main the first TLS callback of the title faults inside rt::shims::library_loader::host_module_name (a null read in a std::map lookup reached from GetProcAddress): the title's /GA TLS writes zero the TLS block of gta6rt.exe at index 0, and the function-local statics then read a zeroed TLS epoch. With this PR the trace shows the tls_index0 event and the run goes on to the title's own startup code, past that fault (it then needs the xmem shims of xmem: serve the seven missing imports (physical pages, default allocators, XMemIsToolsMemAvailable); XMemVirtualAlloc takes 2 MiB pages and placeholders #6919 and XErrorReport of xgameruntime: serve XErrorReport (rebase of #5312) #6582). That makes it the real fix for denisturcanu84's Wine finding (RT-488), not a workaround in library_loader.cpp.
  • Merge conflicts with current main (three files): runtime/CMakeLists.txt (keep both test blocks: gta6rt_stack/run_tiny_game_stack and run_tiny_tls_ga/run_tiny_tls_clone_cleanup), runtime/README.md (keep main's paragraph on blocks given to already-running threads, then this PR's sentence and bullets), and two hunks in runtime/src/pe_loader.cpp on_host_thread_event (keep main's forget_ended_thread_id() and release_existing_blocks_of_this_thread() try/catch calls, then this PR's installed[]/kTlsSlotCount/kMainImageSlot loops). It builds clean after that.
  • Runtime tests that match tls|loader|pe_loader after that merge: 9 of 10 pass (loader_tls_index0, loader_tls_index0_threads, loader_tls_index0_noreserve, run_tiny_game_tls, run_tiny_tls_clone_cleanup among them). run_tiny_tls_ga fails under Wine: check_tls_index0.cmake:44 expects --run without the reservation to refuse the /GA executable, but it ran it to completion (tls_index=0 main=42 thread=42 OK, exit 0). I have not checked whether that is Wine-specific or a gap in the refusal.

Synthetic fixtures for the tests; the retail executable was only used to see where --run stops. No game data here. AI-assisted (Claude Code).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.