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:
Diffstat (limited to 'runtime/src/main.cpp')
-rw-r--r--runtime/src/main.cpp227
1 files changed, 209 insertions, 18 deletions
diff --git a/runtime/src/main.cpp b/runtime/src/main.cpp
index f01997775..ad17dd3b0 100644
--- a/runtime/src/main.cpp
+++ b/runtime/src/main.cpp
@@ -9,6 +9,13 @@
9// gta6rt --init <image> [--game-dir DIR] [--overlay DIR] 9// gta6rt --init <image> [--game-dir DIR] [--overlay DIR]
10// The same mapping, then each loaded DLL's TLS callbacks and DllMain(DLL_PROCESS_ATTACH) are run. 10// The same mapping, then each loaded DLL's TLS callbacks and DllMain(DLL_PROCESS_ATTACH) are run.
11// 11//
12// gta6rt --precompile-pipelines [--threads N] [--big-threads N] [--big-bytes N] [--all] [--smallest-first]
13// [--limit N] [--min-bytes N] [--max-bytes N] [--filter PART]... [--skip-listed] [--list]
14// No game: creates the Vulkan device as --run does and builds every compute pipeline of the shader library
15// (LEONIDA_SHADERS) into the pipeline journal and the driver's cache, so a title's first dispatch of a large one
16// does not stall it. Resumable: entries already journaled are skipped (--all: built anyway). Programs named by
17// LEONIDA_SKIP_COMPUTE are built too unless --skip-listed is given. See shims/d3d12_precompile.h.
18//
12// gta6rt --run <exe> [--game-dir DIR] [--overlay DIR] [--trace-d3d12] [--trace FILE] [-- game arguments...] 19// gta6rt --run <exe> [--game-dir DIR] [--overlay DIR] [--trace-d3d12] [--trace FILE] [-- game arguments...]
13// The same, then the EXE's own TLS callbacks and its entry point, on a game thread. The game's argv and 20// The same, then the EXE's own TLS callbacks and its entry point, on a game thread. The game's argv and
14// command line are <exe name> plus the arguments after "--"; exit/ExitProcess from the game end the run 21// command line are <exe name> plus the arguments after "--"; exit/ExitProcess from the game end the run
@@ -24,6 +31,7 @@
24#include <exception> 31#include <exception>
25#include <filesystem> 32#include <filesystem>
26#include <map> 33#include <map>
34#include <mutex>
27#include <string> 35#include <string>
28#include <system_error> 36#include <system_error>
29#include <vector> 37#include <vector>
@@ -32,24 +40,51 @@
32 40
33namespace { 41namespace {
34 42
35// The retail executable (1.0.2.1) runs a hang watchdog thread (function at RVA 0x2215a60): when the game's main loop 43// The retail title runs a hang watchdog thread: when the game's main loop has not set its "kick" byte for 30
36// has not set its "kick" byte (RVA 0x71b6331) for 30 one-second ticks, it calls a crash callback and then writes to 44// one-second ticks, it calls a crash callback and then writes to address 0 (`movl $0, 0`). Under the runtime the
37// address 0 (`movl $0, 0` at RVA 0x2215c35). Under the runtime the game thread can legitimately stall for longer than 45// game thread can legitimately stall for longer than that, e.g. while the driver compiles pipelines against a cold
38// that, e.g. while the driver compiles pipelines against a cold cache (first boot after a driver update), and the 46// cache (first boot after a driver update), and the title then kills itself. By default the watchdog stays armed, as
39// title then kills itself. By default the watchdog stays armed, as on the console. With LEONIDA_TITLE_WATCHDOG=0, and 47// on the console. LEONIDA_TITLE_WATCHDOG=0 asks to keep it from firing, as before. The two places that takes are
40// only when that exact trap instruction sits where it does in this build, a runtime thread sets the kick byte twice a 48// measured locally and not kept in the repository: LEONIDA_TITLE_WATCHDOG_KICK="<trap RVA>,<kick RVA>" (hex) names
41// second so the title's watchdog never fires. 49// them, and only with both variables, and only when that exact trap instruction sits at the first RVA, does a
42constexpr std::uint32_t kWatchdogTrapRva = 0x2215c35; 50// runtime thread set the byte at the second twice a second, so the title's watchdog never fires. Either variable
43constexpr std::uint32_t kWatchdogKickRva = 0x71b6331; 51// alone leaves the watchdog armed and says so once.
44constexpr unsigned char kWatchdogTrap[] = {0xC7, 0x04, 0x25, 0, 0, 0, 0, 0, 0, 0, 0}; // movl $0, 0x0 52constexpr unsigned char kWatchdogTrap[] = {0xC7, 0x04, 0x25, 0, 0, 0, 0, 0, 0, 0, 0}; // movl $0, 0x0
45 53
54bool watchdog_rvas(std::uint32_t& trap_rva, std::uint32_t& kick_rva) {
55 char value[64]{};
56 const DWORD n = GetEnvironmentVariableA("LEONIDA_TITLE_WATCHDOG_KICK", value, sizeof(value));
57 if (!n || n >= sizeof(value)) return false;
58 char* rest = nullptr;
59 const unsigned long long trap = std::strtoull(value, &rest, 16);
60 if (!rest || *rest != ',') return false;
61 const unsigned long long kick = std::strtoull(rest + 1, &rest, 16);
62 if (!rest || *rest || !trap || !kick || trap > 0xFFFFFFFFull || kick > 0xFFFFFFFFull) return false;
63 trap_rva = static_cast<std::uint32_t>(trap);
64 kick_rva = static_cast<std::uint32_t>(kick);
65 return true;
66}
67
46void keep_title_watchdog_kicked(std::uint8_t* base) { 68void keep_title_watchdog_kicked(std::uint8_t* base) {
47 char value[4]{}; 69 char keep[4]{};
48 if (GetEnvironmentVariableA("LEONIDA_TITLE_WATCHDOG", value, sizeof(value)) != 1 || value[0] != '0') return; 70 const bool disarm = GetEnvironmentVariableA("LEONIDA_TITLE_WATCHDOG", keep, sizeof(keep)) == 1 && keep[0] == '0';
71 std::uint32_t kWatchdogTrapRva = 0, kWatchdogKickRva = 0;
72 const bool named = watchdog_rvas(kWatchdogTrapRva, kWatchdogKickRva);
73 if (!disarm) {
74 if (named)
75 std::fprintf(stderr, "[rt] loader: LEONIDA_TITLE_WATCHDOG_KICK is set but LEONIDA_TITLE_WATCHDOG is not 0;"
76 " the title's hang watchdog stays armed\n");
77 return;
78 }
79 if (!named) {
80 std::fprintf(stderr, "[rt] loader: LEONIDA_TITLE_WATCHDOG=0 needs LEONIDA_TITLE_WATCHDOG_KICK=<trap RVA>,"
81 "<kick RVA> (hex); the title's hang watchdog stays armed\n");
82 return;
83 }
49 MEMORY_BASIC_INFORMATION trap{}, kick{}; 84 MEMORY_BASIC_INFORMATION trap{}, kick{};
50 if (!VirtualQuery(base + kWatchdogTrapRva, &trap, sizeof(trap)) || trap.State != MEM_COMMIT || 85 if (!VirtualQuery(base + kWatchdogTrapRva, &trap, sizeof(trap)) || trap.State != MEM_COMMIT ||
51 std::memcmp(base + kWatchdogTrapRva, kWatchdogTrap, sizeof(kWatchdogTrap)) != 0) 86 std::memcmp(base + kWatchdogTrapRva, kWatchdogTrap, sizeof(kWatchdogTrap)) != 0)
52 return; // not the build this was measured on: leave the title's watchdog alone 87 return; // not the trap the RVAs name: leave the title's watchdog alone
53 const DWORD writable = PAGE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY; 88 const DWORD writable = PAGE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY;
54 if (!VirtualQuery(base + kWatchdogKickRva, &kick, sizeof(kick)) || kick.State != MEM_COMMIT || 89 if (!VirtualQuery(base + kWatchdogKickRva, &kick, sizeof(kick)) || kick.State != MEM_COMMIT ||
55 !(kick.Protect & writable)) 90 !(kick.Protect & writable))
@@ -71,7 +106,7 @@ void keep_title_watchdog_kicked(std::uint8_t* base) {
71 } 106 }
72} 107}
73 108
74// LEONIDA_PEEK="0x9e1dac0:3,0x7446510,0x98f828c" (diagnostic): a thread prints the 8-byte values at these RVAs of the 109// LEONIDA_PEEK="<rva>:3,<rva>,<rva>" (diagnostic): a thread prints the 8-byte values at these RVAs of the
75// title's image (":n" = n consecutive values, at most 32; "RVA>OFF" reads through the pointer stored at the RVA, at 110// title's image (":n" = n consecutive values, at most 32; "RVA>OFF" reads through the pointer stored at the RVA, at
76// pointer + OFF, both hex) every LEONIDA_PEEK_SECONDS (default 10). For answering "what does this 111// pointer + OFF, both hex) every LEONIDA_PEEK_SECONDS (default 10). For answering "what does this
77// global hold at run time" without a debugger: the reverse-engineering notes (docs/re/requests.md) ask for exactly 112// global hold at run time" without a debugger: the reverse-engineering notes (docs/re/requests.md) ask for exactly
@@ -141,13 +176,18 @@ void start_title_peek(std::uint8_t* base) {
141 176
142} // namespace 177} // namespace
143 178
179#include "assert_skip.h"
180#include "avx2_emulation.h"
144#include "base_reservation.h" 181#include "base_reservation.h"
182#include "compile_gate_policy.h"
183#include "bmi_emulation.h"
145#include "code_hooks.h" 184#include "code_hooks.h"
146#include "cpu_emulation.h" 185#include "cpu_emulation.h"
147#include "host_cpu.h" 186#include "host_cpu.h"
148#include "mods.h" 187#include "mods.h"
149#include "pe_loader.h" 188#include "pe_loader.h"
150#include "thread_stacks.h" 189#include "thread_stacks.h"
190#include "dev_overlay.h"
151#include "thread_sampler.h" 191#include "thread_sampler.h"
152#include "title_page_watch.h" 192#include "title_page_watch.h"
153#include "title_geometry_watch.h" 193#include "title_geometry_watch.h"
@@ -155,7 +195,9 @@ void start_title_peek(std::uint8_t* base) {
155#include "../shims/d3d12_xs_device.h" 195#include "../shims/d3d12_xs_device.h"
156#include "../shims/file_system.h" 196#include "../shims/file_system.h"
157#ifdef LEONIDA_VULKAN_DEVICE 197#ifdef LEONIDA_VULKAN_DEVICE
198#include "vulkan_device_fault.h"
158#include "../shims/d3d12_compile_exit.h" 199#include "../shims/d3d12_compile_exit.h"
200#include "../shims/d3d12_precompile.h"
159#include "../shims/package_splash.h" 201#include "../shims/package_splash.h"
160#endif 202#endif
161#include "../shims/process_shim.h" 203#include "../shims/process_shim.h"
@@ -196,7 +238,9 @@ bool configure_first_run_ui(const std::filesystem::path& package, std::filesyste
196 {L"LEONIDA_D3D12", L"vulkan"}, {L"LEONIDA_ARENA_MB", L"2048"}, 238 {L"LEONIDA_D3D12", L"vulkan"}, {L"LEONIDA_ARENA_MB", L"2048"},
197 {L"LEONIDA_GRAPHICS_STAGE_LAYOUT", L"1"}, {L"LEONIDA_PIPELINE_COMPILE", L"on-demand"}, 239 {L"LEONIDA_GRAPHICS_STAGE_LAYOUT", L"1"}, {L"LEONIDA_PIPELINE_COMPILE", L"on-demand"},
198 {L"LEONIDA_FRAME_PACING", L"1"}, 240 {L"LEONIDA_FRAME_PACING", L"1"},
199 {L"LEONIDA_KEYBOARD_PAD", L"always"}, 241 // Focused, not always: keys typed into another window must not press anything on a consent page.
242 // Scripted presses (LEONIDA_INPUT_SCRIPT) still run while the window is unfocused.
243 {L"LEONIDA_KEYBOARD_PAD", L"1"},
200 }; 244 };
201 for (const auto& setting : settings) { 245 for (const auto& setting : settings) {
202 if (!set_default(setting.name, setting.value)) return false; 246 if (!set_default(setting.name, setting.value)) return false;
@@ -221,25 +265,120 @@ int usage() {
221 "usage: gta6rt --dry-run <image> [--game-dir DIR] [--overlay DIR] [--mods DIR] [--archetype-lookup RVA[,ARG]] [--view-mode-getter RVA] [--trace FILE]\n" 265 "usage: gta6rt --dry-run <image> [--game-dir DIR] [--overlay DIR] [--mods DIR] [--archetype-lookup RVA[,ARG]] [--view-mode-getter RVA] [--trace FILE]\n"
222 " gta6rt --init <image> [--game-dir DIR] [--overlay DIR] [--mods DIR] [--archetype-lookup RVA[,ARG]] [--view-mode-getter RVA] [--trace-d3d12] [--trace FILE]\n" 266 " gta6rt --init <image> [--game-dir DIR] [--overlay DIR] [--mods DIR] [--archetype-lookup RVA[,ARG]] [--view-mode-getter RVA] [--trace-d3d12] [--trace FILE]\n"
223 " gta6rt --first-run-ui <exe> [--game-dir DIR] [--overlay DIR] [--trace FILE]\n" 267 " gta6rt --first-run-ui <exe> [--game-dir DIR] [--overlay DIR] [--trace FILE]\n"
224 " 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"); 268 " 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"
269 " gta6rt --precompile-pipelines [--threads N] [--big-threads N] [--big-bytes N] [--all] [--smallest-first] [--limit N] [--min-bytes N] [--max-bytes N] [--filter PART]... [--skip-listed] [--list] [--via-helper]\n"
270 " gta6rt --compile-server [--parent PID] [--threads N] [--idle-threads N] [--idle-exit SECONDS]\n");
225 return 2; 271 return 2;
226} 272}
227 273
274#ifdef LEONIDA_VULKAN_DEVICE
275// gta6rt --precompile-pipelines ...: argv[1] is the mode.
276int precompile_main(int argc, wchar_t** argv) {
277 rt::d3d12::PrecompileOptions options;
278 const auto number = [&](int& i, auto& out) {
279 if (i + 1 >= argc) return false;
280 wchar_t* end = nullptr;
281 const unsigned long long v = std::wcstoull(argv[++i], &end, 10);
282 if (!end || *end) return false;
283 out = static_cast<std::remove_reference_t<decltype(out)>>(v);
284 return true;
285 };
286 for (int i = 2; i < argc; ++i) {
287 const std::wstring a = argv[i];
288 bool ok = true;
289 if (a == L"--threads") ok = number(i, options.threads);
290 else if (a == L"--big-threads") ok = number(i, options.big_threads);
291 else if (a == L"--big-bytes") ok = number(i, options.big_bytes);
292 else if (a == L"--limit") ok = number(i, options.limit);
293 else if (a == L"--min-bytes") ok = number(i, options.min_bytes);
294 else if (a == L"--max-bytes") ok = number(i, options.max_bytes);
295 else if (a == L"--all") options.rebuild = true;
296 else if (a == L"--smallest-first") options.smallest_first = true;
297 else if (a == L"--skip-listed") options.skip_listed = true;
298 else if (a == L"--list") options.dry_run = true;
299 else if (a == L"--via-helper") options.via_helper = true;
300 else if (a == L"--filter" && i + 1 < argc) {
301 const std::wstring part = argv[++i];
302 options.filters.emplace_back(part.begin(), part.end()); // library names are ASCII
303 } else ok = false;
304 if (!ok) return usage();
305 }
306 return rt::d3d12::precompile_compute_pipelines(options);
307}
308
309// gta6rt --compile-server [--parent PID] [--threads N] [--idle-threads N] [--idle-exit SECONDS]
310// (shims/d3d12_compile_helper.h).
311int compile_server_main(int argc, wchar_t** argv) {
312 rt::d3d12::CompileServerOptions options;
313 for (int i = 2; i < argc; ++i) {
314 const std::wstring a = argv[i];
315 if (i + 1 >= argc) return usage();
316 wchar_t* end = nullptr;
317 const unsigned long long v = std::wcstoull(argv[++i], &end, 10);
318 if (!end || *end) return usage();
319 if (a == L"--parent") options.parent_pid = static_cast<unsigned long>(v);
320 else if (a == L"--threads") options.threads = static_cast<unsigned>(v);
321 else if (a == L"--idle-threads") options.idle_threads = static_cast<unsigned>(v);
322 else if (a == L"--idle-exit") options.idle_exit_s = static_cast<unsigned>(v);
323 else return usage();
324 }
325 return rt::d3d12::compile_server(options);
326}
327#endif
328
228} // namespace 329} // namespace
229 330
230#ifdef LEONIDA_VULKAN_DEVICE 331#ifdef LEONIDA_VULKAN_DEVICE
231// The run ends with the title's Vulkan device alive, so no ~Device stops the background pipeline compiler: stop it 332// The run ends with the title's Vulkan device alive, so no ~Device stops the background pipeline compiler: stop it
232// here, before ExitProcess ends its thread, maybe inside the driver's compiler (rt::d3d12::stop_pipeline_compiles). 333// here, before ExitProcess ends its thread, maybe inside the driver's compiler (rt::d3d12::stop_pipeline_compiles).
233constexpr unsigned kExitCompileWaitMs = 2000; // a console close gives the whole process 5 s 334constexpr unsigned kExitCompileWaitMs = 2000; // a console close gives the whole process 5 s
335// For a build still running on a title thread, then the session cache write (rt::d3d12::save_pipeline_caches_at_exit).
336constexpr unsigned kExitCacheWaitMs = 1000;
234 337
235static BOOL WINAPI stop_compiles_on_console_exit(DWORD event) { 338static BOOL WINAPI stop_compiles_on_console_exit(DWORD event) {
236 if (event == CTRL_C_EVENT || event == CTRL_BREAK_EVENT || event == CTRL_CLOSE_EVENT) { 339 if (event == CTRL_C_EVENT || event == CTRL_BREAK_EVENT || event == CTRL_CLOSE_EVENT) {
237 rt::d3d12_xs::stop_list_values(500); // as at the run's end: no list-value thread cut off inside the layer 340 rt::d3d12_xs::stop_list_values(500); // as at the run's end: no list-value thread cut off inside the layer
238 rt::d3d12::stop_pipeline_compiles(kExitCompileWaitMs); 341 rt::d3d12::stop_pipeline_compiles(kExitCompileWaitMs);
342 rt::d3d12::save_pipeline_caches_at_exit(kExitCacheWaitMs);
239 } 343 }
240 return FALSE; // the next handler (the default one: ExitProcess) ends the process, as before 344 return FALSE; // the next handler (the default one: ExitProcess) ends the process, as before
241} 345}
242 346
347// A run that ends in an exception nothing handles (a fault in the title or one of its DLLs, the int3 after a device
348// loss) would otherwise keep none of the pipelines it compiled, and the next boot builds them all again. The device is
349// left alone apart from that write; the exception then goes on as before (the previous filter, or Windows' own
350// handling), so the exit code is the exception's. Not for a stack overflow: no stack is left to write with.
351static LPTOP_LEVEL_EXCEPTION_FILTER previous_fatal_filter = nullptr;
352// The retail title installs a filter of its own (SetUnhandledExceptionFilter from api-ms-win-core-errorhandling),
353// which replaced this one and ended the process without it (measured: a title fault at 354 s wrote nothing). Its
354// call is served here instead: this filter stays installed and hands the exception to the title's, as Windows would.
355static void* volatile title_fatal_filter = nullptr;
356
357static LPTOP_LEVEL_EXCEPTION_FILTER WINAPI title_set_unhandled_exception_filter(LPTOP_LEVEL_EXCEPTION_FILTER filter) {
358 return reinterpret_cast<LPTOP_LEVEL_EXCEPTION_FILTER>(
359 InterlockedExchangePointer(&title_fatal_filter, reinterpret_cast<void*>(filter)));
360}
361
362static LONG WINAPI save_caches_on_fatal_exception(EXCEPTION_POINTERS* info) {
363 const DWORD code = info && info->ExceptionRecord ? info->ExceptionRecord->ExceptionCode : 0;
364 if (code != EXCEPTION_STACK_OVERFLOW) {
365 // Several title threads can fault at once (measured: eight within a second). The first writes; the others
366 // wait here for it, so none of them reaches the title's filter, which may end the process, mid-write.
367 static std::once_flag once;
368 std::call_once(once, [code] {
369 std::fprintf(stderr, "[rt] unhandled exception 0x%08lx: writing the session pipeline cache before the "
370 "process ends\n", static_cast<unsigned long>(code));
371 rt::d3d12::stop_pipeline_compiles(kExitCompileWaitMs);
372 rt::d3d12::save_pipeline_caches_at_exit(kExitCacheWaitMs);
373 std::fflush(stderr);
374 });
375 }
376 if (auto* title = reinterpret_cast<LPTOP_LEVEL_EXCEPTION_FILTER>(
377 InterlockedCompareExchangePointer(&title_fatal_filter, nullptr, nullptr)))
378 return title(info);
379 return previous_fatal_filter ? previous_fatal_filter(info) : EXCEPTION_CONTINUE_SEARCH;
380}
381
243static BOOL WINAPI show_package_window(HWND window, int command) { 382static BOOL WINAPI show_package_window(HWND window, int command) {
244 const BOOL previous = ShowWindow(window, command); 383 const BOOL previous = ShowWindow(window, command);
245 const DWORD error = GetLastError(); 384 const DWORD error = GetLastError();
@@ -251,6 +390,13 @@ static BOOL WINAPI show_package_window(HWND window, int command) {
251#endif 390#endif
252 391
253int wmain(int argc, wchar_t** argv) { 392int wmain(int argc, wchar_t** argv) {
393#ifdef LEONIDA_VULKAN_DEVICE
394 if (argc > 1 && std::wstring(argv[1]) == L"--precompile-pipelines") return precompile_main(argc, argv);
395 if (argc > 1 && std::wstring(argv[1]) == L"--compile-server") return compile_server_main(argc, argv);
396#endif
397 // The title's process (not a build host above): LEONIDA_COMPILE_GATE=auto may calibrate the driver when the device
398 // is made (src/compile_gate_policy.h).
399 leonida::compile_gate_policy::calibration_allowed = true;
254 std::filesystem::path image, game_dir, overlay_dir, mods_dir; 400 std::filesystem::path image, game_dir, overlay_dir, mods_dir;
255 uint32_t archetype_lookup_rva = 0; // --archetype-lookup RVA[,ARG]: the game's archetype lookup by hash 401 uint32_t archetype_lookup_rva = 0; // --archetype-lookup RVA[,ARG]: the game's archetype lookup by hash
256 int archetype_lookup_arg = 0; 402 int archetype_lookup_arg = 0;
@@ -347,6 +493,13 @@ int wmain(int argc, wchar_t** argv) {
347 rt::fs::configure(game_dir, overlay_dir); 493 rt::fs::configure(game_dir, overlay_dir);
348#ifdef LEONIDA_VULKAN_DEVICE 494#ifdef LEONIDA_VULKAN_DEVICE
349 if (run) { 495 if (run) {
496 // Before the image is loaded, so its import binds here (save_caches_on_fatal_exception).
497 const rt::shims::Entry filter_imports[] = {
498 {"api-ms-win-core-errorhandling-l1-1-0.dll", "SetUnhandledExceptionFilter",
499 reinterpret_cast<void*>(&title_set_unhandled_exception_filter)},
500 {"kernel32.dll", "SetUnhandledExceptionFilter", reinterpret_cast<void*>(&title_set_unhandled_exception_filter)},
501 };
502 rt::shims::Table{filter_imports, std::size(filter_imports)};
350 rt::package_splash::configure(game_dir); 503 rt::package_splash::configure(game_dir);
351 if (rt::package_splash::configured()) { 504 if (rt::package_splash::configured()) {
352 const rt::shims::Entry window_imports[] = { 505 const rt::shims::Entry window_imports[] = {
@@ -388,11 +541,15 @@ int wmain(int argc, wchar_t** argv) {
388 rt::d3d12_trace::set_enabled(trace_d3d12); 541 rt::d3d12_trace::set_enabled(trace_d3d12);
389 // Slot 133 imports the title's pages; xmem commits them on first touch, so they are committed first. 542 // Slot 133 imports the title's pages; xmem commits them on first touch, so they are committed first.
390 rt::d3d12_xs::set_placed_at_va_pages_hook(&rt::xmem::commit_physical_range); 543 rt::d3d12_xs::set_placed_at_va_pages_hook(&rt::xmem::commit_physical_range);
544 if (rt::xmem::slot31_runs() && rt::xmem::queue_page_mappings_enabled())
545 rt::d3d12_xs::set_copy_page_mappings_hook(&rt::xmem::copy_page_mappings);
391 // So do the file shims' reads, whose kernel writes do not fault them in: on ERROR_NOACCESS (title_page_watch.h). 546 // So do the file shims' reads, whose kernel writes do not fault them in: on ERROR_NOACCESS (title_page_watch.h).
392 leonida::geometry_writes::aliases.store(&rt::xmem::geometry_aliases); 547 leonida::geometry_writes::aliases.store(&rt::xmem::geometry_aliases);
393 leonida::kernel_writes::set_committer(&rt::xmem::commit_physical_range); 548 leonida::kernel_writes::set_committer(&rt::xmem::commit_physical_range);
394 rt::d3d12_xs::set_texture_page_provider(&rt::xmem::pin_mapped_data); 549 rt::d3d12_xs::set_texture_page_provider(&rt::xmem::pin_mapped_data);
395 leonida::kernel_writes::set_unguarder(&rt::xmem::reopen_unowned); 550 leonida::kernel_writes::set_unguarder(&rt::xmem::reopen_unowned);
551 // The first call of a forwarded device slot names its caller as module+offset (RT-526).
552 rt::d3d12_xs::set_device_slot_caller_formatter(&rt::shims::module_offset);
396 if (int trace_error = 0; !trace_file.empty() && !rt::startup_trace::open(trace_file.c_str(), &trace_error)) { 553 if (int trace_error = 0; !trace_file.empty() && !rt::startup_trace::open(trace_file.c_str(), &trace_error)) {
397 std::fprintf(stderr, trace_error == EEXIST ? "error: the trace file already exists; --trace only creates a new file\n" 554 std::fprintf(stderr, trace_error == EEXIST ? "error: the trace file already exists; --trace only creates a new file\n"
398 : "error: cannot create the trace file\n"); 555 : "error: cannot create the trace file\n");
@@ -407,6 +564,30 @@ int wmain(int argc, wchar_t** argv) {
407 if (!rt::cpu_emulation::install()) 564 if (!rt::cpu_emulation::install())
408 std::fprintf(stderr, "[rt] cpu: AddVectoredExceptionHandler failed (error %lu); instructions this CPU lacks " 565 std::fprintf(stderr, "[rt] cpu: AddVectoredExceptionHandler failed (error %lu); instructions this CPU lacks "
409 "will stop the game\n", GetLastError()); 566 "will stop the game\n", GetLastError());
567 if (const auto bmi = rt::bmi_emulation::detect_host(); !bmi.bmi1 || !bmi.bmi2 || !bmi.lzcnt || !bmi.movbe)
568 std::fprintf(stderr, "[rt] cpu: this CPU lacks%s%s%s%s; the game's uses are emulated (docs/cpu_features.md)\n",
569 bmi.bmi1 ? "" : " BMI1", bmi.bmi2 ? "" : " BMI2", bmi.lzcnt ? "" : " LZCNT",
570 bmi.movbe ? "" : " MOVBE");
571 if (!rt::bmi_emulation::install())
572 std::fprintf(stderr, "[rt] cpu: AddVectoredExceptionHandler (BMI) failed (error %lu); instructions this CPU "
573 "lacks will stop the game\n", GetLastError());
574 if (const auto avx2 = rt::avx2_emulation::detect_host(); !avx2.avx2 || !avx2.fma || !avx2.f16c)
575 std::fprintf(stderr, "[rt] cpu: this CPU lacks%s%s%s; the game's uses are emulated (docs/cpu_features.md)\n",
576 avx2.avx2 ? "" : " AVX2", avx2.fma ? "" : " FMA3", avx2.f16c ? "" : " F16C");
577 if (!rt::avx2_emulation::install())
578 std::fprintf(stderr, "[rt] cpu: AddVectoredExceptionHandler (AVX2) failed (error %lu); instructions this CPU "
579 "lacks will stop the game\n", GetLastError());
580 // LEONIDA_SKIP_ASSERTS=N (src/assert_skip.h): up to N int3 in guest code are logged and stepped over. Off unless
581 // set; installed before the first TLS callback, the first image code that runs.
582 if (init || run)
583 if (const unsigned skip_asserts = rt::assert_skip::limit_from_environment()) {
584 if (rt::assert_skip::install(skip_asserts))
585 std::fprintf(stderr, "[rt] LEONIDA_SKIP_ASSERTS=%u: up to %u int3 in guest code are stepped over "
586 "(diagnostic)\n", skip_asserts, skip_asserts);
587 else
588 std::fprintf(stderr, "[rt] LEONIDA_SKIP_ASSERTS: AddVectoredExceptionHandler failed (error %lu); off\n",
589 GetLastError());
590 }
410 591
411 try { 592 try {
412 rt::Loader loader(game_dir); 593 rt::Loader loader(game_dir);
@@ -493,7 +674,9 @@ int wmain(int argc, wchar_t** argv) {
493 std::fprintf(stderr, "error: %s has no entry point\n", main_module.name.c_str()); 674 std::fprintf(stderr, "error: %s has no entry point\n", main_module.name.c_str());
494 return 1; 675 return 1;
495 } 676 }
496 const std::wstring paths = L"console paths: GAME: -> " + game_dir.native() + L", writes -> " + overlay_dir.native(); 677 const std::filesystem::path scratch_dir = rt::fs::scratch_dir();
678 const std::wstring paths = L"console paths: GAME: -> " + game_dir.native() + L", writes -> " +
679 overlay_dir.native() + L", T: -> " + scratch_dir.native();
497 const HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE); 680 const HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
498 DWORD mode; 681 DWORD mode;
499 bool printed = false; 682 bool printed = false;
@@ -506,18 +689,25 @@ int wmain(int argc, wchar_t** argv) {
506 if (!printed) { 689 if (!printed) {
507 const auto game = game_dir.u8string(); 690 const auto game = game_dir.u8string();
508 const auto overlay = overlay_dir.u8string(); 691 const auto overlay = overlay_dir.u8string();
509 std::printf("console paths: GAME: -> %s, writes -> %s\n", 692 const auto scratch = scratch_dir.u8string();
510 reinterpret_cast<const char*>(game.c_str()), reinterpret_cast<const char*>(overlay.c_str())); 693 std::printf("console paths: GAME: -> %s, writes -> %s, T: -> %s\n",
694 reinterpret_cast<const char*>(game.c_str()), reinterpret_cast<const char*>(overlay.c_str()),
695 reinterpret_cast<const char*>(scratch.c_str()));
511 } 696 }
512 std::printf("running %s\n", main_module.name.c_str()); 697 std::printf("running %s\n", main_module.name.c_str());
513 std::fflush(stdout); 698 std::fflush(stdout);
514 keep_title_watchdog_kicked(main_module.base); 699 keep_title_watchdog_kicked(main_module.base);
515 start_title_peek(main_module.base); 700 start_title_peek(main_module.base);
701 leonida::dev_overlay::start(); // LEONIDA_DEV_OVERLAY=1
516 leonida::thread_sampler::start(main_module.base, main_module.size); // LEONIDA_SAMPLE_MS (diagnostic) 702 leonida::thread_sampler::start(main_module.base, main_module.size); // LEONIDA_SAMPLE_MS (diagnostic)
517#ifdef LEONIDA_VULKAN_DEVICE 703#ifdef LEONIDA_VULKAN_DEVICE
518 SetConsoleCtrlHandler(&stop_compiles_on_console_exit, TRUE); 704 SetConsoleCtrlHandler(&stop_compiles_on_console_exit, TRUE);
705 previous_fatal_filter = SetUnhandledExceptionFilter(&save_caches_on_fatal_exception);
519#endif 706#endif
520 int code; 707 int code;
708#ifdef LEONIDA_VULKAN_DEVICE
709 leonida::thread_stack_hook.store(&rt::print_thread_stacks_now, std::memory_order_release);
710#endif
521 { 711 {
522 auto stacks = rt::start_thread_stacks(); 712 auto stacks = rt::start_thread_stacks();
523 code = rt::process::run_entry(main_module.base + main_module.entry_rva); 713 code = rt::process::run_entry(main_module.base + main_module.entry_rva);
@@ -536,6 +726,7 @@ int wmain(int argc, wchar_t** argv) {
536 rt::d3d12_xs::stop_list_values(500); 726 rt::d3d12_xs::stop_list_values(500);
537#ifdef LEONIDA_VULKAN_DEVICE 727#ifdef LEONIDA_VULKAN_DEVICE
538 rt::d3d12::stop_pipeline_compiles(kExitCompileWaitMs); 728 rt::d3d12::stop_pipeline_compiles(kExitCompileWaitMs);
729 rt::d3d12::save_pipeline_caches_at_exit(kExitCacheWaitMs);
539#endif 730#endif
540 rt::cleanup_tls_clones(); 731 rt::cleanup_tls_clones();
541 ExitProcess(static_cast<UINT>(code)); 732 ExitProcess(static_cast<UINT>(code));