Skip to content

loader: hand static TLS index 0 to the mapped title - #7524

Closed
quietdom wants to merge 8 commits into
ProjectLeonida:mainfrom
quietdom:fix/static-tls-index0
Closed

quietdom wants to merge 8 commits into
ProjectLeonida:mainfrom
quietdom:fix/static-tls-index0

Conversation

@quietdom

Copy link
Copy Markdown

Three commits from bringing up a retail 1.0.2.1 title with gta6rt --run.

Why the loader change

The title's console toolchain folds every thread-local access to TEB->ThreadLocalStoragePointer[0]: 7,802 sites in its .text read gs:[58][0] directly, ignoring the index patched into its TLS directory. gta6rt.exe is the process's first module and therefore owns index 0, so the title wrote its cached allocator pointer to host TLS +0x13a8, read host garbage back at game+0x104075 (0xC0000005), and the same write ended in STATUS_HEAP_CORRUPTION (0xC0000374) on the next malloc.

Loader now takes mirror_index0 (set only by --run). For the first image it copies the raw template and zero-fill to the base of the host EXE's index-0 block: on the loading thread, on threads already running, and on DLL_THREAD_ATTACH. The loader's reserved helper slot still gets its own copy, so the patched _tls_index path is unchanged.

src/host_tls_pad.cpp reserves the room. MSVC's tlssup.obj emits 272 bytes of empty .tls before the .tls\$ contributions, then the pad; the copy ends inside the pad, before _Init_thread_epoch and the task queue's thread-locals. mirror_index0_block checks that range at run time and fails the load if it does not hold.

All runtime thread_local state moves to TlsAlloc slots (shims/host_tls.h): startup trace, XThreadSetTimeSensitive, the save read count, the queue pump guard and the loader's per-thread slot table. Otherwise the title's data overwrites it.

Other commits

  • xmem: serve the seven imports the title needs (XMemAllocDefault, XMemFreeDefault, the physical-page calls, XMemIsToolsMemAvailable); free only blocks the shim allocated; split the console attribute word from the page-protection byte (0x801 on a 24 GiB reservation becomes PAGE_READWRITE); drop and trace MEM_LARGE_PAGES instead of failing.
  • d3d12_xs: implement D3D12ConfigureVirtualMemoryX. The host has one address space, so it returns S_OK; the first call records the undocumented argument layout and caller, since the title traps shortly after when the descriptors are not what it expects.

Diagnostics

startup_trace.h gains the tools that found the fault: a one-shot guard-page write watch with trap-flag re-arm, a last-resort unhandled-exception record, faulting registers plus the TEB TLS vector / slot 0 / +0x13a8 on access violations, and a LEONIDA_TLS_INFO block-layout dump.

Verification

cmake --build runtime/build --config RelWithDebInfo --target gta6rt is clean (/W4 /permissive-). With the mirror in place the heap corruption and the game+0x104075 fault are gone; the title now runs to its own int3 (0x80000003) at game+0x5a91c21, which is the next blocker rather than a loader fault.

The 200+ test targets were not built for this branch. The change is gated on mirror_index0, whose default is off, so test executables load images exactly as before.

No game data is included in the diff.

1.0.2.1 imports XMemAllocDefault, XMemFreeDefault, XMemAllocatePhysicalPages, XMemFreePhysicalPages, XMemMapPhysicalPages, XMemMapPhysicalPagesScatter and XMemIsToolsMemAvailable; none were in the shim table, so loading stopped on unresolved imports.

XMemFree now releases only pointers this shim handed out. The title also frees console pointers (its own arenas, mapped physical pages); passing those to the CRT is what produced STATUS_HEAP_CORRUPTION (0xC0000374) on the retail executable.

Virtual allocations keep the console's attribute word and its page-protection byte apart. The title asks for 0x801 on a 24 GiB reservation and traps on int3 when VirtualAlloc rejects it; the host accepts eight low-byte protections only, so an unknown word becomes PAGE_READWRITE and is recorded once. MEM_LARGE_PAGES is dropped and traced rather than failing the reservation.

Opt-in traces (LEONIDA_XMEM_HEAP_PROBE, LEONIDA_XMEM_NOFREE) record the allocator table and each virtual allocation.
The Xbox-only call hands the title's memory manager the console's virtual-address ranges. The host has one address space and the D3D12 layer allocates from it, so there is nothing to configure and the call returns S_OK.

