Skip to content

Commit 8564bb4

Browse files
authored
Merge pull request #688 from aslan2142/game-rmdir-create-race
OLD-9215: restore old upstream PR 9215 - file_system: RemoveDirectory and a create inside the folder are ordered as on the host
2 parents d468104 + de8cb53 commit 8564bb4

3 files changed

Lines changed: 113 additions & 1 deletion

File tree

‎docs/runtime_imports.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -324,7 +324,9 @@ and the `api-ms-win-core-file-*` sets a GDK title links against.
324324
package has, fails with `ERROR_ALREADY_EXISTS`; a missing parent with `ERROR_PATH_NOT_FOUND`.
325325
- `RemoveDirectory*` needs the folder empty in the title's view (`ERROR_DIR_NOT_EMPTY` otherwise). An overlay folder is
326326
removed; a package folder is hidden by a `.gta6rt-dir` marker inside its marker folder, and stays on disk. A marker
327-
folder on its own (left by a file deleted below it) does not hide anything.
327+
folder on its own (left by a file deleted below it) does not hide anything. A remove and a write-open or
328+
`CreateDirectory*` inside the folder on another thread are ordered as on the host: one goes first, and the create
329+
fails with `ERROR_PATH_NOT_FOUND` or the remove with `ERROR_DIR_NOT_EMPTY`, never both succeeding.
328330
- `MoveFile*` writes the destination in the overlay. A package file is copied there and its old name deleted by a
329331
marker; an overlay file or an overlay-only folder is renamed. An existing destination needs
330332
`MOVEFILE_REPLACE_EXISTING` even when only the package has it. Moving a package folder fails with

‎runtime/shims/file_system.cpp‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -312,9 +312,41 @@ bool drive_root(const std::wstring& path, const std::vector<std::wstring>& parts
312312
return parts.empty() || (parts.size() == 2 && console_drive(path, prefix_length) == Drive::Scratch);
313313
}
314314

315+
// A folder's entries change one step at a time, as on the host: RemoveDirectory holds the folder's lock from its
316+
// emptiness check to its marker, and a GAME: write-open or CreateDirectory holds the lock of the folder it creates in
317+
// from its "does the folder exist" check, through mirroring that folder into the overlay, to the host call that makes
318+
// the entry. One of the two goes first: the create fails with ERROR_PATH_NOT_FOUND, or the remove with
319+
// ERROR_DIR_NOT_EMPTY. Without it both succeeded and the removed folder was back, the new entry in it. The locks are
320+
// striped by the folder's name, so calls in different folders rarely wait on each other; reads never take one.
321+
// Namespace scope, not function-local statics: these run on the title's threads. Taken after roots(); nothing holding
322+
// one takes another of them or calls back into the title (a copy-up's lock may be taken inside one, never around one).
323+
constexpr size_t kFolderLocks = 64;
324+
std::mutex g_folder_locks[kFolderLocks];
325+
326+
std::mutex& folder_lock(const std::vector<std::wstring>& folder) {
327+
// FNV-1a over the upper-cased components: names compare without case, so every spelling of a folder gets its lock.
328+
uint64_t hash = 14695981039346656037ull;
329+
const auto mix = [&hash](wchar_t c) {
330+
hash ^= static_cast<uint64_t>(c);
331+
hash *= 1099511628211ull;
332+
};
333+
for (const auto& part : folder) {
334+
std::wstring upper(part.size(), L'\0');
335+
if (part.empty() || LCMapStringEx(LOCALE_NAME_INVARIANT, LCMAP_UPPERCASE, part.data(),
336+
static_cast<int>(part.size()), upper.data(), static_cast<int>(upper.size()),
337+
nullptr, nullptr, 0) != static_cast<int>(part.size()))
338+
upper = part;
339+
for (const wchar_t c : upper) mix(c);
340+
mix(L'\\');
341+
}
342+
return g_folder_locks[hash % kFolderLocks];
343+
}
344+
315345
struct Target {
316346
std::filesystem::path path;
317347
DWORD error = 0; // non-zero: the caller fails with this error and does not touch the host
348+
// A write-open's hold on the folder it opens in, until the Target goes after the host open (g_folder_locks).
349+
std::unique_lock<std::mutex> folder;
318350
};
319351

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

509544
Target t;
545+
t.folder = std::move(folder);
510546
t.path = disk_path(r.overlay, parts);
511547

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

11691207
const std::filesystem::path target = disk_path(r.overlay, parts);
@@ -1217,6 +1255,8 @@ BOOL WINAPI remove_directory_w(LPCWSTR name) {
12171255
const Roots r = roots();
12181256
if (r.game.empty() || r.overlay.empty()) return fail_bool(ERROR_PATH_NOT_FOUND);
12191257
if (drive_root(name, parts)) return fail_bool(ERROR_ACCESS_DENIED); // "GAME:" and "T:" themselves stay
1258+
// From the emptiness check to the marker: a create in the folder comes wholly before or after (g_folder_locks).
1259+
std::lock_guard folder(folder_lock(parts));
12201260
const View v = view(r, parts);
12211261
if (v.kind == Kind::None) return fail_bool(missing_error(r, parts));
12221262
if (v.kind == Kind::File) return fail_bool(ERROR_DIRECTORY);

‎runtime/test/file_system_test.cpp‎

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
#include <aclapi.h>
99

1010
#include <algorithm>
11+
#include <atomic>
1112
#include <clocale>
1213
#include <cstring>
1314
#include <cstdio>
@@ -927,6 +928,75 @@ void run_checks(const std::filesystem::path& root) {
927928
}
928929
}
929930

