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:
authorjaybeebabageyus <jaybeebabageyus@users.noreply.github.com>2026-11-22 20:57:07 +0100
committerjaybeebabageyus <jaybeebabageyus@users.noreply.github.com>2026-11-22 20:57:07 +0100
commit50e9dd32fa8d9ebb6ba22e559ca62fa95920b88d (patch)
treed5b82116e556cfc96f96b7e575b91a049dd42fb9 /runtime/src/pe_loader.cpp
parent1188e6406e31870119a7e50c5972599db554a406 (diff)
parent162821017ea3c286c8bec860f3ff94f037912061 (diff)
Merge remote-tracking branch 'upstream/main' into 2070-lifecycle-fix
# Conflicts: # runtime/src/pe_loader.cpp # runtime/src/pe_loader.h # runtime/test/loader_tls_test.cpp
Diffstat (limited to 'runtime/src/pe_loader.cpp')
-rw-r--r--runtime/src/pe_loader.cpp145
1 files changed, 141 insertions, 4 deletions
diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp
index ec87ab7ee..663b1174c 100644
--- a/runtime/src/pe_loader.cpp
+++ b/runtime/src/pe_loader.cpp
@@ -15,6 +15,7 @@
15#include <vector> 15#include <vector>
16 16
17#include "../shims/shims.h" 17#include "../shims/shims.h"
18#include "../shims/startup_trace.h"
18#include "base_reservation.h" 19#include "base_reservation.h"
19 20
20namespace rt { 21namespace rt {
@@ -383,7 +384,9 @@ void uninstall_thread_block(Module& m) {
383 release_thread_slot(slot); 384 release_thread_slot(slot);
384} 385}
385 386
386void run_callbacks(Module& m, uint32_t reason) { 387// `trace`: record each callback in the startup trace. Only the Loader's own calls (process attach and detach) pass
388// true; the thread events run under the Windows loader lock and stay out of the trace.
389void run_callbacks(Module& m, uint32_t reason, bool trace = false) {
387 auto* tls = tls_directory(m); 390 auto* tls = tls_directory(m);
388 if (!tls || !tls->AddressOfCallBacks) return; 391 if (!tls || !tls->AddressOfCallBacks) return;
389 const uint64_t table_rva = rva_in(m, tls->AddressOfCallBacks, "the TLS callback table"); 392 const uint64_t table_rva = rva_in(m, tls->AddressOfCallBacks, "the TLS callback table");
@@ -395,6 +398,10 @@ void run_callbacks(Module& m, uint32_t reason) {
395 if (!fn) break; 398 if (!fn) break;
396 auto callback = 399 auto callback =
397 reinterpret_cast<PIMAGE_TLS_CALLBACK>(m.base + rva_in(m, fn, "a TLS callback")); 400 reinterpret_cast<PIMAGE_TLS_CALLBACK>(m.base + rva_in(m, fn, "a TLS callback"));
401 if (trace && startup_trace::enabled())
402 startup_trace::event("tls_callback", "\"module\":" + startup_trace::quote(m.name) + ",\"at\":" +
403 startup_trace::quote(startup_trace::where(reinterpret_cast<uint64_t>(callback))) +
404 ",\"reason\":" + std::to_string(reason));
398 callback(m.base, static_cast<DWORD>(reason), nullptr); 405 callback(m.base, static_cast<DWORD>(reason), nullptr);
399 } 406 }
400} 407}
@@ -531,10 +538,34 @@ bool lookup_in_loader(void* ctx, uint64_t address, std::string& module, uint32_t
531 } 538 }
532 return false; 539 return false;
533} 540}
541
542void* bundled_find_loaded(void* ctx, const std::string& dll_lower) {
543 return static_cast<Loader*>(ctx)->find_loaded_module(dll_lower);
544}
545
546void* bundled_load(void* ctx, const std::string& dll_lower, uint32_t flags, bool& handled) {
547 return static_cast<Loader*>(ctx)->load_runtime_module(dll_lower, flags, handled);
548}
549
550void* bundled_get_proc(void* ctx, void* module, const std::string& sym, bool& owns_handle) {
551 return static_cast<Loader*>(ctx)->resolve_module_export(module, sym, owns_handle);
552}
553
554bool bundled_owns_handle(void* ctx, void* module) {
555 return static_cast<Loader*>(ctx)->owns_module_handle(module);
556}
557
558const shims::BundledModuleOps kBundledOps{
559 &bundled_find_loaded,
560 &bundled_load,
561 &bundled_get_proc,
562 &bundled_owns_handle,
563};
534} // namespace 564} // namespace
535 565
536Loader::Loader(std::filesystem::path game_dir) : game_dir_(std::move(game_dir)) { 566Loader::Loader(std::filesystem::path game_dir) : game_dir_(std::move(game_dir)) {
537 shims::add_module_lookup(this, &lookup_in_loader); 567 shims::add_module_lookup(this, &lookup_in_loader);
568 shims::add_bundled_loader(this, &kBundledOps);
538} 569}
539 570
540Loader::~Loader() { 571Loader::~Loader() {
@@ -558,6 +589,7 @@ Loader::~Loader() {
558 entry(m.base, DLL_PROCESS_DETACH, nullptr); // explicit unload; the return value is ignored 589 entry(m.base, DLL_PROCESS_DETACH, nullptr); // explicit unload; the return value is ignored
559 } 590 }
560 } 591 }
592 shims::remove_bundled_loader(this);
561 shims::remove_module_lookup(this); 593 shims::remove_module_lookup(this);
562 for (auto* m : order_) { 594 for (auto* m : order_) {
563 // TLS state must go away before the image and its TLS block are unmapped. 595 // TLS state must go away before the image and its TLS block are unmapped.
@@ -581,6 +613,7 @@ Loader::~Loader() {
581} 613}
582 614
583Module& Loader::load(const std::filesystem::path& image) { 615Module& Loader::load(const std::filesystem::path& image) {
616 std::lock_guard lock(mutex_);
584 std::string key = lower(image.filename().string()); 617 std::string key = lower(image.filename().string());
585 if (auto it = by_name_.find(key); it != by_name_.end()) return *it->second; 618 if (auto it = by_name_.find(key); it != by_name_.end()) return *it->second;
586 Module& m = map_image(image); 619 Module& m = map_image(image);
@@ -588,9 +621,105 @@ Module& Loader::load(const std::filesystem::path& image) {
588 protect_sections(m); 621 protect_sections(m);
589 register_unwind(m); 622 register_unwind(m);
590 init_order_.push_back(&m); 623 init_order_.push_back(&m);
624 if (startup_trace::enabled())
625 startup_trace::event("map", "\"module\":" + startup_trace::quote(m.name) +
626 ",\"base\":" + startup_trace::quote(startup_trace::hex(reinterpret_cast<uint64_t>(m.base))) +
627 ",\"size\":" + startup_trace::quote(startup_trace::hex(m.size)) +
628 ",\"relocated\":" + (m.relocated ? "true" : "false"));
591 return m; 629 return m;
592} 630}
593 631
632void* Loader::find_loaded_module(const std::string& dll_lower) const {
633 std::lock_guard lock(mutex_);
634 auto it = by_name_.find(dll_lower);
635 return it == by_name_.end() ? nullptr : static_cast<void*>(it->second->base);
636}
637
638void* Loader::load_runtime_module(const std::string& dll_lower, uint32_t flags, bool& handled) {
639 handled = false;
640 if (dll_lower.empty() || prefer_host_copy(dll_lower)) return nullptr;
641
642 std::lock_guard lock(mutex_);
643 const auto existing = by_name_.find(dll_lower);
644 const std::filesystem::path candidate = game_dir_ / dll_lower;
645 std::error_code ec;
646 const bool is_bundled = existing != by_name_.end() || std::filesystem::is_regular_file(candidate, ec);
647 if (!is_bundled) return nullptr;
648
649 handled = true;
650 // Win32 DONT_RESOLVE_DLL_REFERENCES (0x1) forbids resolving dependencies or running TLS/DllMain; refuse it
651 // explicitly instead of silently performing a normal resolving + initialising load.
652 if ((flags & DONT_RESOLVE_DLL_REFERENCES) != 0) {
653 std::fprintf(stderr,
654 "[rt] loader: LoadLibraryEx(%s, DONT_RESOLVE_DLL_REFERENCES) is not supported for bundled DLLs\n",
655 dll_lower.c_str());
656 SetLastError(ERROR_NOT_SUPPORTED);
657 return nullptr;
658 }
659
660 if (existing != by_name_.end()) {
661 try {
662 initialise();
663 return static_cast<void*>(existing->second->base);
664 } catch (const std::exception& e) {
665 std::fprintf(stderr, "[rt] loader: run-time initialise of %s failed: %s\n", dll_lower.c_str(), e.what());
666 SetLastError(ERROR_DLL_INIT_FAILED);
667 return nullptr;
668 }
669 }
670
671 try {
672 Module& m = load(candidate);
673 initialise();
674 std::fprintf(stderr, "[rt] loader: %s mapped from game_dir (run-time load)\n", m.name.c_str());
675 return static_cast<void*>(m.base);
676 } catch (const std::exception& e) {
677 // Do not leave a failed run-time load indexed by name so later GetModuleHandle/LoadLibrary calls do not
678 // observe a half-initialised module. ~Loader still frees any VirtualAlloc'd mapping in order_.
679 by_name_.erase(dll_lower);
680 std::fprintf(stderr, "[rt] loader: run-time load of %s failed: %s\n", dll_lower.c_str(), e.what());
681 SetLastError(ERROR_DLL_INIT_FAILED);
682 return nullptr;
683 }
684}
685
686void* Loader::resolve_module_export(void* module_handle, const std::string& sym, bool& owns_handle) {
687 owns_handle = false;
688 if (!module_handle) return nullptr;
689 std::lock_guard lock(mutex_);
690 Module* target = nullptr;
691 for (Module* m : order_) {
692 if (m->base == module_handle) {
693 target = m;
694 break;
695 }
696 }
697 if (!target) return nullptr;
698 owns_handle = true;
699 if (auto it = target->exports.find(sym); it != target->exports.end()) return it->second;
700 if (auto it = target->forwarders.find(sym); it != target->forwarders.end()) {
701 try {
702 Binding binding = Binding::Unimplemented;
703 void* fn = resolve_forwarder(it->second, binding, 0);
704 if (binding == Binding::Module) initialise();
705 return fn;
706 } catch (const std::exception& e) {
707 std::fprintf(stderr, "[rt] loader: forwarder %s from %s failed: %s\n", it->second.c_str(),
708 target->name.c_str(), e.what());
709 return nullptr;
710 }
711 }
712 return nullptr;
713}
714
715bool Loader::owns_module_handle(void* module_handle) const {
716 if (!module_handle) return false;
717 std::lock_guard lock(mutex_);
718 for (const Module* m : order_)
719 if (m->base == module_handle) return true;
720 return false;
721}
722
594// x64 has no frame-pointer chain to fall back on: without its .pdata registered, an exception raised in (or passing 723// x64 has no frame-pointer chain to fall back on: without its .pdata registered, an exception raised in (or passing
595// through) a mapped image can't be dispatched past that frame, and the process dies. Images the system loader maps 724// through) a mapped image can't be dispatched past that frame, and the process dies. Images the system loader maps
596// are found through its own module list; ours are VirtualAlloc'd, so they are registered as dynamic function tables. 725// are found through its own module list; ours are VirtualAlloc'd, so they are registered as dynamic function tables.
@@ -645,7 +774,11 @@ void Loader::initialise(Module& m) {
645 if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && m.entry_rva) { 774 if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && m.entry_rva) {
646 if (m.entry_rva >= m.size) throw std::runtime_error(m.name + ": the entry point is outside the image"); 775 if (m.entry_rva >= m.size) throw std::runtime_error(m.name + ": the entry point is outside the image");
647 auto entry = reinterpret_cast<BOOL(NTAPI*)(void*, DWORD, void*)>(m.base + m.entry_rva); 776 auto entry = reinterpret_cast<BOOL(NTAPI*)(void*, DWORD, void*)>(m.base + m.entry_rva);
648 if (!entry(m.base, DLL_PROCESS_ATTACH, nullptr)) { 777 const BOOL ok = entry(m.base, DLL_PROCESS_ATTACH, nullptr);
778 if (startup_trace::enabled())
779 startup_trace::event("dllmain", "\"module\":" + startup_trace::quote(m.name) +
780 ",\"result\":" + std::to_string(ok));
781 if (!ok) {
649 set_initialised(m, true); // it ran: a second DLL_PROCESS_ATTACH would be wrong 782 set_initialised(m, true); // it ran: a second DLL_PROCESS_ATTACH would be wrong
650 throw std::runtime_error(m.name + ": DllMain returned FALSE"); 783 throw std::runtime_error(m.name + ": DllMain returned FALSE");
651 } 784 }
@@ -855,7 +988,7 @@ void Loader::install_tls_for_thread(Module& m) { install_thread_block(m); }
855 988
856void Loader::uninstall_tls_for_thread(Module& m) { uninstall_thread_block(m); } 989void Loader::uninstall_tls_for_thread(Module& m) { uninstall_thread_block(m); }
857 990
858void Loader::run_tls_callbacks(Module& m, uint32_t reason) { run_callbacks(m, reason); } 991void Loader::run_tls_callbacks(Module& m, uint32_t reason) { run_callbacks(m, reason, /*trace=*/true); }
859 992
860void Loader::parse_exports(Module& m) { 993void Loader::parse_exports(Module& m) {
861 auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew); 994 auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew);
@@ -879,6 +1012,8 @@ void Loader::parse_exports(Module& m) {
879 auto add_export = [&](const std::string& key, uint32_t rva) { 1012 auto add_export = [&](const std::string& key, uint32_t rva) {
880 if (rva >= dir_begin && rva < dir_end) 1013 if (rva >= dir_begin && rva < dir_end)
881 m.forwarders[key] = read_string(m.name, m.base, m.size, rva, "a forwarded export"); 1014 m.forwarders[key] = read_string(m.name, m.base, m.size, rva, "a forwarded export");
1015 else if (rva >= m.size) // base + rva would point past the mapping, and a caller would jump there
1016 throw std::runtime_error(m.name + ": export " + key + " points outside the image");
882 else 1017 else
883 m.exports[key] = m.base + rva; 1018 m.exports[key] = m.base + rva;
884 }; 1019 };
@@ -919,10 +1054,12 @@ void* Loader::resolve_forwarder(const std::string& spec, Binding& binding, int d
919 } 1054 }
920 } 1055 }
921 1056
1057 // shim_key, not the bare module name: forwarder strings usually leave out ".dll" ("MSVCP140.?foo"), and the host
1058 // CRT copies are named with it, so a forwarded CRT symbol must skip the bundled Xbox build as a direct import does.
922 const std::filesystem::path candidates[] = {game_dir_ / module, game_dir_ / (module + ".dll")}; 1059 const std::filesystem::path candidates[] = {game_dir_ / module, game_dir_ / (module + ".dll")};
923 for (const auto& candidate : candidates) { 1060 for (const auto& candidate : candidates) {
924 std::error_code ec; 1061 std::error_code ec;
925 if (prefer_host_copy(lower(module)) || !std::filesystem::exists(candidate, ec)) continue; 1062 if (prefer_host_copy(shim_key) || !std::filesystem::exists(candidate, ec)) continue;
926 Module& dep = load(candidate); 1063 Module& dep = load(candidate);
927 if (auto it = dep.exports.find(symbol); it != dep.exports.end()) { 1064 if (auto it = dep.exports.find(symbol); it != dep.exports.end()) {
928 binding = Binding::Module; 1065 binding = Binding::Module;