Its argument list is not documented; the first call records all four registers, a hex view of every argument that points at readable memory and the caller, because 1.0.2.1 traps (int3) shortly after the call when the descriptors are not what it expects. LEONIDA_CVMX_RET overrides the return for the experiment.
The title's console toolchain folds every thread-local access to TEB->ThreadLocalStoragePointer[0] (7,802 gs:[58][0] sites in 1.0.2.1), so its CRT ignores the index the loader patches into its TLS directory. gta6rt.exe is the process's first module and owns index 0; the title wrote its cached allocator pointer to host TLS +0x13a8, read host garbage back at game+0x104075 (0xC0000005), and the same write ended in STATUS_HEAP_CORRUPTION (0xC0000374) on the next malloc.

Loader now takes mirror_index0. For the first image it copies the raw template and zero-fill to the base of the host EXE's index-0 block, on the loading thread, on threads that were already running, and on DLL_THREAD_ATTACH. The loader's own reserved helper slot still receives a separate copy, so the patched _tls_index keeps working.

src/host_tls_pad.cpp reserves the room: MSVC's tlssup.obj puts 272 bytes of empty .tls before the .tls\$ contributions, then the pad. The template ends inside the pad, before _Init_thread_epoch and the task queue's thread-locals, and mirror_index0_block enforces that range at run time.

Every runtime thread_local moves to a TlsAlloc slot (shims/host_tls.h): startup trace state, XThread time-sensitive flag, save read count, queue pump guard and the loader's per-thread slot table. Otherwise the title's data would overwrite them.

startup_trace gains the diagnostics that found this: guard-page write watch with re-arm, a last-resort unhandled record, faulting registers plus the TEB TLS vector, slot 0 and +0x13a8 on access violations, and the LEONIDA_TLS_INFO layout dump.

Verified with cmake --build runtime/build --config RelWithDebInfo --target gta6rt (clean). With the mirror the heap corruption and the game+0x104075 fault are gone; the title runs to its own int3 (0x80000003) at game+0x5a91c21. The test targets were not built.
@MartinIndra02

Copy link
Copy Markdown
Contributor

Independent Windows build test of 664303000: fail (linker error in loader_test.exe).

Setup: Windows 11 x64, MSVC 19.44.35220 (RelWithDebInfo, Windows SDK 10.0.26100.0), Ninja.

  • cmake --build ... --target loader_test fails to link:
    pe_loader.cpp.obj : error LNK2019: unresolved external symbol "unsigned char * __cdecl guest_tls_pad_end(void)" (?guest_tls_pad_end@@YAPEAEXZ) referenced in function "bool __cdecl rt::`anonymous namespace'::mirror_index0_block(void *,struct rt::Module const &)"
    loader_test.exe : fatal error LNK1120: 1 unresolved externals
    
  • Cause: runtime/CMakeLists.txt adds src/host_tls_pad.cpp to gta6rt, but loader_test (and any other target compiling src/pe_loader.cpp) does not link src/host_tls_pad.cpp.

AI-assisted review/test.

@Envyre

Envyre commented Nov 23, 2026

Copy link
Copy Markdown

