Skip to content

loader: enumerate only this process's threads for startup TLS - #7884

Closed
sarveshgamers wants to merge 7 commits into
ProjectLeonida:mainfrom
sarveshgamers:fix/loader-tls-thread-enum
Closed

sarveshgamers wants to merge 7 commits into
ProjectLeonida:mainfrom
sarveshgamers:fix/loader-tls-thread-enum

Conversation

@sarveshgamers

@sarveshgamers sarveshgamers commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Claimed as a new RT item in the coordination thread (#7496 (comment)) and recorded as done with this PR in the current thread (#8047 (comment)). No RT- ID has been assigned yet; the item is "startup TLS thread enumeration".

What and why

Loader::install_on_existing_threads gives every other running thread its copy of a mapped module's static TLS. To find them it takes a TH32CS_SNAPTHREAD snapshot and calls Thread32Next over every thread in the system, once per mapped TLS module. On Windows 11 with 5,650 threads in 297 processes, a dry run of the retail executable measured:

part per TLS module
CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD) 6.0–10.5 ms
Thread32First/Thread32Next walk 22.5–31.6 ms

The three startup TLS modules (the executable, XboxBvhBuilder.dll, libHttpClient.GDK.dll) paid that three times.

What changes

  • Prefer ntdll's NtGetNextThread, which walks only this process's threads and returns a handle for each. A one-thread probe costs 0.008 ms.
  • Run it per module, not once per process: a thread created between two module loads has no DLL_THREAD_ATTACH for the later module, so it still has to be found and given that module's block.
  • Keep the calling thread's handle only as the enumeration cursor; it never enters the candidate list (its block was installed by install_thread_block). That also means a single-thread process is a complete walk, not an empty one.
  • Give each returned handle a single owner until the candidate list accepts it, so a failed vector growth cannot leak or double-close it.
  • Treat a returned handle with no readable thread id as an incomplete walk, so the calling thread is not installed under id 0.
  • A missing export, a call that fails before STATUS_NO_MORE_ENTRIES, or an older/stub implementation without it falls back to the existing Toolhelp walk. Current Wine implements NtGetNextThread and takes the Nt path. The fallback also closes any handles from the partial ntdll walk. LEONIDA_LOADER_TOOLHELP=1 forces that path, and loader_tls_toolhelp runs the same suite through it on CI.

The same threads are given the same blocks and the same install/restore path runs, so behavior is unchanged; ~Loader still restores every block.

Measurements

gta6rt --dry-run <retail executable> --game-dir <own 1.0.2.1 package>, Windows 11, main dde82f27e, clang-cl 23.1.6 + xwin, warm file cache, 12 alternating runs of a before/after binary pair:

median dry-run
before 1016.1 ms
after 861.4 ms
saved 154.7 ms (15%)

The instrumented component on the same code path (main 8575d36ed) was 6.0–10.5 ms snapshot + 22.5–31.6 ms walk per module; NtGetNextThread measured 0.008 ms for the one-thread probe. This is startup CPU only; no game data or GPU work is involved.

Tests

  • loader_tls_test <tiny_tls.dll>: 86 checks pass (includes threads that existed before load(), thread-pool workers, three modules at once, and a terminated thread). The new case starts a thread between three module loads and checks that it reads all three templates; a per-process cached thread list would fail it.
  • loader_tls_toolhelp (LEONIDA_LOADER_TOOLHELP=1): the same 86 checks pass through the Toolhelp fallback.
  • pe_loader_test <tiny_dll.dll> <tiny_exe.exe>: 79 checks pass without a package; 111 checks pass with LEONIDA_GAME_DIR set to my own 1.0.2.1 copy (optional package integration and unwind tables).
  • loader_test: 88 checks, 0 failed.
  • Handle ownership: the reviewer's std::pmr::null_memory_resource() synthetic (candidate vector cannot grow) showed the retained NtGetNextThread handle before the fix and none after it; normal loader_tls_test still passes 86 checks.
  • tests/test_docs_env_vars.py: 4 tests pass after documenting LEONIDA_LOADER_TOOLHELP in runtime/README.md.

Independent Windows checks on 7880e0f24 (before the review fixes): 3/3 focused CTests passed, and a full ctest -C RelWithDebInfo run passed 111/111. The current head c2a116ab8 is locally checked on both enumeration paths; a re-check on the current head is welcome.

  • gta6rt --dry-run on the retail executable completes with the same 29 unimplemented imports.

AI-assisted. No game data, logs or traces are included.

