From db0dc8bd5ebce6e2bc27d47085f7f104eb3037d3 Mon Sep 17 00:00:00 2001 From: NotRexed Date: Fri, 20 Nov 2026 15:22:16 -0500 Subject: 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 --- runtime/src/pe_loader.cpp | 207 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 207 insertions(+) create mode 100644 runtime/src/pe_loader.cpp (limited to 'runtime/src/pe_loader.cpp') 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 @@ +#include "pe_loader.h" + +#include + +#include +#include +#include +#include + +#include "../shims/shims.h" + +namespace rt { + +std::string lower(std::string s) { + std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return (char)std::tolower(c); }); + return s; +} + +namespace { + +std::vector read_file(const std::filesystem::path& p) { + std::ifstream f(p, std::ios::binary); + if (!f) throw std::runtime_error("cannot open " + p.string()); + return {std::istreambuf_iterator(f), {}}; +} + +template +T* at(uint8_t* base, uint32_t rva) { return reinterpret_cast(base + rva); } + +// The Xbox builds of the MSVC runtime import the same CRT the desktop does, so the host's own copies are used. +bool prefer_host_copy(const std::string& dll) { + static const char* names[] = {"vcruntime140.dll", "vcruntime140_1.dll", "msvcp140.dll", "msvcp140_1.dll", + "msvcp140_2.dll", "msvcp140_atomic_wait.dll", "msvcp140_codecvt_ids.dll", + "concrt140.dll", "vccorlib140.dll", "vcomp140.dll"}; + for (auto* n : names) + if (dll == n) return true; + return false; +} + +} // namespace + +Loader::~Loader() { + for (auto* m : order_) { + if (m->base) VirtualFree(m->base, 0, MEM_RELEASE); + delete m; + } +} + +Module& Loader::load(const std::filesystem::path& image) { + std::string key = lower(image.filename().string()); + if (auto it = by_name_.find(key); it != by_name_.end()) return *it->second; + Module& m = map_image(image); + bind_imports(m); + protect_sections(m); + return m; +} + +Module& Loader::map_image(const std::filesystem::path& path) { + auto file = read_file(path); + auto* dos = reinterpret_cast(file.data()); + if (file.size() < sizeof(IMAGE_DOS_HEADER) || dos->e_magic != IMAGE_DOS_SIGNATURE) + throw std::runtime_error(path.string() + ": not an MZ image"); + auto* nt = reinterpret_cast(file.data() + dos->e_lfanew); + if (nt->Signature != IMAGE_NT_SIGNATURE || nt->FileHeader.Machine != IMAGE_FILE_MACHINE_AMD64) + throw std::runtime_error(path.string() + ": not an x86-64 PE"); + auto& oh = nt->OptionalHeader; + + auto* m = new Module; + m->name = path.filename().string(); + m->path = path; + m->preferred_base = oh.ImageBase; + m->size = oh.SizeOfImage; + m->entry_rva = oh.AddressOfEntryPoint; + by_name_[lower(m->name)] = m; + order_.push_back(m); + + m->base = static_cast( + VirtualAlloc(reinterpret_cast(oh.ImageBase), oh.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + if (!m->base) { + auto& relocs = oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC]; + if (!relocs.Size) + throw std::runtime_error(m->name + ": preferred base is taken and the image has no relocations"); + m->base = static_cast(VirtualAlloc(nullptr, oh.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + if (!m->base) throw std::runtime_error(m->name + ": VirtualAlloc failed"); + } + + std::memcpy(m->base, file.data(), oh.SizeOfHeaders); + auto* sec = IMAGE_FIRST_SECTION(nt); + for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++sec) { + uint32_t n = std::min(sec->SizeOfRawData, sec->Misc.VirtualSize ? sec->Misc.VirtualSize : sec->SizeOfRawData); + if (n && sec->PointerToRawData + n <= file.size()) + std::memcpy(m->base + sec->VirtualAddress, file.data() + sec->PointerToRawData, n); + } + + int64_t delta = reinterpret_cast(m->base) - static_cast(oh.ImageBase); + if (delta) { + m->relocated = true; + auto& dir = oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC]; + auto* block = at(m->base, dir.VirtualAddress); + auto* end = reinterpret_cast(block) + dir.Size; + while (reinterpret_cast(block) < end && block->SizeOfBlock) { + auto* entries = reinterpret_cast(block + 1); + size_t count = (block->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) / 2; + for (size_t i = 0; i < count; ++i) { + uint16_t type = entries[i] >> 12, off = entries[i] & 0xFFF; + if (type == IMAGE_REL_BASED_DIR64) + *at(m->base, block->VirtualAddress + off) += delta; + else if (type != IMAGE_REL_BASED_ABSOLUTE) + throw std::runtime_error(m->name + ": unsupported relocation type " + std::to_string(type)); + } + block = reinterpret_cast(reinterpret_cast(block) + block->SizeOfBlock); + } + } + parse_exports(*m); + return *m; +} + +void Loader::parse_exports(Module& m) { + auto* nt = at(m.base, reinterpret_cast(m.base)->e_lfanew); + auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT]; + if (!dir.Size) return; + auto* ed = at(m.base, dir.VirtualAddress); + auto* funcs = at(m.base, ed->AddressOfFunctions); + auto* names = at(m.base, ed->AddressOfNames); + auto* ords = at(m.base, ed->AddressOfNameOrdinals); + for (uint32_t i = 0; i < ed->NumberOfFunctions; ++i) + if (funcs[i]) m.exports["#" + std::to_string(ed->Base + i)] = m.base + funcs[i]; + for (uint32_t i = 0; i < ed->NumberOfNames; ++i) + m.exports[at(m.base, names[i])] = m.base + funcs[ords[i]]; + // Forwarded exports (RVA inside the export directory) aren't followed yet; none of the bundled DLLs use them. +} + +void* Loader::resolve(Module& m, const std::string& dll, const std::string& name, uint16_t ordinal, bool by_ordinal) { + std::string key = lower(dll); + std::string sym = by_ordinal ? "#" + std::to_string(ordinal) : name; + + if (void* p = shims::find(key, sym)) { + m.imports.push_back({dll, sym, Binding::Shim}); + return p; + } + // Bundled game module (an Xbox build that ships beside the game)? + auto bundled = game_dir_ / dll; + if (!prefer_host_copy(key) && std::filesystem::exists(bundled)) { + Module& dep = load(bundled); + if (auto it = dep.exports.find(sym); it != dep.exports.end()) { + m.imports.push_back({dll, sym, Binding::Module}); + return it->second; + } + } + // Host Windows: system DLLs and API sets. LOAD_LIBRARY_SEARCH_SYSTEM32 keeps the game folder out of the search. + if (HMODULE h = LoadLibraryExA(dll.c_str(), nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32)) { + FARPROC p = GetProcAddress(h, by_ordinal ? MAKEINTRESOURCEA(ordinal) : name.c_str()); + if (p) { + m.imports.push_back({dll, sym, Binding::Host}); + return reinterpret_cast(p); + } + } + m.imports.push_back({dll, sym, Binding::Unimplemented}); + return shims::make_unimplemented_thunk(dll, sym); +} + +void Loader::bind_imports(Module& m) { + auto* nt = at(m.base, reinterpret_cast(m.base)->e_lfanew); + + auto bind_thunks = [&](const std::string& dll, IMAGE_THUNK_DATA64* lookup, IMAGE_THUNK_DATA64* iat) { + for (; lookup->u1.AddressOfData; ++lookup, ++iat) { + bool by_ord = IMAGE_SNAP_BY_ORDINAL64(lookup->u1.Ordinal); + uint16_t ord = by_ord ? (uint16_t)IMAGE_ORDINAL64(lookup->u1.Ordinal) : 0; + std::string name = by_ord ? "" : at(m.base, (uint32_t)lookup->u1.AddressOfData)->Name; + iat->u1.Function = reinterpret_cast(resolve(m, dll, name, ord, by_ord)); + } + }; + + auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]; + if (dir.Size) { + for (auto* d = at(m.base, dir.VirtualAddress); d->Name; ++d) { + std::string dll = at(m.base, d->Name); + uint32_t lookup = d->OriginalFirstThunk ? d->OriginalFirstThunk : d->FirstThunk; + bind_thunks(dll, at(m.base, lookup), at(m.base, d->FirstThunk)); + } + } + // Delay imports are bound eagerly: simpler, and the full import surface shows up in --dry-run. + auto& ddir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT]; + if (ddir.Size) { + for (auto* d = at(m.base, ddir.VirtualAddress); d->DllNameRVA; ++d) { + std::string dll = at(m.base, d->DllNameRVA); + bind_thunks(dll, at(m.base, d->ImportNameTableRVA), + at(m.base, d->ImportAddressTableRVA)); + } + } +} + +void Loader::protect_sections(Module& m) { + auto* nt = at(m.base, reinterpret_cast(m.base)->e_lfanew); + DWORD old; + VirtualProtect(m.base, nt->OptionalHeader.SizeOfHeaders, PAGE_READONLY, &old); + auto* sec = IMAGE_FIRST_SECTION(nt); + for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++sec) { + bool x = sec->Characteristics & IMAGE_SCN_MEM_EXECUTE, w = sec->Characteristics & IMAGE_SCN_MEM_WRITE; + DWORD prot = x ? (w ? PAGE_EXECUTE_READWRITE : PAGE_EXECUTE_READ) : (w ? PAGE_READWRITE : PAGE_READONLY); + SIZE_T size = sec->Misc.VirtualSize ? sec->Misc.VirtualSize : sec->SizeOfRawData; + if (size) VirtualProtect(m.base + sec->VirtualAddress, size, prot, &old); + } + FlushInstructionCache(GetCurrentProcess(), m.base, m.size); +} + +} // namespace rt -- cgit v1.2.3