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:
authorAlxcBTW <187763517+AlxcBTW@users.noreply.github.com>2026-11-22 17:51:53 +0100
committerAlxcBTW <187763517+AlxcBTW@users.noreply.github.com>2026-11-22 17:51:53 +0100
commit97daa1aec0e11d9b063b32a5da6c176d55793330 (patch)
treeb25b47984eb810fea1ae338a8cd4feec34cbe0c4 /runtime/src/pe_loader.cpp
parent0a3bf1ed91a529cb0ad093262d8b9d5250102763 (diff)
parent49475796c226c8511b9470bf97a4daf57b8af323 (diff)
Merge origin/main into presentx-planes
Keeps the swapchain_colorspace enable and main's custom border colour extension in create_vulkan_device_standalone; the present compose path follows main's LayoutPieces. 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.cpp134
1 files changed, 130 insertions, 4 deletions
diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp
index 387051756..bdb3df6f5 100644
--- a/runtime/src/pe_loader.cpp
+++ b/runtime/src/pe_loader.cpp
@@ -14,6 +14,7 @@
14#include <vector> 14#include <vector>
15 15
16#include "../shims/shims.h" 16#include "../shims/shims.h"
17#include "../shims/startup_trace.h"
17#include "base_reservation.h" 18#include "base_reservation.h"
18 19
19namespace rt { 20namespace rt {
@@ -214,7 +215,9 @@ void uninstall_thread_block(Module& m) {
214 release_thread_block(); 215 release_thread_block();
215} 216}
216 217
217void run_callbacks(Module& m, uint32_t reason) { 218// `trace`: record each callback in the startup trace. Only the Loader's own calls (process attach and detach) pass
219// true; the thread events run under the Windows loader lock and stay out of the trace.
220void run_callbacks(Module& m, uint32_t reason, bool trace = false) {
218 auto* tls = tls_directory(m); 221 auto* tls = tls_directory(m);
219 if (!tls || !tls->AddressOfCallBacks) return; 222 if (!tls || !tls->AddressOfCallBacks) return;
220 const uint64_t table_rva = rva_in(m, tls->AddressOfCallBacks, "the TLS callback table"); 223 const uint64_t table_rva = rva_in(m, tls->AddressOfCallBacks, "the TLS callback table");
@@ -226,6 +229,10 @@ void run_callbacks(Module& m, uint32_t reason) {
226 if (!fn) break; 229 if (!fn) break;
227 auto callback = 230 auto callback =
228 reinterpret_cast<PIMAGE_TLS_CALLBACK>(m.base + rva_in(m, fn, "a TLS callback")); 231 reinterpret_cast<PIMAGE_TLS_CALLBACK>(m.base + rva_in(m, fn, "a TLS callback"));
232 if (trace && startup_trace::enabled())
233 startup_trace::event("tls_callback", "\"module\":" + startup_trace::quote(m.name) + ",\"at\":" +
234 startup_trace::quote(startup_trace::where(reinterpret_cast<uint64_t>(callback))) +
235 ",\"reason\":" + std::to_string(reason));
229 callback(m.base, static_cast<DWORD>(reason), nullptr); 236 callback(m.base, static_cast<DWORD>(reason), nullptr);
230 } 237 }
231} 238}
@@ -345,10 +352,34 @@ bool lookup_in_loader(void* ctx, uint64_t address, std::string& module, uint32_t
345 } 352 }
346 return false; 353 return false;
347} 354}
355
356void* bundled_find_loaded(void* ctx, const std::string& dll_lower) {
357 return static_cast<Loader*>(ctx)->find_loaded_module(dll_lower);
358}
359
360void* bundled_load(void* ctx, const std::string& dll_lower, bool& handled) {
361 return static_cast<Loader*>(ctx)->load_runtime_module(dll_lower, handled);
362}
363
364void* bundled_get_proc(void* ctx, void* module, const std::string& sym, bool& owns_handle) {
365 return static_cast<Loader*>(ctx)->resolve_module_export(module, sym, owns_handle);
366}
367
368bool bundled_owns_handle(void* ctx, void* module) {
369 return static_cast<Loader*>(ctx)->owns_module_handle(module);
370}
371
372const shims::BundledModuleOps kBundledOps{
373 &bundled_find_loaded,
374 &bundled_load,
375 &bundled_get_proc,
376 &bundled_owns_handle,
377};
348} // namespace 378} // namespace
349 379
350Loader::Loader(std::filesystem::path game_dir) : game_dir_(std::move(game_dir)) { 380Loader::Loader(std::filesystem::path game_dir) : game_dir_(std::move(game_dir)) {
351 shims::add_module_lookup(this, &lookup_in_loader); 381 shims::add_module_lookup(this, &lookup_in_loader);
382 shims::add_bundled_loader(this, &kBundledOps);
352} 383}
353 384
354Loader::~Loader() { 385Loader::~Loader() {
@@ -372,6 +403,7 @@ Loader::~Loader() {
372 entry(m.base, DLL_PROCESS_DETACH, nullptr); // explicit unload; the return value is ignored 403 entry(m.base, DLL_PROCESS_DETACH, nullptr); // explicit unload; the return value is ignored
373 } 404 }
374 } 405 }
406 shims::remove_bundled_loader(this);
375 shims::remove_module_lookup(this); 407 shims::remove_module_lookup(this);
376 for (auto* m : order_) { 408 for (auto* m : order_) {
377 // TLS state must go away before the image and its TLS block are unmapped. 409 // TLS state must go away before the image and its TLS block are unmapped.
@@ -394,6 +426,7 @@ Loader::~Loader() {
394} 426}
395 427
396Module& Loader::load(const std::filesystem::path& image) { 428Module& Loader::load(const std::filesystem::path& image) {
429 std::lock_guard lock(mutex_);
397 std::string key = lower(image.filename().string()); 430 std::string key = lower(image.filename().string());
398 if (auto it = by_name_.find(key); it != by_name_.end()) return *it->second; 431 if (auto it = by_name_.find(key); it != by_name_.end()) return *it->second;
399 Module& m = map_image(image); 432 Module& m = map_image(image);
@@ -401,9 +434,94 @@ Module& Loader::load(const std::filesystem::path& image) {
401 protect_sections(m); 434 protect_sections(m);
402 register_unwind(m); 435 register_unwind(m);
403 init_order_.push_back(&m); 436 init_order_.push_back(&m);
437 if (startup_trace::enabled())
438 startup_trace::event("map", "\"module\":" + startup_trace::quote(m.name) +
439 ",\"base\":" + startup_trace::quote(startup_trace::hex(reinterpret_cast<uint64_t>(m.base))) +
440 ",\"size\":" + startup_trace::quote(startup_trace::hex(m.size)) +
441 ",\"relocated\":" + (m.relocated ? "true" : "false"));
404 return m; 442 return m;
405} 443}
406 444
445void* Loader::find_loaded_module(const std::string& dll_lower) const {
446 std::lock_guard lock(mutex_);
447 auto it = by_name_.find(dll_lower);
448 return it == by_name_.end() ? nullptr : static_cast<void*>(it->second->base);
449}
450
451void* Loader::load_runtime_module(const std::string& dll_lower, bool& handled) {
452 handled = false;
453 if (dll_lower.empty() || prefer_host_copy(dll_lower)) return nullptr;
454
455 std::lock_guard lock(mutex_);
456 if (auto it = by_name_.find(dll_lower); it != by_name_.end()) {
457 handled = true;
458 try {
459 initialise();
460 return static_cast<void*>(it->second->base);
461 } catch (const std::exception& e) {
462 std::fprintf(stderr, "[rt] loader: run-time initialise of %s failed: %s\n", dll_lower.c_str(), e.what());
463 SetLastError(ERROR_DLL_INIT_FAILED);
464 return nullptr;
465 }
466 }
467
468 const std::filesystem::path candidate = game_dir_ / dll_lower;
469 std::error_code ec;
470 if (!std::filesystem::is_regular_file(candidate, ec)) return nullptr;
471
472 handled = true;
473 try {
474 Module& m = load(candidate);
475 initialise();
476 std::fprintf(stderr, "[rt] loader: %s mapped from game_dir (run-time load)\n", m.name.c_str());
477 return static_cast<void*>(m.base);
478 } catch (const std::exception& e) {
479 // Do not leave a failed run-time load indexed by name so later GetModuleHandle/LoadLibrary calls do not
480 // observe a half-initialised module. ~Loader still frees any VirtualAlloc'd mapping in order_.
481 by_name_.erase(dll_lower);
482 std::fprintf(stderr, "[rt] loader: run-time load of %s failed: %s\n", dll_lower.c_str(), e.what());
483 SetLastError(ERROR_DLL_INIT_FAILED);
484 return nullptr;
485 }
486}
487
488void* Loader::resolve_module_export(void* module_handle, const std::string& sym, bool& owns_handle) {
489 owns_handle = false;
490 if (!module_handle) return nullptr;
491 std::lock_guard lock(mutex_);
492 Module* target = nullptr;
493 for (Module* m : order_) {
494 if (m->base == module_handle) {
495 target = m;
496 break;
497 }
498 }
499 if (!target) return nullptr;
500 owns_handle = true;
501 if (auto it = target->exports.find(sym); it != target->exports.end()) return it->second;
502 if (auto it = target->forwarders.find(sym); it != target->forwarders.end()) {
503 try {
504 Binding binding = Binding::Unimplemented;
505 void* fn = resolve_forwarder(it->second, binding, 0);
506 if (binding == Binding::Module) initialise();
507 return fn;
508 } catch (const std::exception& e) {
509 std::fprintf(stderr, "[rt] loader: forwarder %s from %s failed: %s\n", it->second.c_str(),
510 target->name.c_str(), e.what());
511 return nullptr;
512 }
513 }
514 return nullptr;
515}
516
517bool Loader::owns_module_handle(void* module_handle) const {
518 if (!module_handle) return false;
519 std::lock_guard lock(mutex_);
520 for (const Module* m : order_)
521 if (m->base == module_handle) return true;
522 return false;
523}
524
407// x64 has no frame-pointer chain to fall back on: without its .pdata registered, an exception raised in (or passing 525// x64 has no frame-pointer chain to fall back on: without its .pdata registered, an exception raised in (or passing
408// through) a mapped image can't be dispatched past that frame, and the process dies. Images the system loader maps 526// through) a mapped image can't be dispatched past that frame, and the process dies. Images the system loader maps
409// are found through its own module list; ours are VirtualAlloc'd, so they are registered as dynamic function tables. 527// are found through its own module list; ours are VirtualAlloc'd, so they are registered as dynamic function tables.
@@ -458,7 +576,11 @@ void Loader::initialise(Module& m) {
458 if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && m.entry_rva) { 576 if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && m.entry_rva) {
459 if (m.entry_rva >= m.size) throw std::runtime_error(m.name + ": the entry point is outside the image"); 577 if (m.entry_rva >= m.size) throw std::runtime_error(m.name + ": the entry point is outside the image");
460 auto entry = reinterpret_cast<BOOL(NTAPI*)(void*, DWORD, void*)>(m.base + m.entry_rva); 578 auto entry = reinterpret_cast<BOOL(NTAPI*)(void*, DWORD, void*)>(m.base + m.entry_rva);
461 if (!entry(m.base, DLL_PROCESS_ATTACH, nullptr)) { 579 const BOOL ok = entry(m.base, DLL_PROCESS_ATTACH, nullptr);
580 if (startup_trace::enabled())
581 startup_trace::event("dllmain", "\"module\":" + startup_trace::quote(m.name) +
582 ",\"result\":" + std::to_string(ok));
583 if (!ok) {
462 set_initialised(m, true); // it ran: a second DLL_PROCESS_ATTACH would be wrong 584 set_initialised(m, true); // it ran: a second DLL_PROCESS_ATTACH would be wrong
463 throw std::runtime_error(m.name + ": DllMain returned FALSE"); 585 throw std::runtime_error(m.name + ": DllMain returned FALSE");
464 } 586 }
@@ -645,7 +767,7 @@ void Loader::install_tls_for_thread(Module& m) { install_thread_block(m); }
645 767
646void Loader::uninstall_tls_for_thread(Module& m) { uninstall_thread_block(m); } 768void Loader::uninstall_tls_for_thread(Module& m) { uninstall_thread_block(m); }
647 769
648void Loader::run_tls_callbacks(Module& m, uint32_t reason) { run_callbacks(m, reason); } 770void Loader::run_tls_callbacks(Module& m, uint32_t reason) { run_callbacks(m, reason, /*trace=*/true); }
649 771
650void Loader::parse_exports(Module& m) { 772void Loader::parse_exports(Module& m) {
651 auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew); 773 auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew);
@@ -669,6 +791,8 @@ void Loader::parse_exports(Module& m) {
669 auto add_export = [&](const std::string& key, uint32_t rva) { 791 auto add_export = [&](const std::string& key, uint32_t rva) {
670 if (rva >= dir_begin && rva < dir_end) 792 if (rva >= dir_begin && rva < dir_end)
671 m.forwarders[key] = read_string(m.name, m.base, m.size, rva, "a forwarded export"); 793 m.forwarders[key] = read_string(m.name, m.base, m.size, rva, "a forwarded export");
794 else if (rva >= m.size) // base + rva would point past the mapping, and a caller would jump there
795 throw std::runtime_error(m.name + ": export " + key + " points outside the image");
672 else 796 else
673 m.exports[key] = m.base + rva; 797 m.exports[key] = m.base + rva;
674 }; 798 };
@@ -709,10 +833,12 @@ void* Loader::resolve_forwarder(const std::string& spec, Binding& binding, int d
709 } 833 }
710 } 834 }
711 835
836 // shim_key, not the bare module name: forwarder strings usually leave out ".dll" ("MSVCP140.?foo"), and the host
837 // CRT copies are named with it, so a forwarded CRT symbol must skip the bundled Xbox build as a direct import does.
712 const std::filesystem::path candidates[] = {game_dir_ / module, game_dir_ / (module + ".dll")}; 838 const std::filesystem::path candidates[] = {game_dir_ / module, game_dir_ / (module + ".dll")};
713 for (const auto& candidate : candidates) { 839 for (const auto& candidate : candidates) {
714 std::error_code ec; 840 std::error_code ec;
715 if (prefer_host_copy(lower(module)) || !std::filesystem::exists(candidate, ec)) continue; 841 if (prefer_host_copy(shim_key) || !std::filesystem::exists(candidate, ec)) continue;
716 Module& dep = load(candidate); 842 Module& dep = load(candidate);
717 if (auto it = dep.exports.find(symbol); it != dep.exports.end()) { 843 if (auto it = dep.exports.find(symbol); it != dep.exports.end()) {
718 binding = Binding::Module; 844 binding = Binding::Module;