diff options
| author | AwkGrep256 <AwkGrep256@users.noreply.github.com> | 2026-11-23 01:40:15 +0300 |
|---|---|---|
| committer | AwkGrep256 <AwkGrep256@users.noreply.github.com> | 2026-11-23 01:40:15 +0300 |
| commit | 874450476350ea9dc986212b83b67d1d48e176ce (patch) | |
| tree | fb0c542f48d29c2ec92c1de0ae1ab581862f5b8f /runtime/src/pe_loader.cpp | |
| parent | c77e99d96cf2c317ed31bdef15bfbf606b8c2b8f (diff) | |
| parent | aa2988cc555bad7ecd508b48a702adbb32fe7c95 (diff) | |
Merge main into ps-helper-lanes (#3061 and #3273 are on main)
docs/design.md: main's versions of the rows next to "Whole-quad mode",
with this branch's edit of that row, once (a both-sides merge listed it
twice; test_docs_design_rows). docs/shader_validation.md: main's file
plus the helper-lane section, nothing else.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'runtime/src/pe_loader.cpp')
| -rw-r--r-- | runtime/src/pe_loader.cpp | 173 |
1 files changed, 132 insertions, 41 deletions
diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index f2c62ec91..f4ecc0de2 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp | |||
| @@ -121,9 +121,14 @@ struct TlsCloneRecord { | |||
| 121 | std::mutex g_tls_alloc_mutex; | 121 | std::mutex g_tls_alloc_mutex; |
| 122 | std::array<TlsHostModule, kMaxMappedTlsModules> g_tls_hosts{}; | 122 | std::array<TlsHostModule, kMaxMappedTlsModules> g_tls_hosts{}; |
| 123 | std::array<std::atomic<Module*>, kMaxMappedTlsModules> g_tls_slot_owners{}; | 123 | std::array<std::atomic<Module*>, kMaxMappedTlsModules> g_tls_slot_owners{}; |
| 124 | std::array<std::atomic<uint64_t>, kMaxMappedTlsModules> g_tls_slot_generations{}; | ||
| 125 | std::atomic<uint64_t> g_next_tls_generation{1}; | ||
| 124 | std::vector<TlsCloneRecord> g_tls_clones; | 126 | std::vector<TlsCloneRecord> g_tls_clones; |
| 125 | 127 | ||
| 126 | void cleanup_tls_clones_at_exit() { | 128 | // Frees every TLS helper clone this process loaded and deletes its files. load() registers the wrapper with atexit; |
| 129 | // the --run path in main() must also call this directly before ExitProcess, which skips the atexit table. Call it | ||
| 130 | // only when no mapped code can run again: it unmaps the helper images. | ||
| 131 | void cleanup_tls_clones_internal() { | ||
| 127 | for (const auto& rec : g_tls_clones) { | 132 | for (const auto& rec : g_tls_clones) { |
| 128 | if (rec.module) FreeLibrary(rec.module); | 133 | if (rec.module) FreeLibrary(rec.module); |
| 129 | if (!rec.path.empty()) DeleteFileW(rec.path.c_str()); | 134 | if (!rec.path.empty()) DeleteFileW(rec.path.c_str()); |
| @@ -131,16 +136,54 @@ void cleanup_tls_clones_at_exit() { | |||
| 131 | g_tls_clones.clear(); | 136 | g_tls_clones.clear(); |
| 132 | } | 137 | } |
| 133 | 138 | ||
| 139 | void cleanup_tls_clones_at_exit() { cleanup_tls_clones_internal(); } | ||
| 140 | |||
| 141 | // The owner process named by "leonida_tls_host_<pid>_<slot>.dll"; 0 when the name does not carry one. | ||
| 142 | DWORD clone_owner_pid(const wchar_t* name) { | ||
| 143 | constexpr wchar_t prefix[] = L"leonida_tls_host_"; | ||
| 144 | const wchar_t* p = name; | ||
| 145 | for (size_t i = 0; i < sizeof(prefix) / sizeof(wchar_t) - 1; ++i) | ||
| 146 | if (*p++ != prefix[i]) return 0; | ||
| 147 | if (*p < L'0' || *p > L'9') return 0; | ||
| 148 | unsigned long pid = 0; | ||
| 149 | while (*p >= L'0' && *p <= L'9') { | ||
| 150 | pid = pid * 10 + (*p - L'0'); | ||
| 151 | if (pid > 0xFFFFFFFFul) return 0; | ||
| 152 | ++p; | ||
| 153 | } | ||
| 154 | return static_cast<DWORD>(pid); | ||
| 155 | } | ||
| 156 | |||
| 157 | bool process_alive(DWORD pid) { | ||
| 158 | // PROCESS_QUERY_LIMITED_INFORMATION needs no handle rights a normal process could deny; a failure means the | ||
| 159 | // process is gone. A still-mapped or still-open file is caught by the checks below even for a misjudged PID. | ||
| 160 | HANDLE p = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid); | ||
| 161 | if (!p) return false; | ||
| 162 | CloseHandle(p); | ||
| 163 | return true; | ||
| 164 | } | ||
| 165 | |||
| 166 | // Deletes clones left behind by processes that have exited. Deletion is scoped to files whose owner is gone: a | ||
| 167 | // clone of a live process is either still open by its copy step's handle or mapped as an image, so it is skipped | ||
| 168 | // (or DeleteFileW fails harmlessly), and a concurrent process between CopyFileW and LoadLibraryExW keeps its file. | ||
| 134 | void sweep_stale_tls_clones(const std::filesystem::path& dir) { | 169 | void sweep_stale_tls_clones(const std::filesystem::path& dir) { |
| 135 | WIN32_FIND_DATAW fd{}; | 170 | WIN32_FIND_DATAW fd{}; |
| 136 | const std::filesystem::path pattern = dir / L"leonida_tls_host_*.dll"; | 171 | const std::filesystem::path pattern = dir / L"leonida_tls_host_*.dll"; |
| 137 | HANDLE h = FindFirstFileW(pattern.c_str(), &fd); | 172 | HANDLE h = FindFirstFileW(pattern.c_str(), &fd); |
| 138 | if (h == INVALID_HANDLE_VALUE) return; | 173 | if (h == INVALID_HANDLE_VALUE) return; |
| 139 | do { | 174 | do { |
| 140 | if ((fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) { | 175 | if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) continue; |
| 141 | // Fails harmlessly for clones still mapped in live processes; deletes orphaned ones from exited processes. | 176 | const std::filesystem::path path = dir / fd.cFileName; |
| 142 | DeleteFileW((dir / fd.cFileName).c_str()); | 177 | const DWORD owner = clone_owner_pid(fd.cFileName); |
| 143 | } | 178 | if (owner && owner != GetCurrentProcessId() && process_alive(owner)) continue; |
| 179 | // An exclusive open (no sharing) conflicts with any handle another process holds on the file, so a failure | ||
| 180 | // means the copy->load sequence or a mapped image still owns it. Only unowned files reach DeleteFileW, and | ||
| 181 | // that stays harmless for a mapped image. | ||
| 182 | HANDLE probe = | ||
| 183 | CreateFileW(path.c_str(), GENERIC_READ, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); | ||
| 184 | if (probe == INVALID_HANDLE_VALUE) continue; | ||
| 185 | CloseHandle(probe); | ||
| 186 | DeleteFileW(path.c_str()); | ||
| 144 | } while (FindNextFileW(h, &fd)); | 187 | } while (FindNextFileW(h, &fd)); |
| 145 | FindClose(h); | 188 | FindClose(h); |
| 146 | } | 189 | } |
| @@ -208,13 +251,27 @@ TlsHostModule ensure_tls_host(size_t slot) { | |||
| 208 | const std::wstring name = | 251 | const std::wstring name = |
| 209 | L"leonida_tls_host_" + std::to_wstring(GetCurrentProcessId()) + L"_" + std::to_wstring(slot) + L".dll"; | 252 | L"leonida_tls_host_" + std::to_wstring(GetCurrentProcessId()) + L"_" + std::to_wstring(slot) + L".dll"; |
| 210 | const std::filesystem::path clone_path = dir / name; | 253 | const std::filesystem::path clone_path = dir / name; |
| 211 | if (!CopyFileW(primary.c_str(), clone_path.c_str(), FALSE)) return {}; | 254 | // The staging name must not match the sweep pattern, which only covers final clone names ending in .dll. |
| 212 | 255 | const std::filesystem::path staging = clone_path.wstring() + L".new"; | |
| 213 | // Hold a read-only-shared handle across LoadLibraryExW so another process cannot overwrite the clone in between. | 256 | if (!CopyFileW(primary.c_str(), staging.c_str(), FALSE)) return {}; |
| 214 | HANDLE guard = CreateFileW(clone_path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE, nullptr, | 257 | |
| 258 | // Open the guard before the clone exists under its final name and hold it across LoadLibraryExW: the rename | ||
| 259 | // below needs DELETE access, which the handle's FILE_SHARE_DELETE grants, and no purge can remove the clone | ||
| 260 | // while the handle is open (an exclusive open conflicts with it) or once the image is mapped. Copying straight | ||
| 261 | // to the final name would leave a window where a concurrent sweep sees an unowned file. | ||
| 262 | HANDLE guard = CreateFileW(staging.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE, nullptr, | ||
| 215 | OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); | 263 | OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); |
| 264 | if (guard == INVALID_HANDLE_VALUE) { | ||
| 265 | DeleteFileW(staging.c_str()); | ||
| 266 | return {}; | ||
| 267 | } | ||
| 268 | if (!MoveFileExW(staging.c_str(), clone_path.c_str(), MOVEFILE_REPLACE_EXISTING)) { | ||
| 269 | CloseHandle(guard); | ||
| 270 | DeleteFileW(staging.c_str()); | ||
| 271 | return {}; | ||
| 272 | } | ||
| 216 | TlsHostModule loaded = load_tls_host_image(clone_path, false); | 273 | TlsHostModule loaded = load_tls_host_image(clone_path, false); |
| 217 | if (guard != INVALID_HANDLE_VALUE) CloseHandle(guard); | 274 | CloseHandle(guard); |
| 218 | 275 | ||
| 219 | if (loaded.index == TLS_OUT_OF_INDEXES) { | 276 | if (loaded.index == TLS_OUT_OF_INDEXES) { |
| 220 | DeleteFileW(clone_path.c_str()); | 277 | DeleteFileW(clone_path.c_str()); |
| @@ -234,6 +291,7 @@ TlsHostModule ensure_tls_host(size_t slot) { | |||
| 234 | 291 | ||
| 235 | struct ThreadTlsSlot { | 292 | struct ThreadTlsSlot { |
| 236 | Module* module = nullptr; | 293 | Module* module = nullptr; |
| 294 | uint64_t generation = 0; | ||
| 237 | void* saved = nullptr; | 295 | void* saved = nullptr; |
| 238 | void* block = nullptr; | 296 | void* block = nullptr; |
| 239 | uint32_t index = kNoTlsIndex; | 297 | uint32_t index = kNoTlsIndex; |
| @@ -278,11 +336,13 @@ void install_thread_block(Module& m) { | |||
| 278 | if (m.tls_slot >= kMaxMappedTlsModules) return; | 336 | if (m.tls_slot >= kMaxMappedTlsModules) return; |
| 279 | const size_t slot = m.tls_slot; | 337 | const size_t slot = m.tls_slot; |
| 280 | ThreadTlsSlot& entry = g_thread_tls_slots[slot]; | 338 | ThreadTlsSlot& entry = g_thread_tls_slots[slot]; |
| 281 | if (entry.module == &m) return; | 339 | if (entry.module == &m && entry.generation == m.tls_generation) return; |
| 282 | if (entry.module) { | 340 | if (entry.module) { |
| 283 | // A copy left by a module whose Loader is gone is released; a live module's is a conflict. | 341 | // A copy left by a module whose Loader is gone (or from an earlier generation) is released; a live owner's is a conflict. |
| 284 | if (entry.module == g_tls_slot_owners[slot].load()) | 342 | if (entry.module == g_tls_slot_owners[slot].load() && |
| 343 | entry.generation == g_tls_slot_generations[slot].load()) { | ||
| 285 | throw std::runtime_error("another manually mapped module's TLS is already installed in this thread slot"); | 344 | throw std::runtime_error("another manually mapped module's TLS is already installed in this thread slot"); |
| 345 | } | ||
| 286 | release_thread_slot(slot); | 346 | release_thread_slot(slot); |
| 287 | } | 347 | } |
| 288 | 348 | ||
| @@ -290,6 +350,7 @@ void install_thread_block(Module& m) { | |||
| 290 | if (!total) { | 350 | if (!total) { |
| 291 | // Callback-only TLS module (no data block): still record attachment in this slot so DLL_THREAD_DETACH runs. | 351 | // Callback-only TLS module (no data block): still record attachment in this slot so DLL_THREAD_DETACH runs. |
| 292 | entry.module = &m; | 352 | entry.module = &m; |
| 353 | entry.generation = m.tls_generation; | ||
| 293 | return; | 354 | return; |
| 294 | } | 355 | } |
| 295 | if (m.tls_index == kNoTlsIndex) return; | 356 | if (m.tls_index == kNoTlsIndex) return; |
| @@ -306,6 +367,7 @@ void install_thread_block(Module& m) { | |||
| 306 | void* saved = slots[m.tls_index]; | 367 | void* saved = slots[m.tls_index]; |
| 307 | slots[m.tls_index] = block; | 368 | slots[m.tls_index] = block; |
| 308 | entry.module = &m; | 369 | entry.module = &m; |
| 370 | entry.generation = m.tls_generation; | ||
| 309 | entry.saved = saved; | 371 | entry.saved = saved; |
| 310 | entry.block = block; | 372 | entry.block = block; |
| 311 | entry.index = m.tls_index; | 373 | entry.index = m.tls_index; |
| @@ -315,7 +377,7 @@ void uninstall_thread_block(Module& m) { | |||
| 315 | if (m.tls_slot >= kMaxMappedTlsModules) return; | 377 | if (m.tls_slot >= kMaxMappedTlsModules) return; |
| 316 | const size_t slot = m.tls_slot; | 378 | const size_t slot = m.tls_slot; |
| 317 | ThreadTlsSlot& entry = g_thread_tls_slots[slot]; | 379 | ThreadTlsSlot& entry = g_thread_tls_slots[slot]; |
| 318 | if (entry.module != &m) return; | 380 | if (entry.module != &m || entry.generation != m.tls_generation) return; |
| 319 | if (m.tls_block == entry.block) { | 381 | if (m.tls_block == entry.block) { |
| 320 | m.tls_block = nullptr; | 382 | m.tls_block = nullptr; |
| 321 | m.tls_saved_block = nullptr; | 383 | m.tls_saved_block = nullptr; |
| @@ -351,29 +413,39 @@ void run_callbacks(Module& m, uint32_t reason, bool trace = false) { | |||
| 351 | // only after the module's DLL_PROCESS_ATTACH (initialise()), as the Windows loader orders them. | 413 | // only after the module's DLL_PROCESS_ATTACH (initialise()), as the Windows loader orders them. |
| 352 | void __cdecl on_host_thread_event(DWORD reason) { | 414 | void __cdecl on_host_thread_event(DWORD reason) { |
| 353 | SharedTlsLock lock; | 415 | SharedTlsLock lock; |
| 354 | try { | 416 | // The try/catch is per slot: a throw from one module's install or callbacks must not take the thread events |
| 355 | if (reason == DLL_THREAD_ATTACH) { | 417 | // away from the other slots. Nothing may leave DllMain. |
| 356 | for (size_t slot = 0; slot < kMaxMappedTlsModules; ++slot) { | 418 | if (reason == DLL_THREAD_ATTACH) { |
| 357 | Module* m = g_tls_slot_owners[slot].load(); | 419 | for (size_t slot = 0; slot < kMaxMappedTlsModules; ++slot) { |
| 358 | if (!m) continue; | 420 | Module* m = g_tls_slot_owners[slot].load(); |
| 421 | if (!m) continue; | ||
| 422 | try { | ||
| 359 | install_thread_block(*m); | 423 | install_thread_block(*m); |
| 360 | if (m->initialised) run_callbacks(*m, DLL_THREAD_ATTACH); | 424 | if (m->initialised) run_callbacks(*m, DLL_THREAD_ATTACH); |
| 425 | } catch (const std::exception& e) { | ||
| 426 | // The thread runs on without this module's TLS; later slots still get theirs. | ||
| 427 | std::fprintf(stderr, "[rt] loader: thread attach, slot %zu (%s): %s\n", slot, m->name.c_str(), | ||
| 428 | e.what()); | ||
| 361 | } | 429 | } |
| 362 | } else if (reason == DLL_THREAD_DETACH) { | 430 | } |
| 363 | for (size_t i = kMaxMappedTlsModules; i-- > 0;) { | 431 | } else if (reason == DLL_THREAD_DETACH) { |
| 364 | Module* m = g_tls_slot_owners[i].load(); | 432 | for (size_t i = kMaxMappedTlsModules; i-- > 0;) { |
| 365 | if (m && g_thread_tls_slots[i].module == m) { | 433 | Module* m = g_tls_slot_owners[i].load(); |
| 434 | if (m && g_thread_tls_slots[i].module == m && | ||
| 435 | g_thread_tls_slots[i].generation == m->tls_generation) { | ||
| 436 | try { | ||
| 366 | if (m->initialised) run_callbacks(*m, DLL_THREAD_DETACH); | 437 | if (m->initialised) run_callbacks(*m, DLL_THREAD_DETACH); |
| 367 | uninstall_thread_block(*m); | 438 | } catch (const std::exception& e) { |
| 368 | } else { | 439 | std::fprintf(stderr, "[rt] loader: thread detach, slot %zu (%s): %s\n", i, m->name.c_str(), |
| 369 | release_thread_slot(i); // installed by a module whose Loader is gone (or nothing to do) | 440 | e.what()); |
| 370 | } | 441 | } |
| 442 | // Released even when the callbacks threw: a leaked block would be handed to the OS loader as the | ||
| 443 | // helper's own TLS block and freed with it at thread exit. | ||
| 444 | uninstall_thread_block(*m); | ||
| 445 | } else { | ||
| 446 | release_thread_slot(i); // installed by a module whose Loader is gone (or nothing to do) | ||
| 371 | } | 447 | } |
| 372 | } | 448 | } |
| 373 | } catch (const std::exception& e) { | ||
| 374 | // Nothing may leave DllMain. The thread runs on without the module's TLS (attach) or keeps the copy (detach). | ||
| 375 | std::fprintf(stderr, "[rt] loader: thread %s: %s\n", reason == DLL_THREAD_ATTACH ? "attach" : "detach", | ||
| 376 | e.what()); | ||
| 377 | } | 449 | } |
| 378 | } | 450 | } |
| 379 | 451 | ||
| @@ -452,6 +524,9 @@ void redirect_pc_to_file_header_at(const void* resolved) { | |||
| 452 | 524 | ||
| 453 | } // namespace | 525 | } // namespace |
| 454 | 526 | ||
| 527 | // Declared in pe_loader.h; the body needs the internal clone registry above. | ||
| 528 | void cleanup_tls_clones() { cleanup_tls_clones_internal(); } | ||
| 529 | |||
| 455 | namespace { | 530 | namespace { |
| 456 | bool lookup_in_loader(void* ctx, uint64_t address, std::string& module, uint32_t& rva) { | 531 | bool lookup_in_loader(void* ctx, uint64_t address, std::string& module, uint32_t& rva) { |
| 457 | for (const Module* m : static_cast<Loader*>(ctx)->modules()) { | 532 | for (const Module* m : static_cast<Loader*>(ctx)->modules()) { |
| @@ -525,7 +600,8 @@ Loader::~Loader() { | |||
| 525 | { | 600 | { |
| 526 | ExclusiveTlsLock lock; | 601 | ExclusiveTlsLock lock; |
| 527 | Module* owner = m; | 602 | Module* owner = m; |
| 528 | g_tls_slot_owners[m->tls_slot].compare_exchange_strong(owner, nullptr); | 603 | if (g_tls_slot_owners[m->tls_slot].compare_exchange_strong(owner, nullptr)) |
| 604 | g_tls_slot_generations[m->tls_slot].store(0); | ||
| 529 | } | 605 | } |
| 530 | uninstall_tls_for_thread(*m); | 606 | uninstall_tls_for_thread(*m); |
| 531 | } | 607 | } |
| @@ -541,10 +617,19 @@ Module& Loader::load(const std::filesystem::path& image) { | |||
| 541 | std::lock_guard lock(mutex_); | 617 | std::lock_guard lock(mutex_); |
| 542 | std::string key = lower(image.filename().string()); | 618 | std::string key = lower(image.filename().string()); |
| 543 | if (auto it = by_name_.find(key); it != by_name_.end()) return *it->second; | 619 | if (auto it = by_name_.find(key); it != by_name_.end()) return *it->second; |
| 544 | Module& m = map_image(image); | 620 | Module* mapped = nullptr; |
| 545 | bind_imports(m); // loads every bundled module m imports first, so they land in init_order_ before m | 621 | try { |
| 546 | protect_sections(m); | 622 | mapped = &map_image(image); |
| 547 | register_unwind(m); | 623 | bind_imports(*mapped); // loads every bundled module m imports first, so they land in init_order_ before m |
| 624 | protect_sections(*mapped); | ||
| 625 | register_unwind(*mapped); | ||
| 626 | } catch (...) { | ||
| 627 | // A failed load, nested ones (a dependency of a run-time load) included, must not stay findable by name: | ||
| 628 | // a later lookup would get a half-mapped image with unbound imports. ~Loader still frees it through order_. | ||
| 629 | by_name_.erase(key); | ||
| 630 | throw; | ||
| 631 | } | ||
| 632 | Module& m = *mapped; | ||
| 548 | init_order_.push_back(&m); | 633 | init_order_.push_back(&m); |
| 549 | if (startup_trace::enabled()) | 634 | if (startup_trace::enabled()) |
| 550 | startup_trace::event("map", "\"module\":" + startup_trace::quote(m.name) + | 635 | startup_trace::event("map", "\"module\":" + startup_trace::quote(m.name) + |
| @@ -599,8 +684,8 @@ void* Loader::load_runtime_module(const std::string& dll_lower, uint32_t flags, | |||
| 599 | std::fprintf(stderr, "[rt] loader: %s mapped from game_dir (run-time load)\n", m.name.c_str()); | 684 | std::fprintf(stderr, "[rt] loader: %s mapped from game_dir (run-time load)\n", m.name.c_str()); |
| 600 | return static_cast<void*>(m.base); | 685 | return static_cast<void*>(m.base); |
| 601 | } catch (const std::exception& e) { | 686 | } catch (const std::exception& e) { |
| 602 | // Do not leave a failed run-time load indexed by name so later GetModuleHandle/LoadLibrary calls do not | 687 | // load() drops a module that failed to map or bind (dependencies included); this also drops one whose |
| 603 | // observe a half-initialised module. ~Loader still frees any VirtualAlloc'd mapping in order_. | 688 | // initialise() failed, so later GetModuleHandle/LoadLibrary calls don't see it. ~Loader frees it via order_. |
| 604 | by_name_.erase(dll_lower); | 689 | by_name_.erase(dll_lower); |
| 605 | std::fprintf(stderr, "[rt] loader: run-time load of %s failed: %s\n", dll_lower.c_str(), e.what()); | 690 | std::fprintf(stderr, "[rt] loader: run-time load of %s failed: %s\n", dll_lower.c_str(), e.what()); |
| 606 | SetLastError(ERROR_DLL_INIT_FAILED); | 691 | SetLastError(ERROR_DLL_INIT_FAILED); |
| @@ -827,8 +912,9 @@ Module& Loader::map_image(const std::filesystem::path& path) { | |||
| 827 | // zero-fill size; it has no field naming the TLS block. The Windows loader allocates a block per module per thread and | 912 | // zero-fill size; it has no field naming the TLS block. The Windows loader allocates a block per module per thread and |
| 828 | // puts it in TEB->ThreadLocalStoragePointer[module index], which is what __declspec(thread) code reads via _tls_index. | 913 | // puts it in TEB->ThreadLocalStoragePointer[module index], which is what __declspec(thread) code reads via _tls_index. |
| 829 | // Only the OS loader can allocate that module index, so the loader reuses the index the OS assigned to | 914 | // Only the OS loader can allocate that module index, so the loader reuses the index the OS assigned to |
| 830 | // gta6rt_tls_host.dll. That makes one manually mapped TLS module work; a second one is rejected rather than silently | 915 | // gta6rt_tls_host.dll and maps a fresh clone of the helper for every additional simultaneous TLS module, each clone |
| 831 | // sharing (and corrupting) the same slot. | 916 | // getting its own index. All kMaxMappedTlsModules slots can be live at once; a further module is rejected rather than |
| 917 | // silently sharing (and corrupting) a slot. | ||
| 832 | void Loader::initialize_tls(Module& m) { | 918 | void Loader::initialize_tls(Module& m) { |
| 833 | auto* tls = tls_directory(m); | 919 | auto* tls = tls_directory(m); |
| 834 | if (!tls) return; | 920 | if (!tls) return; |
| @@ -880,6 +966,8 @@ void Loader::initialize_tls(Module& m) { | |||
| 880 | throw std::runtime_error(m.name + ": static TLS slot was claimed concurrently"); | 966 | throw std::runtime_error(m.name + ": static TLS slot was claimed concurrently"); |
| 881 | 967 | ||
| 882 | m.tls_slot = static_cast<uint32_t>(slot); | 968 | m.tls_slot = static_cast<uint32_t>(slot); |
| 969 | m.tls_generation = g_next_tls_generation.fetch_add(1, std::memory_order_relaxed); | ||
| 970 | g_tls_slot_generations[slot].store(m.tls_generation); | ||
| 883 | m.tls_index = index; | 971 | m.tls_index = index; |
| 884 | m.tls_template = raw ? m.base + raw_rva : nullptr; | 972 | m.tls_template = raw ? m.base + raw_rva : nullptr; |
| 885 | m.tls_raw_size = static_cast<uint32_t>(raw); | 973 | m.tls_raw_size = static_cast<uint32_t>(raw); |
| @@ -895,11 +983,13 @@ void Loader::initialize_tls(Module& m) { | |||
| 895 | ExclusiveTlsLock lock; | 983 | ExclusiveTlsLock lock; |
| 896 | m.tls_index = kNoTlsIndex; | 984 | m.tls_index = kNoTlsIndex; |
| 897 | m.tls_slot = kNoTlsIndex; | 985 | m.tls_slot = kNoTlsIndex; |
| 986 | m.tls_generation = 0; | ||
| 987 | g_tls_slot_generations[slot].store(0); | ||
| 898 | g_tls_slot_owners[slot].store(nullptr); | 988 | g_tls_slot_owners[slot].store(nullptr); |
| 899 | throw; | 989 | throw; |
| 900 | } | 990 | } |
| 901 | // The loading thread's copy is the one the Module records (and ~Loader frees on that thread). | 991 | // The loading thread's copy is the one the Module records (and ~Loader frees on that thread). |
| 902 | if (g_thread_tls_slots[slot].module == &m) { | 992 | if (g_thread_tls_slots[slot].module == &m && g_thread_tls_slots[slot].generation == m.tls_generation) { |
| 903 | m.tls_block = g_thread_tls_slots[slot].block; | 993 | m.tls_block = g_thread_tls_slots[slot].block; |
| 904 | m.tls_saved_block = g_thread_tls_slots[slot].saved; | 994 | m.tls_saved_block = g_thread_tls_slots[slot].saved; |
| 905 | } | 995 | } |
| @@ -931,6 +1021,7 @@ void Loader::parse_exports(Module& m) { | |||
| 931 | // into the string, so forwarders are kept apart and followed when an import asks for one. | 1021 | // into the string, so forwarders are kept apart and followed when an import asks for one. |
| 932 | const uint64_t dir_begin = dir.VirtualAddress, dir_end = dir_begin + dir.Size; | 1022 | const uint64_t dir_begin = dir.VirtualAddress, dir_end = dir_begin + dir.Size; |
| 933 | auto add_export = [&](const std::string& key, uint32_t rva) { | 1023 | auto add_export = [&](const std::string& key, uint32_t rva) { |
| 1024 | if (!rva) return; // An unused address-table slot is absent even when a name refers to it. | ||
| 934 | if (rva >= dir_begin && rva < dir_end) | 1025 | if (rva >= dir_begin && rva < dir_end) |
| 935 | m.forwarders[key] = read_string(m.name, m.base, m.size, rva, "a forwarded export"); | 1026 | m.forwarders[key] = read_string(m.name, m.base, m.size, rva, "a forwarded export"); |
| 936 | else if (rva >= m.size) // base + rva would point past the mapping, and a caller would jump there | 1027 | else if (rva >= m.size) // base + rva would point past the mapping, and a caller would jump there |
| @@ -1053,8 +1144,8 @@ void Loader::bind_imports(Module& m) { | |||
| 1053 | uint16_t ord = by_ord ? (uint16_t)IMAGE_ORDINAL64(lookup->u1.Ordinal) : 0; | 1144 | uint16_t ord = by_ord ? (uint16_t)IMAGE_ORDINAL64(lookup->u1.Ordinal) : 0; |
| 1054 | std::string name; | 1145 | std::string name; |
| 1055 | if (!by_ord) { | 1146 | if (!by_ord) { |
| 1147 | require_range(m.name, lookup->u1.AddressOfData, sizeof(uint16_t), m.size, "an import name"); | ||
| 1056 | uint32_t hint = static_cast<uint32_t>(lookup->u1.AddressOfData); | 1148 | uint32_t hint = static_cast<uint32_t>(lookup->u1.AddressOfData); |
| 1057 | require_range(m.name, hint, sizeof(uint16_t), m.size, "an import name"); | ||
| 1058 | name = read_string(m.name, m.base, m.size, hint + sizeof(uint16_t), "an import name"); | 1149 | name = read_string(m.name, m.base, m.size, hint + sizeof(uint16_t), "an import name"); |
| 1059 | } | 1150 | } |
| 1060 | at<IMAGE_THUNK_DATA64>(m.base, static_cast<uint32_t>(iat_rva))->u1.Function = | 1151 | at<IMAGE_THUNK_DATA64>(m.base, static_cast<uint32_t>(iat_rva))->u1.Function = |