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:34:35 +0100 |
| commit | a28493ba8f7ab85749fc2c4bdefa8091bf9085cc (patch) | |
| tree | 0c4472516e0df9c052308fd2e0c00b4f18381b68 /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 | 275 |
1 files changed, 202 insertions, 73 deletions
diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index 387051756..6d1248057 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,64 @@ 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::vector<TlsCloneRecord> g_tls_clones; | ||
| 123 | |||
| 124 | void cleanup_tls_clones_at_exit() { | ||
| 125 | for (const auto& rec : g_tls_clones) { | ||
| 126 | if (rec.module) FreeLibrary(rec.module); | ||
| 127 | if (!rec.path.empty()) DeleteFileW(rec.path.c_str()); | ||
| 128 | } | ||
| 129 | g_tls_clones.clear(); | ||
| 130 | } | ||
| 131 | |||
| 132 | void sweep_stale_tls_clones(const std::filesystem::path& dir) { | ||
| 133 | WIN32_FIND_DATAW fd{}; | ||
| 134 | const std::filesystem::path pattern = dir / L"leonida_tls_host_*.dll"; | ||
| 135 | HANDLE h = FindFirstFileW(pattern.c_str(), &fd); | ||
| 136 | if (h == INVALID_HANDLE_VALUE) return; | ||
| 137 | do { | ||
| 138 | if ((fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) { | ||
| 139 | // Fails harmlessly for clones still mapped in live processes; deletes orphaned ones from exited processes. | ||
| 140 | DeleteFileW((dir / fd.cFileName).c_str()); | ||
| 141 | } | ||
| 142 | } while (FindNextFileW(h, &fd)); | ||
| 143 | FindClose(h); | ||
| 144 | } | ||
| 145 | |||
| 146 | TlsHostModule load_tls_host_image(const std::filesystem::path& path, bool hook_thread_events) { | ||
| 147 | TlsHostModule host; | ||
| 148 | 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 | 149 | // 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. | 150 | // 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); | 151 | host.module = LoadLibraryExW(path.c_str(), nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); |
| @@ -121,31 +167,81 @@ TlsHostModule load_tls_host() { | |||
| 121 | return host; | 167 | return host; |
| 122 | } | 168 | } |
| 123 | host.index = *reinterpret_cast<DWORD*>(tls->AddressOfIndex); | 169 | 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). | 170 | if (hook_thread_events) { |
| 125 | using SetThreadEvent = void(__cdecl*)(void(__cdecl*)(DWORD)); | 171 | // 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"))) | 172 | using SetThreadEvent = void(__cdecl*)(void(__cdecl*)(DWORD)); |
| 127 | set(&on_host_thread_event); | 173 | if (auto set = reinterpret_cast<SetThreadEvent>(GetProcAddress(host.module, "gta6rt_tls_host_set_thread_event"))) |
| 174 | set(&on_host_thread_event); | ||
| 175 | } | ||
| 128 | return host; | 176 | return host; |
| 129 | } | 177 | } |
| 130 | 178 | ||
| 131 | TlsHostModule& tls_host() { | 179 | // 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 | 180 | 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. | 181 | if (slot >= kMaxMappedTlsModules) return {}; |
| 134 | static TlsHostModule host = load_tls_host(); | 182 | if (g_tls_hosts[slot].index != TLS_OUT_OF_INDEXES) return g_tls_hosts[slot]; |
| 135 | return host; | 183 | |
| 184 | const std::filesystem::path primary = tls_host_base_path(); | ||
| 185 | if (primary.empty()) return {}; | ||
| 186 | |||
| 187 | if (slot == 0) { | ||
| 188 | g_tls_hosts[0] = load_tls_host_image(primary, true); | ||
| 189 | return g_tls_hosts[0]; | ||
| 190 | } | ||
| 191 | |||
| 192 | // Ensure slot 0 is loaded first so thread attach/detach events are hooked. | ||
| 193 | if (g_tls_hosts[0].index == TLS_OUT_OF_INDEXES) { | ||
| 194 | g_tls_hosts[0] = load_tls_host_image(primary, true); | ||
| 195 | if (g_tls_hosts[0].index == TLS_OUT_OF_INDEXES) return {}; | ||
| 196 | } | ||
| 197 | |||
| 198 | // Clone gta6rt_tls_host.dll to a distinct path using CopyFileW (Wine 9 lacks CopyFile2 used by std::filesystem). | ||
| 199 | const std::filesystem::path dir = tls_host_clone_dir(); | ||
| 200 | static bool swept = false; | ||
| 201 | if (!swept) { | ||
| 202 | swept = true; | ||
| 203 | sweep_stale_tls_clones(dir); | ||
| 204 | std::atexit(&cleanup_tls_clones_at_exit); | ||
| 205 | } | ||
| 206 | const std::wstring name = | ||
| 207 | L"leonida_tls_host_" + std::to_wstring(GetCurrentProcessId()) + L"_" + std::to_wstring(slot) + L".dll"; | ||
| 208 | const std::filesystem::path clone_path = dir / name; | ||
| 209 | if (!CopyFileW(primary.c_str(), clone_path.c_str(), FALSE)) return {}; | ||
| 210 | |||
| 211 | // Hold a read-only-shared handle across LoadLibraryExW so another process cannot overwrite the clone in between. | ||
| 212 | HANDLE guard = CreateFileW(clone_path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE, nullptr, | ||
| 213 | OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); | ||
| 214 | TlsHostModule loaded = load_tls_host_image(clone_path, false); | ||
| 215 | if (guard != INVALID_HANDLE_VALUE) CloseHandle(guard); | ||
| 216 | |||
| 217 | if (loaded.index == TLS_OUT_OF_INDEXES) { | ||
| 218 | DeleteFileW(clone_path.c_str()); | ||
| 219 | return {}; | ||
| 220 | } | ||
| 221 | for (size_t i = 0; i < kMaxMappedTlsModules; ++i) { | ||
| 222 | if (i != slot && g_tls_hosts[i].index == loaded.index) { | ||
| 223 | FreeLibrary(loaded.module); | ||
| 224 | DeleteFileW(clone_path.c_str()); | ||
| 225 | return {}; | ||
| 226 | } | ||
| 227 | } | ||
| 228 | g_tls_clones.push_back({loaded.module, clone_path}); | ||
| 229 | g_tls_hosts[slot] = loaded; | ||
| 230 | return g_tls_hosts[slot]; | ||
| 136 | } | 231 | } |
| 137 | 232 | ||
| 138 | std::atomic<Module*> g_tls_slot_owner{nullptr}; | 233 | struct ThreadTlsSlot { |
| 234 | Module* module = nullptr; | ||
| 235 | void* saved = nullptr; | ||
| 236 | void* block = nullptr; | ||
| 237 | uint32_t index = kNoTlsIndex; | ||
| 238 | }; | ||
| 139 | 239 | ||
| 140 | // Per-thread installation state. Only one mapped TLS module can own the reserved slot, so one entry per thread is | 240 | // 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. | 241 | 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 | 242 | ||
| 147 | // Orders the TLS owner's publication, its `initialised` flag and its retirement against the thread events. Shared in | 243 | // 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 | 244 | // 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). | 245 | // loader lock, which the events run under). |
| 150 | SRWLOCK g_tls_lock = SRWLOCK_INIT; | 246 | SRWLOCK g_tls_lock = SRWLOCK_INIT; |
| 151 | struct SharedTlsLock { | 247 | struct SharedTlsLock { |
| @@ -163,30 +259,38 @@ struct ExclusiveTlsLock { | |||
| 163 | 259 | ||
| 164 | // Puts the helper DLL's own block back in this thread's slot and frees the copy that replaced it. Uses only this | 260 | // 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. | 261 | // thread's record, so it also works after the module that installed the copy is gone. |
| 166 | void release_thread_block() { | 262 | void release_thread_slot(size_t slot) { |
| 167 | if (!g_thread_tls_block) return; | 263 | if (slot >= kMaxMappedTlsModules) return; |
| 168 | void** slots = module_tls_slots(); | 264 | ThreadTlsSlot& entry = g_thread_tls_slots[slot]; |
| 169 | if (slots && g_thread_tls_index < kMaxModuleTlsSlots && slots[g_thread_tls_index] == g_thread_tls_block) | 265 | if (!entry.module && !entry.block) return; |
| 170 | slots[g_thread_tls_index] = g_thread_tls_saved; | 266 | if (entry.block) { |
| 171 | VirtualFree(g_thread_tls_block, 0, MEM_RELEASE); | 267 | void** slots = module_tls_slots(); |
| 172 | g_thread_tls_module = nullptr; | 268 | if (slots && entry.index < kMaxModuleTlsSlots && slots[entry.index] == entry.block) |
| 173 | g_thread_tls_saved = nullptr; | 269 | slots[entry.index] = entry.saved; |
| 174 | g_thread_tls_block = nullptr; | 270 | VirtualFree(entry.block, 0, MEM_RELEASE); |
| 175 | g_thread_tls_index = kNoTlsIndex; | 271 | } |
| 272 | entry = ThreadTlsSlot{}; | ||
| 176 | } | 273 | } |
| 177 | 274 | ||
| 178 | void install_thread_block(Module& m) { | 275 | void install_thread_block(Module& m) { |
| 179 | if (m.tls_index == kNoTlsIndex) return; | 276 | if (m.tls_slot >= kMaxMappedTlsModules) return; |
| 180 | if (g_thread_tls_module == &m) return; | 277 | const size_t slot = m.tls_slot; |
| 181 | if (g_thread_tls_module) { | 278 | ThreadTlsSlot& entry = g_thread_tls_slots[slot]; |
| 279 | if (entry.module == &m) return; | ||
| 280 | if (entry.module) { | ||
| 182 | // A copy left by a module whose Loader is gone is released; a live module's is a conflict. | 281 | // A copy left by a module whose Loader is gone is released; a live module's is a conflict. |
| 183 | if (g_thread_tls_module == g_tls_slot_owner.load()) | 282 | if (entry.module == g_tls_slot_owners[slot].load()) |
| 184 | throw std::runtime_error("another manually mapped module's TLS is already installed in this thread"); | 283 | throw std::runtime_error("another manually mapped module's TLS is already installed in this thread slot"); |
| 185 | release_thread_block(); | 284 | release_thread_slot(slot); |
| 186 | } | 285 | } |
| 187 | 286 | ||
| 188 | const uint64_t total = static_cast<uint64_t>(m.tls_raw_size) + m.tls_zero_fill; | 287 | const uint64_t total = static_cast<uint64_t>(m.tls_raw_size) + m.tls_zero_fill; |
| 189 | if (!total) return; | 288 | if (!total) { |
| 289 | // Callback-only TLS module (no data block): still record attachment in this slot so DLL_THREAD_DETACH runs. | ||
| 290 | entry.module = &m; | ||
| 291 | return; | ||
| 292 | } | ||
| 293 | if (m.tls_index == kNoTlsIndex) return; | ||
| 190 | void** slots = module_tls_slots(); | 294 | void** slots = module_tls_slots(); |
| 191 | if (!slots || m.tls_index >= kMaxModuleTlsSlots) | 295 | if (!slots || m.tls_index >= kMaxModuleTlsSlots) |
| 192 | throw std::runtime_error(m.name + ": cannot install TLS in this thread"); | 296 | throw std::runtime_error(m.name + ": cannot install TLS in this thread"); |
| @@ -199,19 +303,22 @@ void install_thread_block(Module& m) { | |||
| 199 | 303 | ||
| 200 | void* saved = slots[m.tls_index]; | 304 | void* saved = slots[m.tls_index]; |
| 201 | slots[m.tls_index] = block; | 305 | slots[m.tls_index] = block; |
| 202 | g_thread_tls_module = &m; | 306 | entry.module = &m; |
| 203 | g_thread_tls_saved = saved; | 307 | entry.saved = saved; |
| 204 | g_thread_tls_block = block; | 308 | entry.block = block; |
| 205 | g_thread_tls_index = m.tls_index; | 309 | entry.index = m.tls_index; |
| 206 | } | 310 | } |
| 207 | 311 | ||
| 208 | void uninstall_thread_block(Module& m) { | 312 | void uninstall_thread_block(Module& m) { |
| 209 | if (g_thread_tls_module != &m) return; | 313 | if (m.tls_slot >= kMaxMappedTlsModules) return; |
| 210 | if (m.tls_block == g_thread_tls_block) { | 314 | const size_t slot = m.tls_slot; |
| 315 | ThreadTlsSlot& entry = g_thread_tls_slots[slot]; | ||
| 316 | if (entry.module != &m) return; | ||
| 317 | if (m.tls_block == entry.block) { | ||
| 211 | m.tls_block = nullptr; | 318 | m.tls_block = nullptr; |
| 212 | m.tls_saved_block = nullptr; | 319 | m.tls_saved_block = nullptr; |
| 213 | } | 320 | } |
| 214 | release_thread_block(); | 321 | release_thread_slot(slot); |
| 215 | } | 322 | } |
| 216 | 323 | ||
| 217 | void run_callbacks(Module& m, uint32_t reason) { | 324 | void run_callbacks(Module& m, uint32_t reason) { |
| @@ -231,24 +338,28 @@ void run_callbacks(Module& m, uint32_t reason) { | |||
| 231 | } | 338 | } |
| 232 | 339 | ||
| 233 | // Runs in gta6rt_tls_host.dll's DllMain for each thread the process starts or ends once the helper is loaded, under | 340 | // 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 | 341 | // 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 | 342 | // 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 | 343 | // 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) { | 344 | void __cdecl on_host_thread_event(DWORD reason) { |
| 239 | SharedTlsLock lock; | 345 | SharedTlsLock lock; |
| 240 | Module* m = g_tls_slot_owner.load(); | ||
| 241 | try { | 346 | try { |
| 242 | if (reason == DLL_THREAD_ATTACH) { | 347 | if (reason == DLL_THREAD_ATTACH) { |
| 243 | if (!m) return; | 348 | for (size_t slot = 0; slot < kMaxMappedTlsModules; ++slot) { |
| 244 | install_thread_block(*m); | 349 | Module* m = g_tls_slot_owners[slot].load(); |
| 245 | if (m->initialised) run_callbacks(*m, DLL_THREAD_ATTACH); | 350 | if (!m) continue; |
| 351 | install_thread_block(*m); | ||
| 352 | if (m->initialised) run_callbacks(*m, DLL_THREAD_ATTACH); | ||
| 353 | } | ||
| 246 | } else if (reason == DLL_THREAD_DETACH) { | 354 | } else if (reason == DLL_THREAD_DETACH) { |
| 247 | if (m && g_thread_tls_module == m) { | 355 | for (size_t i = kMaxMappedTlsModules; i-- > 0;) { |
| 248 | if (m->initialised) run_callbacks(*m, DLL_THREAD_DETACH); | 356 | Module* m = g_tls_slot_owners[i].load(); |
| 249 | uninstall_thread_block(*m); | 357 | if (m && g_thread_tls_slots[i].module == m) { |
| 250 | } else { | 358 | if (m->initialised) run_callbacks(*m, DLL_THREAD_DETACH); |
| 251 | release_thread_block(); // installed by a module whose Loader is gone (or nothing to do) | 359 | uninstall_thread_block(*m); |
| 360 | } else { | ||
| 361 | release_thread_slot(i); // installed by a module whose Loader is gone (or nothing to do) | ||
| 362 | } | ||
| 252 | } | 363 | } |
| 253 | } | 364 | } |
| 254 | } catch (const std::exception& e) { | 365 | } catch (const std::exception& e) { |
| @@ -375,13 +486,13 @@ Loader::~Loader() { | |||
| 375 | shims::remove_module_lookup(this); | 486 | shims::remove_module_lookup(this); |
| 376 | for (auto* m : order_) { | 487 | for (auto* m : order_) { |
| 377 | // TLS state must go away before the image and its TLS block are unmapped. | 488 | // TLS state must go away before the image and its TLS block are unmapped. |
| 378 | if (m->tls_index != kNoTlsIndex) { | 489 | 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 | 490 | // 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). | 491 | // thread that still holds a copy frees it when it ends (on_host_thread_event). |
| 381 | { | 492 | { |
| 382 | ExclusiveTlsLock lock; | 493 | ExclusiveTlsLock lock; |
| 383 | Module* owner = m; | 494 | Module* owner = m; |
| 384 | g_tls_slot_owner.compare_exchange_strong(owner, nullptr); | 495 | g_tls_slot_owners[m->tls_slot].compare_exchange_strong(owner, nullptr); |
| 385 | } | 496 | } |
| 386 | uninstall_tls_for_thread(*m); | 497 | uninstall_tls_for_thread(*m); |
| 387 | } | 498 | } |
| @@ -604,19 +715,36 @@ void Loader::initialize_tls(Module& m) { | |||
| 604 | require_range(m.name, index_rva, sizeof(uint32_t), m.size, "the TLS index"); | 715 | require_range(m.name, index_rva, sizeof(uint32_t), m.size, "the TLS index"); |
| 605 | } | 716 | } |
| 606 | 717 | ||
| 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"); | 718 | if (!module_tls_slots()) throw std::runtime_error(m.name + ": this thread has no TLS array"); |
| 612 | 719 | ||
| 720 | size_t slot = kMaxMappedTlsModules; | ||
| 721 | DWORD index = TLS_OUT_OF_INDEXES; | ||
| 613 | { | 722 | { |
| 723 | std::lock_guard alloc_lock(g_tls_alloc_mutex); | ||
| 724 | for (size_t i = 0; i < kMaxMappedTlsModules; ++i) { | ||
| 725 | if (g_tls_slot_owners[i].load() == nullptr) { | ||
| 726 | slot = i; | ||
| 727 | break; | ||
| 728 | } | ||
| 729 | } | ||
| 730 | if (slot >= kMaxMappedTlsModules) | ||
| 731 | throw std::runtime_error(m.name + ": all " + std::to_string(kMaxMappedTlsModules) + | ||
| 732 | " manually mapped static TLS slots are in use"); | ||
| 733 | |||
| 734 | // Load/clone gta6rt_tls_host.dll OUTSIDE ExclusiveTlsLock so LoadLibraryExW cannot deadlock with | ||
| 735 | // on_host_thread_event (which runs under the Windows loader lock and takes SharedTlsLock). | ||
| 736 | index = ensure_tls_host(slot).index; | ||
| 737 | if (index == TLS_OUT_OF_INDEXES) | ||
| 738 | throw std::runtime_error(m.name + ": gta6rt_tls_host.dll is missing or has no module TLS index"); | ||
| 739 | if (index >= kMaxModuleTlsSlots) throw std::runtime_error(m.name + ": reserved TLS index is out of range"); | ||
| 740 | |||
| 614 | // The fields are complete before a thread event can see the owner. | 741 | // The fields are complete before a thread event can see the owner. |
| 615 | ExclusiveTlsLock lock; | 742 | ExclusiveTlsLock lock; |
| 616 | Module* expected = nullptr; | 743 | Module* expected = nullptr; |
| 617 | if (!g_tls_slot_owner.compare_exchange_strong(expected, &m)) | 744 | 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"); | 745 | throw std::runtime_error(m.name + ": static TLS slot was claimed concurrently"); |
| 619 | 746 | ||
| 747 | m.tls_slot = static_cast<uint32_t>(slot); | ||
| 620 | m.tls_index = index; | 748 | m.tls_index = index; |
| 621 | m.tls_template = raw ? m.base + raw_rva : nullptr; | 749 | m.tls_template = raw ? m.base + raw_rva : nullptr; |
| 622 | m.tls_raw_size = static_cast<uint32_t>(raw); | 750 | m.tls_raw_size = static_cast<uint32_t>(raw); |
| @@ -631,13 +759,14 @@ void Loader::initialize_tls(Module& m) { | |||
| 631 | } catch (...) { | 759 | } catch (...) { |
| 632 | ExclusiveTlsLock lock; | 760 | ExclusiveTlsLock lock; |
| 633 | m.tls_index = kNoTlsIndex; | 761 | m.tls_index = kNoTlsIndex; |
| 634 | g_tls_slot_owner = nullptr; | 762 | m.tls_slot = kNoTlsIndex; |
| 763 | g_tls_slot_owners[slot].store(nullptr); | ||
| 635 | throw; | 764 | throw; |
| 636 | } | 765 | } |
| 637 | // The loading thread's copy is the one the Module records (and ~Loader frees on that thread). | 766 | // The loading thread's copy is the one the Module records (and ~Loader frees on that thread). |
| 638 | if (g_thread_tls_module == &m) { | 767 | if (g_thread_tls_slots[slot].module == &m) { |
| 639 | m.tls_block = g_thread_tls_block; | 768 | m.tls_block = g_thread_tls_slots[slot].block; |
| 640 | m.tls_saved_block = g_thread_tls_saved; | 769 | m.tls_saved_block = g_thread_tls_slots[slot].saved; |
| 641 | } | 770 | } |
| 642 | } | 771 | } |
| 643 | 772 | ||