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:
authorTreXito <81475944+TreXito@users.noreply.github.com>2026-11-23 17:34:10 +0000
committerTreXito <81475944+TreXito@users.noreply.github.com>2026-11-23 17:34:10 +0000
commit5734bcf8409e78582e9ce088d86ebf4d2f56f4bb (patch)
tree913c17eaed0223161efd6807b07f885d87a6b93a /runtime/src/pe_loader.cpp
parent2052b36fd73967584215a9cd99c534f1f98f8e52 (diff)
parentdde82f27e994337094afc476ded0b1426f6e87e2 (diff)
Merge origin/main into fuzz/cvt-diff
docs/shader_validation.md: keep main's division fixup section and this branch's conversions section, one after the other. 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.cpp166
1 files changed, 148 insertions, 18 deletions
diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp
index e8c504f0f..e5becb472 100644
--- a/runtime/src/pe_loader.cpp
+++ b/runtime/src/pe_loader.cpp
@@ -13,6 +13,7 @@
13#include <fstream> 13#include <fstream>
14#include <mutex> 14#include <mutex>
15#include <stdexcept> 15#include <stdexcept>
16#include <system_error>
16#include <vector> 17#include <vector>
17 18
18#include "../shims/shims.h" 19#include "../shims/shims.h"
@@ -28,9 +29,54 @@ std::string lower(std::string s) {
28 29
29namespace { 30namespace {
30 31
32std::filesystem::path::string_type module_key(const std::filesystem::path& path) {
33 // Keep identity in the platform's native path representation. Only the existing ASCII case folding is
34 // applied here; representable names also retain their old narrow-byte alias below.
35 auto key = path.filename().native();
36 for (auto& c : key)
37 if (c >= 'A' && c <= 'Z') c = static_cast<std::filesystem::path::value_type>(c + ('a' - 'A'));
38 return key;
39}
40
41std::string narrow_module_key(const std::filesystem::path& path) {
42 const auto filename = path.filename();
43 try {
44 const auto narrow = filename.string();
45 // A lossy/default-character alias must not collapse two distinct Unicode basenames.
46 if (std::filesystem::path(narrow).native() == filename.native()) return lower(narrow);
47 } catch (const std::system_error&) {
48 // Some Windows standard libraries throw when a basename is outside the current narrow code page.
49 // It still has a native identity; it simply has no alias in the existing narrow lookup API.
50 }
51 return {};
52}
53
54// Windows matches module names case-insensitively with its own upcase table (RtlEqualUnicodeString); the
55// ordinal ignore-case compare is that table.
56bool same_module_name(const wchar_t* a, const wchar_t* b) {
57 return CompareStringOrdinal(a, -1, b, -1, TRUE) == CSTR_EQUAL;
58}
59
60// A narrow (ANSI code page) module name widened for a case-insensitive compare; empty when it is not valid in the
61// code page.
62std::wstring acp_to_wide(const std::string& narrow) {
63 if (narrow.empty()) return {};
64 const int n = MultiByteToWideChar(CP_ACP, MB_ERR_INVALID_CHARS, narrow.data(), static_cast<int>(narrow.size()),
65 nullptr, 0);
66 if (n <= 0) return {};
67 std::wstring wide(static_cast<size_t>(n), L'\0');
68 MultiByteToWideChar(CP_ACP, MB_ERR_INVALID_CHARS, narrow.data(), static_cast<int>(narrow.size()), wide.data(), n);
69 return wide;
70}
71
72std::string path_utf8(const std::filesystem::path& path) {
73 const auto bytes = path.u8string();
74 return {reinterpret_cast<const char*>(bytes.data()), bytes.size()};
75}
76
31std::vector<uint8_t> read_file(const std::filesystem::path& p) { 77std::vector<uint8_t> read_file(const std::filesystem::path& p) {
32 std::ifstream f(p, std::ios::binary); 78 std::ifstream f(p, std::ios::binary);
33 if (!f) throw std::runtime_error("cannot open " + p.string()); 79 if (!f) throw std::runtime_error("cannot open " + path_utf8(p));
34 return {std::istreambuf_iterator<char>(f), {}}; 80 return {std::istreambuf_iterator<char>(f), {}};
35} 81}
36 82
@@ -870,11 +916,30 @@ bool bundled_owns_handle(void* ctx, void* module) {
870 return static_cast<Loader*>(ctx)->owns_module_handle(module); 916 return static_cast<Loader*>(ctx)->owns_module_handle(module);
871} 917}
872 918
919void* bundled_find_loaded_w(void* ctx, const std::wstring& basename) {
920 return static_cast<Loader*>(ctx)->find_loaded_module_w(basename);
921}
922
923void* bundled_load_w(void* ctx, const std::wstring& basename, uint32_t flags, bool& handled) {
924 return static_cast<Loader*>(ctx)->load_runtime_module_w(basename, flags, handled);
925}
926
873const shims::BundledModuleOps kBundledOps{ 927const shims::BundledModuleOps kBundledOps{
874 &bundled_find_loaded, 928 &bundled_find_loaded,
875 &bundled_load, 929 &bundled_load,
876 &bundled_get_proc, 930 &bundled_get_proc,
877 &bundled_owns_handle, 931 &bundled_owns_handle,
932 &bundled_find_loaded_w,
933 &bundled_load_w,
934};
935
936// Marks what a run-time load maps as a dynamic load for as long as it is in scope (the caller holds the mutex).
937struct RuntimeLoadScope {
938 explicit RuntimeLoadScope(int& depth) : depth_(depth) { ++depth_; }
939 ~RuntimeLoadScope() { --depth_; }
940 RuntimeLoadScope(const RuntimeLoadScope&) = delete;
941 RuntimeLoadScope& operator=(const RuntimeLoadScope&) = delete;
942 int& depth_;
878}; 943};
879} // namespace 944} // namespace
880 945
@@ -930,11 +995,14 @@ Loader::~Loader() {
930 995
931Module& Loader::load(const std::filesystem::path& image) { 996Module& Loader::load(const std::filesystem::path& image) {
932 std::lock_guard lock(mutex_); 997 std::lock_guard lock(mutex_);
933 std::string key = lower(image.filename().string()); 998 const auto key = module_key(image);
934 if (auto it = by_name_.find(key); it != by_name_.end()) return *it->second; 999 if (auto it = by_name_.find(key); it != by_name_.end()) return *it->second;
1000 const auto narrow_key = narrow_module_key(image);
1001 if (Module* existing = find_narrow_module(narrow_key)) return *existing;
935 Module* mapped = nullptr; 1002 Module* mapped = nullptr;
936 try { 1003 try {
937 mapped = &map_image(image); 1004 mapped = &map_image(image, narrow_key);
1005 mapped->dynamic_load = runtime_loads_ > 0; // before bind_imports: its dependencies are marked the same way
938 bind_imports(*mapped); // loads every bundled module m imports first, so they land in init_order_ before m 1006 bind_imports(*mapped); // loads every bundled module m imports first, so they land in init_order_ before m
939 protect_sections(*mapped); 1007 protect_sections(*mapped);
940 register_unwind(*mapped); 1008 register_unwind(*mapped);
@@ -954,10 +1022,41 @@ Module& Loader::load(const std::filesystem::path& image) {
954 return m; 1022 return m;
955} 1023}
956 1024
1025Module* Loader::find_narrow_module(const std::string& dll_lower) const {
1026 if (dll_lower.empty()) return nullptr;
1027 // library_loader and PE import names keep their existing narrow-byte contract: the exact compare below is
1028 // bytewise, and the key is never reinterpreted as UTF-8.
1029 for (const auto& entry : by_name_)
1030 if (entry.second->narrow_key == dll_lower) return entry.second;
1031 // The key is ASCII case-folded only. A name with letters outside ASCII (Cyrillic in code page 1251, say)
1032 // compares case-insensitively through the code page, as GetModuleHandleA does: GUEST_ДА.EXE finds guest_да.exe.
1033 // Widening the folded key is safe here: rt::lower() folds ASCII letters only, and no ANSI code page's multibyte
1034 // sequences contain ASCII letter bytes, so both sides widen to the same characters they were spelt with.
1035 if (const std::wstring wide = acp_to_wide(dll_lower); !wide.empty())
1036 for (const auto& entry : by_name_)
1037 if (!entry.second->narrow_key.empty() &&
1038 same_module_name(acp_to_wide(entry.second->narrow_key).c_str(), wide.c_str()))
1039 return entry.second;
1040 return nullptr;
1041}
1042
1043Module* Loader::find_wide_module(const std::wstring& basename) const {
1044 if (basename.empty()) return nullptr;
1045 for (const auto& entry : by_name_)
1046 if (same_module_name(entry.first.c_str(), basename.c_str())) return entry.second;
1047 return nullptr;
1048}
1049
1050void* Loader::find_loaded_module_w(const std::wstring& basename) const {
1051 std::lock_guard lock(mutex_);
1052 Module* m = find_wide_module(basename);
1053 return m ? static_cast<void*>(m->base) : nullptr;
1054}
1055
957void* Loader::find_loaded_module(const std::string& dll_lower) const { 1056void* Loader::find_loaded_module(const std::string& dll_lower) const {
958 std::lock_guard lock(mutex_); 1057 std::lock_guard lock(mutex_);
959 auto it = by_name_.find(dll_lower); 1058 Module* m = find_narrow_module(dll_lower);
960 return it == by_name_.end() ? nullptr : static_cast<void*>(it->second->base); 1059 return m ? static_cast<void*>(m->base) : nullptr;
961} 1060}
962 1061
963void* Loader::load_runtime_module(const std::string& dll_lower, uint32_t flags, bool& handled) { 1062void* Loader::load_runtime_module(const std::string& dll_lower, uint32_t flags, bool& handled) {
@@ -965,44 +1064,69 @@ void* Loader::load_runtime_module(const std::string& dll_lower, uint32_t flags,
965 if (dll_lower.empty() || prefer_host_copy(dll_lower)) return nullptr; 1064 if (dll_lower.empty() || prefer_host_copy(dll_lower)) return nullptr;
966 1065
967 std::lock_guard lock(mutex_); 1066 std::lock_guard lock(mutex_);
968 const auto existing = by_name_.find(dll_lower); 1067 const RuntimeLoadScope dynamic(runtime_loads_);
1068 Module* existing = find_narrow_module(dll_lower);
969 const std::filesystem::path candidate = game_dir_ / dll_lower; 1069 const std::filesystem::path candidate = game_dir_ / dll_lower;
970 std::error_code ec; 1070 std::error_code ec;
971 const bool is_bundled = existing != by_name_.end() || std::filesystem::is_regular_file(candidate, ec); 1071 const bool is_bundled = existing || std::filesystem::is_regular_file(candidate, ec);
972 if (!is_bundled) return nullptr; 1072 if (!is_bundled) return nullptr;
973 1073
974 handled = true; 1074 handled = true;
1075 return load_runtime_candidate(existing, candidate, flags, dll_lower);
1076}
1077
1078void* Loader::load_runtime_module_w(const std::wstring& basename, uint32_t flags, bool& handled) {
1079 handled = false;
1080 if (basename.empty()) return nullptr;
1081 // A name the code page can spell takes the narrow path's host-copy rule as well.
1082 if (const std::string narrow = narrow_module_key(std::filesystem::path(basename)); !narrow.empty())
1083 if (prefer_host_copy(narrow)) return nullptr;
1084
1085 std::lock_guard lock(mutex_);
1086 Module* existing = find_wide_module(basename);
1087 const std::filesystem::path candidate = game_dir_ / basename;
1088 std::error_code ec;
1089 if (!existing && !std::filesystem::is_regular_file(candidate, ec)) return nullptr;
1090
1091 handled = true;
1092 return load_runtime_candidate(existing, candidate, flags, path_utf8(basename));
1093}
1094
1095void* Loader::load_runtime_candidate(Module* existing, const std::filesystem::path& candidate, uint32_t flags,
1096 const std::string& display) {
975 // Win32 DONT_RESOLVE_DLL_REFERENCES (0x1) forbids resolving dependencies or running TLS/DllMain; refuse it 1097 // Win32 DONT_RESOLVE_DLL_REFERENCES (0x1) forbids resolving dependencies or running TLS/DllMain; refuse it
976 // explicitly instead of silently performing a normal resolving + initialising load. 1098 // explicitly instead of silently performing a normal resolving + initialising load.
977 if ((flags & DONT_RESOLVE_DLL_REFERENCES) != 0) { 1099 if ((flags & DONT_RESOLVE_DLL_REFERENCES) != 0) {
978 std::fprintf(stderr, 1100 std::fprintf(stderr,
979 "[rt] loader: LoadLibraryEx(%s, DONT_RESOLVE_DLL_REFERENCES) is not supported for bundled DLLs\n", 1101 "[rt] loader: LoadLibraryEx(%s, DONT_RESOLVE_DLL_REFERENCES) is not supported for bundled DLLs\n",
980 dll_lower.c_str()); 1102 display.c_str());
981 SetLastError(ERROR_NOT_SUPPORTED); 1103 SetLastError(ERROR_NOT_SUPPORTED);
982 return nullptr; 1104 return nullptr;
983 } 1105 }
984 1106
985 if (existing != by_name_.end()) { 1107 if (existing) {
986 try { 1108 try {
987 initialise(); 1109 initialise();
988 return static_cast<void*>(existing->second->base); 1110 return static_cast<void*>(existing->base);
989 } catch (const std::exception& e) { 1111 } catch (const std::exception& e) {
990 std::fprintf(stderr, "[rt] loader: run-time initialise of %s failed: %s\n", dll_lower.c_str(), e.what()); 1112 std::fprintf(stderr, "[rt] loader: run-time initialise of %s failed: %s\n", display.c_str(), e.what());
991 SetLastError(ERROR_DLL_INIT_FAILED); 1113 SetLastError(ERROR_DLL_INIT_FAILED);
992 return nullptr; 1114 return nullptr;
993 } 1115 }
994 } 1116 }
995 1117
1118 Module* mapped = nullptr;
996 try { 1119 try {
997 Module& m = load(candidate); 1120 Module& m = load(candidate);
1121 mapped = &m;
998 initialise(); 1122 initialise();
999 std::fprintf(stderr, "[rt] loader: %s mapped from game_dir (run-time load)\n", m.name.c_str()); 1123 std::fprintf(stderr, "[rt] loader: %s mapped from game_dir (run-time load)\n", m.name.c_str());
1000 return static_cast<void*>(m.base); 1124 return static_cast<void*>(m.base);
1001 } catch (const std::exception& e) { 1125 } catch (const std::exception& e) {
1002 // load() drops a module that failed to map or bind (dependencies included); this also drops one whose 1126 // load() drops a module that failed to map or bind (dependencies included); this also drops one whose
1003 // initialise() failed, so later GetModuleHandle/LoadLibrary calls don't see it. ~Loader frees it via order_. 1127 // initialise() failed, so later GetModuleHandle/LoadLibrary calls don't see it. ~Loader frees it via order_.
1004 by_name_.erase(dll_lower); 1128 by_name_.erase(module_key(mapped ? mapped->path : candidate));
1005 std::fprintf(stderr, "[rt] loader: run-time load of %s failed: %s\n", dll_lower.c_str(), e.what()); 1129 std::fprintf(stderr, "[rt] loader: run-time load of %s failed: %s\n", display.c_str(), e.what());
1006 SetLastError(ERROR_DLL_INIT_FAILED); 1130 SetLastError(ERROR_DLL_INIT_FAILED);
1007 return nullptr; 1131 return nullptr;
1008 } 1132 }
@@ -1024,6 +1148,7 @@ void* Loader::resolve_module_export(void* module_handle, const std::string& sym,
1024 if (auto it = target->exports.find(sym); it != target->exports.end()) return it->second; 1148 if (auto it = target->exports.find(sym); it != target->exports.end()) return it->second;
1025 if (auto it = target->forwarders.find(sym); it != target->forwarders.end()) { 1149 if (auto it = target->forwarders.find(sym); it != target->forwarders.end()) {
1026 try { 1150 try {
1151 const RuntimeLoadScope dynamic(runtime_loads_);
1027 Binding binding = Binding::Unimplemented; 1152 Binding binding = Binding::Unimplemented;
1028 void* fn = resolve_forwarder(it->second, binding, 0); 1153 void* fn = resolve_forwarder(it->second, binding, 0);
1029 if (binding == Binding::Module) initialise(); 1154 if (binding == Binding::Module) initialise();
@@ -1110,7 +1235,11 @@ void Loader::initialise(Module& m) {
1110 auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew); 1235 auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew);
1111 if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && m.entry_rva) { 1236 if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && m.entry_rva) {
1112 auto entry = reinterpret_cast<BOOL(NTAPI*)(void*, DWORD, void*)>(m.base + m.entry_rva); 1237 auto entry = reinterpret_cast<BOOL(NTAPI*)(void*, DWORD, void*)>(m.base + m.entry_rva);
1113 const BOOL ok = entry(m.base, DLL_PROCESS_ATTACH, nullptr); 1238 // lpvReserved "is NULL for dynamic loads and non-NULL for static loads" (DllMain docs). What Windows points
1239 // it at is its own; a static load gets a CONTEXT captured here, so a DLL that reads through it reads memory.
1240 CONTEXT context{};
1241 if (!m.dynamic_load) RtlCaptureContext(&context);
1242 const BOOL ok = entry(m.base, DLL_PROCESS_ATTACH, m.dynamic_load ? nullptr : &context);
1114 if (startup_trace::enabled()) 1243 if (startup_trace::enabled())
1115 startup_trace::event("dllmain", "\"module\":" + startup_trace::quote(m.name) + 1244 startup_trace::event("dllmain", "\"module\":" + startup_trace::quote(m.name) +
1116 ",\"result\":" + std::to_string(ok)); 1245 ",\"result\":" + std::to_string(ok));
@@ -1129,12 +1258,12 @@ void Loader::set_initialised(Module& m, bool value) {
1129 m.initialised = value; 1258 m.initialised = value;
1130} 1259}
1131 1260
1132Module& Loader::map_image(const std::filesystem::path& path) { 1261Module& Loader::map_image(const std::filesystem::path& path, const std::string& narrow_key) {
1133 auto file = read_file(path); 1262 auto file = read_file(path);
1134 const std::string name = path.filename().string(); 1263 const std::string name = path_utf8(path.filename());
1135 auto* dos = reinterpret_cast<IMAGE_DOS_HEADER*>(file.data()); 1264 auto* dos = reinterpret_cast<IMAGE_DOS_HEADER*>(file.data());
1136 if (file.size() < sizeof(IMAGE_DOS_HEADER) || dos->e_magic != IMAGE_DOS_SIGNATURE) 1265 if (file.size() < sizeof(IMAGE_DOS_HEADER) || dos->e_magic != IMAGE_DOS_SIGNATURE)
1137 throw std::runtime_error(path.string() + ": not an MZ image"); 1266 throw std::runtime_error(path_utf8(path) + ": not an MZ image");
1138 if (dos->e_lfanew < 0 || static_cast<uint64_t>(dos->e_lfanew) + sizeof(IMAGE_NT_HEADERS64) > file.size()) 1267 if (dos->e_lfanew < 0 || static_cast<uint64_t>(dos->e_lfanew) + sizeof(IMAGE_NT_HEADERS64) > file.size())
1139 throw std::runtime_error(name + ": the NT headers are outside the file"); 1268 throw std::runtime_error(name + ": the NT headers are outside the file");
1140 auto* nt = reinterpret_cast<IMAGE_NT_HEADERS64*>(file.data() + dos->e_lfanew); 1269 auto* nt = reinterpret_cast<IMAGE_NT_HEADERS64*>(file.data() + dos->e_lfanew);
@@ -1158,11 +1287,12 @@ Module& Loader::map_image(const std::filesystem::path& path) {
1158 1287
1159 auto* m = new Module; 1288 auto* m = new Module;
1160 m->name = name; 1289 m->name = name;
1290 m->narrow_key = narrow_key;
1161 m->path = path; 1291 m->path = path;
1162 m->preferred_base = oh.ImageBase; 1292 m->preferred_base = oh.ImageBase;
1163 m->size = oh.SizeOfImage; 1293 m->size = oh.SizeOfImage;
1164 m->entry_rva = oh.AddressOfEntryPoint; 1294 m->entry_rva = oh.AddressOfEntryPoint;
1165 by_name_[lower(m->name)] = m; 1295 by_name_[module_key(path)] = m;
1166 order_.push_back(m); 1296 order_.push_back(m);
1167 1297
1168 // Inside the range gta6rt reserved for this image before the process started (base_reservation.h), else as usual. 1298 // Inside the range gta6rt reserved for this image before the process started (base_reservation.h), else as usual.