diff options
Diffstat (limited to 'runtime/src/pe_loader.cpp')
| -rw-r--r-- | runtime/src/pe_loader.cpp | 546 |
1 files changed, 252 insertions, 294 deletions
diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index 821fc1595..70bb34ad9 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp | |||
| @@ -2,8 +2,6 @@ | |||
| 2 | 2 | ||
| 3 | #include <windows.h> | 3 | #include <windows.h> |
| 4 | #include <intrin.h> | 4 | #include <intrin.h> |
| 5 | #include <psapi.h> | ||
| 6 | #include <tlhelp32.h> | ||
| 7 | 5 | ||
| 8 | #include <algorithm> | 6 | #include <algorithm> |
| 9 | #include <array> | 7 | #include <array> |
| @@ -85,15 +83,19 @@ IMAGE_TLS_DIRECTORY64* tls_directory(Module& m) { | |||
| 85 | // A mapped executable is different: MSVC code built with /GA (an EXE-only optimisation) skips _tls_index and reads | 83 | // A mapped executable is different: MSVC code built with /GA (an EXE-only optimisation) skips _tls_index and reads |
| 86 | // TEB->ThreadLocalStoragePointer[0] directly (mov rax, gs:[58h]; mov rax, [rax]), because Windows always gives the | 84 | // TEB->ThreadLocalStoragePointer[0] directly (mov rax, gs:[58h]; mov rax, [rax]), because Windows always gives the |
| 87 | // process executable module TLS index 0. Measured with a `thread_local int v = 42;` EXE built /O2 /GA /MD: natively | 85 | // process executable module TLS index 0. Measured with a `thread_local int v = 42;` EXE built /O2 /GA /MD: natively |
| 88 | // tls_index=0 value=42; mapped with a helper index (6) the code still read slot 0 and printed value=0. Index 0 belongs to | 86 | // tls_index=0 value=42; mapped with a helper index (6) the code still read slot 0 and printed value=0. Index 0 |
| 89 | // the runtime's own EXE (gta6rt.exe has a TLS block, 1350 bytes when measured, and no TLS callbacks; each test EXE | 87 | // belongs to the runtime's own EXE (gta6rt.exe: a 1398-byte template when measured, no TLS callbacks; so does each |
| 90 | // that links this file has one too), and every TLS read in its disassembly goes through _tls_index (the only direct gs:[58h] read is | 88 | // test EXE that links this file), and every TLS read in its disassembly goes through _tls_index (the only direct |
| 91 | // module_tls_slots below, which wants the array itself). So index 0 is freed by moving the owner: | 89 | // gs:[58h] read is module_tls_slots below, which wants the array itself). reserve_tls_index0 therefore moves the owner |
| 92 | // move_index0_owner swaps slots 0 and H of every thread, H being the index of a further helper clone that exists for | 90 | // off index 0, once, at process start: it loads the home clone (make_home_clone_image), whose TLS template is a copy of |
| 93 | // this, and writes H into the owner's _tls_index. The owner then finds its block through H, and slot 0 holds the | 91 | // the owner's, and on the calling thread swaps slots 0 and home and writes home into the owner's _tls_index. From then on every thread the OS |
| 94 | // helper's spare block, which the mapped executable's copy replaces (kMainImageSlot) exactly as a DLL's copy replaces | 92 | // starts has a fresh copy of the owner's template at home, which is where the owner looks, from its first instruction: |
| 95 | // a helper's. The swap is permanent: both pointers are blocks the OS allocated for this thread, and at thread exit it | 93 | // nothing has to run on a new thread first. Slot 0 holds a block nobody reads, which the mapped executable's copy |
| 96 | // frees every slot by index whatever block each holds, so nothing has to be swapped back. | 94 | // replaces (kMainImageSlot) exactly as a DLL's copy replaces a helper's, and the OS frees both slots at thread exit. |
| 95 | // It has to happen before any other thread has run the owner's code: MSVC keeps &ThreadLocalStoragePointer[_tls_index] | ||
| 96 | // across calls (zlib_inflate in shader_library.h saves it at [rbp-80h] across memset, push_back and inflate_codes, then | ||
| 97 | // reads _Init_thread_epoch through it), so a running thread cannot be moved safely, wherever it is stopped. Such a | ||
| 98 | // thread's TLS would also stay where it was, at index 0. | ||
| 97 | constexpr DWORD kMaxModuleTlsSlots = 64; | 99 | constexpr DWORD kMaxModuleTlsSlots = 64; |
| 98 | constexpr size_t kMaxMappedTlsModules = 16; | 100 | constexpr size_t kMaxMappedTlsModules = 16; |
| 99 | // The slot for a mapped executable, which reads module TLS index 0 (see above). Only one at a time; a second | 101 | // The slot for a mapped executable, which reads module TLS index 0 (see above). Only one at a time; a second |
| @@ -107,6 +109,7 @@ void __cdecl on_host_thread_event(DWORD reason); | |||
| 107 | struct TlsHostModule { | 109 | struct TlsHostModule { |
| 108 | HMODULE module = nullptr; | 110 | HMODULE module = nullptr; |
| 109 | DWORD index = TLS_OUT_OF_INDEXES; | 111 | DWORD index = TLS_OUT_OF_INDEXES; |
| 112 | bool hooked = false; // its DllMain reports thread events to on_host_thread_event | ||
| 110 | }; | 113 | }; |
| 111 | 114 | ||
| 112 | std::filesystem::path tls_host_base_path() { | 115 | std::filesystem::path tls_host_base_path() { |
| @@ -144,13 +147,16 @@ std::array<std::atomic<uint64_t>, kTlsSlotCount> g_tls_slot_generations{}; | |||
| 144 | std::atomic<uint64_t> g_next_tls_generation{1}; | 147 | std::atomic<uint64_t> g_next_tls_generation{1}; |
| 145 | std::vector<TlsCloneRecord> g_tls_clones; | 148 | std::vector<TlsCloneRecord> g_tls_clones; |
| 146 | 149 | ||
| 147 | // The move of module TLS index 0 (see kMainImageSlot), done at most once per process. `moved` is written under both | 150 | // The move of module TLS index 0 (see kMainImageSlot): done at most once, by reserve_tls_index0 under |
| 148 | // g_tls_alloc_mutex and an exclusive g_tls_lock, so thread events read it under the shared lock; the other fields are | 151 | // g_tls_alloc_mutex. `why` is the reason it was not done, for the executable that then maps with a helper index. |
| 149 | // set before it and never change after. | 152 | // Constant-initialized only (no std::string): gta6rt reserves from a CRT initializer that runs before the dynamic |
| 153 | // initializers of this file, which would otherwise reset what it wrote. | ||
| 150 | struct Index0Move { | 154 | struct Index0Move { |
| 151 | bool moved = false; | 155 | bool moved = false; |
| 152 | TlsHostModule home; // the clone whose index now holds the owner's block; never freed | 156 | bool traced = false; // the startup trace opens after the move; the first executable map reports it |
| 153 | DWORD mark = TLS_OUT_OF_INDEXES; // TlsAlloc slot, non-zero on a thread whose slots 0 and home are swapped | 157 | TlsHostModule home; // the clone whose index holds the owner's TLS from now on; never freed |
| 158 | char owner[260] = {}; // UTF-8 file name of the image that held index 0 | ||
| 159 | char why[160] = "reserve_tls_index0 was not called at process start"; | ||
| 154 | }; | 160 | }; |
| 155 | Index0Move g_index0; | 161 | Index0Move g_index0; |
| 156 | 162 | ||
| @@ -244,8 +250,11 @@ TlsHostModule load_tls_host_image(const std::filesystem::path& path, bool hook_t | |||
| 244 | if (hook_thread_events) { | 250 | if (hook_thread_events) { |
| 245 | // Only the primary helper reports thread attach/detach events; on_host_thread_event iterates all active slots. | 251 | // Only the primary helper reports thread attach/detach events; on_host_thread_event iterates all active slots. |
| 246 | using SetThreadEvent = void(__cdecl*)(void(__cdecl*)(DWORD)); | 252 | using SetThreadEvent = void(__cdecl*)(void(__cdecl*)(DWORD)); |
| 247 | if (auto set = reinterpret_cast<SetThreadEvent>(GetProcAddress(host.module, "gta6rt_tls_host_set_thread_event"))) | 253 | auto set = reinterpret_cast<SetThreadEvent>(GetProcAddress(host.module, "gta6rt_tls_host_set_thread_event")); |
| 254 | if (set) { | ||
| 248 | set(&on_host_thread_event); | 255 | set(&on_host_thread_event); |
| 256 | host.hooked = true; | ||
| 257 | } | ||
| 249 | } | 258 | } |
| 250 | return host; | 259 | return host; |
| 251 | } | 260 | } |
| @@ -253,18 +262,26 @@ TlsHostModule load_tls_host_image(const std::filesystem::path& path, bool hook_t | |||
| 253 | // The primary helper: slot 0's index, and the only helper whose DllMain reports thread events (on_host_thread_event | 262 | // The primary helper: slot 0's index, and the only helper whose DllMain reports thread events (on_host_thread_event |
| 254 | // covers every slot). Must be called with g_tls_alloc_mutex held and WITHOUT g_tls_lock held (LoadLibraryExW takes the | 263 | // covers every slot). Must be called with g_tls_alloc_mutex held and WITHOUT g_tls_lock held (LoadLibraryExW takes the |
| 255 | // Windows loader lock). | 264 | // Windows loader lock). |
| 265 | // A helper without the thread-event export is refused: no thread started later would get its copies. | ||
| 256 | bool ensure_primary_tls_host() { | 266 | bool ensure_primary_tls_host() { |
| 257 | if (g_tls_hosts[0].index != TLS_OUT_OF_INDEXES) return true; | 267 | if (g_tls_hosts[0].index != TLS_OUT_OF_INDEXES) return true; |
| 258 | const std::filesystem::path primary = tls_host_base_path(); | 268 | const std::filesystem::path primary = tls_host_base_path(); |
| 259 | if (primary.empty()) return false; | 269 | if (primary.empty()) return false; |
| 260 | g_tls_hosts[0] = load_tls_host_image(primary, true); | 270 | TlsHostModule host = load_tls_host_image(primary, true); |
| 261 | return g_tls_hosts[0].index != TLS_OUT_OF_INDEXES; | 271 | if (host.index != TLS_OUT_OF_INDEXES && !host.hooked) { |
| 272 | FreeLibrary(host.module); | ||
| 273 | return false; | ||
| 274 | } | ||
| 275 | g_tls_hosts[0] = host; | ||
| 276 | return host.index != TLS_OUT_OF_INDEXES; | ||
| 262 | } | 277 | } |
| 263 | 278 | ||
| 264 | // Copies gta6rt_tls_host.dll to "leonida_tls_host_<pid>_<tag>.dll" in the clone directory and loads it, so the OS | 279 | // Copies gta6rt_tls_host.dll (or writes `image`, a changed copy of it) to "leonida_tls_host_<pid>_<tag>.dll" in the |
| 265 | // gives the copy an index of its own. On failure the file is gone again and the result has no index. The caller | 280 | // clone directory and loads it, so the OS gives the copy an index of its own. On failure the file is gone again and |
| 266 | // records the clone (g_tls_clones) if it is to be freed at exit. Same locking rule as ensure_primary_tls_host. | 281 | // the result has no index. The caller records the clone (g_tls_clones) if it is to be freed at exit. Same locking rule |
| 267 | TlsHostModule load_tls_host_clone(const std::wstring& tag, std::filesystem::path& clone_path) { | 282 | // as ensure_primary_tls_host. |
| 283 | TlsHostModule load_tls_host_clone(const std::wstring& tag, std::filesystem::path& clone_path, | ||
| 284 | const std::vector<uint8_t>* image = nullptr) { | ||
| 268 | const std::filesystem::path primary = tls_host_base_path(); | 285 | const std::filesystem::path primary = tls_host_base_path(); |
| 269 | if (primary.empty()) return {}; | 286 | if (primary.empty()) return {}; |
| 270 | // Clone gta6rt_tls_host.dll to a distinct path using CopyFileW (Wine 9 lacks CopyFile2 used by std::filesystem). | 287 | // Clone gta6rt_tls_host.dll to a distinct path using CopyFileW (Wine 9 lacks CopyFile2 used by std::filesystem). |
| @@ -279,7 +296,21 @@ TlsHostModule load_tls_host_clone(const std::wstring& tag, std::filesystem::path | |||
| 279 | clone_path = dir / name; | 296 | clone_path = dir / name; |
| 280 | // The staging name must not match the sweep pattern, which only covers final clone names ending in .dll. | 297 | // The staging name must not match the sweep pattern, which only covers final clone names ending in .dll. |
| 281 | const std::filesystem::path staging = clone_path.wstring() + L".new"; | 298 | const std::filesystem::path staging = clone_path.wstring() + L".new"; |
| 282 | if (!CopyFileW(primary.c_str(), staging.c_str(), FALSE)) return {}; | 299 | if (image) { |
| 300 | HANDLE out = | ||
| 301 | CreateFileW(staging.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); | ||
| 302 | if (out == INVALID_HANDLE_VALUE) return {}; | ||
| 303 | DWORD written = 0; | ||
| 304 | const bool ok = WriteFile(out, image->data(), static_cast<DWORD>(image->size()), &written, nullptr) && | ||
| 305 | written == image->size(); | ||
| 306 | CloseHandle(out); | ||
| 307 | if (!ok) { | ||
| 308 | DeleteFileW(staging.c_str()); | ||
| 309 | return {}; | ||
| 310 | } | ||
| 311 | } else if (!CopyFileW(primary.c_str(), staging.c_str(), FALSE)) { | ||
| 312 | return {}; | ||
| 313 | } | ||
| 283 | 314 | ||
| 284 | // Open the guard before the clone exists under its final name and hold it across LoadLibraryExW: the rename | 315 | // Open the guard before the clone exists under its final name and hold it across LoadLibraryExW: the rename |
| 285 | // below needs DELETE access, which the handle's FILE_SHARE_DELETE grants, and no purge can remove the clone | 316 | // below needs DELETE access, which the handle's FILE_SHARE_DELETE grants, and no purge can remove the clone |
| @@ -314,7 +345,7 @@ TlsHostModule ensure_tls_host(size_t slot) { | |||
| 314 | std::filesystem::path clone_path; | 345 | std::filesystem::path clone_path; |
| 315 | TlsHostModule loaded = load_tls_host_clone(std::to_wstring(slot), clone_path); | 346 | TlsHostModule loaded = load_tls_host_clone(std::to_wstring(slot), clone_path); |
| 316 | if (loaded.index == TLS_OUT_OF_INDEXES) return {}; | 347 | if (loaded.index == TLS_OUT_OF_INDEXES) return {}; |
| 317 | // Index 0 is the runtime EXE's, and after the move the home clone's index holds that EXE's block. | 348 | // Index 0 is the runtime EXE's, and after the move the home clone's index holds that EXE's TLS. |
| 318 | bool taken = loaded.index == 0 || loaded.index == g_index0.home.index; | 349 | bool taken = loaded.index == 0 || loaded.index == g_index0.home.index; |
| 319 | for (size_t i = 0; i < kMaxMappedTlsModules; ++i) taken |= i != slot && g_tls_hosts[i].index == loaded.index; | 350 | for (size_t i = 0; i < kMaxMappedTlsModules; ++i) taken |= i != slot && g_tls_hosts[i].index == loaded.index; |
| 320 | if (taken) { | 351 | if (taken) { |
| @@ -340,8 +371,7 @@ thread_local std::array<ThreadTlsSlot, kTlsSlotCount> g_thread_tls_slots{}; | |||
| 340 | 371 | ||
| 341 | // Orders the TLS owners' publication, their `initialised` flags and their retirement against the thread events. Shared | 372 | // Orders the TLS owners' publication, their `initialised` flags and their retirement against the thread events. Shared |
| 342 | // in on_host_thread_event, exclusive only for those short writes (no allocation and no call that takes the Windows | 373 | // in on_host_thread_event, exclusive only for those short writes (no allocation and no call that takes the Windows |
| 343 | // loader lock, which the events run under) and for the one-time index-0 move, which lists and stops threads under it | 374 | // loader lock, which the events run under). |
| 344 | // with the loader lock already held. | ||
| 345 | SRWLOCK g_tls_lock = SRWLOCK_INIT; | 375 | SRWLOCK g_tls_lock = SRWLOCK_INIT; |
| 346 | struct SharedTlsLock { | 376 | struct SharedTlsLock { |
| 347 | SharedTlsLock() { AcquireSRWLockShared(&g_tls_lock); } | 377 | SharedTlsLock() { AcquireSRWLockShared(&g_tls_lock); } |
| @@ -356,19 +386,92 @@ struct ExclusiveTlsLock { | |||
| 356 | ExclusiveTlsLock& operator=(const ExclusiveTlsLock&) = delete; | 386 | ExclusiveTlsLock& operator=(const ExclusiveTlsLock&) = delete; |
| 357 | }; | 387 | }; |
| 358 | 388 | ||
| 359 | // x64 TEB fields the move reads and writes on other threads (the same offsets on Wine): ThreadLocalStoragePointer, | 389 | // gta6rt_tls_host.dll's exports that the home clone's TLS directory is pointed at (tls_host.cpp): a zero array in its |
| 360 | // and TlsSlots[64], the array TlsGetValue reads for an index below 64. | 390 | // .rdata and that array's size. |
| 361 | constexpr size_t kTebTlsPointer = 0x58; | 391 | constexpr char kHomeTemplateExport[] = "gta6rt_tls_home_template"; |
| 362 | constexpr size_t kTebTlsSlots = 0x1480; | 392 | constexpr char kHomeTemplateSizeExport[] = "gta6rt_tls_home_template_size"; |
| 363 | 393 | ||
| 364 | // The image that owns module TLS index 0: the one whose TLS directory's AddressOfIndex holds 0. Only images the | 394 | // File offset of `len` bytes at `rva` in an image file held in memory, or SIZE_MAX when they are not all inside one |
| 365 | // Windows loader mapped are listed, so their headers are read unchecked. | 395 | // section's raw data. |
| 366 | struct Index0Owner { | 396 | size_t file_offset(const std::vector<uint8_t>& file, const IMAGE_NT_HEADERS64* nt, uint64_t rva, uint64_t len) { |
| 367 | const uint8_t* base = nullptr; | 397 | const auto* sec = IMAGE_FIRST_SECTION(nt); |
| 368 | size_t size = 0; | 398 | for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++sec) { |
| 369 | DWORD* index = nullptr; // the owner's _tls_index | 399 | if (reinterpret_cast<const uint8_t*>(sec + 1) > file.data() + file.size()) break; |
| 370 | std::string name; // UTF-8 file name, for the trace and messages | 400 | if (rva < sec->VirtualAddress || rva + len > static_cast<uint64_t>(sec->VirtualAddress) + sec->SizeOfRawData) |
| 371 | }; | 401 | continue; |
| 402 | const uint64_t off = sec->PointerToRawData + (rva - sec->VirtualAddress); | ||
| 403 | return off + len <= file.size() ? static_cast<size_t>(off) : SIZE_MAX; | ||
| 404 | } | ||
| 405 | return SIZE_MAX; | ||
| 406 | } | ||
| 407 | |||
| 408 | // The RVA of a named export in an image file held in memory, 0 when it has none. | ||
| 409 | uint32_t file_export(const std::vector<uint8_t>& file, const IMAGE_NT_HEADERS64* nt, const char* wanted) { | ||
| 410 | const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_EXPORT); | ||
| 411 | const size_t ed_off = file_offset(file, nt, dir.VirtualAddress, sizeof(IMAGE_EXPORT_DIRECTORY)); | ||
| 412 | if (!dir.Size || ed_off == SIZE_MAX) return 0; | ||
| 413 | const auto* ed = reinterpret_cast<const IMAGE_EXPORT_DIRECTORY*>(file.data() + ed_off); | ||
| 414 | const size_t names = file_offset(file, nt, ed->AddressOfNames, uint64_t{4} * ed->NumberOfNames); | ||
| 415 | const size_t ords = file_offset(file, nt, ed->AddressOfNameOrdinals, uint64_t{2} * ed->NumberOfNames); | ||
| 416 | const size_t funcs = file_offset(file, nt, ed->AddressOfFunctions, uint64_t{4} * ed->NumberOfFunctions); | ||
| 417 | if (names == SIZE_MAX || ords == SIZE_MAX || funcs == SIZE_MAX) return 0; | ||
| 418 | const size_t wanted_len = std::strlen(wanted) + 1; | ||
| 419 | for (uint32_t i = 0; i < ed->NumberOfNames; ++i) { | ||
| 420 | uint32_t name_rva, func_rva; | ||
| 421 | uint16_t ord; | ||
| 422 | std::memcpy(&name_rva, file.data() + names + 4 * i, 4); | ||
| 423 | std::memcpy(&ord, file.data() + ords + 2 * i, 2); | ||
| 424 | const size_t name = file_offset(file, nt, name_rva, wanted_len); | ||
| 425 | if (name == SIZE_MAX || std::memcmp(file.data() + name, wanted, wanted_len) != 0) continue; | ||
| 426 | if (ord >= ed->NumberOfFunctions) return 0; | ||
| 427 | std::memcpy(&func_rva, file.data() + funcs + 4 * ord, 4); | ||
| 428 | return func_rva; | ||
| 429 | } | ||
| 430 | return 0; | ||
| 431 | } | ||
| 432 | |||
| 433 | // Turns gta6rt_tls_host.dll's bytes into the home clone: its TLS directory now covers gta6rt_tls_home_template, which | ||
| 434 | // starts with a copy of the owner's template (taken from the mapped owner, so its pointers are already relocated; the | ||
| 435 | // array itself has no relocations), and takes the owner's alignment. The OS then gives every thread, at the home | ||
| 436 | // index, a block that is a fresh copy of the owner's TLS. The zero fill goes into the covered range too: | ||
| 437 | // LdrpAllocateTls allocates and copies End - Start only (Windows 11 26300) and ignores SizeOfZeroFill. The directory's | ||
| 438 | // Start and End have base relocations, so they follow the clone wherever it loads. Empty on success, else why not. | ||
| 439 | std::string make_home_clone_image(std::vector<uint8_t>& file, const IMAGE_TLS_DIRECTORY64& owner) { | ||
| 440 | if (file.size() < sizeof(IMAGE_DOS_HEADER)) return "gta6rt_tls_host.dll is truncated"; | ||
| 441 | const auto* dos = reinterpret_cast<const IMAGE_DOS_HEADER*>(file.data()); | ||
| 442 | if (dos->e_magic != IMAGE_DOS_SIGNATURE || dos->e_lfanew < 0 || | ||
| 443 | static_cast<size_t>(dos->e_lfanew) + sizeof(IMAGE_NT_HEADERS64) > file.size()) | ||
| 444 | return "gta6rt_tls_host.dll has no PE header"; | ||
| 445 | auto* nt = reinterpret_cast<IMAGE_NT_HEADERS64*>(file.data() + dos->e_lfanew); | ||
| 446 | if (nt->Signature != IMAGE_NT_SIGNATURE || nt->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR64_MAGIC) | ||
| 447 | return "gta6rt_tls_host.dll is not a 64-bit image"; | ||
| 448 | const uint32_t array_rva = file_export(file, nt, kHomeTemplateExport); | ||
| 449 | const uint32_t size_rva = file_export(file, nt, kHomeTemplateSizeExport); | ||
| 450 | const size_t size_off = file_offset(file, nt, size_rva, sizeof(uint32_t)); | ||
| 451 | if (!array_rva || !size_rva || size_off == SIZE_MAX) | ||
| 452 | return "gta6rt_tls_host.dll has no gta6rt_tls_home_template"; | ||
| 453 | uint32_t capacity; | ||
| 454 | std::memcpy(&capacity, file.data() + size_off, sizeof(capacity)); | ||
| 455 | const uint64_t raw = owner.EndAddressOfRawData - owner.StartAddressOfRawData; | ||
| 456 | const uint64_t total = raw + owner.SizeOfZeroFill; | ||
| 457 | if (owner.EndAddressOfRawData < owner.StartAddressOfRawData || total > capacity) | ||
| 458 | return "the owner's TLS (" + std::to_string(total) + " bytes) does not fit gta6rt_tls_home_template (" + | ||
| 459 | std::to_string(capacity) + " bytes)"; | ||
| 460 | const size_t array_off = file_offset(file, nt, array_rva, capacity); | ||
| 461 | const auto tls_dir = directory(nt, IMAGE_DIRECTORY_ENTRY_TLS); | ||
| 462 | const size_t tls_off = file_offset(file, nt, tls_dir.VirtualAddress, sizeof(IMAGE_TLS_DIRECTORY64)); | ||
| 463 | if (array_off == SIZE_MAX || !tls_dir.Size || tls_off == SIZE_MAX) | ||
| 464 | return "gta6rt_tls_host.dll's TLS directory or home template lies outside its file"; | ||
| 465 | std::memcpy(file.data() + array_off, reinterpret_cast<const void*>(owner.StartAddressOfRawData), raw); | ||
| 466 | std::memset(file.data() + array_off + raw, 0, capacity - raw); | ||
| 467 | auto* tls = reinterpret_cast<IMAGE_TLS_DIRECTORY64*>(file.data() + tls_off); | ||
| 468 | tls->StartAddressOfRawData = nt->OptionalHeader.ImageBase + array_rva; | ||
| 469 | tls->EndAddressOfRawData = tls->StartAddressOfRawData + total; | ||
| 470 | tls->SizeOfZeroFill = 0; | ||
| 471 | tls->Characteristics = | ||
| 472 | (tls->Characteristics & ~IMAGE_SCN_ALIGN_MASK) | (owner.Characteristics & IMAGE_SCN_ALIGN_MASK); | ||
| 473 | return {}; | ||
| 474 | } | ||
| 372 | 475 | ||
| 373 | std::string module_file_name(HMODULE module) { | 476 | std::string module_file_name(HMODULE module) { |
| 374 | wchar_t path[MAX_PATH]; | 477 | wchar_t path[MAX_PATH]; |
| @@ -384,243 +487,77 @@ std::string module_file_name(HMODULE module) { | |||
| 384 | return out; | 487 | return out; |
| 385 | } | 488 | } |
| 386 | 489 | ||
| 387 | // Empty on success, else why index 0 has no single movable owner. | 490 | // The move on the calling thread, kept apart so that no frame of reserve_index0 holds a slot address across it. After |
| 388 | std::string find_index0_owner(Index0Owner& owner) { | 491 | // it the owner's live block is at `home` and slot 0 holds the home clone's fresh copy, which nothing reads. |
| 389 | std::vector<HMODULE> modules(256); | 492 | __declspec(noinline) void move_index0_on_this_thread(DWORD* owner_index, DWORD home) { |
| 390 | DWORD needed = 0; | 493 | void** slots = module_tls_slots(); |
| 391 | for (;;) { | 494 | std::swap(slots[0], slots[home]); |
| 392 | const DWORD bytes = static_cast<DWORD>(modules.size() * sizeof(HMODULE)); | 495 | *owner_index = home; |
| 393 | if (!EnumProcessModules(GetCurrentProcess(), modules.data(), bytes, &needed)) | ||
| 394 | return "the process's modules cannot be listed"; | ||
| 395 | if (needed <= bytes) break; | ||
| 396 | modules.resize(needed / sizeof(HMODULE) + 16); // a DLL loaded in between needs room too | ||
| 397 | } | ||
| 398 | modules.resize(needed / sizeof(HMODULE)); | ||
| 399 | int found = 0; | ||
| 400 | HMODULE owner_module = nullptr; | ||
| 401 | for (HMODULE module : modules) { | ||
| 402 | auto* base = reinterpret_cast<uint8_t*>(module); | ||
| 403 | auto* nt = at<IMAGE_NT_HEADERS64>(base, reinterpret_cast<IMAGE_DOS_HEADER*>(base)->e_lfanew); | ||
| 404 | const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_TLS); | ||
| 405 | if (!dir.Size || !dir.VirtualAddress) continue; | ||
| 406 | auto* tls = at<IMAGE_TLS_DIRECTORY64>(base, dir.VirtualAddress); | ||
| 407 | if (!tls->AddressOfIndex || *reinterpret_cast<DWORD*>(tls->AddressOfIndex) != 0) continue; | ||
| 408 | ++found; | ||
| 409 | owner_module = module; | ||
| 410 | owner.base = base; | ||
| 411 | owner.size = nt->OptionalHeader.SizeOfImage; | ||
| 412 | owner.index = reinterpret_cast<DWORD*>(tls->AddressOfIndex); | ||
| 413 | } | ||
| 414 | if (found == 0) return "no module holds it"; | ||
| 415 | if (found > 1) return "more than one module reports it"; | ||
| 416 | owner.name = module_file_name(owner_module); | ||
| 417 | // The helpers are loaded after the EXE, so one of them holds index 0 only in a process whose EXE has no TLS; DLL | ||
| 418 | // slot 0 then already maps DLLs there. | ||
| 419 | for (const auto& host : g_tls_hosts) | ||
| 420 | if (host.module == owner_module) return "it belongs to gta6rt_tls_host.dll"; | ||
| 421 | return {}; | ||
| 422 | } | 496 | } |
| 423 | 497 | ||
| 424 | using NtQueryInformationThreadFn = LONG(NTAPI*)(HANDLE, int, PVOID, ULONG, PULONG); | 498 | // See reserve_tls_index0. Empty on success, else why not; nothing has changed then. g_tls_alloc_mutex held. It reads |
| 425 | using LdrLockLoaderLockFn = LONG(NTAPI*)(ULONG, ULONG*, ULONG_PTR*); | 499 | // no thread_local data and runs no code that does, before or after the move. |
| 426 | using LdrUnlockLoaderLockFn = LONG(NTAPI*)(ULONG, ULONG_PTR); | 500 | std::string reserve_index0() { |
| 427 | 501 | // Windows gives index 0 to the process executable when it has TLS; a DLL can only hold it in a process whose EXE | |
| 428 | struct ThreadBasicInformation { // THREAD_BASIC_INFORMATION (NtQueryInformationThread class 0) | 502 | // has none, and a DLL that is still loading or was loaded without its references resolved shows 0 too. |
| 429 | LONG exit_status; | 503 | const HMODULE exe = GetModuleHandleW(nullptr); |
| 430 | PVOID teb; | 504 | auto* base = reinterpret_cast<uint8_t*>(exe); |
| 431 | PVOID process_id; | 505 | auto* nt = at<IMAGE_NT_HEADERS64>(base, reinterpret_cast<IMAGE_DOS_HEADER*>(base)->e_lfanew); |
| 432 | PVOID thread_id; | 506 | const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_TLS); |
| 433 | ULONG_PTR affinity; | 507 | if (!dir.Size || !dir.VirtualAddress) return "the process executable has no TLS, so index 0 is not its"; |
| 434 | LONG priority; | 508 | const IMAGE_TLS_DIRECTORY64 owner = *at<IMAGE_TLS_DIRECTORY64>(base, dir.VirtualAddress); |
| 435 | LONG base_priority; | 509 | auto* owner_index = reinterpret_cast<DWORD*>(owner.AddressOfIndex); |
| 436 | }; | 510 | if (!owner_index) return "the process executable's TLS directory has no index"; |
| 437 | 511 | if (*owner_index != 0) return "the process executable's _tls_index is " + std::to_string(*owner_index) + ", not 0"; | |
| 438 | struct OtherThread { | 512 | if (!module_tls_slots()) return "this thread has no TLS array"; |
| 439 | HANDLE handle = nullptr; | 513 | if (!ensure_primary_tls_host()) |
| 440 | uint8_t* teb = nullptr; | 514 | return "gta6rt_tls_host.dll is missing, has no module TLS index or lacks gta6rt_tls_host_set_thread_event"; |
| 441 | bool suspended = false; | 515 | |
| 442 | }; | 516 | std::vector<uint8_t> image; |
| 443 | 517 | try { | |
| 444 | enum class SwapResult { Done, Busy, Failed }; | 518 | image = read_file(tls_host_base_path()); |
| 445 | 519 | } catch (const std::exception& e) { | |
| 446 | // One attempt at the swap, with every other thread of the process stopped. The exclusive g_tls_lock keeps every | 520 | return e.what(); |
| 447 | // thread event out, and with it the adoption on threads that start meanwhile. Busy: a thread was stopped inside the | ||
| 448 | // owner's code, perhaps between its load of _tls_index and its read of the slot, so the caller resumes everything and | ||
| 449 | // tries again. Measured in ntdll (Windows 11 26300): a starting thread fills its whole TLS array before it stores it in | ||
| 450 | // its TEB (LdrpAllocateTls), an ending one clears that TEB field before it frees the blocks (LdrpFreeTls), and | ||
| 451 | // LoadLibrary of a DLL with TLS has the kernel update every thread's array in one system call (NtSetInformationProcess, | ||
| 452 | // class 0x23), which GetThreadContext below waits out on the calling thread. So an array seen here is complete and | ||
| 453 | // still owned; a thread with none yet gets one with the owner's block at 0 and adopts the swap in DLL_THREAD_ATTACH. | ||
| 454 | // Wine builds a starting thread's array and grows every thread's array for LoadLibrary in user mode, both under its | ||
| 455 | // loader lock, so the Windows loader lock is held as well; it comes before g_tls_lock, the order the thread events | ||
| 456 | // (run under it) take them in. | ||
| 457 | SwapResult swap_index0_on_all_threads(const Index0Owner& owner, DWORD home, DWORD mark, std::string& error) { | ||
| 458 | static const HMODULE ntdll = GetModuleHandleW(L"ntdll.dll"); | ||
| 459 | static const auto query = | ||
| 460 | reinterpret_cast<NtQueryInformationThreadFn>(GetProcAddress(ntdll, "NtQueryInformationThread")); | ||
| 461 | static const auto lock_loader = reinterpret_cast<LdrLockLoaderLockFn>(GetProcAddress(ntdll, "LdrLockLoaderLock")); | ||
| 462 | static const auto unlock_loader = | ||
| 463 | reinterpret_cast<LdrUnlockLoaderLockFn>(GetProcAddress(ntdll, "LdrUnlockLoaderLock")); | ||
| 464 | if (!query || !lock_loader || !unlock_loader) { | ||
| 465 | error = "ntdll lacks NtQueryInformationThread or the loader lock calls"; | ||
| 466 | return SwapResult::Failed; | ||
| 467 | } | ||
| 468 | ULONG disposition = 0; | ||
| 469 | ULONG_PTR cookie = 0; | ||
| 470 | if (lock_loader(0, &disposition, &cookie) < 0) { | ||
| 471 | error = "the Windows loader lock cannot be taken"; | ||
| 472 | return SwapResult::Failed; | ||
| 473 | } | ||
| 474 | struct LoaderUnlock { | ||
| 475 | ULONG_PTR cookie; | ||
| 476 | ~LoaderUnlock() { unlock_loader(0, cookie); } | ||
| 477 | } loader_unlock{cookie}; | ||
| 478 | ExclusiveTlsLock lock; | ||
| 479 | |||
| 480 | // Listed under the lock: a thread that starts later runs its DLL_THREAD_ATTACH after the swap and adopts it there | ||
| 481 | // (adopt_index0_move_on_this_thread). | ||
| 482 | std::vector<OtherThread> threads; | ||
| 483 | { | ||
| 484 | HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); | ||
| 485 | if (snapshot == INVALID_HANDLE_VALUE) { | ||
| 486 | error = "the process's threads cannot be listed"; | ||
| 487 | return SwapResult::Failed; | ||
| 488 | } | ||
| 489 | THREADENTRY32 entry{}; | ||
| 490 | entry.dwSize = sizeof(entry); | ||
| 491 | const DWORD pid = GetCurrentProcessId(), self = GetCurrentThreadId(); | ||
| 492 | for (BOOL more = Thread32First(snapshot, &entry); more; more = Thread32Next(snapshot, &entry)) { | ||
| 493 | if (entry.th32OwnerProcessID != pid || entry.th32ThreadID == self) continue; | ||
| 494 | HANDLE h = OpenThread(THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION | SYNCHRONIZE, | ||
| 495 | FALSE, entry.th32ThreadID); | ||
| 496 | if (!h) continue; // ended since the snapshot | ||
| 497 | ThreadBasicInformation info{}; | ||
| 498 | if (query(h, 0, &info, sizeof(info), nullptr) < 0 || !info.teb) { | ||
| 499 | CloseHandle(h); | ||
| 500 | continue; | ||
| 501 | } | ||
| 502 | threads.push_back({h, static_cast<uint8_t*>(info.teb)}); | ||
| 503 | } | ||
| 504 | CloseHandle(snapshot); | ||
| 505 | } | ||
| 506 | |||
| 507 | // From the first SuspendThread to the last ResumeThread nothing below allocates or takes a lock: a stopped thread | ||
| 508 | // can hold the heap lock. | ||
| 509 | bool busy = false; | ||
| 510 | for (auto& t : threads) { | ||
| 511 | if (SuspendThread(t.handle) == static_cast<DWORD>(-1)) { | ||
| 512 | if (WaitForSingleObject(t.handle, 0) == WAIT_OBJECT_0) continue; // it ended; its TEB is gone | ||
| 513 | busy = true; // a live thread left unswapped would read the helper's block for the owner's | ||
| 514 | break; | ||
| 515 | } | ||
| 516 | t.suspended = true; | ||
| 517 | // SuspendThread only asks; GetThreadContext returns once the thread has stopped. | ||
| 518 | CONTEXT context{}; | ||
| 519 | context.ContextFlags = CONTEXT_CONTROL; | ||
| 520 | if (!GetThreadContext(t.handle, &context)) { | ||
| 521 | if (WaitForSingleObject(t.handle, 0) == WAIT_OBJECT_0) continue; // it ended; its TEB is gone | ||
| 522 | busy = true; | ||
| 523 | break; | ||
| 524 | } | ||
| 525 | if (context.Rip - reinterpret_cast<uint64_t>(owner.base) < owner.size) { | ||
| 526 | busy = true; | ||
| 527 | break; | ||
| 528 | } | ||
| 529 | } | ||
| 530 | if (!busy) { | ||
| 531 | for (auto& t : threads) { | ||
| 532 | if (!t.suspended || WaitForSingleObject(t.handle, 0) == WAIT_OBJECT_0) continue; | ||
| 533 | // No array yet: the thread is still starting, and its DLL_THREAD_ATTACH adopts the swap. | ||
| 534 | auto** slots = *reinterpret_cast<void***>(t.teb + kTebTlsPointer); | ||
| 535 | if (!slots) continue; | ||
| 536 | std::swap(slots[0], slots[home]); | ||
| 537 | reinterpret_cast<void**>(t.teb + kTebTlsSlots)[mark] = reinterpret_cast<void*>(1); | ||
| 538 | } | ||
| 539 | // The owner's code reads the new index from here on, this thread's included. | ||
| 540 | void** own = module_tls_slots(); | ||
| 541 | std::swap(own[0], own[home]); | ||
| 542 | TlsSetValue(mark, reinterpret_cast<void*>(1)); | ||
| 543 | *owner.index = home; | ||
| 544 | g_index0.moved = true; | ||
| 545 | } | ||
| 546 | for (auto& t : threads) { | ||
| 547 | if (t.suspended) ResumeThread(t.handle); | ||
| 548 | CloseHandle(t.handle); | ||
| 549 | } | 521 | } |
| 550 | return busy ? SwapResult::Busy : SwapResult::Done; | 522 | if (std::string why = make_home_clone_image(image, owner); !why.empty()) return why; |
| 551 | } | 523 | std::filesystem::path path; |
| 524 | const TlsHostModule home = load_tls_host_clone(L"home", path, &image); | ||
| 525 | if (home.index == TLS_OUT_OF_INDEXES) return "the home clone of gta6rt_tls_host.dll cannot be loaded"; | ||
| 526 | auto drop = [&](std::string why) { | ||
| 527 | FreeLibrary(home.module); // safe until the move below: nothing lives at its index yet | ||
| 528 | DeleteFileW(path.c_str()); | ||
| 529 | return why; | ||
| 530 | }; | ||
| 531 | bool taken = home.index == 0 || home.index >= kMaxModuleTlsSlots; | ||
| 532 | for (const auto& host : g_tls_hosts) taken |= host.index == home.index; | ||
| 533 | if (taken) return drop("the home clone got an unusable module TLS index"); | ||
| 534 | // The OS must have taken the changed directory: the mapped clone's template is the owner's, at full size. | ||
| 535 | auto* home_base = reinterpret_cast<uint8_t*>(home.module); | ||
| 536 | auto* home_nt = at<IMAGE_NT_HEADERS64>(home_base, reinterpret_cast<IMAGE_DOS_HEADER*>(home_base)->e_lfanew); | ||
| 537 | const auto* home_tls = | ||
| 538 | at<IMAGE_TLS_DIRECTORY64>(home_base, directory(home_nt, IMAGE_DIRECTORY_ENTRY_TLS).VirtualAddress); | ||
| 539 | const uint64_t raw = owner.EndAddressOfRawData - owner.StartAddressOfRawData; | ||
| 540 | if (home_tls->EndAddressOfRawData - home_tls->StartAddressOfRawData != raw + owner.SizeOfZeroFill || | ||
| 541 | std::memcmp(reinterpret_cast<const void*>(home_tls->StartAddressOfRawData), | ||
| 542 | reinterpret_cast<const void*>(owner.StartAddressOfRawData), raw) != 0) | ||
| 543 | return drop("the home clone's mapped TLS template is not the owner's"); | ||
| 552 | 544 | ||
| 553 | // Frees module TLS index 0 for a mapped executable (see kMainImageSlot): loads the home clone, then swaps slots 0 | ||
| 554 | // and home on every thread and writes home into the owner's _tls_index. Empty on success (also when it was done | ||
| 555 | // before), else why not; nothing has changed then. Must be called with g_tls_alloc_mutex held and WITHOUT g_tls_lock | ||
| 556 | // held. Never inlined, so the caller reads its own thread_local data through the new index once this returns. | ||
| 557 | __declspec(noinline) std::string move_index0_owner() { | ||
| 558 | if (g_index0.moved) return {}; | ||
| 559 | if (!ensure_primary_tls_host()) return "gta6rt_tls_host.dll is missing or has no module TLS index"; | ||
| 560 | Index0Owner owner; | ||
| 561 | if (std::string why = find_index0_owner(owner); !why.empty()) return "module TLS index 0: " + why; | ||
| 562 | if (g_index0.home.index == TLS_OUT_OF_INDEXES) { | ||
| 563 | // Kept loaded for the process lifetime: FreeLibrary would make the OS free every thread's slot at its index, | ||
| 564 | // which holds the owner's block from now on. Not in g_tls_clones for that reason; the sweep of a later run | ||
| 565 | // deletes the file once this process has ended. | ||
| 566 | std::filesystem::path path; | ||
| 567 | TlsHostModule home = load_tls_host_clone(L"home", path); | ||
| 568 | if (home.index == TLS_OUT_OF_INDEXES) return "the TLS helper clone for index 0 cannot be loaded"; | ||
| 569 | bool taken = home.index == 0 || home.index >= kMaxModuleTlsSlots; | ||
| 570 | for (const auto& host : g_tls_hosts) taken |= host.index == home.index; | ||
| 571 | if (taken) { | ||
| 572 | FreeLibrary(home.module); | ||
| 573 | DeleteFileW(path.c_str()); | ||
| 574 | return "the TLS helper clone for index 0 got an unusable index"; | ||
| 575 | } | ||
| 576 | g_index0.home = home; | ||
| 577 | } | ||
| 578 | if (g_index0.mark == TLS_OUT_OF_INDEXES) { | ||
| 579 | const DWORD mark = TlsAlloc(); | ||
| 580 | if (mark == TLS_OUT_OF_INDEXES) return "no TlsAlloc slot is free"; | ||
| 581 | if (mark >= 64) { // another thread's TlsSlots can only be written for the first 64 | ||
| 582 | TlsFree(mark); | ||
| 583 | return "no TlsAlloc slot below 64 is free"; | ||
| 584 | } | ||
| 585 | g_index0.mark = mark; | ||
| 586 | } | ||
| 587 | // _tls_index sits in .data; made writable first in case a linker merged it into a read-only section. | 545 | // _tls_index sits in .data; made writable first in case a linker merged it into a read-only section. |
| 588 | DWORD old_protect = 0; | 546 | DWORD old_protect = 0; |
| 589 | if (!VirtualProtect(owner.index, sizeof(DWORD), PAGE_READWRITE, &old_protect)) | 547 | if (!VirtualProtect(owner_index, sizeof(DWORD), PAGE_READWRITE, &old_protect)) |
| 590 | return "the owner's _tls_index cannot be written"; | 548 | return drop("the owner's _tls_index cannot be written"); |
| 591 | // A thread caught in the owner's code usually leaves it within microseconds; one that keeps computing there for | 549 | move_index0_on_this_thread(owner_index, home.index); |
| 592 | // the whole budget makes the move give up (the executable then maps with a helper index), and a later executable | 550 | VirtualProtect(owner_index, sizeof(DWORD), old_protect, &old_protect); |
| 593 | // tries again. | 551 | |
| 594 | std::string error; | 552 | // Kept loaded for the process lifetime: FreeLibrary would make the OS free every thread's block at its index, the |
| 595 | SwapResult result = SwapResult::Busy; | 553 | // owner's from now on. Not in g_tls_clones for that reason; a later run's sweep deletes the file. |
| 596 | const ULONGLONG give_up = GetTickCount64() + 250; | 554 | g_index0.home = home; |
| 597 | for (bool first = true; result == SwapResult::Busy && (first || GetTickCount64() < give_up); first = false) { | 555 | const std::string name = module_file_name(exe); |
| 598 | if (!first) Sleep(1); | 556 | std::snprintf(g_index0.owner, sizeof(g_index0.owner), "%s", name.c_str()); |
| 599 | result = swap_index0_on_all_threads(owner, g_index0.home.index, g_index0.mark, error); | 557 | g_index0.moved = true; |
| 600 | } | ||
| 601 | VirtualProtect(owner.index, sizeof(DWORD), old_protect, &old_protect); | ||
| 602 | if (result == SwapResult::Busy) return "a thread kept running inside " + owner.name; | ||
| 603 | if (result == SwapResult::Failed) return error; | ||
| 604 | if (startup_trace::enabled()) | ||
| 605 | startup_trace::event("tls_index0", "\"owner\":" + startup_trace::quote(owner.name) + | ||
| 606 | ",\"moved_to\":" + std::to_string(g_index0.home.index)); | ||
| 607 | return {}; | 558 | return {}; |
| 608 | } | 559 | } |
| 609 | 560 | ||
| 610 | // Puts a thread started after the move in the same state as the threads the move swapped. Called first in this | ||
| 611 | // thread's DLL_THREAD_ATTACH, under the shared lock, before anything reads the runtime's own thread_local data: the | ||
| 612 | // OS built this thread's array with the owner's block at 0 and the home clone's at home. DLLs loaded before the | ||
| 613 | // helper get their DLL_THREAD_ATTACH earlier, and the EXE's TLS callbacks run later (measured on Windows 11 26300: | ||
| 614 | // DllMain of every DLL, then the EXE's callbacks, for attach and for detach), so only runtime code a vectored | ||
| 615 | // exception handler runs in that window would read the home clone's block in place of its own. | ||
| 616 | void adopt_index0_move_on_this_thread() { | ||
| 617 | if (!g_index0.moved || TlsGetValue(g_index0.mark)) return; | ||
| 618 | void** slots = module_tls_slots(); | ||
| 619 | if (!slots) return; | ||
| 620 | std::swap(slots[0], slots[g_index0.home.index]); | ||
| 621 | TlsSetValue(g_index0.mark, reinterpret_cast<void*>(1)); | ||
| 622 | } | ||
| 623 | |||
| 624 | // Puts the helper DLL's own block back in this thread's slot and frees the copy that replaced it. Uses only this | 561 | // Puts the helper DLL's own block back in this thread's slot and frees the copy that replaced it. Uses only this |
| 625 | // thread's record, so it also works after the module that installed the copy is gone. | 562 | // thread's record, so it also works after the module that installed the copy is gone. |
| 626 | void release_thread_slot(size_t slot) { | 563 | void release_thread_slot(size_t slot) { |
| @@ -711,24 +648,38 @@ void run_callbacks(Module& m, uint32_t reason, bool trace = false) { | |||
| 711 | } | 648 | } |
| 712 | } | 649 | } |
| 713 | 650 | ||
| 714 | // The body of on_host_thread_event, called with the shared lock held. A new thread gets its own copy of each active | 651 | // Runs in gta6rt_tls_host.dll's DllMain for each thread the process starts or ends once the helper is loaded, under |
| 715 | // TLS owner's template; an ending one gives each helper's block back before the Windows loader frees it. TLS callbacks | 652 | // the Windows loader lock, on that thread. A new thread gets its own copy of each active TLS owner's template; an |
| 716 | // get the thread events only after the module's DLL_PROCESS_ATTACH (initialise()), as the Windows loader orders them. | 653 | // ending one gives each helper's block back before the Windows loader frees it. TLS callbacks get the thread events |
| 717 | // The mapped executable comes last both ways, as Windows runs an EXE's TLS callbacks after every DllMain for attach | 654 | // only after the module's DLL_PROCESS_ATTACH (initialise()), as the Windows loader orders them. Windows allocates |
| 718 | // and for detach (measured on Windows 11 26300); kMainImageSlot is the highest slot, so attach runs in slot order and | 655 | // every module's block before the first DllMain of a new thread, and runs an EXE's TLS callbacks after every DllMain, |
| 719 | // detach runs the DLL slots in reverse and that slot after them. | 656 | // for attach and for detach (measured on Windows 11 26300). So attach installs all copies first and then runs the |
| 720 | __declspec(noinline) void deliver_thread_event(DWORD reason) { | 657 | // callbacks, the DLL slots in order and the executable's last; detach runs the DLL slots in reverse and then the |
| 658 | // executable's slot, each releasing its copy after its callbacks. | ||
| 659 | void __cdecl on_host_thread_event(DWORD reason) { | ||
| 660 | SharedTlsLock lock; | ||
| 721 | // The try/catch is per slot: a throw from one module's install or callbacks must not take the thread events | 661 | // The try/catch is per slot: a throw from one module's install or callbacks must not take the thread events |
| 722 | // away from the other slots. Nothing may leave DllMain. | 662 | // away from the other slots. Nothing may leave DllMain. |
| 723 | if (reason == DLL_THREAD_ATTACH) { | 663 | if (reason == DLL_THREAD_ATTACH) { |
| 664 | std::array<Module*, kTlsSlotCount> installed{}; | ||
| 724 | for (size_t slot = 0; slot < kTlsSlotCount; ++slot) { | 665 | for (size_t slot = 0; slot < kTlsSlotCount; ++slot) { |
| 725 | Module* m = g_tls_slot_owners[slot].load(); | 666 | Module* m = g_tls_slot_owners[slot].load(); |
| 726 | if (!m) continue; | 667 | if (!m) continue; |
| 727 | try { | 668 | try { |
| 728 | install_thread_block(*m); | 669 | install_thread_block(*m); |
| 729 | if (m->initialised) run_callbacks(*m, DLL_THREAD_ATTACH); | 670 | installed[slot] = m; |
| 671 | } catch (const std::exception& e) { | ||
| 672 | // The thread runs on without this module's TLS (and its callbacks); later slots still get theirs. | ||
| 673 | std::fprintf(stderr, "[rt] loader: thread attach, slot %zu (%s): %s\n", slot, m->name.c_str(), | ||
| 674 | e.what()); | ||
| 675 | } | ||
| 676 | } | ||
| 677 | for (size_t slot = 0; slot < kTlsSlotCount; ++slot) { | ||
| 678 | Module* m = installed[slot]; | ||
| 679 | if (!m || !m->initialised) continue; | ||
| 680 | try { | ||
| 681 | run_callbacks(*m, DLL_THREAD_ATTACH); | ||
| 730 | } catch (const std::exception& e) { | 682 | } catch (const std::exception& e) { |
| 731 | // The thread runs on without this module's TLS; later slots still get theirs. | ||
| 732 | std::fprintf(stderr, "[rt] loader: thread attach, slot %zu (%s): %s\n", slot, m->name.c_str(), | 683 | std::fprintf(stderr, "[rt] loader: thread attach, slot %zu (%s): %s\n", slot, m->name.c_str(), |
| 733 | e.what()); | 684 | e.what()); |
| 734 | } | 685 | } |
| @@ -755,15 +706,6 @@ __declspec(noinline) void deliver_thread_event(DWORD reason) { | |||
| 755 | } | 706 | } |
| 756 | } | 707 | } |
| 757 | 708 | ||
| 758 | // Runs in gta6rt_tls_host.dll's DllMain for each thread the process starts or ends once the helper is loaded, under | ||
| 759 | // the Windows loader lock, on that thread. It reads no thread_local data itself: on a new thread the index-0 move has | ||
| 760 | // to be adopted before the runtime's own TLS is where its _tls_index says (deliver_thread_event is not inlined). | ||
| 761 | void __cdecl on_host_thread_event(DWORD reason) { | ||
| 762 | SharedTlsLock lock; | ||
| 763 | if (reason == DLL_THREAD_ATTACH) adopt_index0_move_on_this_thread(); | ||
| 764 | deliver_thread_event(reason); | ||
| 765 | } | ||
| 766 | |||
| 767 | // The Xbox builds of the MSVC runtime import the same CRT the desktop does, so the host's own copies are used. | 709 | // The Xbox builds of the MSVC runtime import the same CRT the desktop does, so the host's own copies are used. |
| 768 | bool prefer_host_copy(const std::string& dll) { | 710 | bool prefer_host_copy(const std::string& dll) { |
| 769 | static const char* names[] = {"vcruntime140.dll", "vcruntime140_1.dll", "msvcp140.dll", "msvcp140_1.dll", | 711 | static const char* names[] = {"vcruntime140.dll", "vcruntime140_1.dll", "msvcp140.dll", "msvcp140_1.dll", |
| @@ -842,6 +784,18 @@ void redirect_pc_to_file_header_at(const void* resolved) { | |||
| 842 | // Declared in pe_loader.h; the body needs the internal clone registry above. | 784 | // Declared in pe_loader.h; the body needs the internal clone registry above. |
| 843 | void cleanup_tls_clones() { cleanup_tls_clones_internal(); } | 785 | void cleanup_tls_clones() { cleanup_tls_clones_internal(); } |
| 844 | 786 | ||
| 787 | bool reserve_tls_index0(std::string* why) { | ||
| 788 | std::lock_guard alloc_lock(g_tls_alloc_mutex); | ||
| 789 | static bool attempted = false; // once: a later attempt could meet threads that already run this EXE's code | ||
| 790 | if (!attempted) { | ||
| 791 | attempted = true; | ||
| 792 | const std::string reason = reserve_index0(); | ||
| 793 | std::snprintf(g_index0.why, sizeof(g_index0.why), "%s", reason.c_str()); | ||
| 794 | } | ||
| 795 | if (why) *why = g_index0.moved ? std::string() : std::string(g_index0.why); | ||
| 796 | return g_index0.moved; | ||
| 797 | } | ||
| 798 | |||
| 845 | namespace { | 799 | namespace { |
| 846 | bool lookup_in_loader(void* ctx, uint64_t address, std::string& module, uint32_t& rva) { | 800 | bool lookup_in_loader(void* ctx, uint64_t address, std::string& module, uint32_t& rva) { |
| 847 | for (const Module* m : static_cast<Loader*>(ctx)->modules()) { | 801 | for (const Module* m : static_cast<Loader*>(ctx)->modules()) { |
| @@ -1261,18 +1215,22 @@ void Loader::initialize_tls(Module& m) { | |||
| 1261 | { | 1215 | { |
| 1262 | std::lock_guard alloc_lock(g_tls_alloc_mutex); | 1216 | std::lock_guard alloc_lock(g_tls_alloc_mutex); |
| 1263 | if (executable) { | 1217 | if (executable) { |
| 1264 | // Load/clone OUTSIDE ExclusiveTlsLock, as below; the move takes that lock itself. | 1218 | if (g_index0.moved && g_tls_slot_owners[kMainImageSlot].load() == nullptr) { |
| 1265 | std::string why = move_index0_owner(); | ||
| 1266 | if (why.empty() && g_tls_slot_owners[kMainImageSlot].load() == nullptr) { | ||
| 1267 | slot = kMainImageSlot; | 1219 | slot = kMainImageSlot; |
| 1268 | index = 0; | 1220 | index = 0; |
| 1221 | if (!g_index0.traced && startup_trace::enabled()) { | ||
| 1222 | g_index0.traced = true; | ||
| 1223 | startup_trace::event("tls_index0", "\"owner\":" + startup_trace::quote(g_index0.owner) + | ||
| 1224 | ",\"moved_to\":" + std::to_string(g_index0.home.index)); | ||
| 1225 | } | ||
| 1269 | } else { | 1226 | } else { |
| 1270 | // Mapped on as a DLL is: code that reads _tls_index works, /GA code reads another image's slot 0. | 1227 | // Mapped on as a DLL is: its code that reads _tls_index works, but its /GA code would read and write |
| 1271 | if (why.empty()) why = "another mapped executable holds it"; | 1228 | // the block in slot 0, which is the runtime's own TLS or the other executable's. gta6rt refuses to |
| 1229 | // run such an image (main.cpp); a Loader user must not run its code either. | ||
| 1272 | std::fprintf(stderr, | 1230 | std::fprintf(stderr, |
| 1273 | "[rt] loader: %s does not get module TLS index 0 (%s); its code built with /GA will not " | 1231 | "[rt] loader: %s does not get module TLS index 0 (%s); its code built with /GA would use " |
| 1274 | "find its TLS\n", | 1232 | "another module's TLS\n", |
| 1275 | m.name.c_str(), why.c_str()); | 1233 | m.name.c_str(), g_index0.moved ? "another mapped executable holds it" : g_index0.why); |
| 1276 | } | 1234 | } |
| 1277 | } | 1235 | } |
| 1278 | if (slot == kTlsSlotCount) { | 1236 | if (slot == kTlsSlotCount) { |