Depends on: none in these hunks. #7524 and #5805 also edit install_on_existing_threads, but not the candidate struct or the enumeration loop this changes; #4313 edits the same file elsewhere. A rebase may still be needed if one lands first. This branch is on main dde82f27e.

Loader::install_on_existing_threads takes a TH32CS_SNAPTHREAD snapshot and walks every thread in the system, once per mapped TLS module. With gta6rt --dry-run on the retail executable (Windows 11, 5,650 system threads), that is 6-10 ms for the snapshot and 23-32 ms for the Thread32Next walk per module; the three startup TLS modules add about 90 ms.

Prefer ntdll's NtGetNextThread, which returns one handle per thread of this process only (0.008 ms for the one-thread probe). It still runs per module, so a thread created between two module loads is seen; the calling thread is kept as the enumeration cursor and skipped by the install loop. A missing export or a call that does not reach STATUS_NO_MORE_ENTRIES falls back to the existing Toolhelp walk, which also keeps Wine and older Windows working.
… templates

The enumeration in install_on_existing_threads runs per load, not once per process: a thread created after the first module has no DLL_THREAD_ATTACH for a module mapped later, so it still has to be found. The new case starts a thread between three loads and checks that it reads all three templates; a cached thread list would fail it.
A process always has its calling thread. An implementation that answers STATUS_NO_MORE_ENTRIES without yielding one is treated like a missing export and retried through Toolhelp, so a broken or stub ntdll cannot silently skip every other thread.
@sarveshgamers
sarveshgamers force-pushed the fix/loader-tls-thread-enum branch from abe50d9 to 7880e0f Compare November 23, 2026 17:50
@shdann

shdann commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

AI-assisted Windows 11 review of 7880e0f24. The new NtGetNextThread path leaks its most recent thread handle if candidates.push_back cannot allocate. At that point Windows has returned the handle, but the cleanup list does not own it yet.

I reproduced this with the synthetic loader_tls CTest. To repeat it in runtime/src/pe_loader.cpp:

  1. Include <memory_resource>. Change the local Candidates::list to std::pmr::vector<Candidate> list{std::pmr::null_memory_resource()};. Bind candidates as auto&. This makes the first vector growth throw std::bad_alloc.
  2. Put this observer immediately before struct Candidates in install_on_existing_threads. It runs after the candidate list destructor.
    struct Observe {
        HANDLE value{};
        ~Observe() {
            DWORD flags{};
            if (value && GetHandleInformation(value, &flags)) {
                std::fprintf(stderr, "retained thread handle after candidate cleanup: thread %lu\n", GetThreadId(value));
                CloseHandle(value);
            }
        }
    } probe;
  1. Set probe.value = thread; immediately before candidates.push_back({GetThreadId(thread), thread});. Build loader_tls_test in RelWithDebInfo. Run ctest -C RelWithDebInfo -R "^loader_tls$" --output-on-failure from the build directory.

The unmodified test passes. With the allocation failure, GetHandleInformation succeeds after cleanup, and GetThreadId returns 13668 in my run. The expected result is a closed handle. The observer closes the leaked handle after recording it. Please give the returned handle a local owner until insertion succeeds.

@likecrank-dotcom

Copy link
Copy Markdown

Independent native Windows validation of head 7880e0f247923bb5391d77209d72fc53feee42d2.

Windows 11 Pro; MSVC 19.44.35230.0, Windows SDK 10.0.26100.0, CMake 3.31.6-msvc6; Visual Studio 2022 x64 RelWithDebInfo. Host GPU: NVIDIA RTX 5060 Ti, driver 32.0.16.2114 (these are CPU tests).

Built loader_test, pe_loader_test, and loader_tls_test from the exact PR head, with no local source changes. Focused CTest run:

  • loader: PASS, 88 checks / 0 failed (10.27 s).
  • pe_loader: PASS, 79 checks (0.46 s); the optional package-dependent sections printed SKIP because LEONIDA_GAME_DIR was unset.
  • loader_tls: PASS, 86 checks (8.73 s), including the new thread-between-module-loads case.

3/3 CTest entries passed. Only locally built synthetic PE/DLL fixtures were used. This does not validate retail startup performance, the forced-Toolhelp fallback, or the full runtime suite.

AI-assisted with Codex.

@Kerwinss

Copy link
Copy Markdown

Tested 7880e0f on Windows 11 Pro 10.0.26300, MSVC 14.51 (VS Build Tools 2026), RTX 4060 / 621.24 (CPU tests only, no Vulkan SDK): pass.

