upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/runtime/src/pe_loader.cpp
diff options
context:
space:
mode:
authorOreoFR <29048345+OreoFR@users.noreply.github.com>2026-11-29 09:41:15 +0100
committerOreoFR <29048345+OreoFR@users.noreply.github.com>2026-11-29 09:41:15 +0100
commite7c33662107196e6ba3dd143993dba4e5b44bf4c (patch)
tree7586e357119506317a9ea6f36bf9ab2d8955cbd5 /runtime/src/pe_loader.cpp
parente11c0017cae0d1938e4710e34b9666e603308657 (diff)
parent54b2a81e95c470c953ddee6177fd6255cbaf041d (diff)
Merge origin/main into #1906 (carry prep)
docs/design.md: wave64 emulation row keeps main's barrier text and the PR's s_bitset sentence. Co-authored-by: Jordan <44410206+JordanWebDev@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'runtime/src/pe_loader.cpp')
-rw-r--r--runtime/src/pe_loader.cpp296
1 files changed, 237 insertions, 59 deletions
diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp
index 3558cffb5..303469b06 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,8 +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"
22#include "clzero_patch.h" 24#include "clzero_patch.h"
23#include "cpu_emulation.h" 25#include "cpu_emulation.h"
26#include "isa_jit_patch.h"
24 27
25namespace rt { 28namespace rt {
26 29
@@ -77,9 +80,16 @@ std::string path_utf8(const std::filesystem::path& path) {
77} 80}
78 81
79std::vector<uint8_t> read_file(const std::filesystem::path& p) { 82std::vector<uint8_t> read_file(const std::filesystem::path& p) {
80 std::ifstream f(p, std::ios::binary); 83 std::unique_ptr<std::FILE, decltype(&std::fclose)> file(
81 if (!f) throw std::runtime_error("cannot open " + path_utf8(p)); 84 _wfsopen(p.c_str(), L"rb", _SH_DENYNO), std::fclose);
82 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;
83} 93}
84 94
85template <class T> 95template <class T>
@@ -1341,6 +1351,15 @@ void* bundled_load_w(void* ctx, const std::wstring& basename, uint32_t flags, bo
1341 return static_cast<Loader*>(ctx)->load_runtime_module_w(basename, flags, handled); 1351 return static_cast<Loader*>(ctx)->load_runtime_module_w(basename, flags, handled);
1342} 1352}
1343 1353
1354void* bundled_compat_module(void* ctx, const std::wstring& basename, const std::wstring& name, bool load,
1355 uint32_t flags, bool& handled) {
1356 return static_cast<Loader*>(ctx)->runtime_compat_module(basename, name, load, flags, handled);
1357}
1358
1359bool bundled_owns_compat_handle(void* ctx, void* module) {
1360 return static_cast<Loader*>(ctx)->owns_compat_handle(module);
1361}
1362
1344const shims::BundledModuleOps kBundledOps{ 1363const shims::BundledModuleOps kBundledOps{
1345 &bundled_find_loaded, 1364 &bundled_find_loaded,
1346 &bundled_load, 1365 &bundled_load,
@@ -1348,6 +1367,8 @@ const shims::BundledModuleOps kBundledOps{
1348 &bundled_owns_handle, 1367 &bundled_owns_handle,
1349 &bundled_find_loaded_w, 1368 &bundled_find_loaded_w,
1350 &bundled_load_w, 1369 &bundled_load_w,
1370 &bundled_compat_module,
1371 &bundled_owns_compat_handle,
1351}; 1372};
1352 1373
1353// Marks what a run-time load maps as a dynamic load for as long as it is in scope (the caller holds the mutex). 1374// Marks what a run-time load maps as a dynamic load for as long as it is in scope (the caller holds the mutex).
@@ -1363,7 +1384,18 @@ struct RuntimeLoadScope {
1363Loader::Loader(std::filesystem::path game_dir) : game_dir_(std::move(game_dir)) { 1384Loader::Loader(std::filesystem::path game_dir) : game_dir_(std::move(game_dir)) {
1364 std::vector<wchar_t> compat(32768); 1385 std::vector<wchar_t> compat(32768);
1365 const DWORD n = GetEnvironmentVariableW(L"LEONIDA_COMPAT_DIR", compat.data(), static_cast<DWORD>(compat.size())); 1386 const DWORD n = GetEnvironmentVariableW(L"LEONIDA_COMPAT_DIR", compat.data(), static_cast<DWORD>(compat.size()));
1366 if (n > 0 && n < compat.size()) compat_dir_ = std::filesystem::path(compat.data()); 1387 if (n > 0 && n < compat.size()) {
1388 // Absolute, with backslashes and no trailing separator: LoadLibraryExW with LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR
1389 // needs a full path, and owns_compat_handle() compares it with a module's own folder.
1390 std::error_code ec;
1391 compat_dir_ = std::filesystem::absolute(std::filesystem::path(compat.data()), ec).lexically_normal();
1392 compat_dir_.make_preferred();
1393 if (!compat_dir_.has_filename()) compat_dir_ = compat_dir_.parent_path();
1394 for (std::filesystem::directory_iterator it(compat_dir_, ec), end; !ec && it != end; it.increment(ec)) {
1395 std::error_code file_ec;
1396 if (it->is_regular_file(file_ec)) compat_files_.push_back(it->path().filename());
1397 }
1398 }
1367 shims::add_module_lookup(this, &lookup_in_loader); 1399 shims::add_module_lookup(this, &lookup_in_loader);
1368 shims::add_bundled_loader(this, &kBundledOps); 1400 shims::add_bundled_loader(this, &kBundledOps);
1369} 1401}
@@ -1504,6 +1536,8 @@ void* Loader::load_runtime_module_w(const std::wstring& basename, uint32_t flags
1504 if (prefer_host_copy(narrow)) return nullptr; 1536 if (prefer_host_copy(narrow)) return nullptr;
1505 1537
1506 std::lock_guard lock(mutex_); 1538 std::lock_guard lock(mutex_);
1539 // As load_runtime_module: a run-time load, so DllMain gets a null lpvReserved.
1540 const RuntimeLoadScope dynamic(runtime_loads_);
1507 Module* existing = find_wide_module(basename); 1541 Module* existing = find_wide_module(basename);
1508 const std::filesystem::path candidate = game_dir_ / basename; 1542 const std::filesystem::path candidate = game_dir_ / basename;
1509 std::error_code ec; 1543 std::error_code ec;
@@ -1721,10 +1755,7 @@ Module& Loader::map_image(const std::filesystem::path& path, const std::string&
1721 if (!m->base) 1755 if (!m->base)
1722 m->base = static_cast<uint8_t*>(VirtualAlloc(reinterpret_cast<void*>(oh.ImageBase), oh.SizeOfImage, 1756 m->base = static_cast<uint8_t*>(VirtualAlloc(reinterpret_cast<void*>(oh.ImageBase), oh.SizeOfImage,
1723 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); 1757 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE));
1724 if (!m->base) { 1758 if (!m->base) { // whether the image may move is decided at the relocation step below
1725 const auto relocs = directory(nt, IMAGE_DIRECTORY_ENTRY_BASERELOC);
1726 if (!relocs.Size)
1727 throw std::runtime_error(m->name + ": preferred base is taken and the image has no relocations");
1728 m->base = static_cast<uint8_t*>(VirtualAlloc(nullptr, oh.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); 1759 m->base = static_cast<uint8_t*>(VirtualAlloc(nullptr, oh.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE));
1729 if (!m->base) throw std::runtime_error(m->name + ": VirtualAlloc failed"); 1760 if (!m->base) throw std::runtime_error(m->name + ": VirtualAlloc failed");
1730 } 1761 }
@@ -1749,10 +1780,19 @@ Module& Loader::map_image(const std::filesystem::path& path, const std::string&
1749 } 1780 }
1750 1781
1751 int64_t delta = reinterpret_cast<int64_t>(m->base) - static_cast<int64_t>(oh.ImageBase); 1782 int64_t delta = reinterpret_cast<int64_t>(m->base) - static_cast<int64_t>(oh.ImageBase);
1752 if (delta) { 1783 // A moved image with a relocation table is fixed up, whatever IMAGE_FILE_RELOCS_STRIPPED says. Without a table,
1753 m->relocated = true; 1784 // the flag refuses the move; with the flag clear the image is moved and nothing is fixed up, so it is trusted to
1754 const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_BASERELOC); 1785 // hold no absolute addresses. The Windows 11 loader does all three (runtime/README.md); that move is logged so
1755 if (!dir.Size) throw std::runtime_error(m->name + ": the image has no relocations and isn't at its base"); 1786 // it shows in traces. base_reservation::needed still keeps the main image's range free when it has no
1787 // relocation directory, so a main image is moved this way only where the range could not be had.
1788 const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_BASERELOC);
1789 if (delta) m->relocated = true;
1790 if (delta && !dir.Size && (nt->FileHeader.Characteristics & IMAGE_FILE_RELOCS_STRIPPED))
1791 throw std::runtime_error(m->name + ": preferred base is taken and the image's relocations are stripped");
1792 if (delta && !dir.Size)
1793 std::fprintf(stderr, "[rt] loader: %s: preferred base %#llx is taken, moved to %p with no relocations\n",
1794 m->name.c_str(), static_cast<unsigned long long>(oh.ImageBase), static_cast<void*>(m->base));
1795 if (delta && dir.Size) {
1756 require_range(m->name, dir.VirtualAddress, dir.Size, m->size, "the relocation table"); 1796 require_range(m->name, dir.VirtualAddress, dir.Size, m->size, "the relocation table");
1757 auto* block = at<IMAGE_BASE_RELOCATION>(m->base, dir.VirtualAddress); 1797 auto* block = at<IMAGE_BASE_RELOCATION>(m->base, dir.VirtualAddress);
1758 auto* end = reinterpret_cast<uint8_t*>(block) + dir.Size; 1798 auto* end = reinterpret_cast<uint8_t*>(block) + dir.Size;
@@ -1884,6 +1924,25 @@ void Loader::initialize_tls(Module& m) {
1884 throw std::runtime_error(m.name + ": reserved TLS index is out of range"); 1924 throw std::runtime_error(m.name + ": reserved TLS index is out of range");
1885 } 1925 }
1886 1926
1927 // An EXE's code may read its TLS at index 0 directly (/GA); index 0 is gta6rt.exe's here (pe_loader.h,
1928 // tls_ga_slot). Patched before any of the image's code runs, TLS callbacks included, and before the owner is
1929 // published below: from then on a thread event (install_thread_block) reads m.tls_ga_slot
1930 // (RT-LOADER-RUNTIME-SCOPE-AND-TLS-SLOT).
1931 if (executable && total && index != 0 && ga_tls_patch_enabled()) {
1932 static const DWORD ga_slot = TlsAlloc();
1933 if (ga_slot == TLS_OUT_OF_INDEXES || ga_slot >= 64) {
1934 std::fprintf(stderr, "[rt] loader: %s: no TlsAlloc slot below 64 for its index-0 TLS reads\n",
1935 m.name.c_str());
1936 } else {
1937 m.tls_ga_sites = patch_ga_tls_reads(m, ga_slot);
1938 if (m.tls_ga_sites) m.tls_ga_slot = ga_slot;
1939 std::fprintf(stderr,
1940 "[rt] loader: %s: %zu index-0 TLS reads (gs:[58h]) now read its own TLS (TlsSlots[%lu]); "
1941 "its module TLS index is %u\n",
1942 m.name.c_str(), m.tls_ga_sites, static_cast<unsigned long>(ga_slot), index);
1943 }
1944 }
1945
1887 // The fields are complete before a thread event can see the owner. 1946 // The fields are complete before a thread event can see the owner.
1888 ExclusiveTlsLock lock; 1947 ExclusiveTlsLock lock;
1889 Module* expected = nullptr; 1948 Module* expected = nullptr;
@@ -1902,26 +1961,6 @@ void Loader::initialize_tls(Module& m) {
1902 // VirtualProtect dance. 1961 // VirtualProtect dance.
1903 if (index_rva) *reinterpret_cast<uint32_t*>(m.base + index_rva) = index; 1962 if (index_rva) *reinterpret_cast<uint32_t*>(m.base + index_rva) = index;
1904 } 1963 }
1905 {
1906 // An EXE's code may read its TLS at index 0 directly (/GA); index 0 is gta6rt.exe's here (pe_loader.h,
1907 // tls_ga_slot). Patched before any of the image's code runs, TLS callbacks included.
1908 const auto* dos = reinterpret_cast<const IMAGE_DOS_HEADER*>(m.base);
1909 const auto* nt = reinterpret_cast<const IMAGE_NT_HEADERS64*>(m.base + dos->e_lfanew);
1910 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && total && index != 0 && ga_tls_patch_enabled()) {
1911 static const DWORD ga_slot = TlsAlloc();
1912 if (ga_slot == TLS_OUT_OF_INDEXES || ga_slot >= 64) {
1913 std::fprintf(stderr, "[rt] loader: %s: no TlsAlloc slot below 64 for its index-0 TLS reads\n",
1914 m.name.c_str());
1915 } else {
1916 m.tls_ga_sites = patch_ga_tls_reads(m, ga_slot);
1917 if (m.tls_ga_sites) m.tls_ga_slot = ga_slot;
1918 std::fprintf(stderr,
1919 "[rt] loader: %s: %zu index-0 TLS reads (gs:[58h]) now read its own TLS (TlsSlots[%lu]); "
1920 "its module TLS index is %u\n",
1921 m.name.c_str(), m.tls_ga_sites, static_cast<unsigned long>(ga_slot), index);
1922 }
1923 }
1924 }
1925 try { 1964 try {
1926 install_thread_block(m); 1965 install_thread_block(m);
1927 } catch (...) { 1966 } catch (...) {
@@ -2040,37 +2079,128 @@ void* Loader::resolve_forwarder(const std::string& spec, Binding& binding, int d
2040 return reinterpret_cast<void*>(p); 2079 return reinterpret_cast<void*>(p);
2041} 2080}
2042 2081
2082const std::filesystem::path* Loader::compat_file(const std::wstring& basename) const {
2083 if (basename.empty()) return nullptr;
2084 for (const auto& file : compat_files_)
2085 if (same_module_name(file.c_str(), basename.c_str())) return &file;
2086 return nullptr;
2087}
2088
2089void* Loader::compat_handle(const std::filesystem::path& file, bool load, uint32_t& error) {
2090 error = ERROR_SUCCESS;
2091 const std::string key = lower(path_utf8(file));
2092 if (auto it = compat_modules_.find(key); it != compat_modules_.end()) return it->second;
2093 const std::filesystem::path candidate = compat_dir_ / file;
2094 // Already live without a lookup through here: Windows loaded it from the folder as another compat DLL's
2095 // dependency (LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR), or something loaded it by its path. That is the module a
2096 // static import or a run-time load must share. The reference taken here is kept, as for the DLLs loaded below.
2097 if (HMODULE live = nullptr; GetModuleHandleExW(0, candidate.c_str(), &live) && live) {
2098 compat_modules_.emplace(key, live);
2099 std::fprintf(stderr, "[rt] compat: %s -> %s (already loaded)\n", path_utf8(file).c_str(),
2100 path_utf8(candidate).c_str());
2101 return live;
2102 }
2103 if (!load) return nullptr;
2104 // The full path, with the compat folder on the DLL's own search path for its dependencies; never the game
2105 // folder. Windows maps it, so its CRT, TLS and SEH work as for any host DLL.
2106 // A file Windows cannot map (truncated, wrong machine, not a PE image) otherwise raises a modal "Bad Image"
2107 // box and LoadLibraryExW does not return until someone clicks it: a headless run would hang on a failure
2108 // that the caller reports anyway. The mode is this thread's, and goes back as it was.
2109 DWORD previous_mode = 0;
2110 const bool mode_set = SetThreadErrorMode(GetThreadErrorMode() | SEM_FAILCRITICALERRORS, &previous_mode) != 0;
2111 HMODULE h = LoadLibraryExW(candidate.c_str(), nullptr, LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32);
2112 error = h ? ERROR_SUCCESS : GetLastError();
2113 if (mode_set) SetThreadErrorMode(previous_mode, nullptr);
2114 if (!h) return nullptr;
2115 compat_modules_.emplace(key, h);
2116 std::fprintf(stderr, "[rt] compat: %s -> %s\n", path_utf8(file).c_str(), path_utf8(candidate).c_str());
2117 return h;
2118}
2119
2043bool Loader::resolve_compat(const std::string& key, const std::string& dll, const std::string& name, uint16_t ordinal, 2120bool Loader::resolve_compat(const std::string& key, const std::string& dll, const std::string& name, uint16_t ordinal,
2044 bool by_ordinal, void*& out) { 2121 bool by_ordinal, void*& out) {
2045 out = nullptr; 2122 out = nullptr;
2046 if (compat_dir_.empty() || key.empty() || key.find_first_of("/\\:") != std::string::npos) return false; 2123 if (compat_dir_.empty() || key.empty() || key.find_first_of("/\\:") != std::string::npos) return false;
2047 HMODULE h = nullptr; 2124 const std::filesystem::path* file = compat_file(acp_to_wide(dll));
2048 if (auto it = compat_modules_.find(key); it != compat_modules_.end()) { 2125 if (!file) return false;
2049 h = static_cast<HMODULE>(it->second); 2126 uint32_t error = ERROR_SUCCESS;
2050 } else { 2127 HMODULE h = static_cast<HMODULE>(compat_handle(*file, true, error));
2051 const std::filesystem::path candidate = compat_dir_ / std::filesystem::path(dll); 2128 if (!h)
2052 std::error_code ec; 2129 throw std::runtime_error("LEONIDA_COMPAT_DIR: " + path_utf8(compat_dir_ / *file) +
2053 if (!std::filesystem::is_regular_file(candidate, ec)) return false; 2130 " exists but Windows could not load it (error " + std::to_string(error) + ")");
2054 // The full path, with the compat folder on the DLL's own search path for its dependencies; never the game
2055 // folder. Windows maps it, so its CRT, TLS and SEH work as for any host DLL.
2056 // A file Windows cannot map (truncated, wrong machine, not a PE image) otherwise raises a modal "Bad Image"
2057 // box and LoadLibraryExW does not return until someone clicks it: a headless run would hang on a failure
2058 // that is reported right below anyway. The mode is this thread's, and goes back as it was.
2059 DWORD previous_mode = 0;
2060 const bool mode_set = SetThreadErrorMode(GetThreadErrorMode() | SEM_FAILCRITICALERRORS, &previous_mode) != 0;
2061 h = LoadLibraryExW(candidate.c_str(), nullptr, LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32);
2062 const DWORD load_error = h ? ERROR_SUCCESS : GetLastError();
2063 if (mode_set) SetThreadErrorMode(previous_mode, nullptr);
2064 if (!h)
2065 throw std::runtime_error("LEONIDA_COMPAT_DIR: " + path_utf8(candidate) + " exists but Windows could not " +
2066 "load it (error " + std::to_string(load_error) + ")");
2067 compat_modules_.emplace(key, h);
2068 std::fprintf(stderr, "[rt] compat: %s -> %s\n", dll.c_str(), path_utf8(candidate).c_str());
2069 }
2070 out = reinterpret_cast<void*>(GetProcAddress(h, by_ordinal ? MAKEINTRESOURCEA(ordinal) : name.c_str())); 2131 out = reinterpret_cast<void*>(GetProcAddress(h, by_ordinal ? MAKEINTRESOURCEA(ordinal) : name.c_str()));
2071 return true; 2132 return true;
2072} 2133}
2073 2134
2135void* Loader::runtime_compat_module(const std::wstring& basename, const std::wstring& name, bool load,
2136 uint32_t flags, bool& handled) {
2137 handled = false;
2138 if (compat_dir_.empty()) return nullptr;
2139 std::lock_guard lock(mutex_);
2140 const std::filesystem::path* file = compat_file(basename);
2141 if (!file) return nullptr;
2142 const std::filesystem::path compat_path = compat_dir_ / *file;
2143 // A name with a directory names one file, which Windows would load even when another of the same name is in use:
2144 // the compat DLL answers it only when it is that file (".dll" added as LoadLibrary adds it). Any other path goes
2145 // on as without the folder.
2146 if (name.find_first_of(L"\\/:") != std::wstring::npos) {
2147 std::filesystem::path given(name);
2148 given.replace_filename(basename);
2149 std::error_code ec;
2150 if (!std::filesystem::equivalent(given, compat_path, ec)) return nullptr;
2151 }
2152 handled = true;
2153 // DONT_RESOLVE_DLL_REFERENCES maps a DLL without its dependencies, TLS or DllMain. The compat DLL is shared with
2154 // static imports, initialised, so refuse it before loading or returning a handle, as for bundled DLLs
2155 // (load_runtime_candidate).
2156 if (load && (flags & DONT_RESOLVE_DLL_REFERENCES) != 0) {
2157 std::fprintf(stderr, "[rt] compat: LoadLibraryEx(%s, DONT_RESOLVE_DLL_REFERENCES) is not supported\n",
2158 path_utf8(compat_path).c_str());
2159 SetLastError(ERROR_NOT_SUPPORTED);
2160 return nullptr;
2161 }
2162 uint32_t error = ERROR_SUCCESS;
2163 void* h = compat_handle(*file, load, error);
2164 if (!h && load) {
2165 // As a LoadLibrary of a file Windows refuses: null and its error, never the shim (the player put the DLL
2166 // there to own the module).
2167 std::fprintf(stderr, "[rt] compat: %s exists but Windows could not load it (error %u, run-time load)\n",
2168 path_utf8(compat_path).c_str(), error);
2169 SetLastError(error);
2170 } else if (!h) {
2171 SetLastError(ERROR_MOD_NOT_FOUND); // GetModuleHandle of a module nothing has loaded yet
2172 }
2173 return h;
2174}
2175
2176bool Loader::owns_compat_handle(void* module) {
2177 if (!module || compat_dir_.empty()) return false;
2178 {
2179 std::lock_guard lock(mutex_);
2180 for (const auto& [key, h] : compat_modules_)
2181 if (h == module) return true;
2182 }
2183 // A DLL from the folder that no lookup has seen yet (Windows loaded it as another compat DLL's dependency): its
2184 // exports are its own too. Recorded, with a kept reference, through compat_handle(). GetModuleFileNameW can take
2185 // the Windows loader lock, so the path is read without mutex_ held; compat_dir_ and compat_files_ do not change
2186 // after construction.
2187 std::vector<wchar_t> path(MAX_PATH);
2188 DWORD length = 0;
2189 for (;;) {
2190 length = GetModuleFileNameW(static_cast<HMODULE>(module), path.data(), static_cast<DWORD>(path.size()));
2191 if (!length || length < path.size() || path.size() >= 32768) break;
2192 path.resize(path.size() * 2);
2193 }
2194 if (!length || length >= path.size()) return false;
2195 const std::filesystem::path file(std::wstring(path.data(), length));
2196 if (!same_module_name(file.parent_path().c_str(), compat_dir_.c_str())) return false;
2197 const std::filesystem::path* entry = compat_file(file.filename().native());
2198 if (!entry) return false;
2199 std::lock_guard lock(mutex_);
2200 uint32_t error = ERROR_SUCCESS;
2201 return compat_handle(*entry, false, error) == module;
2202}
2203
2074void* Loader::resolve(Module& m, const std::string& dll, const std::string& name, uint16_t ordinal, bool by_ordinal) { 2204void* Loader::resolve(Module& m, const std::string& dll, const std::string& name, uint16_t ordinal, bool by_ordinal) {
2075 std::string key = lower(dll); 2205 std::string key = lower(dll);
2076 std::string sym = by_ordinal ? "#" + std::to_string(ordinal) : name; 2206 std::string sym = by_ordinal ? "#" + std::to_string(ordinal) : name;
@@ -2123,7 +2253,10 @@ void Loader::bind_imports(Module& m) {
2123 const uint64_t headers_end = nt->OptionalHeader.SizeOfHeaders; 2253 const uint64_t headers_end = nt->OptionalHeader.SizeOfHeaders;
2124 2254
2125 // Thunk tables have no length field: they end at a zero entry, so each step is checked against the image. 2255 // Thunk tables have no length field: they end at a zero entry, so each step is checked against the image.
2126 auto bind_thunks = [&](const std::string& dll, uint64_t lookup_rva, uint64_t iat_rva) { 2256 // `delayed`: a delay import that binds to an unimplemented thunk is traced. Windows' delay-load helper would raise
2257 // 0xC06D007E (module) or 0xC06D007F (procedure) at its first call, which a title can catch for a fallback; the
2258 // thunk returns 0 instead, so the trace names each such import before any image code runs.
2259 auto bind_thunks = [&](const std::string& dll, uint64_t lookup_rva, uint64_t iat_rva, bool delayed) {
2127 for (;; lookup_rva += sizeof(IMAGE_THUNK_DATA64), iat_rva += sizeof(IMAGE_THUNK_DATA64)) { 2260 for (;; lookup_rva += sizeof(IMAGE_THUNK_DATA64), iat_rva += sizeof(IMAGE_THUNK_DATA64)) {
2128 require_range(m.name, lookup_rva, sizeof(IMAGE_THUNK_DATA64), m.size, "an import lookup table"); 2261 require_range(m.name, lookup_rva, sizeof(IMAGE_THUNK_DATA64), m.size, "an import lookup table");
2129 require_range(m.name, iat_rva, sizeof(IMAGE_THUNK_DATA64), m.size, "an import address table"); 2262 require_range(m.name, iat_rva, sizeof(IMAGE_THUNK_DATA64), m.size, "an import address table");
@@ -2141,6 +2274,10 @@ void Loader::bind_imports(Module& m) {
2141 throw std::runtime_error(m.name + ": an import address table lands in the headers"); 2274 throw std::runtime_error(m.name + ": an import address table lands in the headers");
2142 at<IMAGE_THUNK_DATA64>(m.base, static_cast<uint32_t>(iat_rva))->u1.Function = 2275 at<IMAGE_THUNK_DATA64>(m.base, static_cast<uint32_t>(iat_rva))->u1.Function =
2143 reinterpret_cast<uint64_t>(resolve(m, dll, name, ord, by_ord)); 2276 reinterpret_cast<uint64_t>(resolve(m, dll, name, ord, by_ord));
2277 if (delayed && startup_trace::enabled() && m.imports.back().binding == Binding::Unimplemented)
2278 startup_trace::event("delay_import_unimplemented",
2279 "\"module\":" + startup_trace::quote(m.name) + ",\"import\":" +
2280 startup_trace::quote(dll + "!" + m.imports.back().name));
2144 } 2281 }
2145 }; 2282 };
2146 2283
@@ -2153,7 +2290,7 @@ void Loader::bind_imports(Module& m) {
2153 if (!d->Name) break; 2290 if (!d->Name) break;
2154 std::string dll = read_string(m.name, m.base, m.size, d->Name, "an imported DLL name"); 2291 std::string dll = read_string(m.name, m.base, m.size, d->Name, "an imported DLL name");
2155 uint32_t lookup = d->OriginalFirstThunk ? d->OriginalFirstThunk : d->FirstThunk; 2292 uint32_t lookup = d->OriginalFirstThunk ? d->OriginalFirstThunk : d->FirstThunk;
2156 bind_thunks(dll, lookup, d->FirstThunk); 2293 bind_thunks(dll, lookup, d->FirstThunk, false);
2157 } 2294 }
2158 } 2295 }
2159 // Delay imports are bound eagerly: simpler, and the full import surface shows up in --dry-run. 2296 // Delay imports are bound eagerly: simpler, and the full import surface shows up in --dry-run.
@@ -2176,7 +2313,7 @@ void Loader::bind_imports(Module& m) {
2176 // thunk addresses as name RVAs. 2313 // thunk addresses as name RVAs.
2177 if (!d->ImportNameTableRVA) 2314 if (!d->ImportNameTableRVA)
2178 throw std::runtime_error(m.name + ": a delay-import descriptor has no name table"); 2315 throw std::runtime_error(m.name + ": a delay-import descriptor has no name table");
2179 bind_thunks(dll, d->ImportNameTableRVA, d->ImportAddressTableRVA); 2316 bind_thunks(dll, d->ImportNameTableRVA, d->ImportAddressTableRVA, true);
2180 } 2317 }
2181 } 2318 }
2182} 2319}
@@ -2202,6 +2339,47 @@ void Loader::protect_sections(Module& m) {
2202 "[rt] loader: %s: %zu CLZERO loops run from stubs at %p (%zu bytes), not as a #UD per line\n", 2339 "[rt] loader: %s: %zu CLZERO loops run from stubs at %p (%zu bytes), not as a #UD per line\n",
2203 m.name.c_str(), patched.sites, static_cast<void*>(patched.stubs), patched.stub_bytes); 2340 m.name.c_str(), patched.sites, static_cast<void*>(patched.stubs), patched.stub_bytes);
2204 } 2341 }
2342 {
2343 const auto isa = rt::isa_jit_patch::patch_image(m.base, m.size);
2344 if (isa.stubs && isa.stub_bytes) {
2345 std::unique_lock lock(ranges_mutex_);
2346 ranges_.push_back({reinterpret_cast<uint64_t>(isa.stubs),
2347 static_cast<uint32_t>(isa.stub_bytes), m.name + "[isa-stubs]"});
2348 }
2349 if (isa.inplace_sites || isa.bmi_stubs || isa.avx2_stubs || isa.fma3_stubs) {
2350 std::fprintf(stderr,
2351 "[rt] loader: %s: native AVX1/x64 acceleration: %zu in-place, %zu BMI, %zu AVX2 (%zu fused 4B), "
2352 "%zu FMA3 stubs at %p (%zu KiB)\n",
2353 m.name.c_str(), isa.inplace_sites, isa.bmi_stubs, isa.avx2_stubs, isa.avx2_fused_4b,
2354 isa.fma3_stubs, static_cast<void*>(isa.stubs), (isa.stub_bytes + 1023u) / 1024u);
2355 }
2356 }
2357 static const auto bmi_host = rt::bmi_emulation::detect_host();
2358 if ((!bmi_host.bmi1 || !bmi_host.lzcnt) && rt::bmi_emulation::lzcnt_patch_enabled()) {
2359 std::vector<std::pair<uint32_t, uint32_t>> exec_ranges;
2360 const IMAGE_SECTION_HEADER* cs = IMAGE_FIRST_SECTION(nt);
2361 for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++cs) {
2362 if (!(cs->Characteristics & IMAGE_SCN_MEM_EXECUTE) || cs->VirtualAddress >= m.size) continue;
2363 const uint64_t size = std::min<uint64_t>(std::min(cs->Misc.VirtualSize, cs->SizeOfRawData),
2364 m.size - cs->VirtualAddress);
2365 if (size) exec_ranges.push_back({cs->VirtualAddress, static_cast<uint32_t>(size)});
2366 }
2367 const auto exc = directory(nt, IMAGE_DIRECTORY_ENTRY_EXCEPTION);
2368 const RUNTIME_FUNCTION* pdata = nullptr;
2369 uint32_t pdata_count = 0;
2370 if (exc.VirtualAddress && exc.Size >= sizeof(RUNTIME_FUNCTION) && exc.VirtualAddress < m.size) {
2371 const uint64_t max_bytes = std::min<uint64_t>(exc.Size, m.size - exc.VirtualAddress);
2372 pdata_count = static_cast<uint32_t>(max_bytes / sizeof(RUNTIME_FUNCTION));
2373 pdata = at<RUNTIME_FUNCTION>(m.base, exc.VirtualAddress);
2374 }
2375 const auto patched = rt::bmi_emulation::patch_image(
2376 m.base, m.size, exec_ranges, pdata, pdata_count, !bmi_host.bmi1, !bmi_host.lzcnt);
2377 if (patched.tzcnt_sites || patched.lzcnt_sites)
2378 std::fprintf(stderr,
2379 "[rt] loader: %s: patched %zu TZCNT and %zu LZCNT sites (%zu stubs at %p, %zu #UD)\n",
2380 m.name.c_str(), patched.tzcnt_sites, patched.lzcnt_sites, patched.stub_sites,
2381 static_cast<void*>(patched.stubs), patched.ud2_sites);
2382 }
2205 VirtualProtect(m.base, nt->OptionalHeader.SizeOfHeaders, PAGE_READONLY, &old); 2383 VirtualProtect(m.base, nt->OptionalHeader.SizeOfHeaders, PAGE_READONLY, &old);
2206 auto* sec = IMAGE_FIRST_SECTION(nt); 2384 auto* sec = IMAGE_FIRST_SECTION(nt);
2207 for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++sec) { 2385 for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++sec) {