[PR #1881] pe_loader: fix wide dynamic load, failed-load rollback, GA TLS race, and compat forwarders (RT-PE-LOADER-DYNAMIC-ROLLBACK-AND-TLS) #1892

Open
opened 2026-11-26 21:19:19 +01:00 by 4ld0 · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/ubiquitarianism/leonida/pull/1881
Author: @ambroseautomation
Created: 11/25/2026
Status: 🔄 Open

Base: main ← Head: fix/rt-pe-loader-dynamic-rollback-and-tls


📝 Commits (1)

  • 80e6e53 pe_loader: fix wide dynamic load, failed-load rollback, GA TLS publication, and compat forwarders (RT-PE-LOADER-DYNAMIC-ROLLBACK-AND-TLS)

📊 Changes

3 files changed (+298 additions, -74 deletions)

View changed files

📝 runtime/src/pe_loader.cpp (+130 -68)
📝 runtime/src/pe_loader.h (+3 -0)
📝 runtime/test/loader_test.cpp (+165 -6)

📄 Description

Coordination item: RT-PE-LOADER-DYNAMIC-ROLLBACK-AND-TLS

Problem & Root Causes

Auditing runtime/src/pe_loader.cpp uncovered six bugs across runtime dynamic loads, failed-load rollback, static TLS publication, and compat-DLL forwarder precedence:

  1. Wide runtime loads (LoadLibraryW / LoadLibraryExW) passed non-NULL lpvReserved to DllMain:
    • Loader::load_runtime_module() established RuntimeLoadScope dynamic(runtime_loads_) so newly mapped modules got dynamic_load = true (lpvReserved == nullptr), while Loader::load_runtime_module_w() omitted it. Every bundled DLL dynamically loaded via load_runtime_module_w() received dynamic_load = false and a non-NULL CONTEXT* lpvReserved (pretending to be a static load).
  2. Failed runtime initialise() poisoned subsequent runtime loads and left failed dependencies registered:
    • When initialise() threw during Loader::load_runtime_candidate(), only by_name_.erase(module_key(mapped->path)) ran.
    • If a module threw in run_tls_callbacks() before m.initialised became true, it stayed in init_order_, causing every subsequent unrelated runtime LoadLibrary to re-run it and fail.
    • If a dependency's DllMain returned FALSE, the failed dependency stayed findable in by_name_, and the uninitialised parent remained in init_order_, so a later unrelated runtime load silently executed the abandoned parent's DllMain.
    • Also, Loader::initialise() used range-for iteration over init_order_, which invalidates iterators if a DllMain recursively loads another bundled module.
  3. Failed Loader::load() leaked newly mapped modules, address ranges, and static TLS slots:
    • When map_image(), bind_imports(), protect_sections(), or register_unwind() threw after order_.push_back(m) / initialize_tls(*m), Loader::load() only erased key from by_name_, leaving the failed module in order_, ranges_, and occupying one of the 16 static TLS slots (exhausting the pool after 16 failed TLS loads).
  4. /GA TLS patch publication race & VirtualSize == 0 section skip:
    • Loader::initialize_tls() published g_tls_slot_owners[slot] = &m and released ExclusiveTlsLock before running patch_ga_tls_reads() and writing m.tls_ga_slot, creating a data race where concurrent DLL_THREAD_ATTACH events saw m.tls_ga_slot == kNoTlsIndex and omitted the thread's /GA view (and shadowed nt under /W4 C4456).
    • Both patch_ga_tls_reads() and the CLZERO scan in protect_sections() computed min(Misc.VirtualSize, SizeOfRawData), skipping executable sections with Misc.VirtualSize == 0 (which map_image() and section protection treat as SizeOfRawData per PE/COFF).
  5. Unchecked VirtualFree(nullptr) in forget_ended_thread_id():
    • forget_ended_thread_id() called VirtualFree(it->ga_view, 0, MEM_RELEASE) unconditionally even when it->ga_view == nullptr.
  6. Loader::resolve_forwarder() bypassed LEONIDA_COMPAT_DIR:
    • resolve_forwarder() checked shims::find() directly without first checking resolve_compat(), allowing a forwarded export to bypass a drop-in compat DLL (or fall through to a shim for a symbol missing from a compat DLL that owns the module).

Summary of Changes

  • runtime/src/pe_loader.h, runtime/src/pe_loader.cpp:
    • Moved RuntimeLoadScope into Loader::load_runtime_candidate() so both narrow and wide runtime loads set dynamic_load = true.
    • Added Loader::unmap_module() and Loader::rollback_load() (sharing teardown with ~Loader()) to atomically roll back init_order_, order_, by_name_, ranges_, unwind tables, xmem hooks (keyed per-Module*), and static TLS slots on Loader::load() failures.
    • Added index-based Loader::initialise_all(Module** failed) and updated Loader::load_runtime_candidate() catch cleanup to unlink failed/uninitialised newly added modules from by_name_ and drop uninitialised entries from init_order_ while keeping modules whose DllMain ran (initialised == true) for ~Loader() process detach.
    • Moved /GA TlsAlloc() + patch_ga_tls_reads() before ExclusiveTlsLock publication in Loader::initialize_tls() (also clearing m.tls_ga_slot on install_thread_block() catch and removing the shadowed nt /W4 warning).
    • Treated Misc.VirtualSize == 0 as SizeOfRawData in patch_ga_tls_reads() and the CLZERO scan in protect_sections().
    • Guarded if (it->ga_view) in forget_ended_thread_id().
    • Checked resolve_compat() before shims::find() in Loader::resolve_forwarder().
  • runtime/test/loader_test.cpp:
    • Added 6 targeted regression checks covering wide load_runtime_module_w lpvReserved == nullptr, failed runtime TLS callback recovery, failed runtime dependency DllMain cleanup, 20x failed-load TLS slot / modules() / find_address() rollback, /GA patching with VirtualSize == 0, and LEONIDA_COMPAT_DIR forwarder precedence.

Verification

Environment: Windows 11 Pro 64-bit, MSVC 14.51.36231 (cl.exe), LLVM clang-cl.exe. GPU: n/a (CPU-only PE loader tests).

Before fix (upstream/main pe_loader.{h,cpp} + new regression tests in loader_test.cpp)

loader_test.exe (cl /std:c++20 /MD /W4 /permissive- /utf-8 /EHsc):

  • 101 checks, 6 failed (exit 1):
    • FAIL a wide run-time load's DllMain gets a NULL lpvReserved: lpvReserved was non-NULL
    • FAIL a runtime load that fails in TLS callbacks does not break later runtime loads: the later valid runtime load failed because of the abandoned module
    • FAIL a runtime load whose dependency fails DllMain drops both from lookup and skips abandoned parent: the failed dependency or parent remained findable by name
    • FAIL failed loads after TLS setup roll back modules, address ranges, and static TLS slots: failed loads leaked static TLS slots and exhausted the 16-slot pool
    • FAIL GA TLS patching scans executable sections whose VirtualSize is 0: the gs:[58h] read in the VirtualSize==0 section was not patched
    • FAIL a forwarded export honours LEONIDA_COMPAT_DIR over a shim: forwarded export to compat DLL did not bind to its Answer export

After fix

MSVC (cl.exe /std:c++20 /MD /W4 /WX /permissive- /utf-8 /EHsc, 0 warnings) and clang-cl (/std:c++20 /MD /W4 /permissive- /utf-8 /EHsc, 0 warnings in pe_loader.{h,cpp}):

  • loader_test: 101 checks, 0 failed (MSVC + clang-cl)
  • module_names_test tiny_dll.dll: 73 checks, 0 failures (MSVC + clang-cl)
  • loader_tls_test tiny_tls.dll: OK (118 checks) (MSVC + clang-cl)
  • loader_tls_index0_test runs: OK (40 checks) (MSVC + clang-cl)
  • loader_tls_index0_test threads: OK (6 checks) (MSVC + clang-cl)
  • loader_tls_index0_test noreserve: OK (3 checks) (MSVC + clang-cl)
  • python -I scripts/check_no_game_data.py runtime/src/pe_loader.h runtime/src/pe_loader.cpp runtime/test/loader_test.cpp: clean (exit 0)

AI-assisted: yes


🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.

## 📋 Pull Request Information **Original PR:** https://github.com/ubiquitarianism/leonida/pull/1881 **Author:** [@ambroseautomation](https://github.com/ambroseautomation) **Created:** 11/25/2026 **Status:** 🔄 Open **Base:** `main` ← **Head:** `fix/rt-pe-loader-dynamic-rollback-and-tls` --- ### 📝 Commits (1) - [`80e6e53`](https://github.com/ubiquitarianism/leonida/commit/80e6e53968756d916093e76c8b504159f3f8b5cc) pe_loader: fix wide dynamic load, failed-load rollback, GA TLS publication, and compat forwarders (RT-PE-LOADER-DYNAMIC-ROLLBACK-AND-TLS) ### 📊 Changes **3 files changed** (+298 additions, -74 deletions) <details> <summary>View changed files</summary> 📝 `runtime/src/pe_loader.cpp` (+130 -68) 📝 `runtime/src/pe_loader.h` (+3 -0) 📝 `runtime/test/loader_test.cpp` (+165 -6) </details> ### 📄 Description Coordination item: `RT-PE-LOADER-DYNAMIC-ROLLBACK-AND-TLS` ## Problem & Root Causes Auditing `runtime/src/pe_loader.cpp` uncovered six bugs across runtime dynamic loads, failed-load rollback, static TLS publication, and compat-DLL forwarder precedence: 1. **Wide runtime loads (`LoadLibraryW` / `LoadLibraryExW`) passed non-NULL `lpvReserved` to `DllMain`:** - `Loader::load_runtime_module()` established `RuntimeLoadScope dynamic(runtime_loads_)` so newly mapped modules got `dynamic_load = true` (`lpvReserved == nullptr`), while `Loader::load_runtime_module_w()` omitted it. Every bundled DLL dynamically loaded via `load_runtime_module_w()` received `dynamic_load = false` and a non-NULL `CONTEXT*` `lpvReserved` (pretending to be a static load). 2. **Failed runtime `initialise()` poisoned subsequent runtime loads and left failed dependencies registered:** - When `initialise()` threw during `Loader::load_runtime_candidate()`, only `by_name_.erase(module_key(mapped->path))` ran. - If a module threw in `run_tls_callbacks()` before `m.initialised` became `true`, it stayed in `init_order_`, causing every subsequent unrelated runtime `LoadLibrary` to re-run it and fail. - If a dependency's `DllMain` returned `FALSE`, the failed dependency stayed findable in `by_name_`, and the uninitialised parent remained in `init_order_`, so a later unrelated runtime load silently executed the abandoned parent's `DllMain`. - Also, `Loader::initialise()` used range-for iteration over `init_order_`, which invalidates iterators if a `DllMain` recursively loads another bundled module. 3. **Failed `Loader::load()` leaked newly mapped modules, address ranges, and static TLS slots:** - When `map_image()`, `bind_imports()`, `protect_sections()`, or `register_unwind()` threw after `order_.push_back(m)` / `initialize_tls(*m)`, `Loader::load()` only erased `key` from `by_name_`, leaving the failed module in `order_`, `ranges_`, and occupying one of the 16 static TLS slots (exhausting the pool after 16 failed TLS loads). 4. **`/GA` TLS patch publication race & `VirtualSize == 0` section skip:** - `Loader::initialize_tls()` published `g_tls_slot_owners[slot] = &m` and released `ExclusiveTlsLock` *before* running `patch_ga_tls_reads()` and writing `m.tls_ga_slot`, creating a data race where concurrent `DLL_THREAD_ATTACH` events saw `m.tls_ga_slot == kNoTlsIndex` and omitted the thread's `/GA` view (and shadowed `nt` under `/W4` `C4456`). - Both `patch_ga_tls_reads()` and the CLZERO scan in `protect_sections()` computed `min(Misc.VirtualSize, SizeOfRawData)`, skipping executable sections with `Misc.VirtualSize == 0` (which `map_image()` and section protection treat as `SizeOfRawData` per PE/COFF). 5. **Unchecked `VirtualFree(nullptr)` in `forget_ended_thread_id()`:** - `forget_ended_thread_id()` called `VirtualFree(it->ga_view, 0, MEM_RELEASE)` unconditionally even when `it->ga_view == nullptr`. 6. **`Loader::resolve_forwarder()` bypassed `LEONIDA_COMPAT_DIR`:** - `resolve_forwarder()` checked `shims::find()` directly without first checking `resolve_compat()`, allowing a forwarded export to bypass a drop-in compat DLL (or fall through to a shim for a symbol missing from a compat DLL that owns the module). ## Summary of Changes - [`runtime/src/pe_loader.h`](runtime/src/pe_loader.h), [`runtime/src/pe_loader.cpp`](runtime/src/pe_loader.cpp): - Moved `RuntimeLoadScope` into `Loader::load_runtime_candidate()` so both narrow and wide runtime loads set `dynamic_load = true`. - Added `Loader::unmap_module()` and `Loader::rollback_load()` (sharing teardown with `~Loader()`) to atomically roll back `init_order_`, `order_`, `by_name_`, `ranges_`, unwind tables, xmem hooks (keyed per-`Module*`), and static TLS slots on `Loader::load()` failures. - Added index-based `Loader::initialise_all(Module** failed)` and updated `Loader::load_runtime_candidate()` catch cleanup to unlink failed/uninitialised newly added modules from `by_name_` and drop uninitialised entries from `init_order_` while keeping modules whose `DllMain` ran (`initialised == true`) for `~Loader()` process detach. - Moved `/GA` `TlsAlloc()` + `patch_ga_tls_reads()` before `ExclusiveTlsLock` publication in `Loader::initialize_tls()` (also clearing `m.tls_ga_slot` on `install_thread_block()` catch and removing the shadowed `nt` `/W4` warning). - Treated `Misc.VirtualSize == 0` as `SizeOfRawData` in `patch_ga_tls_reads()` and the CLZERO scan in `protect_sections()`. - Guarded `if (it->ga_view)` in `forget_ended_thread_id()`. - Checked `resolve_compat()` before `shims::find()` in `Loader::resolve_forwarder()`. - [`runtime/test/loader_test.cpp`](runtime/test/loader_test.cpp): - Added 6 targeted regression checks covering wide `load_runtime_module_w` `lpvReserved == nullptr`, failed runtime TLS callback recovery, failed runtime dependency `DllMain` cleanup, 20x failed-load TLS slot / `modules()` / `find_address()` rollback, `/GA` patching with `VirtualSize == 0`, and `LEONIDA_COMPAT_DIR` forwarder precedence. ## Verification Environment: Windows 11 Pro 64-bit, MSVC `14.51.36231` (`cl.exe`), LLVM `clang-cl.exe`. GPU: n/a (CPU-only PE loader tests). ### Before fix (`upstream/main` `pe_loader.{h,cpp}` + new regression tests in `loader_test.cpp`) `loader_test.exe` (`cl /std:c++20 /MD /W4 /permissive- /utf-8 /EHsc`): - `101 checks, 6 failed` (exit 1): - `FAIL a wide run-time load's DllMain gets a NULL lpvReserved: lpvReserved was non-NULL` - `FAIL a runtime load that fails in TLS callbacks does not break later runtime loads: the later valid runtime load failed because of the abandoned module` - `FAIL a runtime load whose dependency fails DllMain drops both from lookup and skips abandoned parent: the failed dependency or parent remained findable by name` - `FAIL failed loads after TLS setup roll back modules, address ranges, and static TLS slots: failed loads leaked static TLS slots and exhausted the 16-slot pool` - `FAIL GA TLS patching scans executable sections whose VirtualSize is 0: the gs:[58h] read in the VirtualSize==0 section was not patched` - `FAIL a forwarded export honours LEONIDA_COMPAT_DIR over a shim: forwarded export to compat DLL did not bind to its Answer export` ### After fix MSVC (`cl.exe /std:c++20 /MD /W4 /WX /permissive- /utf-8 /EHsc`, 0 warnings) and `clang-cl` (`/std:c++20 /MD /W4 /permissive- /utf-8 /EHsc`, 0 warnings in `pe_loader.{h,cpp}`): - `loader_test`: **101 checks, 0 failed** (MSVC + `clang-cl`) - `module_names_test tiny_dll.dll`: **73 checks, 0 failures** (MSVC + `clang-cl`) - `loader_tls_test tiny_tls.dll`: **OK (118 checks)** (MSVC + `clang-cl`) - `loader_tls_index0_test runs`: **OK (40 checks)** (MSVC + `clang-cl`) - `loader_tls_index0_test threads`: **OK (6 checks)** (MSVC + `clang-cl`) - `loader_tls_index0_test noreserve`: **OK (3 checks)** (MSVC + `clang-cl`) - `python -I scripts/check_no_game_data.py runtime/src/pe_loader.h runtime/src/pe_loader.cpp runtime/test/loader_test.cpp`: clean (exit 0) AI-assisted: yes --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
Sign in to join this conversation.
No labels
bug
pull-request
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
starred/leonida#1892
No description provided.