diff --git a/docs/boot.md b/docs/boot.md index 4bc580c750..cfdc57cadb 100644 --- a/docs/boot.md +++ b/docs/boot.md @@ -135,7 +135,16 @@ Useful switches: * `--overlay DIR` sends the guest's writes to DIR instead of the default `\overlay` (useful when the package drive is read-only); the package itself is never written. Set `LEONIDA_WRITE_DIR` to override that folder for one run (it wins over `--overlay`). For a fresh first-run profile, also set `LEONIDA_SAVE_DIR` to a separate - empty directory for the local game-save provider. + empty directory for the local game-save provider. The title's `T:` drive (its temporary drive, + where it writes its crash dump `T:\.dmp` and crash log) is a folder of each process's own inside the overlay, + `\.gta6rt-temp\-pid` (the process's start time in UTC and its id). + The folder is reserved with a create-only `CreateDirectoryW` when `gta6rt` starts the title (or on the first `T:` + call): when that name already exists, as after a reused process id in the same millisecond, it takes `-2`, `-3`, + ... (up to 1000 names), so a run never writes into a folder that existed before it. The startup line names it + (`console paths: GAME: -> ..., writes -> ..., T: -> ...`). + Folders of earlier runs are kept, so a run's crash files can be read after it stops; delete them by hand. With + one folder for every run, a `CREATE_NEW` of a name an earlier run had left failed with `ERROR_FILE_EXISTS` (80) + and no report landed (old upstream issue 7913). ### Under Wine on Linux diff --git a/docs/runtime_imports.md b/docs/runtime_imports.md index 3d6efb25fa..f6cf768812 100644 --- a/docs/runtime_imports.md +++ b/docs/runtime_imports.md @@ -290,10 +290,17 @@ and the `api-ms-win-core-file-*` sets a GDK title links against. passed to the host unchanged. `--game-dir` defaults to the image's folder. `gta6rt` makes it and `--overlay` absolute at startup, so a bare image name (`gta6rt --run game.exe` from the game folder) and a relative folder both keep naming the same place after the title changes its current directory (CTest `run_tiny_game_dir`). - `G:\` is the same folder as `GAME:`, and `T:\` is a scratch folder, `\.gta6rt-temp`, that `GAME:` does - not see (RT-218; the other console layers map those two drives this way, and only the executable can say which - spelling GTA VI uses). A path under `--game-dir` or the overlay is always a host path, so a package that sits on - a host drive `G:` keeps working, and with no folders configured `G:` and `T:` stay host drives. + `G:\` is the same folder as `GAME:`, and `T:\` is a scratch folder that `GAME:` does not see (RT-218; the other + console layers map those two drives this way, and only the executable can say which spelling GTA VI uses). Each + process has its own, `\.gta6rt-temp\-pid` (start time in UTC and process id, + `rt::fs::scratch_dir()`, named on the startup line), as the console's temporary drive is empty at launch and + shared with no other run: with one folder for all runs, a `CREATE_NEW` of a name an earlier run left failed with + `ERROR_FILE_EXISTS` (old upstream issue 7913). `rt::fs::reserve_unique_dir` reserves it once per overlay with a + create-only `CreateDirectoryW`; a name that already exists (a reused process id in the same millisecond) is skipped + for `-2`, `-3`, ... up to 1000 names, after which `T:` paths fail with `ERROR_INVALID_NAME` and the reason is + printed once. Earlier runs' folders are kept, never reused, and `T:\..` cannot reach them. A path under + `--game-dir` or the overlay is always a host path, so a package that sits on a host drive `G:` keeps working, and + with no folders configured `G:` and `T:` stay host drives. `T:\` is a drive root like `GAME:\`: its folder is made on the first `T:` call, so it is a folder before anything is written there, and removing or moving it fails with `ERROR_ACCESS_DENIED`. - An open that can write, and `DeleteFile`, use the overlay: `--overlay DIR`, default `\overlay`. A diff --git a/runtime/shims/file_system.cpp b/runtime/shims/file_system.cpp index dad6f37a8e..b3cc6b219e 100644 --- a/runtime/shims/file_system.cpp +++ b/runtime/shims/file_system.cpp @@ -6,7 +6,8 @@ // here (docs/runtime_imports.md, "Console paths and the write overlay"; the prefixes come from ivall/xcl, // GPL-2.0-only, as facts). The rules: // - "GAME:" (any case, "\\" or "/") maps under --game-dir, "G:\\" is the same folder and "T:\\" a scratch folder in -// the overlay (RT-218); any other path is a host path and goes to the host; +// the overlay (RT-218), \\.gta6rt-temp\\, a new one reserved by every process; any other path is a +// host path and goes to the host; // - an open that can write, and DeleteFile, go to the overlay (--overlay, default \\overlay), so the // package stays exactly as installed. A write-open of a package file copies it into the overlay first, so // OPEN_EXISTING keeps its bytes; a delete of a package file leaves an empty marker under @@ -26,6 +27,7 @@ #include #include +#include #include #include #include @@ -49,7 +51,7 @@ namespace { constexpr wchar_t kGamePrefix[] = L"game:"; constexpr size_t kGamePrefixLength = 5; constexpr wchar_t kDeletedDir[] = L".gta6rt-deleted"; -constexpr wchar_t kScratchDir[] = L".gta6rt-temp"; // what "T:\" names, inside the overlay +constexpr wchar_t kScratchDir[] = L".gta6rt-temp"; // holds one folder per process; "T:\" names this process's // A removed package folder is marked by this file inside its marker folder: the marker folder itself can already // exist because files below it were deleted, and that alone does not hide the folder. constexpr wchar_t kRemovedDirMarker[] = L".gta6rt-dir"; @@ -167,9 +169,68 @@ std::filesystem::path win32_find_path(const std::filesystem::path& path, const s // other console layers map those two drives (RT-218). Only the executable can say which spelling the title uses, so // a host drive of the same letter must keep working: a path under --game-dir or the overlay (a package on drive G:, // or a path GetModuleFileName handed back) stays a host path, and so does every G:/T: path while no roots are -// configured. The scratch folder lives in the overlay, as `.gta6rt-temp`. +// configured. The scratch folder lives in the overlay, as `.gta6rt-temp\`, one per process (scratch_folder()). enum class Drive { None, Game, Scratch }; +// The stem of this process's T: folder below `.gta6rt-temp`: the process's start time (UTC, to the millisecond) and +// its id, e.g. "20261123-181502-123-pid4242". On the console T: is the title's own temporary drive, empty at launch +// and shared with nothing; one folder that every run shared kept the files earlier runs left, so a title that makes a +// file there with CREATE_NEW (its crash dump and crash log, measured under Wine) got ERROR_FILE_EXISTS. The stem only +// makes the folder easy to find: a reused process id in the same millisecond gives the same stem, so the folder is +// reserved by reserve_unique_dir, which never hands out one that already existed. +const std::wstring& scratch_run() { + static const std::wstring name = [] { + const DWORD last_error = ::GetLastError(); + FILETIME created{}, exited{}, kernel{}, user{}; + SYSTEMTIME t{}; + if (!::GetProcessTimes(::GetCurrentProcess(), &created, &exited, &kernel, &user) || + !::FileTimeToSystemTime(&created, &t)) + ::GetSystemTime(&t); + wchar_t buffer[64]; + const unsigned long pid = ::GetCurrentProcessId(); + std::swprintf(buffer, sizeof(buffer) / sizeof(buffer[0]), L"%04u%02u%02u-%02u%02u%02u-%03u-pid%lu", + unsigned{t.wYear}, unsigned{t.wMonth}, unsigned{t.wDay}, unsigned{t.wHour}, unsigned{t.wMinute}, + unsigned{t.wSecond}, unsigned{t.wMilliseconds}, pid); + ::SetLastError(last_error); + return std::wstring(buffer); + }(); + return name; +} + +// The T: folder this process reserved in each overlay it was given (configure() may name several, as the test does), +// or the error that stopped the reservation. Decided once per overlay, under the mutex, so concurrent first T: calls +// get the same folder. +struct ScratchFolder { + std::wstring name; // empty: the reservation failed with `error` + DWORD error = 0; +}; +std::mutex g_scratch_mutex; +std::map g_scratch_folders; // keyed by the overlay path, lowercased + +// The name of this process's folder below \.gta6rt-temp, reserved on the first call for that overlay; empty +// when it could not be reserved (logged once). With no overlay configured nothing is made and the stem is the name. +std::wstring scratch_folder(const std::filesystem::path& overlay) { + if (overlay.empty()) return scratch_run(); + std::lock_guard lock(g_scratch_mutex); + ScratchFolder& folder = g_scratch_folders[lower(overlay.native())]; + if (folder.name.empty() && folder.error == 0) { + const DWORD last_error = ::GetLastError(); + DWORD error = 0; + const std::filesystem::path reserved = reserve_unique_dir(overlay / kScratchDir, scratch_run(), error); + if (reserved.empty()) { + folder.error = error ? error : ERROR_CANNOT_MAKE; + std::fprintf(stderr, + "[rt] file_system: no T: folder could be reserved below %ls (Win32 error %lu); T: paths " + "fail with ERROR_INVALID_NAME\n", + (overlay / kScratchDir).c_str(), static_cast(folder.error)); + } else { + folder.name = reserved.filename().native(); + } + ::SetLastError(last_error); + } + return folder.name; +} + Drive console_drive(const std::wstring& path, size_t& prefix_length) { if (path.size() >= kGamePrefixLength && lower(path.substr(0, kGamePrefixLength)) == kGamePrefix) { prefix_length = kGamePrefixLength; @@ -191,11 +252,15 @@ Parsed parse_console(const std::wstring& path, std::vector& parts) if (drive == Drive::None) return Parsed::Host; parts.clear(); if (drive == Drive::Scratch) { - parts.push_back(kScratchDir); const std::filesystem::path overlay = roots().overlay; + const std::wstring folder = scratch_folder(overlay); + if (folder.empty()) return Parsed::Refused; + parts.push_back(kScratchDir); + parts.push_back(folder); + // The folder is this process's from its reservation on; made again if something removed it since. const DWORD last_error = ::GetLastError(); std::error_code ec; - if (!overlay.empty()) std::filesystem::create_directories(win32_io_path(overlay / kScratchDir), ec); + if (!overlay.empty()) std::filesystem::create_directories(win32_io_path(overlay / kScratchDir / folder), ec); ::SetLastError(last_error); } const size_t floor = parts.size(); // ".." may not climb out of the drive's own root @@ -227,7 +292,7 @@ Parsed parse_console(const std::wstring& path, std::vector& parts) if (!flush()) return Parsed::Refused; // The overlay's own folders are not part of the title's GAME: tree: hidden from its listings (internal_dir) and // refused as an explicit path too, in every spelling the loop above normalises (case, slashes, "." and ".."). - // T: still names the scratch folder: its first part is pushed above, not parsed from the title's path. + // T: still names the scratch folder: its first two parts are pushed above, not parsed from the title's path. if (drive == Drive::Game && !parts.empty() && internal_dir(parts.front().c_str())) return Parsed::Refused; return Parsed::Console; } @@ -244,7 +309,7 @@ std::filesystem::path disk_path(const std::filesystem::path& root, const std::ve bool drive_root(const std::wstring& path, const std::vector& parts) { size_t prefix_length = 0; - return parts.empty() || (parts.size() == 1 && console_drive(path, prefix_length) == Drive::Scratch); + return parts.empty() || (parts.size() == 2 && console_drive(path, prefix_length) == Drive::Scratch); } struct Target { @@ -687,6 +752,34 @@ std::filesystem::path overlay_dir() { return g_overlay_dir; } +std::filesystem::path scratch_dir() { + const std::filesystem::path overlay = overlay_dir(); + if (overlay.empty()) return {}; + const std::wstring folder = scratch_folder(overlay); + return folder.empty() ? std::filesystem::path() : overlay / kScratchDir / folder; +} + +std::wstring scratch_stem() { return scratch_run(); } + +std::filesystem::path reserve_unique_dir(const std::filesystem::path& base, const std::wstring& stem, DWORD& error, + unsigned max_tries) { + error = 0; + std::error_code ec; + std::filesystem::create_directories(win32_io_path(base), ec); + for (unsigned n = 1; n <= max_tries; ++n) { + const std::filesystem::path candidate = base / (n == 1 ? stem : stem + L"-" + std::to_wstring(n)); + // Create-only: success means no other process or run had this name, so the folder is new and ours. Through + // win32_io_path, as every other create here, so a long overlay root keeps working. + if (::CreateDirectoryW(win32_io_path(candidate).c_str(), nullptr)) { + error = 0; + return candidate; + } + error = ::GetLastError(); + if (error != ERROR_ALREADY_EXISTS) return {}; // another name will not get past this error + } + return {}; +} + // gta6rt --trace FILE: a failed open of a guest path goes to the startup trace as a "file_open_failed" event (the // path the title passed, the Win32 error, the caller as module+RVA), so a boot that stops on a missing or refused // file names it. Failures only, and at most 256 of them, so a title probing many optional files can't fill the file. diff --git a/runtime/shims/file_system.h b/runtime/shims/file_system.h index d252bb1ce5..420430e13e 100644 --- a/runtime/shims/file_system.h +++ b/runtime/shims/file_system.h @@ -28,6 +28,19 @@ void configure(const std::filesystem::path& game_dir, const std::filesystem::pat std::filesystem::path game_dir(); std::filesystem::path overlay_dir(); +// The folder "T:\" names in this process: \.gta6rt-temp\, or -2, -3, ... when that name was +// taken (scratch_stem(), reserve_unique_dir). Reserved on the first T: call or the first call of this function for the +// overlay and kept for the rest of the process; empty while no overlay is configured or when no folder could be made. +std::filesystem::path scratch_dir(); +// The first name tried for that folder: the process's start time (UTC) and id, "YYYYMMDD-HHMMSS-mmm-pid". +std::wstring scratch_stem(); + +// Makes a new folder base\stem, or base\stem-2 ... base\stem- when the names before it exist, each with a +// create-only CreateDirectoryW, so the folder returned did not exist before and no other process got it. Makes `base` +// first. Returns an empty path, with the Win32 error in `error`, when every name was taken (ERROR_ALREADY_EXISTS) or +// a create failed for another reason. +std::filesystem::path reserve_unique_dir(const std::filesystem::path& base, const std::wstring& stem, + unsigned long& error, unsigned max_tries = 1000); // For tests: true makes the CopyFile2 shim use its CopyFileExW fallback even where the host has CopyFile2, so the // path Wine 9 takes can be checked on Windows. Off by default; main.cpp never sets it. diff --git a/runtime/src/main.cpp b/runtime/src/main.cpp index 094aaa3211..28949830bc 100644 --- a/runtime/src/main.cpp +++ b/runtime/src/main.cpp @@ -541,7 +541,9 @@ int wmain(int argc, wchar_t** argv) { std::fprintf(stderr, "error: %s has no entry point\n", main_module.name.c_str()); return 1; } - const std::wstring paths = L"console paths: GAME: -> " + game_dir.native() + L", writes -> " + overlay_dir.native(); + const std::filesystem::path scratch_dir = rt::fs::scratch_dir(); + const std::wstring paths = L"console paths: GAME: -> " + game_dir.native() + L", writes -> " + + overlay_dir.native() + L", T: -> " + scratch_dir.native(); const HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE); DWORD mode; bool printed = false; @@ -554,8 +556,10 @@ int wmain(int argc, wchar_t** argv) { if (!printed) { const auto game = game_dir.u8string(); const auto overlay = overlay_dir.u8string(); - std::printf("console paths: GAME: -> %s, writes -> %s\n", - reinterpret_cast(game.c_str()), reinterpret_cast(overlay.c_str())); + const auto scratch = scratch_dir.u8string(); + std::printf("console paths: GAME: -> %s, writes -> %s, T: -> %s\n", + reinterpret_cast(game.c_str()), reinterpret_cast(overlay.c_str()), + reinterpret_cast(scratch.c_str())); } std::printf("running %s\n", main_module.name.c_str()); std::fflush(stdout); diff --git a/runtime/test/check_console_paths.cmake b/runtime/test/check_console_paths.cmake index bdd74a7d1a..9f9a699b1d 100644 --- a/runtime/test/check_console_paths.cmake +++ b/runtime/test/check_console_paths.cmake @@ -1,12 +1,12 @@ -# Redirect the loader's stdout so both console paths must survive as UTF-8. +# Redirect the loader's stdout so the console paths (GAME:, the overlay and T:'s folder in it) must survive as UTF-8. execute_process( COMMAND ${RUNNER} "${LOADER}" --game-dir "game-Игра" --overlay "overlay-保存" --run "${GUEST}" -- hello 42 TIMEOUT 90 ENCODING UTF-8 RESULT_VARIABLE code OUTPUT_VARIABLE output ERROR_VARIABLE error) if(NOT code STREQUAL "0" OR - NOT output MATCHES "console paths: GAME: -> [^\n]*game-Игра, writes -> [^\n]*overlay-保存\r?\n") - message(FATAL_ERROR "Runtime did not report both Unicode paths (exit ${code})\n${output}\n${error}") + NOT output MATCHES "console paths: GAME: -> [^\n]*game-Игра, writes -> [^\n]*overlay-保存, T: -> [^\n]*overlay-保存[\\/]\\.gta6rt-temp[\\/][^\n]*pid[0-9]+\r?\n") + message(FATAL_ERROR "Runtime did not report the Unicode paths (exit ${code})\n${output}\n${error}") endif() if(NOT output MATCHES "(^|\n)tiny_game: OK(\r?\n|$)" OR NOT output MATCHES "(^|\n)game exited with code 0(\r?\n|$)") diff --git a/runtime/test/check_game_dir.cmake b/runtime/test/check_game_dir.cmake index 039a1ade31..1c973fd545 100644 --- a/runtime/test/check_game_dir.cmake +++ b/runtime/test/check_game_dir.cmake @@ -1,7 +1,8 @@ # Run the stand-in game from its own folder by bare name, as a player would (`gta6rt --run game.exe`), and again # with `--game-dir .`. In both, GAME: has to name that folder as an absolute path: the guest moves its current # directory away and then reads GAME:\tiny_game_probe.txt (argument game-file). Before, a bare name left GAME: with -# an empty root (`console paths: GAME: -> , writes -> overlay`) and the open failed with ERROR_PATH_NOT_FOUND. +# an empty root (`console paths: GAME: -> , writes -> overlay`) and the open failed with ERROR_PATH_NOT_FOUND. The line +# also names T:'s folder, this process's own below \.gta6rt-temp. # The verdict is checked from the output, as check_loaded_gdk.cmake does, because under Wine an exit status alone # can look successful. get_filename_component(guest_dir "${GUEST}" DIRECTORY) @@ -23,7 +24,7 @@ foreach(variant "bare" "dot") # An absolute GAME: root: a drive letter (Windows, and Wine's Z:) or a leading slash, and an overlay inside it. if(NOT code STREQUAL "0" OR NOT output MATCHES "(^|\n)tiny_game: PASS GAME:" OR NOT output MATCHES "(^|\n)tiny_game: OK(\n|$)" - OR NOT output MATCHES "(^|\n)console paths: GAME: -> ([A-Za-z]:|[\\/])[^\n]*, writes -> ([A-Za-z]:|[\\/])[^\n]*overlay(\n|$)" + OR NOT output MATCHES "(^|\n)console paths: GAME: -> ([A-Za-z]:|[\\/])[^\n]*, writes -> ([A-Za-z]:|[\\/])[^\n]*overlay, T: -> ([A-Za-z]:|[\\/])[^\n]*overlay[\\/]\\.gta6rt-temp[\\/][0-9]+-[0-9]+-[0-9]+-pid[0-9]+(\n|$)" OR NOT output MATCHES "(^|\n)game exited with code 0(\n|$)") string(APPEND failures "--- ${variant}: returned ${code}\n${output}\n") endif() diff --git a/runtime/test/file_system_test.cpp b/runtime/test/file_system_test.cpp index 493ffd6bf3..fcc45d4fb1 100644 --- a/runtime/test/file_system_test.cpp +++ b/runtime/test/file_system_test.cpp @@ -118,6 +118,81 @@ int count(const std::vector& names, const wchar_t* name) { bool contains(const std::vector& names, const wchar_t* name) { return count(names, name) != 0; } +// The folder "T:\" names in another process `pid`: the one below \.gta6rt-temp whose name ends in +// "-pid" or "-pid-" (rt::fs::scratch_dir() in that process). Empty when there is none, as when every +// process shared .gta6rt-temp. +std::filesystem::path t_folder(const std::filesystem::path& overlay, DWORD pid) { + const std::wstring marker = L"-pid" + std::to_wstring(pid); + std::error_code ec; + for (auto it = std::filesystem::directory_iterator(overlay / ".gta6rt-temp", ec); + !ec && it != std::filesystem::directory_iterator(); it.increment(ec)) { + const std::wstring name = it->path().filename().wstring(); + const size_t at = name.rfind(marker); + std::error_code type_ec; + if (it->is_directory(type_ec) && at != std::wstring::npos && + (at + marker.size() == name.size() || name[at + marker.size()] == L'-')) + return it->path(); + } + return {}; +} + +// This process's T: folder in the configured overlay. +std::filesystem::path own_t_folder(const std::filesystem::path& overlay) { + return rt::fs::overlay_dir() == overlay ? rt::fs::scratch_dir() : std::filesystem::path(); +} + +// file_system_test started by itself as a second process (run_t_drive_child below): it opens T:\crash.dmp with +// CREATE_NEW on the overlay its parent uses, writes "child process" and exits with 0, or with the open's Win32 error. +constexpr wchar_t kChildPackage[] = L"LEONIDA_FS_TEST_CHILD_PACKAGE"; +constexpr wchar_t kChildOverlay[] = L"LEONIDA_FS_TEST_CHILD_OVERLAY"; + +std::wstring environment(const wchar_t* name) { + std::wstring buffer(32768, L'\0'); + const DWORD n = ::GetEnvironmentVariableW(name, buffer.data(), static_cast(buffer.size())); + if (n == 0 || n >= buffer.size()) return {}; + buffer.resize(n); + return buffer; +} + +int t_drive_child(const std::wstring& package, const std::wstring& overlay) { + rt::fs::configure(package, overlay); + const auto create_w = resolve("kernel32.dll", "CreateFileW"); + if (!create_w) return 1000; + const HANDLE h = create_w(L"T:\\crash.dmp", GENERIC_WRITE, 0, nullptr, CREATE_NEW, 0, nullptr); + if (h == INVALID_HANDLE_VALUE) return static_cast(::GetLastError()); + DWORD written = 0; + ::WriteFile(h, "child process", 13, &written, nullptr); + ::CloseHandle(h); + return 0; +} + +// Runs t_drive_child in a new process of this executable on the given folders. Returns its exit code (~0u when it +// could not be started or did not finish) and its process id in `pid`. +DWORD run_t_drive_child(const std::filesystem::path& package, const std::filesystem::path& overlay, DWORD& pid) { + pid = 0; + std::wstring self(32768, L'\0'); + const DWORD length = ::GetModuleFileNameW(nullptr, self.data(), static_cast(self.size())); + if (length == 0 || length >= self.size()) return ~0u; + self.resize(length); + std::wstring command = L"\"" + self + L"\""; + ::SetEnvironmentVariableW(kChildPackage, package.c_str()); + ::SetEnvironmentVariableW(kChildOverlay, overlay.c_str()); + STARTUPINFOW startup{}; + startup.cb = sizeof(startup); + PROCESS_INFORMATION process{}; + const BOOL started = ::CreateProcessW(self.c_str(), command.data(), nullptr, nullptr, FALSE, 0, nullptr, nullptr, + &startup, &process); + ::SetEnvironmentVariableW(kChildPackage, nullptr); + ::SetEnvironmentVariableW(kChildOverlay, nullptr); + if (!started) return ~0u; + DWORD code = ~0u; + if (::WaitForSingleObject(process.hProcess, 60000) == WAIT_OBJECT_0) ::GetExitCodeProcess(process.hProcess, &code); + pid = process.dwProcessId; + ::CloseHandle(process.hThread); + ::CloseHandle(process.hProcess); + return code; +} + // Denies the current user `rights` on a folder while it lives and puts the folder's old DACL back when it goes, on // every way out of the check. Both changes go through one handle opened before the deny. Under Wine the DACL is the // folder's unix mode: a deny of FILE_LIST_DIRECTORY clears its owner and group read bits (server/file.c, sd_to_mode), @@ -244,6 +319,8 @@ void check_read_file_first_touch(const std::filesystem::path& root) { } // namespace int main() { + if (const std::wstring child_overlay = environment(kChildOverlay); !child_overlay.empty()) + return t_drive_child(environment(kChildPackage), child_overlay); // A folder of this run's own: Wine hands each fresh prefix the same small process ids, so a folder named after // the process id alone can be one an earlier run left behind. LARGE_INTEGER now{}; @@ -1274,18 +1351,18 @@ void run_checks(const std::filesystem::path& root) { "on a fresh overlay CreateDirectoryW(T:\\shadercache) succeeds"); std::filesystem::path fresh = fresh_overlay(); check(copy_w(L"GAME:\\data\\hello.txt", L"T:\\hello.tmp", FALSE) != FALSE && - read_path(fresh / ".gta6rt-temp" / "hello.tmp") == "package", + read_path(own_t_folder(fresh) / "hello.tmp") == "package", "on a fresh overlay CopyFileW(GAME:\\data\\hello.txt, T:\\hello.tmp) succeeds"); fresh = fresh_overlay(); SetLastError(0); check(rmdir_w(L"T:\\") == FALSE && GetLastError() == ERROR_ACCESS_DENIED && - std::filesystem::is_directory(fresh / ".gta6rt-temp"), + std::filesystem::is_directory(own_t_folder(fresh)), "T:\\ cannot be removed, like GAME:\\"); fresh = fresh_overlay(); SetLastError(0); check(move_w(L"T:\\", L"GAME:\\moved") == FALSE && GetLastError() == ERROR_ACCESS_DENIED && attributes_w(L"GAME:\\moved") == INVALID_FILE_ATTRIBUTES && - std::filesystem::is_directory(fresh / ".gta6rt-temp"), + std::filesystem::is_directory(own_t_folder(fresh)), "T:\\ cannot be moved"); fresh_overlay(); attributes_w(L"T:\\"); @@ -1302,8 +1379,8 @@ void run_checks(const std::filesystem::path& root) { ::WriteFile(h, "scratch", 7, &written, nullptr); ::CloseHandle(h); } - check(read_path(overlay / ".gta6rt-temp" / "cache" / "scratch.bin") == "scratch", - "a T: file lands in the overlay's scratch folder"); + check(read_path(own_t_folder(overlay) / "cache" / "scratch.bin") == "scratch", + "a T: file lands in this process's scratch folder in the overlay"); check(!std::filesystem::exists(package / "cache" / "scratch.bin") && !std::filesystem::exists(package / ".gta6rt-temp"), "and the package is untouched"); h = create_w(L"t:/cache/scratch.bin", GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr); @@ -1323,6 +1400,8 @@ void run_checks(const std::filesystem::path& root) { // as an explicit GAME: or G: path, refused like any other invalid name, in every spelling parse_console() // normalises (RT-294). T:\ still names the scratch folder, and an ordinary dotted name is not reserved. write_path(overlay / ".gta6rt-temp" / "runtime.tmp", "runtime"); + if (const std::filesystem::path t_dir = own_t_folder(overlay); !t_dir.empty()) + write_path(t_dir / "runtime.tmp", "runtime"); write_path(overlay / ".gta6rt-deleted" / "data" / "gone.txt", ""); write_path(overlay / ".gta6rt-other" / "ok.txt", "ok"); for (const wchar_t* reserved : {L"GAME:\\.gta6rt-temp\\runtime.tmp", L"GAME:\\.GTA6RT-TEMP\\runtime.tmp", @@ -1347,7 +1426,8 @@ void run_checks(const std::filesystem::path& root) { if (markers != INVALID_HANDLE_VALUE) find_close(markers); SetLastError(0); const HANDLE probe = create_w(L"GAME:\\.gta6rt-temp\\probe.txt", GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, 0, nullptr); - check(probe == INVALID_HANDLE_VALUE && !std::filesystem::exists(overlay / ".gta6rt-temp" / "probe.txt"), + check(probe == INVALID_HANDLE_VALUE && !std::filesystem::exists(overlay / ".gta6rt-temp" / "probe.txt") && + !std::filesystem::exists(own_t_folder(overlay) / "probe.txt"), "a write through GAME:\\.gta6rt-temp creates nothing in the scratch folder"); if (probe != INVALID_HANDLE_VALUE) ::CloseHandle(probe); check(mkdir_w(L"GAME:\\.gta6rt-copy\\sub", nullptr) == FALSE && !std::filesystem::exists(overlay / ".gta6rt-copy" / "sub"), @@ -1376,6 +1456,157 @@ void run_checks(const std::filesystem::path& root) { rt::fs::configure(package, overlay); } + // T: is the title's temporary drive, which on the console no other run shares: each process gets a folder of its + // own below \.gta6rt-temp. With one folder for every run, the title's crash dump and crash log, made with + // CREATE_NEW, failed with ERROR_FILE_EXISTS on names an earlier run had left (old upstream issue 7913, measured + // under Wine). + { + const std::filesystem::path t_overlay = root / "t_overlay"; + const std::filesystem::path temp = t_overlay / ".gta6rt-temp"; + // What earlier runs left: a file in the folder they all shared, and one in an earlier process's own folder. + write_path(temp / "crash.dmp", "earlier run"); + write_path(temp / "20200101-000000-000-pid1" / "crash.dmp", "earlier process"); + write_path(package / "crash.dmp", "package"); // and a GAME: file of the same name + rt::fs::configure(package, t_overlay); + + SetLastError(0); + HANDLE h = create_w(L"T:\\crash.dmp", GENERIC_WRITE, 0, nullptr, CREATE_NEW, 0, nullptr); + const DWORD create_error = h == INVALID_HANDLE_VALUE ? GetLastError() : 0; + check(h != INVALID_HANDLE_VALUE, + "CreateFileW(T:\\crash.dmp, CREATE_NEW) succeeds when earlier runs left that name in .gta6rt-temp"); + if (create_error) std::printf(" (failed with Win32 error %lu)\n", static_cast(create_error)); + if (h != INVALID_HANDLE_VALUE) { + DWORD written = 0; + ::WriteFile(h, "this process", 12, &written, nullptr); + ::CloseHandle(h); + } + const std::filesystem::path mine = own_t_folder(t_overlay); + check(!mine.empty() && mine.parent_path() == temp && read_path(mine / "crash.dmp") == "this process", + "T:\\crash.dmp lands in this process's own folder \\.gta6rt-temp\\-pid"); + const std::wstring name = mine.filename().wstring(); + const auto digits = [&](size_t from, size_t n) { + if (name.size() < from + n) return false; + for (size_t i = from; i < from + n; ++i) + if (name[i] < L'0' || name[i] > L'9') return false; + return true; + }; + check(digits(0, 8) && name.size() > 20 && name[8] == L'-' && digits(9, 6) && name[15] == L'-' && + digits(16, 3) && name.compare(19, 4, L"-pid") == 0, + "the folder is named YYYYMMDD-HHMMSS-mmm-pid, the process's start time and id"); + check(name == rt::fs::scratch_stem(), "with no folder of that name yet, it is the stem itself"); + check(read_path(temp / "crash.dmp") == "earlier run" && + read_path(temp / "20200101-000000-000-pid1" / "crash.dmp") == "earlier process" && + read_path(package / "crash.dmp") == "package", + "the earlier runs' files and the package file of the same name are left as they were"); + + // The same folder for every T: call of this process, also after configure() names the overlay again. + rt::fs::configure(package, t_overlay); + h = create_w(L"t:/crash.dmp", GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr); + check(h != INVALID_HANDLE_VALUE && read_handle(h) == "this process", + "T: keeps naming the same folder for the rest of the process"); + if (h != INVALID_HANDLE_VALUE) ::CloseHandle(h); + const std::vector t_names = list(first_w, next_w, find_close, L"T:\\*"); + check(count(t_names, L"crash.dmp") == 1 && !contains(t_names, L"20200101-000000-000-pid1") && + !contains(t_names, L".gta6rt-temp"), + "a T:\\ listing shows this process's files only"); + SetLastError(0); + check(create_w(L"T:\\..\\crash.dmp", GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr) == + INVALID_HANDLE_VALUE && + GetLastError() == ERROR_INVALID_NAME, + "T:\\.. cannot climb into the shared .gta6rt-temp folder"); + SetLastError(0); + check(rmdir_w(L"T:\\") == FALSE && GetLastError() == ERROR_ACCESS_DENIED && std::filesystem::is_directory(mine), + "this process's T:\\ folder cannot be removed, like GAME:\\"); + + // A second process on the same overlay gets a folder of its own, and its CREATE_NEW of the same name succeeds. + DWORD child_pid = 0; + const DWORD child_code = run_t_drive_child(package, t_overlay, child_pid); + check(child_code == 0, + "a second process's CreateFileW(T:\\crash.dmp, CREATE_NEW) on the same overlay succeeds"); + if (child_code != 0) + std::printf(" (the second process exited with %lu)\n", static_cast(child_code)); + const std::filesystem::path theirs = child_pid ? t_folder(t_overlay, child_pid) : std::filesystem::path(); + check(!theirs.empty() && theirs != mine && theirs.parent_path() == temp && + read_path(theirs / "crash.dmp") == "child process", + "the second process wrote into a folder of its own"); + check(read_path(mine / "crash.dmp") == "this process", "and this process's T: file is unchanged"); + + // A reused process id in the same millisecond gives the same stem as a folder an earlier run kept. The folder + // is reserved with a create-only call, so that one (and the next name, taken too) is never used again. + const std::filesystem::path stale_overlay = root / "t_stale_overlay"; + const std::filesystem::path stale = stale_overlay / ".gta6rt-temp" / rt::fs::scratch_stem(); + const std::filesystem::path stale_2 = stale_overlay / ".gta6rt-temp" / (rt::fs::scratch_stem() + L"-2"); + write_path(stale / "crash.dmp", "same stem, earlier run"); + std::filesystem::create_directories(stale_2); + rt::fs::configure(package, stale_overlay); + h = create_w(L"T:\\crash.dmp", GENERIC_WRITE, 0, nullptr, CREATE_NEW, 0, nullptr); + check(h != INVALID_HANDLE_VALUE, + "CreateFileW(T:\\crash.dmp, CREATE_NEW) succeeds when a kept folder has this process's own stem"); + if (h != INVALID_HANDLE_VALUE) ::CloseHandle(h); + check(rt::fs::scratch_dir() == stale_overlay / ".gta6rt-temp" / (rt::fs::scratch_stem() + L"-3") && + std::filesystem::exists(rt::fs::scratch_dir() / "crash.dmp"), + "T: is -3 when and -2 already existed"); + check(read_path(stale / "crash.dmp") == "same stem, earlier run" && std::filesystem::is_empty(stale_2), + "and the folders that already existed are left as they were"); + + // Concurrent first T: calls on a new overlay reserve one folder between them. + const std::filesystem::path race_overlay = root / "t_race_overlay"; + rt::fs::configure(package, race_overlay); + { + std::vector threads; + for (int i = 0; i < 8; ++i) threads.emplace_back([&] { attributes_w(L"T:\\"); }); + for (auto& thread : threads) thread.join(); + } + size_t reserved = 0; + for (const auto& entry : std::filesystem::directory_iterator(race_overlay / ".gta6rt-temp")) { + (void)entry; + ++reserved; + } + check(reserved == 1 && std::filesystem::is_directory(rt::fs::scratch_dir()), + "eight threads making their first T: call at once reserve one folder"); + rt::fs::configure(package, t_overlay); + + // GAME: is not affected: reads come from the package, writes land in the overlay's mirror of the package. + h = create_w(L"GAME:\\crash.dmp", GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr); + check(h != INVALID_HANDLE_VALUE && read_handle(h) == "package", + "GAME:\\crash.dmp still reads the package file"); + if (h != INVALID_HANDLE_VALUE) ::CloseHandle(h); + h = create_w(L"GAME:\\data\\t_written.txt", GENERIC_WRITE, 0, nullptr, CREATE_NEW, 0, nullptr); + check(h != INVALID_HANDLE_VALUE, "a GAME: write-open still succeeds"); + if (h != INVALID_HANDLE_VALUE) ::CloseHandle(h); + check(std::filesystem::exists(t_overlay / "data" / "t_written.txt") && + !std::filesystem::exists(mine / "data") && + !std::filesystem::exists(package / "data" / "t_written.txt"), + "and lands at \\data, not in T:'s folder or the package"); + rt::fs::configure(package, overlay); + } + + // reserve_unique_dir: a create-only CreateDirectoryW per name, so the folder it returns is new; a name that exists + // (a folder or a file) is skipped, and after max_tries names the call fails instead of reusing one. + { + const std::filesystem::path base = root / "reserve"; + std::filesystem::create_directories(base / "stem"); + write_path(base / "stem-2" / "old.txt", "old"); + DWORD error = 1; + const std::filesystem::path third = rt::fs::reserve_unique_dir(base, L"stem", error); + check(third == base / "stem-3" && error == 0 && std::filesystem::is_directory(third) && + std::filesystem::is_empty(third), + "reserve_unique_dir(base, stem) with stem and stem-2 taken makes stem-3, new and empty"); + check(read_path(base / "stem-2" / "old.txt") == "old", "and leaves the taken folders alone"); + check(rt::fs::reserve_unique_dir(base, L"stem", error) == base / "stem-4", + "a second call never hands out stem-3 again: it makes stem-4"); + write_path(base / "stem-5", "a file"); + check(rt::fs::reserve_unique_dir(base, L"stem", error) == base / "stem-6", + "a file with the next name counts as taken too"); + error = 0; + check(rt::fs::reserve_unique_dir(base, L"stem", error, 6).empty() && error == ERROR_ALREADY_EXISTS, + "with every name up to max_tries taken it fails with ERROR_ALREADY_EXISTS"); + const std::filesystem::path fresh_base = root / "reserve_new" / "deep"; + check(rt::fs::reserve_unique_dir(fresh_base, L"stem", error) == fresh_base / "stem" && + std::filesystem::is_directory(fresh_base / "stem"), + "a missing base folder is made first, and the stem itself is the first name"); + } + // An open that writes needs its folder to exist in the title's view, and a failed open changes nothing. { const auto overlay_has = [&](const wchar_t* name) { return std::filesystem::exists(overlay / name); }; @@ -1650,9 +1881,11 @@ void run_checks(const std::filesystem::path& root) { check(h != INVALID_HANDLE_VALUE && ::WriteFile(h, "test", 4, &written, nullptr) && written == 4, "T: creates and writes its scratch directory under a long overlay root"); if (h != INVALID_HANDLE_VALUE) ::CloseHandle(h); - check(read_guest(L"T:\\scratch.bin") == "test" && - read_path(extended(scratch_overlay / ".gta6rt-temp" / "scratch.bin")) == "test", - "T: reads from the same long backing directory"); + const std::filesystem::path scratch_folder = rt::fs::scratch_dir(); // configured on scratch_overlay above + check(read_guest(L"T:\\scratch.bin") == "test" && !scratch_folder.empty() && + scratch_folder.parent_path() == scratch_overlay / ".gta6rt-temp" && + read_path(extended(scratch_folder / "scratch.bin")) == "test", + "T: reads from the same long backing directory, this process's own folder in it"); rt::fs::configure(package, overlay); std::error_code cleanup_error; diff --git a/tests/test_console_paths.py b/tests/test_console_paths.py index 44921c916a..7d775af51a 100644 --- a/tests/test_console_paths.py +++ b/tests/test_console_paths.py @@ -25,7 +25,8 @@ def test_requires_the_guest_to_finish_successfully(self): loader = Path(tmp) / "loader.py" for name, verdict, expected in cases: with self.subTest(name=name): - output = "console paths: GAME: -> game-Игра, writes -> overlay-保存\n" + verdict + output = ("console paths: GAME: -> game-Игра, writes -> overlay-保存, " + "T: -> overlay-保存\\.gta6rt-temp\\20261123-181502-123-pid42\n" + verdict) loader.write_text( f"import sys\nsys.stdout.buffer.write({output.encode('utf-8')!r})\n", encoding="utf-8", newline="\n",