Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion docs/boot.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,16 @@ Useful switches:
* `--overlay DIR` sends the guest's writes to DIR instead of the default `<game-dir>\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:\<guid>.dmp` and crash log) is a folder of each process's own inside the overlay,
`<overlay>\.gta6rt-temp\<YYYYMMDD-HHMMSS-mmm>-pid<id>` (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

Expand Down
15 changes: 11 additions & 4 deletions docs/runtime_imports.md
Original file line number Diff line number Diff line change
Expand Up @@ -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, `<overlay>\.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, `<overlay>\.gta6rt-temp\<YYYYMMDD-HHMMSS-mmm>-pid<id>` (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 `<game-dir>\overlay`. A
Expand Down
107 changes: 100 additions & 7 deletions runtime/shims/file_system.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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), <overlay>\\.gta6rt-temp\\<run>, 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 <game-dir>\\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
Expand All @@ -26,6 +27,7 @@
#include <intrin.h>

#include <atomic>
#include <cstdio>
#include <cstring>
#include <cwchar>
#include <cwctype>
Expand All @@ -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";
Expand Down Expand Up @@ -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\<run>`, 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<std::wstring, ScratchFolder> g_scratch_folders; // keyed by the overlay path, lowercased

// The name of this process's folder below <overlay>\.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<unsigned long>(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;
Expand All @@ -191,11 +252,15 @@ Parsed parse_console(const std::wstring& path, std::vector<std::wstring>& 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
Expand Down Expand Up @@ -227,7 +292,7 @@ Parsed parse_console(const std::wstring& path, std::vector<std::wstring>& 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;
}
Expand All @@ -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<std::wstring>& 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 {
Expand Down Expand Up @@ -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.
Expand Down
13 changes: 13 additions & 0 deletions runtime/shims/file_system.h
Original file line number Diff line number Diff line change
Expand Up @@ -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: <overlay dir>\.gta6rt-temp\<stem>, or <stem>-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<id>".
std::wstring scratch_stem();

// Makes a new folder base\stem, or base\stem-2 ... base\stem-<max_tries> 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.
Expand Down
10 changes: 7 additions & 3 deletions runtime/src/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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<const char*>(game.c_str()), reinterpret_cast<const char*>(overlay.c_str()));
const auto scratch = scratch_dir.u8string();
std::printf("console paths: GAME: -> %s, writes -> %s, T: -> %s\n",
reinterpret_cast<const char*>(game.c_str()), reinterpret_cast<const char*>(overlay.c_str()),
reinterpret_cast<const char*>(scratch.c_str()));
}
std::printf("running %s\n", main_module.name.c_str());
std::fflush(stdout);
Expand Down
6 changes: 3 additions & 3 deletions runtime/test/check_console_paths.cmake
Original file line number Diff line number Diff line change
@@ -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|$)")
Expand Down
5 changes: 3 additions & 2 deletions runtime/test/check_game_dir.cmake
Original file line number Diff line number Diff line change
@@ -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 <overlay>\.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)
Expand All @@ -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()
Expand Down
Loading
Loading