upleb.uk

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

summaryrefslogtreecommitdiff
path: root/runtime/src/main.cpp
diff options
context:
space:
mode:
authorAndretuta <Andretuta@users.noreply.github.com>2026-11-25 18:33:16 -0300
committerAndretuta <Andretuta@users.noreply.github.com>2026-11-25 18:33:16 -0300
commitadf9c3f20bbb6f7685770b301719bc7e4c357507 (patch)
tree178d820b89deaace44dd963c7f9c4ee1cad50a31 /runtime/src/main.cpp
parent7430be3869d72fda88796f00efaacb7f1f965e71 (diff)
parent4eab4f6d34b61d9c66d54308a7af2b56539339a1 (diff)
Merge main into gpu/rx9070xt-refresh
Keep this branch's RX 9070 XT row and the rows main added below it (RX 9070, Ryzen 5 7600X iGPU, RTX 5070 Ti, RTX 3080). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'runtime/src/main.cpp')
-rw-r--r--runtime/src/main.cpp311
1 files changed, 308 insertions, 3 deletions
diff --git a/runtime/src/main.cpp b/runtime/src/main.cpp
index 098a8ee40..094aaa321 100644
--- a/runtime/src/main.cpp
+++ b/runtime/src/main.cpp
@@ -18,24 +18,147 @@
18// (--overlay, default <game-dir>/overlay) so the package is never modified (shims/file_system.cpp). 18// (--overlay, default <game-dir>/overlay) so the package is never modified (shims/file_system.cpp).
19#include <windows.h> 19#include <windows.h>
20 20
21#include <cstdint>
21#include <cstdio> 22#include <cstdio>
22#include <cstdlib> 23#include <cstdlib>
23#include <exception> 24#include <exception>
24#include <filesystem> 25#include <filesystem>
25#include <map> 26#include <map>
27#include <mutex>
26#include <string> 28#include <string>
27#include <system_error> 29#include <system_error>
28#include <vector> 30#include <vector>
29 31
32#include <cstring>
33
34namespace {
35
36// The retail executable (1.0.2.1) runs a hang watchdog thread (function at RVA 0x2215a60): when the game's main loop
37// has not set its "kick" byte (RVA 0x71b6331) for 30 one-second ticks, it calls a crash callback and then writes to
38// address 0 (`movl $0, 0` at RVA 0x2215c35). Under the runtime the game thread can legitimately stall for longer than
39// that, e.g. while the driver compiles pipelines against a cold cache (first boot after a driver update), and the
40// title then kills itself. By default the watchdog stays armed, as on the console. With LEONIDA_TITLE_WATCHDOG=0, and
41// only when that exact trap instruction sits where it does in this build, a runtime thread sets the kick byte twice a
42// second so the title's watchdog never fires.
43constexpr std::uint32_t kWatchdogTrapRva = 0x2215c35;
44constexpr std::uint32_t kWatchdogKickRva = 0x71b6331;
45constexpr unsigned char kWatchdogTrap[] = {0xC7, 0x04, 0x25, 0, 0, 0, 0, 0, 0, 0, 0}; // movl $0, 0x0
46
47void keep_title_watchdog_kicked(std::uint8_t* base) {
48 char value[4]{};
49 if (GetEnvironmentVariableA("LEONIDA_TITLE_WATCHDOG", value, sizeof(value)) != 1 || value[0] != '0') return;
50 MEMORY_BASIC_INFORMATION trap{}, kick{};
51 if (!VirtualQuery(base + kWatchdogTrapRva, &trap, sizeof(trap)) || trap.State != MEM_COMMIT ||
52 std::memcmp(base + kWatchdogTrapRva, kWatchdogTrap, sizeof(kWatchdogTrap)) != 0)
53 return; // not the build this was measured on: leave the title's watchdog alone
54 const DWORD writable = PAGE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY;
55 if (!VirtualQuery(base + kWatchdogKickRva, &kick, sizeof(kick)) || kick.State != MEM_COMMIT ||
56 !(kick.Protect & writable))
57 return;
58 volatile std::uint8_t* const byte = base + kWatchdogKickRva;
59 const HANDLE thread = CreateThread(
60 nullptr, 0,
61 [](LPVOID p) -> DWORD {
62 auto* b = static_cast<volatile std::uint8_t*>(p);
63 for (;;) {
64 *b = 1;
65 Sleep(500);
66 }
67 },
68 const_cast<std::uint8_t*>(byte), 0, nullptr);
69 if (thread) {
70 CloseHandle(thread);
71 std::fprintf(stderr, "[rt] loader: keeping the title's hang watchdog kicked (LEONIDA_TITLE_WATCHDOG=0; unset or 1 keeps it armed)\n");
72 }
73}
74
75// LEONIDA_PEEK="0x9e1dac0:3,0x7446510,0x98f828c" (diagnostic): a thread prints the 8-byte values at these RVAs of the
76// title's image (":n" = n consecutive values, at most 32; "RVA>OFF" reads through the pointer stored at the RVA, at
77// pointer + OFF, both hex) every LEONIDA_PEEK_SECONDS (default 10). For answering "what does this
78// global hold at run time" without a debugger: the reverse-engineering notes (docs/re/requests.md) ask for exactly
79// that. Reads are checked; nothing is written.
80void start_title_peek(std::uint8_t* base) {
81 static char spec[1024];
82 const DWORD n = GetEnvironmentVariableA("LEONIDA_PEEK", spec, sizeof(spec));
83 if (!n || n >= sizeof(spec)) return;
84 static std::uint8_t* image = base;
85 const HANDLE thread = CreateThread(
86 nullptr, 0,
87 [](LPVOID) -> DWORD {
88 char seconds[16]{};
89 DWORD period = 10;
90 if (GetEnvironmentVariableA("LEONIDA_PEEK_SECONDS", seconds, sizeof(seconds)) > 0)
91 period = std::max<DWORD>(1, static_cast<DWORD>(std::strtoul(seconds, nullptr, 10)));
92 for (unsigned tick = 0;; ++tick) {
93 std::string line = "[rt] peek t=" + std::to_string(tick * period) + "s:";
94 for (const char* at = spec; *at;) {
95 char* end = nullptr;
96 const std::uint64_t rva = std::strtoull(at, &end, 16);
97 if (end == at) break;
98 // "RVA>OFF": the 8-byte pointer at the RVA, then the values at pointer + OFF (both hex).
99 bool deref = false;
100 std::uint64_t offset = 0;
101 if (*end == '>') {
102 deref = true;
103 offset = std::strtoull(end + 1, &end, 16);
104 }
105 unsigned count = 1;
106 if (*end == ':') count = static_cast<unsigned>(std::strtoul(end + 1, &end, 10));
107 char text[48];
108 if (deref)
109 std::snprintf(text, sizeof(text), " 0x%llx>%llx=", static_cast<unsigned long long>(rva),
110 static_cast<unsigned long long>(offset));
111 else
112 std::snprintf(text, sizeof(text), " 0x%llx=", static_cast<unsigned long long>(rva));
113 line += text;
114 const std::uint8_t* from = image + rva;
115 if (deref) {
116 std::uint64_t pointer = 0;
117 SIZE_T got = 0;
118 if (!ReadProcessMemory(GetCurrentProcess(), from, &pointer, sizeof(pointer), &got) ||
119 got != sizeof(pointer) || !pointer)
120 count = 0, line += "?";
121 from = reinterpret_cast<const std::uint8_t*>(pointer + offset);
122 }
123 for (unsigned i = 0; i < count && i < 32; ++i) {
124 std::uint64_t value = 0;
125 SIZE_T got = 0;
126 const bool ok = ReadProcessMemory(GetCurrentProcess(), from + 8ull * i, &value,
127 sizeof(value), &got) && got == sizeof(value);
128 std::snprintf(text, sizeof(text), ok ? "%s%llx" : "%s?", i ? "," : "",
129 static_cast<unsigned long long>(value));
130 line += text;
131 }
132 at = *end == ',' ? end + 1 : end;
133 if (at == end && *end) break;
134 }
135 std::fprintf(stderr, "%s\n", line.c_str());
136 Sleep(period * 1000);
137 }
138 },
139 nullptr, 0, nullptr);
140 if (thread) CloseHandle(thread);
141}
142
143} // namespace
144
30#include "base_reservation.h" 145#include "base_reservation.h"
31#include "code_hooks.h" 146#include "code_hooks.h"
32#include "cpu_emulation.h" 147#include "cpu_emulation.h"
33#include "host_cpu.h" 148#include "host_cpu.h"
34#include "mods.h" 149#include "mods.h"
35#include "pe_loader.h" 150#include "pe_loader.h"
151#include "thread_stacks.h"
152#include "thread_sampler.h"
153#include "title_page_watch.h"
154#include "title_geometry_watch.h"
36#include "../shims/d3d12_trace.h" 155#include "../shims/d3d12_trace.h"
37#include "../shims/d3d12_xs_device.h" 156#include "../shims/d3d12_xs_device.h"
38#include "../shims/file_system.h" 157#include "../shims/file_system.h"
158#ifdef LEONIDA_VULKAN_DEVICE
159#include "../shims/d3d12_compile_exit.h"
160#include "../shims/package_splash.h"
161#endif
39#include "../shims/process_shim.h" 162#include "../shims/process_shim.h"
40#include "../shims/shims.h" 163#include "../shims/shims.h"
41#include "../shims/startup_trace.h" 164#include "../shims/startup_trace.h"
@@ -52,22 +175,128 @@ const char* binding_name(rt::Binding b) {
52 } 175 }
53} 176}
54 177
178// Module TLS index 0 for the game's executable (rt::reserve_tls_index0), from the CRT's initializer table: .CRT$XCT
179// runs after the C runtime is set up and before every C++ dynamic initializer of gta6rt (.CRT$XCU), so before any of
180// gta6rt's code can have started a thread. The frames above it (wmainCRTStartup, __scrt_common_main_seh, _initterm)
181// hold no TLS slot address. The result is read again where an image is run.
182void __cdecl reserve_tls_index0_at_start() { rt::reserve_tls_index0(); }
183#pragma section(".CRT$XCT", read)
184extern "C" __declspec(allocate(".CRT$XCT")) void(__cdecl* const gta6rt_reserve_tls_index0)() =
185 reserve_tls_index0_at_start;
186#pragma comment(linker, "/INCLUDE:gta6rt_reserve_tls_index0")
187
188// Select the settings used to display the offline first-run UI. Keep explicit caller settings.
189bool configure_first_run_ui(const std::filesystem::path& package, std::filesystem::path& overlay) {
190 // A variable that is set but empty is not a setting: Windows cannot hold one, but a caller on Wine can pass one
191 // (NAME= in the environment), and asking for the size alone reports it as present there.
192 const auto set_default = [](const wchar_t* name, const wchar_t* value) {
193 wchar_t first[2]{};
194 return GetEnvironmentVariableW(name, first, 2) != 0 || _wputenv_s(name, value) == 0;
195 };
196 const struct { const wchar_t* name; const wchar_t* value; } settings[] = {
197 {L"LEONIDA_D3D12", L"vulkan"}, {L"LEONIDA_ARENA_MB", L"2048"},
198 {L"LEONIDA_GRAPHICS_STAGE_LAYOUT", L"1"}, {L"LEONIDA_PIPELINE_COMPILE", L"on-demand"},
199 {L"LEONIDA_FRAME_PACING", L"1"},
200 // Focused, not always: keys typed into another window must not press anything on a consent page.
201 // Scripted presses (LEONIDA_INPUT_SCRIPT) still run while the window is unfocused.
202 {L"LEONIDA_KEYBOARD_PAD", L"1"},
203 };
204 for (const auto& setting : settings) {
205 if (!set_default(setting.name, setting.value)) return false;
206 }
207 std::wstring executable(32768, L'\0');
208 const DWORD length = GetModuleFileNameW(nullptr, executable.data(), static_cast<DWORD>(executable.size()));
209 if (!length || length >= executable.size()) return false;
210 executable.resize(length);
211 const auto state = std::filesystem::path(executable).parent_path() / L"first-run-ui";
212 if (overlay.empty()) overlay = state / L"overlay";
213 if (!GetEnvironmentVariableW(L"LEONIDA_XMEM_BACKING_DIR", nullptr, 0)) {
214 std::error_code error;
215 const auto backing = state / L"xmem";
216 std::filesystem::create_directories(backing, error);
217 if (error || !set_default(L"LEONIDA_XMEM_BACKING_DIR", backing.c_str())) return false;
218 }
219 return SetCurrentDirectoryW(package.c_str()) != FALSE;
220}
221
55int usage() { 222int usage() {
56 std::fprintf(stderr, 223 std::fprintf(stderr,
57 "usage: gta6rt --dry-run <image> [--game-dir DIR] [--overlay DIR] [--mods DIR] [--archetype-lookup RVA[,ARG]] [--view-mode-getter RVA] [--trace FILE]\n" 224 "usage: gta6rt --dry-run <image> [--game-dir DIR] [--overlay DIR] [--mods DIR] [--archetype-lookup RVA[,ARG]] [--view-mode-getter RVA] [--trace FILE]\n"
58 " gta6rt --init <image> [--game-dir DIR] [--overlay DIR] [--mods DIR] [--archetype-lookup RVA[,ARG]] [--view-mode-getter RVA] [--trace-d3d12] [--trace FILE]\n" 225 " gta6rt --init <image> [--game-dir DIR] [--overlay DIR] [--mods DIR] [--archetype-lookup RVA[,ARG]] [--view-mode-getter RVA] [--trace-d3d12] [--trace FILE]\n"
226 " gta6rt --first-run-ui <exe> [--game-dir DIR] [--overlay DIR] [--trace FILE]\n"
59 " gta6rt --run <exe> [--game-dir DIR] [--overlay DIR] [--mods DIR] [--archetype-lookup RVA[,ARG]] [--view-mode-getter RVA] [--trace-d3d12] [--trace FILE] [-- game arguments...]\n"); 227 " gta6rt --run <exe> [--game-dir DIR] [--overlay DIR] [--mods DIR] [--archetype-lookup RVA[,ARG]] [--view-mode-getter RVA] [--trace-d3d12] [--trace FILE] [-- game arguments...]\n");
60 return 2; 228 return 2;
61} 229}
62 230
63} // namespace 231} // namespace
64 232
233#ifdef LEONIDA_VULKAN_DEVICE
234// The run ends with the title's Vulkan device alive, so no ~Device stops the background pipeline compiler: stop it
235// here, before ExitProcess ends its thread, maybe inside the driver's compiler (rt::d3d12::stop_pipeline_compiles).
236constexpr unsigned kExitCompileWaitMs = 2000; // a console close gives the whole process 5 s
237// For a build still running on a title thread, then the session cache write (rt::d3d12::save_pipeline_caches_at_exit).
238constexpr unsigned kExitCacheWaitMs = 1000;
239
240static BOOL WINAPI stop_compiles_on_console_exit(DWORD event) {
241 if (event == CTRL_C_EVENT || event == CTRL_BREAK_EVENT || event == CTRL_CLOSE_EVENT) {
242 rt::d3d12_xs::stop_list_values(500); // as at the run's end: no list-value thread cut off inside the layer
243 rt::d3d12::stop_pipeline_compiles(kExitCompileWaitMs);
244 rt::d3d12::save_pipeline_caches_at_exit(kExitCacheWaitMs);
245 }
246 return FALSE; // the next handler (the default one: ExitProcess) ends the process, as before
247}
248
249// A run that ends in an exception nothing handles (a fault in the title or one of its DLLs, the int3 after a device
250// loss) would otherwise keep none of the pipelines it compiled, and the next boot builds them all again. The device is
251// left alone apart from that write; the exception then goes on as before (the previous filter, or Windows' own
252// handling), so the exit code is the exception's. Not for a stack overflow: no stack is left to write with.
253static LPTOP_LEVEL_EXCEPTION_FILTER previous_fatal_filter = nullptr;
254// The retail title installs a filter of its own (SetUnhandledExceptionFilter from api-ms-win-core-errorhandling),
255// which replaced this one and ended the process without it (measured: a title fault at 354 s wrote nothing). Its
256// call is served here instead: this filter stays installed and hands the exception to the title's, as Windows would.
257static void* volatile title_fatal_filter = nullptr;
258
259static LPTOP_LEVEL_EXCEPTION_FILTER WINAPI title_set_unhandled_exception_filter(LPTOP_LEVEL_EXCEPTION_FILTER filter) {
260 return reinterpret_cast<LPTOP_LEVEL_EXCEPTION_FILTER>(
261 InterlockedExchangePointer(&title_fatal_filter, reinterpret_cast<void*>(filter)));
262}
263
264static LONG WINAPI save_caches_on_fatal_exception(EXCEPTION_POINTERS* info) {
265 const DWORD code = info && info->ExceptionRecord ? info->ExceptionRecord->ExceptionCode : 0;
266 if (code != EXCEPTION_STACK_OVERFLOW) {
267 // Several title threads can fault at once (measured: eight within a second). The first writes; the others
268 // wait here for it, so none of them reaches the title's filter, which may end the process, mid-write.
269 static std::once_flag once;
270 std::call_once(once, [code] {
271 std::fprintf(stderr, "[rt] unhandled exception 0x%08lx: writing the session pipeline cache before the "
272 "process ends\n", static_cast<unsigned long>(code));
273 rt::d3d12::stop_pipeline_compiles(kExitCompileWaitMs);
274 rt::d3d12::save_pipeline_caches_at_exit(kExitCacheWaitMs);
275 std::fflush(stderr);
276 });
277 }
278 if (auto* title = reinterpret_cast<LPTOP_LEVEL_EXCEPTION_FILTER>(
279 InterlockedCompareExchangePointer(&title_fatal_filter, nullptr, nullptr)))
280 return title(info);
281 return previous_fatal_filter ? previous_fatal_filter(info) : EXCEPTION_CONTINUE_SEARCH;
282}
283
284static BOOL WINAPI show_package_window(HWND window, int command) {
285 const BOOL previous = ShowWindow(window, command);
286 const DWORD error = GetLastError();
287 if (command != SW_HIDE && rt::package_splash::paint_window(window))
288 rt::startup_trace::event("package_splash_window");
289 SetLastError(error);
290 return previous;
291}
292#endif
293
65int wmain(int argc, wchar_t** argv) { 294int wmain(int argc, wchar_t** argv) {
66 std::filesystem::path image, game_dir, overlay_dir, mods_dir; 295 std::filesystem::path image, game_dir, overlay_dir, mods_dir;
67 uint32_t archetype_lookup_rva = 0; // --archetype-lookup RVA[,ARG]: the game's archetype lookup by hash 296 uint32_t archetype_lookup_rva = 0; // --archetype-lookup RVA[,ARG]: the game's archetype lookup by hash
68 int archetype_lookup_arg = 0; 297 int archetype_lookup_arg = 0;
69 uint32_t view_mode_getter_rva = 0; // --view-mode-getter RVA: the game's view mode of a camera context 298 uint32_t view_mode_getter_rva = 0; // --view-mode-getter RVA: the game's view mode of a camera context
70 bool dry_run = false, init = false, run = false, trace_d3d12 = false; 299 bool dry_run = false, init = false, run = false, trace_d3d12 = false, first_run_ui = false;
71 std::vector<std::wstring> game_args; // wide: path::string() throws on a character the code page lacks (RT-84) 300 std::vector<std::wstring> game_args; // wide: path::string() throws on a character the code page lacks (RT-84)
72 std::wstring trace_file; 301 std::wstring trace_file;
73 for (int i = 1; i < argc; ++i) { 302 for (int i = 1; i < argc; ++i) {
@@ -78,6 +307,7 @@ int wmain(int argc, wchar_t** argv) {
78 } 307 }
79 if (a == L"--dry-run") dry_run = true; 308 if (a == L"--dry-run") dry_run = true;
80 else if (a == L"--init") init = true; 309 else if (a == L"--init") init = true;
310 else if (a == L"--first-run-ui") first_run_ui = true;
81 else if (a == L"--run") run = true; 311 else if (a == L"--run") run = true;
82 else if (a == L"--trace-d3d12") trace_d3d12 = true; 312 else if (a == L"--trace-d3d12") trace_d3d12 = true;
83 else if (a == L"--trace" && i + 1 < argc) trace_file = argv[++i]; 313 else if (a == L"--trace" && i + 1 < argc) trace_file = argv[++i];
@@ -104,7 +334,8 @@ int wmain(int argc, wchar_t** argv) {
104 } 334 }
105 if (image.empty()) return usage(); 335 if (image.empty()) return usage();
106 // Exactly one mode: --dry-run --run would otherwise initialise the modules and call the entry point. 336 // Exactly one mode: --dry-run --run would otherwise initialise the modules and call the entry point.
107 if (dry_run + init + run != 1) return usage(); 337 if (dry_run + init + run + first_run_ui != 1) return usage();
338 run = run || first_run_ui;
108 // The game runs AVX code from its TLS callbacks on; without AVX that is a bare 0xC000001D (src/host_cpu.h). 339 // The game runs AVX code from its TLS callbacks on; without AVX that is a bare 0xC000001D (src/host_cpu.h).
109 if ((init || run) && !rt::host_cpu::check_skipped()) 340 if ((init || run) && !rt::host_cpu::check_skipped())
110 if (const auto missing = rt::host_cpu::missing_host_features(); !missing.empty()) { 341 if (const auto missing = rt::host_cpu::missing_host_features(); !missing.empty()) {
@@ -119,7 +350,21 @@ int wmain(int argc, wchar_t** argv) {
119 std::filesystem::path a = std::filesystem::absolute(p, ec); 350 std::filesystem::path a = std::filesystem::absolute(p, ec);
120 return ec ? p : a; 351 return ec ? p : a;
121 }; 352 };
353 if (first_run_ui) {
354 image = absolute_or_same(image);
355 if (!mods_dir.empty()) mods_dir = absolute_or_same(mods_dir);
356 if (!trace_file.empty()) trace_file = absolute_or_same(trace_file).wstring();
357 }
122 game_dir = game_dir.empty() ? absolute_or_same(image).parent_path() : absolute_or_same(game_dir); 358 game_dir = game_dir.empty() ? absolute_or_same(image).parent_path() : absolute_or_same(game_dir);
359 // An unattended run can select a fresh write root even when its launcher supplies --overlay.
360 if (const DWORD size = GetEnvironmentVariableW(L"LEONIDA_WRITE_DIR", nullptr, 0)) {
361 std::wstring dir(size, 0);
362 const DWORD n = GetEnvironmentVariableW(L"LEONIDA_WRITE_DIR", dir.data(), size);
363 if (n && n < size) {
364 dir.resize(n);
365 overlay_dir = dir;
366 }
367 }
123 if (!overlay_dir.empty()) overlay_dir = absolute_or_same(overlay_dir); 368 if (!overlay_dir.empty()) overlay_dir = absolute_or_same(overlay_dir);
124 // LEONIDA_SHADERS too: the D3D12 device reads it at the title's first pipeline state, after it may have moved. 369 // LEONIDA_SHADERS too: the D3D12 device reads it at the title's first pipeline state, after it may have moved.
125 if (const DWORD size = GetEnvironmentVariableW(L"LEONIDA_SHADERS", nullptr, 0)) { 370 if (const DWORD size = GetEnvironmentVariableW(L"LEONIDA_SHADERS", nullptr, 0)) {
@@ -135,8 +380,31 @@ int wmain(int argc, wchar_t** argv) {
135 if (!rt::base_reservation::inherited()) 380 if (!rt::base_reservation::inherited())
136 if (const auto range = rt::base_reservation::needed(image)) return rt::base_reservation::relaunch(*range); 381 if (const auto range = rt::base_reservation::needed(image)) return rt::base_reservation::relaunch(*range);
137 // GAME: paths read under --game-dir; whatever a title writes lands in the overlay, never in the package. 382 // GAME: paths read under --game-dir; whatever a title writes lands in the overlay, never in the package.
383 if (first_run_ui && !configure_first_run_ui(game_dir, overlay_dir)) {
384 std::fprintf(stderr, "cannot initialize the first-run UI paths or graphics settings\n");
385 return 1;
386 }
138 if (overlay_dir.empty()) overlay_dir = game_dir / "overlay"; 387 if (overlay_dir.empty()) overlay_dir = game_dir / "overlay";
139 rt::fs::configure(game_dir, overlay_dir); 388 rt::fs::configure(game_dir, overlay_dir);
389#ifdef LEONIDA_VULKAN_DEVICE
390 if (run) {
391 // Before the image is loaded, so its import binds here (save_caches_on_fatal_exception).
392 const rt::shims::Entry filter_imports[] = {
393 {"api-ms-win-core-errorhandling-l1-1-0.dll", "SetUnhandledExceptionFilter",
394 reinterpret_cast<void*>(&title_set_unhandled_exception_filter)},
395 {"kernel32.dll", "SetUnhandledExceptionFilter", reinterpret_cast<void*>(&title_set_unhandled_exception_filter)},
396 };
397 rt::shims::Table{filter_imports, std::size(filter_imports)};
398 rt::package_splash::configure(game_dir);
399 if (rt::package_splash::configured()) {
400 const rt::shims::Entry window_imports[] = {
401 {"ext-ms-win-rtcore-ntuser-window-l1-1-0.dll", "ShowWindow", reinterpret_cast<void*>(&show_package_window)},
402 {"user32.dll", "ShowWindow", reinterpret_cast<void*>(&show_package_window)},
403 };
404 rt::shims::Table{window_imports, std::size(window_imports)};
405 }
406 }
407#endif
140 // Mods (docs/modding.md): <folder of gta6rt.exe>\mods unless --mods names another. Loaded and reported here; 408 // Mods (docs/modding.md): <folder of gta6rt.exe>\mods unless --mods names another. Loaded and reported here;
141 // the archetype swaps take effect once the game's archetype lookup is hooked for this executable version. 409 // the archetype swaps take effect once the game's archetype lookup is hooked for this executable version.
142 if (mods_dir.empty()) { 410 if (mods_dir.empty()) {
@@ -168,6 +436,11 @@ int wmain(int argc, wchar_t** argv) {
168 rt::d3d12_trace::set_enabled(trace_d3d12); 436 rt::d3d12_trace::set_enabled(trace_d3d12);
169 // Slot 133 imports the title's pages; xmem commits them on first touch, so they are committed first. 437 // Slot 133 imports the title's pages; xmem commits them on first touch, so they are committed first.
170 rt::d3d12_xs::set_placed_at_va_pages_hook(&rt::xmem::commit_physical_range); 438 rt::d3d12_xs::set_placed_at_va_pages_hook(&rt::xmem::commit_physical_range);
439 // So do the file shims' reads, whose kernel writes do not fault them in: on ERROR_NOACCESS (title_page_watch.h).
440 leonida::geometry_writes::aliases.store(&rt::xmem::geometry_aliases);
441 leonida::kernel_writes::set_committer(&rt::xmem::commit_physical_range);
442 rt::d3d12_xs::set_texture_page_provider(&rt::xmem::pin_mapped_data);
443 leonida::kernel_writes::set_unguarder(&rt::xmem::reopen_unowned);
171 if (int trace_error = 0; !trace_file.empty() && !rt::startup_trace::open(trace_file.c_str(), &trace_error)) { 444 if (int trace_error = 0; !trace_file.empty() && !rt::startup_trace::open(trace_file.c_str(), &trace_error)) {
172 std::fprintf(stderr, trace_error == EEXIST ? "error: the trace file already exists; --trace only creates a new file\n" 445 std::fprintf(stderr, trace_error == EEXIST ? "error: the trace file already exists; --trace only creates a new file\n"
173 : "error: cannot create the trace file\n"); 446 : "error: cannot create the trace file\n");
@@ -186,6 +459,20 @@ int wmain(int argc, wchar_t** argv) {
186 try { 459 try {
187 rt::Loader loader(game_dir); 460 rt::Loader loader(game_dir);
188 rt::Module& main_module = loader.load(image); // maps, binds and installs TLS; runs no image code 461 rt::Module& main_module = loader.load(image); // maps, binds and installs TLS; runs no image code
462 // An executable with TLS that did not get index 0: its /GA code would read and write the TLS in slot 0, which
463 // is gta6rt's own (or another executable's), so no code of it may run.
464 const auto* main_nt = reinterpret_cast<const IMAGE_NT_HEADERS64*>(
465 main_module.base + reinterpret_cast<const IMAGE_DOS_HEADER*>(main_module.base)->e_lfanew);
466 const bool main_is_exe = (main_nt->FileHeader.Characteristics & IMAGE_FILE_DLL) == 0;
467 if ((init || run) && main_is_exe && main_module.tls_slot != rt::kNoTlsIndex && main_module.tls_index != 0) {
468 std::string why;
469 if (rt::reserve_tls_index0(&why)) why = "another mapped executable holds it";
470 std::fprintf(stderr,
471 "error: %s cannot have module TLS index 0 (%s); code built with /GA would read and write "
472 "another module's TLS through slot 0, so it is not run\n",
473 main_module.name.c_str(), why.c_str());
474 return 1;
475 }
189 // The mods' archetype swaps (docs/modding.md): hooked here, before any image code runs, when the lookup's RVA 476 // The mods' archetype swaps (docs/modding.md): hooked here, before any image code runs, when the lookup's RVA
190 // for this executable is given. The count of redirected calls shows whether the RVA is the real lookup. 477 // for this executable is given. The count of redirected calls shows whether the RVA is the real lookup.
191 if (view_mode_getter_rva) { 478 if (view_mode_getter_rva) {
@@ -272,7 +559,18 @@ int wmain(int argc, wchar_t** argv) {
272 } 559 }
273 std::printf("running %s\n", main_module.name.c_str()); 560 std::printf("running %s\n", main_module.name.c_str());
274 std::fflush(stdout); 561 std::fflush(stdout);
275 const int code = rt::process::run_entry(main_module.base + main_module.entry_rva); 562 keep_title_watchdog_kicked(main_module.base);
563 start_title_peek(main_module.base);
564 leonida::thread_sampler::start(main_module.base, main_module.size); // LEONIDA_SAMPLE_MS (diagnostic)
565#ifdef LEONIDA_VULKAN_DEVICE
566 SetConsoleCtrlHandler(&stop_compiles_on_console_exit, TRUE);
567 previous_fatal_filter = SetUnhandledExceptionFilter(&save_caches_on_fatal_exception);
568#endif
569 int code;
570 {
571 auto stacks = rt::start_thread_stacks();
572 code = rt::process::run_entry(main_module.base + main_module.entry_rva);
573 }
276 std::fflush(stdout); 574 std::fflush(stdout);
277 std::printf("game exited with code %d\n", code); 575 std::printf("game exited with code %d\n", code);
278 rt::shims::report_called_unimplemented(); 576 rt::shims::report_called_unimplemented();
@@ -282,6 +580,13 @@ int wmain(int argc, wchar_t** argv) {
282 // Not `return`: a normal host exit runs the CRT's atexit table, which the game shares with gta6rt (its 580 // Not `return`: a normal host exit runs the CRT's atexit table, which the game shares with gta6rt (its
283 // handlers would run against a game that has stopped) and whose last word decides the exit status. 581 // handlers would run against a game that has stopped) and whose last word decides the exit status.
284 // ExitProcess also skips atexit, so the TLS clone cleanup registered there is run here instead. 582 // ExitProcess also skips atexit, so the TLS clone cleanup registered there is run here instead.
583 // The list-value threads end first: ExitProcess must not cut one off inside the layer (in a held submission,
584 // holding its queues' lock).
585 rt::d3d12_xs::stop_list_values(500);
586#ifdef LEONIDA_VULKAN_DEVICE
587 rt::d3d12::stop_pipeline_compiles(kExitCompileWaitMs);
588 rt::d3d12::save_pipeline_caches_at_exit(kExitCacheWaitMs);
589#endif
285 rt::cleanup_tls_clones(); 590 rt::cleanup_tls_clones();
286 ExitProcess(static_cast<UINT>(code)); 591 ExitProcess(static_cast<UINT>(code));
287 } catch (const std::exception& e) { 592 } catch (const std::exception& e) {