Merged onto main dde82f2 (clean): full runtime build, then ctest -C RelWithDebInfo: 111/111 passed, the same as main alone. loader_tls passes, including the new check that a thread created between module loads gets each later module's template. Also passed at the previous head abe50d9.

Code read: the walk keeps each returned handle as the next call's cursor and in candidates, so all of them are closed by Candidates::close(). A partial walk closes its handles before the Toolhelp fallback, and the calling thread is skipped in the install loop on both paths. One gap: on Windows the test only exercises the NtGetNextThread path, not the Toolhelp fallback (that path runs under Wine).

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

@justrealyme

Copy link
Copy Markdown

Tested 7880e0f on NVIDIA GeForce RTX 5070 Ti, driver 617.42, Windows 11 build 26300, VS 2022 Build Tools (MSVC 19.44), Windows SDK 10.0.26100, Vulkan SDK 1.4.363.0, RelWithDebInfo: pass.

Built loader_tls_test and ran ctest -R ^loader_tls$: Passed (0.2 s).

Synthetic tests only, no game files. AI-assisted (Claude Code).

…ot grow

A failed candidates.push_back left the handle returned by NtGetNextThread open, because the candidate list is what owns handles. A local owner now closes it unless the vector takes it. Reproduced with the reviewer's std::pmr::null_memory_resource() synthetic: without the owner the observer saw the retained handle after cleanup; with it, none. The normal loader_tls suite still passes 86 checks.
@sarveshgamers

Copy link
Copy Markdown
Contributor Author

Thanks, fixed in d9dbcd8. The handle returned by NtGetNextThread now sits in a local owner until candidates.push_back succeeds, and the owner closes it if the vector throws. Reproduced with the pmr null_memory_resource synthetic: without the owner the observer printed the retained handle after cleanup; with it, none. Normal loader_tls still passes 86/86.

On the fallback gap: I rebuilt with the export name deliberately disabled and loader_tls passed 86/86 through the Toolhelp path. The Windows test only takes NtGetNextThread otherwise, as noted; the Wine job is the natural fallback coverage in CI.

LEONIDA_LOADER_TOOLHELP=1 forces the documented fallback, and a second CTest entry runs loader_tls_test through it (86 checks). The variable is documented in runtime/README.md, so test_docs_env_vars stays green. The normal entry still covers NtGetNextThread.
@sarveshgamers

Copy link
Copy Markdown
Contributor Author

The fallback gap is now covered too: LEONIDA_LOADER_TOOLHELP=1 forces the Toolhelp path, and a second CTest entry (loader_tls_toolhelp) runs the same 86 checks through it. Both entries pass locally; runtime/README.md documents the variable and tests/test_docs_env_vars.py stays green.

…ead id

Two review follow-ups: ThreadHandle now has an explicit constructor and deleted copy so it cannot be duplicated and double-close, and a returned handle whose GetThreadId is 0 makes the walk incomplete instead of being installed under id 0 (the calling thread would then not be skipped). loader_tls passes 86 checks on both the NtGetNextThread and Toolhelp paths.
@sarveshgamers

Copy link
Copy Markdown
Contributor Author

Second review pass: ThreadHandle is now single-owner (explicit constructor, deleted copy), and a handle whose GetThreadId is 0 makes the walk incomplete and falls back, instead of installing the calling thread under id 0. loader_tls still passes 86 checks on both the NtGetNextThread and Toolhelp paths. The body now lists #7524, #5805 and #4313 as rebase conflicts and uses the current coordination thread #8047.

@likecrank-dotcom

Copy link
Copy Markdown

Independent retest of 297a1c2dbf97f20e70c14059c4089cea62894297, including the new registered Toolhelp test. Native Windows 11 Pro 10.0.26300, MSVC 19.44.35230.0 / SDK 10.0.26100.0, VS 2022 x64 RelWithDebInfo, CMake 3.31.6-msvc6; same RTX 5060 Ti / driver 32.0.16.2114 host (CPU tests).

Built from the exact head with no local source edits, then focused CTest:

  • loader: PASS, 88 checks, 10.34 s.
  • pe_loader: PASS, 79 checks, 0.63 s; optional package sections skipped.
  • loader_tls: PASS, 86 checks, 1.20 s.
  • loader_tls_toolhelp: PASS, 86 checks, 0.61 s, using the PR's registered LEONIDA_LOADER_TOOLHELP=1 environment setting.

4/4 CTest entries passed. This independently covers both the normal enumeration and the forced fallback on Windows. It does not inject allocation failure, unreadable thread IDs, or partial-enumeration failure. No game files; not a full runtime-suite or retail performance run. AI-assisted with Codex.

