diff options
| author | kett1m <benho0@proton.me> | 2026-11-29 20:30:08 +0100 |
|---|---|---|
| committer | kett1m <benho0@proton.me> | 2026-11-29 20:30:08 +0100 |
| commit | 72eedf1589aad277c1839929f3d6ae6bd4823be9 (patch) | |
| tree | 0e790e14655e9245e85ff56d483e260bc540e81a /runtime/src/pe_loader.cpp | |
| parent | 84239b50b2af3e040a911727583de8edac260469 (diff) | |
| parent | dd87aa405a0d48cbce4269c9d20e50c3ec8b5dbc (diff) | |
Merge remote-tracking branch 'origin/main' into x64-recomp-vex-bounds
# Conflicts:
# tests/test_x64_recomp.py
Diffstat (limited to 'runtime/src/pe_loader.cpp')
| -rw-r--r-- | runtime/src/pe_loader.cpp | 780 |
1 files changed, 656 insertions, 124 deletions
diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index c29a288a9..49588b424 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp | |||
| @@ -2,6 +2,7 @@ | |||
| 2 | 2 | ||
| 3 | #include <windows.h> | 3 | #include <windows.h> |
| 4 | #include <intrin.h> | 4 | #include <intrin.h> |
| 5 | #include <share.h> | ||
| 5 | #include <tlhelp32.h> | 6 | #include <tlhelp32.h> |
| 6 | 7 | ||
| 7 | #include <algorithm> | 8 | #include <algorithm> |
| @@ -10,7 +11,7 @@ | |||
| 10 | #include <cstdio> | 11 | #include <cstdio> |
| 11 | #include <cstdlib> | 12 | #include <cstdlib> |
| 12 | #include <cstring> | 13 | #include <cstring> |
| 13 | #include <fstream> | 14 | #include <memory> |
| 14 | #include <mutex> | 15 | #include <mutex> |
| 15 | #include <stdexcept> | 16 | #include <stdexcept> |
| 16 | #include <system_error> | 17 | #include <system_error> |
| @@ -19,6 +20,10 @@ | |||
| 19 | #include "../shims/shims.h" | 20 | #include "../shims/shims.h" |
| 20 | #include "../shims/startup_trace.h" | 21 | #include "../shims/startup_trace.h" |
| 21 | #include "base_reservation.h" | 22 | #include "base_reservation.h" |
| 23 | #include "bmi_emulation.h" | ||
| 24 | #include "clzero_patch.h" | ||
| 25 | #include "cpu_emulation.h" | ||
| 26 | #include "isa_jit_patch.h" | ||
| 22 | 27 | ||
| 23 | namespace rt { | 28 | namespace rt { |
| 24 | 29 | ||
| @@ -75,9 +80,16 @@ std::string path_utf8(const std::filesystem::path& path) { | |||
| 75 | } | 80 | } |
| 76 | 81 | ||
| 77 | std::vector<uint8_t> read_file(const std::filesystem::path& p) { | 82 | std::vector<uint8_t> read_file(const std::filesystem::path& p) { |
| 78 | std::ifstream f(p, std::ios::binary); | 83 | std::unique_ptr<std::FILE, decltype(&std::fclose)> file( |
| 79 | if (!f) throw std::runtime_error("cannot open " + path_utf8(p)); | 84 | _wfsopen(p.c_str(), L"rb", _SH_DENYNO), std::fclose); |
| 80 | return {std::istreambuf_iterator<char>(f), {}}; | 85 | if (!file) throw std::runtime_error("cannot open " + path_utf8(p)); |
| 86 | |||
| 87 | std::vector<uint8_t> bytes; | ||
| 88 | std::array<uint8_t, 64 * 1024> block; | ||
| 89 | while (const auto count = std::fread(block.data(), 1, block.size(), file.get())) | ||
| 90 | bytes.insert(bytes.end(), block.data(), block.data() + count); | ||
| 91 | if (std::ferror(file.get())) throw std::runtime_error("cannot read " + path_utf8(p)); | ||
| 92 | return bytes; | ||
| 81 | } | 93 | } |
| 82 | 94 | ||
| 83 | template <class T> | 95 | template <class T> |
| @@ -126,8 +138,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 | 138 | // 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 | 139 | // 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). | 140 | // module TLS index for each simultaneous module (up to kMaxMappedTlsModules). |
| 141 | // | ||
| 142 | // A mapped executable is different: MSVC code built with /GA (an EXE-only optimisation) skips _tls_index and reads | ||
| 143 | // TEB->ThreadLocalStoragePointer[0] directly (mov rax, gs:[58h]; mov rax, [rax]), because Windows always gives the | ||
| 144 | // process executable module TLS index 0. Measured with a `thread_local int v = 42;` EXE built /O2 /GA /MD: natively | ||
| 145 | // tls_index=0 value=42; mapped with a helper index (6) the code still read slot 0 and printed value=0. Index 0 | ||
| 146 | // belongs to the runtime's own EXE (gta6rt.exe: a 1398-byte template when measured, no TLS callbacks; so does each | ||
| 147 | // test EXE that links this file), and every TLS read in its disassembly goes through _tls_index (the only direct | ||
| 148 | // gs:[58h] read is module_tls_slots below, which wants the array itself). reserve_tls_index0 therefore moves the owner | ||
| 149 | // off index 0, once, at process start: it loads the home clone (make_home_clone_image), whose TLS template is a copy of | ||
| 150 | // 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 | ||
| 151 | // starts has a fresh copy of the owner's template at home, which is where the owner looks, from its first instruction: | ||
| 152 | // nothing has to run on a new thread first. Slot 0 holds a block nobody reads, which the mapped executable's copy | ||
| 153 | // replaces (kMainImageSlot) exactly as a DLL's copy replaces a helper's, and the OS frees both slots at thread exit. | ||
| 154 | // It has to happen before any other thread has run the owner's code: MSVC keeps &ThreadLocalStoragePointer[_tls_index] | ||
| 155 | // across calls (zlib_inflate in shader_library.h saves it at [rbp-80h] across memset, push_back and inflate_codes, then | ||
| 156 | // reads _Init_thread_epoch through it), so a running thread cannot be moved safely, wherever it is stopped. Such a | ||
| 157 | // thread's TLS would also stay where it was, at index 0. | ||
| 129 | constexpr DWORD kMaxModuleTlsSlots = 64; | 158 | constexpr DWORD kMaxModuleTlsSlots = 64; |
| 130 | constexpr size_t kMaxMappedTlsModules = 16; | 159 | constexpr size_t kMaxMappedTlsModules = 16; |
| 160 | // The slot for a mapped executable, which reads module TLS index 0 (see above). Only one at a time; a second | ||
| 161 | // executable mapped while one is live gets an ordinary helper slot. kTlsSlotCount sizes the per-slot tables. | ||
| 162 | constexpr size_t kMainImageSlot = kMaxMappedTlsModules; | ||
| 163 | constexpr size_t kTlsSlotCount = kMaxMappedTlsModules + 1; | ||
| 131 | void** module_tls_slots() { return reinterpret_cast<void**>(__readgsqword(0x58)); } | 164 | void** module_tls_slots() { return reinterpret_cast<void**>(__readgsqword(0x58)); } |
| 132 | 165 | ||
| 133 | void __cdecl on_host_thread_event(DWORD reason); | 166 | void __cdecl on_host_thread_event(DWORD reason); |
| @@ -135,6 +168,7 @@ void __cdecl on_host_thread_event(DWORD reason); | |||
| 135 | struct TlsHostModule { | 168 | struct TlsHostModule { |
| 136 | HMODULE module = nullptr; | 169 | HMODULE module = nullptr; |
| 137 | DWORD index = TLS_OUT_OF_INDEXES; | 170 | DWORD index = TLS_OUT_OF_INDEXES; |
| 171 | bool hooked = false; // its DllMain reports thread events to on_host_thread_event | ||
| 138 | }; | 172 | }; |
| 139 | 173 | ||
| 140 | std::filesystem::path tls_host_base_path() { | 174 | std::filesystem::path tls_host_base_path() { |
| @@ -154,6 +188,15 @@ std::filesystem::path tls_host_base_path() { | |||
| 154 | } | 188 | } |
| 155 | 189 | ||
| 156 | std::filesystem::path tls_host_clone_dir() { | 190 | std::filesystem::path tls_host_clone_dir() { |
| 191 | if (const char* dir = std::getenv("LEONIDA_TEST_DIR"); dir && *dir) return std::filesystem::path(dir); | ||
| 192 | const char* tmp = std::getenv("TMP"); | ||
| 193 | const char* temp = std::getenv("TEMP"); | ||
| 194 | const char* profile = std::getenv("USERPROFILE"); | ||
| 195 | if ((!tmp || !*tmp) && (!temp || !*temp) && (!profile || !*profile)) { | ||
| 196 | std::error_code ec; | ||
| 197 | auto cwd = std::filesystem::current_path(ec); | ||
| 198 | if (!ec) return cwd; | ||
| 199 | } | ||
| 157 | wchar_t buf[MAX_PATH]; | 200 | wchar_t buf[MAX_PATH]; |
| 158 | DWORD n = GetTempPathW(MAX_PATH, buf); | 201 | DWORD n = GetTempPathW(MAX_PATH, buf); |
| 159 | if (n > 0 && n < MAX_PATH) return std::filesystem::path(buf); | 202 | if (n > 0 && n < MAX_PATH) return std::filesystem::path(buf); |
| @@ -167,20 +210,39 @@ struct TlsCloneRecord { | |||
| 167 | 210 | ||
| 168 | std::mutex g_tls_alloc_mutex; | 211 | std::mutex g_tls_alloc_mutex; |
| 169 | std::array<TlsHostModule, kMaxMappedTlsModules> g_tls_hosts{}; | 212 | std::array<TlsHostModule, kMaxMappedTlsModules> g_tls_hosts{}; |
| 170 | std::array<std::atomic<Module*>, kMaxMappedTlsModules> g_tls_slot_owners{}; | 213 | std::array<std::atomic<Module*>, kTlsSlotCount> g_tls_slot_owners{}; |
| 171 | std::array<std::atomic<uint64_t>, kMaxMappedTlsModules> g_tls_slot_generations{}; | 214 | std::array<std::atomic<uint64_t>, kTlsSlotCount> g_tls_slot_generations{}; |
| 172 | std::atomic<uint64_t> g_next_tls_generation{1}; | 215 | std::atomic<uint64_t> g_next_tls_generation{1}; |
| 173 | std::vector<TlsCloneRecord> g_tls_clones; | 216 | // Allocated with the first clone and never destroyed: cleanup_tls_clones_at_exit runs from the atexit table, and a |
| 217 | // static vector's destructor (registered when its dynamic initializer ran) could run before it. Under | ||
| 218 | // g_tls_alloc_mutex, as are its records. | ||
| 219 | std::vector<TlsCloneRecord>* g_tls_clones = nullptr; | ||
| 220 | |||
| 221 | // The move of module TLS index 0 (see kMainImageSlot): done at most once, by reserve_tls_index0 under | ||
| 222 | // g_tls_alloc_mutex. `why` is the reason it was not done, for the executable that then maps with a helper index. | ||
| 223 | // Constant-initialized only (no std::string): gta6rt reserves from a CRT initializer that runs before the dynamic | ||
| 224 | // initializers of this file, which would otherwise reset what it wrote. | ||
| 225 | struct Index0Move { | ||
| 226 | bool moved = false; | ||
| 227 | bool traced = false; // the startup trace opens after the move; the first executable map reports it | ||
| 228 | TlsHostModule home; // the clone whose index holds the owner's TLS from now on; never freed | ||
| 229 | char owner[260] = {}; // UTF-8 file name of the image that held index 0 | ||
| 230 | char why[160] = "reserve_tls_index0 was not called at process start"; | ||
| 231 | }; | ||
| 232 | Index0Move g_index0; | ||
| 174 | 233 | ||
| 175 | // Frees every TLS helper clone this process loaded and deletes its files. load() registers the wrapper with atexit; | 234 | // 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 | 235 | // 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. | 236 | // ExitProcess, which skips the atexit table. Call it only when no mapped code can run again: it unmaps the helper |
| 237 | // images. The home clone is not recorded (reserve_index0): it stays loaded, so its file outlives the process and the | ||
| 238 | // next run's sweep deletes it. | ||
| 178 | void cleanup_tls_clones_internal() { | 239 | void cleanup_tls_clones_internal() { |
| 179 | for (const auto& rec : g_tls_clones) { | 240 | if (!g_tls_clones) return; |
| 241 | for (const auto& rec : *g_tls_clones) { | ||
| 180 | if (rec.module) FreeLibrary(rec.module); | 242 | if (rec.module) FreeLibrary(rec.module); |
| 181 | if (!rec.path.empty()) DeleteFileW(rec.path.c_str()); | 243 | if (!rec.path.empty()) DeleteFileW(rec.path.c_str()); |
| 182 | } | 244 | } |
| 183 | g_tls_clones.clear(); | 245 | g_tls_clones->clear(); |
| 184 | } | 246 | } |
| 185 | 247 | ||
| 186 | void cleanup_tls_clones_at_exit() { cleanup_tls_clones_internal(); } | 248 | void cleanup_tls_clones_at_exit() { cleanup_tls_clones_internal(); } |
| @@ -204,10 +266,14 @@ DWORD clone_owner_pid(const wchar_t* name) { | |||
| 204 | bool process_alive(DWORD pid) { | 266 | bool process_alive(DWORD pid) { |
| 205 | // PROCESS_QUERY_LIMITED_INFORMATION needs no handle rights a normal process could deny; a failure means the | 267 | // 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. | 268 | // process is gone. A still-mapped or still-open file is caught by the checks below even for a misjudged PID. |
| 269 | // OpenProcess also succeeds on a process that has ended while another process still holds a handle to it (a | ||
| 270 | // 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); | 271 | HANDLE p = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid); |
| 208 | if (!p) return false; | 272 | if (!p) return false; |
| 273 | DWORD code = 0; | ||
| 274 | const bool alive = !GetExitCodeProcess(p, &code) || code == STILL_ACTIVE; | ||
| 209 | CloseHandle(p); | 275 | CloseHandle(p); |
| 210 | return true; | 276 | return alive; |
| 211 | } | 277 | } |
| 212 | 278 | ||
| 213 | // Deletes clones left behind by processes that have exited. Deletion is scoped to files whose owner is gone: a | 279 | // Deletes clones left behind by processes that have exited. Deletion is scoped to files whose owner is gone: a |
| @@ -262,45 +328,66 @@ TlsHostModule load_tls_host_image(const std::filesystem::path& path, bool hook_t | |||
| 262 | if (hook_thread_events) { | 328 | if (hook_thread_events) { |
| 263 | // Only the primary helper reports thread attach/detach events; on_host_thread_event iterates all active slots. | 329 | // 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)); | 330 | using SetThreadEvent = void(__cdecl*)(void(__cdecl*)(DWORD)); |
| 265 | if (auto set = reinterpret_cast<SetThreadEvent>(GetProcAddress(host.module, "gta6rt_tls_host_set_thread_event"))) | 331 | auto set = reinterpret_cast<SetThreadEvent>(GetProcAddress(host.module, "gta6rt_tls_host_set_thread_event")); |
| 332 | if (set) { | ||
| 266 | set(&on_host_thread_event); | 333 | set(&on_host_thread_event); |
| 334 | host.hooked = true; | ||
| 335 | } | ||
| 267 | } | 336 | } |
| 268 | return host; | 337 | return host; |
| 269 | } | 338 | } |
| 270 | 339 | ||
| 271 | // Must be called with g_tls_alloc_mutex held and WITHOUT g_tls_lock held (LoadLibraryExW takes the Windows loader lock). | 340 | // 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) { | 341 | // 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 {}; | 342 | // Windows loader lock). |
| 274 | if (g_tls_hosts[slot].index != TLS_OUT_OF_INDEXES) return g_tls_hosts[slot]; | 343 | // A helper without the thread-event export is refused: no thread started later would get its copies. |
| 275 | 344 | bool ensure_primary_tls_host() { | |
| 345 | if (g_tls_hosts[0].index != TLS_OUT_OF_INDEXES) return true; | ||
| 276 | const std::filesystem::path primary = tls_host_base_path(); | 346 | const std::filesystem::path primary = tls_host_base_path(); |
| 277 | if (primary.empty()) return {}; | 347 | if (primary.empty()) return false; |
| 278 | 348 | TlsHostModule host = load_tls_host_image(primary, true); | |
| 279 | if (slot == 0) { | 349 | if (host.index != TLS_OUT_OF_INDEXES && !host.hooked) { |
| 280 | g_tls_hosts[0] = load_tls_host_image(primary, true); | 350 | FreeLibrary(host.module); |
| 281 | return g_tls_hosts[0]; | 351 | 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 | } | 352 | } |
| 353 | g_tls_hosts[0] = host; | ||
| 354 | return host.index != TLS_OUT_OF_INDEXES; | ||
| 355 | } | ||
| 289 | 356 | ||
| 357 | // Copies gta6rt_tls_host.dll (or writes `image`, a changed copy of it) to "leonida_tls_host_<pid>_<tag>.dll" in the | ||
| 358 | // clone directory and loads it, so the OS gives the copy an index of its own. On failure the file is gone again and | ||
| 359 | // the result has no index. The caller records the clone (g_tls_clones) if it is to be freed at exit. Same locking rule | ||
| 360 | // as ensure_primary_tls_host. | ||
| 361 | TlsHostModule load_tls_host_clone(const std::wstring& tag, std::filesystem::path& clone_path, | ||
| 362 | const std::vector<uint8_t>* image = nullptr) { | ||
| 363 | const std::filesystem::path primary = tls_host_base_path(); | ||
| 364 | if (primary.empty()) return {}; | ||
| 290 | // Clone gta6rt_tls_host.dll to a distinct path using CopyFileW (Wine 9 lacks CopyFile2 used by std::filesystem). | 365 | // 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(); | 366 | const std::filesystem::path dir = tls_host_clone_dir(); |
| 292 | static bool swept = false; | 367 | static bool swept = false; |
| 293 | if (!swept) { | 368 | if (!swept) { |
| 294 | swept = true; | 369 | swept = true; |
| 295 | sweep_stale_tls_clones(dir); | 370 | sweep_stale_tls_clones(dir); |
| 296 | std::atexit(&cleanup_tls_clones_at_exit); | ||
| 297 | } | 371 | } |
| 298 | const std::wstring name = | 372 | 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"; | 373 | 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. | 374 | // 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"; | 375 | const std::filesystem::path staging = clone_path.wstring() + L".new"; |
| 303 | if (!CopyFileW(primary.c_str(), staging.c_str(), FALSE)) return {}; | 376 | if (image) { |
| 377 | HANDLE out = | ||
| 378 | CreateFileW(staging.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); | ||
| 379 | if (out == INVALID_HANDLE_VALUE) return {}; | ||
| 380 | DWORD written = 0; | ||
| 381 | const bool ok = WriteFile(out, image->data(), static_cast<DWORD>(image->size()), &written, nullptr) && | ||
| 382 | written == image->size(); | ||
| 383 | CloseHandle(out); | ||
| 384 | if (!ok) { | ||
| 385 | DeleteFileW(staging.c_str()); | ||
| 386 | return {}; | ||
| 387 | } | ||
| 388 | } else if (!CopyFileW(primary.c_str(), staging.c_str(), FALSE)) { | ||
| 389 | return {}; | ||
| 390 | } | ||
| 304 | 391 | ||
| 305 | // Open the guard before the clone exists under its final name and hold it across LoadLibraryExW: the rename | 392 | // 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 | 393 | // below needs DELETE access, which the handle's FILE_SHARE_DELETE grants, and no purge can remove the clone |
| @@ -320,18 +407,34 @@ TlsHostModule ensure_tls_host(size_t slot) { | |||
| 320 | TlsHostModule loaded = load_tls_host_image(clone_path, false); | 407 | TlsHostModule loaded = load_tls_host_image(clone_path, false); |
| 321 | CloseHandle(guard); | 408 | CloseHandle(guard); |
| 322 | 409 | ||
| 323 | if (loaded.index == TLS_OUT_OF_INDEXES) { | 410 | if (loaded.index == TLS_OUT_OF_INDEXES) DeleteFileW(clone_path.c_str()); |
| 411 | return loaded; | ||
| 412 | } | ||
| 413 | |||
| 414 | // Must be called with g_tls_alloc_mutex held and WITHOUT g_tls_lock held (LoadLibraryExW takes the Windows loader lock). | ||
| 415 | TlsHostModule ensure_tls_host(size_t slot) { | ||
| 416 | if (slot >= kMaxMappedTlsModules) return {}; | ||
| 417 | if (g_tls_hosts[slot].index != TLS_OUT_OF_INDEXES) return g_tls_hosts[slot]; | ||
| 418 | // Slot 0 is the primary helper; it is loaded first in any case so thread attach/detach events are hooked. | ||
| 419 | if (!ensure_primary_tls_host()) return {}; | ||
| 420 | if (slot == 0) return g_tls_hosts[0]; | ||
| 421 | |||
| 422 | std::filesystem::path clone_path; | ||
| 423 | TlsHostModule loaded = load_tls_host_clone(std::to_wstring(slot), clone_path); | ||
| 424 | if (loaded.index == TLS_OUT_OF_INDEXES) return {}; | ||
| 425 | // Index 0 is the runtime EXE's, and after the move the home clone's index holds that EXE's TLS. | ||
| 426 | bool taken = loaded.index == 0 || loaded.index == g_index0.home.index; | ||
| 427 | for (size_t i = 0; i < kMaxMappedTlsModules; ++i) taken |= i != slot && g_tls_hosts[i].index == loaded.index; | ||
| 428 | if (taken) { | ||
| 429 | FreeLibrary(loaded.module); | ||
| 324 | DeleteFileW(clone_path.c_str()); | 430 | DeleteFileW(clone_path.c_str()); |
| 325 | return {}; | 431 | return {}; |
| 326 | } | 432 | } |
| 327 | for (size_t i = 0; i < kMaxMappedTlsModules; ++i) { | 433 | if (!g_tls_clones) { |
| 328 | if (i != slot && g_tls_hosts[i].index == loaded.index) { | 434 | g_tls_clones = new std::vector<TlsCloneRecord>; |
| 329 | FreeLibrary(loaded.module); | 435 | std::atexit(&cleanup_tls_clones_at_exit); |
| 330 | DeleteFileW(clone_path.c_str()); | ||
| 331 | return {}; | ||
| 332 | } | ||
| 333 | } | 436 | } |
| 334 | g_tls_clones.push_back({loaded.module, clone_path}); | 437 | g_tls_clones->push_back({loaded.module, clone_path}); |
| 335 | g_tls_hosts[slot] = loaded; | 438 | g_tls_hosts[slot] = loaded; |
| 336 | return g_tls_hosts[slot]; | 439 | return g_tls_hosts[slot]; |
| 337 | } | 440 | } |
| @@ -347,7 +450,7 @@ struct ThreadTlsSlot { | |||
| 347 | }; | 450 | }; |
| 348 | 451 | ||
| 349 | // Per-thread installation state for each reserved TLS slot. | 452 | // Per-thread installation state for each reserved TLS slot. |
| 350 | thread_local std::array<ThreadTlsSlot, kMaxMappedTlsModules> g_thread_tls_slots{}; | 453 | thread_local std::array<ThreadTlsSlot, kTlsSlotCount> g_thread_tls_slots{}; |
| 351 | 454 | ||
| 352 | // Orders the TLS owners' publication, their `initialised` flags and their retirement against the thread events. Shared | 455 | // 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 | 456 | // in on_host_thread_event, exclusive only for those short writes (no allocation and no call that takes the Windows |
| @@ -366,10 +469,185 @@ struct ExclusiveTlsLock { | |||
| 366 | ExclusiveTlsLock& operator=(const ExclusiveTlsLock&) = delete; | 469 | ExclusiveTlsLock& operator=(const ExclusiveTlsLock&) = delete; |
| 367 | }; | 470 | }; |
| 368 | 471 | ||
| 472 | // gta6rt_tls_host.dll's exports that the home clone's TLS directory is pointed at (tls_host.cpp): a zero array in its | ||
| 473 | // .rdata and that array's size. | ||
| 474 | constexpr char kHomeTemplateExport[] = "gta6rt_tls_home_template"; | ||
| 475 | constexpr char kHomeTemplateSizeExport[] = "gta6rt_tls_home_template_size"; | ||
| 476 | |||
| 477 | // File offset of `len` bytes at `rva` in an image file held in memory, or SIZE_MAX when they are not all inside one | ||
| 478 | // section's raw data. | ||
| 479 | size_t file_offset(const std::vector<uint8_t>& file, const IMAGE_NT_HEADERS64* nt, uint64_t rva, uint64_t len) { | ||
| 480 | const auto* sec = IMAGE_FIRST_SECTION(nt); | ||
| 481 | for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++sec) { | ||
| 482 | if (reinterpret_cast<const uint8_t*>(sec + 1) > file.data() + file.size()) break; | ||
| 483 | if (rva < sec->VirtualAddress || rva + len > static_cast<uint64_t>(sec->VirtualAddress) + sec->SizeOfRawData) | ||
| 484 | continue; | ||
| 485 | const uint64_t off = sec->PointerToRawData + (rva - sec->VirtualAddress); | ||
| 486 | return off + len <= file.size() ? static_cast<size_t>(off) : SIZE_MAX; | ||
| 487 | } | ||
| 488 | return SIZE_MAX; | ||
| 489 | } | ||
| 490 | |||
| 491 | // The RVA of a named export in an image file held in memory, 0 when it has none. | ||
| 492 | uint32_t file_export(const std::vector<uint8_t>& file, const IMAGE_NT_HEADERS64* nt, const char* wanted) { | ||
| 493 | const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_EXPORT); | ||
| 494 | const size_t ed_off = file_offset(file, nt, dir.VirtualAddress, sizeof(IMAGE_EXPORT_DIRECTORY)); | ||
| 495 | if (!dir.Size || ed_off == SIZE_MAX) return 0; | ||
| 496 | const auto* ed = reinterpret_cast<const IMAGE_EXPORT_DIRECTORY*>(file.data() + ed_off); | ||
| 497 | const size_t names = file_offset(file, nt, ed->AddressOfNames, uint64_t{4} * ed->NumberOfNames); | ||
| 498 | const size_t ords = file_offset(file, nt, ed->AddressOfNameOrdinals, uint64_t{2} * ed->NumberOfNames); | ||
| 499 | const size_t funcs = file_offset(file, nt, ed->AddressOfFunctions, uint64_t{4} * ed->NumberOfFunctions); | ||
| 500 | if (names == SIZE_MAX || ords == SIZE_MAX || funcs == SIZE_MAX) return 0; | ||
| 501 | const size_t wanted_len = std::strlen(wanted) + 1; | ||
| 502 | for (uint32_t i = 0; i < ed->NumberOfNames; ++i) { | ||
| 503 | uint32_t name_rva, func_rva; | ||
| 504 | uint16_t ord; | ||
| 505 | std::memcpy(&name_rva, file.data() + names + 4 * i, 4); | ||
| 506 | std::memcpy(&ord, file.data() + ords + 2 * i, 2); | ||
| 507 | const size_t name = file_offset(file, nt, name_rva, wanted_len); | ||
| 508 | if (name == SIZE_MAX || std::memcmp(file.data() + name, wanted, wanted_len) != 0) continue; | ||
| 509 | if (ord >= ed->NumberOfFunctions) return 0; | ||
| 510 | std::memcpy(&func_rva, file.data() + funcs + 4 * ord, 4); | ||
| 511 | return func_rva; | ||
| 512 | } | ||
| 513 | return 0; | ||
| 514 | } | ||
| 515 | |||
| 516 | // Turns gta6rt_tls_host.dll's bytes into the home clone: its TLS directory now covers gta6rt_tls_home_template, which | ||
| 517 | // starts with a copy of the owner's template (taken from the mapped owner, so its pointers are already relocated; the | ||
| 518 | // array itself has no relocations), and takes the owner's alignment. The OS then gives every thread, at the home | ||
| 519 | // index, a block that is a fresh copy of the owner's TLS. The zero fill goes into the covered range too: | ||
| 520 | // LdrpAllocateTls allocates and copies End - Start only (Windows 11 26300) and ignores SizeOfZeroFill. The directory's | ||
| 521 | // Start and End have base relocations, so they follow the clone wherever it loads. Empty on success, else why not. | ||
| 522 | std::string make_home_clone_image(std::vector<uint8_t>& file, const IMAGE_TLS_DIRECTORY64& owner) { | ||
| 523 | if (file.size() < sizeof(IMAGE_DOS_HEADER)) return "gta6rt_tls_host.dll is truncated"; | ||
| 524 | const auto* dos = reinterpret_cast<const IMAGE_DOS_HEADER*>(file.data()); | ||
| 525 | if (dos->e_magic != IMAGE_DOS_SIGNATURE || dos->e_lfanew < 0 || | ||
| 526 | static_cast<size_t>(dos->e_lfanew) + sizeof(IMAGE_NT_HEADERS64) > file.size()) | ||
| 527 | return "gta6rt_tls_host.dll has no PE header"; | ||
| 528 | auto* nt = reinterpret_cast<IMAGE_NT_HEADERS64*>(file.data() + dos->e_lfanew); | ||
| 529 | if (nt->Signature != IMAGE_NT_SIGNATURE || nt->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR64_MAGIC) | ||
| 530 | return "gta6rt_tls_host.dll is not a 64-bit image"; | ||
| 531 | const uint32_t array_rva = file_export(file, nt, kHomeTemplateExport); | ||
| 532 | const uint32_t size_rva = file_export(file, nt, kHomeTemplateSizeExport); | ||
| 533 | const size_t size_off = file_offset(file, nt, size_rva, sizeof(uint32_t)); | ||
| 534 | if (!array_rva || !size_rva || size_off == SIZE_MAX) | ||
| 535 | return "gta6rt_tls_host.dll has no gta6rt_tls_home_template"; | ||
| 536 | uint32_t capacity; | ||
| 537 | std::memcpy(&capacity, file.data() + size_off, sizeof(capacity)); | ||
| 538 | const uint64_t raw = owner.EndAddressOfRawData - owner.StartAddressOfRawData; | ||
| 539 | const uint64_t total = raw + owner.SizeOfZeroFill; | ||
| 540 | if (owner.EndAddressOfRawData < owner.StartAddressOfRawData || total > capacity) | ||
| 541 | return "the owner's TLS (" + std::to_string(total) + " bytes) does not fit gta6rt_tls_home_template (" + | ||
| 542 | std::to_string(capacity) + " bytes)"; | ||
| 543 | const size_t array_off = file_offset(file, nt, array_rva, capacity); | ||
| 544 | const auto tls_dir = directory(nt, IMAGE_DIRECTORY_ENTRY_TLS); | ||
| 545 | const size_t tls_off = file_offset(file, nt, tls_dir.VirtualAddress, sizeof(IMAGE_TLS_DIRECTORY64)); | ||
| 546 | if (array_off == SIZE_MAX || !tls_dir.Size || tls_off == SIZE_MAX) | ||
| 547 | return "gta6rt_tls_host.dll's TLS directory or home template lies outside its file"; | ||
| 548 | std::memcpy(file.data() + array_off, reinterpret_cast<const void*>(owner.StartAddressOfRawData), raw); | ||
| 549 | std::memset(file.data() + array_off + raw, 0, capacity - raw); | ||
| 550 | auto* tls = reinterpret_cast<IMAGE_TLS_DIRECTORY64*>(file.data() + tls_off); | ||
| 551 | tls->StartAddressOfRawData = nt->OptionalHeader.ImageBase + array_rva; | ||
| 552 | tls->EndAddressOfRawData = tls->StartAddressOfRawData + total; | ||
| 553 | tls->SizeOfZeroFill = 0; | ||
| 554 | tls->Characteristics = | ||
| 555 | (tls->Characteristics & ~IMAGE_SCN_ALIGN_MASK) | (owner.Characteristics & IMAGE_SCN_ALIGN_MASK); | ||
| 556 | return {}; | ||
| 557 | } | ||
| 558 | |||
| 559 | std::string module_file_name(HMODULE module) { | ||
| 560 | wchar_t path[MAX_PATH]; | ||
| 561 | const DWORD n = GetModuleFileNameW(module, path, MAX_PATH); | ||
| 562 | if (!n || n >= MAX_PATH) return "?"; | ||
| 563 | const wchar_t* name = path; | ||
| 564 | for (const wchar_t* p = path; *p; ++p) | ||
| 565 | if (*p == L'\\' || *p == L'/') name = p + 1; | ||
| 566 | const int bytes = WideCharToMultiByte(CP_UTF8, 0, name, -1, nullptr, 0, nullptr, nullptr); | ||
| 567 | if (bytes <= 1) return "?"; | ||
| 568 | std::string out(static_cast<size_t>(bytes - 1), '\0'); | ||
| 569 | WideCharToMultiByte(CP_UTF8, 0, name, -1, out.data(), bytes, nullptr, nullptr); | ||
| 570 | return out; | ||
| 571 | } | ||
| 572 | |||
| 573 | // The move on the calling thread, kept apart so that no frame of reserve_index0 holds a slot address across it. After | ||
| 574 | // it the owner's live block is at `home` and slot 0 holds the home clone's fresh copy, which nothing reads. | ||
| 575 | __declspec(noinline) void move_index0_on_this_thread(DWORD* owner_index, DWORD home) { | ||
| 576 | void** slots = module_tls_slots(); | ||
| 577 | std::swap(slots[0], slots[home]); | ||
| 578 | *owner_index = home; | ||
| 579 | } | ||
| 580 | |||
| 581 | // See reserve_tls_index0. Empty on success, else why not; nothing has changed then. g_tls_alloc_mutex held. It reads | ||
| 582 | // no thread_local data and runs no code that does, before or after the move. | ||
| 583 | std::string reserve_index0() { | ||
| 584 | // Windows gives index 0 to the process executable when it has TLS; a DLL can only hold it in a process whose EXE | ||
| 585 | // has none, and a DLL that is still loading or was loaded without its references resolved shows 0 too. | ||
| 586 | const HMODULE exe = GetModuleHandleW(nullptr); | ||
| 587 | auto* base = reinterpret_cast<uint8_t*>(exe); | ||
| 588 | auto* nt = at<IMAGE_NT_HEADERS64>(base, reinterpret_cast<IMAGE_DOS_HEADER*>(base)->e_lfanew); | ||
| 589 | const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_TLS); | ||
| 590 | if (!dir.Size || !dir.VirtualAddress) return "the process executable has no TLS, so index 0 is not its"; | ||
| 591 | const IMAGE_TLS_DIRECTORY64 owner = *at<IMAGE_TLS_DIRECTORY64>(base, dir.VirtualAddress); | ||
| 592 | auto* owner_index = reinterpret_cast<DWORD*>(owner.AddressOfIndex); | ||
| 593 | if (!owner_index) return "the process executable's TLS directory has no index"; | ||
| 594 | if (*owner_index != 0) return "the process executable's _tls_index is " + std::to_string(*owner_index) + ", not 0"; | ||
| 595 | if (!module_tls_slots()) return "this thread has no TLS array"; | ||
| 596 | if (!ensure_primary_tls_host()) | ||
| 597 | return "gta6rt_tls_host.dll is missing, has no module TLS index or lacks gta6rt_tls_host_set_thread_event"; | ||
| 598 | |||
| 599 | std::vector<uint8_t> image; | ||
| 600 | try { | ||
| 601 | image = read_file(tls_host_base_path()); | ||
| 602 | } catch (const std::exception& e) { | ||
| 603 | return e.what(); | ||
| 604 | } | ||
| 605 | if (std::string why = make_home_clone_image(image, owner); !why.empty()) return why; | ||
| 606 | std::filesystem::path path; | ||
| 607 | const TlsHostModule home = load_tls_host_clone(L"home", path, &image); | ||
| 608 | if (home.index == TLS_OUT_OF_INDEXES) return "the home clone of gta6rt_tls_host.dll cannot be loaded"; | ||
| 609 | auto drop = [&](std::string why) { | ||
| 610 | FreeLibrary(home.module); // safe until the move below: nothing lives at its index yet | ||
| 611 | DeleteFileW(path.c_str()); | ||
| 612 | return why; | ||
| 613 | }; | ||
| 614 | bool taken = home.index == 0 || home.index >= kMaxModuleTlsSlots; | ||
| 615 | for (const auto& host : g_tls_hosts) taken |= host.index == home.index; | ||
| 616 | if (taken) return drop("the home clone got an unusable module TLS index"); | ||
| 617 | // The OS must have taken the changed directory: the mapped clone's template is the owner's, at full size. | ||
| 618 | auto* home_base = reinterpret_cast<uint8_t*>(home.module); | ||
| 619 | auto* home_nt = at<IMAGE_NT_HEADERS64>(home_base, reinterpret_cast<IMAGE_DOS_HEADER*>(home_base)->e_lfanew); | ||
| 620 | const auto* home_tls = | ||
| 621 | at<IMAGE_TLS_DIRECTORY64>(home_base, directory(home_nt, IMAGE_DIRECTORY_ENTRY_TLS).VirtualAddress); | ||
| 622 | const uint64_t raw = owner.EndAddressOfRawData - owner.StartAddressOfRawData; | ||
| 623 | if (home_tls->EndAddressOfRawData - home_tls->StartAddressOfRawData != raw + owner.SizeOfZeroFill || | ||
| 624 | std::memcmp(reinterpret_cast<const void*>(home_tls->StartAddressOfRawData), | ||
| 625 | reinterpret_cast<const void*>(owner.StartAddressOfRawData), raw) != 0) | ||
| 626 | return drop("the home clone's mapped TLS template is not the owner's"); | ||
| 627 | |||
| 628 | // Everything that can throw comes first: past the move this records the result and nothing more. | ||
| 629 | const std::string name = module_file_name(exe); | ||
| 630 | // _tls_index sits in .data; made writable first in case a linker merged it into a read-only section. | ||
| 631 | DWORD old_protect = 0; | ||
| 632 | if (!VirtualProtect(owner_index, sizeof(DWORD), PAGE_READWRITE, &old_protect)) | ||
| 633 | return drop("the owner's _tls_index cannot be written"); | ||
| 634 | move_index0_on_this_thread(owner_index, home.index); | ||
| 635 | VirtualProtect(owner_index, sizeof(DWORD), old_protect, &old_protect); | ||
| 636 | |||
| 637 | // Kept loaded for the process lifetime: FreeLibrary would make the OS free every thread's block at its index, the | ||
| 638 | // owner's from now on. Not in g_tls_clones for that reason. Its file cannot be deleted while it is mapped | ||
| 639 | // (DeleteFileW and a POSIX-semantics delete both fail with ERROR_ACCESS_DENIED on Windows 11), so it stays until | ||
| 640 | // a later run's sweep. | ||
| 641 | g_index0.home = home; | ||
| 642 | std::snprintf(g_index0.owner, sizeof(g_index0.owner), "%s", name.c_str()); | ||
| 643 | g_index0.moved = true; | ||
| 644 | return {}; | ||
| 645 | } | ||
| 646 | |||
| 369 | // Puts the helper DLL's own block back in this thread's slot and frees the copy that replaced it. Uses only this | 647 | // 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. | 648 | // thread's record, so it also works after the module that installed the copy is gone. |
| 371 | void release_thread_slot(size_t slot) { | 649 | void release_thread_slot(size_t slot) { |
| 372 | if (slot >= kMaxMappedTlsModules) return; | 650 | if (slot >= kTlsSlotCount) return; |
| 373 | ThreadTlsSlot& entry = g_thread_tls_slots[slot]; | 651 | ThreadTlsSlot& entry = g_thread_tls_slots[slot]; |
| 374 | if (!entry.module && !entry.block) return; | 652 | if (!entry.module && !entry.block) return; |
| 375 | if (entry.ga_view) { | 653 | if (entry.ga_view) { |
| @@ -438,7 +716,7 @@ void** make_ga_view(const Module& m, void* block) { | |||
| 438 | } | 716 | } |
| 439 | 717 | ||
| 440 | void install_thread_block(Module& m) { | 718 | void install_thread_block(Module& m) { |
| 441 | if (m.tls_slot >= kMaxMappedTlsModules) return; | 719 | if (m.tls_slot >= kTlsSlotCount) return; |
| 442 | const size_t slot = m.tls_slot; | 720 | const size_t slot = m.tls_slot; |
| 443 | ThreadTlsSlot& entry = g_thread_tls_slots[slot]; | 721 | ThreadTlsSlot& entry = g_thread_tls_slots[slot]; |
| 444 | if (entry.module == &m && entry.generation == m.tls_generation) return; | 722 | if (entry.module == &m && entry.generation == m.tls_generation) return; |
| @@ -530,7 +808,7 @@ bool ga_tls_patch_enabled() { | |||
| 530 | } | 808 | } |
| 531 | 809 | ||
| 532 | void uninstall_thread_block(Module& m) { | 810 | void uninstall_thread_block(Module& m) { |
| 533 | if (m.tls_slot >= kMaxMappedTlsModules) return; | 811 | if (m.tls_slot >= kTlsSlotCount) return; |
| 534 | const size_t slot = m.tls_slot; | 812 | const size_t slot = m.tls_slot; |
| 535 | ThreadTlsSlot& entry = g_thread_tls_slots[slot]; | 813 | ThreadTlsSlot& entry = g_thread_tls_slots[slot]; |
| 536 | if (entry.module != &m || entry.generation != m.tls_generation) return; | 814 | if (entry.module != &m || entry.generation != m.tls_generation) return; |
| @@ -697,7 +975,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. | 975 | // 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) { | 976 | void install_on_existing_threads(Module& m) { |
| 699 | const uint64_t total = static_cast<uint64_t>(m.tls_raw_size) + m.tls_zero_fill; | 977 | 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; | 978 | 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 | 979 | // 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. | 980 | // 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; | 981 | if (!query_thread_fn()) return; |
| @@ -882,7 +1160,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 | 1160 | // 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 | 1161 | // 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 | 1162 | // 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. | 1163 | // only after the module's DLL_PROCESS_ATTACH (initialise()), as the Windows loader orders them. Windows allocates |
| 1164 | // every module's block before the first DllMain of a new thread, and runs an EXE's TLS callbacks after every DllMain, | ||
| 1165 | // for attach and for detach (measured on Windows 11 26300). So attach installs all copies first and then runs the | ||
| 1166 | // callbacks, the DLL slots in order and the executable's last; detach runs the DLL slots in reverse and then the | ||
| 1167 | // executable's slot, each releasing its copy after its callbacks. | ||
| 886 | void __cdecl on_host_thread_event(DWORD reason) { | 1168 | void __cdecl on_host_thread_event(DWORD reason) { |
| 887 | SharedTlsLock lock; | 1169 | SharedTlsLock lock; |
| 888 | // The try/catch is per slot: a throw from one module's install or callbacks must not take the thread events | 1170 | // The try/catch is per slot: a throw from one module's install or callbacks must not take the thread events |
| @@ -893,14 +1175,25 @@ void __cdecl on_host_thread_event(DWORD reason) { | |||
| 893 | } catch (const std::exception& e) { | 1175 | } catch (const std::exception& e) { |
| 894 | std::fprintf(stderr, "[rt] loader: thread attach: %s\n", e.what()); | 1176 | std::fprintf(stderr, "[rt] loader: thread attach: %s\n", e.what()); |
| 895 | } | 1177 | } |
| 896 | for (size_t slot = 0; slot < kMaxMappedTlsModules; ++slot) { | 1178 | std::array<Module*, kTlsSlotCount> installed{}; |
| 1179 | for (size_t slot = 0; slot < kTlsSlotCount; ++slot) { | ||
| 897 | Module* m = g_tls_slot_owners[slot].load(); | 1180 | Module* m = g_tls_slot_owners[slot].load(); |
| 898 | if (!m) continue; | 1181 | if (!m) continue; |
| 899 | try { | 1182 | try { |
| 900 | install_thread_block(*m); | 1183 | install_thread_block(*m); |
| 901 | if (m->initialised) run_callbacks(*m, DLL_THREAD_ATTACH); | 1184 | installed[slot] = m; |
| 1185 | } catch (const std::exception& e) { | ||
| 1186 | // The thread runs on without this module's TLS (and its callbacks); later slots still get theirs. | ||
| 1187 | std::fprintf(stderr, "[rt] loader: thread attach, slot %zu (%s): %s\n", slot, m->name.c_str(), | ||
| 1188 | e.what()); | ||
| 1189 | } | ||
| 1190 | } | ||
| 1191 | for (size_t slot = 0; slot < kTlsSlotCount; ++slot) { | ||
| 1192 | Module* m = installed[slot]; | ||
| 1193 | if (!m || !m->initialised) continue; | ||
| 1194 | try { | ||
| 1195 | run_callbacks(*m, DLL_THREAD_ATTACH); | ||
| 902 | } catch (const std::exception& e) { | 1196 | } 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(), | 1197 | std::fprintf(stderr, "[rt] loader: thread attach, slot %zu (%s): %s\n", slot, m->name.c_str(), |
| 905 | e.what()); | 1198 | e.what()); |
| 906 | } | 1199 | } |
| @@ -913,7 +1206,8 @@ void __cdecl on_host_thread_event(DWORD reason) { | |||
| 913 | } catch (const std::exception& e) { | 1206 | } catch (const std::exception& e) { |
| 914 | std::fprintf(stderr, "[rt] loader: thread detach: %s\n", e.what()); | 1207 | std::fprintf(stderr, "[rt] loader: thread detach: %s\n", e.what()); |
| 915 | } | 1208 | } |
| 916 | for (size_t i = kMaxMappedTlsModules; i-- > 0;) { | 1209 | for (size_t step = 0; step < kTlsSlotCount; ++step) { |
| 1210 | const size_t i = step < kMaxMappedTlsModules ? kMaxMappedTlsModules - 1 - step : kMainImageSlot; | ||
| 917 | Module* m = g_tls_slot_owners[i].load(); | 1211 | Module* m = g_tls_slot_owners[i].load(); |
| 918 | if (m && g_thread_tls_slots[i].module == m && | 1212 | if (m && g_thread_tls_slots[i].module == m && |
| 919 | g_thread_tls_slots[i].generation == m->tls_generation) { | 1213 | g_thread_tls_slots[i].generation == m->tls_generation) { |
| @@ -1017,6 +1311,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. | 1311 | // Declared in pe_loader.h; the body needs the internal clone registry above. |
| 1018 | void cleanup_tls_clones() { cleanup_tls_clones_internal(); } | 1312 | void cleanup_tls_clones() { cleanup_tls_clones_internal(); } |
| 1019 | 1313 | ||
| 1314 | bool reserve_tls_index0(std::string* why) { | ||
| 1315 | std::lock_guard alloc_lock(g_tls_alloc_mutex); | ||
| 1316 | static bool attempted = false; // once: a later attempt could meet threads that already run this EXE's code | ||
| 1317 | if (!attempted) { | ||
| 1318 | attempted = true; | ||
| 1319 | // A throw (std::filesystem::temp_directory_path when GetTempPathW fails, an allocation) is a failed | ||
| 1320 | // reservation like any other: gta6rt calls this before main, where an exception would end it with no message. | ||
| 1321 | try { | ||
| 1322 | const std::string reason = reserve_index0(); | ||
| 1323 | std::snprintf(g_index0.why, sizeof(g_index0.why), "%s", reason.c_str()); | ||
| 1324 | } catch (const std::exception& e) { | ||
| 1325 | std::snprintf(g_index0.why, sizeof(g_index0.why), "%s", e.what()); | ||
| 1326 | } catch (...) { | ||
| 1327 | std::snprintf(g_index0.why, sizeof(g_index0.why), "an unknown error while reserving it"); | ||
| 1328 | } | ||
| 1329 | } | ||
| 1330 | if (why) *why = g_index0.moved ? std::string() : std::string(g_index0.why); | ||
| 1331 | return g_index0.moved; | ||
| 1332 | } | ||
| 1333 | |||
| 1020 | namespace { | 1334 | namespace { |
| 1021 | bool lookup_in_loader(void* ctx, uint64_t address, std::string& module, uint32_t& rva) { | 1335 | 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); | 1336 | return static_cast<Loader*>(ctx)->find_address(address, module, rva); |
| @@ -1046,6 +1360,15 @@ void* bundled_load_w(void* ctx, const std::wstring& basename, uint32_t flags, bo | |||
| 1046 | return static_cast<Loader*>(ctx)->load_runtime_module_w(basename, flags, handled); | 1360 | return static_cast<Loader*>(ctx)->load_runtime_module_w(basename, flags, handled); |
| 1047 | } | 1361 | } |
| 1048 | 1362 | ||
| 1363 | void* bundled_compat_module(void* ctx, const std::wstring& basename, const std::wstring& name, bool load, | ||
| 1364 | uint32_t flags, bool& handled) { | ||
| 1365 | return static_cast<Loader*>(ctx)->runtime_compat_module(basename, name, load, flags, handled); | ||
| 1366 | } | ||
| 1367 | |||
| 1368 | bool bundled_owns_compat_handle(void* ctx, void* module) { | ||
| 1369 | return static_cast<Loader*>(ctx)->owns_compat_handle(module); | ||
| 1370 | } | ||
| 1371 | |||
| 1049 | const shims::BundledModuleOps kBundledOps{ | 1372 | const shims::BundledModuleOps kBundledOps{ |
| 1050 | &bundled_find_loaded, | 1373 | &bundled_find_loaded, |
| 1051 | &bundled_load, | 1374 | &bundled_load, |
| @@ -1053,6 +1376,8 @@ const shims::BundledModuleOps kBundledOps{ | |||
| 1053 | &bundled_owns_handle, | 1376 | &bundled_owns_handle, |
| 1054 | &bundled_find_loaded_w, | 1377 | &bundled_find_loaded_w, |
| 1055 | &bundled_load_w, | 1378 | &bundled_load_w, |
| 1379 | &bundled_compat_module, | ||
| 1380 | &bundled_owns_compat_handle, | ||
| 1056 | }; | 1381 | }; |
| 1057 | 1382 | ||
| 1058 | // Marks what a run-time load maps as a dynamic load for as long as it is in scope (the caller holds the mutex). | 1383 | // Marks what a run-time load maps as a dynamic load for as long as it is in scope (the caller holds the mutex). |
| @@ -1068,7 +1393,18 @@ struct RuntimeLoadScope { | |||
| 1068 | Loader::Loader(std::filesystem::path game_dir) : game_dir_(std::move(game_dir)) { | 1393 | Loader::Loader(std::filesystem::path game_dir) : game_dir_(std::move(game_dir)) { |
| 1069 | std::vector<wchar_t> compat(32768); | 1394 | std::vector<wchar_t> compat(32768); |
| 1070 | const DWORD n = GetEnvironmentVariableW(L"LEONIDA_COMPAT_DIR", compat.data(), static_cast<DWORD>(compat.size())); | 1395 | const DWORD n = GetEnvironmentVariableW(L"LEONIDA_COMPAT_DIR", compat.data(), static_cast<DWORD>(compat.size())); |
| 1071 | if (n > 0 && n < compat.size()) compat_dir_ = std::filesystem::path(compat.data()); | 1396 | if (n > 0 && n < compat.size()) { |
| 1397 | // Absolute, with backslashes and no trailing separator: LoadLibraryExW with LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | ||
| 1398 | // needs a full path, and owns_compat_handle() compares it with a module's own folder. | ||
| 1399 | std::error_code ec; | ||
| 1400 | compat_dir_ = std::filesystem::absolute(std::filesystem::path(compat.data()), ec).lexically_normal(); | ||
| 1401 | compat_dir_.make_preferred(); | ||
| 1402 | if (!compat_dir_.has_filename()) compat_dir_ = compat_dir_.parent_path(); | ||
| 1403 | for (std::filesystem::directory_iterator it(compat_dir_, ec), end; !ec && it != end; it.increment(ec)) { | ||
| 1404 | std::error_code file_ec; | ||
| 1405 | if (it->is_regular_file(file_ec)) compat_files_.push_back(it->path().filename()); | ||
| 1406 | } | ||
| 1407 | } | ||
| 1072 | shims::add_module_lookup(this, &lookup_in_loader); | 1408 | shims::add_module_lookup(this, &lookup_in_loader); |
| 1073 | shims::add_bundled_loader(this, &kBundledOps); | 1409 | shims::add_bundled_loader(this, &kBundledOps); |
| 1074 | } | 1410 | } |
| @@ -1094,11 +1430,12 @@ Loader::~Loader() { | |||
| 1094 | entry(m.base, DLL_PROCESS_DETACH, nullptr); // explicit unload; the return value is ignored | 1430 | entry(m.base, DLL_PROCESS_DETACH, nullptr); // explicit unload; the return value is ignored |
| 1095 | } | 1431 | } |
| 1096 | } | 1432 | } |
| 1433 | shims::remove_xmem_allocation_hooks(this); | ||
| 1097 | shims::remove_bundled_loader(this); | 1434 | shims::remove_bundled_loader(this); |
| 1098 | shims::remove_module_lookup(this); | 1435 | shims::remove_module_lookup(this); |
| 1099 | for (auto* m : order_) { | 1436 | for (auto* m : order_) { |
| 1100 | // TLS state must go away before the image and its TLS block are unmapped. | 1437 | // TLS state must go away before the image and its TLS block are unmapped. |
| 1101 | if (m->tls_index != kNoTlsIndex && m->tls_slot < kMaxMappedTlsModules) { | 1438 | 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 | 1439 | // 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). | 1440 | // thread that still holds a copy frees it when it ends (on_host_thread_event). |
| 1104 | { | 1441 | { |
| @@ -1208,6 +1545,8 @@ void* Loader::load_runtime_module_w(const std::wstring& basename, uint32_t flags | |||
| 1208 | if (prefer_host_copy(narrow)) return nullptr; | 1545 | if (prefer_host_copy(narrow)) return nullptr; |
| 1209 | 1546 | ||
| 1210 | std::lock_guard lock(mutex_); | 1547 | std::lock_guard lock(mutex_); |
| 1548 | // As load_runtime_module: a run-time load, so DllMain gets a null lpvReserved. | ||
| 1549 | const RuntimeLoadScope dynamic(runtime_loads_); | ||
| 1211 | Module* existing = find_wide_module(basename); | 1550 | Module* existing = find_wide_module(basename); |
| 1212 | const std::filesystem::path candidate = game_dir_ / basename; | 1551 | const std::filesystem::path candidate = game_dir_ / basename; |
| 1213 | std::error_code ec; | 1552 | std::error_code ec; |
| @@ -1425,10 +1764,7 @@ Module& Loader::map_image(const std::filesystem::path& path, const std::string& | |||
| 1425 | if (!m->base) | 1764 | if (!m->base) |
| 1426 | m->base = static_cast<uint8_t*>(VirtualAlloc(reinterpret_cast<void*>(oh.ImageBase), oh.SizeOfImage, | 1765 | m->base = static_cast<uint8_t*>(VirtualAlloc(reinterpret_cast<void*>(oh.ImageBase), oh.SizeOfImage, |
| 1427 | MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); | 1766 | MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); |
| 1428 | if (!m->base) { | 1767 | if (!m->base) { // whether the image may move is decided at the relocation step below |
| 1429 | const auto relocs = directory(nt, IMAGE_DIRECTORY_ENTRY_BASERELOC); | ||
| 1430 | if (!relocs.Size) | ||
| 1431 | throw std::runtime_error(m->name + ": preferred base is taken and the image has no relocations"); | ||
| 1432 | m->base = static_cast<uint8_t*>(VirtualAlloc(nullptr, oh.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); | 1768 | m->base = static_cast<uint8_t*>(VirtualAlloc(nullptr, oh.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); |
| 1433 | if (!m->base) throw std::runtime_error(m->name + ": VirtualAlloc failed"); | 1769 | if (!m->base) throw std::runtime_error(m->name + ": VirtualAlloc failed"); |
| 1434 | } | 1770 | } |
| @@ -1453,10 +1789,19 @@ Module& Loader::map_image(const std::filesystem::path& path, const std::string& | |||
| 1453 | } | 1789 | } |
| 1454 | 1790 | ||
| 1455 | int64_t delta = reinterpret_cast<int64_t>(m->base) - static_cast<int64_t>(oh.ImageBase); | 1791 | int64_t delta = reinterpret_cast<int64_t>(m->base) - static_cast<int64_t>(oh.ImageBase); |
| 1456 | if (delta) { | 1792 | // A moved image with a relocation table is fixed up, whatever IMAGE_FILE_RELOCS_STRIPPED says. Without a table, |
| 1457 | m->relocated = true; | 1793 | // the flag refuses the move; with the flag clear the image is moved and nothing is fixed up, so it is trusted to |
| 1458 | const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_BASERELOC); | 1794 | // hold no absolute addresses. The Windows 11 loader does all three (runtime/README.md); that move is logged so |
| 1459 | if (!dir.Size) throw std::runtime_error(m->name + ": the image has no relocations and isn't at its base"); | 1795 | // it shows in traces. base_reservation::needed still keeps the main image's range free when it has no |
| 1796 | // relocation directory, so a main image is moved this way only where the range could not be had. | ||
| 1797 | const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_BASERELOC); | ||
| 1798 | if (delta) m->relocated = true; | ||
| 1799 | if (delta && !dir.Size && (nt->FileHeader.Characteristics & IMAGE_FILE_RELOCS_STRIPPED)) | ||
| 1800 | throw std::runtime_error(m->name + ": preferred base is taken and the image's relocations are stripped"); | ||
| 1801 | if (delta && !dir.Size) | ||
| 1802 | std::fprintf(stderr, "[rt] loader: %s: preferred base %#llx is taken, moved to %p with no relocations\n", | ||
| 1803 | m->name.c_str(), static_cast<unsigned long long>(oh.ImageBase), static_cast<void*>(m->base)); | ||
| 1804 | if (delta && dir.Size) { | ||
| 1460 | require_range(m->name, dir.VirtualAddress, dir.Size, m->size, "the relocation table"); | 1805 | require_range(m->name, dir.VirtualAddress, dir.Size, m->size, "the relocation table"); |
| 1461 | auto* block = at<IMAGE_BASE_RELOCATION>(m->base, dir.VirtualAddress); | 1806 | auto* block = at<IMAGE_BASE_RELOCATION>(m->base, dir.VirtualAddress); |
| 1462 | auto* end = reinterpret_cast<uint8_t*>(block) + dir.Size; | 1807 | auto* end = reinterpret_cast<uint8_t*>(block) + dir.Size; |
| @@ -1498,6 +1843,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. | 1843 | // installed here, before bind_imports can return control to the caller and before any image code can run. |
| 1499 | initialize_tls(*m); | 1844 | initialize_tls(*m); |
| 1500 | parse_exports(*m); | 1845 | parse_exports(*m); |
| 1846 | if (auto it = m->exports.find("__XMemAllocationHooks__"); it != m->exports.end()) { | ||
| 1847 | const auto offset = static_cast<uint64_t>(static_cast<uint8_t*>(it->second) - m->base); | ||
| 1848 | if (offset <= m->size && m->size - offset >= sizeof(shims::XMemAllocationHooks)) { | ||
| 1849 | shims::add_xmem_allocation_hooks(this, static_cast<const shims::XMemAllocationHooks*>(it->second)); | ||
| 1850 | } | ||
| 1851 | } | ||
| 1501 | return *m; | 1852 | return *m; |
| 1502 | } | 1853 | } |
| 1503 | 1854 | ||
| @@ -1507,7 +1858,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 | 1858 | // 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 | 1859 | // 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 | 1860 | // 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. | 1861 | // silently sharing (and corrupting) a slot. An executable takes index 0 instead (kMainImageSlot), as on Windows. |
| 1511 | void Loader::initialize_tls(Module& m) { | 1862 | void Loader::initialize_tls(Module& m) { |
| 1512 | auto* tls = tls_directory(m); | 1863 | auto* tls = tls_directory(m); |
| 1513 | if (!tls) return; | 1864 | if (!tls) return; |
| @@ -1536,26 +1887,70 @@ void Loader::initialize_tls(Module& m) { | |||
| 1536 | 1887 | ||
| 1537 | if (!module_tls_slots()) throw std::runtime_error(m.name + ": this thread has no TLS array"); | 1888 | if (!module_tls_slots()) throw std::runtime_error(m.name + ": this thread has no TLS array"); |
| 1538 | 1889 | ||
| 1539 | size_t slot = kMaxMappedTlsModules; | 1890 | auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew); |
| 1891 | const bool executable = (nt->FileHeader.Characteristics & IMAGE_FILE_DLL) == 0; | ||
| 1892 | |||
| 1893 | size_t slot = kTlsSlotCount; | ||
| 1540 | DWORD index = TLS_OUT_OF_INDEXES; | 1894 | DWORD index = TLS_OUT_OF_INDEXES; |
| 1541 | { | 1895 | { |
| 1542 | std::lock_guard alloc_lock(g_tls_alloc_mutex); | 1896 | std::lock_guard alloc_lock(g_tls_alloc_mutex); |
| 1543 | for (size_t i = 0; i < kMaxMappedTlsModules; ++i) { | 1897 | if (executable) { |
| 1544 | if (g_tls_slot_owners[i].load() == nullptr) { | 1898 | if (g_index0.moved && g_tls_slot_owners[kMainImageSlot].load() == nullptr) { |
| 1545 | slot = i; | 1899 | slot = kMainImageSlot; |
| 1546 | break; | 1900 | index = 0; |
| 1901 | if (!g_index0.traced && startup_trace::enabled()) { | ||
| 1902 | g_index0.traced = true; | ||
| 1903 | startup_trace::event("tls_index0", "\"owner\":" + startup_trace::quote(g_index0.owner) + | ||
| 1904 | ",\"moved_to\":" + std::to_string(g_index0.home.index)); | ||
| 1905 | } | ||
| 1906 | } else { | ||
| 1907 | // Mapped on as a DLL is: its code that reads _tls_index works, but its /GA code would read and write | ||
| 1908 | // the block in slot 0, which is the runtime's own TLS or the other executable's. gta6rt refuses to | ||
| 1909 | // run such an image (main.cpp); a Loader user must not run its code either. | ||
| 1910 | std::fprintf(stderr, | ||
| 1911 | "[rt] loader: %s does not get module TLS index 0 (%s); its code built with /GA would use " | ||
| 1912 | "another module's TLS\n", | ||
| 1913 | m.name.c_str(), g_index0.moved ? "another mapped executable holds it" : g_index0.why); | ||
| 1914 | } | ||
| 1915 | } | ||
| 1916 | if (slot == kTlsSlotCount) { | ||
| 1917 | for (size_t i = 0; i < kMaxMappedTlsModules; ++i) { | ||
| 1918 | if (g_tls_slot_owners[i].load() == nullptr) { | ||
| 1919 | slot = i; | ||
| 1920 | break; | ||
| 1921 | } | ||
| 1547 | } | 1922 | } |
| 1923 | if (slot >= kMaxMappedTlsModules) | ||
| 1924 | throw std::runtime_error(m.name + ": all " + std::to_string(kMaxMappedTlsModules) + | ||
| 1925 | " manually mapped static TLS slots are in use"); | ||
| 1926 | |||
| 1927 | // Load/clone gta6rt_tls_host.dll OUTSIDE ExclusiveTlsLock so LoadLibraryExW cannot deadlock with | ||
| 1928 | // on_host_thread_event (which runs under the Windows loader lock and takes SharedTlsLock). | ||
| 1929 | index = ensure_tls_host(slot).index; | ||
| 1930 | if (index == TLS_OUT_OF_INDEXES) | ||
| 1931 | throw std::runtime_error(m.name + ": gta6rt_tls_host.dll is missing or has no module TLS index"); | ||
| 1932 | if (index >= kMaxModuleTlsSlots) | ||
| 1933 | throw std::runtime_error(m.name + ": reserved TLS index is out of range"); | ||
| 1548 | } | 1934 | } |
| 1549 | if (slot >= kMaxMappedTlsModules) | ||
| 1550 | throw std::runtime_error(m.name + ": all " + std::to_string(kMaxMappedTlsModules) + | ||
| 1551 | " manually mapped static TLS slots are in use"); | ||
| 1552 | 1935 | ||
| 1553 | // Load/clone gta6rt_tls_host.dll OUTSIDE ExclusiveTlsLock so LoadLibraryExW cannot deadlock with | 1936 | // An EXE's code may read its TLS at index 0 directly (/GA); index 0 is gta6rt.exe's here (pe_loader.h, |
| 1554 | // on_host_thread_event (which runs under the Windows loader lock and takes SharedTlsLock). | 1937 | // tls_ga_slot). Patched before any of the image's code runs, TLS callbacks included, and before the owner is |
| 1555 | index = ensure_tls_host(slot).index; | 1938 | // published below: from then on a thread event (install_thread_block) reads m.tls_ga_slot |
| 1556 | if (index == TLS_OUT_OF_INDEXES) | 1939 | // (RT-LOADER-RUNTIME-SCOPE-AND-TLS-SLOT). |
| 1557 | throw std::runtime_error(m.name + ": gta6rt_tls_host.dll is missing or has no module TLS index"); | 1940 | if (executable && total && index != 0 && ga_tls_patch_enabled()) { |
| 1558 | if (index >= kMaxModuleTlsSlots) throw std::runtime_error(m.name + ": reserved TLS index is out of range"); | 1941 | static const DWORD ga_slot = TlsAlloc(); |
| 1942 | if (ga_slot == TLS_OUT_OF_INDEXES || ga_slot >= 64) { | ||
| 1943 | std::fprintf(stderr, "[rt] loader: %s: no TlsAlloc slot below 64 for its index-0 TLS reads\n", | ||
| 1944 | m.name.c_str()); | ||
| 1945 | } else { | ||
| 1946 | m.tls_ga_sites = patch_ga_tls_reads(m, ga_slot); | ||
| 1947 | if (m.tls_ga_sites) m.tls_ga_slot = ga_slot; | ||
| 1948 | std::fprintf(stderr, | ||
| 1949 | "[rt] loader: %s: %zu index-0 TLS reads (gs:[58h]) now read its own TLS (TlsSlots[%lu]); " | ||
| 1950 | "its module TLS index is %u\n", | ||
| 1951 | m.name.c_str(), m.tls_ga_sites, static_cast<unsigned long>(ga_slot), index); | ||
| 1952 | } | ||
| 1953 | } | ||
| 1559 | 1954 | ||
| 1560 | // The fields are complete before a thread event can see the owner. | 1955 | // The fields are complete before a thread event can see the owner. |
| 1561 | ExclusiveTlsLock lock; | 1956 | ExclusiveTlsLock lock; |
| @@ -1575,26 +1970,6 @@ void Loader::initialize_tls(Module& m) { | |||
| 1575 | // VirtualProtect dance. | 1970 | // VirtualProtect dance. |
| 1576 | if (index_rva) *reinterpret_cast<uint32_t*>(m.base + index_rva) = index; | 1971 | if (index_rva) *reinterpret_cast<uint32_t*>(m.base + index_rva) = index; |
| 1577 | } | 1972 | } |
| 1578 | { | ||
| 1579 | // An EXE's code may read its TLS at index 0 directly (/GA); index 0 is gta6rt.exe's here (pe_loader.h, | ||
| 1580 | // tls_ga_slot). Patched before any of the image's code runs, TLS callbacks included. | ||
| 1581 | const auto* dos = reinterpret_cast<const IMAGE_DOS_HEADER*>(m.base); | ||
| 1582 | const auto* nt = reinterpret_cast<const IMAGE_NT_HEADERS64*>(m.base + dos->e_lfanew); | ||
| 1583 | if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && total && index != 0 && ga_tls_patch_enabled()) { | ||
| 1584 | static const DWORD ga_slot = TlsAlloc(); | ||
| 1585 | if (ga_slot == TLS_OUT_OF_INDEXES || ga_slot >= 64) { | ||
| 1586 | std::fprintf(stderr, "[rt] loader: %s: no TlsAlloc slot below 64 for its index-0 TLS reads\n", | ||
| 1587 | m.name.c_str()); | ||
| 1588 | } else { | ||
| 1589 | m.tls_ga_sites = patch_ga_tls_reads(m, ga_slot); | ||
| 1590 | if (m.tls_ga_sites) m.tls_ga_slot = ga_slot; | ||
| 1591 | std::fprintf(stderr, | ||
| 1592 | "[rt] loader: %s: %zu index-0 TLS reads (gs:[58h]) now read its own TLS (TlsSlots[%lu]); " | ||
| 1593 | "its module TLS index is %u\n", | ||
| 1594 | m.name.c_str(), m.tls_ga_sites, static_cast<unsigned long>(ga_slot), index); | ||
| 1595 | } | ||
| 1596 | } | ||
| 1597 | } | ||
| 1598 | try { | 1973 | try { |
| 1599 | install_thread_block(m); | 1974 | install_thread_block(m); |
| 1600 | } catch (...) { | 1975 | } catch (...) { |
| @@ -1713,37 +2088,128 @@ void* Loader::resolve_forwarder(const std::string& spec, Binding& binding, int d | |||
| 1713 | return reinterpret_cast<void*>(p); | 2088 | return reinterpret_cast<void*>(p); |
| 1714 | } | 2089 | } |
| 1715 | 2090 | ||
| 2091 | const std::filesystem::path* Loader::compat_file(const std::wstring& basename) const { | ||
| 2092 | if (basename.empty()) return nullptr; | ||
| 2093 | for (const auto& file : compat_files_) | ||
| 2094 | if (same_module_name(file.c_str(), basename.c_str())) return &file; | ||
| 2095 | return nullptr; | ||
| 2096 | } | ||
| 2097 | |||
| 2098 | void* Loader::compat_handle(const std::filesystem::path& file, bool load, uint32_t& error) { | ||
| 2099 | error = ERROR_SUCCESS; | ||
| 2100 | const std::string key = lower(path_utf8(file)); | ||
| 2101 | if (auto it = compat_modules_.find(key); it != compat_modules_.end()) return it->second; | ||
| 2102 | const std::filesystem::path candidate = compat_dir_ / file; | ||
| 2103 | // Already live without a lookup through here: Windows loaded it from the folder as another compat DLL's | ||
| 2104 | // dependency (LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR), or something loaded it by its path. That is the module a | ||
| 2105 | // static import or a run-time load must share. The reference taken here is kept, as for the DLLs loaded below. | ||
| 2106 | if (HMODULE live = nullptr; GetModuleHandleExW(0, candidate.c_str(), &live) && live) { | ||
| 2107 | compat_modules_.emplace(key, live); | ||
| 2108 | std::fprintf(stderr, "[rt] compat: %s -> %s (already loaded)\n", path_utf8(file).c_str(), | ||
| 2109 | path_utf8(candidate).c_str()); | ||
| 2110 | return live; | ||
| 2111 | } | ||
| 2112 | if (!load) return nullptr; | ||
| 2113 | // The full path, with the compat folder on the DLL's own search path for its dependencies; never the game | ||
| 2114 | // folder. Windows maps it, so its CRT, TLS and SEH work as for any host DLL. | ||
| 2115 | // A file Windows cannot map (truncated, wrong machine, not a PE image) otherwise raises a modal "Bad Image" | ||
| 2116 | // box and LoadLibraryExW does not return until someone clicks it: a headless run would hang on a failure | ||
| 2117 | // that the caller reports anyway. The mode is this thread's, and goes back as it was. | ||
| 2118 | DWORD previous_mode = 0; | ||
| 2119 | const bool mode_set = SetThreadErrorMode(GetThreadErrorMode() | SEM_FAILCRITICALERRORS, &previous_mode) != 0; | ||
| 2120 | HMODULE h = LoadLibraryExW(candidate.c_str(), nullptr, LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32); | ||
| 2121 | error = h ? ERROR_SUCCESS : GetLastError(); | ||
| 2122 | if (mode_set) SetThreadErrorMode(previous_mode, nullptr); | ||
| 2123 | if (!h) return nullptr; | ||
| 2124 | compat_modules_.emplace(key, h); | ||
| 2125 | std::fprintf(stderr, "[rt] compat: %s -> %s\n", path_utf8(file).c_str(), path_utf8(candidate).c_str()); | ||
| 2126 | return h; | ||
| 2127 | } | ||
| 2128 | |||
| 1716 | bool Loader::resolve_compat(const std::string& key, const std::string& dll, const std::string& name, uint16_t ordinal, | 2129 | bool Loader::resolve_compat(const std::string& key, const std::string& dll, const std::string& name, uint16_t ordinal, |
| 1717 | bool by_ordinal, void*& out) { | 2130 | bool by_ordinal, void*& out) { |
| 1718 | out = nullptr; | 2131 | out = nullptr; |
| 1719 | if (compat_dir_.empty() || key.empty() || key.find_first_of("/\\:") != std::string::npos) return false; | 2132 | if (compat_dir_.empty() || key.empty() || key.find_first_of("/\\:") != std::string::npos) return false; |
| 1720 | HMODULE h = nullptr; | 2133 | const std::filesystem::path* file = compat_file(acp_to_wide(dll)); |
| 1721 | if (auto it = compat_modules_.find(key); it != compat_modules_.end()) { | 2134 | if (!file) return false; |
| 1722 | h = static_cast<HMODULE>(it->second); | 2135 | uint32_t error = ERROR_SUCCESS; |
| 1723 | } else { | 2136 | HMODULE h = static_cast<HMODULE>(compat_handle(*file, true, error)); |
| 1724 | const std::filesystem::path candidate = compat_dir_ / std::filesystem::path(dll); | 2137 | if (!h) |
| 1725 | std::error_code ec; | 2138 | throw std::runtime_error("LEONIDA_COMPAT_DIR: " + path_utf8(compat_dir_ / *file) + |
| 1726 | if (!std::filesystem::is_regular_file(candidate, ec)) return false; | 2139 | " exists but Windows could not load it (error " + std::to_string(error) + ")"); |
| 1727 | // The full path, with the compat folder on the DLL's own search path for its dependencies; never the game | ||
| 1728 | // folder. Windows maps it, so its CRT, TLS and SEH work as for any host DLL. | ||
| 1729 | // A file Windows cannot map (truncated, wrong machine, not a PE image) otherwise raises a modal "Bad Image" | ||
| 1730 | // box and LoadLibraryExW does not return until someone clicks it: a headless run would hang on a failure | ||
| 1731 | // that is reported right below anyway. The mode is this thread's, and goes back as it was. | ||
| 1732 | DWORD previous_mode = 0; | ||
| 1733 | const bool mode_set = SetThreadErrorMode(GetThreadErrorMode() | SEM_FAILCRITICALERRORS, &previous_mode) != 0; | ||
| 1734 | h = LoadLibraryExW(candidate.c_str(), nullptr, LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32); | ||
| 1735 | const DWORD load_error = h ? ERROR_SUCCESS : GetLastError(); | ||
| 1736 | if (mode_set) SetThreadErrorMode(previous_mode, nullptr); | ||
| 1737 | if (!h) | ||
| 1738 | throw std::runtime_error("LEONIDA_COMPAT_DIR: " + path_utf8(candidate) + " exists but Windows could not " + | ||
| 1739 | "load it (error " + std::to_string(load_error) + ")"); | ||
| 1740 | compat_modules_.emplace(key, h); | ||
| 1741 | std::fprintf(stderr, "[rt] compat: %s -> %s\n", dll.c_str(), path_utf8(candidate).c_str()); | ||
| 1742 | } | ||
| 1743 | out = reinterpret_cast<void*>(GetProcAddress(h, by_ordinal ? MAKEINTRESOURCEA(ordinal) : name.c_str())); | 2140 | out = reinterpret_cast<void*>(GetProcAddress(h, by_ordinal ? MAKEINTRESOURCEA(ordinal) : name.c_str())); |
| 1744 | return true; | 2141 | return true; |
| 1745 | } | 2142 | } |
| 1746 | 2143 | ||
| 2144 | void* Loader::runtime_compat_module(const std::wstring& basename, const std::wstring& name, bool load, | ||
| 2145 | uint32_t flags, bool& handled) { | ||
| 2146 | handled = false; | ||
| 2147 | if (compat_dir_.empty()) return nullptr; | ||
| 2148 | std::lock_guard lock(mutex_); | ||
| 2149 | const std::filesystem::path* file = compat_file(basename); | ||
| 2150 | if (!file) return nullptr; | ||
| 2151 | const std::filesystem::path compat_path = compat_dir_ / *file; | ||
| 2152 | // A name with a directory names one file, which Windows would load even when another of the same name is in use: | ||
| 2153 | // the compat DLL answers it only when it is that file (".dll" added as LoadLibrary adds it). Any other path goes | ||
| 2154 | // on as without the folder. | ||
| 2155 | if (name.find_first_of(L"\\/:") != std::wstring::npos) { | ||
| 2156 | std::filesystem::path given(name); | ||
| 2157 | given.replace_filename(basename); | ||
| 2158 | std::error_code ec; | ||
| 2159 | if (!std::filesystem::equivalent(given, compat_path, ec)) return nullptr; | ||
| 2160 | } | ||
| 2161 | handled = true; | ||
| 2162 | // DONT_RESOLVE_DLL_REFERENCES maps a DLL without its dependencies, TLS or DllMain. The compat DLL is shared with | ||
| 2163 | // static imports, initialised, so refuse it before loading or returning a handle, as for bundled DLLs | ||
| 2164 | // (load_runtime_candidate). | ||
| 2165 | if (load && (flags & DONT_RESOLVE_DLL_REFERENCES) != 0) { | ||
| 2166 | std::fprintf(stderr, "[rt] compat: LoadLibraryEx(%s, DONT_RESOLVE_DLL_REFERENCES) is not supported\n", | ||
| 2167 | path_utf8(compat_path).c_str()); | ||
| 2168 | SetLastError(ERROR_NOT_SUPPORTED); | ||
| 2169 | return nullptr; | ||
| 2170 | } | ||
| 2171 | uint32_t error = ERROR_SUCCESS; | ||
| 2172 | void* h = compat_handle(*file, load, error); | ||
| 2173 | if (!h && load) { | ||
| 2174 | // As a LoadLibrary of a file Windows refuses: null and its error, never the shim (the player put the DLL | ||
| 2175 | // there to own the module). | ||
| 2176 | std::fprintf(stderr, "[rt] compat: %s exists but Windows could not load it (error %u, run-time load)\n", | ||
| 2177 | path_utf8(compat_path).c_str(), error); | ||
| 2178 | SetLastError(error); | ||
| 2179 | } else if (!h) { | ||
| 2180 | SetLastError(ERROR_MOD_NOT_FOUND); // GetModuleHandle of a module nothing has loaded yet | ||
| 2181 | } | ||
| 2182 | return h; | ||
| 2183 | } | ||
| 2184 | |||
| 2185 | bool Loader::owns_compat_handle(void* module) { | ||
| 2186 | if (!module || compat_dir_.empty()) return false; | ||
| 2187 | { | ||
| 2188 | std::lock_guard lock(mutex_); | ||
| 2189 | for (const auto& [key, h] : compat_modules_) | ||
| 2190 | if (h == module) return true; | ||
| 2191 | } | ||
| 2192 | // A DLL from the folder that no lookup has seen yet (Windows loaded it as another compat DLL's dependency): its | ||
| 2193 | // exports are its own too. Recorded, with a kept reference, through compat_handle(). GetModuleFileNameW can take | ||
| 2194 | // the Windows loader lock, so the path is read without mutex_ held; compat_dir_ and compat_files_ do not change | ||
| 2195 | // after construction. | ||
| 2196 | std::vector<wchar_t> path(MAX_PATH); | ||
| 2197 | DWORD length = 0; | ||
| 2198 | for (;;) { | ||
| 2199 | length = GetModuleFileNameW(static_cast<HMODULE>(module), path.data(), static_cast<DWORD>(path.size())); | ||
| 2200 | if (!length || length < path.size() || path.size() >= 32768) break; | ||
| 2201 | path.resize(path.size() * 2); | ||
| 2202 | } | ||
| 2203 | if (!length || length >= path.size()) return false; | ||
| 2204 | const std::filesystem::path file(std::wstring(path.data(), length)); | ||
| 2205 | if (!same_module_name(file.parent_path().c_str(), compat_dir_.c_str())) return false; | ||
| 2206 | const std::filesystem::path* entry = compat_file(file.filename().native()); | ||
| 2207 | if (!entry) return false; | ||
| 2208 | std::lock_guard lock(mutex_); | ||
| 2209 | uint32_t error = ERROR_SUCCESS; | ||
| 2210 | return compat_handle(*entry, false, error) == module; | ||
| 2211 | } | ||
| 2212 | |||
| 1747 | void* Loader::resolve(Module& m, const std::string& dll, const std::string& name, uint16_t ordinal, bool by_ordinal) { | 2213 | void* Loader::resolve(Module& m, const std::string& dll, const std::string& name, uint16_t ordinal, bool by_ordinal) { |
| 1748 | std::string key = lower(dll); | 2214 | std::string key = lower(dll); |
| 1749 | std::string sym = by_ordinal ? "#" + std::to_string(ordinal) : name; | 2215 | std::string sym = by_ordinal ? "#" + std::to_string(ordinal) : name; |
| @@ -1796,7 +2262,10 @@ void Loader::bind_imports(Module& m) { | |||
| 1796 | const uint64_t headers_end = nt->OptionalHeader.SizeOfHeaders; | 2262 | const uint64_t headers_end = nt->OptionalHeader.SizeOfHeaders; |
| 1797 | 2263 | ||
| 1798 | // Thunk tables have no length field: they end at a zero entry, so each step is checked against the image. | 2264 | // Thunk tables have no length field: they end at a zero entry, so each step is checked against the image. |
| 1799 | auto bind_thunks = [&](const std::string& dll, uint64_t lookup_rva, uint64_t iat_rva) { | 2265 | // `delayed`: a delay import that binds to an unimplemented thunk is traced. Windows' delay-load helper would raise |
| 2266 | // 0xC06D007E (module) or 0xC06D007F (procedure) at its first call, which a title can catch for a fallback; the | ||
| 2267 | // thunk returns 0 instead, so the trace names each such import before any image code runs. | ||
| 2268 | auto bind_thunks = [&](const std::string& dll, uint64_t lookup_rva, uint64_t iat_rva, bool delayed) { | ||
| 1800 | for (;; lookup_rva += sizeof(IMAGE_THUNK_DATA64), iat_rva += sizeof(IMAGE_THUNK_DATA64)) { | 2269 | for (;; lookup_rva += sizeof(IMAGE_THUNK_DATA64), iat_rva += sizeof(IMAGE_THUNK_DATA64)) { |
| 1801 | require_range(m.name, lookup_rva, sizeof(IMAGE_THUNK_DATA64), m.size, "an import lookup table"); | 2270 | require_range(m.name, lookup_rva, sizeof(IMAGE_THUNK_DATA64), m.size, "an import lookup table"); |
| 1802 | require_range(m.name, iat_rva, sizeof(IMAGE_THUNK_DATA64), m.size, "an import address table"); | 2271 | require_range(m.name, iat_rva, sizeof(IMAGE_THUNK_DATA64), m.size, "an import address table"); |
| @@ -1814,6 +2283,10 @@ void Loader::bind_imports(Module& m) { | |||
| 1814 | throw std::runtime_error(m.name + ": an import address table lands in the headers"); | 2283 | throw std::runtime_error(m.name + ": an import address table lands in the headers"); |
| 1815 | at<IMAGE_THUNK_DATA64>(m.base, static_cast<uint32_t>(iat_rva))->u1.Function = | 2284 | at<IMAGE_THUNK_DATA64>(m.base, static_cast<uint32_t>(iat_rva))->u1.Function = |
| 1816 | reinterpret_cast<uint64_t>(resolve(m, dll, name, ord, by_ord)); | 2285 | reinterpret_cast<uint64_t>(resolve(m, dll, name, ord, by_ord)); |
| 2286 | if (delayed && startup_trace::enabled() && m.imports.back().binding == Binding::Unimplemented) | ||
| 2287 | startup_trace::event("delay_import_unimplemented", | ||
| 2288 | "\"module\":" + startup_trace::quote(m.name) + ",\"import\":" + | ||
| 2289 | startup_trace::quote(dll + "!" + m.imports.back().name)); | ||
| 1817 | } | 2290 | } |
| 1818 | }; | 2291 | }; |
| 1819 | 2292 | ||
| @@ -1826,7 +2299,7 @@ void Loader::bind_imports(Module& m) { | |||
| 1826 | if (!d->Name) break; | 2299 | if (!d->Name) break; |
| 1827 | std::string dll = read_string(m.name, m.base, m.size, d->Name, "an imported DLL name"); | 2300 | std::string dll = read_string(m.name, m.base, m.size, d->Name, "an imported DLL name"); |
| 1828 | uint32_t lookup = d->OriginalFirstThunk ? d->OriginalFirstThunk : d->FirstThunk; | 2301 | uint32_t lookup = d->OriginalFirstThunk ? d->OriginalFirstThunk : d->FirstThunk; |
| 1829 | bind_thunks(dll, lookup, d->FirstThunk); | 2302 | bind_thunks(dll, lookup, d->FirstThunk, false); |
| 1830 | } | 2303 | } |
| 1831 | } | 2304 | } |
| 1832 | // Delay imports are bound eagerly: simpler, and the full import surface shows up in --dry-run. | 2305 | // Delay imports are bound eagerly: simpler, and the full import surface shows up in --dry-run. |
| @@ -1849,7 +2322,7 @@ void Loader::bind_imports(Module& m) { | |||
| 1849 | // thunk addresses as name RVAs. | 2322 | // thunk addresses as name RVAs. |
| 1850 | if (!d->ImportNameTableRVA) | 2323 | if (!d->ImportNameTableRVA) |
| 1851 | throw std::runtime_error(m.name + ": a delay-import descriptor has no name table"); | 2324 | throw std::runtime_error(m.name + ": a delay-import descriptor has no name table"); |
| 1852 | bind_thunks(dll, d->ImportNameTableRVA, d->ImportAddressTableRVA); | 2325 | bind_thunks(dll, d->ImportNameTableRVA, d->ImportAddressTableRVA, true); |
| 1853 | } | 2326 | } |
| 1854 | } | 2327 | } |
| 1855 | } | 2328 | } |
| @@ -1857,6 +2330,65 @@ void Loader::bind_imports(Module& m) { | |||
| 1857 | void Loader::protect_sections(Module& m) { | 2330 | void Loader::protect_sections(Module& m) { |
| 1858 | auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew); | 2331 | auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew); |
| 1859 | DWORD old; | 2332 | DWORD old; |
| 2333 | // On a CPU without CLZERO, the image's CLZERO loops run from stubs instead of taking a #UD per cache line | ||
| 2334 | // (clzero_patch.h). The sections are still writable here, and none of the image's code has run. | ||
| 2335 | static const bool clzero_missing = !rt::cpu_emulation::detect_host().clzero; | ||
| 2336 | if (clzero_missing && rt::clzero_patch::enabled()) { | ||
| 2337 | std::vector<std::pair<uint8_t*, size_t>> code; | ||
| 2338 | const IMAGE_SECTION_HEADER* cs = IMAGE_FIRST_SECTION(nt); | ||
| 2339 | for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++cs) { | ||
| 2340 | if (!(cs->Characteristics & IMAGE_SCN_MEM_EXECUTE) || cs->VirtualAddress >= m.size) continue; | ||
| 2341 | const uint64_t size = std::min<uint64_t>(std::min(cs->Misc.VirtualSize, cs->SizeOfRawData), | ||
| 2342 | m.size - cs->VirtualAddress); | ||
| 2343 | if (size) code.push_back({m.base + cs->VirtualAddress, static_cast<size_t>(size)}); | ||
| 2344 | } | ||
| 2345 | const auto patched = rt::clzero_patch::patch(code, uint64_t(m.base), uint64_t(m.base) + m.size); | ||
| 2346 | if (patched.sites) | ||
| 2347 | std::fprintf(stderr, | ||
| 2348 | "[rt] loader: %s: %zu CLZERO loops run from stubs at %p (%zu bytes), not as a #UD per line\n", | ||
| 2349 | m.name.c_str(), patched.sites, static_cast<void*>(patched.stubs), patched.stub_bytes); | ||
| 2350 | } | ||
| 2351 | { | ||
| 2352 | const auto isa = rt::isa_jit_patch::patch_image(m.base, m.size); | ||
| 2353 | if (isa.stubs && isa.stub_bytes) { | ||
| 2354 | std::unique_lock lock(ranges_mutex_); | ||
| 2355 | ranges_.push_back({reinterpret_cast<uint64_t>(isa.stubs), | ||
| 2356 | static_cast<uint32_t>(isa.stub_bytes), m.name + "[isa-stubs]"}); | ||
| 2357 | } | ||
| 2358 | if (isa.inplace_sites || isa.bmi_stubs || isa.avx2_stubs || isa.fma3_stubs) { | ||
| 2359 | std::fprintf(stderr, | ||
| 2360 | "[rt] loader: %s: native AVX1/x64 acceleration: %zu in-place, %zu BMI, %zu AVX2 (%zu fused 4B), " | ||
| 2361 | "%zu FMA3 stubs at %p (%zu KiB)\n", | ||
| 2362 | m.name.c_str(), isa.inplace_sites, isa.bmi_stubs, isa.avx2_stubs, isa.avx2_fused_4b, | ||
| 2363 | isa.fma3_stubs, static_cast<void*>(isa.stubs), (isa.stub_bytes + 1023u) / 1024u); | ||
| 2364 | } | ||
| 2365 | } | ||
| 2366 | static const auto bmi_host = rt::bmi_emulation::detect_host(); | ||
| 2367 | if ((!bmi_host.bmi1 || !bmi_host.lzcnt) && rt::bmi_emulation::lzcnt_patch_enabled()) { | ||
| 2368 | std::vector<std::pair<uint32_t, uint32_t>> exec_ranges; | ||
| 2369 | const IMAGE_SECTION_HEADER* cs = IMAGE_FIRST_SECTION(nt); | ||
| 2370 | for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++cs) { | ||
| 2371 | if (!(cs->Characteristics & IMAGE_SCN_MEM_EXECUTE) || cs->VirtualAddress >= m.size) continue; | ||
| 2372 | const uint64_t size = std::min<uint64_t>(std::min(cs->Misc.VirtualSize, cs->SizeOfRawData), | ||
| 2373 | m.size - cs->VirtualAddress); | ||
| 2374 | if (size) exec_ranges.push_back({cs->VirtualAddress, static_cast<uint32_t>(size)}); | ||
| 2375 | } | ||
| 2376 | const auto exc = directory(nt, IMAGE_DIRECTORY_ENTRY_EXCEPTION); | ||
| 2377 | const RUNTIME_FUNCTION* pdata = nullptr; | ||
| 2378 | uint32_t pdata_count = 0; | ||
| 2379 | if (exc.VirtualAddress && exc.Size >= sizeof(RUNTIME_FUNCTION) && exc.VirtualAddress < m.size) { | ||
| 2380 | const uint64_t max_bytes = std::min<uint64_t>(exc.Size, m.size - exc.VirtualAddress); | ||
| 2381 | pdata_count = static_cast<uint32_t>(max_bytes / sizeof(RUNTIME_FUNCTION)); | ||
| 2382 | pdata = at<RUNTIME_FUNCTION>(m.base, exc.VirtualAddress); | ||
| 2383 | } | ||
| 2384 | const auto patched = rt::bmi_emulation::patch_image( | ||
| 2385 | m.base, m.size, exec_ranges, pdata, pdata_count, !bmi_host.bmi1, !bmi_host.lzcnt); | ||
| 2386 | if (patched.tzcnt_sites || patched.lzcnt_sites) | ||
| 2387 | std::fprintf(stderr, | ||
| 2388 | "[rt] loader: %s: patched %zu TZCNT and %zu LZCNT sites (%zu stubs at %p, %zu #UD)\n", | ||
| 2389 | m.name.c_str(), patched.tzcnt_sites, patched.lzcnt_sites, patched.stub_sites, | ||
| 2390 | static_cast<void*>(patched.stubs), patched.ud2_sites); | ||
| 2391 | } | ||
| 1860 | VirtualProtect(m.base, nt->OptionalHeader.SizeOfHeaders, PAGE_READONLY, &old); | 2392 | VirtualProtect(m.base, nt->OptionalHeader.SizeOfHeaders, PAGE_READONLY, &old); |
| 1861 | auto* sec = IMAGE_FIRST_SECTION(nt); | 2393 | auto* sec = IMAGE_FIRST_SECTION(nt); |
| 1862 | for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++sec) { | 2394 | for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++sec) { |