diff options
| author | jaybeebabageyus <jaybeebabageyus@users.noreply.github.com> | 2026-11-22 16:49:22 +0100 |
|---|---|---|
| committer | jaybeebabageyus <jaybeebabageyus@users.noreply.github.com> | 2026-11-22 17:51:11 +0100 |
| commit | 81d82bfcc4082a28279403888251adde907541f3 (patch) | |
| tree | 5a5ab4af06022bbaefc97f6e3e0073f7049532bb /runtime/src/pe_loader.cpp | |
| parent | 4eb6155d3ac4f9d3fadb0d095c4ce13e76783615 (diff) | |
runtime: support multiple simultaneous manually mapped static-TLS modules
Diffstat (limited to 'runtime/src/pe_loader.cpp')
| -rw-r--r-- | runtime/src/pe_loader.cpp | 290 |
1 files changed, 216 insertions, 74 deletions
diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index 387051756..113ca23ea 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp | |||
| @@ -4,6 +4,7 @@ | |||
| 4 | #include <intrin.h> | 4 | #include <intrin.h> |
| 5 | 5 | ||
| 6 | #include <algorithm> | 6 | #include <algorithm> |
| 7 | #include <array> | ||
| 7 | #include <atomic> | 8 | #include <atomic> |
| 8 | #include <cstdio> | 9 | #include <cstdio> |
| 9 | #include <cstdlib> | 10 | #include <cstdlib> |
| @@ -73,8 +74,11 @@ IMAGE_TLS_DIRECTORY64* tls_directory(Module& m) { | |||
| 73 | // loader-assigned per-module TLS index and is a different index space from TlsAlloc/TlsGetValue (TlsSlots). Only the OS | 74 | // loader-assigned per-module TLS index and is a different index space from TlsAlloc/TlsGetValue (TlsSlots). Only the OS |
| 74 | // loader can allocate a module index, so the runtime ships a minimal DLL whose only content is a TLS anchor | 75 | // loader can allocate a module index, so the runtime ships a minimal DLL whose only content is a TLS anchor |
| 75 | // (src/tls_host.cpp). Loading it makes the OS reserve an index and give every thread a block for it; the native loader | 76 | // (src/tls_host.cpp). Loading it makes the OS reserve an index and give every thread a block for it; the native loader |
| 76 | // reuses that index for the mapped image. One helper means one mapped TLS module at a time. | 77 | // reuses that index for the mapped image. When more than one manually mapped module uses static TLS at once, the loader |
| 78 | // clones gta6rt_tls_host.dll to a per-process temporary path on demand and loads it, so the OS assigns an independent | ||
| 79 | // module TLS index for each simultaneous module (up to kMaxMappedTlsModules). | ||
| 77 | constexpr DWORD kMaxModuleTlsSlots = 64; | 80 | constexpr DWORD kMaxModuleTlsSlots = 64; |
| 81 | constexpr size_t kMaxMappedTlsModules = 16; | ||
| 78 | void** module_tls_slots() { return reinterpret_cast<void**>(__readgsqword(0x58)); } | 82 | void** module_tls_slots() { return reinterpret_cast<void**>(__readgsqword(0x58)); } |
| 79 | 83 | ||
| 80 | void __cdecl on_host_thread_event(DWORD reason); | 84 | void __cdecl on_host_thread_event(DWORD reason); |
| @@ -84,22 +88,66 @@ struct TlsHostModule { | |||
| 84 | DWORD index = TLS_OUT_OF_INDEXES; | 88 | DWORD index = TLS_OUT_OF_INDEXES; |
| 85 | }; | 89 | }; |
| 86 | 90 | ||
| 87 | TlsHostModule load_tls_host() { | 91 | std::filesystem::path tls_host_base_path() { |
| 88 | TlsHostModule host; | ||
| 89 | // Dynamic buffer loop for paths that exceed MAX_PATH | ||
| 90 | std::wstring exe_path; | 92 | std::wstring exe_path; |
| 91 | DWORD size = MAX_PATH; | 93 | DWORD size = MAX_PATH; |
| 92 | while (true) { | 94 | while (true) { |
| 93 | exe_path.resize(size); | 95 | exe_path.resize(size); |
| 94 | DWORD len = GetModuleFileNameW(nullptr, exe_path.data(), size); | 96 | DWORD len = GetModuleFileNameW(nullptr, exe_path.data(), size); |
| 95 | if (len == 0) return host; | 97 | if (len == 0) return {}; |
| 96 | if (len < size - 1) { | 98 | if (len < size - 1) { |
| 97 | exe_path.resize(len); | 99 | exe_path.resize(len); |
| 98 | break; | 100 | break; |
| 99 | } | 101 | } |
| 100 | size *= 2; | 102 | size *= 2; |
| 101 | } | 103 | } |
| 102 | const std::filesystem::path path = std::filesystem::path(exe_path).parent_path() / L"gta6rt_tls_host.dll"; | 104 | return std::filesystem::path(exe_path).parent_path() / L"gta6rt_tls_host.dll"; |
| 105 | } | ||
| 106 | |||
| 107 | std::filesystem::path tls_host_clone_dir() { | ||
| 108 | wchar_t buf[MAX_PATH]; | ||
| 109 | DWORD n = GetTempPathW(MAX_PATH, buf); | ||
| 110 | if (n > 0 && n < MAX_PATH) return std::filesystem::path(buf); | ||
| 111 | return std::filesystem::temp_directory_path(); | ||
| 112 | } | ||
| 113 | |||
| 114 | struct TlsCloneRecord { | ||
| 115 | HMODULE module = nullptr; | ||
| 116 | std::filesystem::path path; | ||
| 117 | }; | ||
| 118 | |||
| 119 | std::mutex g_tls_alloc_mutex; | ||
| 120 | std::array<TlsHostModule, kMaxMappedTlsModules> g_tls_hosts{}; | ||
| 121 | std::array<std::atomic<Module*>, kMaxMappedTlsModules> g_tls_slot_owners{}; | ||
| 122 | std::array<std::atomic<uint64_t>, kMaxMappedTlsModules> g_tls_slot_generations{}; | ||
| 123 | std::atomic<uint64_t> g_next_tls_generation{1}; | ||
| 124 | std::vector<TlsCloneRecord> g_tls_clones; | ||
| 125 | |||
| 126 | void cleanup_tls_clones_at_exit() { | ||
| 127 | for (const auto& rec : g_tls_clones) { | ||
| 128 | if (rec.module) FreeLibrary(rec.module); | ||
| 129 | if (!rec.path.empty()) DeleteFileW(rec.path.c_str()); | ||
| 130 | } | ||
| 131 | g_tls_clones.clear(); | ||
| 132 | } | ||
| 133 | |||
| 134 | void sweep_stale_tls_clones(const std::filesystem::path& dir) { | ||
| 135 | WIN32_FIND_DATAW fd{}; | ||
| 136 | const std::filesystem::path pattern = dir / L"leonida_tls_host_*.dll"; | ||
| 137 | HANDLE h = FindFirstFileW(pattern.c_str(), &fd); | ||
| 138 | if (h == INVALID_HANDLE_VALUE) return; | ||
| 139 | do { | ||
| 140 | if ((fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) { | ||
| 141 | // Fails harmlessly for clones still mapped in live processes; deletes orphaned ones from exited processes. | ||
| 142 | DeleteFileW((dir / fd.cFileName).c_str()); | ||
| 143 | } | ||
| 144 | } while (FindNextFileW(h, &fd)); | ||
| 145 | FindClose(h); | ||
| 146 | } | ||
| 147 | |||
| 148 | TlsHostModule load_tls_host_image(const std::filesystem::path& path, bool hook_thread_events) { | ||
| 149 | TlsHostModule host; | ||
| 150 | if (path.empty()) return host; | ||
| 103 | // The helper is linked with the static CRT (/MT), so it needs only system DLLs. Restricting the dependency search | 151 | // The helper is linked with the static CRT (/MT), so it needs only system DLLs. Restricting the dependency search |
| 104 | // to System32 keeps a game-supplied vcruntime next to the executable from being picked up. | 152 | // to System32 keeps a game-supplied vcruntime next to the executable from being picked up. |
| 105 | host.module = LoadLibraryExW(path.c_str(), nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); | 153 | host.module = LoadLibraryExW(path.c_str(), nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); |
| @@ -121,31 +169,82 @@ TlsHostModule load_tls_host() { | |||
| 121 | return host; | 169 | return host; |
| 122 | } | 170 | } |
| 123 | host.index = *reinterpret_cast<DWORD*>(tls->AddressOfIndex); | 171 | host.index = *reinterpret_cast<DWORD*>(tls->AddressOfIndex); |
| 124 | // From here on the helper's DllMain reports every thread the process starts or ends (on_host_thread_event). | 172 | if (hook_thread_events) { |
| 125 | using SetThreadEvent = void(__cdecl*)(void(__cdecl*)(DWORD)); | 173 | // Only the primary helper reports thread attach/detach events; on_host_thread_event iterates all active slots. |
| 126 | if (auto set = reinterpret_cast<SetThreadEvent>(GetProcAddress(host.module, "gta6rt_tls_host_set_thread_event"))) | 174 | using SetThreadEvent = void(__cdecl*)(void(__cdecl*)(DWORD)); |
| 127 | set(&on_host_thread_event); | 175 | if (auto set = reinterpret_cast<SetThreadEvent>(GetProcAddress(host.module, "gta6rt_tls_host_set_thread_event"))) |
| 176 | set(&on_host_thread_event); | ||
| 177 | } | ||
| 128 | return host; | 178 | return host; |
| 129 | } | 179 | } |
| 130 | 180 | ||
| 131 | TlsHostModule& tls_host() { | 181 | // Must be called with g_tls_alloc_mutex held and WITHOUT g_tls_lock held (LoadLibraryExW takes the Windows loader lock). |
| 132 | // The helper stays loaded for the process lifetime: unloading it would release the reserved TLS index. Its own | 182 | TlsHostModule ensure_tls_host(size_t slot) { |
| 133 | // per-thread blocks are restored by uninstall_tls_for_thread, so the OS loader can free them normally. | 183 | if (slot >= kMaxMappedTlsModules) return {}; |
| 134 | static TlsHostModule host = load_tls_host(); | 184 | if (g_tls_hosts[slot].index != TLS_OUT_OF_INDEXES) return g_tls_hosts[slot]; |
| 135 | return host; | 185 | |
| 186 | const std::filesystem::path primary = tls_host_base_path(); | ||
| 187 | if (primary.empty()) return {}; | ||
| 188 | |||
| 189 | if (slot == 0) { | ||
| 190 | g_tls_hosts[0] = load_tls_host_image(primary, true); | ||
| 191 | return g_tls_hosts[0]; | ||
| 192 | } | ||
| 193 | |||
| 194 | // Ensure slot 0 is loaded first so thread attach/detach events are hooked. | ||
| 195 | if (g_tls_hosts[0].index == TLS_OUT_OF_INDEXES) { | ||
| 196 | g_tls_hosts[0] = load_tls_host_image(primary, true); | ||
| 197 | if (g_tls_hosts[0].index == TLS_OUT_OF_INDEXES) return {}; | ||
| 198 | } | ||
| 199 | |||
| 200 | // Clone gta6rt_tls_host.dll to a distinct path using CopyFileW (Wine 9 lacks CopyFile2 used by std::filesystem). | ||
| 201 | const std::filesystem::path dir = tls_host_clone_dir(); | ||
| 202 | static bool swept = false; | ||
| 203 | if (!swept) { | ||
| 204 | swept = true; | ||
| 205 | sweep_stale_tls_clones(dir); | ||
| 206 | std::atexit(&cleanup_tls_clones_at_exit); | ||
| 207 | } | ||
| 208 | const std::wstring name = | ||
| 209 | L"leonida_tls_host_" + std::to_wstring(GetCurrentProcessId()) + L"_" + std::to_wstring(slot) + L".dll"; | ||
| 210 | const std::filesystem::path clone_path = dir / name; | ||
| 211 | if (!CopyFileW(primary.c_str(), clone_path.c_str(), FALSE)) return {}; | ||
| 212 | |||
| 213 | // Hold a read-only-shared handle across LoadLibraryExW so another process cannot overwrite the clone in between. | ||
| 214 | HANDLE guard = CreateFileW(clone_path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE, nullptr, | ||
| 215 | OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); | ||
| 216 | TlsHostModule loaded = load_tls_host_image(clone_path, false); | ||
| 217 | if (guard != INVALID_HANDLE_VALUE) CloseHandle(guard); | ||
| 218 | |||
| 219 | if (loaded.index == TLS_OUT_OF_INDEXES) { | ||
| 220 | DeleteFileW(clone_path.c_str()); | ||
| 221 | return {}; | ||
| 222 | } | ||
| 223 | for (size_t i = 0; i < kMaxMappedTlsModules; ++i) { | ||
| 224 | if (i != slot && g_tls_hosts[i].index == loaded.index) { | ||
| 225 | FreeLibrary(loaded.module); | ||
| 226 | DeleteFileW(clone_path.c_str()); | ||
| 227 | return {}; | ||
| 228 | } | ||
| 229 | } | ||
| 230 | g_tls_clones.push_back({loaded.module, clone_path}); | ||
| 231 | g_tls_hosts[slot] = loaded; | ||
| 232 | return g_tls_hosts[slot]; | ||
| 136 | } | 233 | } |
| 137 | 234 | ||
| 138 | std::atomic<Module*> g_tls_slot_owner{nullptr}; | 235 | struct ThreadTlsSlot { |
| 236 | Module* module = nullptr; | ||
| 237 | uint64_t generation = 0; | ||
| 238 | void* saved = nullptr; | ||
| 239 | void* block = nullptr; | ||
| 240 | uint32_t index = kNoTlsIndex; | ||
| 241 | }; | ||
| 139 | 242 | ||
| 140 | // Per-thread installation state. Only one mapped TLS module can own the reserved slot, so one entry per thread is | 243 | // Per-thread installation state for each reserved TLS slot. |
| 141 | // enough; the saved pointer is the helper DLL's own block that the OS loader will free at thread exit. | 244 | thread_local std::array<ThreadTlsSlot, kMaxMappedTlsModules> g_thread_tls_slots{}; |
| 142 | thread_local Module* g_thread_tls_module = nullptr; | ||
| 143 | thread_local void* g_thread_tls_saved = nullptr; | ||
| 144 | thread_local void* g_thread_tls_block = nullptr; | ||
| 145 | thread_local uint32_t g_thread_tls_index = kNoTlsIndex; | ||
| 146 | 245 | ||
| 147 | // Orders the TLS owner's publication, its `initialised` flag and its retirement against the thread events. Shared in | 246 | // Orders the TLS owners' publication, their `initialised` flags and their retirement against the thread events. Shared |
| 148 | // on_host_thread_event, exclusive only for those short writes (no allocation and no call that takes the Windows | 247 | // in on_host_thread_event, exclusive only for those short writes (no allocation and no call that takes the Windows |
| 149 | // loader lock, which the events run under). | 248 | // loader lock, which the events run under). |
| 150 | SRWLOCK g_tls_lock = SRWLOCK_INIT; | 249 | SRWLOCK g_tls_lock = SRWLOCK_INIT; |
| 151 | struct SharedTlsLock { | 250 | struct SharedTlsLock { |
| @@ -163,30 +262,41 @@ struct ExclusiveTlsLock { | |||
| 163 | 262 | ||
| 164 | // Puts the helper DLL's own block back in this thread's slot and frees the copy that replaced it. Uses only this | 263 | // Puts the helper DLL's own block back in this thread's slot and frees the copy that replaced it. Uses only this |
| 165 | // thread's record, so it also works after the module that installed the copy is gone. | 264 | // thread's record, so it also works after the module that installed the copy is gone. |
| 166 | void release_thread_block() { | 265 | void release_thread_slot(size_t slot) { |
| 167 | if (!g_thread_tls_block) return; | 266 | if (slot >= kMaxMappedTlsModules) return; |
| 168 | void** slots = module_tls_slots(); | 267 | ThreadTlsSlot& entry = g_thread_tls_slots[slot]; |
| 169 | if (slots && g_thread_tls_index < kMaxModuleTlsSlots && slots[g_thread_tls_index] == g_thread_tls_block) | 268 | if (!entry.module && !entry.block) return; |
| 170 | slots[g_thread_tls_index] = g_thread_tls_saved; | 269 | if (entry.block) { |
| 171 | VirtualFree(g_thread_tls_block, 0, MEM_RELEASE); | 270 | void** slots = module_tls_slots(); |
| 172 | g_thread_tls_module = nullptr; | 271 | if (slots && entry.index < kMaxModuleTlsSlots && slots[entry.index] == entry.block) |
| 173 | g_thread_tls_saved = nullptr; | 272 | slots[entry.index] = entry.saved; |
| 174 | g_thread_tls_block = nullptr; | 273 | VirtualFree(entry.block, 0, MEM_RELEASE); |
| 175 | g_thread_tls_index = kNoTlsIndex; | 274 | } |
| 275 | entry = ThreadTlsSlot{}; | ||
| 176 | } | 276 | } |
| 177 | 277 | ||
| 178 | void install_thread_block(Module& m) { | 278 | void install_thread_block(Module& m) { |
| 179 | if (m.tls_index == kNoTlsIndex) return; | 279 | if (m.tls_slot >= kMaxMappedTlsModules) return; |
| 180 | if (g_thread_tls_module == &m) return; | 280 | const size_t slot = m.tls_slot; |
| 181 | if (g_thread_tls_module) { | 281 | ThreadTlsSlot& entry = g_thread_tls_slots[slot]; |
| 182 | // A copy left by a module whose Loader is gone is released; a live module's is a conflict. | 282 | if (entry.module == &m && entry.generation == m.tls_generation) return; |
| 183 | if (g_thread_tls_module == g_tls_slot_owner.load()) | 283 | if (entry.module) { |
| 184 | throw std::runtime_error("another manually mapped module's TLS is already installed in this thread"); | 284 | // A copy left by a module whose Loader is gone (or from an earlier generation) is released; a live owner's is a conflict. |
| 185 | release_thread_block(); | 285 | if (entry.module == g_tls_slot_owners[slot].load() && |
| 286 | entry.generation == g_tls_slot_generations[slot].load()) { | ||
| 287 | throw std::runtime_error("another manually mapped module's TLS is already installed in this thread slot"); | ||
| 288 | } | ||
| 289 | release_thread_slot(slot); | ||
| 186 | } | 290 | } |
| 187 | 291 | ||
| 188 | const uint64_t total = static_cast<uint64_t>(m.tls_raw_size) + m.tls_zero_fill; | 292 | const uint64_t total = static_cast<uint64_t>(m.tls_raw_size) + m.tls_zero_fill; |
| 189 | if (!total) return; | 293 | if (!total) { |
| 294 | // Callback-only TLS module (no data block): still record attachment in this slot so DLL_THREAD_DETACH runs. | ||
| 295 | entry.module = &m; | ||
| 296 | entry.generation = m.tls_generation; | ||
| 297 | return; | ||
| 298 | } | ||
| 299 | if (m.tls_index == kNoTlsIndex) return; | ||
| 190 | void** slots = module_tls_slots(); | 300 | void** slots = module_tls_slots(); |
| 191 | if (!slots || m.tls_index >= kMaxModuleTlsSlots) | 301 | if (!slots || m.tls_index >= kMaxModuleTlsSlots) |
| 192 | throw std::runtime_error(m.name + ": cannot install TLS in this thread"); | 302 | throw std::runtime_error(m.name + ": cannot install TLS in this thread"); |
| @@ -199,19 +309,23 @@ void install_thread_block(Module& m) { | |||
| 199 | 309 | ||
| 200 | void* saved = slots[m.tls_index]; | 310 | void* saved = slots[m.tls_index]; |
| 201 | slots[m.tls_index] = block; | 311 | slots[m.tls_index] = block; |
| 202 | g_thread_tls_module = &m; | 312 | entry.module = &m; |
| 203 | g_thread_tls_saved = saved; | 313 | entry.generation = m.tls_generation; |
| 204 | g_thread_tls_block = block; | 314 | entry.saved = saved; |
| 205 | g_thread_tls_index = m.tls_index; | 315 | entry.block = block; |
| 316 | entry.index = m.tls_index; | ||
| 206 | } | 317 | } |
| 207 | 318 | ||
| 208 | void uninstall_thread_block(Module& m) { | 319 | void uninstall_thread_block(Module& m) { |
| 209 | if (g_thread_tls_module != &m) return; | 320 | if (m.tls_slot >= kMaxMappedTlsModules) return; |
| 210 | if (m.tls_block == g_thread_tls_block) { | 321 | const size_t slot = m.tls_slot; |
| 322 | ThreadTlsSlot& entry = g_thread_tls_slots[slot]; | ||
| 323 | if (entry.module != &m || entry.generation != m.tls_generation) return; | ||
| 324 | if (m.tls_block == entry.block) { | ||
| 211 | m.tls_block = nullptr; | 325 | m.tls_block = nullptr; |
| 212 | m.tls_saved_block = nullptr; | 326 | m.tls_saved_block = nullptr; |
| 213 | } | 327 | } |
| 214 | release_thread_block(); | 328 | release_thread_slot(slot); |
| 215 | } | 329 | } |
| 216 | 330 | ||
| 217 | void run_callbacks(Module& m, uint32_t reason) { | 331 | void run_callbacks(Module& m, uint32_t reason) { |
| @@ -231,24 +345,29 @@ void run_callbacks(Module& m, uint32_t reason) { | |||
| 231 | } | 345 | } |
| 232 | 346 | ||
| 233 | // Runs in gta6rt_tls_host.dll's DllMain for each thread the process starts or ends once the helper is loaded, under | 347 | // Runs in gta6rt_tls_host.dll's DllMain for each thread the process starts or ends once the helper is loaded, under |
| 234 | // the Windows loader lock, on that thread. A new thread gets its own copy of the TLS owner's template; an ending one | 348 | // the Windows loader lock, on that thread. A new thread gets its own copy of each active TLS owner's template; an |
| 235 | // gives the helper's block back before the Windows loader frees it. TLS callbacks get the thread events only after | 349 | // ending one gives each helper's block back before the Windows loader frees it. TLS callbacks get the thread events |
| 236 | // the module's DLL_PROCESS_ATTACH (initialise()), as the Windows loader orders them. Threads that existed before the | 350 | // only after the module's DLL_PROCESS_ATTACH (initialise()), as the Windows loader orders them. |
| 237 | // module was loaded get nothing: install_tls_for_thread is still the way to cover those. | ||
| 238 | void __cdecl on_host_thread_event(DWORD reason) { | 351 | void __cdecl on_host_thread_event(DWORD reason) { |
| 239 | SharedTlsLock lock; | 352 | SharedTlsLock lock; |
| 240 | Module* m = g_tls_slot_owner.load(); | ||
| 241 | try { | 353 | try { |
| 242 | if (reason == DLL_THREAD_ATTACH) { | 354 | if (reason == DLL_THREAD_ATTACH) { |
| 243 | if (!m) return; | 355 | for (size_t slot = 0; slot < kMaxMappedTlsModules; ++slot) { |
| 244 | install_thread_block(*m); | 356 | Module* m = g_tls_slot_owners[slot].load(); |
| 245 | if (m->initialised) run_callbacks(*m, DLL_THREAD_ATTACH); | 357 | if (!m) continue; |
| 358 | install_thread_block(*m); | ||
| 359 | if (m->initialised) run_callbacks(*m, DLL_THREAD_ATTACH); | ||
| 360 | } | ||
| 246 | } else if (reason == DLL_THREAD_DETACH) { | 361 | } else if (reason == DLL_THREAD_DETACH) { |
| 247 | if (m && g_thread_tls_module == m) { | 362 | for (size_t i = kMaxMappedTlsModules; i-- > 0;) { |
| 248 | if (m->initialised) run_callbacks(*m, DLL_THREAD_DETACH); | 363 | Module* m = g_tls_slot_owners[i].load(); |
| 249 | uninstall_thread_block(*m); | 364 | if (m && g_thread_tls_slots[i].module == m && |
| 250 | } else { | 365 | g_thread_tls_slots[i].generation == m->tls_generation) { |
| 251 | release_thread_block(); // installed by a module whose Loader is gone (or nothing to do) | 366 | if (m->initialised) run_callbacks(*m, DLL_THREAD_DETACH); |
| 367 | uninstall_thread_block(*m); | ||
| 368 | } else { | ||
| 369 | release_thread_slot(i); // installed by a module whose Loader is gone (or nothing to do) | ||
| 370 | } | ||
| 252 | } | 371 | } |
| 253 | } | 372 | } |
| 254 | } catch (const std::exception& e) { | 373 | } catch (const std::exception& e) { |
| @@ -375,13 +494,14 @@ Loader::~Loader() { | |||
| 375 | shims::remove_module_lookup(this); | 494 | shims::remove_module_lookup(this); |
| 376 | for (auto* m : order_) { | 495 | for (auto* m : order_) { |
| 377 | // TLS state must go away before the image and its TLS block are unmapped. | 496 | // TLS state must go away before the image and its TLS block are unmapped. |
| 378 | if (m->tls_index != kNoTlsIndex) { | 497 | if (m->tls_index != kNoTlsIndex && m->tls_slot < kMaxMappedTlsModules) { |
| 379 | // Retired first, under the lock: no thread event installs it or runs its callbacks after this, and a | 498 | // Retired first, under the lock: no thread event installs it or runs its callbacks after this, and a |
| 380 | // thread that still holds a copy frees it when it ends (on_host_thread_event). | 499 | // thread that still holds a copy frees it when it ends (on_host_thread_event). |
| 381 | { | 500 | { |
| 382 | ExclusiveTlsLock lock; | 501 | ExclusiveTlsLock lock; |
| 383 | Module* owner = m; | 502 | Module* owner = m; |
| 384 | g_tls_slot_owner.compare_exchange_strong(owner, nullptr); | 503 | if (g_tls_slot_owners[m->tls_slot].compare_exchange_strong(owner, nullptr)) |
| 504 | g_tls_slot_generations[m->tls_slot].store(0); | ||
| 385 | } | 505 | } |
| 386 | uninstall_tls_for_thread(*m); | 506 | uninstall_tls_for_thread(*m); |
| 387 | } | 507 | } |
| @@ -604,19 +724,38 @@ void Loader::initialize_tls(Module& m) { | |||
| 604 | require_range(m.name, index_rva, sizeof(uint32_t), m.size, "the TLS index"); | 724 | require_range(m.name, index_rva, sizeof(uint32_t), m.size, "the TLS index"); |
| 605 | } | 725 | } |
| 606 | 726 | ||
| 607 | DWORD index = tls_host().index; | ||
| 608 | if (index == TLS_OUT_OF_INDEXES) | ||
| 609 | throw std::runtime_error(m.name + ": gta6rt_tls_host.dll is missing or has no module TLS index"); | ||
| 610 | if (index >= kMaxModuleTlsSlots) throw std::runtime_error(m.name + ": reserved TLS index is out of range"); | ||
| 611 | if (!module_tls_slots()) throw std::runtime_error(m.name + ": this thread has no TLS array"); | 727 | if (!module_tls_slots()) throw std::runtime_error(m.name + ": this thread has no TLS array"); |
| 612 | 728 | ||
| 729 | size_t slot = kMaxMappedTlsModules; | ||
| 730 | DWORD index = TLS_OUT_OF_INDEXES; | ||
| 613 | { | 731 | { |
| 732 | std::lock_guard alloc_lock(g_tls_alloc_mutex); | ||
| 733 | for (size_t i = 0; i < kMaxMappedTlsModules; ++i) { | ||
| 734 | if (g_tls_slot_owners[i].load() == nullptr) { | ||
| 735 | slot = i; | ||
| 736 | break; | ||
| 737 | } | ||
| 738 | } | ||
| 739 | if (slot >= kMaxMappedTlsModules) | ||
| 740 | throw std::runtime_error(m.name + ": all " + std::to_string(kMaxMappedTlsModules) + | ||
| 741 | " manually mapped static TLS slots are in use"); | ||
| 742 | |||
| 743 | // Load/clone gta6rt_tls_host.dll OUTSIDE ExclusiveTlsLock so LoadLibraryExW cannot deadlock with | ||
| 744 | // on_host_thread_event (which runs under the Windows loader lock and takes SharedTlsLock). | ||
| 745 | index = ensure_tls_host(slot).index; | ||
| 746 | if (index == TLS_OUT_OF_INDEXES) | ||
| 747 | throw std::runtime_error(m.name + ": gta6rt_tls_host.dll is missing or has no module TLS index"); | ||
| 748 | if (index >= kMaxModuleTlsSlots) throw std::runtime_error(m.name + ": reserved TLS index is out of range"); | ||
| 749 | |||
| 614 | // The fields are complete before a thread event can see the owner. | 750 | // The fields are complete before a thread event can see the owner. |
| 615 | ExclusiveTlsLock lock; | 751 | ExclusiveTlsLock lock; |
| 616 | Module* expected = nullptr; | 752 | Module* expected = nullptr; |
| 617 | if (!g_tls_slot_owner.compare_exchange_strong(expected, &m)) | 753 | if (!g_tls_slot_owners[slot].compare_exchange_strong(expected, &m)) |
| 618 | throw std::runtime_error(m.name + ": only one manually mapped module may use static TLS at a time"); | 754 | throw std::runtime_error(m.name + ": static TLS slot was claimed concurrently"); |
| 619 | 755 | ||
| 756 | m.tls_slot = static_cast<uint32_t>(slot); | ||
| 757 | m.tls_generation = g_next_tls_generation.fetch_add(1, std::memory_order_relaxed); | ||
| 758 | g_tls_slot_generations[slot].store(m.tls_generation); | ||
| 620 | m.tls_index = index; | 759 | m.tls_index = index; |
| 621 | m.tls_template = raw ? m.base + raw_rva : nullptr; | 760 | m.tls_template = raw ? m.base + raw_rva : nullptr; |
| 622 | m.tls_raw_size = static_cast<uint32_t>(raw); | 761 | m.tls_raw_size = static_cast<uint32_t>(raw); |
| @@ -631,13 +770,16 @@ void Loader::initialize_tls(Module& m) { | |||
| 631 | } catch (...) { | 770 | } catch (...) { |
| 632 | ExclusiveTlsLock lock; | 771 | ExclusiveTlsLock lock; |
| 633 | m.tls_index = kNoTlsIndex; | 772 | m.tls_index = kNoTlsIndex; |
| 634 | g_tls_slot_owner = nullptr; | 773 | m.tls_slot = kNoTlsIndex; |
| 774 | m.tls_generation = 0; | ||
| 775 | g_tls_slot_generations[slot].store(0); | ||
| 776 | g_tls_slot_owners[slot].store(nullptr); | ||
| 635 | throw; | 777 | throw; |
| 636 | } | 778 | } |
| 637 | // The loading thread's copy is the one the Module records (and ~Loader frees on that thread). | 779 | // The loading thread's copy is the one the Module records (and ~Loader frees on that thread). |
| 638 | if (g_thread_tls_module == &m) { | 780 | if (g_thread_tls_slots[slot].module == &m && g_thread_tls_slots[slot].generation == m.tls_generation) { |
| 639 | m.tls_block = g_thread_tls_block; | 781 | m.tls_block = g_thread_tls_slots[slot].block; |
| 640 | m.tls_saved_block = g_thread_tls_saved; | 782 | m.tls_saved_block = g_thread_tls_slots[slot].saved; |
| 641 | } | 783 | } |
| 642 | } | 784 | } |
| 643 | 785 | ||