NtGetNextThread returns the calling thread too, but its only use is as the next call's cursor: install_thread_block already gave it the module's copy. Keep that handle in a separate cursor list, so the install loop is unchanged and a single-thread process does not look like an empty walk. The Toolhelp fallback excludes the calling thread again, and loader_tls passes 86 checks on both paths.
@sarveshgamers

Copy link
Copy Markdown
Contributor Author

Follow-up to the review: the calling thread's handle now stays out of the candidate list (it is only the next-call cursor), so the install loop is unchanged and a single-thread process counts as a complete walk. That also removes the direct hunk overlap with #7524/#5805. loader_tls is 86/86 on both the NtGetNextThread and Toolhelp entries at c2a116a.

@MartinIndra02

Copy link
Copy Markdown
Contributor

Independent build + test: PASS

AI-assisted (Claude Code). Windows 11 x64, MSVC 19.44.35220, Ninja RelWithDebInfo. GPU (not used by these tests): NVIDIA GeForce RTX 3080 driver 621.24 / 32.0.16.2124.

Head 297a1c2db, based on current main (dde82f27e). Re-ran the CMake configure for the new loader_tls_toolhelp ctest entry, then built loader_tls_test, tiny_tls, pe_loader_test, tiny_dll, tiny_exe, loader_test and test_pe_loader_bounds.

Command Result
ctest -R "^loader_tls" 2/2 passed: loader_tls 0.37 s (NtGetNextThread), loader_tls_toolhelp 1.34 s (LEONIDA_LOADER_TOOLHELP=1)
ctest -R "^loader_tls" --repeat until-fail:5 2/2 passed on all 5 repeats
ctest -R loader (loader, pe_loader, pe_loader_bounds, loader_tls, loader_tls_toolhelp) 5/5 passed
new loader_tls_test with runtime/src/pe_loader.cpp reverted to main passed

The last row is expected: the new late-thread check is a guard that both enumeration paths have to satisfy, not a test that only passes with the fix. On this machine the NtGetNextThread path makes the whole suite about 3.6x faster than the Toolhelp path.

Code notes (not blocking):

  • The calling thread is now skipped in the install loop (c.id == self) instead of in the enumeration, so both paths share the same skip. When GetThreadId returns 0, the walk is treated as incomplete and falls back to Toolhelp, which keeps that skip correct.
  • next_thread_fn() reads LEONIDA_LOADER_TOOLHELP once per process into a function-static. That works for the separate ctest entry, but setting the variable after the first TLS module has loaded has no effect. That's worth one line in the README paragraph.

@AirKyzzZ

Copy link
Copy Markdown
Contributor

Tested c2a116ab8 on RTX 2060 (NVIDIA 566.14), Windows 10 22H2, clang-cl 23.1.6 with the MSVC 14.44 STL, RelWithDebInfo: pass.

Built loader_tls_test and ran ctest -R ^loader_tls: loader_tls and loader_tls_toolhelp both pass, 4 runs each (0.33 to 0.67 s and 0.91 to 0.97 s). As expected for a change that keeps behaviour, this PR's test also passes with main's runtime/src/pe_loader.cpp (0.49 to 0.84 s), so the new between-loads case is a guard against a per-process thread cache rather than a red/green check.

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

@optinium51-bot

Copy link
Copy Markdown

Tested c2a116ab8 merged onto main 47428cc22 (clean merge) on NVIDIA GeForce RTX 3060 (driver 616.92), Windows 11 26200, MSVC 14.52 (VS 2026), RelWithDebInfo + Ninja: pass.

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

@Kerwinss

Copy link
Copy Markdown

Re-tested the new head c2a116a on Windows 11 Pro 10.0.26300, MSVC 14.51 (VS Build Tools 2026), Windows SDK 10.0.26100, NVIDIA GeForce RTX 4060 / 621.24, Khronos Vulkan headers via -DLEONIDA_VULKAN_HEADERS_FETCH=ON (no glslangValidator): pass.

Merged onto main dde82f2 (clean), full runtime build, ctest -C RelWithDebInfo -j6: 236/238. The two failures are the ones main has on this GPU: d3d12_depth_resolve (#7985) and d3d12_vulkan_device:6574 (claimed by iTzAlvar). The third, crt_timed_wait (FAIL an unnotified wait_for times out), is the early wake-up #7686 fixes and is unrelated: run alone it passed 10/10 on main and 10/10 with this PR. loader_tls passes. (My earlier pass was at 7880e0f.)

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

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.

9 participants