diff options
| author | NotRexed <therealnothingfn@gmail.com> | 2026-11-20 15:22:16 -0500 |
|---|---|---|
| committer | NotRexed <therealnothingfn@gmail.com> | 2026-11-20 15:22:16 -0500 |
| commit | db0dc8bd5ebce6e2bc27d47085f7f104eb3037d3 (patch) | |
| tree | 4fb3edca45f8b4dd3368c6ac2a0e4fdc8ed7065c /runtime/src/pe_loader.cpp | |
Initial commit: Leonida, build-it-yourself PC port groundwork
Shader pipeline (carve, FSSM unpack, gfx1013 disassembly, RDNA2 to SPIR-V),
asset export via rpf9-explorer's Core (submodule), PE loader and shim
skeleton, and make_game.py, which builds from the user's own copy of the game.
No game data, keys or executables are included.
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.cpp | 207 |
1 files changed, 207 insertions, 0 deletions
diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp new file mode 100644 index 000000000..f27060b94 --- /dev/null +++ b/runtime/src/pe_loader.cpp | |||
| @@ -0,0 +1,207 @@ | |||
| 1 | #include "pe_loader.h" | ||
| 2 | |||
| 3 | #include <windows.h> | ||
| 4 | |||
| 5 | #include <algorithm> | ||
| 6 | #include <cstring> | ||
| 7 | #include <fstream> | ||
| 8 | #include <stdexcept> | ||
| 9 | |||
| 10 | #include "../shims/shims.h" | ||
| 11 | |||
| 12 | namespace rt { | ||
| 13 | |||
| 14 | std::string lower(std::string s) { | ||
| 15 | std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return (char)std::tolower(c); }); | ||
| 16 | return s; | ||
| 17 | } | ||
| 18 | |||
| 19 | namespace { | ||
| 20 | |||
| 21 | std::vector<uint8_t> read_file(const std::filesystem::path& p) { | ||
| 22 | std::ifstream f(p, std::ios::binary); | ||
| 23 | if (!f) throw std::runtime_error("cannot open " + p.string()); | ||
| 24 | return {std::istreambuf_iterator<char>(f), {}}; | ||
| 25 | } | ||
| 26 | |||
| 27 | template <class T> | ||
| 28 | T* at(uint8_t* base, uint32_t rva) { return reinterpret_cast<T*>(base + rva); } | ||
| 29 | |||
| 30 | // The Xbox builds of the MSVC runtime import the same CRT the desktop does, so the host's own copies are used. | ||
| 31 | bool prefer_host_copy(const std::string& dll) { | ||
| 32 | static const char* names[] = {"vcruntime140.dll", "vcruntime140_1.dll", "msvcp140.dll", "msvcp140_1.dll", | ||
| 33 | "msvcp140_2.dll", "msvcp140_atomic_wait.dll", "msvcp140_codecvt_ids.dll", | ||
| 34 | "concrt140.dll", "vccorlib140.dll", "vcomp140.dll"}; | ||
| 35 | for (auto* n : names) | ||
| 36 | if (dll == n) return true; | ||
| 37 | return false; | ||
| 38 | } | ||
| 39 | |||
| 40 | } // namespace | ||
| 41 | |||
| 42 | Loader::~Loader() { | ||
| 43 | for (auto* m : order_) { | ||
| 44 | if (m->base) VirtualFree(m->base, 0, MEM_RELEASE); | ||
| 45 | delete m; | ||
| 46 | } | ||
| 47 | } | ||
| 48 | |||
| 49 | Module& Loader::load(const std::filesystem::path& image) { | ||
| 50 | std::string key = lower(image.filename().string()); | ||
| 51 | if (auto it = by_name_.find(key); it != by_name_.end()) return *it->second; | ||
| 52 | Module& m = map_image(image); | ||
| 53 | bind_imports(m); | ||
| 54 | protect_sections(m); | ||
| 55 | return m; | ||
| 56 | } | ||
| 57 | |||
| 58 | Module& Loader::map_image(const std::filesystem::path& path) { | ||
| 59 | auto file = read_file(path); | ||
| 60 | auto* dos = reinterpret_cast<IMAGE_DOS_HEADER*>(file.data()); | ||
| 61 | if (file.size() < sizeof(IMAGE_DOS_HEADER) || dos->e_magic != IMAGE_DOS_SIGNATURE) | ||
| 62 | throw std::runtime_error(path.string() + ": not an MZ image"); | ||
| 63 | auto* nt = reinterpret_cast<IMAGE_NT_HEADERS64*>(file.data() + dos->e_lfanew); | ||
| 64 | if (nt->Signature != IMAGE_NT_SIGNATURE || nt->FileHeader.Machine != IMAGE_FILE_MACHINE_AMD64) | ||
| 65 | throw std::runtime_error(path.string() + ": not an x86-64 PE"); | ||
| 66 | auto& oh = nt->OptionalHeader; | ||
| 67 | |||
| 68 | auto* m = new Module; | ||
| 69 | m->name = path.filename().string(); | ||
| 70 | m->path = path; | ||
| 71 | m->preferred_base = oh.ImageBase; | ||
| 72 | m->size = oh.SizeOfImage; | ||
| 73 | m->entry_rva = oh.AddressOfEntryPoint; | ||
| 74 | by_name_[lower(m->name)] = m; | ||
| 75 | order_.push_back(m); | ||
| 76 | |||
| 77 | m->base = static_cast<uint8_t*>( | ||
| 78 | VirtualAlloc(reinterpret_cast<void*>(oh.ImageBase), oh.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); | ||
| 79 | if (!m->base) { | ||
| 80 | auto& relocs = oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC]; | ||
| 81 | if (!relocs.Size) | ||
| 82 | throw std::runtime_error(m->name + ": preferred base is taken and the image has no relocations"); | ||
| 83 | m->base = static_cast<uint8_t*>(VirtualAlloc(nullptr, oh.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); | ||
| 84 | if (!m->base) throw std::runtime_error(m->name + ": VirtualAlloc failed"); | ||
| 85 | } | ||
| 86 | |||
| 87 | std::memcpy(m->base, file.data(), oh.SizeOfHeaders); | ||
| 88 | auto* sec = IMAGE_FIRST_SECTION(nt); | ||
| 89 | for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++sec) { | ||
| 90 | uint32_t n = std::min(sec->SizeOfRawData, sec->Misc.VirtualSize ? sec->Misc.VirtualSize : sec->SizeOfRawData); | ||
| 91 | if (n && sec->PointerToRawData + n <= file.size()) | ||
| 92 | std::memcpy(m->base + sec->VirtualAddress, file.data() + sec->PointerToRawData, n); | ||
| 93 | } | ||
| 94 | |||
| 95 | int64_t delta = reinterpret_cast<int64_t>(m->base) - static_cast<int64_t>(oh.ImageBase); | ||
| 96 | if (delta) { | ||
| 97 | m->relocated = true; | ||
| 98 | auto& dir = oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC]; | ||
| 99 | auto* block = at<IMAGE_BASE_RELOCATION>(m->base, dir.VirtualAddress); | ||
| 100 | auto* end = reinterpret_cast<uint8_t*>(block) + dir.Size; | ||
| 101 | while (reinterpret_cast<uint8_t*>(block) < end && block->SizeOfBlock) { | ||
| 102 | auto* entries = reinterpret_cast<uint16_t*>(block + 1); | ||
| 103 | size_t count = (block->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) / 2; | ||
| 104 | for (size_t i = 0; i < count; ++i) { | ||
| 105 | uint16_t type = entries[i] >> 12, off = entries[i] & 0xFFF; | ||
| 106 | if (type == IMAGE_REL_BASED_DIR64) | ||
| 107 | *at<uint64_t>(m->base, block->VirtualAddress + off) += delta; | ||
| 108 | else if (type != IMAGE_REL_BASED_ABSOLUTE) | ||
| 109 | throw std::runtime_error(m->name + ": unsupported relocation type " + std::to_string(type)); | ||
| 110 | } | ||
| 111 | block = reinterpret_cast<IMAGE_BASE_RELOCATION*>(reinterpret_cast<uint8_t*>(block) + block->SizeOfBlock); | ||
| 112 | } | ||
| 113 | } | ||
| 114 | parse_exports(*m); | ||
| 115 | return *m; | ||
| 116 | } | ||
| 117 | |||
| 118 | void Loader::parse_exports(Module& m) { | ||
| 119 | auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew); | ||
| 120 | auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT]; | ||
| 121 | if (!dir.Size) return; | ||
| 122 | auto* ed = at<IMAGE_EXPORT_DIRECTORY>(m.base, dir.VirtualAddress); | ||
| 123 | auto* funcs = at<uint32_t>(m.base, ed->AddressOfFunctions); | ||
| 124 | auto* names = at<uint32_t>(m.base, ed->AddressOfNames); | ||
| 125 | auto* ords = at<uint16_t>(m.base, ed->AddressOfNameOrdinals); | ||
| 126 | for (uint32_t i = 0; i < ed->NumberOfFunctions; ++i) | ||
| 127 | if (funcs[i]) m.exports["#" + std::to_string(ed->Base + i)] = m.base + funcs[i]; | ||
| 128 | for (uint32_t i = 0; i < ed->NumberOfNames; ++i) | ||
| 129 | m.exports[at<char>(m.base, names[i])] = m.base + funcs[ords[i]]; | ||
| 130 | // Forwarded exports (RVA inside the export directory) aren't followed yet; none of the bundled DLLs use them. | ||
| 131 | } | ||
| 132 | |||
| 133 | void* Loader::resolve(Module& m, const std::string& dll, const std::string& name, uint16_t ordinal, bool by_ordinal) { | ||
| 134 | std::string key = lower(dll); | ||
| 135 | std::string sym = by_ordinal ? "#" + std::to_string(ordinal) : name; | ||
| 136 | |||
| 137 | if (void* p = shims::find(key, sym)) { | ||
| 138 | m.imports.push_back({dll, sym, Binding::Shim}); | ||
| 139 | return p; | ||
| 140 | } | ||
| 141 | // Bundled game module (an Xbox build that ships beside the game)? | ||
| 142 | auto bundled = game_dir_ / dll; | ||
| 143 | if (!prefer_host_copy(key) && std::filesystem::exists(bundled)) { | ||
| 144 | Module& dep = load(bundled); | ||
| 145 | if (auto it = dep.exports.find(sym); it != dep.exports.end()) { | ||
| 146 | m.imports.push_back({dll, sym, Binding::Module}); | ||
| 147 | return it->second; | ||
| 148 | } | ||
| 149 | } | ||
| 150 | // Host Windows: system DLLs and API sets. LOAD_LIBRARY_SEARCH_SYSTEM32 keeps the game folder out of the search. | ||
| 151 | if (HMODULE h = LoadLibraryExA(dll.c_str(), nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32)) { | ||
| 152 | FARPROC p = GetProcAddress(h, by_ordinal ? MAKEINTRESOURCEA(ordinal) : name.c_str()); | ||
| 153 | if (p) { | ||
| 154 | m.imports.push_back({dll, sym, Binding::Host}); | ||
| 155 | return reinterpret_cast<void*>(p); | ||
| 156 | } | ||
| 157 | } | ||
| 158 | m.imports.push_back({dll, sym, Binding::Unimplemented}); | ||
| 159 | return shims::make_unimplemented_thunk(dll, sym); | ||
| 160 | } | ||
| 161 | |||
| 162 | void Loader::bind_imports(Module& m) { | ||
| 163 | auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew); | ||
| 164 | |||
| 165 | auto bind_thunks = [&](const std::string& dll, IMAGE_THUNK_DATA64* lookup, IMAGE_THUNK_DATA64* iat) { | ||
| 166 | for (; lookup->u1.AddressOfData; ++lookup, ++iat) { | ||
| 167 | bool by_ord = IMAGE_SNAP_BY_ORDINAL64(lookup->u1.Ordinal); | ||
| 168 | uint16_t ord = by_ord ? (uint16_t)IMAGE_ORDINAL64(lookup->u1.Ordinal) : 0; | ||
| 169 | std::string name = by_ord ? "" : at<IMAGE_IMPORT_BY_NAME>(m.base, (uint32_t)lookup->u1.AddressOfData)->Name; | ||
| 170 | iat->u1.Function = reinterpret_cast<uint64_t>(resolve(m, dll, name, ord, by_ord)); | ||
| 171 | } | ||
| 172 | }; | ||
| 173 | |||
| 174 | auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]; | ||
| 175 | if (dir.Size) { | ||
| 176 | for (auto* d = at<IMAGE_IMPORT_DESCRIPTOR>(m.base, dir.VirtualAddress); d->Name; ++d) { | ||
| 177 | std::string dll = at<char>(m.base, d->Name); | ||
| 178 | uint32_t lookup = d->OriginalFirstThunk ? d->OriginalFirstThunk : d->FirstThunk; | ||
| 179 | bind_thunks(dll, at<IMAGE_THUNK_DATA64>(m.base, lookup), at<IMAGE_THUNK_DATA64>(m.base, d->FirstThunk)); | ||
| 180 | } | ||
| 181 | } | ||
| 182 | // Delay imports are bound eagerly: simpler, and the full import surface shows up in --dry-run. | ||
| 183 | auto& ddir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT]; | ||
| 184 | if (ddir.Size) { | ||
| 185 | for (auto* d = at<IMAGE_DELAYLOAD_DESCRIPTOR>(m.base, ddir.VirtualAddress); d->DllNameRVA; ++d) { | ||
| 186 | std::string dll = at<char>(m.base, d->DllNameRVA); | ||
| 187 | bind_thunks(dll, at<IMAGE_THUNK_DATA64>(m.base, d->ImportNameTableRVA), | ||
| 188 | at<IMAGE_THUNK_DATA64>(m.base, d->ImportAddressTableRVA)); | ||
| 189 | } | ||
| 190 | } | ||
| 191 | } | ||
| 192 | |||
| 193 | void Loader::protect_sections(Module& m) { | ||
| 194 | auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew); | ||
| 195 | DWORD old; | ||
| 196 | VirtualProtect(m.base, nt->OptionalHeader.SizeOfHeaders, PAGE_READONLY, &old); | ||
| 197 | auto* sec = IMAGE_FIRST_SECTION(nt); | ||
| 198 | for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++sec) { | ||
| 199 | bool x = sec->Characteristics & IMAGE_SCN_MEM_EXECUTE, w = sec->Characteristics & IMAGE_SCN_MEM_WRITE; | ||
| 200 | DWORD prot = x ? (w ? PAGE_EXECUTE_READWRITE : PAGE_EXECUTE_READ) : (w ? PAGE_READWRITE : PAGE_READONLY); | ||
| 201 | SIZE_T size = sec->Misc.VirtualSize ? sec->Misc.VirtualSize : sec->SizeOfRawData; | ||
| 202 | if (size) VirtualProtect(m.base + sec->VirtualAddress, size, prot, &old); | ||
| 203 | } | ||
| 204 | FlushInstructionCache(GetCurrentProcess(), m.base, m.size); | ||
| 205 | } | ||
| 206 | |||
| 207 | } // namespace rt | ||