upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/runtime
diff options
context:
space:
mode:
authorItsNotRexed <300290919+ItsNotRexed@users.noreply.github.com>2026-11-22 10:40:29 -0500
committerItsNotRexed <300290919+ItsNotRexed@users.noreply.github.com>2026-11-22 10:40:29 -0500
commit81c6cfe4fd44096e4c2bc52685cdc021eb829e5c (patch)
treed720ceeff53b2858d978e96825d0c5dee5900f4c /runtime
parent92fa203c165ebb20e83bc4ad740ff52968f710d4 (diff)
parent47f4cdc643f3fca3f87a34d9a4718f250d7cd905 (diff)
Merge pull request #2021 from jaybeebabageyus
Diffstat (limited to 'runtime')
-rw-r--r--runtime/CMakeLists.txt30
-rw-r--r--runtime/shims/library_loader.cpp104
-rw-r--r--runtime/shims/registry.cpp79
-rw-r--r--runtime/shims/shims.h16
-rw-r--r--runtime/src/pe_loader.cpp106
-rw-r--r--runtime/src/pe_loader.h8
-rw-r--r--runtime/test/check_loaded_bundled.cmake14
-rw-r--r--runtime/test/fixtures/tiny_bundled_dll.cpp39
-rw-r--r--runtime/test/fixtures/tiny_bundled_dll.def5
-rw-r--r--runtime/test/fixtures/tiny_bundled_load.cpp83
-rw-r--r--runtime/test/fixtures/xmem_stub.cpp9
-rw-r--r--runtime/test/fixtures/xmem_stub.def3
12 files changed, 476 insertions, 20 deletions
diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt
index e36c87489..d9dad1919 100644
--- a/runtime/CMakeLists.txt
+++ b/runtime/CMakeLists.txt
@@ -387,6 +387,33 @@ if(BUILD_TESTING)
387 set_target_properties(tiny_gdk_load PROPERTIES 387 set_target_properties(tiny_gdk_load PROPERTIES
388 RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$<CONFIG>" 388 RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$<CONFIG>"
389 ) 389 )
390 # Run-time LoadLibrary of a bundled Xbox DLL (importing xmem.dll) through rt::Loader.
391 add_library(xmem_stub SHARED test/fixtures/xmem_stub.cpp test/fixtures/xmem_stub.def)
392 target_compile_definitions(xmem_stub PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
393 target_compile_options(xmem_stub PRIVATE /W4 /permissive- /utf-8)
394 set_target_properties(xmem_stub PROPERTIES
395 OUTPUT_NAME xmem
396 PREFIX ""
397 RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/stubs/$<CONFIG>"
398 ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/stubs/$<CONFIG>"
399 )
400 add_library(tiny_bundled_dll SHARED test/fixtures/tiny_bundled_dll.cpp test/fixtures/tiny_bundled_dll.def)
401 target_link_libraries(tiny_bundled_dll PRIVATE xmem_stub)
402 target_compile_definitions(tiny_bundled_dll PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
403 target_compile_options(tiny_bundled_dll PRIVATE /W4 /permissive- /utf-8)
404 set_target_properties(tiny_bundled_dll PROPERTIES
405 OUTPUT_NAME tiny_bundled_dll
406 PREFIX ""
407 RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$<CONFIG>"
408 ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/stubs/$<CONFIG>"
409 )
410 add_executable(tiny_bundled_load test/fixtures/tiny_bundled_load.cpp)
411 target_compile_definitions(tiny_bundled_load PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
412 target_compile_options(tiny_bundled_load PRIVATE /W4 /permissive- /utf-8)
413 add_dependencies(tiny_bundled_load tiny_bundled_dll)
414 set_target_properties(tiny_bundled_load PROPERTIES
415 RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$<CONFIG>"
416 )
390 add_executable(tiny_game test/fixtures/tiny_game.cpp) 417 add_executable(tiny_game test/fixtures/tiny_game.cpp)
391 target_link_libraries(tiny_game PRIVATE xgameruntime_stub) 418 target_link_libraries(tiny_game PRIVATE xgameruntime_stub)
392 target_compile_definitions(tiny_game PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX _CRT_SECURE_NO_WARNINGS) # plain fopen, as games use 419 target_compile_definitions(tiny_game PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX _CRT_SECURE_NO_WARNINGS) # plain fopen, as games use
@@ -621,6 +648,9 @@ if(BUILD_TESTING)
621 add_test(NAME run_tiny_gdk_load COMMAND ${CMAKE_COMMAND} 648 add_test(NAME run_tiny_gdk_load COMMAND ${CMAKE_COMMAND}
622 "-DLOADER=$<TARGET_FILE:gta6rt>" "-DGUEST=$<TARGET_FILE:tiny_gdk_load>" 649 "-DLOADER=$<TARGET_FILE:gta6rt>" "-DGUEST=$<TARGET_FILE:tiny_gdk_load>"
623 "-DRUNNER=${CMAKE_CROSSCOMPILING_EMULATOR}" -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_loaded_gdk.cmake") 650 "-DRUNNER=${CMAKE_CROSSCOMPILING_EMULATOR}" -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_loaded_gdk.cmake")
651 add_test(NAME run_tiny_bundled_load COMMAND ${CMAKE_COMMAND}
652 "-DLOADER=$<TARGET_FILE:gta6rt>" "-DGUEST=$<TARGET_FILE:tiny_bundled_load>"
653 "-DRUNNER=${CMAKE_CROSSCOMPILING_EMULATOR}" -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_loaded_bundled.cmake")
624 add_test(NAME run_tiny_game COMMAND gta6rt --run $<TARGET_FILE:tiny_game> -- hello 42) 654 add_test(NAME run_tiny_game COMMAND gta6rt --run $<TARGET_FILE:tiny_game> -- hello 42)
625 add_test(NAME run_tiny_game_exit_code COMMAND tiny_game_exit_code_test 655 add_test(NAME run_tiny_game_exit_code COMMAND tiny_game_exit_code_test
626 "$<TARGET_FILE:gta6rt>" "$<TARGET_FILE:tiny_game>") 656 "$<TARGET_FILE:gta6rt>" "$<TARGET_FILE:tiny_game>")
diff --git a/runtime/shims/library_loader.cpp b/runtime/shims/library_loader.cpp
index 585c6a299..b67a38660 100644
--- a/runtime/shims/library_loader.cpp
+++ b/runtime/shims/library_loader.cpp
@@ -92,60 +92,124 @@ const Pseudo* pseudo(HMODULE h) {
92 92
93namespace { 93namespace {
94 94
95constexpr DWORD kDataFileLoadFlags =
96 LOAD_LIBRARY_AS_DATAFILE | LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE | LOAD_LIBRARY_AS_IMAGE_RESOURCE;
97
98HMODULE load_shim_or_bundled(const std::string& path, bool& handled) {
99 handled = false;
100 if (HMODULE h = owned_handle(path)) {
101 handled = true;
102 return h;
103 }
104 const std::string dll = module_name(path);
105 if (!dll.empty()) {
106 if (void* h = load_bundled_module(dll, handled); handled) return reinterpret_cast<HMODULE>(h);
107 }
108 return nullptr;
109}
110
95HMODULE WINAPI load_library_a(LPCSTR name) { 111HMODULE WINAPI load_library_a(LPCSTR name) {
96 if (HMODULE h = name ? owned_handle(name) : nullptr) return h; 112 if (name) {
113 bool handled = false;
114 HMODULE h = load_shim_or_bundled(name, handled);
115 if (handled) return h;
116 }
97 return LoadLibraryA(name); 117 return LoadLibraryA(name);
98} 118}
99 119
100HMODULE WINAPI load_library_w(LPCWSTR name) { 120HMODULE WINAPI load_library_w(LPCWSTR name) {
101 if (HMODULE h = name ? owned_handle(narrow(name)) : nullptr) return h; 121 if (name) {
122 bool handled = false;
123 HMODULE h = load_shim_or_bundled(narrow(name), handled);
124 if (handled) return h;
125 }
102 return LoadLibraryW(name); 126 return LoadLibraryW(name);
103} 127}
104 128
105HMODULE WINAPI load_library_ex_a(LPCSTR name, HANDLE file, DWORD flags) { 129HMODULE WINAPI load_library_ex_a(LPCSTR name, HANDLE file, DWORD flags) {
106 if (HMODULE h = name ? owned_handle(name) : nullptr) return h; 130 if (name && (flags & kDataFileLoadFlags) == 0) {
131 bool handled = false;
132 HMODULE h = load_shim_or_bundled(name, handled);
133 if (handled) return h;
134 }
107 return LoadLibraryExA(name, file, flags); 135 return LoadLibraryExA(name, file, flags);
108} 136}
109 137
110HMODULE WINAPI load_library_ex_w(LPCWSTR name, HANDLE file, DWORD flags) { 138HMODULE WINAPI load_library_ex_w(LPCWSTR name, HANDLE file, DWORD flags) {
111 if (HMODULE h = name ? owned_handle(narrow(name)) : nullptr) return h; 139 if (name && (flags & kDataFileLoadFlags) == 0) {
140 bool handled = false;
141 HMODULE h = load_shim_or_bundled(narrow(name), handled);
142 if (handled) return h;
143 }
112 return LoadLibraryExW(name, file, flags); 144 return LoadLibraryExW(name, file, flags);
113} 145}
114 146
115// GetModuleHandle answers for an owned module as if it were loaded: the GDK may probe before it loads. 147// GetModuleHandle answers for an owned module as if it were loaded (the GDK may probe before it loads), and for any
148// bundled package module already mapped by the native loader.
116HMODULE WINAPI get_module_handle_a(LPCSTR name) { 149HMODULE WINAPI get_module_handle_a(LPCSTR name) {
117 if (HMODULE h = name ? owned_handle(name) : nullptr) return h; 150 if (name) {
151 if (HMODULE h = owned_handle(name)) return h;
152 const std::string dll = module_name(name);
153 if (!dll.empty())
154 if (void* h = find_loaded_bundled_module(dll)) return reinterpret_cast<HMODULE>(h);
155 }
118 return GetModuleHandleA(name); 156 return GetModuleHandleA(name);
119} 157}
120 158
121HMODULE WINAPI get_module_handle_w(LPCWSTR name) { 159HMODULE WINAPI get_module_handle_w(LPCWSTR name) {
122 if (HMODULE h = name ? owned_handle(narrow(name)) : nullptr) return h; 160 if (name) {
161 const std::string path = narrow(name);
162 if (HMODULE h = owned_handle(path)) return h;
163 const std::string dll = module_name(path);
164 if (!dll.empty())
165 if (void* h = find_loaded_bundled_module(dll)) return reinterpret_cast<HMODULE>(h);
166 }
123 return GetModuleHandleW(name); 167 return GetModuleHandleW(name);
124} 168}
125 169
126FARPROC WINAPI get_proc_address(HMODULE module, LPCSTR name) { 170FARPROC WINAPI get_proc_address(HMODULE module, LPCSTR name) {
127 const Pseudo* p = pseudo(module); 171 if (const Pseudo* p = pseudo(module)) {
128 if (!p) return GetProcAddress(module, name); 172 if (!name) {
129 if (!name) { 173 SetLastError(ERROR_PROC_NOT_FOUND);
174 return nullptr;
175 }
176 // A value below 0x10000 is an ordinal (IS_INTRESOURCE), as in the real GetProcAddress.
177 const std::string what =
178 IS_INTRESOURCE(name) ? "#" + std::to_string(reinterpret_cast<uintptr_t>(name)) : name;
179 if (void* fn = find(p->dll, what)) return reinterpret_cast<FARPROC>(fn);
180 {
181 static auto* m = new std::mutex;
182 static auto* seen = new std::set<std::string>;
183 std::lock_guard lock(*m);
184 if (seen->insert(p->dll + "!" + what).second)
185 std::fprintf(stderr, "[rt] loader: GetProcAddress(%s, %s): not served\n", p->dll.c_str(), what.c_str());
186 }
130 SetLastError(ERROR_PROC_NOT_FOUND); 187 SetLastError(ERROR_PROC_NOT_FOUND);
131 return nullptr; 188 return nullptr;
132 } 189 }
133 // A value below 0x10000 is an ordinal (IS_INTRESOURCE), as in the real GetProcAddress. 190
191 if (!name) {
192 if (owns_bundled_module_handle(module)) {
193 SetLastError(ERROR_PROC_NOT_FOUND);
194 return nullptr;
195 }
196 return GetProcAddress(module, name);
197 }
198
134 const std::string what = IS_INTRESOURCE(name) ? "#" + std::to_string(reinterpret_cast<uintptr_t>(name)) : name; 199 const std::string what = IS_INTRESOURCE(name) ? "#" + std::to_string(reinterpret_cast<uintptr_t>(name)) : name;
135 if (void* fn = find(p->dll, what)) return reinterpret_cast<FARPROC>(fn); 200 bool owns_handle = false;
136 { 201 void* fn = get_bundled_proc_address(module, what, owns_handle);
137 static auto* m = new std::mutex; 202 if (owns_handle) {
138 static auto* seen = new std::set<std::string>; 203 if (fn) return reinterpret_cast<FARPROC>(fn);
139 std::lock_guard lock(*m); 204 SetLastError(ERROR_PROC_NOT_FOUND);
140 if (seen->insert(p->dll + "!" + what).second) 205 return nullptr;
141 std::fprintf(stderr, "[rt] loader: GetProcAddress(%s, %s): not served\n", p->dll.c_str(), what.c_str());
142 } 206 }
143 SetLastError(ERROR_PROC_NOT_FOUND); 207 return GetProcAddress(module, name);
144 return nullptr;
145} 208}
146 209
147BOOL WINAPI free_library(HMODULE module) { 210BOOL WINAPI free_library(HMODULE module) {
148 if (pseudo(module)) return TRUE; // owned modules are never unloaded 211 if (pseudo(module)) return TRUE; // owned modules are never unloaded
212 if (owns_bundled_module_handle(module)) return TRUE; // mapped modules stay live until ~Loader detaches them
149 return FreeLibrary(module); 213 return FreeLibrary(module);
150} 214}
151 215
diff --git a/runtime/shims/registry.cpp b/runtime/shims/registry.cpp
index bf6df91a0..52c168484 100644
--- a/runtime/shims/registry.cpp
+++ b/runtime/shims/registry.cpp
@@ -375,6 +375,85 @@ void remove_module_lookup(void* ctx) {
375 } 375 }
376} 376}
377 377
378namespace {
379
380struct BundledLoaderEntry {
381 void* ctx;
382 const BundledModuleOps* ops;
383};
384
385// Immortal: late mapped-DLL detach or atexit handlers may call GetProcAddress/FreeLibrary during process teardown.
386std::mutex& bundled_loader_mutex() {
387 static auto* m = new std::mutex;
388 return *m;
389}
390
391std::vector<BundledLoaderEntry>& bundled_loaders() {
392 static auto* v = new std::vector<BundledLoaderEntry>;
393 return *v;
394}
395
396std::vector<BundledLoaderEntry> snapshot_bundled_loaders() {
397 std::lock_guard lock(bundled_loader_mutex());
398 return bundled_loaders();
399}
400
401} // namespace
402
403void add_bundled_loader(void* ctx, const BundledModuleOps* ops) {
404 if (!ctx || !ops) return;
405 std::lock_guard lock(bundled_loader_mutex());
406 bundled_loaders().push_back({ctx, ops});
407}
408
409void remove_bundled_loader(void* ctx) {
410 std::lock_guard lock(bundled_loader_mutex());
411 auto& list = bundled_loaders();
412 for (auto it = list.begin(); it != list.end(); ++it)
413 if (it->ctx == ctx) {
414 list.erase(it);
415 break;
416 }
417}
418
419void* find_loaded_bundled_module(const std::string& dll_lower) {
420 for (const auto& entry : snapshot_bundled_loaders())
421 if (void* h = entry.ops->find_loaded(entry.ctx, dll_lower)) return h;
422 return nullptr;
423}
424
425void* load_bundled_module(const std::string& dll_lower, bool& handled) {
426 handled = false;
427 for (const auto& entry : snapshot_bundled_loaders()) {
428 bool loader_handled = false;
429 void* h = entry.ops->load_bundled(entry.ctx, dll_lower, loader_handled);
430 if (loader_handled) {
431 handled = true;
432 return h;
433 }
434 }
435 return nullptr;
436}
437
438void* get_bundled_proc_address(void* module, const std::string& sym, bool& owns_handle) {
439 owns_handle = false;
440 for (const auto& entry : snapshot_bundled_loaders()) {
441 bool loader_owns = false;
442 void* fn = entry.ops->get_proc(entry.ctx, module, sym, loader_owns);
443 if (loader_owns) {
444 owns_handle = true;
445 return fn;
446 }
447 }
448 return nullptr;
449}
450
451bool owns_bundled_module_handle(void* module) {
452 for (const auto& entry : snapshot_bundled_loaders())
453 if (entry.ops->owns_handle(entry.ctx, module)) return true;
454 return false;
455}
456
378Table::Table(const Entry* entries, size_t count) { 457Table::Table(const Entry* entries, size_t count) {
379 for (size_t i = 0; i < count; ++i) table()[lower_ascii(entries[i].dll) + "!" + entries[i].name] = entries[i].fn; 458 for (size_t i = 0; i < count; ++i) table()[lower_ascii(entries[i].dll) + "!" + entries[i].name] = entries[i].fn;
380} 459}
diff --git a/runtime/shims/shims.h b/runtime/shims/shims.h
index 2d9021a15..80feee3fa 100644
--- a/runtime/shims/shims.h
+++ b/runtime/shims/shims.h
@@ -58,6 +58,22 @@ void remove_module_lookup(void* ctx);
58// The base of the mapped module holding `address`, through the same lookups. False if no live Loader maps it. 58// The base of the mapped module holding `address`, through the same lookups. False if no live Loader maps it.
59bool mapped_image_base(uint64_t address, uint64_t& base); 59bool mapped_image_base(uint64_t address, uint64_t& base);
60 60
61// Run-time LoadLibrary / GetModuleHandle / GetProcAddress / FreeLibrary for bundled package DLLs managed by a live
62// Loader. Registered in Loader::Loader and removed in Loader::~Loader.
63struct BundledModuleOps {
64 void* (*find_loaded)(void* ctx, const std::string& dll_lower);
65 void* (*load_bundled)(void* ctx, const std::string& dll_lower, bool& handled);
66 void* (*get_proc)(void* ctx, void* module, const std::string& sym, bool& owns_handle);
67 bool (*owns_handle)(void* ctx, void* module);
68};
69void add_bundled_loader(void* ctx, const BundledModuleOps* ops);
70void remove_bundled_loader(void* ctx);
71
72void* find_loaded_bundled_module(const std::string& dll_lower);
73void* load_bundled_module(const std::string& dll_lower, bool& handled);
74void* get_bundled_proc_address(void* module, const std::string& sym, bool& owns_handle);
75bool owns_bundled_module_handle(void* module);
76
61// Test seam: called at the top of every unimplemented-import call with the address of rt_unimplemented's return 77// Test seam: called at the top of every unimplemented-import call with the address of rt_unimplemented's return
62// address slot (so a test can check stack alignment) and from inside the call (so it can walk the stack). 78// address slot (so a test can check stack alignment) and from inside the call (so it can walk the stack).
63using TestHook = void (*)(const void* return_address_slot); 79using TestHook = void (*)(const void* return_address_slot);
diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp
index edbc3cbec..bdb3df6f5 100644
--- a/runtime/src/pe_loader.cpp
+++ b/runtime/src/pe_loader.cpp
@@ -352,10 +352,34 @@ bool lookup_in_loader(void* ctx, uint64_t address, std::string& module, uint32_t
352 } 352 }
353 return false; 353 return false;
354} 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};
355} // namespace 378} // namespace
356 379
357Loader::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)) {
358 shims::add_module_lookup(this, &lookup_in_loader); 381 shims::add_module_lookup(this, &lookup_in_loader);
382 shims::add_bundled_loader(this, &kBundledOps);
359} 383}
360 384
361Loader::~Loader() { 385Loader::~Loader() {
@@ -379,6 +403,7 @@ Loader::~Loader() {
379 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
380 } 404 }
381 } 405 }
406 shims::remove_bundled_loader(this);
382 shims::remove_module_lookup(this); 407 shims::remove_module_lookup(this);
383 for (auto* m : order_) { 408 for (auto* m : order_) {
384 // 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.
@@ -401,6 +426,7 @@ Loader::~Loader() {
401} 426}
402 427
403Module& Loader::load(const std::filesystem::path& image) { 428Module& Loader::load(const std::filesystem::path& image) {
429 std::lock_guard lock(mutex_);
404 std::string key = lower(image.filename().string()); 430 std::string key = lower(image.filename().string());
405 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;
406 Module& m = map_image(image); 432 Module& m = map_image(image);
@@ -416,6 +442,86 @@ Module& Loader::load(const std::filesystem::path& image) {
416 return m; 442 return m;
417} 443}
418 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
419// 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
420// 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
421// 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.
diff --git a/runtime/src/pe_loader.h b/runtime/src/pe_loader.h
index 1303cdff9..d9f89f542 100644
--- a/runtime/src/pe_loader.h
+++ b/runtime/src/pe_loader.h
@@ -8,6 +8,7 @@
8#include <cstdint> 8#include <cstdint>
9#include <filesystem> 9#include <filesystem>
10#include <map> 10#include <map>
11#include <mutex>
11#include <string> 12#include <string>
12#include <vector> 13#include <vector>
13 14
@@ -103,6 +104,12 @@ public:
103 void install_tls_for_thread(Module& m); 104 void install_tls_for_thread(Module& m);
104 void uninstall_tls_for_thread(Module& m); 105 void uninstall_tls_for_thread(Module& m);
105 106
107 // Run-time module lookup/loading used by the library_loader shim for bundled package DLLs.
108 void* find_loaded_module(const std::string& dll_lower) const;
109 void* load_runtime_module(const std::string& dll_lower, bool& handled);
110 void* resolve_module_export(void* module_handle, const std::string& sym, bool& owns_handle);
111 bool owns_module_handle(void* module_handle) const;
112
106private: 113private:
107 void initialise(Module& m); 114 void initialise(Module& m);
108 static void set_initialised(Module& m, bool value); 115 static void set_initialised(Module& m, bool value);
@@ -115,6 +122,7 @@ private:
115 void protect_sections(Module& m); 122 void protect_sections(Module& m);
116 void register_unwind(Module& m); 123 void register_unwind(Module& m);
117 124
125 mutable std::recursive_mutex mutex_;
118 std::filesystem::path game_dir_; 126 std::filesystem::path game_dir_;
119 std::map<std::string, Module*> by_name_; // lower-case file name 127 std::map<std::string, Module*> by_name_; // lower-case file name
120 std::vector<Module*> order_; // mapping order; owns the modules 128 std::vector<Module*> order_; // mapping order; owns the modules
diff --git a/runtime/test/check_loaded_bundled.cmake b/runtime/test/check_loaded_bundled.cmake
new file mode 100644
index 000000000..397e59c2f
--- /dev/null
+++ b/runtime/test/check_loaded_bundled.cmake
@@ -0,0 +1,14 @@
1# Run the run-time bundled-DLL load fixture (tiny_bundled_load) under the loader and check its verdict from outside,
2# as check_loaded_gdk.cmake does.
3get_filename_component(guest_dir "${GUEST}" DIRECTORY)
4get_filename_component(guest_name "${GUEST}" NAME)
5execute_process(
6 COMMAND ${RUNNER} "${LOADER}" --run "${guest_name}"
7 WORKING_DIRECTORY "${guest_dir}"
8 TIMEOUT 90
9 RESULT_VARIABLE code OUTPUT_VARIABLE output ERROR_VARIABLE output)
10string(REPLACE "\r\n" "\n" output "${output}")
11if(NOT code STREQUAL "0" OR NOT output MATCHES "(^|\n)tiny_bundled_load: PASS(\n|$)"
12 OR NOT output MATCHES "(^|\n)game exited with code 0(\n|$)")
13 message(FATAL_ERROR "Loaded bundled-DLL run-time fixture returned ${code}\n${output}")
14endif()
diff --git a/runtime/test/fixtures/tiny_bundled_dll.cpp b/runtime/test/fixtures/tiny_bundled_dll.cpp
new file mode 100644
index 000000000..ef0fbe63b
--- /dev/null
+++ b/runtime/test/fixtures/tiny_bundled_dll.cpp
@@ -0,0 +1,39 @@
1// A stand-in bundled Xbox DLL (like Bink2Scarlett.dll or amd_fidelityfx_upscaler_xbox.dll) that imports console
2// memory functions from xmem.dll and is loaded at run time through LoadLibraryW by tiny_bundled_load.exe.
3// Test code, not game content.
4#include <windows.h>
5
6#include <cstddef>
7#include <cstdint>
8
9extern "C" {
10__declspec(dllimport) void* __stdcall XMemAlloc(size_t size, uint64_t attributes);
11__declspec(dllimport) void __stdcall XMemFree(void* ptr, uint64_t attributes);
12}
13
14namespace {
15int g_attach_count = 0;
16}
17
18BOOL WINAPI DllMain(HINSTANCE, DWORD reason, LPVOID) {
19 if (reason == DLL_PROCESS_ATTACH) ++g_attach_count;
20 return TRUE;
21}
22
23extern "C" __declspec(dllexport) int __stdcall bundled_attach_count() { return g_attach_count; }
24
25extern "C" __declspec(dllexport) uint32_t __stdcall bundled_alloc_sum() {
26 auto* buf = static_cast<uint32_t*>(XMemAlloc(16 * sizeof(uint32_t), 0x5e50000));
27 if (!buf) return 0;
28 if ((reinterpret_cast<uintptr_t>(buf) & 63u) != 0) {
29 XMemFree(buf, 0x5e50000);
30 return 0;
31 }
32 uint32_t sum = 0;
33 for (uint32_t i = 0; i < 16; ++i) {
34 buf[i] = i + 1;
35 sum += buf[i];
36 }
37 XMemFree(buf, 0x5e50000);
38 return sum;
39}
diff --git a/runtime/test/fixtures/tiny_bundled_dll.def b/runtime/test/fixtures/tiny_bundled_dll.def
new file mode 100644
index 000000000..9771777bb
--- /dev/null
+++ b/runtime/test/fixtures/tiny_bundled_dll.def
@@ -0,0 +1,5 @@
1EXPORTS
2 bundled_attach_count @1
3 bundled_alloc_sum @2
4 bundled_fwd_alloc=xmem.XMemAlloc @3
5 bundled_fwd_free=xmem.XMemFree @4
diff --git a/runtime/test/fixtures/tiny_bundled_load.cpp b/runtime/test/fixtures/tiny_bundled_load.cpp
new file mode 100644
index 000000000..51fbaac72
--- /dev/null
+++ b/runtime/test/fixtures/tiny_bundled_load.cpp
@@ -0,0 +1,83 @@
1// A mapped program that loads a bundled Xbox DLL (tiny_bundled_dll.dll, which imports xmem.dll) at run time via
2// LoadLibraryW, GetModuleHandle, GetProcAddress and FreeLibrary — the pattern used by titles that dynamically load
3// Bink2Scarlett.dll, XboxBvhBuilder.dll or the FidelityFX DLLs. Under `gta6rt --run`, library_loader.cpp routes the
4// load to rt::Loader so the DLL's xmem.dll imports bind to the shim registry instead of failing under the host loader.
5// Ordinary test code; no game data.
6#include <windows.h>
7
8#include <cstddef>
9#include <cstdint>
10#include <cstdio>
11
12namespace {
13
14using AttachCountFn = int(__stdcall*)();
15using AllocSumFn = uint32_t(__stdcall*)();
16using XMemAllocFn = void*(__stdcall*)(size_t, uint64_t);
17using XMemFreeFn = void(__stdcall*)(void*, uint64_t);
18
19int fail(const char* stage, unsigned long value) {
20 std::printf("tiny_bundled_load: FAIL %s (0x%08lx)\n", stage, value);
21 return 1;
22}
23
24} // namespace
25
26int main() {
27 if (GetModuleHandleW(L"tiny_bundled_dll.dll") != nullptr)
28 return fail("GetModuleHandleW before LoadLibrary should be NULL", 0);
29
30 HMODULE mod = LoadLibraryW(L"tiny_bundled_dll.dll");
31 if (!mod) return fail("LoadLibraryW(tiny_bundled_dll.dll)", GetLastError());
32
33 // Must be mapped by rt::Loader, not by the host Windows loader.
34 HMODULE host_view = nullptr;
35 if (GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, L"tiny_bundled_dll.dll", &host_view) &&
36 host_view == mod) {
37 return fail("tiny_bundled_dll.dll came from the host loader, not rt::Loader", 0);
38 }
39
40 if (GetModuleHandleW(L"tiny_bundled_dll.dll") != mod)
41 return fail("GetModuleHandleW after LoadLibrary returns the same handle", 0);
42 if (GetModuleHandleA("TINY_BUNDLED_DLL") != mod)
43 return fail("GetModuleHandleA case-insensitive without .dll returns the same handle", 0);
44 if (LoadLibraryExA("C:\\Fake\\Path\\tiny_bundled_dll.dll", nullptr, 0) != mod)
45 return fail("LoadLibraryExA with full path returns the same already-mapped handle", GetLastError());
46
47 auto attach_count = reinterpret_cast<AttachCountFn>(GetProcAddress(mod, "bundled_attach_count"));
48 if (!attach_count) return fail("GetProcAddress(bundled_attach_count)", GetLastError());
49 const int count = attach_count();
50 if (count != 1) return fail("DllMain(DLL_PROCESS_ATTACH) ran once", static_cast<unsigned long>(count));
51
52 auto alloc_sum = reinterpret_cast<AllocSumFn>(GetProcAddress(mod, "bundled_alloc_sum"));
53 if (!alloc_sum) return fail("GetProcAddress(bundled_alloc_sum)", GetLastError());
54 if (reinterpret_cast<void*>(GetProcAddress(mod, MAKEINTRESOURCEA(2))) != reinterpret_cast<void*>(alloc_sum))
55 return fail("GetProcAddress by ordinal #2 matches bundled_alloc_sum", GetLastError());
56 const uint32_t sum = alloc_sum();
57 if (sum != 136u) return fail("bundled_alloc_sum via xmem shim returned 136", sum);
58
59 auto fwd_alloc = reinterpret_cast<XMemAllocFn>(GetProcAddress(mod, "bundled_fwd_alloc"));
60 auto fwd_free = reinterpret_cast<XMemFreeFn>(GetProcAddress(mod, "bundled_fwd_free"));
61 if (!fwd_alloc || !fwd_free) return fail("GetProcAddress follows forwarders to xmem shim", GetLastError());
62 void* block = fwd_alloc(128, 0);
63 if (!block || (reinterpret_cast<uintptr_t>(block) & 63u) != 0)
64 return fail("forwarded xmem.XMemAlloc returned aligned block", 0);
65 fwd_free(block, 0);
66
67 SetLastError(0);
68 if (GetProcAddress(mod, "NoSuchExport") != nullptr || GetLastError() != ERROR_PROC_NOT_FOUND)
69 return fail("missing export returns NULL with ERROR_PROC_NOT_FOUND", GetLastError());
70 SetLastError(0);
71 if (GetProcAddress(mod, nullptr) != nullptr || GetLastError() != ERROR_PROC_NOT_FOUND)
72 return fail("null export name returns NULL with ERROR_PROC_NOT_FOUND", GetLastError());
73
74 if (!FreeLibrary(mod)) return fail("FreeLibrary(tiny_bundled_dll.dll)", GetLastError());
75
76 // Host modules still resolve through the host loader.
77 HMODULE k32 = LoadLibraryW(L"kernel32.dll");
78 if (!k32 || GetProcAddress(k32, "GetTickCount") != GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "GetTickCount"))
79 return fail("kernel32.dll still comes from the host", GetLastError());
80
81 std::puts("tiny_bundled_load: PASS");
82 return 0;
83}
diff --git a/runtime/test/fixtures/xmem_stub.cpp b/runtime/test/fixtures/xmem_stub.cpp
new file mode 100644
index 000000000..75754408e
--- /dev/null
+++ b/runtime/test/fixtures/xmem_stub.cpp
@@ -0,0 +1,9 @@
1// Link-time stand-in for the console's xmem.dll, so tiny_bundled_dll.dll gets real imports of XMemAlloc and
2// XMemFree (the same imports Bink2Scarlett.dll and amd_fidelityfx_upscaler_xbox.dll carry). Under `gta6rt --run` the
3// shim registry answers them instead; if the host loader ever loaded this stub directly, XMemAlloc returns nullptr
4// so the test fails loudly. Test code, not game content.
5#include <cstddef>
6#include <cstdint>
7
8extern "C" __declspec(dllexport) void* __stdcall XMemAlloc(size_t, uint64_t) { return nullptr; }
9extern "C" __declspec(dllexport) void __stdcall XMemFree(void*, uint64_t) {}
diff --git a/runtime/test/fixtures/xmem_stub.def b/runtime/test/fixtures/xmem_stub.def
new file mode 100644
index 000000000..60c6ed789
--- /dev/null
+++ b/runtime/test/fixtures/xmem_stub.def
@@ -0,0 +1,3 @@
1EXPORTS
2 XMemAlloc
3 XMemFree