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:
authorДмитрий Корлодный <deusex1998@gmail.com>2026-11-28 13:59:13 +0000
committerДмитрий Корлодный <deusex1998@gmail.com>2026-11-28 13:59:13 +0000
commit5fbcc642a52de0f269be65a9dce208dcb87f00fe (patch)
tree518cbe01fe433c290c4cdcd5955bf4585facd68a /runtime/src/pe_loader.cpp
parentf7e422ee8a307ced9a41e11fb02330b4cb7abdaa (diff)
parent9c49bd5332327e689c5c957786c31b10efb3f32b (diff)
Merge upstream main into PR #1559
Diffstat (limited to 'runtime/src/pe_loader.cpp')
-rw-r--r--runtime/src/pe_loader.cpp196
1 files changed, 161 insertions, 35 deletions
diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp
index 3558cffb5..5e89ac2ab 100644
--- a/runtime/src/pe_loader.cpp
+++ b/runtime/src/pe_loader.cpp
@@ -1341,6 +1341,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); 1341 return static_cast<Loader*>(ctx)->load_runtime_module_w(basename, flags, handled);
1342} 1342}
1343 1343
1344void* bundled_compat_module(void* ctx, const std::wstring& basename, const std::wstring& name, bool load,
1345 uint32_t flags, bool& handled) {
1346 return static_cast<Loader*>(ctx)->runtime_compat_module(basename, name, load, flags, handled);
1347}
1348
1349bool bundled_owns_compat_handle(void* ctx, void* module) {
1350 return static_cast<Loader*>(ctx)->owns_compat_handle(module);
1351}
1352
1344const shims::BundledModuleOps kBundledOps{ 1353const shims::BundledModuleOps kBundledOps{
1345 &bundled_find_loaded, 1354 &bundled_find_loaded,
1346 &bundled_load, 1355 &bundled_load,
@@ -1348,6 +1357,8 @@ const shims::BundledModuleOps kBundledOps{
1348 &bundled_owns_handle, 1357 &bundled_owns_handle,
1349 &bundled_find_loaded_w, 1358 &bundled_find_loaded_w,
1350 &bundled_load_w, 1359 &bundled_load_w,
1360 &bundled_compat_module,
1361 &bundled_owns_compat_handle,
1351}; 1362};
1352 1363
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). 1364// 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 +1374,18 @@ struct RuntimeLoadScope {
1363Loader::Loader(std::filesystem::path game_dir) : game_dir_(std::move(game_dir)) { 1374Loader::Loader(std::filesystem::path game_dir) : game_dir_(std::move(game_dir)) {
1364 std::vector<wchar_t> compat(32768); 1375 std::vector<wchar_t> compat(32768);
1365 const DWORD n = GetEnvironmentVariableW(L"LEONIDA_COMPAT_DIR", compat.data(), static_cast<DWORD>(compat.size())); 1376 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()); 1377 if (n > 0 && n < compat.size()) {
1378 // Absolute, with backslashes and no trailing separator: LoadLibraryExW with LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR
1379 // needs a full path, and owns_compat_handle() compares it with a module's own folder.
1380 std::error_code ec;
1381 compat_dir_ = std::filesystem::absolute(std::filesystem::path(compat.data()), ec).lexically_normal();
1382 compat_dir_.make_preferred();
1383 if (!compat_dir_.has_filename()) compat_dir_ = compat_dir_.parent_path();
1384 for (std::filesystem::directory_iterator it(compat_dir_, ec), end; !ec && it != end; it.increment(ec)) {
1385 std::error_code file_ec;
1386 if (it->is_regular_file(file_ec)) compat_files_.push_back(it->path().filename());
1387 }
1388 }
1367 shims::add_module_lookup(this, &lookup_in_loader); 1389 shims::add_module_lookup(this, &lookup_in_loader);
1368 shims::add_bundled_loader(this, &kBundledOps); 1390 shims::add_bundled_loader(this, &kBundledOps);
1369} 1391}
@@ -1721,10 +1743,7 @@ Module& Loader::map_image(const std::filesystem::path& path, const std::string&
1721 if (!m->base) 1743 if (!m->base)
1722 m->base = static_cast<uint8_t*>(VirtualAlloc(reinterpret_cast<void*>(oh.ImageBase), oh.SizeOfImage, 1744 m->base = static_cast<uint8_t*>(VirtualAlloc(reinterpret_cast<void*>(oh.ImageBase), oh.SizeOfImage,
1723 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); 1745 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE));
1724 if (!m->base) { 1746 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)); 1747 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"); 1748 if (!m->base) throw std::runtime_error(m->name + ": VirtualAlloc failed");
1730 } 1749 }
@@ -1749,10 +1768,19 @@ Module& Loader::map_image(const std::filesystem::path& path, const std::string&
1749 } 1768 }
1750 1769
1751 int64_t delta = reinterpret_cast<int64_t>(m->base) - static_cast<int64_t>(oh.ImageBase); 1770 int64_t delta = reinterpret_cast<int64_t>(m->base) - static_cast<int64_t>(oh.ImageBase);
1752 if (delta) { 1771 // A moved image with a relocation table is fixed up, whatever IMAGE_FILE_RELOCS_STRIPPED says. Without a table,
1753 m->relocated = true; 1772 // 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); 1773 // 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"); 1774 // it shows in traces. base_reservation::needed still keeps the main image's range free when it has no
1775 // relocation directory, so a main image is moved this way only where the range could not be had.
1776 const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_BASERELOC);
1777 if (delta) m->relocated = true;
1778 if (delta && !dir.Size && (nt->FileHeader.Characteristics & IMAGE_FILE_RELOCS_STRIPPED))
1779 throw std::runtime_error(m->name + ": preferred base is taken and the image's relocations are stripped");
1780 if (delta && !dir.Size)
1781 std::fprintf(stderr, "[rt] loader: %s: preferred base %#llx is taken, moved to %p with no relocations\n",
1782 m->name.c_str(), static_cast<unsigned long long>(oh.ImageBase), static_cast<void*>(m->base));
1783 if (delta && dir.Size) {
1756 require_range(m->name, dir.VirtualAddress, dir.Size, m->size, "the relocation table"); 1784 require_range(m->name, dir.VirtualAddress, dir.Size, m->size, "the relocation table");
1757 auto* block = at<IMAGE_BASE_RELOCATION>(m->base, dir.VirtualAddress); 1785 auto* block = at<IMAGE_BASE_RELOCATION>(m->base, dir.VirtualAddress);
1758 auto* end = reinterpret_cast<uint8_t*>(block) + dir.Size; 1786 auto* end = reinterpret_cast<uint8_t*>(block) + dir.Size;
@@ -2040,37 +2068,128 @@ void* Loader::resolve_forwarder(const std::string& spec, Binding& binding, int d
2040 return reinterpret_cast<void*>(p); 2068 return reinterpret_cast<void*>(p);
2041} 2069}
2042 2070
2071const std::filesystem::path* Loader::compat_file(const std::wstring& basename) const {
2072 if (basename.empty()) return nullptr;
2073 for (const auto& file : compat_files_)
2074 if (same_module_name(file.c_str(), basename.c_str())) return &file;
2075 return nullptr;
2076}
2077
2078void* Loader::compat_handle(const std::filesystem::path& file, bool load, uint32_t& error) {
2079 error = ERROR_SUCCESS;
2080 const std::string key = lower(path_utf8(file));
2081 if (auto it = compat_modules_.find(key); it != compat_modules_.end()) return it->second;
2082 const std::filesystem::path candidate = compat_dir_ / file;
2083 // Already live without a lookup through here: Windows loaded it from the folder as another compat DLL's
2084 // dependency (LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR), or something loaded it by its path. That is the module a
2085 // static import or a run-time load must share. The reference taken here is kept, as for the DLLs loaded below.
2086 if (HMODULE live = nullptr; GetModuleHandleExW(0, candidate.c_str(), &live) && live) {
2087 compat_modules_.emplace(key, live);
2088 std::fprintf(stderr, "[rt] compat: %s -> %s (already loaded)\n", path_utf8(file).c_str(),
2089 path_utf8(candidate).c_str());
2090 return live;
2091 }
2092 if (!load) return nullptr;
2093 // The full path, with the compat folder on the DLL's own search path for its dependencies; never the game
2094 // folder. Windows maps it, so its CRT, TLS and SEH work as for any host DLL.
2095 // A file Windows cannot map (truncated, wrong machine, not a PE image) otherwise raises a modal "Bad Image"
2096 // box and LoadLibraryExW does not return until someone clicks it: a headless run would hang on a failure
2097 // that the caller reports anyway. The mode is this thread's, and goes back as it was.
2098 DWORD previous_mode = 0;
2099 const bool mode_set = SetThreadErrorMode(GetThreadErrorMode() | SEM_FAILCRITICALERRORS, &previous_mode) != 0;
2100 HMODULE h = LoadLibraryExW(candidate.c_str(), nullptr, LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32);
2101 error = h ? ERROR_SUCCESS : GetLastError();
2102 if (mode_set) SetThreadErrorMode(previous_mode, nullptr);
2103 if (!h) return nullptr;
2104 compat_modules_.emplace(key, h);
2105 std::fprintf(stderr, "[rt] compat: %s -> %s\n", path_utf8(file).c_str(), path_utf8(candidate).c_str());
2106 return h;
2107}
2108
2043bool Loader::resolve_compat(const std::string& key, const std::string& dll, const std::string& name, uint16_t ordinal, 2109bool Loader::resolve_compat(const std::string& key, const std::string& dll, const std::string& name, uint16_t ordinal,
2044 bool by_ordinal, void*& out) { 2110 bool by_ordinal, void*& out) {
2045 out = nullptr; 2111 out = nullptr;
2046 if (compat_dir_.empty() || key.empty() || key.find_first_of("/\\:") != std::string::npos) return false; 2112 if (compat_dir_.empty() || key.empty() || key.find_first_of("/\\:") != std::string::npos) return false;
2047 HMODULE h = nullptr; 2113 const std::filesystem::path* file = compat_file(acp_to_wide(dll));
2048 if (auto it = compat_modules_.find(key); it != compat_modules_.end()) { 2114 if (!file) return false;
2049 h = static_cast<HMODULE>(it->second); 2115 uint32_t error = ERROR_SUCCESS;
2050 } else { 2116 HMODULE h = static_cast<HMODULE>(compat_handle(*file, true, error));
2051 const std::filesystem::path candidate = compat_dir_ / std::filesystem::path(dll); 2117 if (!h)
2052 std::error_code ec; 2118 throw std::runtime_error("LEONIDA_COMPAT_DIR: " + path_utf8(compat_dir_ / *file) +
2053 if (!std::filesystem::is_regular_file(candidate, ec)) return false; 2119 " 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())); 2120 out = reinterpret_cast<void*>(GetProcAddress(h, by_ordinal ? MAKEINTRESOURCEA(ordinal) : name.c_str()));
2071 return true; 2121 return true;
2072} 2122}
2073 2123
2124void* Loader::runtime_compat_module(const std::wstring& basename, const std::wstring& name, bool load,
2125 uint32_t flags, bool& handled) {
2126 handled = false;
2127 if (compat_dir_.empty()) return nullptr;
2128 std::lock_guard lock(mutex_);
2129 const std::filesystem::path* file = compat_file(basename);
2130 if (!file) return nullptr;
2131 const std::filesystem::path compat_path = compat_dir_ / *file;
2132 // A name with a directory names one file, which Windows would load even when another of the same name is in use:
2133 // the compat DLL answers it only when it is that file (".dll" added as LoadLibrary adds it). Any other path goes
2134 // on as without the folder.
2135 if (name.find_first_of(L"\\/:") != std::wstring::npos) {
2136 std::filesystem::path given(name);
2137 given.replace_filename(basename);
2138 std::error_code ec;
2139 if (!std::filesystem::equivalent(given, compat_path, ec)) return nullptr;
2140 }
2141 handled = true;
2142 // DONT_RESOLVE_DLL_REFERENCES maps a DLL without its dependencies, TLS or DllMain. The compat DLL is shared with
2143 // static imports, initialised, so refuse it before loading or returning a handle, as for bundled DLLs
2144 // (load_runtime_candidate).
2145 if (load && (flags & DONT_RESOLVE_DLL_REFERENCES) != 0) {
2146 std::fprintf(stderr, "[rt] compat: LoadLibraryEx(%s, DONT_RESOLVE_DLL_REFERENCES) is not supported\n",
2147 path_utf8(compat_path).c_str());
2148 SetLastError(ERROR_NOT_SUPPORTED);
2149 return nullptr;
2150 }
2151 uint32_t error = ERROR_SUCCESS;
2152 void* h = compat_handle(*file, load, error);
2153 if (!h && load) {
2154 // As a LoadLibrary of a file Windows refuses: null and its error, never the shim (the player put the DLL
2155 // there to own the module).
2156 std::fprintf(stderr, "[rt] compat: %s exists but Windows could not load it (error %u, run-time load)\n",
2157 path_utf8(compat_path).c_str(), error);
2158 SetLastError(error);
2159 } else if (!h) {
2160 SetLastError(ERROR_MOD_NOT_FOUND); // GetModuleHandle of a module nothing has loaded yet
2161 }
2162 return h;
2163}
2164
2165bool Loader::owns_compat_handle(void* module) {
2166 if (!module || compat_dir_.empty()) return false;
2167 {
2168 std::lock_guard lock(mutex_);
2169 for (const auto& [key, h] : compat_modules_)
2170 if (h == module) return true;
2171 }
2172 // A DLL from the folder that no lookup has seen yet (Windows loaded it as another compat DLL's dependency): its
2173 // exports are its own too. Recorded, with a kept reference, through compat_handle(). GetModuleFileNameW can take
2174 // the Windows loader lock, so the path is read without mutex_ held; compat_dir_ and compat_files_ do not change
2175 // after construction.
2176 std::vector<wchar_t> path(MAX_PATH);
2177 DWORD length = 0;
2178 for (;;) {
2179 length = GetModuleFileNameW(static_cast<HMODULE>(module), path.data(), static_cast<DWORD>(path.size()));
2180 if (!length || length < path.size() || path.size() >= 32768) break;
2181 path.resize(path.size() * 2);
2182 }
2183 if (!length || length >= path.size()) return false;
2184 const std::filesystem::path file(std::wstring(path.data(), length));
2185 if (!same_module_name(file.parent_path().c_str(), compat_dir_.c_str())) return false;
2186 const std::filesystem::path* entry = compat_file(file.filename().native());
2187 if (!entry) return false;
2188 std::lock_guard lock(mutex_);
2189 uint32_t error = ERROR_SUCCESS;
2190 return compat_handle(*entry, false, error) == module;
2191}
2192
2074void* Loader::resolve(Module& m, const std::string& dll, const std::string& name, uint16_t ordinal, bool by_ordinal) { 2193void* Loader::resolve(Module& m, const std::string& dll, const std::string& name, uint16_t ordinal, bool by_ordinal) {
2075 std::string key = lower(dll); 2194 std::string key = lower(dll);
2076 std::string sym = by_ordinal ? "#" + std::to_string(ordinal) : name; 2195 std::string sym = by_ordinal ? "#" + std::to_string(ordinal) : name;
@@ -2123,7 +2242,10 @@ void Loader::bind_imports(Module& m) {
2123 const uint64_t headers_end = nt->OptionalHeader.SizeOfHeaders; 2242 const uint64_t headers_end = nt->OptionalHeader.SizeOfHeaders;
2124 2243
2125 // Thunk tables have no length field: they end at a zero entry, so each step is checked against the image. 2244 // 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) { 2245 // `delayed`: a delay import that binds to an unimplemented thunk is traced. Windows' delay-load helper would raise
2246 // 0xC06D007E (module) or 0xC06D007F (procedure) at its first call, which a title can catch for a fallback; the
2247 // thunk returns 0 instead, so the trace names each such import before any image code runs.
2248 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)) { 2249 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"); 2250 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"); 2251 require_range(m.name, iat_rva, sizeof(IMAGE_THUNK_DATA64), m.size, "an import address table");
@@ -2141,6 +2263,10 @@ void Loader::bind_imports(Module& m) {
2141 throw std::runtime_error(m.name + ": an import address table lands in the headers"); 2263 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 = 2264 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)); 2265 reinterpret_cast<uint64_t>(resolve(m, dll, name, ord, by_ord));
2266 if (delayed && startup_trace::enabled() && m.imports.back().binding == Binding::Unimplemented)
2267 startup_trace::event("delay_import_unimplemented",
2268 "\"module\":" + startup_trace::quote(m.name) + ",\"import\":" +
2269 startup_trace::quote(dll + "!" + m.imports.back().name));
2144 } 2270 }
2145 }; 2271 };
2146 2272
@@ -2153,7 +2279,7 @@ void Loader::bind_imports(Module& m) {
2153 if (!d->Name) break; 2279 if (!d->Name) break;
2154 std::string dll = read_string(m.name, m.base, m.size, d->Name, "an imported DLL name"); 2280 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; 2281 uint32_t lookup = d->OriginalFirstThunk ? d->OriginalFirstThunk : d->FirstThunk;
2156 bind_thunks(dll, lookup, d->FirstThunk); 2282 bind_thunks(dll, lookup, d->FirstThunk, false);
2157 } 2283 }
2158 } 2284 }
2159 // Delay imports are bound eagerly: simpler, and the full import surface shows up in --dry-run. 2285 // Delay imports are bound eagerly: simpler, and the full import surface shows up in --dry-run.
@@ -2176,7 +2302,7 @@ void Loader::bind_imports(Module& m) {
2176 // thunk addresses as name RVAs. 2302 // thunk addresses as name RVAs.
2177 if (!d->ImportNameTableRVA) 2303 if (!d->ImportNameTableRVA)
2178 throw std::runtime_error(m.name + ": a delay-import descriptor has no name table"); 2304 throw std::runtime_error(m.name + ": a delay-import descriptor has no name table");
2179 bind_thunks(dll, d->ImportNameTableRVA, d->ImportAddressTableRVA); 2305 bind_thunks(dll, d->ImportNameTableRVA, d->ImportAddressTableRVA, true);
2180 } 2306 }
2181 } 2307 }
2182} 2308}