diff --git a/README.md b/README.md index cc51cc5e9..d68d2d296 100644 --- a/README.md +++ b/README.md @@ -51,7 +51,7 @@ work on booting can start as soon as one is available to a developer. | Texture dictionaries and world texture pools (DDS) | ✅ Exported. Some pool entries (BCPack) are skipped | | Audio banks (AWC: Opus, XMA2) | ✅ Exported whole. Opus repackaged **losslessly** as Ogg Opus; PCM (codec 0/2) as WAV; XMA2 decoded with ffmpeg. `--wav` adds 16-bit PCM WAV ([notes](docs/audio.md)) | | Music/radio config | ? Measured. **1,589** audio-config records with exact durations and AWC stream ids; station grouping and content-id lists; no per-track start offsets ([notes](docs/audio_config.md)) | -| PE loader and import shims | ⚠️ Skeleton. Untested against the real executable | +| PE loader and import shims | ⚠️ Runs a stand-in executable end to end (`gta6rt --run`: CRT startup, statics, heap, files, threads, GDK imports through the shims, exit code back). Untested against the real executable | | Xbox D3D12 → Vulkan | ⚠️ In progress. A Vulkan-backed device behind the Xbox-ABI proxy creates queues, command lists, fences, descriptor heaps, views and committed resources; barriers, clears, uploads and copies (BC included) run on Vulkan, checked on one GPU. No shader views, pipelines, draws or swapchain yet ([plan](docs/d3d12_vulkan.md)) | | Booting, story mode, anything playable | ❌ No | diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 529db697b..04dc0276b 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -59,6 +59,7 @@ if(WIN32) shims/d3d12_xs.cpp shims/d3d12_xs_device.cpp shims/xgameruntime.cpp + shims/process.cpp ) target_compile_definitions(gta6rt PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE) target_compile_options(gta6rt PRIVATE /W4 /permissive- /utf-8) @@ -210,6 +211,24 @@ if(BUILD_TESTING) target_link_options(pe_loader_test PRIVATE /OPT:NOREF) target_link_libraries(pe_loader_test PRIVATE gta6rt_d3d12_xs_rootsig psapi) add_dependencies(pe_loader_test tiny_dll tiny_exe) + + # `gta6rt --run` rehearsal: a stand-in game EXE (CRT startup, statics, heap, files, threads) that imports + # xgameruntime.dll from a link-time stub; under --run the shim registry answers those imports instead. + add_library(xgameruntime_stub SHARED test/fixtures/xgameruntime_stub.cpp) + target_compile_definitions(xgameruntime_stub PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + set_target_properties(xgameruntime_stub PROPERTIES + OUTPUT_NAME xgameruntime + PREFIX "" + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$" + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$" + ) + add_executable(tiny_game test/fixtures/tiny_game.cpp) + target_link_libraries(tiny_game PRIVATE xgameruntime_stub) + target_compile_definitions(tiny_game PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(tiny_game PRIVATE /W4 /permissive- /utf-8 /EHsc) + set_target_properties(tiny_game PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$" + ) add_test(NAME pe_loader COMMAND pe_loader_test "$" "$") endif() @@ -258,6 +277,12 @@ if(BUILD_TESTING) if(WIN32 AND TARGET xgameruntime_test) add_test(NAME xgameruntime COMMAND xgameruntime_test) endif() + if(WIN32 AND TARGET gta6rt AND TARGET tiny_game) + # The stand-in game passes only with its own arguments; with others it exits 1, which --run passes through. + add_test(NAME run_tiny_game COMMAND gta6rt --run $ -- hello 42) + add_test(NAME run_tiny_game_exit_code COMMAND gta6rt --run $ -- wrong args) + set_tests_properties(run_tiny_game_exit_code PROPERTIES WILL_FAIL TRUE) + endif() if(WIN32 AND TARGET root_signature_test) add_test(NAME root_signature COMMAND root_signature_test) endif() diff --git a/runtime/README.md b/runtime/README.md index 0b5bdea00..ae59ca0e3 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -111,6 +111,8 @@ the files in place and never copy or commit game data. ## Current limits +`gta6rt --run [-- args]` runs an executable's entry point inside the runtime (`shims/process.cpp` gives it its +own command line and turns its `exit` into the end of the run); CTest's `run_tiny_game` does that with a stand-in game. The game does not boot yet. The missing executable blocks the import-driven work: the real device entry point, command-list/queue/fence extensions, `PresentX`, and most of the `xgameruntime` surface (an offline shim covers `XGameRuntimeInitialize`, device/console queries, `XTaskQueue` and `XAsync`; see `xgameruntime_test`). The diff --git a/runtime/shims/process.cpp b/runtime/shims/process.cpp new file mode 100644 index 000000000..79fb73de9 --- /dev/null +++ b/runtime/shims/process.cpp @@ -0,0 +1,199 @@ +// Process-level imports of a mapped executable: its command line and its way out. +// +// `gta6rt --run` calls a mapped EXE's entry point inside the gta6rt process. The EXE's CRT startup asks for its +// arguments and finally calls exit(); both go through the EXE's own import table, so they can be answered here: +// - argv/argc and the command line are the game's (set by run_entry), not gta6rt's; +// - exit(), _exit(), quick_exit(), ExitProcess() and abort() from the game end the game's run, not the host: +// the exit code is recorded, the run is signalled as finished and the calling thread ends. atexit handlers +// and static destructors of the game are not run (its CRT shares the host's, whose process-wide atexit table +// also holds gta6rt's own). +// Covered CRTs: the Universal CRT (api-ms-win-crt-runtime-l1-1-0.dll / ucrtbase.dll, what MSVC links) and +// msvcrt.dll (MinGW). Calls made inside host DLLs, not through the game's imports, are not seen here. +#include + +#include +#include +#include +#include +#include +#include + +#include "process.h" +#include "shims.h" + +namespace rt::process { +namespace { + +std::vector g_args; +std::vector g_wargs; +std::vector g_argv; +std::vector g_wargv; +std::string g_cmdline; +std::wstring g_wcmdline; +int g_argc = 0; +char** g_argv_ptr = nullptr; +wchar_t** g_wargv_ptr = nullptr; +char** g_env = nullptr; +wchar_t** g_wenv = nullptr; + +std::atomic g_exited{false}; +std::atomic g_exit_code{0}; +HANDLE g_done = nullptr; + +std::string quote(const std::string& a) { + if (!a.empty() && a.find_first_of(" \t\"") == std::string::npos) return a; + std::string out = "\""; + for (char c : a) { + if (c == '"') out += '\\'; + out += c; + } + return out + "\""; +} + +std::wstring widen(const std::string& s) { + int n = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, nullptr, 0); + std::wstring w(n > 0 ? n - 1 : 0, L'\0'); + if (n > 1) MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, w.data(), n); + return w; +} + +[[noreturn]] void end_run(int code) { + bool expected = false; + if (g_exited.compare_exchange_strong(expected, true)) { + g_exit_code = code; + if (g_done) SetEvent(g_done); + ExitThread(static_cast(code)); + } + // The run is already over: this is game code running during host shutdown (an atexit handler the game + // registered with the shared CRT calling exit again). Finish the process with the game's exit code; ending + // just this thread here would make the host's last thread, and so the process, exit with `code` instead. + ExitProcess(static_cast(g_exit_code.load())); +} + +// ---- the way out +void __cdecl game_exit(int code) { end_run(code); } +void __stdcall game_exit_process(UINT code) { end_run(static_cast(code)); } +void __cdecl game_abort() { + std::fprintf(stderr, "[rt] process: the game called abort()\n"); + end_run(3); // the CRT's abort exit code +} + +// ---- arguments +int* __cdecl game_p_argc() { return &g_argc; } +char*** __cdecl game_p_argv() { return &g_argv_ptr; } +wchar_t*** __cdecl game_p_wargv() { return &g_wargv_ptr; } +int __cdecl game_configure_argv(int) { return 0; } // already parsed: run_entry set them +LPSTR __stdcall game_get_command_line_a() { return g_cmdline.data(); } +LPWSTR __stdcall game_get_command_line_w() { return g_wcmdline.data(); } +char** __cdecl game_p_acmdln_storage() { + static char* p = nullptr; + p = g_cmdline.data(); + return &p; +} +wchar_t** __cdecl game_p_wcmdln_storage() { + static wchar_t* p = nullptr; + p = g_wcmdline.data(); + return &p; +} + +// msvcrt.dll: int __getmainargs(int* argc, char*** argv, char*** env, int expand, void* startinfo) +int __cdecl game_getmainargs(int* argc, char*** argv, char*** env, int, void*) { + *argc = g_argc; + *argv = g_argv_ptr; + if (env) *env = g_env; + return 0; +} +int __cdecl game_wgetmainargs(int* argc, wchar_t*** argv, wchar_t*** env, int, void*) { + *argc = g_argc; + *argv = g_wargv_ptr; + if (env) *env = g_wenv; + return 0; +} + +struct EntryCall { + void* entry; +}; + +DWORD WINAPI game_thread(void* p) { + auto* call = static_cast(p); + // An EXE entry point (mainCRTStartup and friends) takes the PEB pointer and returns the process exit code. + auto entry = reinterpret_cast(call->entry); + const DWORD code = entry(nullptr); + end_run(static_cast(code)); // returning from the entry point is an exit too +} + +} // namespace + +void set_command_line(const std::string& program, const std::vector& args) { + g_args.clear(); + g_args.push_back(program); + g_args.insert(g_args.end(), args.begin(), args.end()); + g_wargs.clear(); + g_cmdline.clear(); + for (auto& a : g_args) { + g_wargs.push_back(widen(a)); + if (!g_cmdline.empty()) g_cmdline += ' '; + g_cmdline += quote(a); + } + g_wcmdline = widen(g_cmdline); + g_argv.clear(); + g_wargv.clear(); + for (auto& a : g_args) g_argv.push_back(a.data()); + for (auto& a : g_wargs) g_wargv.push_back(a.data()); + g_argv.push_back(nullptr); + g_wargv.push_back(nullptr); + g_argc = static_cast(g_args.size()); + g_argv_ptr = g_argv.data(); + g_wargv_ptr = g_wargv.data(); + g_env = _environ; + g_wenv = _wenviron; +} + +int run_entry(void* entry, size_t stack_bytes) { + g_exited = false; + g_exit_code = 0; + g_done = CreateEventW(nullptr, TRUE, FALSE, nullptr); + EntryCall call{entry}; + HANDLE thread = CreateThread(nullptr, stack_bytes, game_thread, &call, STACK_SIZE_PARAM_IS_A_RESERVATION, nullptr); + if (!thread) { + CloseHandle(g_done); + g_done = nullptr; + return -1; + } + // The run ends when any game thread exits the process (exit/ExitProcess/abort) or the entry point returns. + HANDLE waits[] = {g_done, thread}; + WaitForMultipleObjects(2, waits, FALSE, INFINITE); + CloseHandle(thread); + CloseHandle(g_done); + g_done = nullptr; + return g_exit_code.load(); +} + +} // namespace rt::process + +namespace { +using namespace rt::process; +#define UCRT(dll) \ + {dll, "exit", reinterpret_cast(&game_exit)}, {dll, "_exit", reinterpret_cast(&game_exit)}, \ + {dll, "_Exit", reinterpret_cast(&game_exit)}, {dll, "quick_exit", reinterpret_cast(&game_exit)}, \ + {dll, "abort", reinterpret_cast(&game_abort)}, {dll, "__p___argc", reinterpret_cast(&game_p_argc)}, \ + {dll, "__p___argv", reinterpret_cast(&game_p_argv)}, \ + {dll, "__p___wargv", reinterpret_cast(&game_p_wargv)}, \ + {dll, "_configure_narrow_argv", reinterpret_cast(&game_configure_argv)}, \ + {dll, "_configure_wide_argv", reinterpret_cast(&game_configure_argv)}, \ + {dll, "__p__acmdln", reinterpret_cast(&game_p_acmdln_storage)}, \ + {dll, "__p__wcmdln", reinterpret_cast(&game_p_wcmdln_storage)} +} // namespace + +SHIM_TABLE(process, + UCRT("api-ms-win-crt-runtime-l1-1-0.dll"), + UCRT("ucrtbase.dll"), + {"msvcrt.dll", "exit", reinterpret_cast(&game_exit)}, + {"msvcrt.dll", "_exit", reinterpret_cast(&game_exit)}, + {"msvcrt.dll", "abort", reinterpret_cast(&game_abort)}, + {"msvcrt.dll", "__getmainargs", reinterpret_cast(&game_getmainargs)}, + {"msvcrt.dll", "__wgetmainargs", reinterpret_cast(&game_wgetmainargs)}, + {"kernel32.dll", "ExitProcess", reinterpret_cast(&game_exit_process)}, + {"kernel32.dll", "GetCommandLineA", reinterpret_cast(&game_get_command_line_a)}, + {"kernel32.dll", "GetCommandLineW", reinterpret_cast(&game_get_command_line_w)}, +); diff --git a/runtime/shims/process.h b/runtime/shims/process.h new file mode 100644 index 000000000..62bc828c3 --- /dev/null +++ b/runtime/shims/process.h @@ -0,0 +1,17 @@ +// The game's command line and exit, for `gta6rt --run` (shims/process.cpp). +#pragma once +#include +#include +#include + +namespace rt::process { + +// What the game sees as argv[0..] and GetCommandLine: `program` then `args`, quoted where needed. +void set_command_line(const std::string& program, const std::vector& args); + +// Runs a mapped EXE's entry point on a new thread with `stack_bytes` of reserved stack and returns the game's +// exit code: the entry point's return value, or what it passed to exit/ExitProcess (3 for abort). Returns when +// the first of those happens; other game threads are left running (the host process ends them when it exits). +int run_entry(void* entry, std::size_t stack_bytes = 8u << 20); + +} // namespace rt::process diff --git a/runtime/src/main.cpp b/runtime/src/main.cpp index 4477c4a69..d79ff97dc 100644 --- a/runtime/src/main.cpp +++ b/runtime/src/main.cpp @@ -6,13 +6,21 @@ // // gta6rt --init [--game-dir DIR] // The same mapping, then each loaded DLL's TLS callbacks and DllMain(DLL_PROCESS_ATTACH) are run. +// +// gta6rt --run [--game-dir DIR] [-- game arguments...] +// The same, then the EXE's own TLS callbacks and its entry point, on a game thread. The game's argv and +// command line are plus the arguments after "--"; exit/ExitProcess from the game end the run +// (shims/process.cpp). gta6rt prints the binding report first and returns the game's exit code. #include #include #include #include +#include #include "pe_loader.h" +#include "../shims/process.h" +#include "../shims/shims.h" namespace { @@ -28,7 +36,8 @@ const char* binding_name(rt::Binding b) { int usage() { std::fprintf(stderr, "usage: gta6rt --dry-run [--game-dir DIR]\n" - " gta6rt --init [--game-dir DIR]\n"); + " gta6rt --init [--game-dir DIR]\n" + " gta6rt --run [--game-dir DIR] [-- game arguments...]\n"); return 2; } @@ -36,28 +45,29 @@ int usage() { int wmain(int argc, wchar_t** argv) { std::filesystem::path image, game_dir; - bool dry_run = false, init = false; + bool dry_run = false, init = false, run = false; + std::vector game_args; for (int i = 1; i < argc; ++i) { std::wstring a = argv[i]; + if (a == L"--") { + for (++i; i < argc; ++i) game_args.push_back(std::filesystem::path(argv[i]).string()); + break; + } if (a == L"--dry-run") dry_run = true; else if (a == L"--init") init = true; + else if (a == L"--run") run = true; else if (a == L"--game-dir" && i + 1 < argc) game_dir = argv[++i]; else if (image.empty()) image = a; else return usage(); } if (image.empty()) return usage(); - if (!dry_run && !init) { - std::fprintf(stderr, - "Only --dry-run and --init exist so far: running game code needs the shims listed by " - "--dry-run first.\n"); - return 2; - } + if (!dry_run && !init && !run) return usage(); if (game_dir.empty()) game_dir = image.parent_path(); try { rt::Loader loader(game_dir); - loader.load(image); - if (init) { + rt::Module& main_module = loader.load(image); + if (init || run) { loader.initialise(); std::printf("%zu module(s) initialised\n", loader.modules().size()); } @@ -76,7 +86,23 @@ int wmain(int argc, wchar_t** argv) { } } std::printf("%zu module(s) mapped, %d unimplemented import(s)\n", loader.modules().size(), unimplemented); - return 0; + if (!run) return 0; + if (!main_module.entry_rva) { + std::fprintf(stderr, "error: %s has no entry point\n", main_module.name.c_str()); + return 1; + } + rt::process::set_command_line(image.filename().string(), game_args); + std::printf("running %s\n", main_module.name.c_str()); + std::fflush(stdout); + const int code = rt::process::run_entry(main_module.base + main_module.entry_rva); + std::fflush(stdout); + std::printf("game exited with code %d\n", code); + rt::shims::report_called_unimplemented(); + std::fflush(stdout); + std::fflush(stderr); + // Not `return`: a normal host exit runs the CRT's atexit table, which the game shares with gta6rt (its + // handlers would run against a game that has stopped) and whose last word decides the exit status. + ExitProcess(static_cast(code)); } catch (const std::exception& e) { std::fprintf(stderr, "error: %s\n", e.what()); return 1; diff --git a/runtime/test/fixtures/tiny_game.cpp b/runtime/test/fixtures/tiny_game.cpp new file mode 100644 index 000000000..3cb08937f --- /dev/null +++ b/runtime/test/fixtures/tiny_game.cpp @@ -0,0 +1,106 @@ +// A stand-in game executable for `gta6rt --run`: what a real title does in its first second, run through the +// loader instead of the Windows one. Test code, not game content. Run as +// gta6rt --run tiny_game.exe -- hello 42 +// It checks its arguments, a static initializer, the heap, a file round trip, a second thread, and the +// xgameruntime.dll imports (answered by the shim registry: the stub DLL it links against would fail them), then +// calls exit() with 0 when everything held. thread_local and a C++ exception need static TLS (#93) and unwind +// registration (#176) in the loader; LEONIDA_RUN_TLS=1 / LEONIDA_RUN_EH=1 turn those checks on. +#include + +#include +#include +#include +#include +#include +#include +#include + +extern "C" __declspec(dllimport) HRESULT __stdcall XGameRuntimeInitialize(); +extern "C" __declspec(dllimport) void __stdcall XGameRuntimeUninitialize(); +extern "C" __declspec(dllimport) uint32_t __stdcall XSystemGetDeviceType(); + +namespace { + +int g_failures = 0; + +void check(bool ok, const char* what) { + std::printf("tiny_game: %s %s\n", ok ? "PASS" : "FAIL", what); + if (!ok) ++g_failures; +} + +struct StaticInit { + int value; + StaticInit() : value(1234) {} +}; +StaticInit g_static; + +bool env_on(const char* name) { + char buf[8] = {}; + return GetEnvironmentVariableA(name, buf, sizeof buf) > 0 && buf[0] == '1'; +} + +thread_local int t_counter = 5; + +} // namespace + +int main(int argc, char** argv) { + std::printf("tiny_game: started, argc=%d\n", argc); + check(argc == 3 && std::strcmp(argv[1], "hello") == 0 && std::strcmp(argv[2], "42") == 0, + "argv is the game's command line (\"hello\" \"42\"), not gta6rt's"); + check(std::strstr(GetCommandLineA(), "hello 42") != nullptr, "GetCommandLineA is the game's command line"); + check(g_static.value == 1234, "a static initializer ran before main"); + + std::vector v(1 << 20); + for (size_t i = 0; i < v.size(); ++i) v[i] = int(i); + check(v[123456] == 123456, "a 4 MiB heap allocation works"); + + char tmp[MAX_PATH] = {}; + GetTempPathA(MAX_PATH, tmp); + std::string path = std::string(tmp) + "leonida_tiny_game_" + std::to_string(GetCurrentProcessId()) + ".txt"; + bool file_ok = false; + if (FILE* f = std::fopen(path.c_str(), "wb")) { + std::fputs("leonida", f); + std::fclose(f); + char back[16] = {}; + if (FILE* r = std::fopen(path.c_str(), "rb")) { + std::fread(back, 1, 7, r); + std::fclose(r); + file_ok = std::strcmp(back, "leonida") == 0; + } + std::remove(path.c_str()); + } + check(file_ok, "a file round trip through the CRT works"); + + long long sum = 0; + std::thread worker([&] { for (int i = 1; i <= 1000; ++i) sum += i; }); + worker.join(); + check(sum == 500500, "a second thread ran and joined"); + + check(XGameRuntimeInitialize() == S_OK, "XGameRuntimeInitialize is answered by the gta6rt shim (S_OK)"); + check(XSystemGetDeviceType() == 7, "XSystemGetDeviceType is answered by the gta6rt shim (Series X)"); + XGameRuntimeUninitialize(); + + if (env_on("LEONIDA_RUN_TLS")) { + int seen = -1; + std::thread t([&] { seen = t_counter; t_counter = 9; }); + t.join(); + check(t_counter == 5 && seen == 5, "thread_local starts at its initializer on each thread"); + } else { + std::printf("tiny_game: SKIP thread_local (needs static TLS, #93; LEONIDA_RUN_TLS=1)\n"); + } + if (env_on("LEONIDA_RUN_EH")) { + bool caught = false; + try { + throw std::string("boom"); + } catch (const std::string& e) { + caught = e == "boom"; + } + check(caught, "a C++ exception is thrown and caught inside the image"); + } else { + std::printf("tiny_game: SKIP C++ exception (needs unwind registration, #176; LEONIDA_RUN_EH=1)\n"); + } + + std::printf("tiny_game: %s\n", g_failures ? "FAILED" : "OK"); + std::fflush(stdout); + std::exit(g_failures ? 1 : 0); // through the shimmed exit(): ends the run, not gta6rt +} diff --git a/runtime/test/fixtures/xgameruntime_stub.cpp b/runtime/test/fixtures/xgameruntime_stub.cpp new file mode 100644 index 000000000..749eda8fc --- /dev/null +++ b/runtime/test/fixtures/xgameruntime_stub.cpp @@ -0,0 +1,10 @@ +// Link-time stand-in for the GDK's xgameruntime.dll, so tiny_game.exe gets real imports of these names. Under +// `gta6rt --run` the shim registry answers them first and this DLL never loads; run directly, these failing answers +// are what tiny_game would see. Test code, not game content. +#include + +#include + +extern "C" __declspec(dllexport) HRESULT __stdcall XGameRuntimeInitialize() { return E_FAIL; } +extern "C" __declspec(dllexport) void __stdcall XGameRuntimeUninitialize() {} +extern "C" __declspec(dllexport) uint32_t __stdcall XSystemGetDeviceType() { return 0; }