Skip to content

Runtime: a mapped DLL's DllMain gets DLL_THREAD_ATTACH/DETACH (RT-170) - #2669

Closed
Sc4ros wants to merge 1 commit into
ProjectLeonida:mainfrom
Sc4ros:rt-dllmain-thread-events
Closed

Sc4ros wants to merge 1 commit into
ProjectLeonida:mainfrom
Sc4ros:rt-dllmain-thread-events

Conversation

@Sc4ros

@Sc4ros Sc4ros commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

#2070 and #2383 have landed, so this is now one commit on main (7ee8da52, rebased 2026-11-23). It was a draft stacked on both.

Claim: #2300 (comment) (RT-170)

AI-assisted (Claude), tested by running the code below on Windows; see "Tested".

Problem (RT-170)

A mapped DLL's DllMain never gets DLL_THREAD_ATTACH / DLL_THREAD_DETACH. A DLL without a TLS directory hears nothing about a thread at all, and a module with one only gets its TLS callbacks.

Cause

on_host_thread_event() only walks the TLS slot owners and only calls run_callbacks(). There is no list of the other initialised modules, and DllMain is never called from it. The thread-event hook (the primary gta6rt_tls_host.dll) is also only loaded when some module has a TLS directory, so a DLL without one has no hook to wait on.

