Skip to content

Runtime: preserve process-attach TLS state at executable entry - #3790

Draft
kmeyer43 wants to merge 2 commits into
ItsNotRexed:mainfrom
kmeyer43:codex/tls-startup-integration
Draft

kmeyer43 wants to merge 2 commits into
ItsNotRexed:mainfrom
kmeyer43:codex/tls-startup-integration

Conversation

@kmeyer43

Copy link
Copy Markdown

Problem and correction

With gta6rt --run, Loader::initialise() ran on the loading thread, while executable entry ran on a newly created thread. A synthetic static TLS variable starts at 0x35; its process-attach callback writes 0x6A, but entry sees a fresh 0x35 template and returns 3.

Run initialization on the executable-entry thread after the existing game command line is established. Keep upstream's automatic TLS installation, thread notifications and restoration. No old ExitThread cleanup shim is introduced. Existing command-line handling from merged #2661 and DisableThreadLibraryCalls handling from merged #2383 are retained.

Failed startup and teardown reentry

Moving initialization into the runner also required explicit rollback: on a DLL initialization rejection, end_run(1) parks the thread and the host eventually calls ExitProcess, bypassing Loader destruction. This regression was introduced by the same-thread prototype, rather than existing upstream.

Extract the destructor's reverse-order process-detach notification pass and invoke it on the initialization thread before reporting startup failure. Keep mappings, unwind information and TLS live throughout callbacks. Repeated rollback and subsequent destruction do not duplicate notifications.

A detach callback could previously reenter bundled LoadLibrary after its module's initialized flag was cleared. The synthetic reproducer recorded a second TLS process attach and terminated with 0xC0000409. Publish a terminal teardown state before guest callbacks, refusing further initialization, bundled loading and forwarded-export resolution. Direct export lookup remains available. No new mutex is held across guest callbacks.

Reproduce

From an MSVC x64 development shell, using only repository-generated synthetic fixtures:

cmake -S runtime -B runtime/build -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo
cmake --build runtime/build --target gta6rt tls_startup_probe startup_rollback_exe startup_rollback_native startup_rollback_test
./runtime/build/tls_startup_probe.exe
./runtime/build/gta6rt.exe --run ./runtime/build/tls_startup_probe.exe
ctest --test-dir runtime/build --output-on-failure -R '^(startup_rollback|tls_startup_.*)$'

Compare the same probe with an unmodified runtime built from main at f847748cc76bd3777f9c070c4034eb2fc1c04e64:

  • Native Windows: process attach and entry share a thread; entry observes 0x6A; exit 0.
  • Unmodified upstream: different threads; entry observes 0x35; exit 3. Reconfirmed before publication.
  • This change: same thread; entry observes 0x6A; exit 0.

The registered rollback test covers native LoadLibrary failure, native executable startup failure, mapped failure, repeated rollback, post-detach refusal, successful initialization, destructor-only teardown and reentrant lookup. Dependency A detaches once with TLS 0x6A; rejecting B prevents executable entry and the runtime exits 1.

Native comparison distinction: Windows LoadLibrary failure detaches A and reports error 1114; Windows static-import executable startup failure exits 0xC0000142 without detaching A. Leonida's rollback retains existing upstream cleanup behavior rather than claiming these native cases are identical.

Validation

Windows 11 x64; MSVC 19.52 / Ninja; RelWithDebInfo. Host GPU: NVIDIA RTX 4070 Ti, driver 617.42; these tests require no GPU or game data.

  • Affected targets built successfully; final rebuild reported no work.
  • Focused loader/TLS, thread-call, command-line and startup-trace selection: 11 passed, 0 failed.
  • Applicable CPU CTest selection: 48 passed, 5 skipped, 1 disabled, 0 failed. The five package-dependent tests had no inputs; gameinput was already disabled.
  • Startup assertions check zero unexpected entry-thread attach notifications, fresh worker TLS 0x35, worker detach once on its own thread with 0x77, and retained entry TLS 0x6A.
  • Negative controls: incorrect callback count returns 2 natively and mapped; incorrect worker state returns 7; invalid cleanup count/state makes the regression checker return 1.
  • Synthetic DLL/EXE ordering, normal return, failed initialization, --init and --dry-run comparisons passed during integration.
  • git diff --check and staged file/security review passed.

Coordination and integration limits

Original claim by @kmeyer43: #3232 (comment), carried forward under #3574, whose continuation preserves earlier claims. The related coordination item is RT-137; this does not claim exclusive ownership of RT-137. The coordinator explicitly left attach/entry-thread ownership overlap to maintainer arbitration: #3232 (comment).

Depends on: #2661, #2383 (already merged into main).

Open work requiring merge integration, not implemented or merged here:

Nonstandard C++ guest throws and Windows structured-exception recovery are not fully implemented. Standard cleanup exceptions are reported; no blanket catch handlers or SEH suppression were added. The terminal guard is not a general concurrent-unload protocol. Combined open-PR behavior has not been tested.

Scope and disclosure

