From b6299c9d825c9a03703a636f8205fb70c7028d60 Mon Sep 17 00:00:00 2001 From: AAyberkU <97833630+AAyberkU@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:04:13 +0300 Subject: process shim: the game thread that ends a run no longer exits the process before gta6rt finishes end_run signalled g_done and only then read g_running. run_entry wakes on g_done, closes it and clears g_running, so the game thread could read false and take the "run is already over" path: ExitProcess with the game's code while main.cpp was still printing "game exited with code N", reporting unimplemented imports, writing the trace "exit" event and cleaning up TLS clones. The exit code stayed right, but the lost line made run_startup_cmdline and the other checks that look for it flaky. end_run now reads g_running before it signals. g_running is set before the game thread starts and is cleared only after g_exited is claimed and g_done is set, so a read taken before the CAS is true for any thread that ends a live run. The exit during host shutdown (no run active) still calls ExitProcess, and so does an exit with no run started, which an "always park the CAS winner" fix would have hung. process_cmdline_test runs 50 entry points that return 77 on one CPU and fails (exit 77) without the fix. Co-Authored-By: Claude Opus 5.5 --- runtime/test/process_cmdline_test.cpp | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) (limited to 'runtime/test/process_cmdline_test.cpp') diff --git a/runtime/test/process_cmdline_test.cpp b/runtime/test/process_cmdline_test.cpp index 79aeed11b..a345c6ac5 100644 --- a/runtime/test/process_cmdline_test.cpp +++ b/runtime/test/process_cmdline_test.cpp @@ -204,6 +204,27 @@ int main() { } } + // The game thread that ends a run must park, not ExitProcess, even when run_entry has already returned and + // cleared the run: main.cpp still prints "game exited with code N" and cleans up after it. On one CPU the + // host preempts the game thread right after SetEvent(g_done), and Sleep lets the game thread run again before + // the next run starts. A thread that exits the process here ends this test with code 77 before its last line. + { + auto returns_77 = +[](void*) -> DWORD { return 77; }; + DWORD_PTR process_mask = 0, system_mask = 0; + GetProcessAffinityMask(GetCurrentProcess(), &process_mask, &system_mask); + SetProcessAffinityMask(GetCurrentProcess(), process_mask & (~process_mask + 1)); // its lowest CPU + for (int i = 0; i < 50; ++i) { + const int code = rt::process::run_entry(reinterpret_cast(returns_77), 64 << 10); + if (code != 77) { + std::fprintf(stderr, "FAIL run %d of an entry point returning 77 returned %d\n", i, code); + ++failures; + break; + } + Sleep(1); + } + SetProcessAffinityMask(GetCurrentProcess(), process_mask); + } + if (failures) return 1; std::printf("process_cmdline: GetCommandLineW parses back to __wargv, non-ASCII arguments intact (code page %u); " "the WinMain line and the kernelbase/API-set names are the game's\n", -- cgit v1.2.3 From 5cf3dafe3ec90e740f90bf73df9e4417143f5253 Mon Sep 17 00:00:00 2001 From: Hiiva <32042291+Hiiva@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:36:08 +0200 Subject: runtime: honor mapped executable argv startup modes (#6117) Squash-merged after diff review of PR #6117 --- docs/runtime_imports.md | 13 +++ runtime/CMakeLists.txt | 35 +++++++ runtime/shims/process.cpp | 118 ++++++++++++++++++--- runtime/shims/process_shim.h | 6 +- runtime/test/check_argv_modes.py | 138 +++++++++++++++++++++++++ runtime/test/check_startup_cmdline.cmake | 7 ++ runtime/test/fixtures/tiny_argv_modes.cpp | 63 +++++++++++ runtime/test/fixtures/tiny_startup_cmdline.cpp | 21 ++-- runtime/test/process_cmdline_test.cpp | 44 ++++++++ 9 files changed, 416 insertions(+), 29 deletions(-) create mode 100644 runtime/test/check_argv_modes.py create mode 100644 runtime/test/fixtures/tiny_argv_modes.cpp (limited to 'runtime/test/process_cmdline_test.cpp') diff --git a/docs/runtime_imports.md b/docs/runtime_imports.md index ae4dfd69e..b6ee0db7c 100644 --- a/docs/runtime_imports.md +++ b/docs/runtime_imports.md @@ -64,6 +64,19 @@ The process shim (`runtime/shims/process.cpp`) serves `ExitProcess` and `GetComm The shims added since account for the rest of the difference from the first version of the table. The UCRT's `_configure_narrow_argv`, `_configure_wide_argv`, `__p___argc`, `__p___wargv` and `abort` are served by `runtime/shims/process.cpp`, which is why almost every DLL gained one or two. The file-system calls listed in *Console paths and the write overlay* below (`CreateFile2`, `CopyFile2`, `CreateDirectoryW`, `FindFirstFileExW`, `SetFileAttributesW` and the rest) account for `msvcp140.dll`, `vcomp140.dll`, `Bink2Scarlett.dll`'s `CreateFile2` and part of the two HTTP clients. `winhttp.dll` is a module the shims own (*WinHTTP offline* below), so every `WinHttp*` import binds to it: 15 in `libHttpClient.GDK.dll` (all 16 but `WinHttpCrackUrl`) and 15 in `XCurl.dll` (all but `WinHttpQueryOption`). That is why the two HTTP clients moved the most: 11 to 26 and 9 to 24 shim imports. +The UCRT argv configuration imports honor the executable's startup mode. Each run starts with `argc == 0` and +null narrow/wide argument tables, while `GetCommandLineA/W` is already available to TLS and process-attach +callbacks. Default startup publishes unexpanded arguments for its chosen width. `setargv.obj` / `wsetargv.obj` +startup expands wildcard arguments against the host working directory, including quoted patterns; an unmatched +pattern stays literal. Narrow expansion searches the ACP-converted pattern and converts matching names back to +ACP, so its matches can differ from wide startup. The two widths retain independent tables, and the most recently +configured width sets the shared `argc`. `noarg.obj` leaves the initial tables null; later no-argument +configuration is a no-op that preserves existing pointers and counts. These are guest-owned tables, without +changing the host CRT's argument globals. This does not add console-path wildcard routing or change the legacy +`msvcrt!__getmainargs` wildcard policy. `run_argv_modes` compares the same six linker-selected MSVC fixtures +natively and through the loader; `run_startup_cmdline` also checks native preconfiguration and command-line +identity through attach and entry. + The six unique Xbox-specific imports (eight consumer/import pairs) are exactly the set recorded in [`d3d12_vulkan.md` ยง7](d3d12_vulkan.md#7-prior-art-and-measured-xbox-abi): diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 2ab8c7bc8..b80132074 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -622,6 +622,31 @@ if(BUILD_TESTING) RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$" ) endforeach() + # These linker-selected startup modes are specific to the MSVC CRT. + if(MSVC) + foreach(width a w) + foreach(mode default expand noargs) + set(target tiny_argv_${mode}_${width}) + add_executable(${target} test/fixtures/tiny_argv_modes.cpp) + target_compile_definitions(${target} PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(${target} PRIVATE /W4 /permissive- /utf-8) + if(width STREQUAL "w") + target_compile_definitions(${target} PRIVATE APP_WIDE) + endif() + if(mode STREQUAL "expand") + if(width STREQUAL "w") + target_link_options(${target} PRIVATE wsetargv.obj) + else() + target_link_options(${target} PRIVATE setargv.obj) + endif() + elseif(mode STREQUAL "noargs") + target_link_options(${target} PRIVATE noarg.obj) + endif() + set_target_properties(${target} PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$") + endforeach() + endforeach() + endif() add_executable(tiny_atexit test/fixtures/tiny_atexit.cpp) target_compile_definitions(tiny_atexit PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) target_compile_options(tiny_atexit PRIVATE /W4 /permissive- /utf-8) @@ -1059,6 +1084,16 @@ if(BUILD_TESTING) set_tests_properties(gameinput PROPERTIES DISABLED TRUE) endif() if(WIN32 AND TARGET gta6rt AND TARGET tiny_game) + if(TARGET tiny_argv_default_a AND NOT CMAKE_CROSSCOMPILING) + find_package(Python3 COMPONENTS Interpreter QUIET) + if(Python3_FOUND) + add_test(NAME run_argv_modes COMMAND "${Python3_EXECUTABLE}" -I + "${CMAKE_CURRENT_SOURCE_DIR}/test/check_argv_modes.py" + --loader "$" --fixtures "$" + --work-dir "${CMAKE_CURRENT_BINARY_DIR}") + set_tests_properties(run_argv_modes PROPERTIES TIMEOUT 90) + endif() + endif() add_test(NAME run_startup_cmdline COMMAND ${CMAKE_COMMAND} "-DLOADER=$" "-DGUEST=$" "-DRUNNER=${CMAKE_CROSSCOMPILING_EMULATOR}" -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_startup_cmdline.cmake") diff --git a/runtime/shims/process.cpp b/runtime/shims/process.cpp index 77bcde936..b66c2e590 100644 --- a/runtime/shims/process.cpp +++ b/runtime/shims/process.cpp @@ -2,7 +2,7 @@ // // `gta6rt --run` calls a mapped EXE's entry point inside the gta6rt process. The EXE's CRT startup asks for its // arguments and finally calls exit(); both go through the EXE's own import table, so they can be answered here: -// - argv/argc and the command line are the game's (set by run_entry), not gta6rt's; +// - the command line is the game's, and its CRT configures its own argv/argc at startup; // - exit(), _exit(), quick_exit(), ExitProcess() and abort() from the game end the game's run, not the host: // the exit code is recorded, the run is signalled as finished and the calling thread waits for the host to // exit; @@ -22,10 +22,12 @@ #include #include +#include #include #include #include #include +#include #include #include #include @@ -38,6 +40,8 @@ namespace rt::process { namespace { +std::vector g_input_args; +std::vector g_input_wargs; std::vector g_args; std::vector g_wargs; std::vector g_argv; @@ -186,7 +190,86 @@ void __cdecl game_abort() { int* __cdecl game_p_argc() { return &g_argc; } char*** __cdecl game_p_argv() { return &g_argv_ptr; } wchar_t*** __cdecl game_p_wargv() { return &g_wargv_ptr; } -int __cdecl game_configure_argv(int) { return 0; } // already parsed: run_entry set them + +std::wstring widen_argument(const std::string& text) { + const int size = MultiByteToWideChar(CP_ACP, 0, text.c_str(), -1, nullptr, 0); + std::wstring wide(size > 0 ? static_cast(size - 1) : 0, L'\0'); + if (size > 1) MultiByteToWideChar(CP_ACP, 0, text.c_str(), -1, wide.data(), size); + return wide; +} + +// UCRT startup expands each wildcard argument against the host working directory, even when the argument was +// quoted. A failed search retains the pattern; a successful search omits "." and ".." and keeps the path prefix. +// Narrow startup searches its ACP-converted text, which can have different wildcard matches from wide startup. +template +std::vector> expand_arguments(const std::vector>& input) { + std::vector> result; + for (const auto& argument : input) { + std::wstring pattern; + if constexpr (std::is_same_v) pattern = argument; + else pattern = widen_argument(argument); + const size_t wildcard = pattern.find_first_of(L"*?"); + if (wildcard == std::wstring::npos) { + result.push_back(argument); + continue; + } + const size_t separator = pattern.find_last_of(L"\\/:", wildcard); + if (separator != std::wstring::npos && pattern[separator] == L':' && separator != 1) { + result.push_back(argument); + continue; + } + WIN32_FIND_DATAW found{}; + const HANDLE handle = ::FindFirstFileExW(pattern.c_str(), FindExInfoStandard, &found, + FindExSearchNameMatch, nullptr, 0); + if (handle == INVALID_HANDLE_VALUE) { + result.push_back(argument); + continue; + } + struct Search { + HANDLE handle; + ~Search() { ::FindClose(handle); } + } search{handle}; + const std::wstring prefix = pattern.substr(0, separator == std::wstring::npos ? 0 : separator + 1); + do { + if (std::wcscmp(found.cFileName, L".") == 0 || std::wcscmp(found.cFileName, L"..") == 0) continue; + const std::wstring match = prefix + found.cFileName; + if constexpr (std::is_same_v) result.push_back(match); + else result.push_back(narrow(match)); + } while (::FindNextFileW(handle, &found)); + } + return result; +} + +template +int configure_argv(int mode, const std::vector>& input, + std::vector>& strings, std::vector& pointers, C**& published) { + // _crt_argv_no_arguments is a no-op, including after another width or mode has been configured. + if (mode == 0) return 0; + if (mode != 1 && mode != 2) return errno = EINVAL; + try { + auto next_strings = mode == 2 ? expand_arguments(input) : input; + std::vector next_pointers; + next_pointers.reserve(next_strings.size() + 1); + for (auto& argument : next_strings) next_pointers.push_back(argument.data()); + next_pointers.push_back(nullptr); + // Publish only after every allocation succeeds. The other width keeps its own strings and pointer table. + strings.swap(next_strings); + pointers.swap(next_pointers); + published = pointers.data(); + g_argc = static_cast(strings.size()); + return 0; + } catch (const std::bad_alloc&) { + return errno = ENOMEM; + } +} + +int __cdecl game_configure_narrow_argv(int mode) { + return configure_argv(mode, g_input_args, g_args, g_argv, g_argv_ptr); +} +int __cdecl game_configure_wide_argv(int mode) { + return configure_argv(mode, g_input_wargs, g_wargs, g_wargv, g_wargv_ptr); +} + LPSTR __stdcall game_get_command_line_a() { return g_cmdline.data(); } LPWSTR __stdcall game_get_command_line_w() { return g_wcmdline.data(); } char** __cdecl game_p_acmdln_storage() { @@ -243,12 +326,14 @@ wchar_t** current_wide_environment() { // msvcrt.dll: int __getmainargs(int* argc, char*** argv, char*** env, int expand, void* startinfo) int __cdecl game_getmainargs(int* argc, char*** argv, char*** env, int, void*) { + if (const int error = game_configure_narrow_argv(1)) return error; *argc = g_argc; *argv = g_argv_ptr; if (env) *env = current_environment(); return 0; } int __cdecl game_wgetmainargs(int* argc, wchar_t*** argv, wchar_t*** env, int, void*) { + if (const int error = game_configure_wide_argv(1)) return error; *argc = g_argc; *argv = g_wargv_ptr; if (env) *env = current_wide_environment(); @@ -270,26 +355,25 @@ DWORD WINAPI game_thread(void* p) { } // namespace void set_command_line(const std::wstring& program, const std::vector& args) { - g_wargs.clear(); - g_wargs.push_back(program); - g_wargs.insert(g_wargs.end(), args.begin(), args.end()); - g_args.clear(); + g_input_wargs.clear(); + g_input_wargs.push_back(program); + g_input_wargs.insert(g_input_wargs.end(), args.begin(), args.end()); + g_input_args.clear(); g_wcmdline.clear(); - for (auto& a : g_wargs) { - g_args.push_back(narrow(a)); + for (const auto& a : g_input_wargs) { + g_input_args.push_back(narrow(a)); if (!g_wcmdline.empty()) g_wcmdline += L' '; g_wcmdline += quote(a); } g_cmdline = narrow(g_wcmdline); + // GetCommandLine is available before TLS/DllMain, but CRT argv starts unconfigured on every run. + g_args.clear(); + g_wargs.clear(); g_argv.clear(); g_wargv.clear(); - for (auto& a : g_args) g_argv.push_back(a.data()); - for (auto& a : g_wargs) g_wargv.push_back(a.data()); - g_argv.push_back(nullptr); - g_wargv.push_back(nullptr); - g_argc = static_cast(g_args.size()); - g_argv_ptr = g_argv.data(); - g_wargv_ptr = g_wargv.data(); + g_argc = 0; + g_argv_ptr = nullptr; + g_wargv_ptr = nullptr; } int run_entry(void* entry, size_t stack_bytes) { @@ -345,8 +429,8 @@ using namespace rt::process; {dll, "abort", reinterpret_cast(&game_abort)}, {dll, "__p___argc", reinterpret_cast(&game_p_argc)}, \ {dll, "__p___argv", reinterpret_cast(&game_p_argv)}, \ {dll, "__p___wargv", reinterpret_cast(&game_p_wargv)}, \ - {dll, "_configure_narrow_argv", reinterpret_cast(&game_configure_argv)}, \ - {dll, "_configure_wide_argv", reinterpret_cast(&game_configure_argv)}, \ + {dll, "_configure_narrow_argv", reinterpret_cast(&game_configure_narrow_argv)}, \ + {dll, "_configure_wide_argv", reinterpret_cast(&game_configure_wide_argv)}, \ {dll, "__p__acmdln", reinterpret_cast(&game_p_acmdln_storage)}, \ {dll, "__p__wcmdln", reinterpret_cast(&game_p_wcmdln_storage)}, \ {dll, "_get_narrow_winmain_command_line", reinterpret_cast(&game_get_narrow_winmain_command_line)}, \ diff --git a/runtime/shims/process_shim.h b/runtime/shims/process_shim.h index 21969bdcf..f6946719b 100644 --- a/runtime/shims/process_shim.h +++ b/runtime/shims/process_shim.h @@ -6,9 +6,9 @@ namespace rt::process { -// What the game sees as argv[0..] and GetCommandLine: `program` then `args`, quoted where needed. The wide forms -// (__wargv, GetCommandLineW) hold the arguments exactly; the narrow ones are their ANSI code page text, with a -// character the code page can't represent replaced as the CRT does (RT-84). +// Set GetCommandLine to `program` then `args`, quoted where needed, before process-attach callbacks. The wide text +// holds the arguments exactly; the narrow text uses the ANSI code page (RT-84). Reset CRT argv to argc=0/null: +// its startup configuration selects no arguments, the original arguments, or wildcard expansion for each width. void set_command_line(const std::wstring& program, const std::vector& args); // Runs a mapped EXE's entry point on a new thread with `stack_bytes` of reserved stack and returns the game's diff --git a/runtime/test/check_argv_modes.py b/runtime/test/check_argv_modes.py new file mode 100644 index 000000000..649ab2f97 --- /dev/null +++ b/runtime/test/check_argv_modes.py @@ -0,0 +1,138 @@ +"""Compare real MSVC argv startup modes natively and through the PE loader. + +Each fixture is linked with the default, setargv/wsetargv, or noarg option. +Raw Windows command lines retain quoted wildcard cases and identical argv[0]. +All files are synthetic; the active code page's native result is the oracle. +""" + +import argparse +import ctypes +import json +import os +from pathlib import Path +import re +import subprocess +import tempfile + + +def run(executable, command, cwd, environment): + result = subprocess.run( + command, executable=executable, cwd=cwd, env=environment, + capture_output=True, timeout=15, + ) + output = result.stdout.decode("utf-8", "replace") + return { + "command": command, + "exit_code": result.returncode, + "lines": [line for line in output.splitlines() + if line.startswith(("STATE ", "NOOP ", "CONFIG "))], + "stdout": output, + "stderr": result.stderr.decode("utf-8", "replace"), + } + + +def entry_count(lines): + if not lines: + return None + match = re.fullmatch(r"STATE entry argc=(\d+) A=.* W=.*", lines[0]) + return int(match[1]) if match else None + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--loader", type=Path, required=True) + parser.add_argument("--fixtures", type=Path, required=True) + parser.add_argument("--work-dir", type=Path, required=True) + parser.add_argument("--report", type=Path, help="optional retained JSON evidence") + args = parser.parse_args() + if os.name != "nt": + parser.error("this native MSVC startup comparison requires Windows") + loader = args.loader.resolve(strict=True) + fixtures = args.fixtures.resolve(strict=True) + work_dir = args.work_dir.resolve(strict=True) + rows = [] + failures = [] + tails = { + "plain": "data/*.txt literal", + "quoted": '"data/*.txt" literal', + "unmatched": "data/*.missing literal", + "empty": "empty/* literal", + "space": '"space dir/*.txt" literal', + "encoding": "unicode/\u6f22*.txt literal", + "sequence": "data/*.txt literal", + } + with tempfile.TemporaryDirectory(prefix="argv_modes_", dir=work_dir) as temporary: + root = Path(temporary) + for directory in ("data", "empty", "space dir", "unicode", "package"): + (root / directory).mkdir() + for name in ("data/a.txt", "data/b.txt", "data/c.bin", + "space dir/a.txt", "space dir/b.txt", + "unicode/A-only.txt", "unicode/\u6f22-only.txt"): + (root / name).write_text("synthetic\n", encoding="utf-8", newline="\n") + for width in ("a", "w"): + for mode in ("default", "expand", "noargs"): + guest = (fixtures / f"tiny_argv_{mode}_{width}.exe").resolve(strict=True) + cases = ["plain", "quoted", "unmatched"] + if mode == "expand": + cases += ["empty", "space", "encoding"] + if mode == "noargs": + cases += ["sequence"] + native_plain = None + for case in cases: + label = f"{width}/{mode}/{case}" + environment = os.environ.copy() + environment.pop("LEONIDA_GAME_DIR", None) + environment.pop("LEONIDA_ARGV_SEQUENCE", None) + if case == "sequence": + environment["LEONIDA_ARGV_SEQUENCE"] = "1" + native_command = subprocess.list2cmdline([guest.name]) + " " + tails[case] + mapped_command = subprocess.list2cmdline([ + loader.name, "--run", str(guest), "--game-dir", str(root / "package"), + "--overlay", str(root / "overlay"), + ]) + " -- " + tails[case] + native = run(guest, native_command, root, environment) + mapped = run(loader, mapped_command, root, environment) + problems = [] + for route, result in (("native", native), ("mapped", mapped)): + if result["exit_code"] != 0 or entry_count(result["lines"]) is None: + problems.append(f"{route} did not complete its fixture") + expected = 0 if mode == "noargs" else 3 + if mode == "expand" and case in ("plain", "quoted", "space"): + expected = 4 + if case != "encoding" and case != "empty": + if entry_count(native["lines"]) != expected: + problems.append(f"native fixture did not produce argc={expected}") + if mode == "noargs" and native["lines"] and native["lines"][0] != "STATE entry argc=0 A=null W=null": + problems.append("native noarg fixture did not start unconfigured") + if case == "plain": + native_plain = native["lines"] + if case == "quoted" and native["lines"] != native_plain: + problems.append("native quoted wildcard differs from unquoted") + if case == "sequence": + noops = [line for line in native["lines"] if line.startswith("NOOP ")] + configs = [line for line in native["lines"] if line.startswith("CONFIG ")] + if len(noops) != 6 or any(not line.endswith("status=0 unchanged=1") for line in noops): + problems.append("native no-argument reconfiguration changed state") + if len(configs) != 4 or any(not line.endswith("status=0") for line in configs): + problems.append("native reconfiguration did not succeed") + if native["lines"] != mapped["lines"]: + problems.append("mapped argv state differs from native") + if "game exited with code 0" not in mapped["stdout"]: + problems.append("loader did not report a completed guest run") + if problems: + failures.append(label + ": " + "; ".join(problems)) + print("FAIL " + failures[-1], flush=True) + print(" native: " + repr(native["lines"]), flush=True) + print(" mapped: " + repr(mapped["lines"]), flush=True) + rows.append({"case": label, "native": native, "mapped": mapped, "problems": problems}) + if any((root / "package").iterdir()): + failures.append("the synthetic package was modified") + report = {"acp": ctypes.windll.kernel32.GetACP(), "pairs": len(rows), "failures": failures, "rows": rows} + if args.report: + args.report.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8", newline="\n") + print(f"argv modes: {len(rows)} native/mapped pairs, {len(failures)} failures, ACP {report['acp']}") + return int(bool(failures)) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/runtime/test/check_startup_cmdline.cmake b/runtime/test/check_startup_cmdline.cmake index 1a2d08c36..d2c315f03 100644 --- a/runtime/test/check_startup_cmdline.cmake +++ b/runtime/test/check_startup_cmdline.cmake @@ -5,6 +5,13 @@ foreach(mode args no_args fail_init) elseif(mode STREQUAL "fail_init") set(args fail-init) endif() + if(NOT mode STREQUAL "fail_init") + execute_process(COMMAND ${RUNNER} "${GUEST}" ${args} TIMEOUT 90 + RESULT_VARIABLE native_code OUTPUT_VARIABLE native_output ERROR_VARIABLE native_error) + if(NOT native_code STREQUAL "0" OR NOT native_output MATCHES "tiny_startup_cmdline: PASS") + message(FATAL_ERROR "Native startup command line (${mode}) returned ${native_code}\n${native_output}\n${native_error}") + endif() + endif() execute_process( COMMAND ${RUNNER} "${LOADER}" --run "${GUEST}" -- ${args} TIMEOUT 90 diff --git a/runtime/test/fixtures/tiny_argv_modes.cpp b/runtime/test/fixtures/tiny_argv_modes.cpp new file mode 100644 index 000000000..a1c90da17 --- /dev/null +++ b/runtime/test/fixtures/tiny_argv_modes.cpp @@ -0,0 +1,63 @@ +// Original fixture linked with the real MSVC default, setargv/wsetargv, and noarg startup options. +// The optional sequence checks later configuration and no-op pointer identity in the same process. +#include +#include +#include +#include +#include + +namespace { +template void dump(C** values) { + if (!values) { std::printf("null"); return; } + for (size_t i = 0; values[i]; ++i) { + std::printf("["); + for (const C* p = values[i]; *p; ++p) { + using U = std::make_unsigned_t; + std::printf(sizeof(C) == 1 ? "%02X" : "%04X", static_cast(static_cast(*p))); + } + std::printf("]"); + } +} +void snapshot(const char* label) { + std::printf("STATE %s argc=%d A=", label, *__p___argc()); + dump(*__p___argv()); + std::printf(" W="); + dump(*__p___wargv()); + std::puts(""); +} +void no_op(bool wide) { + const int argc = *__p___argc(); + char** a = *__p___argv(); + wchar_t** w = *__p___wargv(); + const int status = wide ? _configure_wide_argv(_crt_argv_no_arguments) + : _configure_narrow_argv(_crt_argv_no_arguments); + std::printf("NOOP %c status=%d unchanged=%u\n", wide ? 'W' : 'A', status, + static_cast(argc == *__p___argc() && a == *__p___argv() && w == *__p___wargv())); +} +int body() { + snapshot("entry"); + if (GetEnvironmentVariableW(L"LEONIDA_ARGV_SEQUENCE", nullptr, 0)) { + no_op(false); no_op(true); snapshot("initial-noops"); + std::printf("CONFIG A2 status=%d\n", _configure_narrow_argv(_crt_argv_expanded_arguments)); + snapshot("A2"); no_op(false); snapshot("A2-noop"); + std::printf("CONFIG W1 status=%d\n", _configure_wide_argv(_crt_argv_unexpanded_arguments)); + snapshot("W1"); no_op(true); snapshot("W1-noop"); + std::printf("CONFIG A1 status=%d\n", _configure_narrow_argv(_crt_argv_unexpanded_arguments)); + snapshot("A1"); + std::printf("CONFIG W2 status=%d\n", _configure_wide_argv(_crt_argv_expanded_arguments)); + snapshot("W2"); no_op(false); no_op(true); snapshot("final-noops"); + } + return 0; +} +} +#ifdef APP_WIDE +int wmain(int argc, wchar_t** argv) { + if (argc != *__p___argc() || argv != *__p___wargv()) return 3; + return body(); +} +#else +int main(int argc, char** argv) { + if (argc != *__p___argc() || argv != *__p___argv()) return 3; + return body(); +} +#endif diff --git a/runtime/test/fixtures/tiny_startup_cmdline.cpp b/runtime/test/fixtures/tiny_startup_cmdline.cpp index ac0de4364..b04529179 100644 --- a/runtime/test/fixtures/tiny_startup_cmdline.cpp +++ b/runtime/test/fixtures/tiny_startup_cmdline.cpp @@ -1,4 +1,4 @@ -// Synthetic startup fixture: process-attach callbacks must see the entry point's command line. +// Synthetic startup fixture: process-attach callbacks see the command line before CRT argv is configured. #include #include @@ -10,6 +10,8 @@ namespace { struct Snapshot { int argc; + bool has_argv; + bool has_wargv; char argv[8][256]; wchar_t wargv[8][256]; char line[2048]; @@ -32,18 +34,19 @@ bool capture(Snapshot& s) { s.argc = *__p___argc(); char** args = *__p___argv(); wchar_t** wargs = *__p___wargv(); - if (s.argc < 1 || s.argc > 8 || !args || !wargs) return false; + s.has_argv = args != nullptr; + s.has_wargv = wargs != nullptr; + if (s.argc < 0 || s.argc > 8) return false; for (int i = 0; i < s.argc; ++i) - if (!copy(s.argv[i], args[i]) || !copy(s.wargv[i], wargs[i])) return false; - return !args[s.argc] && !wargs[s.argc] && copy(s.line, GetCommandLineA()) && + if ((args && !copy(s.argv[i], args[i])) || (wargs && !copy(s.wargv[i], wargs[i]))) return false; + return (!args || !args[s.argc]) && (!wargs || !wargs[s.argc]) && copy(s.line, GetCommandLineA()) && copy(s.wline, GetCommandLineW()); } bool matches(const Snapshot& a, const Snapshot& b) { - if (a.argc != b.argc || std::strcmp(a.line, b.line) || std::wcscmp(a.wline, b.wline)) return false; - for (int i = 0; i < a.argc; ++i) - if (std::strcmp(a.argv[i], b.argv[i]) || std::wcscmp(a.wargv[i], b.wargv[i])) return false; - return true; + // Native UCRT has not configured either argv width at process attach. GetCommandLine is already complete. + return a.argc == 0 && !a.has_argv && !a.has_wargv && + std::strcmp(a.line, b.line) == 0 && std::wcscmp(a.wline, b.wline) == 0; } } // namespace @@ -80,7 +83,7 @@ extern "C" __declspec(allocate(".CRT$XLB")) PIMAGE_TLS_CALLBACK g_startup_callba int main(int argc, char** argv) { Snapshot entry{}; bool ok = capture(entry) && g_captured && matches(g_startup, entry) && startup_cmdline_matches(&entry); - ok = ok && argc == entry.argc; + ok = ok && argc == entry.argc && entry.has_argv && !entry.has_wargv; for (int i = 0; ok && i < argc; ++i) ok = std::strcmp(argv[i], entry.argv[i]) == 0; std::printf("tiny_startup_cmdline: %s\n", ok ? "PASS" : "FAIL"); return ok ? 0 : 1; diff --git a/runtime/test/process_cmdline_test.cpp b/runtime/test/process_cmdline_test.cpp index a345c6ac5..fb0a0498c 100644 --- a/runtime/test/process_cmdline_test.cpp +++ b/runtime/test/process_cmdline_test.cpp @@ -28,8 +28,23 @@ char** argv() { return *reinterpret_cast(rt::shims::find("ucrtbase.dll", "__p___argv"))(); } +int configure(bool wide, int mode) { + using Fn = int(__cdecl*)(int); + const auto fn = reinterpret_cast(rt::shims::find( + "ucrtbase.dll", wide ? "_configure_wide_argv" : "_configure_narrow_argv")); + if (fn) return fn(mode); + std::fprintf(stderr, "FAIL missing argv configuration shim\n"); + ++failures; + return -1; +} + void round_trip(const std::vector& args, const char* what) { rt::process::set_command_line(L"game.exe", args); + if (configure(false, 1) || configure(true, 1)) { + std::fprintf(stderr, "FAIL %s: unexpanded argv configuration\n", what); + ++failures; + return; + } using Fn = LPWSTR(WINAPI*)(); const LPWSTR line = reinterpret_cast(rt::shims::find("kernel32.dll", "GetCommandLineW"))(); int count = 0; @@ -43,6 +58,34 @@ void round_trip(const std::vector& args, const char* what) { LocalFree(parsed); } +void check_argv_reset() { + const int host_argc = __argc; + char** const host_argv = __argv; + wchar_t** const host_wargv = __wargv; + using Argc = int*(__cdecl*)(); + const auto count = reinterpret_cast(rt::shims::find("ucrtbase.dll", "__p___argc")); + auto check = [](bool ok, const char* what) { + if (!ok) { std::fprintf(stderr, "FAIL argv state: %s\n", what); ++failures; } + }; + rt::process::set_command_line(L"first.exe", {L"one", L"two"}); + check(*count() == 0 && !argv() && !wargv(), "new run starts unconfigured"); + check(configure(false, 0) == 0 && configure(true, 0) == 0 && *count() == 0 && !argv() && !wargv(), + "no-argument startup leaves the initial state alone"); + check(configure(false, 1) == 0 && *count() == 3 && argv() && !wargv(), "configure only narrow argv"); + char** const narrow = argv(); + check(configure(true, 1) == 0 && *count() == 3 && argv() == narrow && wargv(), + "wide configuration retains the narrow table"); + wchar_t** const wide = wargv(); + check(configure(false, 0) == 0 && configure(true, 0) == 0 && *count() == 3 && argv() == narrow && wargv() == wide, + "no-argument mode preserves configured counts and pointers"); + rt::process::set_command_line(L"second.exe", {L"new"}); + check(*count() == 0 && !argv() && !wargv(), "another run forgets both configured widths"); + check(configure(true, 1) == 0 && *count() == 2 && !argv() && wargv() && + std::wcscmp(wargv()[0], L"second.exe") == 0 && std::wcscmp(wargv()[1], L"new") == 0 && !wargv()[2], + "the new run configures its own program name and arguments"); + check(__argc == host_argc && __argv == host_argv && __wargv == host_wargv, "host CRT argument globals are untouched"); +} + // __wargv[1] must be `want` exactly, and the narrow argv[1] its ANSI code page text (the CRT's replacement for a // character the code page lacks), not a crash. void check_non_ascii(const std::wstring& want, const char* what) { @@ -186,6 +229,7 @@ int main() { check_non_ascii(L"\u0394\u0416\u6F22 x", "an argument outside any single-byte code page"); check_import_names(); + check_argv_reset(); check_getmainargs_environment(); check_winmain(L"game.exe", {L"-foo", L"with space"}, L"-foo \"with space\"", "arguments after a plain name"); check_winmain(L"C:\\My Games\\game.exe", {L"-x"}, L"-x", "a quoted program name with a space"); -- cgit v1.2.3