Fix

  • g_event_modules: the initialised modules, in initialisation order, across all live Loaders (written under the existing TLS lock in Loader::set_initialised, read under its shared side in on_host_thread_event). A module whose DllMain(DLL_PROCESS_ATTACH) failed is not in it.
  • on_host_thread_event: on attach, every TLS owner first gets its copy (so one module's callback or DllMain can use another's thread_local data), then each module gets its TLS callbacks followed by its DllMain, in initialisation order. On detach the same in reverse order, then the TLS copies are given back as before. Each module is isolated: one that throws does not stop the others.
  • A thread is detached only from the modules whose attach it saw (a small per-thread record of plain data), which keeps runtime: support multiple simultaneous manually mapped static-TLS modules #2070's rule that a module that reuses a slot or address after its Loader is gone never gets a detach for a thread it did not see attach (its test_orphan_slot_generation_reuse).
  • DisableThreadLibraryCalls (Runtime: DisableThreadLibraryCalls from a mapped DllMain succeeds #2383) is recorded: BundledModuleOps gets an optional disable_thread_calls entry, Loader::disable_thread_calls sets Module::thread_calls_disabled, and the shim in library_loader.cpp calls it. That module's DllMain then gets no thread events.
  • initialise() makes sure the hook is loaded for any module that has a DllMain or a TLS directory. If gta6rt_tls_host.dll is missing there are no thread events for a DLL without TLS (a TLS module already fails to load without it).

What the Windows loader does (measured, so the loader copies it)

test/thread_events_test.cpp loads four CRT-free fixture DLLs (test/fixtures/thread_events.cpp, one source, four defines) with LoadLibraryW and with rt::Loader, runs three threads one after another, and requires the two event logs to be identical. Windows 11 build 26300 sends, per thread (C = TLS callback, D = DllMain, A = attach, T = detach):

fixture Windows sends notes
plain (DllMain only) DA DT
tls (TLS callback + DllMain) CA DA CT DT callback first on both
disabled (DisableThreadLibraryCalls, no TLS) nothing
disabled_tls (same call, TLS directory present) CA DA CT DT Windows returns TRUE but ignores the call for a module with a TLS directory; the loader does the same

One thing the fixtures taught me, because the first run disagreed with my guess: Windows ignores the TLS directory of a DLL loaded at run time that has no import table (the TLS callbacks never ran for a fixture with no imports). Every fixture therefore calls SetLastError, and the test says so.

Tested

Windows 11 (build 26300), MSVC 19.44 (VS 2022 Build Tools, Visual Studio generator, Release), AMD Radeon RX 9060 XT, driver 32.0.32029.2010.

Limits (documented in runtime/README.md)

No game files, and the fixtures contain no game data.

@rafaelpssz

Copy link
Copy Markdown
Collaborator

Tested 9ffc8d4 on Windows 11 (clang-cl + xwin, RelWithDebInfo, no MSVC), CPU only, no game files.

  • ctest -R "loader_tls|dll_thread_calls|thread_events": 3/3 pass.

  • Red check: I put back runtime/src/pe_loader.cpp and pe_loader.h from the parent 61c7b36e, kept everything else at the head, and rebuilt. thread_events then fails all three of its cases:

    • plain (no TLS directory)
    • tls (TLS callback + DllMain)
    • disabled_tls (DisableThreadLibraryCalls, with TLS)

    Each fails with "the mapped DLL gets exactly the same events, in the same order", so the new test exercises the new thread-event path. dll_thread_calls also fails in that mix. That is expected, since this commit's library_loader.cpp changes go with the new loader; it is not a separate regression.

@Sc4ros

Sc4ros commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

pushed 7ee8da5: rebased on main d974c88 now that #2070 and #2383 have landed (one commit left). Marked ready. The description's "Tested" section has the conflict resolution and the new results: full ctest 169/170 on Windows 11 / RX 9060 XT, and the only failure is the API dump layer crash (TEST-843), which is unrelated. It also combines cleanly with open #3671.

AI-assisted (Claude Code).

@illusionart453-max illusionart453-max 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 Windows CPU recheck of 7ee8da52: pass. Windows 11 build 26200, MSVC 19.44, RelWithDebInfo; no GPU or game files used.

  • Submitted thread_events, loader_tls, dll_thread_calls, loader and pe_loader: 5/5 pass. The native/mapped logs agree for all four fixture variants.
  • Added a temporary cross-module probe: load the plain, TLS and disabled-with-TLS fixtures together in all six permutations, then record one thread's notifications into a shared host buffer. All six combined logs match native LoadLibraryW byte for byte. This also confirms module ordering, in addition to the submitted test's per-module callback-before-DllMain checks. The expanded fixture reports 21 checks, zero failures.
  • Negative control: clean-built with the five changed runtime loader/registry sources and headers restored from parent d974c88a, retaining the new test/CMake fixture. It reports nine failures: the three submitted DllMain parity cases and all six cross-module comparisons. Native controls still pass; the mapped path emits TLS callbacks but omits DllMain notifications.
  • Restored the head runtime and clean-built: expanded probe passes again. Removed the local probe, rebuilt the submitted fixture and bounds target, then thread_events and pe_loader_bounds pass 2/2. Checkout clean.

The documented pre-existing-thread, missing-helper and 64-module limits remain outside this check. This is an independent review, no competing implementation PR. AI-assisted (Codex).

Optional reusable cross-module review probe

Patch against 7ee8da52. Build thread_events_test and run its existing CTest entry. This only adds a synthetic callback sink to the fixtures and six native-versus-mapped order comparisons; it changes no loader code.

diff --git a/runtime/test/fixtures/thread_events.cpp b/runtime/test/fixtures/thread_events.cpp
index 264d37eb..006b8b9f 100644
--- a/runtime/test/fixtures/thread_events.cpp
+++ b/runtime/test/fixtures/thread_events.cpp
@@ -18,6 +18,8 @@ namespace {
 
 char g_log[512];
 volatile LONG g_length = 0;
+using SinkFn = void(__cdecl*)(char, DWORD);
+SinkFn g_sink = nullptr;
 
 void record(char who, DWORD reason) {
     const char what = reason == DLL_THREAD_ATTACH ? 'A' : reason == DLL_THREAD_DETACH ? 'T' : 0;
@@ -28,6 +30,7 @@ void record(char who, DWORD reason) {
         g_log[at] = who;
         g_log[at + 1] = what;
     }
+    if (g_sink) g_sink(who, reason);
 }
 
 #if defined(THREAD_EVENTS_TLS) || defined(THREAD_EVENTS_DISABLE_TLS)
@@ -77,3 +80,5 @@ extern "C" __declspec(dllexport) int __cdecl thread_events_log(char* out, int ca
 #pragma optimize("", on)
 
 extern "C" __declspec(dllexport) void __cdecl thread_events_reset() { g_length = 0; }
+
+extern "C" __declspec(dllexport) void __cdecl thread_events_set_sink(SinkFn sink) { g_sink = sink; }
diff --git a/runtime/test/thread_events_test.cpp b/runtime/test/thread_events_test.cpp
index f9ba92fe..1dbda7c4 100644
--- a/runtime/test/thread_events_test.cpp
+++ b/runtime/test/thread_events_test.cpp
@@ -16,12 +16,15 @@
 // Needs gta6rt_tls_host.dll next to this EXE (the loader's thread-event hook). No game files.
 #include <windows.h>
 
+#include <algorithm>
+#include <array>
 #include <cstdio>
 #include <filesystem>
 #include <memory>
 #include <stdexcept>
 #include <string>
 #include <thread>
+#include <vector>
 
 #include "pe_loader.h"
 
@@ -81,6 +84,60 @@ std::string repeat(const std::string& s, int n) {
     return out;
 }
 
+char combined[600]{};
+LONG combined_length = 0;
+void combined_event(char module, char who, DWORD reason) {
+    if (reason != DLL_THREAD_ATTACH && reason != DLL_THREAD_DETACH) return;
+    const LONG at = InterlockedExchangeAdd(&combined_length, 3);
+    if (at + 3 >= static_cast<LONG>(sizeof combined)) return;
+    combined[at] = module;
+    combined[at + 1] = who;
+    combined[at + 2] = reason == DLL_THREAD_ATTACH ? 'A' : 'T';
+}
+void sink_a(char who, DWORD reason) { combined_event('A', who, reason); }
+void sink_b(char who, DWORD reason) { combined_event('B', who, reason); }
+void sink_c(char who, DWORD reason) { combined_event('C', who, reason); }
+
+std::string multi_log(const std::array<const char*, 3>& paths, bool mapped) {
+    using SinkFn = void(__cdecl*)(char, DWORD);
+    using SetSinkFn = void(__cdecl*)(SinkFn);
+    const SinkFn sinks[] = {sink_a, sink_b, sink_c};
+    std::unique_ptr<rt::Loader> loader;
+    std::vector<HMODULE> native;
+    std::vector<SetSinkFn> setters;
+    if (mapped) {
+        loader = std::make_unique<rt::Loader>(std::filesystem::path(paths[0]).parent_path());
+        for (const char* path : paths) {
+            auto& m = loader->load(path);
+            setters.push_back(reinterpret_cast<SetSinkFn>(m.exports.at("thread_events_set_sink")));
+        }
+        loader->initialise();
+    } else {
+        for (const char* path : paths) {
+            HMODULE h = LoadLibraryW(std::filesystem::path(path).c_str());
+            if (!h) throw std::runtime_error("multi LoadLibrary failed");
+            native.push_back(h);
+            setters.push_back(reinterpret_cast<SetSinkFn>(GetProcAddress(h, "thread_events_set_sink")));
+        }
+    }
+    for (size_t i = 0; i < setters.size(); ++i) setters[i](sinks[i]);
+    combined_length = 0;
+    for (auto& byte : combined) byte = 0;
+    run_threads(1);
+    const std::string result(combined);
+    for (auto setter : setters) setter(nullptr);
+    for (auto it = native.rbegin(); it != native.rend(); ++it) FreeLibrary(*it);
+    return result;
+}
+
+void multi_variant(const std::array<const char*, 3>& paths) {
+    const std::string native = multi_log(paths, false);
+    const std::string mapped = multi_log(paths, true);
+    std::printf("multi: windows='%s' mapped='%s'\n", native.c_str(), mapped.c_str());
+    check(!native.empty(), "multi-module native control produces events");
+    check(mapped == native, "multi-module order matches native Windows");
+}
+
 void variant(const std::filesystem::path& dll, const char* name, const std::string& expected) {
     std::string windows, mapped;
     try {
@@ -111,6 +168,12 @@ int main(int argc, char** argv) {
         variant(argv[3], "disabled (DisableThreadLibraryCalls, no TLS)", "");
         variant(argv[4], "disabled_tls (DisableThreadLibraryCalls, with TLS)", repeat("CADACTDT", 3));
 
+        const char* paths[] = {argv[1], argv[2], argv[4]};
+        std::array<int, 3> order{0, 1, 2};
+        do {
+            multi_variant({paths[order[0]], paths[order[1]], paths[order[2]]});
+        } while (std::next_permutation(order.begin(), order.end()));
+
         // After the Loader is gone, nothing of the unmapped image may be called by a later thread.
         {
             rt::Loader loader(std::filesystem::path(argv[1]).parent_path());

@DenRakEiw

Copy link
Copy Markdown
Contributor

Tested 7ee8da52 on Windows 11 (MSVC 19.44 / Ninja / Windows SDK 10.0.26100, no game files): pass.

  • Trial-merged onto origin/main (3faac557): clean; thread_events_test and all 4 fixture DLLs built cleanly.
  • ctest -R thread_events -V: 1/1 passed (thread_events_test: OK (0 failures), 0.10s; plain, tls, disabled, and disabled_tls event sequences all matched Windows loader).

AI-assisted (Gemini 4 Neon).

@amarovndres

Copy link
Copy Markdown

Tested 7ee8da52 on Windows 11 Pro (build 26200), with the loader tests built from this head with MSVC (VS 2022 Build Tools, Windows SDK 10.0.26100): pass.

  • ctest -R '^(thread_events|loader|loader_tls|pe_loader)': 5/5 passed (loader, loader_tls, pe_loader, pe_loader_bounds, and the new thread_events). main 3faac557 built the same way: the four existing ones pass, so nothing regresses in the TLS path this PR reorganises.
  • thread_events_test: OK (0 failures). In every configuration the mapped DLL gets the same event string as the Windows loader over three threads: TLS callback + DllMain CADACTDTCADACTDTCADACTDT, DisableThreadLibraryCalls without TLS '', and with TLS the full sequence again. Threads after the Loader is destroyed run fine.

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

on_host_thread_event only ran the TLS callbacks of modules that own a TLS slot,
so a DLL without a TLS directory never heard about a thread, and no module's
DllMain did. It now announces every thread to every initialised module, in
initialisation order (reverse for detach): the module's TLS callbacks, then
its DllMain, after the thread's TLS copies are in place. A thread is detached
only from the modules whose attach it saw.

- DisableThreadLibraryCalls from a mapped DllMain (ItsNotRexed#2383) is recorded through a
  new optional BundledModuleOps entry and switches the DllMain events off,
  except for a module with a TLS directory: Windows answers TRUE there and keeps
  sending them, and so does the loader.
- A module that has a DllMain or a TLS directory makes sure the thread-event
  hook (the primary gta6rt_tls_host.dll) is loaded when it is initialised.
- thread_events_test loads four CRT-free fixture DLLs with both the Windows
  loader and rt::Loader and requires identical event logs, so the order is
  measured rather than assumed.

Depends on ItsNotRexed#2070 (the thread-event slot code) and ItsNotRexed#2383.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@Sc4ros
Sc4ros force-pushed the rt-dllmain-thread-events branch from 7ee8da5 to c8ee6ac Compare November 23, 2026 18:54
@Sc4ros

Sc4ros commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

pushed c8ee6ac: rebased on main dde82f27. #3671 is on main now, so the README paragraph and the thread-detach path were merged with it: modules that saw the attach get DLL_THREAD_DETACH first, then the blocks of threads that existed before load() are released, then the per-slot release. No other change.

Windows 11 / RX 9060 XT, MSVC Release: full ctest 256/263 passed, thread_events included. The 7 failures (vk_queue_query_sync, d3d12_vulkan_device, d3d12_texture_tiles, d3d12_indirect_dispatch_count, d3d12_depth_resolve, d3d12_pipeline_library_host, d3d12_indirect_rt) fail the same way on main dde82f27 on this machine.

AI-assisted (Claude Code).

@YordiLorenzo

Copy link
Copy Markdown

Tested c8ee6ac on RTX 4070 SUPER, NVIDIA 621.01, Windows 11 Pro: pass

  • cmake --build RelWithDebInfo, MSVC + Ninja: builds, no errors
  • ctest -R "thread_events|loader|dll_thread_calls|run_tiny_game_tls": 7 passed
  • Negative control, the new test with the five loader files from its base dde82f2: fails 3 of 9 checks, the event order for plain, tls and disabled_tls DLLs

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.

7 participants