Code read of 6643030 (the TLS commit), beyond the link error already reported above:

  1. Threads that already exist don't get the mirror. mirror_index0_block (pe_loader.cpp:420-429) checks the target block against guest_tls_pad_end(), which is the calling thread's pad. When install_on_existing_threads mirrors another thread's block (:658-662), that block's base is compared with the loading thread's pad end, so pad_end < base and the copy is skipped, and the false return is ignored. Measured with a standalone x64 program: another thread's static TLS block sat above the main thread's pad end in 3 of 3 runs. Those threads keep reading the host's bytes at index 0. Comparing the template size against the pad's size (computed once) instead of against an address would work for every thread, and a failed mirror should at least be logged.

  2. Two copies of the title's TLS. The title's _tls_index still points at the helper slot with its own block (:456-470), so accesses through _tls_index (Runtime: give the mapped image the module TLS index 0 its code expects #7473 counted 52 of them) read one copy while the folded index-0 accesses read the mirror; writes through one aren't seen through the other. Writing 0 into the title's index variable and dropping the separate block would keep one copy.

  3. Overlap: Runtime: give the mapped image the module TLS index 0 its code expects #7473 fixes the same problem the opposite way (moves the host's _tls_index off 0 and gives index 0 to the image) and touches the same functions (install_thread_block, install_on_existing_threads, the Loader constructor, g_thread_tls_slots, gta6rt's source list), so only one of the two can land as is.

  4. Smaller: the VirtualAlloc'd block leaks if the mirror check throws (:459-464; check before allocating), and thread_tls_slots() news a per-thread array (:337-344, also from DLL_THREAD_DETACH at :820) that is never freed. The template's alignment field isn't checked against the host block's alignment (ntdll gave 16-byte alignment in the same probe).

AI-assisted (Claude Code).

@Etr0p

Etr0p commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Overlaps #4313 (RT-259). From the two diffs, both PRs aim at the same fault: under gta6rt --run, the mapped title reads its thread-locals through module TLS index 0, which belongs to gta6rt.exe. They fix it in different ways:

  • Loader: the mapped game executable owns module TLS index 0 (RT-259) #4313 moves gta6rt's own TLS out of index 0. In runtime/src/main.cpp, a .CRT$XCT initializer calls rt::reserve_tls_index0() (runtime/src/pe_loader.cpp), which loads a home clone of gta6rt_tls_host.dll (runtime/src/tls_host.cpp, a 16 KiB template), swaps slot 0 with the home slot and rewrites gta6rt.exe's _tls_index. Slot 0 then belongs to the mapped executable (kMainImageSlot) for its whole life. An executable with TLS that does not get index 0 is refused under --run/--init. It adds loader_tls_index0_test and three fixtures.
  • loader: hand static TLS index 0 to the mapped title #7524 keeps index 0 with gta6rt.exe. Under --run (Loader(..., mirror_index0) in pe_loader.cpp), it copies the title's TLS template into the base of the host's index-0 block (mirror_index0_block). The room comes from runtime/src/host_tls_pad.cpp. It moves the runtime's own thread_local state to TlsAlloc slots (runtime/shims/host_tls.h, xgameruntime*.cpp, queue_holds.h). It adds no test.

What #7524 has that #4313 doesn't:

#4313 has 4 Windows --run reports with the retail executable that quote its head 28ea6b971: sneylol, theswiss24, kapitche and Zunraz. tugasky has one more on a merge with main (AMD 26.11.2). Several Wine/Proton runs come on top of those. #7473 (closed) was a third take on the same fix.

Read from the diffs only; nothing built or run for this comment.

AI-assisted (Claude Code).

host_tls_pad.cpp was added only to gta6rt, so loader_test (and any other target compiling pe_loader.cpp) failed to link on guest_tls_pad_end. The pad and its accessors now live in pe_loader.cpp: gta6rt.exe, the only image that owns static TLS index 0, defines LEONIDA_MIRROR_INDEX0 and gets the real 8 KiB pad; other targets get null accessors and never set Module::mirror_index0.

Verified: gta6rt and loader_test build clean, ctest -R ^loader$ passes.
@quietdom

Copy link
Copy Markdown
Author

Fixed in f302413. The pad now lives in pe_loader.cpp, guarded by LEONIDA_MIRROR_INDEX0 (defined only for gta6rt); other targets get null accessors and never set mirror_index0, so loader_test and the rest link without a separate translation unit.

Verified locally: gta6rt and loader_test build clean, and ctest -R ^loader$ passes (1/1).

@Kisanae

Kisanae commented Nov 23, 2026

Copy link
Copy Markdown

Build break on this branch, reproduced twice from a clean configure (no local changes):

xmem_test.cpp.obj : error LNK2019: unresolved external symbol "unsigned char * __cdecl guest_tls_pad(void)" (?guest_tls_pad@@YAPEAEXZ) referenced in function "bool __cdecl rt::startup_trace::open(wchar_t const *,int *)" xmem_test.exe : fatal error LNK1120: 1 unresolved externals FAILED: xmem_test.exe

The third commit says the pad is defined in pe_loader.cpp so every loader target links, but xmem_test is not a loader target: its link line is est/xmem_test.cpp.obj shims/xmem.cpp.obj shims/registry.cpp.obj, and startup_trace.h (pulled in by xmem.cpp) now calls guest_tls_pad() from open(). Nothing in that set defines it.

Two ways out:

  • move the pad to something every consumer links (an inline in a header, or a small .cpp added to the targets that include startup_trace.h), or
  • keep the call behind the loader (e.g. only when a pad was registered), so a target without pe_loader.cpp never needs the symbol.

Environment: VS 2026 (MSVC 14.52), Windows SDK 10.0.26100, Vulkan SDK 1.4.363.0, Windows 11 26300, RTX 4080. Built with scripts/build_runtime.ps1 -Jobs 12.

@Silliana

Copy link
Copy Markdown

Integration signal (no change requested): on Windows 11 26200, RTX 3070 Ti (driver 32.0.15.9649), main 9f53c50, merging this PR with #6582 and #4348 locally on the retail 1.0.2.1 executable: the TLS-index-0 fault is gone, XErrorReport is served, DStorageGetFactory and IDStorageFactoryX::OpenFile return the shim interfaces, and the title creates the D3D12 device on the Vulkan backend (D3D12XboxCreateDevice ok, RTX 3070 Ti, subgroup 32). The next fault is device slot 26's by-value-return ABI (AV reading this=1 at +0xd0), which #6964 addresses. So the TLS half survives the next three subsystems. No game data in this report.

@Kisanae

Kisanae commented Nov 23, 2026

Copy link
Copy Markdown

Follow-up: with the link break above worked around locally, this branch does reach a retail 1.0.2.1 title, and the next
gap is one export that the shims do not serve.

What the branch gets past (no patch beyond the link workaround): the loader change alone stops early, with

[rt] loader: GetProcAddress(xgameruntime.dll, XErrorReport): not served

Adding the flat XErrorReport(HRESULT, const char*) export (the file already has the IXErrorImpl vtable slot; the
title resolves the flat export by name at run time) moves the same run from ~1.2 s and a shallow stop to ~2.1 s with
the GDK runtime coming up:

[rt] xgameruntime: InitializeApiImplEx2(gdk=10002, gs=7901, mode=0x2, options=none) (offline)
[rt] unimplemented: xcrdapi.dll!DStorageGetFactory

So the ordering for a title bring-up looks like: TLS index 0 (this PR) -> flat XErrorReport -> DStorageGetFactory.
If you want, I can send the two-line XErrorReport addition (a wrapper around the existing error_report plus the
table entry) as its own PR against this branch or against main, whichever you prefer; I have not opened one because
this PR already owns the area.

Environment: VS 2026 (MSVC 14.52), Windows SDK 10.0.26100, Vulkan SDK 1.4.363.0, Windows 11 26300, RTX 4080. No game
data, offsets or dumps quoted here — only export names and the shim's own log lines.

…ad symbol

startup_trace.h reached the pad through a function in pe_loader.cpp, so every target that compiles xmem.cpp or startup_trace_test but not the loader failed to link. The pad is now reached through a function pointer that pe_loader.cpp sets during static initialisation; targets without it report no pad.

Review fixes in the same pass: capacity is measured once as guest_tls_pad_end() - module_tls_slots()[0] instead of comparing another thread's block against the loading thread's pad; a mirror module writes 0 to its AddressOfIndex and installs no copy at all (the helper slot is still claimed for its thread events), so there is a single index-0 copy and no allocation before the range check; thread_tls_slots() is freed on DLL_THREAD_DETACH; mirror records are never VirtualFree'd.
… leg

XGameRuntimeInitialize resolves the flat export XErrorReport after a failed API initialisation; without it GetProcAddress returned null and the title reported 0x8924010a instead of the real status. The export logs the HRESULT and forwards to the callback the title registered.
The retail title imports DStorageGetFactory from XCRDAPI.dll and traps when the import is classified but unserved. This is the console DirectStorage factory and file path taken from ItsNotRexed#4348 (mariuslozo-boop), rebased onto the current tree: factory and file interfaces, queue, status array, fences, synthetic files through the file shims, and the access-violation-to-E_DSTORAGE_ACCESS_VIOLATION guard. dstorage_test covers the factory over synthetic files; unimplemented_policy_test classifies xcrdapi.

Verified: gta6rt builds, the title passes DStorageGetFactory and OpenFile, and ctest dstorage/loader/unimplemented_policy pass.
… fail

The shim gained both behaviours for the retail boot: 0x20000000 large-page requests fall back to ordinary committed pages, and nonzero attribute words are recorded and served. The test still asserted the old rejection.
@Silliana

Copy link
Copy Markdown

Measured in a local integration on main 9f53c50: this PR plus #6582/#4348/#6964/#6954/#7076/#7021 booted the retail title to 1,181 ok D3D12 calls (device, 5 queues, 7 allocators, 5 fences, 581 list/Close pairs) and, merged again in the console-command-list stack, past device+queue+fence. It fixes the index-0 access violation in both runs.

#4313 targets the same fault; only one loader-owned index-0 scheme can land. Suggest this one is canonical and #4313 closes, or rebases as a test-only addition (a loader test that asserts the pad and the copy).

Closed #7473 was the earlier attempt at the same fix. Not asking anyone to drop work - just flagging the overlap so the loader change stays single-sourced.

@YaBulochka

Copy link
Copy Markdown
Contributor

Measured against #4313, which is already in the #7154 stack and ships a /GA fixture (clang-cl emits gs:[58h]; mov (%rax),%rax, so the code never loads _tls_index) with 48 checks over the loading thread, a thread alive before load, new threads, a suspended thread without a TLS array, detach, a second EXE, and the refusal path.

This branch has no test for the mirror. run_tiny_game_tls exercises it indirectly, but nothing here reads index 0 without _tls_index, and only gta6rt defines LEONIDA_MIRROR_INDEX0, so no test target even has the pad. I ran the #4313 fixture under a gta6rt built from this branch: tls_index=0 main=42 thread=42, so the design works; the gap is coverage, not behaviour.

The pad is safe only while it is the first thing in the block, and the code does not check that. In the clang-cl/xwin build the pad starts at block +0x10 and _Init_thread_epoch sits at +0x2010, so the 5,248-byte copy ends at +0x1480 and leaves the epoch and the task queue's thread-locals alone. But mirror_index0_capacity() is pad_end - base: it bounds the copy by the pad's end, not by its start. In the plain build main.cpp's in_handler sat at +0x1, and a thread_local in any TU linked before pe_loader.cpp would be overwritten while the range check still passes. #4313 does not depend on that ordering, because the host's whole block moves to its own index (and the epoch is copied with it).

Scope: this PR is 8 commits, not the 3 the description names. dstorage.cpp and dstorage_xs_abi.h are byte-identical to #4348 (2,630 lines), D3D12ConfigureVirtualMemoryX is on main from #6792, XErrorReport is #6582, and the xmem commit reworks #6919. About 3,100 of the 3,428 added lines are not TLS. Those want their own PRs.

Not a blocker, just a detail: mirror_index0 = mirror_index0_ && order_.empty() does not check that the first image is an EXE, so under --init a DLL first image would also get _tls_index = 0.

agent: yes

@Yoshi-OOF Yoshi-OOF left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Independent test on Windows 11 x64 (build 26300), MSVC 19.44, RelWithDebInfo, RTX 5070 Ti (621.24). At upstream dde82f27e, initialization completed, but --run stopped with 0xC0000374. At this PR head the same package progressed to the WSAStartup entry breakpoint, where I deliberately stopped it before Winsock initialization. No heap failure was observed before that stop; this is not a frame or gameplay result, or a TLS-only A/B.

The run also produced six malformed JSONL records: five virtual allocation attribute events and one large-page event. hex() returns a bare 0x... token, which is not a JSON number. With the three string-quoting changes below, a rebuilt run to the same breakpoint produced 23/23 valid JSONL records, including all six XMem events. The protection fallback was not reached, but uses the same invalid encoding.

No game data or logs attached. AI-assisted: yes.

Comment thread runtime/shims/xmem.cpp
if (first) {
rt::startup_trace::event(
"xmem_virtual_alloc_protect",
"\"protect\":" + rt::startup_trace::hex(protect) + ",\"caller\":" +

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Quote the hexadecimal protection value for valid JSONL.

Suggested change
"\"protect\":" + rt::startup_trace::hex(protect) + ",\"caller\":" +
"\"protect\":" + rt::startup_trace::quote(rt::startup_trace::hex(protect)) + ",\"caller\":" +

Comment thread runtime/shims/xmem.cpp
if (!seen.insert(attributes).second) return;
}
rt::startup_trace::event("xmem_virtual_alloc_attributes",
"\"attributes\":" + rt::startup_trace::hex(attributes) +

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Use the same JSON string representation as the existing xmem_attributes event.

Suggested change
"\"attributes\":" + rt::startup_trace::hex(attributes) +
"\"attributes\":" + rt::startup_trace::quote(rt::startup_trace::hex(attributes)) +

Comment thread runtime/shims/xmem.cpp
Comment on lines +312 to +314
"\"allocation_type\":" + rt::startup_trace::hex(allocation_type) + ",\"caller\":" +
rt::startup_trace::quote(
rt::startup_trace::where(reinterpret_cast<uint64_t>(_ReturnAddress()))));

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Quote the hexadecimal allocation type too.

Suggested change
"\"allocation_type\":" + rt::startup_trace::hex(allocation_type) + ",\"caller\":" +
rt::startup_trace::quote(
rt::startup_trace::where(reinterpret_cast<uint64_t>(_ReturnAddress()))));
"\"allocation_type\":" + rt::startup_trace::quote(rt::startup_trace::hex(allocation_type)) +
",\"caller\":" + rt::startup_trace::quote(
rt::startup_trace::where(reinterpret_cast<uint64_t>(_ReturnAddress()))));

