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:
authorthibaut <thibaut-leaux-angeli@live.fr>2026-11-23 18:50:06 +0100
committerthibaut <thibaut-leaux-angeli@live.fr>2026-11-23 18:50:06 +0100
commit4336b7a2a0bed13d702247f29f8506efb0e7568b (patch)
treea8ac0306ca9c21fe5aeb17deaa20d69227058103 /runtime/src/pe_loader.cpp
parent4fb24d2faaa86e7287fa7da2670f54ea89e80fce (diff)
parentdde82f27e994337094afc476ded0b1426f6e87e2 (diff)
Merge remote-tracking branch 'origin/main' into slot133-host-va
Diffstat (limited to 'runtime/src/pe_loader.cpp')
-rw-r--r--runtime/src/pe_loader.cpp100
1 files changed, 94 insertions, 6 deletions
diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp
index bfeab4c7f..e5becb472 100644
--- a/runtime/src/pe_loader.cpp
+++ b/runtime/src/pe_loader.cpp
@@ -51,6 +51,24 @@ std::string narrow_module_key(const std::filesystem::path& path) {
51 return {}; 51 return {};
52} 52}
53 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
54std::string path_utf8(const std::filesystem::path& path) { 72std::string path_utf8(const std::filesystem::path& path) {
55 const auto bytes = path.u8string(); 73 const auto bytes = path.u8string();
56 return {reinterpret_cast<const char*>(bytes.data()), bytes.size()}; 74 return {reinterpret_cast<const char*>(bytes.data()), bytes.size()};
@@ -898,11 +916,30 @@ bool bundled_owns_handle(void* ctx, void* module) {
898 return static_cast<Loader*>(ctx)->owns_module_handle(module); 916 return static_cast<Loader*>(ctx)->owns_module_handle(module);
899} 917}
900 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
901const shims::BundledModuleOps kBundledOps{ 927const shims::BundledModuleOps kBundledOps{
902 &bundled_find_loaded, 928 &bundled_find_loaded,
903 &bundled_load, 929 &bundled_load,
904 &bundled_get_proc, 930 &bundled_get_proc,
905 &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_;
906}; 943};
907} // namespace 944} // namespace
908 945
@@ -965,6 +1002,7 @@ Module& Loader::load(const std::filesystem::path& image) {
965 Module* mapped = nullptr; 1002 Module* mapped = nullptr;
966 try { 1003 try {
967 mapped = &map_image(image, narrow_key); 1004 mapped = &map_image(image, narrow_key);
1005 mapped->dynamic_load = runtime_loads_ > 0; // before bind_imports: its dependencies are marked the same way
968 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
969 protect_sections(*mapped); 1007 protect_sections(*mapped);
970 register_unwind(*mapped); 1008 register_unwind(*mapped);
@@ -986,13 +1024,35 @@ Module& Loader::load(const std::filesystem::path& image) {
986 1024
987Module* Loader::find_narrow_module(const std::string& dll_lower) const { 1025Module* Loader::find_narrow_module(const std::string& dll_lower) const {
988 if (dll_lower.empty()) return nullptr; 1026 if (dll_lower.empty()) return nullptr;
989 // library_loader and PE import names keep their existing narrow-byte contract. Do not reinterpret them 1027 // library_loader and PE import names keep their existing narrow-byte contract: the exact compare below is
990 // as UTF-8 or widen already-folded bytes (which could be part of a multibyte code-page character). 1028 // bytewise, and the key is never reinterpreted as UTF-8.
991 for (const auto& entry : by_name_) 1029 for (const auto& entry : by_name_)
992 if (entry.second->narrow_key == dll_lower) return entry.second; 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;
993 return nullptr; 1047 return nullptr;
994} 1048}
995 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
996void* Loader::find_loaded_module(const std::string& dll_lower) const { 1056void* Loader::find_loaded_module(const std::string& dll_lower) const {
997 std::lock_guard lock(mutex_); 1057 std::lock_guard lock(mutex_);
998 Module* m = find_narrow_module(dll_lower); 1058 Module* m = find_narrow_module(dll_lower);
@@ -1004,6 +1064,7 @@ void* Loader::load_runtime_module(const std::string& dll_lower, uint32_t flags,
1004 if (dll_lower.empty() || prefer_host_copy(dll_lower)) return nullptr; 1064 if (dll_lower.empty() || prefer_host_copy(dll_lower)) return nullptr;
1005 1065
1006 std::lock_guard lock(mutex_); 1066 std::lock_guard lock(mutex_);
1067 const RuntimeLoadScope dynamic(runtime_loads_);
1007 Module* existing = find_narrow_module(dll_lower); 1068 Module* existing = find_narrow_module(dll_lower);
1008 const std::filesystem::path candidate = game_dir_ / dll_lower; 1069 const std::filesystem::path candidate = game_dir_ / dll_lower;
1009 std::error_code ec; 1070 std::error_code ec;
@@ -1011,12 +1072,34 @@ void* Loader::load_runtime_module(const std::string& dll_lower, uint32_t flags,
1011 if (!is_bundled) return nullptr; 1072 if (!is_bundled) return nullptr;
1012 1073
1013 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) {
1014 // 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
1015 // explicitly instead of silently performing a normal resolving + initialising load. 1098 // explicitly instead of silently performing a normal resolving + initialising load.
1016 if ((flags & DONT_RESOLVE_DLL_REFERENCES) != 0) { 1099 if ((flags & DONT_RESOLVE_DLL_REFERENCES) != 0) {
1017 std::fprintf(stderr, 1100 std::fprintf(stderr,
1018 "[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",
1019 dll_lower.c_str()); 1102 display.c_str());
1020 SetLastError(ERROR_NOT_SUPPORTED); 1103 SetLastError(ERROR_NOT_SUPPORTED);
1021 return nullptr; 1104 return nullptr;
1022 } 1105 }
@@ -1026,7 +1109,7 @@ void* Loader::load_runtime_module(const std::string& dll_lower, uint32_t flags,
1026 initialise(); 1109 initialise();
1027 return static_cast<void*>(existing->base); 1110 return static_cast<void*>(existing->base);
1028 } catch (const std::exception& e) { 1111 } catch (const std::exception& e) {
1029 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());
1030 SetLastError(ERROR_DLL_INIT_FAILED); 1113 SetLastError(ERROR_DLL_INIT_FAILED);
1031 return nullptr; 1114 return nullptr;
1032 } 1115 }
@@ -1043,7 +1126,7 @@ void* Loader::load_runtime_module(const std::string& dll_lower, uint32_t flags,
1043 // 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
1044 // 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_.
1045 by_name_.erase(module_key(mapped ? mapped->path : candidate)); 1128 by_name_.erase(module_key(mapped ? mapped->path : candidate));
1046 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());
1047 SetLastError(ERROR_DLL_INIT_FAILED); 1130 SetLastError(ERROR_DLL_INIT_FAILED);
1048 return nullptr; 1131 return nullptr;
1049 } 1132 }
@@ -1065,6 +1148,7 @@ void* Loader::resolve_module_export(void* module_handle, const std::string& sym,
1065 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;
1066 if (auto it = target->forwarders.find(sym); it != target->forwarders.end()) { 1149 if (auto it = target->forwarders.find(sym); it != target->forwarders.end()) {
1067 try { 1150 try {
1151 const RuntimeLoadScope dynamic(runtime_loads_);
1068 Binding binding = Binding::Unimplemented; 1152 Binding binding = Binding::Unimplemented;
1069 void* fn = resolve_forwarder(it->second, binding, 0); 1153 void* fn = resolve_forwarder(it->second, binding, 0);
1070 if (binding == Binding::Module) initialise(); 1154 if (binding == Binding::Module) initialise();
@@ -1151,7 +1235,11 @@ void Loader::initialise(Module& m) {
1151 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);
1152 if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && m.entry_rva) { 1236 if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && m.entry_rva) {
1153 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);
1154 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);
1155 if (startup_trace::enabled()) 1243 if (startup_trace::enabled())
1156 startup_trace::event("dllmain", "\"module\":" + startup_trace::quote(m.name) + 1244 startup_trace::event("dllmain", "\"module\":" + startup_trace::quote(m.name) +
1157 ",\"result\":" + std::to_string(ok)); 1245 ",\"result\":" + std::to_string(ok));