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
4 changes: 3 additions & 1 deletion docs/runtime_imports.md
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,9 @@ and the `api-ms-win-core-file-*` sets a GDK title links against.
package has, fails with `ERROR_ALREADY_EXISTS`; a missing parent with `ERROR_PATH_NOT_FOUND`.
- `RemoveDirectory*` needs the folder empty in the title's view (`ERROR_DIR_NOT_EMPTY` otherwise). An overlay folder is
removed; a package folder is hidden by a `.gta6rt-dir` marker inside its marker folder, and stays on disk. A marker
folder on its own (left by a file deleted below it) does not hide anything.
folder on its own (left by a file deleted below it) does not hide anything. A remove and a write-open or
`CreateDirectory*` inside the folder on another thread are ordered as on the host: one goes first, and the create
fails with `ERROR_PATH_NOT_FOUND` or the remove with `ERROR_DIR_NOT_EMPTY`, never both succeeding.
- `MoveFile*` writes the destination in the overlay. A package file is copied there and its old name deleted by a
marker; an overlay file or an overlay-only folder is renamed. An existing destination needs
`MOVEFILE_REPLACE_EXISTING` even when only the package has it. Moving a package folder fails with
Expand Down
40 changes: 40 additions & 0 deletions runtime/shims/file_system.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -246,9 +246,41 @@ bool drive_root(const std::wstring& path, const std::vector<std::wstring>& parts
return parts.empty() || (parts.size() == 1 && console_drive(path, prefix_length) == Drive::Scratch);
}

// A folder's entries change one step at a time, as on the host: RemoveDirectory holds the folder's lock from its
// emptiness check to its marker, and a GAME: write-open or CreateDirectory holds the lock of the folder it creates in
// from its "does the folder exist" check, through mirroring that folder into the overlay, to the host call that makes
// the entry. One of the two goes first: the create fails with ERROR_PATH_NOT_FOUND, or the remove with
// ERROR_DIR_NOT_EMPTY. Without it both succeeded and the removed folder was back, the new entry in it. The locks are
// striped by the folder's name, so calls in different folders rarely wait on each other; reads never take one.
// Namespace scope, not function-local statics: these run on the title's threads. Taken after roots(); nothing holding
// one takes another of them or calls back into the title (a copy-up's lock may be taken inside one, never around one).
constexpr size_t kFolderLocks = 64;
std::mutex g_folder_locks[kFolderLocks];

std::mutex& folder_lock(const std::vector<std::wstring>& folder) {
// FNV-1a over the upper-cased components: names compare without case, so every spelling of a folder gets its lock.
uint64_t hash = 14695981039346656037ull;
const auto mix = [&hash](wchar_t c) {
hash ^= static_cast<uint64_t>(c);
hash *= 1099511628211ull;
};
for (const auto& part : folder) {
std::wstring upper(part.size(), L'\0');
if (part.empty() || LCMapStringEx(LOCALE_NAME_INVARIANT, LCMAP_UPPERCASE, part.data(),
static_cast<int>(part.size()), upper.data(), static_cast<int>(upper.size()),
nullptr, nullptr, 0) != static_cast<int>(part.size()))
upper = part;
for (const wchar_t c : upper) mix(c);
mix(L'\\');
}
return g_folder_locks[hash % kFolderLocks];
}

struct Target {
std::filesystem::path path;
DWORD error = 0; // non-zero: the caller fails with this error and does not touch the host
// A write-open's hold on the folder it opens in, until the Target goes after the host open (g_folder_locks).
std::unique_lock<std::mutex> folder;
};