@Vonsek

Vonsek commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Second check on a Windows 11 machine (RTX 5080, driver 616.92), own 1.0.2.1 package, MSVC 2022 RelWithDebInfo, LEONIDA_D3D12=vulkan.

Before (main): gta6rt --run game_scarlett_master.exe --game-dir <package> --trace out.jsonl maps and initialises as usual (all seven startup XMemVirtualAlloc calls succeed), then the title faults reading 0xffffffffffffffff right after its first allocation through the cached per-thread allocator pointer. The startup trace agrees with the description above: the title's module TLS index is 5 in this process, and slot 0 holds gta6rt's own block.

With this head (c38194af8): that fault is gone. Per-thread tls_block events appear for every new title thread, and the title runs on into its next stop: an unhandled int3 (exit 0x80000003), immediately after its first XMemAllocatePhysicalPages (attributes 0x280).

That next stop is this branch's older XMemAllocatePhysicalPages shape (size, alignment, attributes, out). main's measured shape is (attributes, page_count*, page_array*), so the head needs a rebase on main before the stop after it means anything: with the four-argument shape that call cannot succeed and the title asserts, which main's shim would not do.

Commands: cmake -S runtime -B build -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo; cmake --build build --target gta6rt gta6rt_tls_host; then the --run line above. Trace stays on my machine; the numbers above are counts and error classes only.

