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:
authorIAmNotSiob <273832158+IAmNotSiob@users.noreply.github.com>2026-11-21 23:50:12 +0100
committerroot <root@m29531.contaboserver.net>2026-11-21 23:50:31 +0100
commit0ca9bb8bc034ac2f5f322ce5b428af964bffca4e (patch)
treedf89c76031bd3b2dbdc63a2e8172e07d659fb4d1 /runtime
parent8bd0087d2d0e45fc18fa78fb40b70ecfc6648854 (diff)
Runtime: gta6rt --run, and a stand-in game executable run through the loader
gta6rt --run <exe> [-- args] maps and binds the executable, initialises its modules and calls its entry point on a game thread. shims/process.cpp answers the process-level imports through the game's own import table: argv/argc and GetCommandLine are the game's (UCRT api-set/ucrtbase and msvcrt forms), and exit/_exit/quick_exit/ExitProcess/abort end the run with that exit code instead of the host. gta6rt then exits with the game's code directly, so the game's atexit handlers don't run during host shutdown. tiny_game.exe (CTest run_tiny_game, run_tiny_game_exit_code) does what a title does in its first second: arguments, a static initializer, a 4 MiB allocation, a file round trip, a thread, and xgameruntime.dll imports, which the shim registry answers instead of the link-time stub. thread_local and a C++ exception are opt-in (LEONIDA_RUN_TLS / LEONIDA_RUN_EH) until #93 and #176.
Diffstat (limited to 'runtime')
-rw-r--r--runtime/CMakeLists.txt25
-rw-r--r--runtime/README.md2
-rw-r--r--runtime/shims/process.cpp199
-rw-r--r--runtime/shims/process.h17
-rw-r--r--runtime/src/main.cpp48
-rw-r--r--runtime/test/fixtures/tiny_game.cpp106
-rw-r--r--runtime/test/fixtures/xgameruntime_stub.cpp10
7 files changed, 396 insertions, 11 deletions
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)
59 shims/d3d12_xs.cpp 59 shims/d3d12_xs.cpp
60 shims/d3d12_xs_device.cpp 60 shims/d3d12_xs_device.cpp
61 shims/xgameruntime.cpp 61 shims/xgameruntime.cpp
62 shims/process.cpp
62 ) 63 )
63 target_compile_definitions(gta6rt PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE) 64 target_compile_definitions(gta6rt PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE)
64 target_compile_options(gta6rt PRIVATE /W4 /permissive- /utf-8) 65 target_compile_options(gta6rt PRIVATE /W4 /permissive- /utf-8)
@@ -210,6 +211,24 @@ if(BUILD_TESTING)
210 target_link_options(pe_loader_test PRIVATE /OPT:NOREF) 211 target_link_options(pe_loader_test PRIVATE /OPT:NOREF)
211 target_link_libraries(pe_loader_test PRIVATE gta6rt_d3d12_xs_rootsig psapi) 212 target_link_libraries(pe_loader_test PRIVATE gta6rt_d3d12_xs_rootsig psapi)
212 add_dependencies(pe_loader_test tiny_dll tiny_exe) 213 add_dependencies(pe_loader_test tiny_dll tiny_exe)
214
215 # `gta6rt --run` rehearsal: a stand-in game EXE (CRT startup, statics, heap, files, threads) that imports
216 # xgameruntime.dll from a link-time stub; under --run the shim registry answers those imports instead.
217 add_library(xgameruntime_stub SHARED test/fixtures/xgameruntime_stub.cpp)
218 target_compile_definitions(xgameruntime_stub PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
219 set_target_properties(xgameruntime_stub PROPERTIES
220 OUTPUT_NAME xgameruntime
221 PREFIX ""
222 RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$<CONFIG>"
223 ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$<CONFIG>"
224 )
225 add_executable(tiny_game test/fixtures/tiny_game.cpp)
226 target_link_libraries(tiny_game PRIVATE xgameruntime_stub)
227 target_compile_definitions(tiny_game PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
228 target_compile_options(tiny_game PRIVATE /W4 /permissive- /utf-8 /EHsc)
229 set_target_properties(tiny_game PROPERTIES
230 RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$<CONFIG>"
231 )
213 add_test(NAME pe_loader COMMAND pe_loader_test "$<TARGET_FILE:tiny_dll>" "$<TARGET_FILE:tiny_exe>") 232 add_test(NAME pe_loader COMMAND pe_loader_test "$<TARGET_FILE:tiny_dll>" "$<TARGET_FILE:tiny_exe>")
214 endif() 233 endif()
215 234
@@ -258,6 +277,12 @@ if(BUILD_TESTING)
258 if(WIN32 AND TARGET xgameruntime_test) 277 if(WIN32 AND TARGET xgameruntime_test)
259 add_test(NAME xgameruntime COMMAND xgameruntime_test) 278 add_test(NAME xgameruntime COMMAND xgameruntime_test)
260 endif() 279 endif()
280 if(WIN32 AND TARGET gta6rt AND TARGET tiny_game)
281 # The stand-in game passes only with its own arguments; with others it exits 1, which --run passes through.
282 add_test(NAME run_tiny_game COMMAND gta6rt --run $<TARGET_FILE:tiny_game> -- hello 42)
283 add_test(NAME run_tiny_game_exit_code COMMAND gta6rt --run $<TARGET_FILE:tiny_game> -- wrong args)
284 set_tests_properties(run_tiny_game_exit_code PROPERTIES WILL_FAIL TRUE)
285 endif()
261 if(WIN32 AND TARGET root_signature_test) 286 if(WIN32 AND TARGET root_signature_test)
262 add_test(NAME root_signature COMMAND root_signature_test) 287 add_test(NAME root_signature COMMAND root_signature_test)
263 endif() 288 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.
111 111
112## Current limits 112## Current limits
113 113
114`gta6rt --run <exe> [-- args]` runs an executable's entry point inside the runtime (`shims/process.cpp` gives it its
115own command line and turns its `exit` into the end of the run); CTest's `run_tiny_game` does that with a stand-in game.
114The game does not boot yet. The missing executable blocks the import-driven work: the real device 116The game does not boot yet. The missing executable blocks the import-driven work: the real device
115entry point, command-list/queue/fence extensions, `PresentX`, and most of the `xgameruntime` surface (an offline 117entry point, command-list/queue/fence extensions, `PresentX`, and most of the `xgameruntime` surface (an offline
116shim covers `XGameRuntimeInitialize`, device/console queries, `XTaskQueue` and `XAsync`; see `xgameruntime_test`). The 118shim 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 @@
1// Process-level imports of a mapped executable: its command line and its way out.
2//
3// `gta6rt --run` calls a mapped EXE's entry point inside the gta6rt process. The EXE's CRT startup asks for its
4// arguments and finally calls exit(); both go through the EXE's own import table, so they can be answered here:
5// - argv/argc and the command line are the game's (set by run_entry), not gta6rt's;
6// - exit(), _exit(), quick_exit(), ExitProcess() and abort() from the game end the game's run, not the host:
7// the exit code is recorded, the run is signalled as finished and the calling thread ends. atexit handlers
8// and static destructors of the game are not run (its CRT shares the host's, whose process-wide atexit table
9// also holds gta6rt's own).
10// Covered CRTs: the Universal CRT (api-ms-win-crt-runtime-l1-1-0.dll / ucrtbase.dll, what MSVC links) and
11// msvcrt.dll (MinGW). Calls made inside host DLLs, not through the game's imports, are not seen here.
12#include <windows.h>
13
14#include <atomic>
15#include <cstdio>
16#include <cstdlib>
17#include <cstring>
18#include <string>
19#include <vector>
20
21#include "process.h"
22#include "shims.h"
23
24namespace rt::process {
25namespace {
26
27std::vector<std::string> g_args;
28std::vector<std::wstring> g_wargs;
29std::vector<char*> g_argv;
30std::vector<wchar_t*> g_wargv;
31std::string g_cmdline;
32std::wstring g_wcmdline;
33int g_argc = 0;
34char** g_argv_ptr = nullptr;
35wchar_t** g_wargv_ptr = nullptr;
36char** g_env = nullptr;
37wchar_t** g_wenv = nullptr;
38
39std::atomic<bool> g_exited{false};
40std::atomic<int> g_exit_code{0};
41HANDLE g_done = nullptr;
42
43std::string quote(const std::string& a) {
44 if (!a.empty() && a.find_first_of(" \t\"") == std::string::npos) return a;
45 std::string out = "\"";
46 for (char c : a) {
47 if (c == '"') out += '\\';
48 out += c;
49 }
50 return out + "\"";
51}
52
53std::wstring widen(const std::string& s) {
54 int n = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, nullptr, 0);
55 std::wstring w(n > 0 ? n - 1 : 0, L'\0');
56 if (n > 1) MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, w.data(), n);
57 return w;
58}
59
60[[noreturn]] void end_run(int code) {
61 bool expected = false;
62 if (g_exited.compare_exchange_strong(expected, true)) {
63 g_exit_code = code;
64 if (g_done) SetEvent(g_done);
65 ExitThread(static_cast<DWORD>(code));
66 }
67 // The run is already over: this is game code running during host shutdown (an atexit handler the game
68 // registered with the shared CRT calling exit again). Finish the process with the game's exit code; ending
69 // just this thread here would make the host's last thread, and so the process, exit with `code` instead.
70 ExitProcess(static_cast<UINT>(g_exit_code.load()));
71}
72
73// ---- the way out
74void __cdecl game_exit(int code) { end_run(code); }
75void __stdcall game_exit_process(UINT code) { end_run(static_cast<int>(code)); }
76void __cdecl game_abort() {
77 std::fprintf(stderr, "[rt] process: the game called abort()\n");
78 end_run(3); // the CRT's abort exit code
79}
80
81// ---- arguments
82int* __cdecl game_p_argc() { return &g_argc; }
83char*** __cdecl game_p_argv() { return &g_argv_ptr; }
84wchar_t*** __cdecl game_p_wargv() { return &g_wargv_ptr; }
85int __cdecl game_configure_argv(int) { return 0; } // already parsed: run_entry set them
86LPSTR __stdcall game_get_command_line_a() { return g_cmdline.data(); }
87LPWSTR __stdcall game_get_command_line_w() { return g_wcmdline.data(); }
88char** __cdecl game_p_acmdln_storage() {
89 static char* p = nullptr;
90 p = g_cmdline.data();
91 return &p;
92}
93wchar_t** __cdecl game_p_wcmdln_storage() {
94 static wchar_t* p = nullptr;
95 p = g_wcmdline.data();
96 return &p;
97}
98
99// msvcrt.dll: int __getmainargs(int* argc, char*** argv, char*** env, int expand, void* startinfo)
100int __cdecl game_getmainargs(int* argc, char*** argv, char*** env, int, void*) {
101 *argc = g_argc;
102 *argv = g_argv_ptr;
103 if (env) *env = g_env;
104 return 0;
105}
106int __cdecl game_wgetmainargs(int* argc, wchar_t*** argv, wchar_t*** env, int, void*) {
107 *argc = g_argc;
108 *argv = g_wargv_ptr;
109 if (env) *env = g_wenv;
110 return 0;
111}
112
113struct EntryCall {
114 void* entry;
115};
116
117DWORD WINAPI game_thread(void* p) {
118 auto* call = static_cast<EntryCall*>(p);
119 // An EXE entry point (mainCRTStartup and friends) takes the PEB pointer and returns the process exit code.
120 auto entry = reinterpret_cast<DWORD(WINAPI*)(void*)>(call->entry);
121 const DWORD code = entry(nullptr);
122 end_run(static_cast<int>(code)); // returning from the entry point is an exit too
123}
124
125} // namespace
126
127void set_command_line(const std::string& program, const std::vector<std::string>& args) {
128 g_args.clear();
129 g_args.push_back(program);
130 g_args.insert(g_args.end(), args.begin(), args.end());
131 g_wargs.clear();
132 g_cmdline.clear();
133 for (auto& a : g_args) {
134 g_wargs.push_back(widen(a));
135 if (!g_cmdline.empty()) g_cmdline += ' ';
136 g_cmdline += quote(a);
137 }
138 g_wcmdline = widen(g_cmdline);
139 g_argv.clear();
140 g_wargv.clear();
141 for (auto& a : g_args) g_argv.push_back(a.data());
142 for (auto& a : g_wargs) g_wargv.push_back(a.data());
143 g_argv.push_back(nullptr);
144 g_wargv.push_back(nullptr);
145 g_argc = static_cast<int>(g_args.size());
146 g_argv_ptr = g_argv.data();
147 g_wargv_ptr = g_wargv.data();
148 g_env = _environ;
149 g_wenv = _wenviron;
150}
151
152int run_entry(void* entry, size_t stack_bytes) {
153 g_exited = false;
154 g_exit_code = 0;
155 g_done = CreateEventW(nullptr, TRUE, FALSE, nullptr);
156 EntryCall call{entry};
157 HANDLE thread = CreateThread(nullptr, stack_bytes, game_thread, &call, STACK_SIZE_PARAM_IS_A_RESERVATION, nullptr);
158 if (!thread) {
159 CloseHandle(g_done);
160 g_done = nullptr;
161 return -1;
162 }
163 // The run ends when any game thread exits the process (exit/ExitProcess/abort) or the entry point returns.
164 HANDLE waits[] = {g_done, thread};
165 WaitForMultipleObjects(2, waits, FALSE, INFINITE);
166 CloseHandle(thread);
167 CloseHandle(g_done);
168 g_done = nullptr;
169 return g_exit_code.load();
170}
171
172} // namespace rt::process
173
174namespace {
175using namespace rt::process;
176#define UCRT(dll) \
177 {dll, "exit", reinterpret_cast<void*>(&game_exit)}, {dll, "_exit", reinterpret_cast<void*>(&game_exit)}, \
178 {dll, "_Exit", reinterpret_cast<void*>(&game_exit)}, {dll, "quick_exit", reinterpret_cast<void*>(&game_exit)}, \
179 {dll, "abort", reinterpret_cast<void*>(&game_abort)}, {dll, "__p___argc", reinterpret_cast<void*>(&game_p_argc)}, \
180 {dll, "__p___argv", reinterpret_cast<void*>(&game_p_argv)}, \
181 {dll, "__p___wargv", reinterpret_cast<void*>(&game_p_wargv)}, \
182 {dll, "_configure_narrow_argv", reinterpret_cast<void*>(&game_configure_argv)}, \
183 {dll, "_configure_wide_argv", reinterpret_cast<void*>(&game_configure_argv)}, \
184 {dll, "__p__acmdln", reinterpret_cast<void*>(&game_p_acmdln_storage)}, \
185 {dll, "__p__wcmdln", reinterpret_cast<void*>(&game_p_wcmdln_storage)}
186} // namespace
187
188SHIM_TABLE(process,
189 UCRT("api-ms-win-crt-runtime-l1-1-0.dll"),
190 UCRT("ucrtbase.dll"),
191 {"msvcrt.dll", "exit", reinterpret_cast<void*>(&game_exit)},
192 {"msvcrt.dll", "_exit", reinterpret_cast<void*>(&game_exit)},
193 {"msvcrt.dll", "abort", reinterpret_cast<void*>(&game_abort)},
194 {"msvcrt.dll", "__getmainargs", reinterpret_cast<void*>(&game_getmainargs)},
195 {"msvcrt.dll", "__wgetmainargs", reinterpret_cast<void*>(&game_wgetmainargs)},
196 {"kernel32.dll", "ExitProcess", reinterpret_cast<void*>(&game_exit_process)},
197 {"kernel32.dll", "GetCommandLineA", reinterpret_cast<void*>(&game_get_command_line_a)},
198 {"kernel32.dll", "GetCommandLineW", reinterpret_cast<void*>(&game_get_command_line_w)},
199);
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 @@
1// The game's command line and exit, for `gta6rt --run` (shims/process.cpp).
2#pragma once
3#include <cstddef>
4#include <string>
5#include <vector>
6
7namespace rt::process {
8
9// What the game sees as argv[0..] and GetCommandLine: `program` then `args`, quoted where needed.
10void set_command_line(const std::string& program, const std::vector<std::string>& args);
11
12// Runs a mapped EXE's entry point on a new thread with `stack_bytes` of reserved stack and returns the game's
13// exit code: the entry point's return value, or what it passed to exit/ExitProcess (3 for abort). Returns when
14// the first of those happens; other game threads are left running (the host process ends them when it exits).
15int run_entry(void* entry, std::size_t stack_bytes = 8u << 20);
16
17} // 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 @@
6// 6//
7// gta6rt --init <image> [--game-dir DIR] 7// gta6rt --init <image> [--game-dir DIR]
8// The same mapping, then each loaded DLL's TLS callbacks and DllMain(DLL_PROCESS_ATTACH) are run. 8// The same mapping, then each loaded DLL's TLS callbacks and DllMain(DLL_PROCESS_ATTACH) are run.
9//
10// gta6rt --run <exe> [--game-dir DIR] [-- game arguments...]
11// The same, then the EXE's own TLS callbacks and its entry point, on a game thread. The game's argv and
12// command line are <exe name> plus the arguments after "--"; exit/ExitProcess from the game end the run
13// (shims/process.cpp). gta6rt prints the binding report first and returns the game's exit code.
9#include <windows.h> 14#include <windows.h>
10 15
11#include <cstdio> 16#include <cstdio>
12#include <map> 17#include <map>
13#include <string> 18#include <string>
19#include <vector>
14 20
15#include "pe_loader.h" 21#include "pe_loader.h"
22#include "../shims/process.h"
23#include "../shims/shims.h"
16 24
17namespace { 25namespace {
18 26
@@ -28,7 +36,8 @@ const char* binding_name(rt::Binding b) {
28int usage() { 36int usage() {
29 std::fprintf(stderr, 37 std::fprintf(stderr,
30 "usage: gta6rt --dry-run <image> [--game-dir DIR]\n" 38 "usage: gta6rt --dry-run <image> [--game-dir DIR]\n"
31 " gta6rt --init <image> [--game-dir DIR]\n"); 39 " gta6rt --init <image> [--game-dir DIR]\n"
40 " gta6rt --run <exe> [--game-dir DIR] [-- game arguments...]\n");
32 return 2; 41 return 2;
33} 42}
34 43
@@ -36,28 +45,29 @@ int usage() {
36 45
37int wmain(int argc, wchar_t** argv) { 46int wmain(int argc, wchar_t** argv) {
38 std::filesystem::path image, game_dir; 47 std::filesystem::path image, game_dir;
39 bool dry_run = false, init = false; 48 bool dry_run = false, init = false, run = false;
49 std::vector<std::string> game_args;
40 for (int i = 1; i < argc; ++i) { 50 for (int i = 1; i < argc; ++i) {
41 std::wstring a = argv[i]; 51 std::wstring a = argv[i];
52 if (a == L"--") {
53 for (++i; i < argc; ++i) game_args.push_back(std::filesystem::path(argv[i]).string());
54 break;
55 }
42 if (a == L"--dry-run") dry_run = true; 56 if (a == L"--dry-run") dry_run = true;
43 else if (a == L"--init") init = true; 57 else if (a == L"--init") init = true;
58 else if (a == L"--run") run = true;
44 else if (a == L"--game-dir" && i + 1 < argc) game_dir = argv[++i]; 59 else if (a == L"--game-dir" && i + 1 < argc) game_dir = argv[++i];
45 else if (image.empty()) image = a; 60 else if (image.empty()) image = a;
46 else return usage(); 61 else return usage();
47 } 62 }
48 if (image.empty()) return usage(); 63 if (image.empty()) return usage();
49 if (!dry_run && !init) { 64 if (!dry_run && !init && !run) return usage();
50 std::fprintf(stderr,
51 "Only --dry-run and --init exist so far: running game code needs the shims listed by "
52 "--dry-run first.\n");
53 return 2;
54 }
55 if (game_dir.empty()) game_dir = image.parent_path(); 65 if (game_dir.empty()) game_dir = image.parent_path();
56 66
57 try { 67 try {
58 rt::Loader loader(game_dir); 68 rt::Loader loader(game_dir);
59 loader.load(image); 69 rt::Module& main_module = loader.load(image);
60 if (init) { 70 if (init || run) {
61 loader.initialise(); 71 loader.initialise();
62 std::printf("%zu module(s) initialised\n", loader.modules().size()); 72 std::printf("%zu module(s) initialised\n", loader.modules().size());
63 } 73 }
@@ -76,7 +86,23 @@ int wmain(int argc, wchar_t** argv) {
76 } 86 }
77 } 87 }
78 std::printf("%zu module(s) mapped, %d unimplemented import(s)\n", loader.modules().size(), unimplemented); 88 std::printf("%zu module(s) mapped, %d unimplemented import(s)\n", loader.modules().size(), unimplemented);
79 return 0; 89 if (!run) return 0;
90 if (!main_module.entry_rva) {
91 std::fprintf(stderr, "error: %s has no entry point\n", main_module.name.c_str());
92 return 1;
93 }
94 rt::process::set_command_line(image.filename().string(), game_args);
95 std::printf("running %s\n", main_module.name.c_str());
96 std::fflush(stdout);
97 const int code = rt::process::run_entry(main_module.base + main_module.entry_rva);
98 std::fflush(stdout);
99 std::printf("game exited with code %d\n", code);
100 rt::shims::report_called_unimplemented();
101 std::fflush(stdout);
102 std::fflush(stderr);
103 // Not `return`: a normal host exit runs the CRT's atexit table, which the game shares with gta6rt (its
104 // handlers would run against a game that has stopped) and whose last word decides the exit status.
105 ExitProcess(static_cast<UINT>(code));
80 } catch (const std::exception& e) { 106 } catch (const std::exception& e) {
81 std::fprintf(stderr, "error: %s\n", e.what()); 107 std::fprintf(stderr, "error: %s\n", e.what());
82 return 1; 108 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 @@
1// A stand-in game executable for `gta6rt --run`: what a real title does in its first second, run through the
2// loader instead of the Windows one. Test code, not game content. Run as
3// gta6rt --run tiny_game.exe -- hello 42
4// It checks its arguments, a static initializer, the heap, a file round trip, a second thread, and the
5// xgameruntime.dll imports (answered by the shim registry: the stub DLL it links against would fail them), then
6// calls exit() with 0 when everything held. thread_local and a C++ exception need static TLS (#93) and unwind
7// registration (#176) in the loader; LEONIDA_RUN_TLS=1 / LEONIDA_RUN_EH=1 turn those checks on.
8#include <windows.h>
9
10#include <cstdint>
11#include <cstdio>
12#include <cstdlib>
13#include <cstring>
14#include <string>
15#include <thread>
16#include <vector>
17
18extern "C" __declspec(dllimport) HRESULT __stdcall XGameRuntimeInitialize();
19extern "C" __declspec(dllimport) void __stdcall XGameRuntimeUninitialize();
20extern "C" __declspec(dllimport) uint32_t __stdcall XSystemGetDeviceType();
21
22namespace {
23
24int g_failures = 0;
25
26void check(bool ok, const char* what) {
27 std::printf("tiny_game: %s %s\n", ok ? "PASS" : "FAIL", what);
28 if (!ok) ++g_failures;
29}
30
31struct StaticInit {
32 int value;
33 StaticInit() : value(1234) {}
34};
35StaticInit g_static;
36
37bool env_on(const char* name) {
38 char buf[8] = {};
39 return GetEnvironmentVariableA(name, buf, sizeof buf) > 0 && buf[0] == '1';
40}
41
42thread_local int t_counter = 5;
43
44} // namespace
45
46int main(int argc, char** argv) {
47 std::printf("tiny_game: started, argc=%d\n", argc);
48 check(argc == 3 && std::strcmp(argv[1], "hello") == 0 && std::strcmp(argv[2], "42") == 0,
49 "argv is the game's command line (\"hello\" \"42\"), not gta6rt's");
50 check(std::strstr(GetCommandLineA(), "hello 42") != nullptr, "GetCommandLineA is the game's command line");
51 check(g_static.value == 1234, "a static initializer ran before main");
52
53 std::vector<int> v(1 << 20);
54 for (size_t i = 0; i < v.size(); ++i) v[i] = int(i);
55 check(v[123456] == 123456, "a 4 MiB heap allocation works");
56
57 char tmp[MAX_PATH] = {};
58 GetTempPathA(MAX_PATH, tmp);
59 std::string path = std::string(tmp) + "leonida_tiny_game_" + std::to_string(GetCurrentProcessId()) + ".txt";
60 bool file_ok = false;
61 if (FILE* f = std::fopen(path.c_str(), "wb")) {
62 std::fputs("leonida", f);
63 std::fclose(f);
64 char back[16] = {};
65 if (FILE* r = std::fopen(path.c_str(), "rb")) {
66 std::fread(back, 1, 7, r);
67 std::fclose(r);
68 file_ok = std::strcmp(back, "leonida") == 0;
69 }
70 std::remove(path.c_str());
71 }
72 check(file_ok, "a file round trip through the CRT works");
73
74 long long sum = 0;
75 std::thread worker([&] { for (int i = 1; i <= 1000; ++i) sum += i; });
76 worker.join();
77 check(sum == 500500, "a second thread ran and joined");
78
79 check(XGameRuntimeInitialize() == S_OK, "XGameRuntimeInitialize is answered by the gta6rt shim (S_OK)");
80 check(XSystemGetDeviceType() == 7, "XSystemGetDeviceType is answered by the gta6rt shim (Series X)");
81 XGameRuntimeUninitialize();
82
83 if (env_on("LEONIDA_RUN_TLS")) {
84 int seen = -1;
85 std::thread t([&] { seen = t_counter; t_counter = 9; });
86 t.join();
87 check(t_counter == 5 && seen == 5, "thread_local starts at its initializer on each thread");
88 } else {
89 std::printf("tiny_game: SKIP thread_local (needs static TLS, #93; LEONIDA_RUN_TLS=1)\n");
90 }
91 if (env_on("LEONIDA_RUN_EH")) {
92 bool caught = false;
93 try {
94 throw std::string("boom");
95 } catch (const std::string& e) {
96 caught = e == "boom";
97 }
98 check(caught, "a C++ exception is thrown and caught inside the image");
99 } else {
100 std::printf("tiny_game: SKIP C++ exception (needs unwind registration, #176; LEONIDA_RUN_EH=1)\n");
101 }
102
103 std::printf("tiny_game: %s\n", g_failures ? "FAILED" : "OK");
104 std::fflush(stdout);
105 std::exit(g_failures ? 1 : 0); // through the shimmed exit(): ends the run, not gta6rt
106}
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 @@
1// Link-time stand-in for the GDK's xgameruntime.dll, so tiny_game.exe gets real imports of these names. Under
2// `gta6rt --run` the shim registry answers them first and this DLL never loads; run directly, these failing answers
3// are what tiny_game would see. Test code, not game content.
4#include <windows.h>
5
6#include <cstdint>
7
8extern "C" __declspec(dllexport) HRESULT __stdcall XGameRuntimeInitialize() { return E_FAIL; }
9extern "C" __declspec(dllexport) void __stdcall XGameRuntimeUninitialize() {}
10extern "C" __declspec(dllexport) uint32_t __stdcall XSystemGetDeviceType() { return 0; }