From 2dca597bd9f143992032010037f2d5c3b970d312 Mon Sep 17 00:00:00 2001 From: Leonardo Guimaraes Date: Sun, 22 Nov 2026 01:24:50 -0300 Subject: Runtime: opt-in startup trace (gta6rt --trace FILE) Writes one JSON object per line, flushed per event: module maps, TLS callbacks, DllMain results, the first call of each unimplemented import with its caller as module+RVA, OutputDebugString text, exceptions with module+RVA and a short unwind, and the exit code. A vectored handler records and returns EXCEPTION_CONTINUE_SEARCH, so behaviour is unchanged. Off by default. startup_trace_test builds a synthetic DLL image (no game data) and checks each event kind. --- runtime/src/main.cpp | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) (limited to 'runtime/src/main.cpp') diff --git a/runtime/src/main.cpp b/runtime/src/main.cpp index 560f68349..5ac73301d 100644 --- a/runtime/src/main.cpp +++ b/runtime/src/main.cpp @@ -9,7 +9,7 @@ // gta6rt --init [--game-dir DIR] [--overlay DIR] // The same mapping, then each loaded DLL's TLS callbacks and DllMain(DLL_PROCESS_ATTACH) are run. // -// gta6rt --run [--game-dir DIR] [--overlay DIR] [--trace-d3d12] [-- game arguments...] +// gta6rt --run [--game-dir DIR] [--overlay DIR] [--trace-d3d12] [--trace FILE] [-- game arguments...] // The same, then the EXE's own TLS callbacks and its entry point, on a game thread. The game's argv and // command line are plus the arguments after "--"; exit/ExitProcess from the game end the run // (shims/process.cpp). gta6rt prints the binding report first and returns the game's exit code. @@ -29,6 +29,7 @@ #include "../shims/file_system.h" #include "../shims/process_shim.h" #include "../shims/shims.h" +#include "../shims/startup_trace.h" namespace { @@ -43,9 +44,9 @@ const char* binding_name(rt::Binding b) { int usage() { std::fprintf(stderr, - "usage: gta6rt --dry-run [--game-dir DIR] [--overlay DIR]\n" - " gta6rt --init [--game-dir DIR] [--overlay DIR] [--trace-d3d12]\n" - " gta6rt --run [--game-dir DIR] [--overlay DIR] [--trace-d3d12] [-- game arguments...]\n"); + "usage: gta6rt --dry-run [--game-dir DIR] [--overlay DIR] [--trace FILE]\n" + " gta6rt --init [--game-dir DIR] [--overlay DIR] [--trace-d3d12] [--trace FILE]\n" + " gta6rt --run [--game-dir DIR] [--overlay DIR] [--trace-d3d12] [--trace FILE] [-- game arguments...]\n"); return 2; } @@ -55,6 +56,7 @@ int wmain(int argc, wchar_t** argv) { std::filesystem::path image, game_dir, overlay_dir; bool dry_run = false, init = false, run = false, trace_d3d12 = false; std::vector game_args; // wide: path::string() throws on a character the code page lacks (RT-84) + std::wstring trace_file; for (int i = 1; i < argc; ++i) { std::wstring a = argv[i]; if (a == L"--") { @@ -65,6 +67,7 @@ int wmain(int argc, wchar_t** argv) { else if (a == L"--init") init = true; else if (a == L"--run") run = true; else if (a == L"--trace-d3d12") trace_d3d12 = true; + else if (a == L"--trace" && i + 1 < argc) trace_file = argv[++i]; else if (a == L"--game-dir" && i + 1 < argc) game_dir = argv[++i]; else if (a == L"--overlay" && i + 1 < argc) overlay_dir = argv[++i]; else if (image.empty()) image = a; @@ -82,6 +85,10 @@ int wmain(int argc, wchar_t** argv) { if (overlay_dir.empty()) overlay_dir = game_dir / "overlay"; rt::fs::configure(game_dir, overlay_dir); rt::d3d12_trace::set_enabled(trace_d3d12); + if (!trace_file.empty() && !rt::startup_trace::open(trace_file.c_str())) { + std::fprintf(stderr, "error: cannot open the trace file\n"); + return 2; + } try { rt::Loader loader(game_dir); @@ -112,7 +119,10 @@ int wmain(int argc, wchar_t** argv) { std::printf("%zu module(s) mapped, %d unimplemented import(s)\n", loader.modules().size(), unimplemented); std::printf("unimplemented by return policy: hresult=%d other=%d\n", unimplemented_hresult, unimplemented - unimplemented_hresult); - if (!run) return 0; + if (!run) { + rt::startup_trace::event("exit", "\"code\":0"); + return 0; + } if (!main_module.entry_rva) { std::fprintf(stderr, "error: %s has no entry point\n", main_module.name.c_str()); return 1; @@ -125,6 +135,7 @@ int wmain(int argc, wchar_t** argv) { std::fflush(stdout); std::printf("game exited with code %d\n", code); rt::shims::report_called_unimplemented(); + rt::startup_trace::event("exit", "\"code\":" + std::to_string(code)); std::fflush(stdout); std::fflush(stderr); // Not `return`: a normal host exit runs the CRT's atexit table, which the game shares with gta6rt (its @@ -132,6 +143,7 @@ int wmain(int argc, wchar_t** argv) { ExitProcess(static_cast(code)); } catch (const std::exception& e) { std::fprintf(stderr, "error: %s\n", e.what()); + rt::startup_trace::event("error", "\"what\":" + rt::startup_trace::quote(e.what())); return 1; } } -- cgit v1.2.3 From d6443b152469c467f6295889de855b2931095161 Mon Sep 17 00:00:00 2001 From: Leonardo Guimaraes Date: Sun, 22 Nov 2026 12:06:49 -0300 Subject: Startup trace: never replace an existing file; write UTF-8 only Review on #1756 (Vonsek): - The trace is opened before the loader reads the image, so `wb` could truncate an input named by mistake (the image itself). open() now uses "x" mode and fails with EEXIST on an existing path; gta6rt says so and exits with 2. - OutputDebugStringA text is in the ANSI code page. It is converted to UTF-8 before quoting, so a byte such as 0xE9 no longer breaks the JSON lines. Host module names now come from GetModuleFileNameW, converted to UTF-8, for the same reason. startup_trace_test: an existing file is refused with EEXIST and its bytes survive, the trace stays off; an ANSI debug string with 0xE9 appears as its UTF-8 form and the whole file is valid UTF-8. --- runtime/README.md | 5 ++++- runtime/shims/registry.cpp | 19 +++++++++++------ runtime/shims/startup_trace.h | 36 +++++++++++++++++++++++-------- runtime/src/main.cpp | 5 +++-- runtime/test/startup_trace_test.cpp | 42 +++++++++++++++++++++++++++++++++++++ 5 files changed, 89 insertions(+), 18 deletions(-) (limited to 'runtime/src/main.cpp') diff --git a/runtime/README.md b/runtime/README.md index 04c92f948..c5fc3678d 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -275,7 +275,10 @@ Share only the lines prefixed with `[d3d12-trace]`. Other runtime diagnostics ar ### Startup trace: `--trace FILE` `--trace FILE` (with `--dry-run`, `--init` or `--run`, before the `--` separator) writes one JSON object per line -to FILE, flushed per event so the file survives a crash ([shims/startup_trace.h](shims/startup_trace.h)): +to FILE, flushed per event so the file survives a crash ([shims/startup_trace.h](shims/startup_trace.h)). FILE must +not exist yet: the trace is created before the loader reads anything, so gta6rt refuses an existing path (exit code 2) +rather than risk truncating an input such as the image. The file is UTF-8; `OutputDebugStringA` text is converted +from the ANSI code page. | `kind` | When | Fields | |---|---|---| diff --git a/runtime/shims/registry.cpp b/runtime/shims/registry.cpp index 7681dbf89..d2d3613b8 100644 --- a/runtime/shims/registry.cpp +++ b/runtime/shims/registry.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include #include @@ -331,13 +332,19 @@ std::string module_offset(uint64_t address) { } } HMODULE host = nullptr; - if (GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, - reinterpret_cast(address), &host) && host) { - char path[MAX_PATH] = {}; - GetModuleFileNameA(host, path, MAX_PATH); - const char* slash = std::strrchr(path, '\\'); + if (GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + reinterpret_cast(address), &host) && host) { + // Wide, then UTF-8: the ANSI form would put code-page bytes into the trace's JSON lines. + wchar_t path[MAX_PATH] = {}; + const DWORD len = GetModuleFileNameW(host, path, MAX_PATH); + const wchar_t* slash = std::wcsrchr(path, L'\\'); + const wchar_t* file = slash ? slash + 1 : path; + const int wlen = len ? static_cast(path + len - file) : 0; + const int bytes = wlen > 0 ? WideCharToMultiByte(CP_UTF8, 0, file, wlen, nullptr, 0, nullptr, nullptr) : 0; + std::string name(bytes > 0 ? bytes : 0, '\0'); + if (bytes > 0) WideCharToMultiByte(CP_UTF8, 0, file, wlen, name.data(), bytes, nullptr, nullptr); std::snprintf(b, sizeof b, "+0x%llx", static_cast(address - reinterpret_cast(host))); - return std::string("host:") + (slash ? slash + 1 : path) + b; + return "host:" + name + b; } std::snprintf(b, sizeof b, "0x%llx", static_cast(address)); return b; diff --git a/runtime/shims/startup_trace.h b/runtime/shims/startup_trace.h index 323262314..392eb39c9 100644 --- a/runtime/shims/startup_trace.h +++ b/runtime/shims/startup_trace.h @@ -22,6 +22,7 @@ #include #include +#include #include #include #include @@ -121,20 +122,33 @@ inline std::string stack_from(const CONTEXT& start_context) { return out + "]"; } +inline std::string utf8_from_wide(const wchar_t* w, int len) { + const int bytes = len > 0 ? WideCharToMultiByte(CP_UTF8, 0, w, len, nullptr, 0, nullptr, nullptr) : 0; + std::string s(bytes > 0 ? bytes : 0, '\0'); + if (bytes > 0) WideCharToMultiByte(CP_UTF8, 0, w, len, s.data(), bytes, nullptr, nullptr); + return s; +} + +// OutputDebugStringA text is in the ANSI code page, not UTF-8: convert it, or a byte such as 0xE9 would land in the +// file as is and break the JSON lines for a strict UTF-8 reader. +inline std::string utf8_from_ansi(const char* a, int len) { + const int chars = len > 0 ? MultiByteToWideChar(CP_ACP, 0, a, len, nullptr, 0) : 0; + if (chars <= 0) return {}; + std::wstring w(static_cast(chars), L'\0'); + MultiByteToWideChar(CP_ACP, 0, a, len, w.data(), chars); + return utf8_from_wide(w.data(), chars); +} + inline std::string debug_text(const EXCEPTION_RECORD& r) { // Parameters: [0] length in characters including the terminator, [1] the string. if (r.NumberParameters < 2 || !r.ExceptionInformation[1]) return {}; const size_t n = static_cast(r.ExceptionInformation[0]); if (r.ExceptionCode == kDbgPrintWide) { const auto* w = reinterpret_cast(r.ExceptionInformation[1]); - const int len = static_cast(n ? n - 1 : wcslen(w)); - const int bytes = WideCharToMultiByte(CP_UTF8, 0, w, len, nullptr, 0, nullptr, nullptr); - std::string s(bytes > 0 ? bytes : 0, '\0'); - if (bytes > 0) WideCharToMultiByte(CP_UTF8, 0, w, len, s.data(), bytes, nullptr, nullptr); - return s; + return utf8_from_wide(w, static_cast(n ? n - 1 : wcslen(w))); } const auto* a = reinterpret_cast(r.ExceptionInformation[1]); - return std::string(a, n ? n - 1 : strlen(a)); + return utf8_from_ansi(a, static_cast(n ? n - 1 : strlen(a))); } inline LONG CALLBACK handler(EXCEPTION_POINTERS* info) { @@ -166,13 +180,17 @@ inline LONG CALLBACK handler(EXCEPTION_POINTERS* info) { } } // namespace detail -// Opens (truncates) the trace file and installs the exception handler. Returns false if the file cannot be opened. -inline bool open(const wchar_t* path) { +// Creates the trace file and installs the exception handler. The file must not exist yet ("x" mode): the trace is +// opened before the loader reads anything, so overwriting would let `--trace` destroy an input, such as the image +// itself. Returns false if the file exists or cannot be created; `error`, when given, receives the errno. +inline bool open(const wchar_t* path, int* error = nullptr) { { const std::lock_guard lock(detail::mutex); if (detail::file) return true; - if (_wfopen_s(&detail::file, path, L"wb") != 0 || !detail::file) { + const errno_t e = _wfopen_s(&detail::file, path, L"wxb"); + if (e != 0 || !detail::file) { detail::file = nullptr; + if (error) *error = e ? e : EINVAL; return false; } detail::start = std::chrono::steady_clock::now(); diff --git a/runtime/src/main.cpp b/runtime/src/main.cpp index 5ac73301d..06baae387 100644 --- a/runtime/src/main.cpp +++ b/runtime/src/main.cpp @@ -85,8 +85,9 @@ int wmain(int argc, wchar_t** argv) { if (overlay_dir.empty()) overlay_dir = game_dir / "overlay"; rt::fs::configure(game_dir, overlay_dir); rt::d3d12_trace::set_enabled(trace_d3d12); - if (!trace_file.empty() && !rt::startup_trace::open(trace_file.c_str())) { - std::fprintf(stderr, "error: cannot open the trace file\n"); + if (int trace_error = 0; !trace_file.empty() && !rt::startup_trace::open(trace_file.c_str(), &trace_error)) { + std::fprintf(stderr, trace_error == EEXIST ? "error: the trace file already exists; --trace only creates a new file\n" + : "error: cannot create the trace file\n"); return 2; } diff --git a/runtime/test/startup_trace_test.cpp b/runtime/test/startup_trace_test.cpp index ad9f82103..8df64680f 100644 --- a/runtime/test/startup_trace_test.cpp +++ b/runtime/test/startup_trace_test.cpp @@ -17,6 +17,7 @@ #include #include #include +#include #include #include #include @@ -50,6 +51,7 @@ constexpr uint32_t kCallRetOffset = 10; // sub rsp,0x28 (4) + call [ constexpr uint32_t kFaultRva = kTextRva + 0x220; constexpr const char* kImageName = "trace_image.bin"; constexpr const char* kDebugText = "leonida trace probe \"quoted\""; +constexpr const char* kAnsiText = "caf\xe9 probe"; // 0xE9: 'é' in code page 1252, never valid alone in UTF-8 uint32_t caller_rva(int i) { return kCallerBase + 0x10u * static_cast(i); } uint32_t return_rva(int i) { return caller_rva(i) + kCallRetOffset; } @@ -165,6 +167,39 @@ void test_disabled_is_silent() { check(rt::startup_trace::quote("a\"b\\c\n\x01") == "\"a\\\"b\\\\c\\n\\u0001\"", "JSON string escaping"); } +// --trace runs before the loader reads anything, so it must never replace an existing file (an input such as the +// image itself could be named by mistake): open() refuses it with EEXIST and leaves its bytes as they were. +void test_existing_file_is_kept(const fs::path& dir) { + const std::vector bytes = {'M', 'Z', 0x90, 0x00, 'k', 'e', 'e', 'p'}; + const fs::path existing = write_file(dir / "existing_input.bin", bytes); + int error = 0; + check(!rt::startup_trace::open(existing.c_str(), &error), "open() refuses a file that already exists"); + check(error == EEXIST, "the refusal reports EEXIST"); + check(!rt::startup_trace::enabled(), "the trace stays off after a refused open()"); + std::ifstream in(existing, std::ios::binary); + const std::vector after((std::istreambuf_iterator(in)), std::istreambuf_iterator()); + check(after == bytes, "the existing file's bytes survive"); +} + +// What a strict reader expects for OutputDebugStringA text: the ANSI code page converted to UTF-8. +std::string ansi_as_utf8(const char* a) { + const int len = static_cast(std::strlen(a)); + const int chars = MultiByteToWideChar(CP_ACP, 0, a, len, nullptr, 0); + std::wstring w(static_cast(chars), L'\0'); + MultiByteToWideChar(CP_ACP, 0, a, len, w.data(), chars); + const int bytes = WideCharToMultiByte(CP_UTF8, 0, w.data(), chars, nullptr, 0, nullptr, nullptr); + std::string s(static_cast(bytes), '\0'); + WideCharToMultiByte(CP_UTF8, 0, w.data(), chars, s.data(), bytes, nullptr, nullptr); + return s; +} + +bool valid_utf8(const fs::path& p) { + std::ifstream in(p, std::ios::binary); + const std::string all((std::istreambuf_iterator(in)), std::istreambuf_iterator()); + return all.empty() || + MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, all.data(), static_cast(all.size()), nullptr, 0) > 0; +} + void test_trace(const fs::path& dir) { const fs::path image = write_file(dir / kImageName, make_image()); const fs::path trace = dir / "trace.jsonl"; @@ -175,6 +210,7 @@ void test_trace(const fs::path& dir) { reinterpret_cast(m.base + caller_rva(0))(nullptr); // unimplemented import reinterpret_cast(m.base + caller_rva(0))(nullptr); // second call: no second event reinterpret_cast(m.base + caller_rva(1))(kDebugText); + reinterpret_cast(m.base + caller_rva(1))(kAnsiText); check(call_faulting(m.base + kFaultRva), "the access violation reached the test's handler"); rt::startup_trace::event("exit", "\"code\":0"); } @@ -200,6 +236,11 @@ void test_trace(const fs::path& dir) { const std::string* d = find_line(lines, "debug_string"); check(has(d, "\"text\":\"leonida trace probe \\\"quoted\\\"\""), "debug_string carries the escaped text"); + const std::string ansi = "\"text\":\"" + ansi_as_utf8(kAnsiText) + "\""; + bool ansi_found = false; + for (auto& l : lines) ansi_found |= l.find("\"kind\":\"debug_string\"") != std::string::npos && l.find(ansi) != std::string::npos; + check(ansi_found, "an ANSI debug string with a byte above 0x7f is written as UTF-8"); + check(valid_utf8(trace), "the whole trace is valid UTF-8"); const std::string* e = find_line(lines, "exception"); check(has(e, "\"code\":\"0xc0000005\""), "exception code"); @@ -216,6 +257,7 @@ int wmain() { try { const fs::path dir = test_dir(); test_disabled_is_silent(); + test_existing_file_is_kept(dir); test_trace(dir); std::error_code ec; fs::remove_all(dir, ec); -- cgit v1.2.3