Cryptoteep added a commit to Cryptoteep/Leonida that referenced this pull request Nov 23, 2026
…gainst main

Update docs/retail_boot_chain.md "What clears it" column against current main:
- Stops 1, 2, 6, 10, 11 landed on main (ItsNotRexed#6919, 042c5f3: physical pages,
  2 MiB pages, and placeholder reservations).
- Stop 3 landed on main (e417570: XErrorReport in runtime/shims/xgameruntime.cpp).
- Replace closed unmerged PR ItsNotRexed#4313 (Stop 4) with tracking open PRs ItsNotRexed#8379, ItsNotRexed#7524.
- Replace closed unmerged PR ItsNotRexed#4348 (Stop 5) with active takeover PR ItsNotRexed#8461, ItsNotRexed#7784.
- Link open tracking PRs for Stops 7, 9, 12 (ItsNotRexed#8851, ItsNotRexed#9061, ItsNotRexed#2490, ItsNotRexed#9045, ItsNotRexed#8414).

Addresses agulerman's finding in ItsNotRexed#8868.
@Numbers-iwnl

Numbers-iwnl commented Nov 23, 2026 •

Copy link
Copy Markdown

Ran this PR against a real copy. It moves the frontier from 4 to 6 on this box.

Machine: Windows 11 26300, Ryzen 7 5700X3D, RX 9070 XT (RDNA4, gfx1201), AMD 32.0.32029.2010 (26.11.2). Build: MSVC 19.44 (unpacked 14.44 toolset + SDK 10.0.28000), Ninja, RelWithDebInfo. Own copy of 1.0.2.1 + the retail executable, gta6rt --run <exe> --game-dir <copy> --trace.

main@867d922 (before): 5 modules mapped, 20 unimplemented imports, two XMemVirtualAlloc reservations (2.3 GB 0x283, 20 MB 0x181), then 0xc0000005 reading TLS index 0 at game_scarlett_master.exe+0x104075 — the stop in #8452 / #7968.

This PR (c38194af8): gets much further, and dies somewhere else entirely:

tls_block  0x2a0338a0000 size 8
tls_block  0x2a0338b0000 size 520
xgameruntime: InitializeApiImplEx2(gdk=10002, gs=7901, mode=0x2, options=none) (offline)
dstorage: DStorageGetFactory -> serving the factory interface
dstorage: IDStorageFactoryX::OpenFile -> serving the file interface
xgameruntime: XDisplayTryEnableHdrMode: HDR disabled (SDR output)
xmem_physical: XMemAllocatePhysicalPages args 0x280, <count>, <array>, 0x9a17a38000  caller game_scarlett_master.exe+0x5eb27ac
exception 0x80000003 at game_scarlett_master.exe+0x5eb27be

So: TLS blocks are handed out, the title gets through xgameruntime and DStorage, and it stops inside the physical-page allocation path — an int3 (0x80000003) immediately after XMemAllocatePhysicalPages with attributes 0x280, which is the documented stop 6 (XMemAllocatePhysicalPages unimplemented, the title asserts on FALSE). Nothing D3D12-side is reached yet.

Nothing about that is a criticism of the PR — it is the point: on this configuration it clears the TLS stop cleanly and lands exactly where the boot-chain doc says the next wall is. I have not merged it with the other boot PRs; this is #7524 alone on its base.

AI-assisted — agent: yes.

@EdouardSence

Copy link
Copy Markdown
Contributor

Tested the TLS part of this PR on the retail executable under Wine 11.22 (Linux, AMD RX 9070 XT on RADV), on main at 867d922 with #8195.

  • Taken: shims/host_tls.h, the pe_loader.cpp/.h index-0 mirror and pad, main.cpp, registry.cpp, startup_trace.h (the merge conflict there with main's skip_int3 was resolved by keeping both), CMakeLists.txt (both sides kept).
  • Left out: this PR's xmem.cpp, xmem_test.cpp and d3d12_xs.cpp changes. They conflict with main, and d3d12_xs.cpp then fails to build (configure_virtual_memory comes from the dropped xmem.cpp part).
  • Result: every static initializer passes (on main alone the run faults in the first one), InitializeApiImplEx2 runs, and with the later stack in my docs: the retail boot chain under Wine on Linux #7232 comment the title reaches stop 14 with 1,198 D3D12 calls and none failed. The title's /GA slot-0 reads find its own block: the allocator pointer at block+0x13a8 is the title's.

The TLS fix looks separable from the DirectStorage/xmem work here; splitting it out would make it mergeable on its own. AI-assisted (Claude Code), run and checked by me.

@heretic1321

Copy link
Copy Markdown

Code review of c38194af8 (TLS index-0 part) against #9223 (RT-259) and compared with #8379 and main 6312c057f.

What is right

  • Single copy on slot 0 (fixed since earlier reviews): 975b0c96f writes 0 to m.tls_index / AddressOfIndex (runtime/src/pe_loader.cpp:1466-1473) and copies directly into slots[0] without allocating a separate helper-slot copy (:492-503), so /GA gs:[58h][0] reads and _tls_index reads now share the same block.
  • Non-loader link break resolved: detail::guest_tls_pad is now registered via function pointer (pe_loader.cpp:40-42), avoiding unresolved symbols in targets without pe_loader.cpp.
  • No-TLS and callback-only (total == 0) images: initialize_tls() returns early for absent/all-zero directories (:1413-1417), and install_thread_block() handles !total before if (m.mirror_index0).

What is wrong or unhandled at c38194af8

  1. Host TLS corruption hazard — mirror_index0_capacity() does not check where g_guest_tls_pad starts (pe_loader.cpp:29, 444-464): mirror_index0_block() copies into slots[0] starting at offset 0, while mirror_index0_capacity() only checks guest_tls_pad_end() - vector[0]. g_guest_tls_pad is not pinned ahead of other .tls$ sections, so any static TLS variable linked before pe_loader.cpp.obj is silently overwritten while the check still passes.
  2. HostTls itself still depends on _Init_thread_epoch in host slot 0, and xtaskqueue still has static thread_locals:
    • HostTls<Tag>::slot() (runtime/shims/host_tls.h:86-89) and mirror_index0_capacity() (pe_loader.cpp:445) use C++11 function-local statics (static const DWORD value = TlsAlloc();), which under MSVC emit guard reads against _Init_thread_epoch inside gta6rt.exe's own index-0 block (safe only if linker layout places _Init_thread_epoch past the title's template, which is unchecked; TlsAlloc() failure is also unchecked).
    • third_party/xtaskqueue/Source/Task/WaitTimer_win32.cpp:24-25 still holds two thread_local pointers (t_callbackTimer, t_callbackInstance) in host slot 0.
  3. No TLS alignment enforcement & hard 8 KiB ceiling (pe_loader.cpp:29, 458-464): g_guest_tls_pad has no alignas, and mirror_index0_block() never checks tls->Characteristics & IMAGE_SCN_ALIGN_MASK against slots[0]'s alignment; templates requiring >16-byte alignment (e.g. 32/64-byte SIMD/cacheline TLS) can #GP.
  4. Unsafe cross-thread memcpy on pre-existing threads (pe_loader.cpp:705-719): install_on_existing_threads() calls mirror_index0_block(host_block, m) (std::memcpy/std::memset) directly into another live thread's active slots[0] without suspending it and without __try/__except (unlike read_thread_slot/write_thread_slot), racing with host TLS reads or thread exit; failures are silently skipped.
  5. Broken multi-module attach/detach ordering & per-thread heap churn under the loader lock:
    • on_host_thread_event(DLL_THREAD_ATTACH) (pe_loader.cpp:860-871) is single-pass in slot order 0..15. Because the EXE is mapped first into slot 0, its DLL_THREAD_ATTACH callback runs before its imported DLLs (slots 1..N) have their TLS installed or attached.
    • DLL_THREAD_DETACH (:880-903) uninstalls/frees DLL slots 15..1 before slot 0 (EXE) runs its detach callback, AND calls release_thread_slot(i) -> thread_tls_slots() (:354-361) unconditionally, allocating a heap std::array under the loader lock on every unrelated exiting thread only to delete it at :902.
  6. Wrong target / mode gating & no slot-0 restoration:
    • runtime/src/main.cpp:156 passes /*mirror_index0=*/true unconditionally (contradicting the PR description's "set only by --run"), clobbering host slot 0 even under --dry-run and --init, and ~Loader() / release_thread_slot() never restore it.
    • m->mirror_index0 = mirror_index0_ && order_.empty() (pe_loader.cpp:1319) does not check IMAGE_FILE_DLL, so loading a DLL first mirrors it into index 0.
  7. No test coverage & heavy scope/conflict overlap: There is no TLS index-0 or /GA test (LEONIDA_MIRROR_INDEX0 is only defined on gta6rt, runtime/CMakeLists.txt:22). The PR also bundles ~3,100 lines of unrelated DirectStorage, xmem (outdated 4-arg XMemAllocatePhysicalPages), D3D12ConfigureVirtualMemoryX (on main), and XErrorReport (on main in 6312c057f), producing 6 merge conflicts with main.

What a reviewer must check

AI-assisted static code review (read-only on Linux; not compiled or run on Windows).

dadnotdaddy pushed a commit to dadnotdaddy/Leonida that referenced this pull request Nov 23, 2026
… module TLS index 0 (RT-259)

Squashed from ItsNotRexed#4313 by mariuslozo-boop, head 28ea6b9 (security scan PASS).

Taken instead of ItsNotRexed#7524 for the TLS index 0 fix: ItsNotRexed#7524's head moved past its scanned sha (and grew a DirectStorage bundle), and its mirror scheme keeps two copies of the title's TLS and misses threads that already exist (review on ItsNotRexed#7524). Conflicts: pe_loader.cpp on_host_thread_event keeps main's forget_ended_thread_id / release_existing_blocks_of_this_thread first, then the PR's two-pass kTlsSlotCount loops (so the executable's slot is covered; the off-by-one reported on the PR comes from taking main's bounds). install_on_existing_threads is bounded by kTlsSlotCount too, so threads already running at load() (thread-pool workers) get the executable's slot-0 copy, as main does for every other module; loader_tls_index0_test now checks that load() gave the early thread its copy and that install/uninstall are no-ops there. CMakeLists.txt keeps both test sets; README keeps main's already-running-thread text plus the PR's ordering sentence and index-0 limits.
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.