Original synthetic executables and DLLs only. No retail game files, protected assets, extracted game inputs, generated binaries, build artifacts or local logs are included. This does not claim to boot GTA 6 or fix every TLS edge case.

AI-assisted investigation and implementation (Codex), with independent AI-assisted review (Gemini). Published as a draft for correctness, integration and ownership 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.

Tested e9e6b57899a7d4de3a2ce9108bcffc49a3fb9aa2 (current refs/pull/3790/head; f8f607e7 is not in the repo) on Windows 11, MSVC 19.44.35228 + Ninja, RelWithDebInfo.

  • ctest tls_startup|startup_rollback -> 3/3 passed: startup_rollback 10/10 modes, tls_startup_native, tls_startup_mapped.
  • Native and mapped probes: process_attach count=1, attach tid == entry tid, value before 0x35 -> after 0x6A, no unexpected DLL_THREAD_ATTACH, one worker attach/detach, detach value 0x77.
  • Repeat runs: 10x all three targets, 50x the TLS pair. The LEONIDA_TLS_PROBE_BAD=count negative control exits 2 in both native and mapped modes.
  • Absent TLS is handled: a scratch PE with TLS-directory RVA 0 (startup_rollback_exe) exits 0, and rollback detaches once on the same thread.

Attach runs via main.cpp:154-156 -> initialise_for_run -> Loader::initialise before entry, which is the right point. Non-blocking pre-existing note: pe_loader.cpp:643-645 sets ERROR_DLL_INIT_FAILED, but shims/library_loader.cpp:203-206 overwrites it with ERROR_PROC_NOT_FOUND for a forwarder blocked during detach (the test only checks a null result); and a successful --run calls ExitProcess before ~Loader, so process-detach callbacks are not delivered on clean shutdown. Neither is introduced here. No blocker.

@kacper-serewis kacper-serewis 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.

Compared the same synthetic executable under native Windows, parent f847748 and head e9e6b57: exits 0/3/0. Parent split process attach and entry across threads; head ran them on one thread, retaining TLS 0x6A. Worker got a fresh 0x35 template and one attach/detach each. Two deliberately wrong controls returned 2 and 7 as expected. Native Windows x64 MSVC 19.50 RelWithDebInfo, ordinary synthetic startup only. AI-assisted.

@CowBoYdu76

Copy link
Copy Markdown
Contributor

Tested e9e6b57 (based on main f847748) on Windows 11 build 26300, MSVC 19.44, Ninja RelWithDebInfo, Vulkan SDK 1.4.363.0: pass.

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

Preserve upstream Unicode-safe console diagnostics alongside entry-thread startup. Retain merged process completion and TLS lifecycle changes. Verified focused TLS/rollback tests, CPU CTest and native/upstream/fixed synthetic comparisons.
@kmeyer43

Copy link
Copy Markdown
Author

Integration status update

I've integrated the latest upstream main, including the changes from #2070 and #2594, and verified that the TLS startup fix continues to work.

Updated local validation:

  • 11 focused tests passed, zero failures.
  • 52 expanded CPU tests passed, 6 skipped, 1 disabled.
  • Native Windows and the updated branch both preserve TLS 0x6A across process attach and executable entry, exiting successfully.
  • Upstream still reproduces the original regression.
  • Existing TLS lifecycle and ExitThread(23) behavior remain intact.

The Runtime, CI, and No Game Data workflows currently show action_required. Could a maintainer approve these runs when convenient?

I'll keep the PR in draft pending CI validation and RT-137 ownership/integration confirmation.

Thanks to everyone who has helped review and test this!

@Vonsek

Vonsek commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Tested bb561f5 on Windows 11 (MSVC RelWithDebInfo): full runtime build, then ctest for the shim/loader tests (loader, pe_loader, loader_tls, dll_thread_calls, unimplemented_policy, startup_trace, xmem, process_cmdline, file_system, winhttp_offline, xgameruntime, run_tiny_*, allocator_proxy) — 30 of 30 passed. AI-assisted.

@tupacfan04

Copy link
Copy Markdown
Contributor

Sound for a draft. Startup now runs on the entry thread before entry (runtime/src/main.cpp:181), the host TLS is installed on thread creation (runtime/src/tls_host.cpp:36), so process-attach writes 0x6A into that thread's block; the probe verifies entry 0x6A and the worker template/detach 0x35/0x77 on the worker's own thread, with no cross-thread leak. Rollback (runtime/src/pe_loader.cpp:597) detaches in reverse order on the init thread, detaching_ makes it terminal, and the load/initialise/forwarder paths refuse (:629,673,728,792,799).

Minor:

  • main.cpp:57 catches only std::exception, so an SEH/non-C++ throw from a guest callback terminates instead of exiting 1.
  • runtime/CMakeLists.txt:778-779 omit ${RUNNER}/timeouts used by sibling tests, so this will not run under Wine/arm64.
  • pe_loader.cpp:629 reads detaching_ outside mutex_ (benign, but inconsistent).

AI-assisted review, no game files, no GPU.

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.

6 participants