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.cpp140
1 files changed, 135 insertions, 5 deletions
diff --git a/runtime/src/main.cpp b/runtime/src/main.cpp
index f01997775..4d483ed59 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]... [--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). See
17// 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>
@@ -148,6 +156,7 @@ void start_title_peek(std::uint8_t* base) {
148#include "mods.h" 156#include "mods.h"
149#include "pe_loader.h" 157#include "pe_loader.h"
150#include "thread_stacks.h" 158#include "thread_stacks.h"
159#include "dev_overlay.h"
151#include "thread_sampler.h" 160#include "thread_sampler.h"
152#include "title_page_watch.h" 161#include "title_page_watch.h"
153#include "title_geometry_watch.h" 162#include "title_geometry_watch.h"
@@ -155,7 +164,9 @@ void start_title_peek(std::uint8_t* base) {
155#include "../shims/d3d12_xs_device.h" 164#include "../shims/d3d12_xs_device.h"
156#include "../shims/file_system.h" 165#include "../shims/file_system.h"
157#ifdef LEONIDA_VULKAN_DEVICE 166#ifdef LEONIDA_VULKAN_DEVICE
167#include "vulkan_device_fault.h"
158#include "../shims/d3d12_compile_exit.h" 168#include "../shims/d3d12_compile_exit.h"
169#include "../shims/d3d12_precompile.h"
159#include "../shims/package_splash.h" 170#include "../shims/package_splash.h"
160#endif 171#endif
161#include "../shims/process_shim.h" 172#include "../shims/process_shim.h"
@@ -196,7 +207,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"}, 207 {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"}, 208 {L"LEONIDA_GRAPHICS_STAGE_LAYOUT", L"1"}, {L"LEONIDA_PIPELINE_COMPILE", L"on-demand"},
198 {L"LEONIDA_FRAME_PACING", L"1"}, 209 {L"LEONIDA_FRAME_PACING", L"1"},
199 {L"LEONIDA_KEYBOARD_PAD", L"always"}, 210 // Focused, not always: keys typed into another window must not press anything on a consent page.
211 // Scripted presses (LEONIDA_INPUT_SCRIPT) still run while the window is unfocused.
212 {L"LEONIDA_KEYBOARD_PAD", L"1"},
200 }; 213 };
201 for (const auto& setting : settings) { 214 for (const auto& setting : settings) {
202 if (!set_default(setting.name, setting.value)) return false; 215 if (!set_default(setting.name, setting.value)) return false;
@@ -221,25 +234,119 @@ 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" 234 "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" 235 " 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" 236 " 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"); 237 " 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"
238 " gta6rt --precompile-pipelines [--threads N] [--big-threads N] [--big-bytes N] [--all] [--smallest-first] [--limit N] [--min-bytes N] [--max-bytes N] [--filter PART]... [--list] [--via-helper]\n"
239 " gta6rt --compile-server [--parent PID] [--threads N] [--idle-threads N] [--idle-exit SECONDS]\n");
225 return 2; 240 return 2;
226} 241}
227 242
243#ifdef LEONIDA_VULKAN_DEVICE
244// gta6rt --precompile-pipelines ...: argv[1] is the mode.
245int precompile_main(int argc, wchar_t** argv) {
246 rt::d3d12::PrecompileOptions options;
247 const auto number = [&](int& i, auto& out) {
248 if (i + 1 >= argc) return false;
249 wchar_t* end = nullptr;
250 const unsigned long long v = std::wcstoull(argv[++i], &end, 10);
251 if (!end || *end) return false;
252 out = static_cast<std::remove_reference_t<decltype(out)>>(v);
253 return true;
254 };
255 for (int i = 2; i < argc; ++i) {
256 const std::wstring a = argv[i];
257 bool ok = true;
258 if (a == L"--threads") ok = number(i, options.threads);
259 else if (a == L"--big-threads") ok = number(i, options.big_threads);
260 else if (a == L"--big-bytes") ok = number(i, options.big_bytes);
261 else if (a == L"--limit") ok = number(i, options.limit);
262 else if (a == L"--min-bytes") ok = number(i, options.min_bytes);
263 else if (a == L"--max-bytes") ok = number(i, options.max_bytes);
264 else if (a == L"--all") options.rebuild = true;
265 else if (a == L"--smallest-first") options.smallest_first = true;
266 else if (a == L"--list") options.dry_run = true;
267 else if (a == L"--via-helper") options.via_helper = true;
268 else if (a == L"--filter" && i + 1 < argc) {
269 const std::wstring part = argv[++i];
270 options.filters.emplace_back(part.begin(), part.end()); // library names are ASCII
271 } else ok = false;
272 if (!ok) return usage();
273 }
274 return rt::d3d12::precompile_compute_pipelines(options);
275}
276
277// gta6rt --compile-server [--parent PID] [--threads N] [--idle-threads N] [--idle-exit SECONDS]
278// (shims/d3d12_compile_helper.h).
279int compile_server_main(int argc, wchar_t** argv) {
280 rt::d3d12::CompileServerOptions options;
281 for (int i = 2; i < argc; ++i) {
282 const std::wstring a = argv[i];
283 if (i + 1 >= argc) return usage();
284 wchar_t* end = nullptr;
285 const unsigned long long v = std::wcstoull(argv[++i], &end, 10);
286 if (!end || *end) return usage();
287 if (a == L"--parent") options.parent_pid = static_cast<unsigned long>(v);
288 else if (a == L"--threads") options.threads = static_cast<unsigned>(v);
289 else if (a == L"--idle-threads") options.idle_threads = static_cast<unsigned>(v);
290 else if (a == L"--idle-exit") options.idle_exit_s = static_cast<unsigned>(v);
291 else return usage();
292 }
293 return rt::d3d12::compile_server(options);
294}
295#endif
296
228} // namespace 297} // namespace
229 298
230#ifdef LEONIDA_VULKAN_DEVICE 299#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 300// 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). 301// 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 302constexpr unsigned kExitCompileWaitMs = 2000; // a console close gives the whole process 5 s
303// For a build still running on a title thread, then the session cache write (rt::d3d12::save_pipeline_caches_at_exit).
304constexpr unsigned kExitCacheWaitMs = 1000;
234 305
235static BOOL WINAPI stop_compiles_on_console_exit(DWORD event) { 306static BOOL WINAPI stop_compiles_on_console_exit(DWORD event) {
236 if (event == CTRL_C_EVENT || event == CTRL_BREAK_EVENT || event == CTRL_CLOSE_EVENT) { 307 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 308 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); 309 rt::d3d12::stop_pipeline_compiles(kExitCompileWaitMs);
310 rt::d3d12::save_pipeline_caches_at_exit(kExitCacheWaitMs);
239 } 311 }
240 return FALSE; // the next handler (the default one: ExitProcess) ends the process, as before 312 return FALSE; // the next handler (the default one: ExitProcess) ends the process, as before
241} 313}
242 314
315// A run that ends in an exception nothing handles (a fault in the title or one of its DLLs, the int3 after a device
316// loss) would otherwise keep none of the pipelines it compiled, and the next boot builds them all again. The device is
317// left alone apart from that write; the exception then goes on as before (the previous filter, or Windows' own
318// handling), so the exit code is the exception's. Not for a stack overflow: no stack is left to write with.
319static LPTOP_LEVEL_EXCEPTION_FILTER previous_fatal_filter = nullptr;
320// The retail title installs a filter of its own (SetUnhandledExceptionFilter from api-ms-win-core-errorhandling),
321// which replaced this one and ended the process without it (measured: a title fault at 354 s wrote nothing). Its
322// call is served here instead: this filter stays installed and hands the exception to the title's, as Windows would.
323static void* volatile title_fatal_filter = nullptr;
324
325static LPTOP_LEVEL_EXCEPTION_FILTER WINAPI title_set_unhandled_exception_filter(LPTOP_LEVEL_EXCEPTION_FILTER filter) {
326 return reinterpret_cast<LPTOP_LEVEL_EXCEPTION_FILTER>(
327 InterlockedExchangePointer(&title_fatal_filter, reinterpret_cast<void*>(filter)));
328}
329
330static LONG WINAPI save_caches_on_fatal_exception(EXCEPTION_POINTERS* info) {
331 const DWORD code = info && info->ExceptionRecord ? info->ExceptionRecord->ExceptionCode : 0;
332 if (code != EXCEPTION_STACK_OVERFLOW) {
333 // Several title threads can fault at once (measured: eight within a second). The first writes; the others
334 // wait here for it, so none of them reaches the title's filter, which may end the process, mid-write.
335 static std::once_flag once;
336 std::call_once(once, [code] {
337 std::fprintf(stderr, "[rt] unhandled exception 0x%08lx: writing the session pipeline cache before the "
338 "process ends\n", static_cast<unsigned long>(code));
339 rt::d3d12::stop_pipeline_compiles(kExitCompileWaitMs);
340 rt::d3d12::save_pipeline_caches_at_exit(kExitCacheWaitMs);
341 std::fflush(stderr);
342 });
343 }
344 if (auto* title = reinterpret_cast<LPTOP_LEVEL_EXCEPTION_FILTER>(
345 InterlockedCompareExchangePointer(&title_fatal_filter, nullptr, nullptr)))
346 return title(info);
347 return previous_fatal_filter ? previous_fatal_filter(info) : EXCEPTION_CONTINUE_SEARCH;
348}
349
243static BOOL WINAPI show_package_window(HWND window, int command) { 350static BOOL WINAPI show_package_window(HWND window, int command) {
244 const BOOL previous = ShowWindow(window, command); 351 const BOOL previous = ShowWindow(window, command);
245 const DWORD error = GetLastError(); 352 const DWORD error = GetLastError();
@@ -251,6 +358,10 @@ static BOOL WINAPI show_package_window(HWND window, int command) {
251#endif 358#endif
252 359
253int wmain(int argc, wchar_t** argv) { 360int wmain(int argc, wchar_t** argv) {
361#ifdef LEONIDA_VULKAN_DEVICE
362 if (argc > 1 && std::wstring(argv[1]) == L"--precompile-pipelines") return precompile_main(argc, argv);
363 if (argc > 1 && std::wstring(argv[1]) == L"--compile-server") return compile_server_main(argc, argv);
364#endif
254 std::filesystem::path image, game_dir, overlay_dir, mods_dir; 365 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 366 uint32_t archetype_lookup_rva = 0; // --archetype-lookup RVA[,ARG]: the game's archetype lookup by hash
256 int archetype_lookup_arg = 0; 367 int archetype_lookup_arg = 0;
@@ -347,6 +458,13 @@ int wmain(int argc, wchar_t** argv) {
347 rt::fs::configure(game_dir, overlay_dir); 458 rt::fs::configure(game_dir, overlay_dir);
348#ifdef LEONIDA_VULKAN_DEVICE 459#ifdef LEONIDA_VULKAN_DEVICE
349 if (run) { 460 if (run) {
461 // Before the image is loaded, so its import binds here (save_caches_on_fatal_exception).
462 const rt::shims::Entry filter_imports[] = {
463 {"api-ms-win-core-errorhandling-l1-1-0.dll", "SetUnhandledExceptionFilter",
464 reinterpret_cast<void*>(&title_set_unhandled_exception_filter)},
465 {"kernel32.dll", "SetUnhandledExceptionFilter", reinterpret_cast<void*>(&title_set_unhandled_exception_filter)},
466 };
467 rt::shims::Table{filter_imports, std::size(filter_imports)};
350 rt::package_splash::configure(game_dir); 468 rt::package_splash::configure(game_dir);
351 if (rt::package_splash::configured()) { 469 if (rt::package_splash::configured()) {
352 const rt::shims::Entry window_imports[] = { 470 const rt::shims::Entry window_imports[] = {
@@ -388,6 +506,8 @@ int wmain(int argc, wchar_t** argv) {
388 rt::d3d12_trace::set_enabled(trace_d3d12); 506 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. 507 // 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); 508 rt::d3d12_xs::set_placed_at_va_pages_hook(&rt::xmem::commit_physical_range);
509 if (rt::xmem::slot31_runs() && rt::xmem::queue_page_mappings_enabled())
510 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). 511 // 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); 512 leonida::geometry_writes::aliases.store(&rt::xmem::geometry_aliases);
393 leonida::kernel_writes::set_committer(&rt::xmem::commit_physical_range); 513 leonida::kernel_writes::set_committer(&rt::xmem::commit_physical_range);
@@ -493,7 +613,9 @@ int wmain(int argc, wchar_t** argv) {
493 std::fprintf(stderr, "error: %s has no entry point\n", main_module.name.c_str()); 613 std::fprintf(stderr, "error: %s has no entry point\n", main_module.name.c_str());
494 return 1; 614 return 1;
495 } 615 }
496 const std::wstring paths = L"console paths: GAME: -> " + game_dir.native() + L", writes -> " + overlay_dir.native(); 616 const std::filesystem::path scratch_dir = rt::fs::scratch_dir();
617 const std::wstring paths = L"console paths: GAME: -> " + game_dir.native() + L", writes -> " +
618 overlay_dir.native() + L", T: -> " + scratch_dir.native();
497 const HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE); 619 const HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
498 DWORD mode; 620 DWORD mode;
499 bool printed = false; 621 bool printed = false;
@@ -506,18 +628,25 @@ int wmain(int argc, wchar_t** argv) {
506 if (!printed) { 628 if (!printed) {
507 const auto game = game_dir.u8string(); 629 const auto game = game_dir.u8string();
508 const auto overlay = overlay_dir.u8string(); 630 const auto overlay = overlay_dir.u8string();
509 std::printf("console paths: GAME: -> %s, writes -> %s\n", 631 const auto scratch = scratch_dir.u8string();
510 reinterpret_cast<const char*>(game.c_str()), reinterpret_cast<const char*>(overlay.c_str())); 632 std::printf("console paths: GAME: -> %s, writes -> %s, T: -> %s\n",
633 reinterpret_cast<const char*>(game.c_str()), reinterpret_cast<const char*>(overlay.c_str()),
634 reinterpret_cast<const char*>(scratch.c_str()));
511 } 635 }
512 std::printf("running %s\n", main_module.name.c_str()); 636 std::printf("running %s\n", main_module.name.c_str());
513 std::fflush(stdout); 637 std::fflush(stdout);
514 keep_title_watchdog_kicked(main_module.base); 638 keep_title_watchdog_kicked(main_module.base);
515 start_title_peek(main_module.base); 639 start_title_peek(main_module.base);
640 leonida::dev_overlay::start(); // LEONIDA_DEV_OVERLAY=1
516 leonida::thread_sampler::start(main_module.base, main_module.size); // LEONIDA_SAMPLE_MS (diagnostic) 641 leonida::thread_sampler::start(main_module.base, main_module.size); // LEONIDA_SAMPLE_MS (diagnostic)
517#ifdef LEONIDA_VULKAN_DEVICE 642#ifdef LEONIDA_VULKAN_DEVICE
518 SetConsoleCtrlHandler(&stop_compiles_on_console_exit, TRUE); 643 SetConsoleCtrlHandler(&stop_compiles_on_console_exit, TRUE);
644 previous_fatal_filter = SetUnhandledExceptionFilter(&save_caches_on_fatal_exception);
519#endif 645#endif
520 int code; 646 int code;
647#ifdef LEONIDA_VULKAN_DEVICE
648 leonida::thread_stack_hook.store(&rt::print_thread_stacks_now, std::memory_order_release);
649#endif
521 { 650 {
522 auto stacks = rt::start_thread_stacks(); 651 auto stacks = rt::start_thread_stacks();
523 code = rt::process::run_entry(main_module.base + main_module.entry_rva); 652 code = rt::process::run_entry(main_module.base + main_module.entry_rva);
@@ -536,6 +665,7 @@ int wmain(int argc, wchar_t** argv) {
536 rt::d3d12_xs::stop_list_values(500); 665 rt::d3d12_xs::stop_list_values(500);
537#ifdef LEONIDA_VULKAN_DEVICE 666#ifdef LEONIDA_VULKAN_DEVICE
538 rt::d3d12::stop_pipeline_compiles(kExitCompileWaitMs); 667 rt::d3d12::stop_pipeline_compiles(kExitCompileWaitMs);
668 rt::d3d12::save_pipeline_caches_at_exit(kExitCacheWaitMs);
539#endif 669#endif
540 rt::cleanup_tls_clones(); 670 rt::cleanup_tls_clones();
541 ExitProcess(static_cast<UINT>(code)); 671 ExitProcess(static_cast<UINT>(code));