931+
// RemoveDirectory of a folder on one thread and, on another, a creating open of a file in it (CREATE_NEW,
932+
// CREATE_ALWAYS, OPEN_ALWAYS) or CreateDirectory of a folder in it. The host orders the two: the remove goes first
933+
// and the create fails with ERROR_PATH_NOT_FOUND, or the create goes first and the remove fails with
934+
// ERROR_DIR_NOT_EMPTY. Both succeeding left the removed folder back in the title's view with the new entry in it.
935+
// Each round takes a folder of its own that only the package has, empty in the title's view, and starts the two
936+
// threads together; the remover waits a few more spins each round so the calls meet at different points.
937+
{
938+
constexpr int kRounds = 2000;
939+
const auto race = [&](bool make_folder, const wchar_t* prefix, const char* what) {
940+
for (int i = 0; i < kRounds; ++i)
941+
std::filesystem::create_directories(package / "rmrace" / (prefix + std::to_wstring(i)));
942+
int create_first = 0, remove_first = 0, both = 0, other = 0, back = 0;
943+
for (int i = 0; i < kRounds; ++i) {
944+
const std::wstring folder = L"GAME:\\rmrace\\" + (prefix + std::to_wstring(i));
945+
const std::wstring child = folder + (make_folder ? L"\\sub" : L"\\new.tmp");
946+
const DWORD disposition = i % 3 == 0 ? CREATE_NEW : i % 3 == 1 ? CREATE_ALWAYS : OPEN_ALWAYS;
947+
std::atomic<int> ready{0};
948+
HANDLE handle = INVALID_HANDLE_VALUE;
949+
bool made = false;
950+
DWORD create_error = 0;
951+
std::thread creator([&] {
952+
ready.fetch_add(1);
953+
while (ready.load() < 2) {
954+
}
955+
if (make_folder) {
956+
made = mkdir_w(child.c_str(), nullptr) != FALSE;
957+
} else {
958+
handle = create_w(child.c_str(), GENERIC_WRITE, 0, nullptr, disposition, 0, nullptr);
959+
made = handle != INVALID_HANDLE_VALUE;
960+
}
961+
create_error = made ? 0 : GetLastError();
962+
});
963+
ready.fetch_add(1);
964+
while (ready.load() < 2) {
965+
}
966+
for (int spin = 0; spin < (i % 64) * 64; ++spin) YieldProcessor();
967+
const bool removed = rmdir_w(folder.c_str()) != FALSE;
968+
const DWORD remove_error = removed ? 0 : GetLastError();
969+
creator.join();
970+
if (handle != INVALID_HANDLE_VALUE) ::CloseHandle(handle);
971+
if (made && removed) {
972+
++both;
973+
} else if (made && remove_error == ERROR_DIR_NOT_EMPTY) {
974+
++create_first;
975+
} else if (removed && create_error == ERROR_PATH_NOT_FOUND) {
976+
++remove_first;
977+
} else {
978+
++other;
979+
}
980+
// A folder the remove took away stays away, whatever the create did.
981+
if (removed) {
982+
SetLastError(0);
983+
if (attributes_w(folder.c_str()) != INVALID_FILE_ATTRIBUTES || GetLastError() != ERROR_FILE_NOT_FOUND)
984+
++back;
985+
}
986+
}
987+
std::printf("NOTE %s against RemoveDirectoryW, %d rounds: create first %d, remove first %d, both succeeded "
988+
"%d, other %d, removed folder back %d\n",
989+
what, kRounds, create_first, remove_first, both, other, back);
990+
const std::string w = what;
991+
check(both == 0, (w + " and RemoveDirectoryW of its folder never both succeed").c_str());
992+
check(other == 0, (w + " or RemoveDirectoryW fails as on the host (ERROR_PATH_NOT_FOUND or "
993+
"ERROR_DIR_NOT_EMPTY)").c_str());
994+
check(back == 0, (w + ": a folder RemoveDirectoryW removed stays removed").c_str());
995+
};
996+
race(false, L"f", "a creating CreateFileW");
997+
race(true, L"d", "CreateDirectoryW");
998+
}
999+
9301000
// MoveFile: the destination is in the overlay; a moved package file is deleted by a marker.
9311001
{
9321002
check(move_w(L"GAME:\\misc\\one.txt", L"GAME:\\misc\\moved.txt") != FALSE, "MoveFileW moves a package file");

0 commit comments

Comments
 (0)