Target fail(DWORD error) {
Expand Down Expand Up @@ -433,10 +465,14 @@ Target write_target(const std::wstring& path, bool copy_up) {
// below a package file (which then read as a folder) and inside a folder the title had removed. The overlay may
// still lack a folder only the package has, so it is mirrored here, which the title cannot see.
// T:'s scratch folder is the exception: it creates its parent folders, as merged with RT-218.
// The folder's lock is held from this check to the caller's host open, so a RemoveDirectory of the folder comes
// wholly before or after (g_folder_locks).
std::unique_lock folder(folder_lock(parent_of(parts)));
const bool scratch = !parts.empty() && same_name(parts.front().c_str(), kScratchDir);
if (!scratch && !is_folder(r, parent_of(parts))) return fail(ERROR_PATH_NOT_FOUND);

Target t;
t.folder = std::move(folder);
t.path = disk_path(r.overlay, parts);

std::error_code ec;
Expand Down Expand Up @@ -1062,6 +1098,8 @@ BOOL create_directory(LPCWSTR template_name, LPCWSTR name, LPSECURITY_ATTRIBUTES
const Roots r = roots();
if (r.game.empty() || r.overlay.empty()) return fail_bool(ERROR_PATH_NOT_FOUND);
if (view(r, parts).kind != Kind::None) return fail_bool(ERROR_ALREADY_EXISTS); // "GAME:" included
// From the parent's check to the new folder: a RemoveDirectory of the parent comes wholly before or after.
std::lock_guard folder(folder_lock(parent_of(parts)));
if (!is_folder(r, parent_of(parts))) return fail_bool(ERROR_PATH_NOT_FOUND);

const std::filesystem::path target = disk_path(r.overlay, parts);
Expand Down Expand Up @@ -1115,6 +1153,8 @@ BOOL WINAPI remove_directory_w(LPCWSTR name) {
const Roots r = roots();
if (r.game.empty() || r.overlay.empty()) return fail_bool(ERROR_PATH_NOT_FOUND);
if (drive_root(name, parts)) return fail_bool(ERROR_ACCESS_DENIED); // "GAME:" and "T:" themselves stay
// From the emptiness check to the marker: a create in the folder comes wholly before or after (g_folder_locks).
std::lock_guard folder(folder_lock(parts));
const View v = view(r, parts);
if (v.kind == Kind::None) return fail_bool(ERROR_FILE_NOT_FOUND);
if (v.kind == Kind::File) return fail_bool(ERROR_DIRECTORY);
Expand Down
70 changes: 70 additions & 0 deletions runtime/test/file_system_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
#include <aclapi.h>

#include <algorithm>
#include <atomic>
#include <clocale>
#include <cstring>
#include <cstdio>
Expand Down Expand Up @@ -807,6 +808,75 @@ void run_checks(const std::filesystem::path& root) {
}
}

// RemoveDirectory of a folder on one thread and, on another, a creating open of a file in it (CREATE_NEW,
// CREATE_ALWAYS, OPEN_ALWAYS) or CreateDirectory of a folder in it. The host orders the two: the remove goes first
// and the create fails with ERROR_PATH_NOT_FOUND, or the create goes first and the remove fails with
// ERROR_DIR_NOT_EMPTY. Both succeeding left the removed folder back in the title's view with the new entry in it.
// Each round takes a folder of its own that only the package has, empty in the title's view, and starts the two
// threads together; the remover waits a few more spins each round so the calls meet at different points.
{
constexpr int kRounds = 2000;
const auto race = [&](bool make_folder, const wchar_t* prefix, const char* what) {
for (int i = 0; i < kRounds; ++i)
std::filesystem::create_directories(package / "rmrace" / (prefix + std::to_wstring(i)));
int create_first = 0, remove_first = 0, both = 0, other = 0, back = 0;
for (int i = 0; i < kRounds; ++i) {
const std::wstring folder = L"GAME:\\rmrace\\" + (prefix + std::to_wstring(i));
const std::wstring child = folder + (make_folder ? L"\\sub" : L"\\new.tmp");
const DWORD disposition = i % 3 == 0 ? CREATE_NEW : i % 3 == 1 ? CREATE_ALWAYS : OPEN_ALWAYS;
std::atomic<int> ready{0};
HANDLE handle = INVALID_HANDLE_VALUE;
bool made = false;
DWORD create_error = 0;
std::thread creator([&] {
ready.fetch_add(1);
while (ready.load() < 2) {
}
if (make_folder) {
made = mkdir_w(child.c_str(), nullptr) != FALSE;
} else {
handle = create_w(child.c_str(), GENERIC_WRITE, 0, nullptr, disposition, 0, nullptr);
made = handle != INVALID_HANDLE_VALUE;
}
create_error = made ? 0 : GetLastError();
});
ready.fetch_add(1);
while (ready.load() < 2) {
}
for (int spin = 0; spin < (i % 64) * 64; ++spin) YieldProcessor();
const bool removed = rmdir_w(folder.c_str()) != FALSE;
const DWORD remove_error = removed ? 0 : GetLastError();
creator.join();
if (handle != INVALID_HANDLE_VALUE) ::CloseHandle(handle);
if (made && removed) {
++both;
} else if (made && remove_error == ERROR_DIR_NOT_EMPTY) {
++create_first;
} else if (removed && create_error == ERROR_PATH_NOT_FOUND) {
++remove_first;
} else {
++other;
}
// A folder the remove took away stays away, whatever the create did.
if (removed) {
SetLastError(0);
if (attributes_w(folder.c_str()) != INVALID_FILE_ATTRIBUTES || GetLastError() != ERROR_FILE_NOT_FOUND)
++back;
}
}
std::printf("NOTE %s against RemoveDirectoryW, %d rounds: create first %d, remove first %d, both succeeded "
"%d, other %d, removed folder back %d\n",
what, kRounds, create_first, remove_first, both, other, back);
const std::string w = what;
check(both == 0, (w + " and RemoveDirectoryW of its folder never both succeed").c_str());
check(other == 0, (w + " or RemoveDirectoryW fails as on the host (ERROR_PATH_NOT_FOUND or "
"ERROR_DIR_NOT_EMPTY)").c_str());
check(back == 0, (w + ": a folder RemoveDirectoryW removed stays removed").c_str());
};
race(false, L"f", "a creating CreateFileW");
race(true, L"d", "CreateDirectoryW");
}

// MoveFile: the destination is in the overlay; a moved package file is deleted by a marker.
{
check(move_w(L"GAME:\\misc\\one.txt", L"GAME:\\misc\\moved.txt") != FALSE, "MoveFileW moves a package file");
Expand Down
Loading