diff options
| author | thibaut <thibaut-leaux-angeli@live.fr> | 2026-11-23 18:50:06 +0100 |
|---|---|---|
| committer | thibaut <thibaut-leaux-angeli@live.fr> | 2026-11-23 18:50:06 +0100 |
| commit | 4336b7a2a0bed13d702247f29f8506efb0e7568b (patch) | |
| tree | a8ac0306ca9c21fe5aeb17deaa20d69227058103 /runtime/src | |
| parent | 4fb24d2faaa86e7287fa7da2670f54ea89e80fce (diff) | |
| parent | dde82f27e994337094afc476ded0b1426f6e87e2 (diff) | |
Merge remote-tracking branch 'origin/main' into slot133-host-va
Diffstat (limited to 'runtime/src')
| -rw-r--r-- | runtime/src/code_hooks.h | 76 | ||||
| -rw-r--r-- | runtime/src/pe_loader.cpp | 100 | ||||
| -rw-r--r-- | runtime/src/pe_loader.h | 12 | ||||
| -rw-r--r-- | runtime/src/shader_library.h | 29 |
4 files changed, 186 insertions, 31 deletions
diff --git a/runtime/src/code_hooks.h b/runtime/src/code_hooks.h index a079f95dd..147a84830 100644 --- a/runtime/src/code_hooks.h +++ b/runtime/src/code_hooks.h | |||
| @@ -23,6 +23,7 @@ using RemapFn = uint32_t (*)(uint32_t); | |||
| 23 | 23 | ||
| 24 | // Executable memory within +-2 GiB of `close_to`, so a rel32 branch from the image reaches it. nullptr if none is free. | 24 | // Executable memory within +-2 GiB of `close_to`, so a rel32 branch from the image reaches it. nullptr if none is free. |
| 25 | inline uint8_t* alloc_near(const void* close_to, std::size_t size) { | 25 | inline uint8_t* alloc_near(const void* close_to, std::size_t size) { |
| 26 | if (!close_to || size == 0) return nullptr; | ||
| 26 | SYSTEM_INFO si; | 27 | SYSTEM_INFO si; |
| 27 | GetSystemInfo(&si); | 28 | GetSystemInfo(&si); |
| 28 | const uintptr_t gran = si.dwAllocationGranularity; | 29 | const uintptr_t gran = si.dwAllocationGranularity; |
| @@ -30,8 +31,9 @@ inline uint8_t* alloc_near(const void* close_to, std::size_t size) { | |||
| 30 | const uintptr_t span = 0x70000000; // stay well inside the rel32 range from anywhere in a large image | 31 | const uintptr_t span = 0x70000000; // stay well inside the rel32 range from anywhere in a large image |
| 31 | for (uintptr_t delta = gran; delta < span; delta += gran) { | 32 | for (uintptr_t delta = gran; delta < span; delta += gran) { |
| 32 | for (int side = 0; side < 2; ++side) { | 33 | for (int side = 0; side < 2; ++side) { |
| 33 | const uintptr_t at = side ? center + delta : center - delta; | ||
| 34 | if (side == 0 && center < delta) continue; | 34 | if (side == 0 && center < delta) continue; |
| 35 | if (side == 1 && UINTPTR_MAX - center < delta) continue; | ||
| 36 | const uintptr_t at = side ? center + delta : center - delta; | ||
| 35 | if (void* p = VirtualAlloc(reinterpret_cast<void*>(at), size, MEM_RESERVE | MEM_COMMIT, | 37 | if (void* p = VirtualAlloc(reinterpret_cast<void*>(at), size, MEM_RESERVE | MEM_COMMIT, |
| 36 | PAGE_EXECUTE_READWRITE)) | 38 | PAGE_EXECUTE_READWRITE)) |
| 37 | return static_cast<uint8_t*>(p); | 39 | return static_cast<uint8_t*>(p); |
| @@ -44,7 +46,7 @@ inline uint8_t* alloc_near(const void* close_to, std::size_t size) { | |||
| 44 | // other argument register as the caller left it. Stack: the caller's call leaves rsp = 8 mod 16; four pushes and | 46 | // other argument register as the caller left it. Stack: the caller's call leaves rsp = 8 mod 16; four pushes and |
| 45 | // 0x68 bytes make it 16-aligned for the call to `fn`, with its 32-byte shadow space and room for xmm0-3. | 47 | // 0x68 bytes make it 16-aligned for the call to `fn`, with its 32-byte shadow space and room for xmm0-3. |
| 46 | inline uint8_t* make_remap_thunk(const void* close_to, int arg, RemapFn fn, const void* original) { | 48 | inline uint8_t* make_remap_thunk(const void* close_to, int arg, RemapFn fn, const void* original) { |
| 47 | if (arg != 0 && arg != 1) return nullptr; | 49 | if (!close_to || !fn || !original || (arg != 0 && arg != 1)) return nullptr; |
| 48 | uint8_t* t = alloc_near(close_to, 4096); | 50 | uint8_t* t = alloc_near(close_to, 4096); |
| 49 | if (!t) return nullptr; | 51 | if (!t) return nullptr; |
| 50 | uint8_t* p = t; | 52 | uint8_t* p = t; |
| @@ -69,7 +71,10 @@ inline uint8_t* make_remap_thunk(const void* close_to, int arg, RemapFn fn, cons | |||
| 69 | put({0x48, 0xB8}); put64(reinterpret_cast<uint64_t>(original)); // mov rax, original | 71 | put({0x48, 0xB8}); put64(reinterpret_cast<uint64_t>(original)); // mov rax, original |
| 70 | put({0xFF, 0xE0}); // jmp rax | 72 | put({0xFF, 0xE0}); // jmp rax |
| 71 | DWORD old = 0; | 73 | DWORD old = 0; |
| 72 | VirtualProtect(t, 4096, PAGE_EXECUTE_READ, &old); | 74 | if (!VirtualProtect(t, 4096, PAGE_EXECUTE_READ, &old)) { |
| 75 | VirtualFree(t, 0, MEM_RELEASE); | ||
| 76 | return nullptr; | ||
| 77 | } | ||
| 73 | FlushInstructionCache(GetCurrentProcess(), t, p - t); | 78 | FlushInstructionCache(GetCurrentProcess(), t, p - t); |
| 74 | return t; | 79 | return t; |
| 75 | } | 80 | } |
| @@ -81,6 +86,7 @@ using ResultFn = uint32_t (*)(uint32_t result, uint32_t arg0); | |||
| 81 | // register arguments (a stack argument would be one slot off) and an integer result. | 86 | // register arguments (a stack argument would be one slot off) and an integer result. |
| 82 | // Stack: rsp = 8 mod 16 at entry; one push and 0x20 bytes of shadow space make it 16-aligned for both calls. | 87 | // Stack: rsp = 8 mod 16 at entry; one push and 0x20 bytes of shadow space make it 16-aligned for both calls. |
| 83 | inline uint8_t* make_result_thunk(const void* close_to, ResultFn fn, const void* original) { | 88 | inline uint8_t* make_result_thunk(const void* close_to, ResultFn fn, const void* original) { |
| 89 | if (!close_to || !fn || !original) return nullptr; | ||
| 84 | uint8_t* t = alloc_near(close_to, 4096); | 90 | uint8_t* t = alloc_near(close_to, 4096); |
| 85 | if (!t) return nullptr; | 91 | if (!t) return nullptr; |
| 86 | uint8_t* p = t; | 92 | uint8_t* p = t; |
| @@ -97,7 +103,10 @@ inline uint8_t* make_result_thunk(const void* close_to, ResultFn fn, const void* | |||
| 97 | put({0x48, 0x83, 0xC4, 0x20}); // add rsp, 0x20 | 103 | put({0x48, 0x83, 0xC4, 0x20}); // add rsp, 0x20 |
| 98 | put({0x59, 0xC3}); // pop rcx ; ret | 104 | put({0x59, 0xC3}); // pop rcx ; ret |
| 99 | DWORD old = 0; | 105 | DWORD old = 0; |
| 100 | VirtualProtect(t, 4096, PAGE_EXECUTE_READ, &old); | 106 | if (!VirtualProtect(t, 4096, PAGE_EXECUTE_READ, &old)) { |
| 107 | VirtualFree(t, 0, MEM_RELEASE); | ||
| 108 | return nullptr; | ||
| 109 | } | ||
| 101 | FlushInstructionCache(GetCurrentProcess(), t, p - t); | 110 | FlushInstructionCache(GetCurrentProcess(), t, p - t); |
| 102 | return t; | 111 | return t; |
| 103 | } | 112 | } |
| @@ -106,14 +115,17 @@ inline uint8_t* make_result_thunk(const void* close_to, ResultFn fn, const void* | |||
| 106 | // Returns how many were rewritten. | 115 | // Returns how many were rewritten. |
| 107 | inline std::size_t redirect_direct_branches(uint8_t* begin, std::size_t size, const uint8_t* target, | 116 | inline std::size_t redirect_direct_branches(uint8_t* begin, std::size_t size, const uint8_t* target, |
| 108 | const uint8_t* thunk) { | 117 | const uint8_t* thunk) { |
| 118 | if (!begin || !target || !thunk || size < 5) return 0; | ||
| 109 | std::size_t n = 0; | 119 | std::size_t n = 0; |
| 110 | for (std::size_t i = 0; i + 5 <= size; ++i) { | 120 | for (std::size_t i = 0; i + 5 <= size; ++i) { |
| 111 | if (begin[i] != 0xE8 && begin[i] != 0xE9) continue; | 121 | if (begin[i] != 0xE8 && begin[i] != 0xE9) continue; |
| 112 | int32_t rel; | 122 | int32_t rel; |
| 113 | std::memcpy(&rel, begin + i + 1, 4); | 123 | std::memcpy(&rel, begin + i + 1, 4); |
| 114 | const uint8_t* next = begin + i + 5; | 124 | const uint8_t* next = begin + i + 5; |
| 115 | if (next + rel != target) continue; | 125 | const uintptr_t next_addr = reinterpret_cast<uintptr_t>(next); |
| 116 | const intptr_t to = thunk - next; | 126 | const uintptr_t dst_addr = next_addr + static_cast<uintptr_t>(static_cast<intptr_t>(rel)); |
| 127 | if (dst_addr != reinterpret_cast<uintptr_t>(target)) continue; | ||
| 128 | const intptr_t to = static_cast<intptr_t>(reinterpret_cast<uintptr_t>(thunk) - next_addr); | ||
| 117 | if (to < INT32_MIN || to > INT32_MAX) continue; | 129 | if (to < INT32_MIN || to > INT32_MAX) continue; |
| 118 | const int32_t rel2 = static_cast<int32_t>(to); | 130 | const int32_t rel2 = static_cast<int32_t>(to); |
| 119 | std::memcpy(begin + i + 1, &rel2, 4); | 131 | std::memcpy(begin + i + 1, &rel2, 4); |
| @@ -136,27 +148,55 @@ struct HookResult { | |||
| 136 | template <class MakeThunk> | 148 | template <class MakeThunk> |
| 137 | inline HookResult redirect_image_calls(uint8_t* base, uint32_t target_rva, MakeThunk make) { | 149 | inline HookResult redirect_image_calls(uint8_t* base, uint32_t target_rva, MakeThunk make) { |
| 138 | HookResult r; | 150 | HookResult r; |
| 151 | if (!base) return r.error = "not a mapped PE image", r; | ||
| 139 | const auto* dos = reinterpret_cast<const IMAGE_DOS_HEADER*>(base); | 152 | const auto* dos = reinterpret_cast<const IMAGE_DOS_HEADER*>(base); |
| 140 | if (dos->e_magic != IMAGE_DOS_SIGNATURE) return r.error = "not a mapped PE image", r; | 153 | if (dos->e_magic != IMAGE_DOS_SIGNATURE || dos->e_lfanew < static_cast<LONG>(sizeof(IMAGE_DOS_HEADER))) |
| 141 | const auto* nt = reinterpret_cast<const IMAGE_NT_HEADERS64*>(base + dos->e_lfanew); | 154 | return r.error = "not a mapped PE image", r; |
| 142 | if (nt->Signature != IMAGE_NT_SIGNATURE || target_rva >= nt->OptionalHeader.SizeOfImage) | 155 | const uint64_t lfanew = static_cast<uint64_t>(dos->e_lfanew); |
| 143 | return r.error = "the RVA is outside the image", r; | 156 | const auto* nt = reinterpret_cast<const IMAGE_NT_HEADERS64*>(base + lfanew); |
| 157 | if (nt->Signature != IMAGE_NT_SIGNATURE || | ||
| 158 | nt->FileHeader.SizeOfOptionalHeader < sizeof(IMAGE_OPTIONAL_HEADER64) || | ||
| 159 | nt->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR64_MAGIC) | ||
| 160 | return r.error = "not a mapped PE64 image", r; | ||
| 161 | const uint64_t image_size = nt->OptionalHeader.SizeOfImage; | ||
| 162 | const uint64_t sec_table_end = | ||
| 163 | lfanew + offsetof(IMAGE_NT_HEADERS64, OptionalHeader) + | ||
| 164 | static_cast<uint64_t>(nt->FileHeader.SizeOfOptionalHeader) + | ||
| 165 | static_cast<uint64_t>(nt->FileHeader.NumberOfSections) * sizeof(IMAGE_SECTION_HEADER); | ||
| 166 | if (image_size == 0 || sec_table_end > image_size) | ||
| 167 | return r.error = "not a mapped PE64 image", r; | ||
| 168 | if (target_rva >= image_size) return r.error = "the RVA is outside the image", r; | ||
| 144 | const IMAGE_SECTION_HEADER* sec = IMAGE_FIRST_SECTION(nt); | 169 | const IMAGE_SECTION_HEADER* sec = IMAGE_FIRST_SECTION(nt); |
| 170 | // Match pe_loader.cpp's effective section span (VirtualSize, falling back to SizeOfRawData when 0), clamped to SizeOfImage. | ||
| 171 | auto exec_section_span = [&](const IMAGE_SECTION_HEADER& s, uint64_t& va, uint64_t& len) -> bool { | ||
| 172 | if (!(s.Characteristics & IMAGE_SCN_MEM_EXECUTE)) return false; | ||
| 173 | va = s.VirtualAddress; | ||
| 174 | const uint64_t raw = s.Misc.VirtualSize ? static_cast<uint64_t>(s.Misc.VirtualSize) | ||
| 175 | : static_cast<uint64_t>(s.SizeOfRawData); | ||
| 176 | if (raw == 0 || va >= image_size) return false; | ||
| 177 | len = raw > image_size - va ? image_size - va : raw; | ||
| 178 | return len > 0; | ||
| 179 | }; | ||
| 145 | bool in_code = false; | 180 | bool in_code = false; |
| 146 | for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i) | 181 | for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i) { |
| 147 | if ((sec[i].Characteristics & IMAGE_SCN_MEM_EXECUTE) && target_rva >= sec[i].VirtualAddress && | 182 | uint64_t va = 0, len = 0; |
| 148 | target_rva < sec[i].VirtualAddress + sec[i].Misc.VirtualSize) | 183 | if (exec_section_span(sec[i], va, len) && target_rva >= va && target_rva < va + len) |
| 149 | in_code = true; | 184 | in_code = true; |
| 185 | } | ||
| 150 | if (!in_code) return r.error = "the RVA is not in an executable section", r; | 186 | if (!in_code) return r.error = "the RVA is not in an executable section", r; |
| 151 | uint8_t* target = base + target_rva; | 187 | uint8_t* target = base + target_rva; |
| 152 | uint8_t* thunk = make(target); | 188 | uint8_t* thunk = make(target); |
| 153 | if (!thunk) return r.error = "no memory within 2 GiB of the image for the thunk", r; | 189 | if (!thunk) return r.error = "no memory within 2 GiB of the image for the thunk", r; |
| 154 | for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i) { | 190 | for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i) { |
| 155 | if (!(sec[i].Characteristics & IMAGE_SCN_MEM_EXECUTE)) continue; | 191 | uint64_t va = 0, len = 0; |
| 156 | uint8_t* begin = base + sec[i].VirtualAddress; | 192 | if (!exec_section_span(sec[i], va, len)) continue; |
| 157 | const std::size_t size = sec[i].Misc.VirtualSize; | 193 | uint8_t* begin = base + va; |
| 194 | const std::size_t size = static_cast<std::size_t>(len); | ||
| 158 | DWORD old = 0; | 195 | DWORD old = 0; |
| 159 | if (!VirtualProtect(begin, size, PAGE_EXECUTE_READWRITE, &old)) return r.error = "VirtualProtect failed", r; | 196 | if (!VirtualProtect(begin, size, PAGE_EXECUTE_READWRITE, &old)) { |
| 197 | if (r.redirected == 0) VirtualFree(thunk, 0, MEM_RELEASE); | ||
| 198 | return r.error = "VirtualProtect failed", r; | ||
| 199 | } | ||
| 160 | r.redirected += redirect_direct_branches(begin, size, target, thunk); | 200 | r.redirected += redirect_direct_branches(begin, size, target, thunk); |
| 161 | DWORD ignored = 0; | 201 | DWORD ignored = 0; |
| 162 | VirtualProtect(begin, size, old, &ignored); | 202 | VirtualProtect(begin, size, old, &ignored); |
| @@ -168,6 +208,7 @@ inline HookResult redirect_image_calls(uint8_t* base, uint32_t target_rva, MakeT | |||
| 168 | 208 | ||
| 169 | // The argument-remapping hook (archetype lookup): argument `arg` of every direct call goes through `fn`. | 209 | // The argument-remapping hook (archetype lookup): argument `arg` of every direct call goes through `fn`. |
| 170 | inline HookResult hook_image_calls(uint8_t* base, uint32_t target_rva, RemapFn fn, int arg) { | 210 | inline HookResult hook_image_calls(uint8_t* base, uint32_t target_rva, RemapFn fn, int arg) { |
| 211 | if (!fn) return HookResult{false, 0, "hook callback is null"}; | ||
| 171 | if (arg != 0 && arg != 1) return HookResult{false, 0, "only argument 0 or 1 can be remapped"}; | 212 | if (arg != 0 && arg != 1) return HookResult{false, 0, "only argument 0 or 1 can be remapped"}; |
| 172 | return redirect_image_calls(base, target_rva, | 213 | return redirect_image_calls(base, target_rva, |
| 173 | [&](uint8_t* target) { return make_remap_thunk(target, arg, fn, target); }); | 214 | [&](uint8_t* target) { return make_remap_thunk(target, arg, fn, target); }); |
| @@ -175,6 +216,7 @@ inline HookResult hook_image_calls(uint8_t* base, uint32_t target_rva, RemapFn f | |||
| 175 | 216 | ||
| 176 | // The result-override hook (view-mode getter): every direct call's result goes through `fn` with the first argument. | 217 | // The result-override hook (view-mode getter): every direct call's result goes through `fn` with the first argument. |
| 177 | inline HookResult hook_image_results(uint8_t* base, uint32_t target_rva, ResultFn fn) { | 218 | inline HookResult hook_image_results(uint8_t* base, uint32_t target_rva, ResultFn fn) { |
| 219 | if (!fn) return HookResult{false, 0, "hook callback is null"}; | ||
| 178 | return redirect_image_calls(base, target_rva, | 220 | return redirect_image_calls(base, target_rva, |
| 179 | [&](uint8_t* target) { return make_result_thunk(target, fn, target); }); | 221 | [&](uint8_t* target) { return make_result_thunk(target, fn, target); }); |
| 180 | } | 222 | } |
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. | ||
| 56 | bool 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. | ||
| 62 | std::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 | |||
| 54 | std::string path_utf8(const std::filesystem::path& path) { | 72 | std::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 | ||
| 919 | void* bundled_find_loaded_w(void* ctx, const std::wstring& basename) { | ||
| 920 | return static_cast<Loader*>(ctx)->find_loaded_module_w(basename); | ||
| 921 | } | ||
| 922 | |||
| 923 | void* 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 | |||
| 901 | const shims::BundledModuleOps kBundledOps{ | 927 | const 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). | ||
| 937 | struct 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 | ||
| 987 | Module* Loader::find_narrow_module(const std::string& dll_lower) const { | 1025 | Module* 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 | |||
| 1043 | Module* 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 | ||
| 1050 | void* 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 | |||
| 996 | void* Loader::find_loaded_module(const std::string& dll_lower) const { | 1056 | void* 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 | |||
| 1078 | void* 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 | |||
| 1095 | void* 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)); |
diff --git a/runtime/src/pe_loader.h b/runtime/src/pe_loader.h index 812b7316f..307837351 100644 --- a/runtime/src/pe_loader.h +++ b/runtime/src/pe_loader.h | |||
| @@ -42,6 +42,10 @@ struct Module { | |||
| 42 | void* function_table = nullptr; | 42 | void* function_table = nullptr; |
| 43 | uint32_t function_count = 0; | 43 | uint32_t function_count = 0; |
| 44 | 44 | ||
| 45 | // Mapped for a run-time LoadLibrary or a GetProcAddress forwarder (a dynamic load), not by a host load() (the | ||
| 46 | // start-up graph, a static load). DllMain's DLL_PROCESS_ATTACH gets lpvReserved NULL only for a dynamic load. | ||
| 47 | bool dynamic_load = false; | ||
| 48 | |||
| 45 | std::vector<ImportRecord> imports; | 49 | std::vector<ImportRecord> imports; |
| 46 | std::map<std::string, void*> exports; // by name, plus "#ordinal" | 50 | std::map<std::string, void*> exports; // by name, plus "#ordinal" |
| 47 | std::map<std::string, std::string> forwarders; // same keys, holding "module.symbol" for re-exports | 51 | std::map<std::string, std::string> forwarders; // same keys, holding "module.symbol" for re-exports |
| @@ -117,6 +121,10 @@ public: | |||
| 117 | // Run-time module lookup/loading used by the library_loader shim for bundled package DLLs. | 121 | // Run-time module lookup/loading used by the library_loader shim for bundled package DLLs. |
| 118 | void* find_loaded_module(const std::string& dll_lower) const; | 122 | void* find_loaded_module(const std::string& dll_lower) const; |
| 119 | void* load_runtime_module(const std::string& dll_lower, uint32_t flags, bool& handled); | 123 | void* load_runtime_module(const std::string& dll_lower, uint32_t flags, bool& handled); |
| 124 | // The same by the module's native basename (any Unicode name, matched case-insensitively as Windows matches | ||
| 125 | // module names), for the W entries of LoadLibrary / GetModuleHandle. | ||
| 126 | void* find_loaded_module_w(const std::wstring& basename) const; | ||
| 127 | void* load_runtime_module_w(const std::wstring& basename, uint32_t flags, bool& handled); | ||
| 120 | void* resolve_module_export(void* module_handle, const std::string& sym, bool& owns_handle); | 128 | void* resolve_module_export(void* module_handle, const std::string& sym, bool& owns_handle); |
| 121 | bool owns_module_handle(void* module_handle) const; | 129 | bool owns_module_handle(void* module_handle) const; |
| 122 | 130 | ||
| @@ -124,6 +132,9 @@ private: | |||
| 124 | void initialise(Module& m); | 132 | void initialise(Module& m); |
| 125 | static void set_initialised(Module& m, bool value); | 133 | static void set_initialised(Module& m, bool value); |
| 126 | Module* find_narrow_module(const std::string& dll_lower) const; // caller holds mutex_ | 134 | Module* find_narrow_module(const std::string& dll_lower) const; // caller holds mutex_ |
| 135 | Module* find_wide_module(const std::wstring& basename) const; // caller holds mutex_ | ||
| 136 | void* load_runtime_candidate(Module* existing, const std::filesystem::path& candidate, uint32_t flags, | ||
| 137 | const std::string& display); // caller holds mutex_ | ||
| 127 | Module& map_image(const std::filesystem::path& path, const std::string& narrow_key); | 138 | Module& map_image(const std::filesystem::path& path, const std::string& narrow_key); |
| 128 | void initialize_tls(Module& m); | 139 | void initialize_tls(Module& m); |
| 129 | void bind_imports(Module& m); | 140 | void bind_imports(Module& m); |
| @@ -138,6 +149,7 @@ private: | |||
| 138 | std::map<std::filesystem::path::string_type, Module*> by_name_; // native basename, ASCII case folded | 149 | std::map<std::filesystem::path::string_type, Module*> by_name_; // native basename, ASCII case folded |
| 139 | std::vector<Module*> order_; // mapping order; owns the modules | 150 | std::vector<Module*> order_; // mapping order; owns the modules |
| 140 | std::vector<Module*> init_order_; // dependencies first, see initialisation_order() | 151 | std::vector<Module*> init_order_; // dependencies first, see initialisation_order() |
| 152 | int runtime_loads_ = 0; // > 0 while a run-time load or forwarder maps modules (under mutex_): they are dynamic | ||
| 141 | 153 | ||
| 142 | // What find_address reads: one entry per mapped image, added once its memory exists. Under ranges_mutex_, a leaf | 154 | // What find_address reads: one entry per mapped image, added once its memory exists. Under ranges_mutex_, a leaf |
| 143 | // lock: mutex_ is held while image code runs and the registry holds its own lock around the lookup, so the | 155 | // lock: mutex_ is held while image code runs and the registry holds its own lock around the lookup, so the |
diff --git a/runtime/src/shader_library.h b/runtime/src/shader_library.h index c4cba63af..8eb76f3c4 100644 --- a/runtime/src/shader_library.h +++ b/runtime/src/shader_library.h | |||
| @@ -722,10 +722,13 @@ struct ShaderEntry { | |||
| 722 | 722 | ||
| 723 | class ShaderLibrary { | 723 | class ShaderLibrary { |
| 724 | public: | 724 | public: |
| 725 | // Reads <dir>/index.json, then <dir>/fspx/index.json when it is there (make_game.py translates the FidelityFX | 725 | // Reads <dir>/index.json, then the indexes of the programs make_game.py translates from the package's DLLs, each |
| 726 | // DLL's FSPX programs into that folder; their entries are named "fspx/<name>"). Entries with neither | 726 | // when it is there: |
| 727 | // fssm_sha256 nor fspx_code_sha256 cannot be found by content and are skipped. The fspx folder is optional: a | 727 | // - <dir>/fspx/index.json, the FidelityFX DLL's FSPX programs, entries named "fspx/<name>" (docs/fspx.md); |
| 728 | // missing or unreadable index there leaves the main one loaded. | 728 | // - <dir>/bvh/index.json, XboxBvhBuilder.dll's FSSM programs, entries named "bvh/<name>" and found by |
| 729 | // fssm_sha256 like the game's own shaders (docs/embedded_shaders.md). | ||
| 730 | // Entries with neither fssm_sha256 nor fspx_code_sha256 cannot be found by content and are skipped. Both folders | ||
| 731 | // are optional: a missing or unreadable index there leaves the main one, and the other folder's, loaded. | ||
| 729 | bool load(const std::filesystem::path& dir, std::string* error = nullptr) { | 732 | bool load(const std::filesystem::path& dir, std::string* error = nullptr) { |
| 730 | const auto fail = [&](const std::string& why) { | 733 | const auto fail = [&](const std::string& why) { |
| 731 | if (error) *error = why; | 734 | if (error) *error = why; |
| @@ -737,10 +740,14 @@ public: | |||
| 737 | } catch (...) { | 740 | } catch (...) { |
| 738 | return fail("index.json could not be read"); | 741 | return fail("index.json could not be read"); |
| 739 | } | 742 | } |
| 740 | try { | 743 | for (const char* folder : {"fspx", "bvh"}) { |
| 741 | const auto ignore = [](const std::string&) { return false; }; | 744 | try { |
| 742 | if (std::ifstream(dir / "fspx/index.json", std::ios::binary)) load_index(dir / "fspx", "fspx/", ignore); | 745 | const auto ignore = [](const std::string&) { return false; }; |
| 743 | } catch (...) { | 746 | const std::filesystem::path sub = dir / folder; |
| 747 | if (std::ifstream(sub / "index.json", std::ios::binary)) | ||
| 748 | load_index(sub, std::string(folder) + "/", ignore); | ||
| 749 | } catch (...) { | ||
| 750 | } | ||
| 744 | } | 751 | } |
| 745 | return true; | 752 | return true; |
| 746 | } | 753 | } |
| @@ -750,6 +757,9 @@ public: | |||
| 750 | // Entries loaded from <dir>/fspx/index.json. A corpus of RPF containers never reaches these: their programs | 757 | // Entries loaded from <dir>/fspx/index.json. A corpus of RPF containers never reaches these: their programs |
| 751 | // come from FidelityFX DLLs, so callers comparing reached entries with size() must leave them out. | 758 | // come from FidelityFX DLLs, so callers comparing reached entries with size() must leave them out. |
| 752 | std::size_t fspx_size() const { return fspx_count_; } | 759 | std::size_t fspx_size() const { return fspx_count_; } |
| 760 | // Entries loaded from <dir>/bvh/index.json. No RPF container reaches these either: XboxBvhBuilder.dll passes | ||
| 761 | // their containers itself. | ||
| 762 | std::size_t bvh_size() const { return bvh_count_; } | ||
| 753 | 763 | ||
| 754 | // The first entry for this program. Two containers can hold the same FSSM program with different input | 764 | // The first entry for this program. Two containers can hold the same FSSM program with different input |
| 755 | // signatures; `candidates` returns all of them. | 765 | // signatures; `candidates` returns all of them. |
| @@ -852,6 +862,7 @@ private: | |||
| 852 | fspx_entries_.clear(); | 862 | fspx_entries_.clear(); |
| 853 | count_ = 0; | 863 | count_ = 0; |
| 854 | fspx_count_ = 0; | 864 | fspx_count_ = 0; |
| 865 | bvh_count_ = 0; | ||
| 855 | } | 866 | } |
| 856 | for (const auto& [name, meta] : root.object) { | 867 | for (const auto& [name, meta] : root.object) { |
| 857 | const Json* hash = meta.find("fssm_sha256"); | 868 | const Json* hash = meta.find("fssm_sha256"); |
| @@ -916,6 +927,7 @@ private: | |||
| 916 | if (by_fspx) fspx_entries_[{e.stage, e.fspx_code_sha256}].push_back(e); | 927 | if (by_fspx) fspx_entries_[{e.stage, e.fspx_code_sha256}].push_back(e); |
| 917 | if (by_fssm) entries_[{e.stage, e.fssm_sha256}].push_back(std::move(e)); | 928 | if (by_fssm) entries_[{e.stage, e.fssm_sha256}].push_back(std::move(e)); |
| 918 | if (by_fspx && prefix == "fspx/") ++fspx_count_; | 929 | if (by_fspx && prefix == "fspx/") ++fspx_count_; |
| 930 | if (prefix == "bvh/") ++bvh_count_; | ||
| 919 | ++count_; | 931 | ++count_; |
| 920 | } | 932 | } |
| 921 | return true; | 933 | return true; |
| @@ -924,6 +936,7 @@ private: | |||
| 924 | std::filesystem::path dir_; | 936 | std::filesystem::path dir_; |
| 925 | std::size_t count_ = 0; | 937 | std::size_t count_ = 0; |
| 926 | std::size_t fspx_count_ = 0; | 938 | std::size_t fspx_count_ = 0; |
| 939 | std::size_t bvh_count_ = 0; | ||
| 927 | // Entries by (stage, fssm_sha256) and by (stage, fspx_code_sha256), in index order. | 940 | // Entries by (stage, fssm_sha256) and by (stage, fspx_code_sha256), in index order. |
| 928 | Entries entries_; | 941 | Entries entries_; |
| 929 | Entries fspx_entries_; | 942 | Entries fspx_entries_; |