diff options
| author | Moriz82 <72836413+Moriz82@users.noreply.github.com> | 2026-11-24 11:42:12 -0600 |
|---|---|---|
| committer | Moriz82 <72836413+Moriz82@users.noreply.github.com> | 2026-11-24 11:42:12 -0600 |
| commit | 273b3bdf9d6e736442ad584ad464df6e86ee928b (patch) | |
| tree | 3886a0af7c74ffa7d9415d662d8dc0fb708f1c08 /runtime/src/pe_loader.cpp | |
| parent | ece4ba5b31ebc6f345c8e29eae1261f2f780057a (diff) | |
[integration] Linux/Proton and native Windows: boot through the story load (RT-PROTON-STORY-LOAD)
One squashed commit of a fork that was developed on a Linux/Proton machine and
tested on two native Windows machines. On all of them the retail 1.0.2.1
package now launches, shows its launch movie, first-run pages and landing
prompt, runs the story load to its end with the loading slideshow drawing its
artwork, and enters the world phase. A first world frame is not verified yet.
docs/linux_proton.md has the setup, a healthy boot's timeline, the machines
and where it stops.
Runtime: frames in the title's own window; DirectStorage pinned reads,
page-list scatter/gather, BCPack and unshuffle with a locally generated
predictor file; pooled, device-local and deferred image backing for streamed
and placed textures; enhanced barriers into LAYOUT_UNDEFINED; a bindless table
that degrades instead of refusing a submission; a descriptor hash finalizer
(off until a library carries it); directly indexed heap offsets for compute
dispatches and VS/PS/GS draws; title buffer windows outside a fragmented
arena; opt-in device-local copies of streamed buffer views; write-fault
retries under the tracker lock, shared trackers and write-watched title memory
for native Windows; device-loss, compute-input and memory probes.
Translator: loop bounds at structured exits, the eight FidelityFX programs
that use a packed-dot form the disassembler skips, buffer bounds modes per
view kind, a compaction option, the hash finalizer option.
Tools and scripts: Linux boot scripts (Wine/Proton, no network), a Windows
boot script, the paired compute translation script.
No game data. AI-assisted (Claude Code and Codex agents), reviewed and booted
by people on the machines named in docs/linux_proton.md.
Co-authored-by: Plaaasma <47513553+Plaaasma@users.noreply.github.com>
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Diffstat (limited to 'runtime/src/pe_loader.cpp')
| -rw-r--r-- | runtime/src/pe_loader.cpp | 477 |
1 files changed, 411 insertions, 66 deletions
diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index ff0693a15..9c12733c6 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp | |||
| @@ -19,6 +19,8 @@ | |||
| 19 | #include "../shims/shims.h" | 19 | #include "../shims/shims.h" |
| 20 | #include "../shims/startup_trace.h" | 20 | #include "../shims/startup_trace.h" |
| 21 | #include "base_reservation.h" | 21 | #include "base_reservation.h" |
| 22 | #include "clzero_patch.h" | ||
| 23 | #include "cpu_emulation.h" | ||
| 22 | 24 | ||
| 23 | namespace rt { | 25 | namespace rt { |
| 24 | 26 | ||
| @@ -126,8 +128,29 @@ IMAGE_TLS_DIRECTORY64* tls_directory(Module& m) { | |||
| 126 | // reuses that index for the mapped image. When more than one manually mapped module uses static TLS at once, the loader | 128 | // reuses that index for the mapped image. When more than one manually mapped module uses static TLS at once, the loader |
| 127 | // clones gta6rt_tls_host.dll to a per-process temporary path on demand and loads it, so the OS assigns an independent | 129 | // clones gta6rt_tls_host.dll to a per-process temporary path on demand and loads it, so the OS assigns an independent |
| 128 | // module TLS index for each simultaneous module (up to kMaxMappedTlsModules). | 130 | // module TLS index for each simultaneous module (up to kMaxMappedTlsModules). |
| 131 | // | ||
| 132 | // A mapped executable is different: MSVC code built with /GA (an EXE-only optimisation) skips _tls_index and reads | ||
| 133 | // TEB->ThreadLocalStoragePointer[0] directly (mov rax, gs:[58h]; mov rax, [rax]), because Windows always gives the | ||
| 134 | // process executable module TLS index 0. Measured with a `thread_local int v = 42;` EXE built /O2 /GA /MD: natively | ||
| 135 | // tls_index=0 value=42; mapped with a helper index (6) the code still read slot 0 and printed value=0. Index 0 | ||
| 136 | // belongs to the runtime's own EXE (gta6rt.exe: a 1398-byte template when measured, no TLS callbacks; so does each | ||
| 137 | // test EXE that links this file), and every TLS read in its disassembly goes through _tls_index (the only direct | ||
| 138 | // gs:[58h] read is module_tls_slots below, which wants the array itself). reserve_tls_index0 therefore moves the owner | ||
| 139 | // off index 0, once, at process start: it loads the home clone (make_home_clone_image), whose TLS template is a copy of | ||
| 140 | // 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 | ||
| 141 | // starts has a fresh copy of the owner's template at home, which is where the owner looks, from its first instruction: | ||
| 142 | // nothing has to run on a new thread first. Slot 0 holds a block nobody reads, which the mapped executable's copy | ||
| 143 | // replaces (kMainImageSlot) exactly as a DLL's copy replaces a helper's, and the OS frees both slots at thread exit. | ||
| 144 | // It has to happen before any other thread has run the owner's code: MSVC keeps &ThreadLocalStoragePointer[_tls_index] | ||
| 145 | // across calls (zlib_inflate in shader_library.h saves it at [rbp-80h] across memset, push_back and inflate_codes, then | ||
| 146 | // reads _Init_thread_epoch through it), so a running thread cannot be moved safely, wherever it is stopped. Such a | ||
| 147 | // thread's TLS would also stay where it was, at index 0. | ||
| 129 | constexpr DWORD kMaxModuleTlsSlots = 64; | 148 | constexpr DWORD kMaxModuleTlsSlots = 64; |
| 130 | constexpr size_t kMaxMappedTlsModules = 16; | 149 | constexpr size_t kMaxMappedTlsModules = 16; |
| 150 | // The slot for a mapped executable, which reads module TLS index 0 (see above). Only one at a time; a second | ||
| 151 | // executable mapped while one is live gets an ordinary helper slot. kTlsSlotCount sizes the per-slot tables. | ||
| 152 | constexpr size_t kMainImageSlot = kMaxMappedTlsModules; | ||
| 153 | constexpr size_t kTlsSlotCount = kMaxMappedTlsModules + 1; | ||
| 131 | void** module_tls_slots() { return reinterpret_cast<void**>(__readgsqword(0x58)); } | 154 | void** module_tls_slots() { return reinterpret_cast<void**>(__readgsqword(0x58)); } |
| 132 | 155 | ||
| 133 | void __cdecl on_host_thread_event(DWORD reason); | 156 | void __cdecl on_host_thread_event(DWORD reason); |
| @@ -135,6 +158,7 @@ void __cdecl on_host_thread_event(DWORD reason); | |||
| 135 | struct TlsHostModule { | 158 | struct TlsHostModule { |
| 136 | HMODULE module = nullptr; | 159 | HMODULE module = nullptr; |
| 137 | DWORD index = TLS_OUT_OF_INDEXES; | 160 | DWORD index = TLS_OUT_OF_INDEXES; |
| 161 | bool hooked = false; // its DllMain reports thread events to on_host_thread_event | ||
| 138 | }; | 162 | }; |
| 139 | 163 | ||
| 140 | std::filesystem::path tls_host_base_path() { | 164 | std::filesystem::path tls_host_base_path() { |
| @@ -167,20 +191,39 @@ struct TlsCloneRecord { | |||
| 167 | 191 | ||
| 168 | std::mutex g_tls_alloc_mutex; | 192 | std::mutex g_tls_alloc_mutex; |
| 169 | std::array<TlsHostModule, kMaxMappedTlsModules> g_tls_hosts{}; | 193 | std::array<TlsHostModule, kMaxMappedTlsModules> g_tls_hosts{}; |
| 170 | std::array<std::atomic<Module*>, kMaxMappedTlsModules> g_tls_slot_owners{}; | 194 | std::array<std::atomic<Module*>, kTlsSlotCount> g_tls_slot_owners{}; |
| 171 | std::array<std::atomic<uint64_t>, kMaxMappedTlsModules> g_tls_slot_generations{}; | 195 | std::array<std::atomic<uint64_t>, kTlsSlotCount> g_tls_slot_generations{}; |
| 172 | std::atomic<uint64_t> g_next_tls_generation{1}; | 196 | std::atomic<uint64_t> g_next_tls_generation{1}; |
| 173 | std::vector<TlsCloneRecord> g_tls_clones; | 197 | // Allocated with the first clone and never destroyed: cleanup_tls_clones_at_exit runs from the atexit table, and a |
| 198 | // static vector's destructor (registered when its dynamic initializer ran) could run before it. Under | ||
| 199 | // g_tls_alloc_mutex, as are its records. | ||
| 200 | std::vector<TlsCloneRecord>* g_tls_clones = nullptr; | ||
| 201 | |||
| 202 | // The move of module TLS index 0 (see kMainImageSlot): done at most once, by reserve_tls_index0 under | ||
| 203 | // g_tls_alloc_mutex. `why` is the reason it was not done, for the executable that then maps with a helper index. | ||
| 204 | // Constant-initialized only (no std::string): gta6rt reserves from a CRT initializer that runs before the dynamic | ||
| 205 | // initializers of this file, which would otherwise reset what it wrote. | ||
| 206 | struct Index0Move { | ||
| 207 | bool moved = false; | ||
| 208 | bool traced = false; // the startup trace opens after the move; the first executable map reports it | ||
| 209 | TlsHostModule home; // the clone whose index holds the owner's TLS from now on; never freed | ||
| 210 | char owner[260] = {}; // UTF-8 file name of the image that held index 0 | ||
| 211 | char why[160] = "reserve_tls_index0 was not called at process start"; | ||
| 212 | }; | ||
| 213 | Index0Move g_index0; | ||
| 174 | 214 | ||
| 175 | // Frees every TLS helper clone this process loaded and deletes its files. load() registers the wrapper with atexit; | 215 | // Frees every TLS helper clone recorded for a mapped DLL's slot and deletes its files. ensure_tls_host registers the |
| 176 | // the --run path in main() must also call this directly before ExitProcess, which skips the atexit table. Call it | 216 | // wrapper with atexit when it records the first clone; the --run path in main() must also call this directly before |
| 177 | // only when no mapped code can run again: it unmaps the helper images. | 217 | // ExitProcess, which skips the atexit table. Call it only when no mapped code can run again: it unmaps the helper |
| 218 | // images. The home clone is not recorded (reserve_index0): it stays loaded, so its file outlives the process and the | ||
| 219 | // next run's sweep deletes it. | ||
| 178 | void cleanup_tls_clones_internal() { | 220 | void cleanup_tls_clones_internal() { |
| 179 | for (const auto& rec : g_tls_clones) { | 221 | if (!g_tls_clones) return; |
| 222 | for (const auto& rec : *g_tls_clones) { | ||
| 180 | if (rec.module) FreeLibrary(rec.module); | 223 | if (rec.module) FreeLibrary(rec.module); |
| 181 | if (!rec.path.empty()) DeleteFileW(rec.path.c_str()); | 224 | if (!rec.path.empty()) DeleteFileW(rec.path.c_str()); |
| 182 | } | 225 | } |
| 183 | g_tls_clones.clear(); | 226 | g_tls_clones->clear(); |
| 184 | } | 227 | } |
| 185 | 228 | ||
| 186 | void cleanup_tls_clones_at_exit() { cleanup_tls_clones_internal(); } | 229 | void cleanup_tls_clones_at_exit() { cleanup_tls_clones_internal(); } |
| @@ -204,10 +247,14 @@ DWORD clone_owner_pid(const wchar_t* name) { | |||
| 204 | bool process_alive(DWORD pid) { | 247 | bool process_alive(DWORD pid) { |
| 205 | // PROCESS_QUERY_LIMITED_INFORMATION needs no handle rights a normal process could deny; a failure means the | 248 | // PROCESS_QUERY_LIMITED_INFORMATION needs no handle rights a normal process could deny; a failure means the |
| 206 | // process is gone. A still-mapped or still-open file is caught by the checks below even for a misjudged PID. | 249 | // process is gone. A still-mapped or still-open file is caught by the checks below even for a misjudged PID. |
| 250 | // OpenProcess also succeeds on a process that has ended while another process still holds a handle to it (a | ||
| 251 | // parent waiting on its exit code, as CMake's execute_process does), so the exit code decides. | ||
| 207 | HANDLE p = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid); | 252 | HANDLE p = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid); |
| 208 | if (!p) return false; | 253 | if (!p) return false; |
| 254 | DWORD code = 0; | ||
| 255 | const bool alive = !GetExitCodeProcess(p, &code) || code == STILL_ACTIVE; | ||
| 209 | CloseHandle(p); | 256 | CloseHandle(p); |
| 210 | return true; | 257 | return alive; |
| 211 | } | 258 | } |
| 212 | 259 | ||
| 213 | // Deletes clones left behind by processes that have exited. Deletion is scoped to files whose owner is gone: a | 260 | // Deletes clones left behind by processes that have exited. Deletion is scoped to files whose owner is gone: a |
| @@ -262,45 +309,66 @@ TlsHostModule load_tls_host_image(const std::filesystem::path& path, bool hook_t | |||
| 262 | if (hook_thread_events) { | 309 | if (hook_thread_events) { |
| 263 | // Only the primary helper reports thread attach/detach events; on_host_thread_event iterates all active slots. | 310 | // Only the primary helper reports thread attach/detach events; on_host_thread_event iterates all active slots. |
| 264 | using SetThreadEvent = void(__cdecl*)(void(__cdecl*)(DWORD)); | 311 | using SetThreadEvent = void(__cdecl*)(void(__cdecl*)(DWORD)); |
| 265 | if (auto set = reinterpret_cast<SetThreadEvent>(GetProcAddress(host.module, "gta6rt_tls_host_set_thread_event"))) | 312 | auto set = reinterpret_cast<SetThreadEvent>(GetProcAddress(host.module, "gta6rt_tls_host_set_thread_event")); |
| 313 | if (set) { | ||
| 266 | set(&on_host_thread_event); | 314 | set(&on_host_thread_event); |
| 315 | host.hooked = true; | ||
| 316 | } | ||
| 267 | } | 317 | } |
| 268 | return host; | 318 | return host; |
| 269 | } | 319 | } |
| 270 | 320 | ||
| 271 | // Must be called with g_tls_alloc_mutex held and WITHOUT g_tls_lock held (LoadLibraryExW takes the Windows loader lock). | 321 | // The primary helper: slot 0's index, and the only helper whose DllMain reports thread events (on_host_thread_event |
| 272 | TlsHostModule ensure_tls_host(size_t slot) { | 322 | // covers every slot). Must be called with g_tls_alloc_mutex held and WITHOUT g_tls_lock held (LoadLibraryExW takes the |
| 273 | if (slot >= kMaxMappedTlsModules) return {}; | 323 | // Windows loader lock). |
| 274 | if (g_tls_hosts[slot].index != TLS_OUT_OF_INDEXES) return g_tls_hosts[slot]; | 324 | // A helper without the thread-event export is refused: no thread started later would get its copies. |
| 275 | 325 | bool ensure_primary_tls_host() { | |
| 326 | if (g_tls_hosts[0].index != TLS_OUT_OF_INDEXES) return true; | ||
| 276 | const std::filesystem::path primary = tls_host_base_path(); | 327 | const std::filesystem::path primary = tls_host_base_path(); |
| 277 | if (primary.empty()) return {}; | 328 | if (primary.empty()) return false; |
| 278 | 329 | TlsHostModule host = load_tls_host_image(primary, true); | |
| 279 | if (slot == 0) { | 330 | if (host.index != TLS_OUT_OF_INDEXES && !host.hooked) { |
| 280 | g_tls_hosts[0] = load_tls_host_image(primary, true); | 331 | FreeLibrary(host.module); |
| 281 | return g_tls_hosts[0]; | 332 | return false; |
| 282 | } | ||
| 283 | |||
| 284 | // Ensure slot 0 is loaded first so thread attach/detach events are hooked. | ||
| 285 | if (g_tls_hosts[0].index == TLS_OUT_OF_INDEXES) { | ||
| 286 | g_tls_hosts[0] = load_tls_host_image(primary, true); | ||
| 287 | if (g_tls_hosts[0].index == TLS_OUT_OF_INDEXES) return {}; | ||
| 288 | } | 333 | } |
| 334 | g_tls_hosts[0] = host; | ||
| 335 | return host.index != TLS_OUT_OF_INDEXES; | ||
| 336 | } | ||
| 289 | 337 | ||
| 338 | // Copies gta6rt_tls_host.dll (or writes `image`, a changed copy of it) to "leonida_tls_host_<pid>_<tag>.dll" in the | ||
| 339 | // clone directory and loads it, so the OS gives the copy an index of its own. On failure the file is gone again and | ||
| 340 | // the result has no index. The caller records the clone (g_tls_clones) if it is to be freed at exit. Same locking rule | ||
| 341 | // as ensure_primary_tls_host. | ||
| 342 | TlsHostModule load_tls_host_clone(const std::wstring& tag, std::filesystem::path& clone_path, | ||
| 343 | const std::vector<uint8_t>* image = nullptr) { | ||
| 344 | const std::filesystem::path primary = tls_host_base_path(); | ||
| 345 | if (primary.empty()) return {}; | ||
| 290 | // Clone gta6rt_tls_host.dll to a distinct path using CopyFileW (Wine 9 lacks CopyFile2 used by std::filesystem). | 346 | // Clone gta6rt_tls_host.dll to a distinct path using CopyFileW (Wine 9 lacks CopyFile2 used by std::filesystem). |
| 291 | const std::filesystem::path dir = tls_host_clone_dir(); | 347 | const std::filesystem::path dir = tls_host_clone_dir(); |
| 292 | static bool swept = false; | 348 | static bool swept = false; |
| 293 | if (!swept) { | 349 | if (!swept) { |
| 294 | swept = true; | 350 | swept = true; |
| 295 | sweep_stale_tls_clones(dir); | 351 | sweep_stale_tls_clones(dir); |
| 296 | std::atexit(&cleanup_tls_clones_at_exit); | ||
| 297 | } | 352 | } |
| 298 | const std::wstring name = | 353 | const std::wstring name = L"leonida_tls_host_" + std::to_wstring(GetCurrentProcessId()) + L"_" + tag + L".dll"; |
| 299 | L"leonida_tls_host_" + std::to_wstring(GetCurrentProcessId()) + L"_" + std::to_wstring(slot) + L".dll"; | 354 | clone_path = dir / name; |
| 300 | const std::filesystem::path clone_path = dir / name; | ||
| 301 | // The staging name must not match the sweep pattern, which only covers final clone names ending in .dll. | 355 | // The staging name must not match the sweep pattern, which only covers final clone names ending in .dll. |
| 302 | const std::filesystem::path staging = clone_path.wstring() + L".new"; | 356 | const std::filesystem::path staging = clone_path.wstring() + L".new"; |
| 303 | if (!CopyFileW(primary.c_str(), staging.c_str(), FALSE)) return {}; | 357 | if (image) { |
| 358 | HANDLE out = | ||
| 359 | CreateFileW(staging.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); | ||
| 360 | if (out == INVALID_HANDLE_VALUE) return {}; | ||
| 361 | DWORD written = 0; | ||
| 362 | const bool ok = WriteFile(out, image->data(), static_cast<DWORD>(image->size()), &written, nullptr) && | ||
| 363 | written == image->size(); | ||
| 364 | CloseHandle(out); | ||
| 365 | if (!ok) { | ||
| 366 | DeleteFileW(staging.c_str()); | ||
| 367 | return {}; | ||
| 368 | } | ||
| 369 | } else if (!CopyFileW(primary.c_str(), staging.c_str(), FALSE)) { | ||
| 370 | return {}; | ||
| 371 | } | ||
| 304 | 372 | ||
| 305 | // Open the guard before the clone exists under its final name and hold it across LoadLibraryExW: the rename | 373 | // Open the guard before the clone exists under its final name and hold it across LoadLibraryExW: the rename |
| 306 | // below needs DELETE access, which the handle's FILE_SHARE_DELETE grants, and no purge can remove the clone | 374 | // below needs DELETE access, which the handle's FILE_SHARE_DELETE grants, and no purge can remove the clone |
| @@ -320,18 +388,34 @@ TlsHostModule ensure_tls_host(size_t slot) { | |||
| 320 | TlsHostModule loaded = load_tls_host_image(clone_path, false); | 388 | TlsHostModule loaded = load_tls_host_image(clone_path, false); |
| 321 | CloseHandle(guard); | 389 | CloseHandle(guard); |
| 322 | 390 | ||
| 323 | if (loaded.index == TLS_OUT_OF_INDEXES) { | 391 | if (loaded.index == TLS_OUT_OF_INDEXES) DeleteFileW(clone_path.c_str()); |
| 392 | return loaded; | ||
| 393 | } | ||
| 394 | |||
| 395 | // Must be called with g_tls_alloc_mutex held and WITHOUT g_tls_lock held (LoadLibraryExW takes the Windows loader lock). | ||
| 396 | TlsHostModule ensure_tls_host(size_t slot) { | ||
| 397 | if (slot >= kMaxMappedTlsModules) return {}; | ||
| 398 | if (g_tls_hosts[slot].index != TLS_OUT_OF_INDEXES) return g_tls_hosts[slot]; | ||
| 399 | // Slot 0 is the primary helper; it is loaded first in any case so thread attach/detach events are hooked. | ||
| 400 | if (!ensure_primary_tls_host()) return {}; | ||
| 401 | if (slot == 0) return g_tls_hosts[0]; | ||
| 402 | |||
| 403 | std::filesystem::path clone_path; | ||
| 404 | TlsHostModule loaded = load_tls_host_clone(std::to_wstring(slot), clone_path); | ||
| 405 | if (loaded.index == TLS_OUT_OF_INDEXES) return {}; | ||
| 406 | // Index 0 is the runtime EXE's, and after the move the home clone's index holds that EXE's TLS. | ||
| 407 | bool taken = loaded.index == 0 || loaded.index == g_index0.home.index; | ||
| 408 | for (size_t i = 0; i < kMaxMappedTlsModules; ++i) taken |= i != slot && g_tls_hosts[i].index == loaded.index; | ||
| 409 | if (taken) { | ||
| 410 | FreeLibrary(loaded.module); | ||
| 324 | DeleteFileW(clone_path.c_str()); | 411 | DeleteFileW(clone_path.c_str()); |
| 325 | return {}; | 412 | return {}; |
| 326 | } | 413 | } |
| 327 | for (size_t i = 0; i < kMaxMappedTlsModules; ++i) { | 414 | if (!g_tls_clones) { |
| 328 | if (i != slot && g_tls_hosts[i].index == loaded.index) { | 415 | g_tls_clones = new std::vector<TlsCloneRecord>; |
| 329 | FreeLibrary(loaded.module); | 416 | std::atexit(&cleanup_tls_clones_at_exit); |
| 330 | DeleteFileW(clone_path.c_str()); | ||
| 331 | return {}; | ||
| 332 | } | ||
| 333 | } | 417 | } |
| 334 | g_tls_clones.push_back({loaded.module, clone_path}); | 418 | g_tls_clones->push_back({loaded.module, clone_path}); |
| 335 | g_tls_hosts[slot] = loaded; | 419 | g_tls_hosts[slot] = loaded; |
| 336 | return g_tls_hosts[slot]; | 420 | return g_tls_hosts[slot]; |
| 337 | } | 421 | } |
| @@ -347,7 +431,7 @@ struct ThreadTlsSlot { | |||
| 347 | }; | 431 | }; |
| 348 | 432 | ||
| 349 | // Per-thread installation state for each reserved TLS slot. | 433 | // Per-thread installation state for each reserved TLS slot. |
| 350 | thread_local std::array<ThreadTlsSlot, kMaxMappedTlsModules> g_thread_tls_slots{}; | 434 | thread_local std::array<ThreadTlsSlot, kTlsSlotCount> g_thread_tls_slots{}; |
| 351 | 435 | ||
| 352 | // Orders the TLS owners' publication, their `initialised` flags and their retirement against the thread events. Shared | 436 | // Orders the TLS owners' publication, their `initialised` flags and their retirement against the thread events. Shared |
| 353 | // in on_host_thread_event, exclusive only for those short writes (no allocation and no call that takes the Windows | 437 | // in on_host_thread_event, exclusive only for those short writes (no allocation and no call that takes the Windows |
| @@ -366,10 +450,185 @@ struct ExclusiveTlsLock { | |||
| 366 | ExclusiveTlsLock& operator=(const ExclusiveTlsLock&) = delete; | 450 | ExclusiveTlsLock& operator=(const ExclusiveTlsLock&) = delete; |
| 367 | }; | 451 | }; |
| 368 | 452 | ||
| 453 | // gta6rt_tls_host.dll's exports that the home clone's TLS directory is pointed at (tls_host.cpp): a zero array in its | ||
| 454 | // .rdata and that array's size. | ||
| 455 | constexpr char kHomeTemplateExport[] = "gta6rt_tls_home_template"; | ||
| 456 | constexpr char kHomeTemplateSizeExport[] = "gta6rt_tls_home_template_size"; | ||
| 457 | |||
| 458 | // File offset of `len` bytes at `rva` in an image file held in memory, or SIZE_MAX when they are not all inside one | ||
| 459 | // section's raw data. | ||
| 460 | size_t file_offset(const std::vector<uint8_t>& file, const IMAGE_NT_HEADERS64* nt, uint64_t rva, uint64_t len) { | ||
| 461 | const auto* sec = IMAGE_FIRST_SECTION(nt); | ||
| 462 | for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++sec) { | ||
| 463 | if (reinterpret_cast<const uint8_t*>(sec + 1) > file.data() + file.size()) break; | ||
| 464 | if (rva < sec->VirtualAddress || rva + len > static_cast<uint64_t>(sec->VirtualAddress) + sec->SizeOfRawData) | ||
| 465 | continue; | ||
| 466 | const uint64_t off = sec->PointerToRawData + (rva - sec->VirtualAddress); | ||
| 467 | return off + len <= file.size() ? static_cast<size_t>(off) : SIZE_MAX; | ||
| 468 | } | ||
| 469 | return SIZE_MAX; | ||
| 470 | } | ||
| 471 | |||
| 472 | // The RVA of a named export in an image file held in memory, 0 when it has none. | ||
| 473 | uint32_t file_export(const std::vector<uint8_t>& file, const IMAGE_NT_HEADERS64* nt, const char* wanted) { | ||
| 474 | const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_EXPORT); | ||
| 475 | const size_t ed_off = file_offset(file, nt, dir.VirtualAddress, sizeof(IMAGE_EXPORT_DIRECTORY)); | ||
| 476 | if (!dir.Size || ed_off == SIZE_MAX) return 0; | ||
| 477 | const auto* ed = reinterpret_cast<const IMAGE_EXPORT_DIRECTORY*>(file.data() + ed_off); | ||
| 478 | const size_t names = file_offset(file, nt, ed->AddressOfNames, uint64_t{4} * ed->NumberOfNames); | ||
| 479 | const size_t ords = file_offset(file, nt, ed->AddressOfNameOrdinals, uint64_t{2} * ed->NumberOfNames); | ||
| 480 | const size_t funcs = file_offset(file, nt, ed->AddressOfFunctions, uint64_t{4} * ed->NumberOfFunctions); | ||
| 481 | if (names == SIZE_MAX || ords == SIZE_MAX || funcs == SIZE_MAX) return 0; | ||
| 482 | const size_t wanted_len = std::strlen(wanted) + 1; | ||
| 483 | for (uint32_t i = 0; i < ed->NumberOfNames; ++i) { | ||
| 484 | uint32_t name_rva, func_rva; | ||
| 485 | uint16_t ord; | ||
| 486 | std::memcpy(&name_rva, file.data() + names + 4 * i, 4); | ||
| 487 | std::memcpy(&ord, file.data() + ords + 2 * i, 2); | ||
| 488 | const size_t name = file_offset(file, nt, name_rva, wanted_len); | ||
| 489 | if (name == SIZE_MAX || std::memcmp(file.data() + name, wanted, wanted_len) != 0) continue; | ||
| 490 | if (ord >= ed->NumberOfFunctions) return 0; | ||
| 491 | std::memcpy(&func_rva, file.data() + funcs + 4 * ord, 4); | ||
| 492 | return func_rva; | ||
| 493 | } | ||
| 494 | return 0; | ||
| 495 | } | ||
| 496 | |||
| 497 | // Turns gta6rt_tls_host.dll's bytes into the home clone: its TLS directory now covers gta6rt_tls_home_template, which | ||
| 498 | // starts with a copy of the owner's template (taken from the mapped owner, so its pointers are already relocated; the | ||
| 499 | // array itself has no relocations), and takes the owner's alignment. The OS then gives every thread, at the home | ||
| 500 | // index, a block that is a fresh copy of the owner's TLS. The zero fill goes into the covered range too: | ||
| 501 | // LdrpAllocateTls allocates and copies End - Start only (Windows 11 26300) and ignores SizeOfZeroFill. The directory's | ||
| 502 | // Start and End have base relocations, so they follow the clone wherever it loads. Empty on success, else why not. | ||
| 503 | std::string make_home_clone_image(std::vector<uint8_t>& file, const IMAGE_TLS_DIRECTORY64& owner) { | ||
| 504 | if (file.size() < sizeof(IMAGE_DOS_HEADER)) return "gta6rt_tls_host.dll is truncated"; | ||
| 505 | const auto* dos = reinterpret_cast<const IMAGE_DOS_HEADER*>(file.data()); | ||
| 506 | if (dos->e_magic != IMAGE_DOS_SIGNATURE || dos->e_lfanew < 0 || | ||
| 507 | static_cast<size_t>(dos->e_lfanew) + sizeof(IMAGE_NT_HEADERS64) > file.size()) | ||
| 508 | return "gta6rt_tls_host.dll has no PE header"; | ||
| 509 | auto* nt = reinterpret_cast<IMAGE_NT_HEADERS64*>(file.data() + dos->e_lfanew); | ||
| 510 | if (nt->Signature != IMAGE_NT_SIGNATURE || nt->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR64_MAGIC) | ||
| 511 | return "gta6rt_tls_host.dll is not a 64-bit image"; | ||
| 512 | const uint32_t array_rva = file_export(file, nt, kHomeTemplateExport); | ||
| 513 | const uint32_t size_rva = file_export(file, nt, kHomeTemplateSizeExport); | ||
| 514 | const size_t size_off = file_offset(file, nt, size_rva, sizeof(uint32_t)); | ||
| 515 | if (!array_rva || !size_rva || size_off == SIZE_MAX) | ||
| 516 | return "gta6rt_tls_host.dll has no gta6rt_tls_home_template"; | ||
| 517 | uint32_t capacity; | ||
| 518 | std::memcpy(&capacity, file.data() + size_off, sizeof(capacity)); | ||
| 519 | const uint64_t raw = owner.EndAddressOfRawData - owner.StartAddressOfRawData; | ||
| 520 | const uint64_t total = raw + owner.SizeOfZeroFill; | ||
| 521 | if (owner.EndAddressOfRawData < owner.StartAddressOfRawData || total > capacity) | ||
| 522 | return "the owner's TLS (" + std::to_string(total) + " bytes) does not fit gta6rt_tls_home_template (" + | ||
| 523 | std::to_string(capacity) + " bytes)"; | ||
| 524 | const size_t array_off = file_offset(file, nt, array_rva, capacity); | ||
| 525 | const auto tls_dir = directory(nt, IMAGE_DIRECTORY_ENTRY_TLS); | ||
| 526 | const size_t tls_off = file_offset(file, nt, tls_dir.VirtualAddress, sizeof(IMAGE_TLS_DIRECTORY64)); | ||
| 527 | if (array_off == SIZE_MAX || !tls_dir.Size || tls_off == SIZE_MAX) | ||
| 528 | return "gta6rt_tls_host.dll's TLS directory or home template lies outside its file"; | ||
| 529 | std::memcpy(file.data() + array_off, reinterpret_cast<const void*>(owner.StartAddressOfRawData), raw); | ||
| 530 | std::memset(file.data() + array_off + raw, 0, capacity - raw); | ||
| 531 | auto* tls = reinterpret_cast<IMAGE_TLS_DIRECTORY64*>(file.data() + tls_off); | ||
| 532 | tls->StartAddressOfRawData = nt->OptionalHeader.ImageBase + array_rva; | ||
| 533 | tls->EndAddressOfRawData = tls->StartAddressOfRawData + total; | ||
| 534 | tls->SizeOfZeroFill = 0; | ||
| 535 | tls->Characteristics = | ||
| 536 | (tls->Characteristics & ~IMAGE_SCN_ALIGN_MASK) | (owner.Characteristics & IMAGE_SCN_ALIGN_MASK); | ||
| 537 | return {}; | ||
| 538 | } | ||
| 539 | |||
| 540 | std::string module_file_name(HMODULE module) { | ||
| 541 | wchar_t path[MAX_PATH]; | ||
| 542 | const DWORD n = GetModuleFileNameW(module, path, MAX_PATH); | ||
| 543 | if (!n || n >= MAX_PATH) return "?"; | ||
| 544 | const wchar_t* name = path; | ||
| 545 | for (const wchar_t* p = path; *p; ++p) | ||
| 546 | if (*p == L'\\' || *p == L'/') name = p + 1; | ||
| 547 | const int bytes = WideCharToMultiByte(CP_UTF8, 0, name, -1, nullptr, 0, nullptr, nullptr); | ||
| 548 | if (bytes <= 1) return "?"; | ||
| 549 | std::string out(static_cast<size_t>(bytes - 1), '\0'); | ||
| 550 | WideCharToMultiByte(CP_UTF8, 0, name, -1, out.data(), bytes, nullptr, nullptr); | ||
| 551 | return out; | ||
| 552 | } | ||
| 553 | |||
| 554 | // The move on the calling thread, kept apart so that no frame of reserve_index0 holds a slot address across it. After | ||
| 555 | // it the owner's live block is at `home` and slot 0 holds the home clone's fresh copy, which nothing reads. | ||
| 556 | __declspec(noinline) void move_index0_on_this_thread(DWORD* owner_index, DWORD home) { | ||
| 557 | void** slots = module_tls_slots(); | ||
| 558 | std::swap(slots[0], slots[home]); | ||
| 559 | *owner_index = home; | ||
| 560 | } | ||
| 561 | |||
| 562 | // See reserve_tls_index0. Empty on success, else why not; nothing has changed then. g_tls_alloc_mutex held. It reads | ||
| 563 | // no thread_local data and runs no code that does, before or after the move. | ||
| 564 | std::string reserve_index0() { | ||
| 565 | // Windows gives index 0 to the process executable when it has TLS; a DLL can only hold it in a process whose EXE | ||
| 566 | // has none, and a DLL that is still loading or was loaded without its references resolved shows 0 too. | ||
| 567 | const HMODULE exe = GetModuleHandleW(nullptr); | ||
| 568 | auto* base = reinterpret_cast<uint8_t*>(exe); | ||
| 569 | auto* nt = at<IMAGE_NT_HEADERS64>(base, reinterpret_cast<IMAGE_DOS_HEADER*>(base)->e_lfanew); | ||
| 570 | const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_TLS); | ||
| 571 | if (!dir.Size || !dir.VirtualAddress) return "the process executable has no TLS, so index 0 is not its"; | ||
| 572 | const IMAGE_TLS_DIRECTORY64 owner = *at<IMAGE_TLS_DIRECTORY64>(base, dir.VirtualAddress); | ||
| 573 | auto* owner_index = reinterpret_cast<DWORD*>(owner.AddressOfIndex); | ||
| 574 | if (!owner_index) return "the process executable's TLS directory has no index"; | ||
| 575 | if (*owner_index != 0) return "the process executable's _tls_index is " + std::to_string(*owner_index) + ", not 0"; | ||
| 576 | if (!module_tls_slots()) return "this thread has no TLS array"; | ||
| 577 | if (!ensure_primary_tls_host()) | ||
| 578 | return "gta6rt_tls_host.dll is missing, has no module TLS index or lacks gta6rt_tls_host_set_thread_event"; | ||
| 579 | |||
| 580 | std::vector<uint8_t> image; | ||
| 581 | try { | ||
| 582 | image = read_file(tls_host_base_path()); | ||
| 583 | } catch (const std::exception& e) { | ||
| 584 | return e.what(); | ||
| 585 | } | ||
| 586 | if (std::string why = make_home_clone_image(image, owner); !why.empty()) return why; | ||
| 587 | std::filesystem::path path; | ||
| 588 | const TlsHostModule home = load_tls_host_clone(L"home", path, &image); | ||
| 589 | if (home.index == TLS_OUT_OF_INDEXES) return "the home clone of gta6rt_tls_host.dll cannot be loaded"; | ||
| 590 | auto drop = [&](std::string why) { | ||
| 591 | FreeLibrary(home.module); // safe until the move below: nothing lives at its index yet | ||
| 592 | DeleteFileW(path.c_str()); | ||
| 593 | return why; | ||
| 594 | }; | ||
| 595 | bool taken = home.index == 0 || home.index >= kMaxModuleTlsSlots; | ||
| 596 | for (const auto& host : g_tls_hosts) taken |= host.index == home.index; | ||
| 597 | if (taken) return drop("the home clone got an unusable module TLS index"); | ||
| 598 | // The OS must have taken the changed directory: the mapped clone's template is the owner's, at full size. | ||
| 599 | auto* home_base = reinterpret_cast<uint8_t*>(home.module); | ||
| 600 | auto* home_nt = at<IMAGE_NT_HEADERS64>(home_base, reinterpret_cast<IMAGE_DOS_HEADER*>(home_base)->e_lfanew); | ||
| 601 | const auto* home_tls = | ||
| 602 | at<IMAGE_TLS_DIRECTORY64>(home_base, directory(home_nt, IMAGE_DIRECTORY_ENTRY_TLS).VirtualAddress); | ||
| 603 | const uint64_t raw = owner.EndAddressOfRawData - owner.StartAddressOfRawData; | ||
| 604 | if (home_tls->EndAddressOfRawData - home_tls->StartAddressOfRawData != raw + owner.SizeOfZeroFill || | ||
| 605 | std::memcmp(reinterpret_cast<const void*>(home_tls->StartAddressOfRawData), | ||
| 606 | reinterpret_cast<const void*>(owner.StartAddressOfRawData), raw) != 0) | ||
| 607 | return drop("the home clone's mapped TLS template is not the owner's"); | ||
| 608 | |||
| 609 | // Everything that can throw comes first: past the move this records the result and nothing more. | ||
| 610 | const std::string name = module_file_name(exe); | ||
| 611 | // _tls_index sits in .data; made writable first in case a linker merged it into a read-only section. | ||
| 612 | DWORD old_protect = 0; | ||
| 613 | if (!VirtualProtect(owner_index, sizeof(DWORD), PAGE_READWRITE, &old_protect)) | ||
| 614 | return drop("the owner's _tls_index cannot be written"); | ||
| 615 | move_index0_on_this_thread(owner_index, home.index); | ||
| 616 | VirtualProtect(owner_index, sizeof(DWORD), old_protect, &old_protect); | ||
| 617 | |||
| 618 | // Kept loaded for the process lifetime: FreeLibrary would make the OS free every thread's block at its index, the | ||
| 619 | // owner's from now on. Not in g_tls_clones for that reason. Its file cannot be deleted while it is mapped | ||
| 620 | // (DeleteFileW and a POSIX-semantics delete both fail with ERROR_ACCESS_DENIED on Windows 11), so it stays until | ||
| 621 | // a later run's sweep. | ||
| 622 | g_index0.home = home; | ||
| 623 | std::snprintf(g_index0.owner, sizeof(g_index0.owner), "%s", name.c_str()); | ||
| 624 | g_index0.moved = true; | ||
| 625 | return {}; | ||
| 626 | } | ||
| 627 | |||
| 369 | // Puts the helper DLL's own block back in this thread's slot and frees the copy that replaced it. Uses only this | 628 | // Puts the helper DLL's own block back in this thread's slot and frees the copy that replaced it. Uses only this |
| 370 | // thread's record, so it also works after the module that installed the copy is gone. | 629 | // thread's record, so it also works after the module that installed the copy is gone. |
| 371 | void release_thread_slot(size_t slot) { | 630 | void release_thread_slot(size_t slot) { |
| 372 | if (slot >= kMaxMappedTlsModules) return; | 631 | if (slot >= kTlsSlotCount) return; |
| 373 | ThreadTlsSlot& entry = g_thread_tls_slots[slot]; | 632 | ThreadTlsSlot& entry = g_thread_tls_slots[slot]; |
| 374 | if (!entry.module && !entry.block) return; | 633 | if (!entry.module && !entry.block) return; |
| 375 | if (entry.ga_view) { | 634 | if (entry.ga_view) { |
| @@ -438,7 +697,7 @@ void** make_ga_view(const Module& m, void* block) { | |||
| 438 | } | 697 | } |
| 439 | 698 | ||
| 440 | void install_thread_block(Module& m) { | 699 | void install_thread_block(Module& m) { |
| 441 | if (m.tls_slot >= kMaxMappedTlsModules) return; | 700 | if (m.tls_slot >= kTlsSlotCount) return; |
| 442 | const size_t slot = m.tls_slot; | 701 | const size_t slot = m.tls_slot; |
| 443 | ThreadTlsSlot& entry = g_thread_tls_slots[slot]; | 702 | ThreadTlsSlot& entry = g_thread_tls_slots[slot]; |
| 444 | if (entry.module == &m && entry.generation == m.tls_generation) return; | 703 | if (entry.module == &m && entry.generation == m.tls_generation) return; |
| @@ -530,7 +789,7 @@ bool ga_tls_patch_enabled() { | |||
| 530 | } | 789 | } |
| 531 | 790 | ||
| 532 | void uninstall_thread_block(Module& m) { | 791 | void uninstall_thread_block(Module& m) { |
| 533 | if (m.tls_slot >= kMaxMappedTlsModules) return; | 792 | if (m.tls_slot >= kTlsSlotCount) return; |
| 534 | const size_t slot = m.tls_slot; | 793 | const size_t slot = m.tls_slot; |
| 535 | ThreadTlsSlot& entry = g_thread_tls_slots[slot]; | 794 | ThreadTlsSlot& entry = g_thread_tls_slots[slot]; |
| 536 | if (entry.module != &m || entry.generation != m.tls_generation) return; | 795 | if (entry.module != &m || entry.generation != m.tls_generation) return; |
| @@ -697,7 +956,7 @@ constexpr size_t kMaxEndedThreads = 1024; | |||
| 697 | // load(): every other running thread gets its own copy of m's template. Not fatal where it cannot be done. | 956 | // load(): every other running thread gets its own copy of m's template. Not fatal where it cannot be done. |
| 698 | void install_on_existing_threads(Module& m) { | 957 | void install_on_existing_threads(Module& m) { |
| 699 | const uint64_t total = static_cast<uint64_t>(m.tls_raw_size) + m.tls_zero_fill; | 958 | const uint64_t total = static_cast<uint64_t>(m.tls_raw_size) + m.tls_zero_fill; |
| 700 | if (!total || m.tls_index >= kMaxModuleTlsSlots || m.tls_slot >= kMaxMappedTlsModules) return; | 959 | if (!total || m.tls_index >= kMaxModuleTlsSlots || m.tls_slot >= kTlsSlotCount) return; |
| 701 | // Stays ahead of the TLS lock: the first call resolves the function with GetModuleHandle and GetProcAddress, which | 960 | // Stays ahead of the TLS lock: the first call resolves the function with GetModuleHandle and GetProcAddress, which |
| 702 | // take the Windows loader lock, and a thread inside its attach event holds that lock while it waits for ours. | 961 | // take the Windows loader lock, and a thread inside its attach event holds that lock while it waits for ours. |
| 703 | if (!query_thread_fn()) return; | 962 | if (!query_thread_fn()) return; |
| @@ -882,7 +1141,11 @@ void release_existing_blocks_of_this_thread() { | |||
| 882 | // Runs in gta6rt_tls_host.dll's DllMain for each thread the process starts or ends once the helper is loaded, under | 1141 | // Runs in gta6rt_tls_host.dll's DllMain for each thread the process starts or ends once the helper is loaded, under |
| 883 | // the Windows loader lock, on that thread. A new thread gets its own copy of each active TLS owner's template; an | 1142 | // the Windows loader lock, on that thread. A new thread gets its own copy of each active TLS owner's template; an |
| 884 | // ending one gives each helper's block back before the Windows loader frees it. TLS callbacks get the thread events | 1143 | // ending one gives each helper's block back before the Windows loader frees it. TLS callbacks get the thread events |
| 885 | // only after the module's DLL_PROCESS_ATTACH (initialise()), as the Windows loader orders them. | 1144 | // only after the module's DLL_PROCESS_ATTACH (initialise()), as the Windows loader orders them. Windows allocates |
| 1145 | // every module's block before the first DllMain of a new thread, and runs an EXE's TLS callbacks after every DllMain, | ||
| 1146 | // for attach and for detach (measured on Windows 11 26300). So attach installs all copies first and then runs the | ||
| 1147 | // callbacks, the DLL slots in order and the executable's last; detach runs the DLL slots in reverse and then the | ||
| 1148 | // executable's slot, each releasing its copy after its callbacks. | ||
| 886 | void __cdecl on_host_thread_event(DWORD reason) { | 1149 | void __cdecl on_host_thread_event(DWORD reason) { |
| 887 | SharedTlsLock lock; | 1150 | SharedTlsLock lock; |
| 888 | // The try/catch is per slot: a throw from one module's install or callbacks must not take the thread events | 1151 | // The try/catch is per slot: a throw from one module's install or callbacks must not take the thread events |
| @@ -893,14 +1156,25 @@ void __cdecl on_host_thread_event(DWORD reason) { | |||
| 893 | } catch (const std::exception& e) { | 1156 | } catch (const std::exception& e) { |
| 894 | std::fprintf(stderr, "[rt] loader: thread attach: %s\n", e.what()); | 1157 | std::fprintf(stderr, "[rt] loader: thread attach: %s\n", e.what()); |
| 895 | } | 1158 | } |
| 896 | for (size_t slot = 0; slot < kMaxMappedTlsModules; ++slot) { | 1159 | std::array<Module*, kTlsSlotCount> installed{}; |
| 1160 | for (size_t slot = 0; slot < kTlsSlotCount; ++slot) { | ||
| 897 | Module* m = g_tls_slot_owners[slot].load(); | 1161 | Module* m = g_tls_slot_owners[slot].load(); |
| 898 | if (!m) continue; | 1162 | if (!m) continue; |
| 899 | try { | 1163 | try { |
| 900 | install_thread_block(*m); | 1164 | install_thread_block(*m); |
| 901 | if (m->initialised) run_callbacks(*m, DLL_THREAD_ATTACH); | 1165 | installed[slot] = m; |
| 1166 | } catch (const std::exception& e) { | ||
| 1167 | // The thread runs on without this module's TLS (and its callbacks); later slots still get theirs. | ||
| 1168 | std::fprintf(stderr, "[rt] loader: thread attach, slot %zu (%s): %s\n", slot, m->name.c_str(), | ||
| 1169 | e.what()); | ||
| 1170 | } | ||
| 1171 | } | ||
| 1172 | for (size_t slot = 0; slot < kTlsSlotCount; ++slot) { | ||
| 1173 | Module* m = installed[slot]; | ||
| 1174 | if (!m || !m->initialised) continue; | ||
| 1175 | try { | ||
| 1176 | run_callbacks(*m, DLL_THREAD_ATTACH); | ||
| 902 | } catch (const std::exception& e) { | 1177 | } catch (const std::exception& e) { |
| 903 | // The thread runs on without this module's TLS; later slots still get theirs. | ||
| 904 | std::fprintf(stderr, "[rt] loader: thread attach, slot %zu (%s): %s\n", slot, m->name.c_str(), | 1178 | std::fprintf(stderr, "[rt] loader: thread attach, slot %zu (%s): %s\n", slot, m->name.c_str(), |
| 905 | e.what()); | 1179 | e.what()); |
| 906 | } | 1180 | } |
| @@ -913,7 +1187,8 @@ void __cdecl on_host_thread_event(DWORD reason) { | |||
| 913 | } catch (const std::exception& e) { | 1187 | } catch (const std::exception& e) { |
| 914 | std::fprintf(stderr, "[rt] loader: thread detach: %s\n", e.what()); | 1188 | std::fprintf(stderr, "[rt] loader: thread detach: %s\n", e.what()); |
| 915 | } | 1189 | } |
| 916 | for (size_t i = kMaxMappedTlsModules; i-- > 0;) { | 1190 | for (size_t step = 0; step < kTlsSlotCount; ++step) { |
| 1191 | const size_t i = step < kMaxMappedTlsModules ? kMaxMappedTlsModules - 1 - step : kMainImageSlot; | ||
| 917 | Module* m = g_tls_slot_owners[i].load(); | 1192 | Module* m = g_tls_slot_owners[i].load(); |
| 918 | if (m && g_thread_tls_slots[i].module == m && | 1193 | if (m && g_thread_tls_slots[i].module == m && |
| 919 | g_thread_tls_slots[i].generation == m->tls_generation) { | 1194 | g_thread_tls_slots[i].generation == m->tls_generation) { |
| @@ -1017,6 +1292,26 @@ void redirect_pc_to_file_header_at(const void* resolved) { | |||
| 1017 | // Declared in pe_loader.h; the body needs the internal clone registry above. | 1292 | // Declared in pe_loader.h; the body needs the internal clone registry above. |
| 1018 | void cleanup_tls_clones() { cleanup_tls_clones_internal(); } | 1293 | void cleanup_tls_clones() { cleanup_tls_clones_internal(); } |
| 1019 | 1294 | ||
| 1295 | bool reserve_tls_index0(std::string* why) { | ||
| 1296 | std::lock_guard alloc_lock(g_tls_alloc_mutex); | ||
| 1297 | static bool attempted = false; // once: a later attempt could meet threads that already run this EXE's code | ||
| 1298 | if (!attempted) { | ||
| 1299 | attempted = true; | ||
| 1300 | // A throw (std::filesystem::temp_directory_path when GetTempPathW fails, an allocation) is a failed | ||
| 1301 | // reservation like any other: gta6rt calls this before main, where an exception would end it with no message. | ||
| 1302 | try { | ||
| 1303 | const std::string reason = reserve_index0(); | ||
| 1304 | std::snprintf(g_index0.why, sizeof(g_index0.why), "%s", reason.c_str()); | ||
| 1305 | } catch (const std::exception& e) { | ||
| 1306 | std::snprintf(g_index0.why, sizeof(g_index0.why), "%s", e.what()); | ||
| 1307 | } catch (...) { | ||
| 1308 | std::snprintf(g_index0.why, sizeof(g_index0.why), "an unknown error while reserving it"); | ||
| 1309 | } | ||
| 1310 | } | ||
| 1311 | if (why) *why = g_index0.moved ? std::string() : std::string(g_index0.why); | ||
| 1312 | return g_index0.moved; | ||
| 1313 | } | ||
| 1314 | |||
| 1020 | namespace { | 1315 | namespace { |
| 1021 | bool lookup_in_loader(void* ctx, uint64_t address, std::string& module, uint32_t& rva) { | 1316 | bool lookup_in_loader(void* ctx, uint64_t address, std::string& module, uint32_t& rva) { |
| 1022 | return static_cast<Loader*>(ctx)->find_address(address, module, rva); | 1317 | return static_cast<Loader*>(ctx)->find_address(address, module, rva); |
| @@ -1094,11 +1389,12 @@ Loader::~Loader() { | |||
| 1094 | entry(m.base, DLL_PROCESS_DETACH, nullptr); // explicit unload; the return value is ignored | 1389 | entry(m.base, DLL_PROCESS_DETACH, nullptr); // explicit unload; the return value is ignored |
| 1095 | } | 1390 | } |
| 1096 | } | 1391 | } |
| 1392 | shims::remove_xmem_allocation_hooks(this); | ||
| 1097 | shims::remove_bundled_loader(this); | 1393 | shims::remove_bundled_loader(this); |
| 1098 | shims::remove_module_lookup(this); | 1394 | shims::remove_module_lookup(this); |
| 1099 | for (auto* m : order_) { | 1395 | for (auto* m : order_) { |
| 1100 | // TLS state must go away before the image and its TLS block are unmapped. | 1396 | // TLS state must go away before the image and its TLS block are unmapped. |
| 1101 | if (m->tls_index != kNoTlsIndex && m->tls_slot < kMaxMappedTlsModules) { | 1397 | if (m->tls_index != kNoTlsIndex && m->tls_slot < kTlsSlotCount) { |
| 1102 | // Retired first, under the lock: no thread event installs it or runs its callbacks after this, and a | 1398 | // Retired first, under the lock: no thread event installs it or runs its callbacks after this, and a |
| 1103 | // thread that still holds a copy frees it when it ends (on_host_thread_event). | 1399 | // thread that still holds a copy frees it when it ends (on_host_thread_event). |
| 1104 | { | 1400 | { |
| @@ -1498,6 +1794,12 @@ Module& Loader::map_image(const std::filesystem::path& path, const std::string& | |||
| 1498 | // installed here, before bind_imports can return control to the caller and before any image code can run. | 1794 | // installed here, before bind_imports can return control to the caller and before any image code can run. |
| 1499 | initialize_tls(*m); | 1795 | initialize_tls(*m); |
| 1500 | parse_exports(*m); | 1796 | parse_exports(*m); |
| 1797 | if (auto it = m->exports.find("__XMemAllocationHooks__"); it != m->exports.end()) { | ||
| 1798 | const auto offset = static_cast<uint64_t>(static_cast<uint8_t*>(it->second) - m->base); | ||
| 1799 | if (offset <= m->size && m->size - offset >= sizeof(shims::XMemAllocationHooks)) { | ||
| 1800 | shims::add_xmem_allocation_hooks(this, static_cast<const shims::XMemAllocationHooks*>(it->second)); | ||
| 1801 | } | ||
| 1802 | } | ||
| 1501 | return *m; | 1803 | return *m; |
| 1502 | } | 1804 | } |
| 1503 | 1805 | ||
| @@ -1507,7 +1809,7 @@ Module& Loader::map_image(const std::filesystem::path& path, const std::string& | |||
| 1507 | // Only the OS loader can allocate that module index, so the loader reuses the index the OS assigned to | 1809 | // Only the OS loader can allocate that module index, so the loader reuses the index the OS assigned to |
| 1508 | // gta6rt_tls_host.dll and maps a fresh clone of the helper for every additional simultaneous TLS module, each clone | 1810 | // gta6rt_tls_host.dll and maps a fresh clone of the helper for every additional simultaneous TLS module, each clone |
| 1509 | // getting its own index. All kMaxMappedTlsModules slots can be live at once; a further module is rejected rather than | 1811 | // getting its own index. All kMaxMappedTlsModules slots can be live at once; a further module is rejected rather than |
| 1510 | // silently sharing (and corrupting) a slot. | 1812 | // silently sharing (and corrupting) a slot. An executable takes index 0 instead (kMainImageSlot), as on Windows. |
| 1511 | void Loader::initialize_tls(Module& m) { | 1813 | void Loader::initialize_tls(Module& m) { |
| 1512 | auto* tls = tls_directory(m); | 1814 | auto* tls = tls_directory(m); |
| 1513 | if (!tls) return; | 1815 | if (!tls) return; |
| @@ -1531,26 +1833,51 @@ void Loader::initialize_tls(Module& m) { | |||
| 1531 | 1833 | ||
| 1532 | if (!module_tls_slots()) throw std::runtime_error(m.name + ": this thread has no TLS array"); | 1834 | if (!module_tls_slots()) throw std::runtime_error(m.name + ": this thread has no TLS array"); |
| 1533 | 1835 | ||
| 1534 | size_t slot = kMaxMappedTlsModules; | 1836 | auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew); |
| 1837 | const bool executable = (nt->FileHeader.Characteristics & IMAGE_FILE_DLL) == 0; | ||
| 1838 | |||
| 1839 | size_t slot = kTlsSlotCount; | ||
| 1535 | DWORD index = TLS_OUT_OF_INDEXES; | 1840 | DWORD index = TLS_OUT_OF_INDEXES; |
| 1536 | { | 1841 | { |
| 1537 | std::lock_guard alloc_lock(g_tls_alloc_mutex); | 1842 | std::lock_guard alloc_lock(g_tls_alloc_mutex); |
| 1538 | for (size_t i = 0; i < kMaxMappedTlsModules; ++i) { | 1843 | if (executable) { |
| 1539 | if (g_tls_slot_owners[i].load() == nullptr) { | 1844 | if (g_index0.moved && g_tls_slot_owners[kMainImageSlot].load() == nullptr) { |
| 1540 | slot = i; | 1845 | slot = kMainImageSlot; |
| 1541 | break; | 1846 | index = 0; |
| 1847 | if (!g_index0.traced && startup_trace::enabled()) { | ||
| 1848 | g_index0.traced = true; | ||
| 1849 | startup_trace::event("tls_index0", "\"owner\":" + startup_trace::quote(g_index0.owner) + | ||
| 1850 | ",\"moved_to\":" + std::to_string(g_index0.home.index)); | ||
| 1851 | } | ||
| 1852 | } else { | ||
| 1853 | // Mapped on as a DLL is: its code that reads _tls_index works, but its /GA code would read and write | ||
| 1854 | // the block in slot 0, which is the runtime's own TLS or the other executable's. gta6rt refuses to | ||
| 1855 | // run such an image (main.cpp); a Loader user must not run its code either. | ||
| 1856 | std::fprintf(stderr, | ||
| 1857 | "[rt] loader: %s does not get module TLS index 0 (%s); its code built with /GA would use " | ||
| 1858 | "another module's TLS\n", | ||
| 1859 | m.name.c_str(), g_index0.moved ? "another mapped executable holds it" : g_index0.why); | ||
| 1542 | } | 1860 | } |
| 1543 | } | 1861 | } |
| 1544 | if (slot >= kMaxMappedTlsModules) | 1862 | if (slot == kTlsSlotCount) { |
| 1545 | throw std::runtime_error(m.name + ": all " + std::to_string(kMaxMappedTlsModules) + | 1863 | for (size_t i = 0; i < kMaxMappedTlsModules; ++i) { |
| 1546 | " manually mapped static TLS slots are in use"); | 1864 | if (g_tls_slot_owners[i].load() == nullptr) { |
| 1547 | 1865 | slot = i; | |
| 1548 | // Load/clone gta6rt_tls_host.dll OUTSIDE ExclusiveTlsLock so LoadLibraryExW cannot deadlock with | 1866 | break; |
| 1549 | // on_host_thread_event (which runs under the Windows loader lock and takes SharedTlsLock). | 1867 | } |
| 1550 | index = ensure_tls_host(slot).index; | 1868 | } |
| 1551 | if (index == TLS_OUT_OF_INDEXES) | 1869 | if (slot >= kMaxMappedTlsModules) |
| 1552 | throw std::runtime_error(m.name + ": gta6rt_tls_host.dll is missing or has no module TLS index"); | 1870 | throw std::runtime_error(m.name + ": all " + std::to_string(kMaxMappedTlsModules) + |
| 1553 | if (index >= kMaxModuleTlsSlots) throw std::runtime_error(m.name + ": reserved TLS index is out of range"); | 1871 | " manually mapped static TLS slots are in use"); |
| 1872 | |||
| 1873 | // Load/clone gta6rt_tls_host.dll OUTSIDE ExclusiveTlsLock so LoadLibraryExW cannot deadlock with | ||
| 1874 | // on_host_thread_event (which runs under the Windows loader lock and takes SharedTlsLock). | ||
| 1875 | index = ensure_tls_host(slot).index; | ||
| 1876 | if (index == TLS_OUT_OF_INDEXES) | ||
| 1877 | throw std::runtime_error(m.name + ": gta6rt_tls_host.dll is missing or has no module TLS index"); | ||
| 1878 | if (index >= kMaxModuleTlsSlots) | ||
| 1879 | throw std::runtime_error(m.name + ": reserved TLS index is out of range"); | ||
| 1880 | } | ||
| 1554 | 1881 | ||
| 1555 | // The fields are complete before a thread event can see the owner. | 1882 | // The fields are complete before a thread event can see the owner. |
| 1556 | ExclusiveTlsLock lock; | 1883 | ExclusiveTlsLock lock; |
| @@ -1847,6 +2174,24 @@ void Loader::bind_imports(Module& m) { | |||
| 1847 | void Loader::protect_sections(Module& m) { | 2174 | void Loader::protect_sections(Module& m) { |
| 1848 | auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew); | 2175 | auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew); |
| 1849 | DWORD old; | 2176 | DWORD old; |
| 2177 | // On a CPU without CLZERO, the image's CLZERO loops run from stubs instead of taking a #UD per cache line | ||
| 2178 | // (clzero_patch.h). The sections are still writable here, and none of the image's code has run. | ||
| 2179 | static const bool clzero_missing = !rt::cpu_emulation::detect_host().clzero; | ||
| 2180 | if (clzero_missing && rt::clzero_patch::enabled()) { | ||
| 2181 | std::vector<std::pair<uint8_t*, size_t>> code; | ||
| 2182 | const IMAGE_SECTION_HEADER* cs = IMAGE_FIRST_SECTION(nt); | ||
| 2183 | for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++cs) { | ||
| 2184 | if (!(cs->Characteristics & IMAGE_SCN_MEM_EXECUTE) || cs->VirtualAddress >= m.size) continue; | ||
| 2185 | const uint64_t size = std::min<uint64_t>(std::min(cs->Misc.VirtualSize, cs->SizeOfRawData), | ||
| 2186 | m.size - cs->VirtualAddress); | ||
| 2187 | if (size) code.push_back({m.base + cs->VirtualAddress, static_cast<size_t>(size)}); | ||
| 2188 | } | ||
| 2189 | const auto patched = rt::clzero_patch::patch(code, uint64_t(m.base), uint64_t(m.base) + m.size); | ||
| 2190 | if (patched.sites) | ||
| 2191 | std::fprintf(stderr, | ||
| 2192 | "[rt] loader: %s: %zu CLZERO loops run from stubs at %p (%zu bytes), not as a #UD per line\n", | ||
| 2193 | m.name.c_str(), patched.sites, static_cast<void*>(patched.stubs), patched.stub_bytes); | ||
| 2194 | } | ||
| 1850 | VirtualProtect(m.base, nt->OptionalHeader.SizeOfHeaders, PAGE_READONLY, &old); | 2195 | VirtualProtect(m.base, nt->OptionalHeader.SizeOfHeaders, PAGE_READONLY, &old); |
| 1851 | auto* sec = IMAGE_FIRST_SECTION(nt); | 2196 | auto* sec = IMAGE_FIRST_SECTION(nt); |
| 1852 | for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++sec) { | 2197 | for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++sec) { |