diff --git a/CHANGELOG.md b/CHANGELOG.md index 67fc77c6..86bdedc7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,20 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game remains unsupported. ### Added +- `xgameruntime.dll!QueryApiImpl` now serves offline `XGameSave` and `XPackage` as COM `IUnknown` objects under BetterXen synthetic keys (#468, not yet closed). A title linked against Microsoft's `xgameruntime.lib` does not request these keys. Every synthetic key and COM slot order now lives in `shims/xgameruntime/synthetic_keys.h`, the single place to find or replace them. Signatures, structure layouts, `E_GS_*` values and container-name rules follow the public Microsoft Learn reference. + - **XGameSave:** provider init, containers, updates, blob writes, submit and read (both asynchronous), enumeration and the close calls. Saves are separated by SCID: each container is one file under `C:\bx_pls\\saves\\`, replaced atomically on submit. A named mutex per SCID directory serializes access across threads and processes. Damaged files (truncated, trailing bytes, duplicate or NUL-bearing names) read as `ERROR_FILE_CORRUPT`, and enumeration skips them and unreadable files with a log line. Offline choices where the reference is silent (16 MiB including blob names, 256-byte blob names, no sync, retry after a failed submit) are listed in `game_save.cpp`. + - **XPackage:** the running executable's directory stands in for the installed package: a stable `BXPKG…` identifier, `XPackageKind::Game` for it, and `XPackageMount` / mount-path queries that return that directory. + - **Lifetimes:** the last uninitialize closes every XGameSave and XPackage handle and drops unconsumed results. Closing a provider closes its containers and their updates. Each handle type has its own value range. An operation queued before an uninitialize completes with `E_GAMERUNTIME_NOT_INITIALIZED` without running. + - **Async:** results of the new operations go through the existing XAsync engine, including `XAsyncGetResultSize`, cancellation and reuse rules. A cancel that arrives after an operation started no longer reports `E_ABORT` for work that was done. An unconsumed result is kept until its block is reused or the runtime is uninitialized. + - **Tests:** `tests/conformance/test_xgameruntime_saves/` covers both families through `QueryApiImpl`, with its own copies of the keys, slot numbers, structure layouts and storage format. It checks: + - name rules, the write and read round trip, and the size limits; + - SCID isolation and enumeration; + - crafted damaged files, a failed replace that keeps the old save, and a successful one that replaces the file; + - 64 threaded and 160 cross-process concurrent submits; + - uninitialize with pending work, stale handles and released memory, and a non-ASCII executable directory. + + Each of eleven injected faults (non-atomic write, missing or per-process lock, ignored SCID, no-op close, lax parsing, uncounted names, retained results, stale work running, children kept after a provider close) makes it fail. + - **Not done:** validation against a caller linked to Microsoft's `xgameruntime.lib`, since these keys are BetterXen's own. `abi/defs/xgameruntime.def` is unchanged (49 exports). - Added `docs/research/d3dmetal-gpu-limits.md` and `tests/conformance/test_d3dmetal_gpu_limits/` (#453). The fixture is an original D3D12 compute test that loads the host `d3d12.dll` directly, with four original HLSL kernels and committed DXC 1.9.2609 output (`shaders/compile.sh` regenerates them). It skips with exit 77 below shader model 6.6. Required checks: - a kernel without `WaveSize` runs, and its lane indices form a permutation within each wave; - a per-texel spin lock with acquire and release fences and a 1024-try cap emulates 64-bit add and max with no dropped update and exact values. diff --git a/shims/xgameruntime/CMakeLists.txt b/shims/xgameruntime/CMakeLists.txt index 9c395fe9..8b6f4ffc 100644 --- a/shims/xgameruntime/CMakeLists.txt +++ b/shims/xgameruntime/CMakeLists.txt @@ -2,6 +2,8 @@ bx_add_shim_dll(xgameruntime xgameruntime xgameruntime.def xgameruntime.cpp task_queue.cpp com_dispatch.cpp + game_save.cpp + package.cpp ) target_link_libraries(xgameruntime PRIVATE bx_runtime_veh kernel32) target_compile_options(xgameruntime PRIVATE -fexceptions) diff --git a/shims/xgameruntime/game_save.cpp b/shims/xgameruntime/game_save.cpp new file mode 100644 index 00000000..96ddd354 --- /dev/null +++ b/shims/xgameruntime/game_save.cpp @@ -0,0 +1,930 @@ +/* + * Offline XGameSave over bottle-local storage (#468). + * + * Reached only through QueryApiImpl with the BetterXen synthetic xgamesave key; the key and + * the vtable slot order are in synthetic_keys.h. Nothing here is exported. + * + * Public reference (Microsoft Learn, gdk-2610, checked 2026-11-26): the XGameSave members + * page and the function and structure pages it links. The signatures, the + * XGameSaveContainerInfo / XGameSaveBlobInfo / XGameSaveBlob layouts, the E_GS_* values, + * the container-name rules and the 16 MB update limit come from there: + * https://learn.microsoft.com/en-us/gaming/gdk/docs/reference/system/xgamesave/xgamesave_members + * No Microsoft header, source or binary was used. + * + * Storage: each SCID has its own directory, \saves\, + * and each container is one file in it, .bxgs. Both ids are the 64-bit FNV-1a + * hash of the string's bytes (each byte taken as one UTF-16 code unit 0-255) as 16 lowercase + * hex digits; neither string is ever used as a path. A submitted update + * rewrites the file through a temporary file and MoveFileExW, so an update lands entirely or + * not at all. Every read and read-modify-write of a SCID directory holds a named mutex derived + * from that directory, so threads and processes sharing a title directory do not lose updates. + * The format is BetterXen-defined, little-endian: + * u32 magic "BXGS", u32 version 1, str name, str display name, i64 last-modified time_t, + * u32 blob count, then per blob: str name, u32 size, size bytes. (str = u32 length + bytes) + * A file is valid only if it is consumed exactly, its container name is valid and matches its + * file name, no string holds a NUL, and blob names are unique and within the limit below. + * + * Offline behaviour, where the public pages leave it open: + * - There is no service. syncOnDemand has no effect and needsSync is always false. + * - The provider needs a live XUser handle and a non-null SCID. Saves are separated by SCID. + * - A second write of the same blob in one update fails with E_INVALIDARG (the page allows + * one modification per blob per update but names no error). + * - "16 MB" for GS_MAX_BLOB_SIZE is read as 16 MiB, enforced on the staged total of blob + * names and data. + * - GS_MAX_BLOB_NAME_SIZE has no published value. BetterXen limits blob names to 256 bytes. + * - A null display name in CreateUpdate keeps the container's current display name. + * - While an update's submit is pending, writing to or submitting that update fails with + * E_ILLEGAL_METHOD_CALL. Once it completes, succeeded, failed or canceled, the update can + * be submitted again, so a failed submit can be retried without staging the data again. + * - Reading named blobs of a container that was never submitted fails with + * E_GS_BLOB_NOT_FOUND; reading all of them returns zero blobs. + * - A full disk on submit is E_GS_OUT_OF_LOCAL_STORAGE. + * - Closing a provider closes its containers and their updates; closing a container closes + * its updates. The last XGameRuntimeUninitialize closes every handle. + * - Paths of MAX_PATH or more (executable or storage) fail with ERROR_FILENAME_EXCED_RANGE. + */ +#include "runtime_internal.h" +#include "synthetic_keys.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "bx_log.h" + +namespace bx::gdk { +namespace { + +using synthetic::GameSaveSlot; + +// E_GS_* values listed on the XGameSave members page. +constexpr HRESULT kInvalidContainerName = static_cast(0x80830001u); +constexpr HRESULT kOutOfLocalStorage = static_cast(0x80830003u); +constexpr HRESULT kUpdateTooBig = static_cast(0x80830005u); +constexpr HRESULT kProvidedBufferTooSmall = static_cast(0x80830007u); +constexpr HRESULT kBlobNotFound = static_cast(0x80830008u); +constexpr HRESULT kFileCorrupt = HRESULT_FROM_WIN32(ERROR_FILE_CORRUPT); + +constexpr size_t kMaxUpdateBytes = 16u * 1024u * 1024u; +constexpr size_t kMaxContainerName = 256; +constexpr size_t kMaxBlobName = 256; + +struct ContainerInfo { // XGameSaveContainerInfo + const char* name; + const char* display_name; + uint32_t blob_count; + uint64_t total_size; + time_t last_modified_time; + bool needs_sync; +}; +static_assert(sizeof(time_t) == 8); +static_assert(offsetof(ContainerInfo, blob_count) == 16 && offsetof(ContainerInfo, total_size) == 24); +static_assert(offsetof(ContainerInfo, last_modified_time) == 32 && offsetof(ContainerInfo, needs_sync) == 40); + +struct BlobInfo { // XGameSaveBlobInfo + const char* name; + uint32_t size; +}; + +struct Blob { // XGameSaveBlob + BlobInfo info; + uint8_t* data; +}; +static_assert(sizeof(BlobInfo) == 16 && offsetof(Blob, data) == 16 && sizeof(Blob) == 24); + +using ContainerInfoCallback = bool(CALLBACK*)(const ContainerInfo*, void*); + +// FNV-1a over the string's bytes, each taken as one UTF-16 code unit 0-255, as 16 hex digits. +std::wstring hex_id(const std::string& text) { + std::wstring wide; + wide.reserve(text.size()); + for (const char c : text) wide.push_back(static_cast(static_cast(c))); + wchar_t id[17]; + std::swprintf(id, 17, L"%016llx", static_cast(fnv1a(wide.c_str()))); + return id; +} + +// --- Names --- + +bool name_char(char c) { + return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_'; +} + +// Rules from the XGameSaveCreateContainer page: an optional path part up to the last '/' +// (A-Z, a-z, 0-9, _, /) and a non-empty file part (A-Z, a-z, 0-9, _, ., -) that does not +// end in a period or contain "..". At most 256 characters. +bool valid_container_name(const char* name, size_t length) { + if (!name || length == 0 || length > kMaxContainerName) return false; + const char* end = name + length; + const char* file = name; + for (const char* c = name; c < end; ++c) { + if (*c == '/') file = c + 1; + } + for (const char* c = name; c < file; ++c) { + if (!name_char(*c) && *c != '/') return false; + } + if (file == end || end[-1] == '.') return false; + for (const char* c = file; c < end; ++c) { + if (!name_char(*c) && *c != '.' && *c != '-') return false; + if (c[0] == '.' && c + 1 < end && c[1] == '.') return false; + } + return true; +} + +bool valid_container_name(const char* name) { + return name && valid_container_name(name, strnlen(name, kMaxContainerName + 1)); +} + +bool valid_blob_name(const std::string& name) { + return !name.empty() && name.size() <= kMaxBlobName && name.find('\0') == std::string::npos; +} + +// --- Container files --- + +struct ContainerData { + std::string name; + std::string display_name; + int64_t last_modified = 0; + uint64_t total_size = 0; + std::map> blobs; // Data left empty when parsed without data. +}; + +constexpr uint32_t kMagic = 0x53475842; // "BXGS" +constexpr uint32_t kFormatVersion = 1; +constexpr wchar_t kExtension[] = L".bxgs"; + +void put_u32(std::vector& out, uint32_t value) { + for (int shift = 0; shift < 32; shift += 8) out.push_back(static_cast(value >> shift)); +} + +void put_u64(std::vector& out, uint64_t value) { + put_u32(out, static_cast(value)); + put_u32(out, static_cast(value >> 32)); +} + +void put_string(std::vector& out, const std::string& text) { + put_u32(out, static_cast(text.size())); + out.insert(out.end(), text.begin(), text.end()); +} + +std::vector serialize(const ContainerData& data) { + std::vector out; + put_u32(out, kMagic); + put_u32(out, kFormatVersion); + put_string(out, data.name); + put_string(out, data.display_name); + put_u64(out, static_cast(data.last_modified)); + put_u32(out, static_cast(data.blobs.size())); + for (const auto& [name, bytes] : data.blobs) { + put_string(out, name); + put_u32(out, static_cast(bytes.size())); + out.insert(out.end(), bytes.begin(), bytes.end()); + } + return out; +} + +class Reader { +public: + explicit Reader(const std::vector& bytes) : next_(bytes.data()), left_(bytes.size()) {} + + bool u32(uint32_t& value) { + if (left_ < 4) return false; + value = 0; + for (int i = 0; i < 4; ++i) value |= static_cast(next_[i]) << (8 * i); + next_ += 4; + left_ -= 4; + return true; + } + + bool u64(uint64_t& value) { + uint32_t low, high; + if (!u32(low) || !u32(high)) return false; + value = (static_cast(high) << 32) | low; + return true; + } + + bool bytes(size_t size, const uint8_t*& data) { + if (left_ < size) return false; + data = next_; + next_ += size; + left_ -= size; + return true; + } + + // A NUL cannot pass through the C string APIs, so a stored one is corruption. + bool string(std::string& text) { + uint32_t size; + const uint8_t* data; + if (!u32(size) || !bytes(size, data) || std::memchr(data, 0, size)) return false; + text.assign(reinterpret_cast(data), size); + return true; + } + + bool done() const { return left_ == 0; } + +private: + const uint8_t* next_; + size_t left_; +}; + +// with_data false validates the whole file but keeps only names and sizes. +bool parse(const std::vector& bytes, ContainerData& data, bool with_data) { + Reader in(bytes); + uint32_t magic, version, count; + uint64_t modified; + if (!in.u32(magic) || magic != kMagic || !in.u32(version) || version != kFormatVersion || + !in.string(data.name) || !valid_container_name(data.name.c_str(), data.name.size()) || + !in.string(data.display_name) || !in.u64(modified) || !in.u32(count)) { + return false; + } + data.last_modified = static_cast(modified); + for (uint32_t i = 0; i < count; ++i) { + std::string name; + uint32_t size; + const uint8_t* blob; + if (!in.string(name) || !valid_blob_name(name) || !in.u32(size) || !in.bytes(size, blob)) return false; + auto content = with_data ? std::vector(blob, blob + size) : std::vector(); + if (!data.blobs.emplace(std::move(name), std::move(content)).second) return false; + data.total_size += size; + } + return in.done(); +} + +std::wstring container_file(const std::wstring& dir, const std::string& name) { + return dir + L"\\" + hex_id(name) + kExtension; +} + +HRESULT read_file(const std::wstring& path, std::vector& out, bool& exists) { + exists = false; + // Share everything, so a reader never blocks another process's replace. + const HANDLE file = CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, + nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + if (file == INVALID_HANDLE_VALUE) { + const auto error = GetLastError(); + return error == ERROR_FILE_NOT_FOUND || error == ERROR_PATH_NOT_FOUND ? S_OK : HRESULT_FROM_WIN32(error); + } + exists = true; + HRESULT hr = S_OK; + LARGE_INTEGER size{}; + if (!GetFileSizeEx(file, &size)) { + hr = HRESULT_FROM_WIN32(GetLastError()); + } else { + try { + out.resize(static_cast(size.QuadPart)); + } catch (const std::bad_alloc&) { + hr = E_OUTOFMEMORY; + } + size_t done = 0; + while (SUCCEEDED(hr) && done < out.size()) { + const DWORD chunk = static_cast(std::min(out.size() - done, 1u << 30)); + DWORD got = 0; + if (!ReadFile(file, out.data() + done, chunk, &got, nullptr)) hr = HRESULT_FROM_WIN32(GetLastError()); + else if (got == 0) hr = HRESULT_FROM_WIN32(ERROR_HANDLE_EOF); + done += got; + } + } + CloseHandle(file); + return hr; +} + +HRESULT write_error(DWORD error) { + return error == ERROR_DISK_FULL || error == ERROR_HANDLE_DISK_FULL ? kOutOfLocalStorage + : HRESULT_FROM_WIN32(error); +} + +HRESULT write_file_atomic(const std::wstring& path, const std::vector& bytes) { + const std::wstring temp = path + L"." + std::to_wstring(GetCurrentProcessId()) + L".tmp"; + const HANDLE file = + CreateFileW(temp.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + if (file == INVALID_HANDLE_VALUE) return write_error(GetLastError()); + HRESULT hr = S_OK; + size_t done = 0; + while (SUCCEEDED(hr) && done < bytes.size()) { + const DWORD chunk = static_cast(std::min(bytes.size() - done, 1u << 30)); + DWORD wrote = 0; + if (!WriteFile(file, bytes.data() + done, chunk, &wrote, nullptr)) hr = write_error(GetLastError()); + done += wrote; + } + if (SUCCEEDED(hr) && !FlushFileBuffers(file)) hr = write_error(GetLastError()); + CloseHandle(file); + if (SUCCEEDED(hr) && !MoveFileExW(temp.c_str(), path.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) { + hr = write_error(GetLastError()); + } + if (FAILED(hr)) DeleteFileW(temp.c_str()); + return hr; +} + +// Logs the file name only: bx_log_emit does not escape, and a Windows file name cannot hold +// a backslash, quote or control character, so it is always valid JSON string content. The +// directory is the title's saves directory for one SCID. +void log_bad_file(const char* event, const std::wstring& path) { + const auto slash = path.find_last_of(L'\\'); + const std::wstring name = slash == std::wstring::npos ? path : path.substr(slash + 1); + char detail[MAX_PATH * 3 + 8]; + const int bytes = WideCharToMultiByte(CP_UTF8, 0, name.c_str(), -1, detail, sizeof(detail), nullptr, nullptr); + if (bytes <= 0) std::snprintf(detail, sizeof(detail), "(unprintable file name)"); + bx_log_emit(BX_LOG_WARN, "xgamesave", event, detail); +} + +// Holds the named mutex for one SCID directory. Abandonment by a crashed owner is not an +// error: every file is replaced atomically, so a half-done update never reaches disk. +class DirectoryLock { +public: + explicit DirectoryLock(const std::wstring& dir) { + wchar_t lower[MAX_PATH]; + if (!LCMapStringEx(LOCALE_NAME_INVARIANT, LCMAP_LOWERCASE, dir.c_str(), -1, lower, MAX_PATH, nullptr, + nullptr, 0)) { + status_ = HRESULT_FROM_WIN32(GetLastError()); + return; + } + wchar_t name[64]; + std::swprintf(name, 64, L"Local\\BetterXen.XGameSave.%016llx", static_cast(fnv1a(lower))); + mutex_ = CreateMutexW(nullptr, FALSE, name); + if (!mutex_) { + status_ = HRESULT_FROM_WIN32(GetLastError()); + return; + } + const DWORD wait = WaitForSingleObject(mutex_, INFINITE); + status_ = wait == WAIT_OBJECT_0 || wait == WAIT_ABANDONED ? S_OK : HRESULT_FROM_WIN32(GetLastError()); + } + + ~DirectoryLock() { + if (!mutex_) return; + if (SUCCEEDED(status_)) ReleaseMutex(mutex_); + CloseHandle(mutex_); + } + + DirectoryLock(const DirectoryLock&) = delete; + DirectoryLock& operator=(const DirectoryLock&) = delete; + + HRESULT status() const { return status_; } + +private: + HANDLE mutex_ = nullptr; + HRESULT status_ = E_FAIL; +}; + +// Caller holds the DirectoryLock for dir. +HRESULT load_container(const std::wstring& dir, const std::string& name, ContainerData& data, bool& exists) { + const auto path = container_file(dir, name); + std::vector bytes; + auto hr = read_file(path, bytes, exists); + if (FAILED(hr) || !exists) return hr; + if (!parse(bytes, data, true)) { + log_bad_file("corrupt_container", path); + return kFileCorrupt; + } + if (data.name != name) { + log_bad_file("container_id_collision", path); + return HRESULT_FROM_WIN32(ERROR_FILE_EXISTS); + } + return S_OK; +} + +// Caller holds the DirectoryLock for dir. Files that cannot be read or parsed are logged and +// skipped, so one bad file does not hide the others. +HRESULT list_containers(const std::wstring& dir, std::vector& out) { + WIN32_FIND_DATAW found; + const HANDLE search = FindFirstFileW((dir + L"\\*" + kExtension).c_str(), &found); + if (search == INVALID_HANDLE_VALUE) { + const auto error = GetLastError(); + return error == ERROR_FILE_NOT_FOUND || error == ERROR_PATH_NOT_FOUND ? S_OK : HRESULT_FROM_WIN32(error); + } + HRESULT hr = S_OK; + do { + const std::wstring file = found.cFileName; + constexpr size_t ext = std::size(kExtension) - 1; + if ((found.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) || file.size() <= ext || + file.compare(file.size() - ext, ext, kExtension) != 0) { + continue; + } + const std::wstring path = dir + L"\\" + file; + std::vector bytes; + bool exists; + ContainerData data; + const auto read = read_file(path, bytes, exists); + if (read == E_OUTOFMEMORY) { + hr = read; + break; + } + if (FAILED(read)) { + log_bad_file("unreadable_container", path); + continue; + } + if (!exists) continue; // Replaced or removed since the search returned it. + if (!parse(bytes, data, false) || container_file(dir, data.name) != path) { + log_bad_file("corrupt_container", path); + continue; + } + try { + out.push_back(std::move(data)); + } catch (const std::bad_alloc&) { + hr = E_OUTOFMEMORY; + } + } while (SUCCEEDED(hr) && FindNextFileW(search, &found)); + FindClose(search); + return hr; +} + +HRESULT saves_directory(const std::string& scid, std::wstring& dir) { + wchar_t root[MAX_PATH]; + auto hr = title_storage_directory(root); + if (FAILED(hr)) return hr; + const std::wstring saves = std::wstring(root) + L"\\saves"; + hr = ensure_directory(saves.c_str()); + if (FAILED(hr)) return hr; + dir = saves + L"\\" + hex_id(scid); + if (dir.size() >= MAX_PATH) return HRESULT_FROM_WIN32(ERROR_FILENAME_EXCED_RANGE); + return ensure_directory(dir.c_str()); +} + +// --- Handles --- +// Lock order: the runtime lock (taken by active_runtime_generation, is_valid_user, around +// consume callbacks and around release_game_save_state) before handle_mutex. Nothing here +// calls into the runtime while holding handle_mutex. + +struct Provider { + uint32_t generation; + std::wstring dir; +}; + +struct Container { + void* provider; + std::string name; +}; + +struct Update { + void* container; + bool keep_display_name; + std::string display_name; + std::map> writes; + size_t staged_bytes = 0; + // Set while a submit of this update is queued or running; cleared by that operation. + std::shared_ptr> pending; +}; + +std::mutex handle_mutex; +std::unordered_map providers; +std::unordered_map containers; +std::unordered_map updates; + +// Each handle type has its own range (tag in bits 40-43), so a handle of one type is never +// a valid handle of another. package.cpp uses tag 4. +enum : uintptr_t { kProviderTag = 1, kContainerTag = 2, kUpdateTag = 3 }; +uintptr_t handle_counter = 0; + +void* next_handle(uintptr_t tag) { + ++handle_counter; + return reinterpret_cast(tag << 40 | (handle_counter & 0xFFFFFFFFFu) << 4); +} + +// The finders below require handle_mutex. A handle from before the last uninitialize, or +// one whose provider was closed, is not found. +const Provider* find_provider(void* handle, uint32_t generation) { + const auto found = providers.find(handle); + if (found == providers.end() || generation == 0 || found->second.generation != generation) return nullptr; + return &found->second; +} + +const Container* find_container(void* handle, uint32_t generation, const Provider** provider) { + const auto found = containers.find(handle); + if (found == containers.end()) return nullptr; + *provider = find_provider(found->second.provider, generation); + return *provider ? &found->second : nullptr; +} + +Update* find_update(void* handle, uint32_t generation, const Container** container, const Provider** provider) { + const auto found = updates.find(handle); + if (found == updates.end()) return nullptr; + *container = find_container(found->second.container, generation, provider); + return *container ? &found->second : nullptr; +} + +template +HRESULT insert_handle(Map& map, uintptr_t tag, Value&& value, void** out) { + void* handle = next_handle(tag); + try { + map.emplace(handle, std::forward(value)); + } catch (const std::bad_alloc&) { + return E_OUTOFMEMORY; + } + *out = handle; + return S_OK; +} + +// Caller holds handle_mutex. +void erase_updates_of(void* container) { + std::erase_if(updates, [&](const auto& entry) { return entry.second.container == container; }); +} + +// Caller holds handle_mutex. +void erase_containers_of(void* provider) { + for (auto it = containers.begin(); it != containers.end();) { + if (it->second.provider == provider) { + erase_updates_of(it->first); + it = containers.erase(it); + } else { + ++it; + } + } +} + +// --- Async operations --- + +enum : uint32_t { kInitProviderOp = 0x58475301, kSubmitUpdateOp = 0x58475302, kReadBlobsOp = 0x58475303 }; + +class InitProviderOp final : public AsyncOp { +public: + uint32_t generation = 0; + std::string scid; + std::wstring dir; + + uint32_t kind() const override { return kInitProviderOp; } + HRESULT execute() override try { + return saves_directory(scid, dir); + } catch (const std::bad_alloc&) { + return E_OUTOFMEMORY; + } + size_t result_size() const override { return sizeof(void*); } +}; + +class SubmitUpdateOp final : public AsyncOp { +public: + std::wstring dir; + std::string name; + bool keep_display_name = false; + std::string display_name; + std::map> writes; + std::shared_ptr> pending; + + // Covers cancellation and a submission that never ran. + ~SubmitUpdateOp() override { finish(); } + + uint32_t kind() const override { return kSubmitUpdateOp; } + size_t result_size() const override { return 0; } + + HRESULT execute() override { + const auto hr = write(); + finish(); + return hr; + } + +private: + // Once per op: a resubmit shares the flag, so an old op must not clear it again later. + void finish() { + if (pending) pending->store(false); + pending.reset(); + } + + HRESULT write() try { + DirectoryLock lock(dir); + if (FAILED(lock.status())) return lock.status(); + ContainerData data; + bool exists = false; + auto hr = load_container(dir, name, data, exists); + if (FAILED(hr)) return hr; + if (!exists) data.name = name; + if (!keep_display_name) data.display_name = display_name; + for (auto& [blob, bytes] : writes) data.blobs[blob] = std::move(bytes); + data.last_modified = static_cast(std::time(nullptr)); + return write_file_atomic(container_file(dir, name), serialize(data)); + } catch (const std::bad_alloc&) { + return E_OUTOFMEMORY; + } +}; + +class ReadBlobsOp final : public AsyncOp { +public: + std::wstring dir; + std::string name; + std::vector wanted; // Empty: every blob. + std::vector>> found; + size_t bytes = 0; + + uint32_t kind() const override { return kReadBlobsOp; } + size_t result_size() const override { return bytes; } + + HRESULT execute() override try { + DirectoryLock lock(dir); + if (FAILED(lock.status())) return lock.status(); + ContainerData data; + bool exists = false; + const auto hr = load_container(dir, name, data, exists); + if (FAILED(hr)) return hr; + if (wanted.empty()) { + for (auto& [blob, content] : data.blobs) found.emplace_back(blob, std::move(content)); + } else { + for (const auto& blob : wanted) { + const auto match = data.blobs.find(blob); + if (match == data.blobs.end()) return kBlobNotFound; + found.emplace_back(blob, std::move(match->second)); + } + } + bytes = found.size() * sizeof(Blob); + for (const auto& [blob, content] : found) bytes += blob.size() + 1 + content.size(); + return S_OK; + } catch (const std::bad_alloc&) { + return E_OUTOFMEMORY; + } + + // Layout in the caller's buffer: the Blob array, then all data, then the names. + void copy_to(Blob* out) const { + auto* cursor = reinterpret_cast(out) + found.size() * sizeof(Blob); + for (size_t i = 0; i < found.size(); ++i) { + const auto& content = found[i].second; + out[i].info.size = static_cast(content.size()); + out[i].data = cursor; + if (!content.empty()) std::memcpy(cursor, content.data(), content.size()); + cursor += content.size(); + } + for (size_t i = 0; i < found.size(); ++i) { + const auto& blob = found[i].first; + std::memcpy(cursor, blob.c_str(), blob.size() + 1); + out[i].info.name = reinterpret_cast(cursor); + cursor += blob.size() + 1; + } + } +}; + +HRESULT stale_handle_error(uint32_t generation) { + return generation ? kRuntimeInvalidHandle : kRuntimeNotInitialized; +} + +// --- Slots --- + +HRESULT WINAPI initialize_provider_async(void*, void* user, const char* scid, bool /*sync_on_demand*/, + void* async) { + if (!async) return E_POINTER; + if (!scid) return E_INVALIDARG; + const auto generation = active_runtime_generation(); + if (!is_valid_user(user)) return stale_handle_error(generation); + std::unique_ptr op(new (std::nothrow) InitProviderOp); + if (!op) return E_OUTOFMEMORY; + try { + op->scid = scid; + } catch (const std::bad_alloc&) { + return E_OUTOFMEMORY; + } + op->generation = generation; + return begin_async_op(async, std::move(op)); +} + +HRESULT WINAPI initialize_provider_result(void*, void* async, void** provider) { + if (!provider) return E_POINTER; + *provider = nullptr; + return consume_async_op(async, kInitProviderOp, [&](AsyncOp& base) { + auto& op = static_cast(base); + std::lock_guard lock(handle_mutex); + return insert_handle(providers, kProviderTag, Provider{op.generation, op.dir}, provider); + }); +} + +void WINAPI close_provider(void*, void* provider) { + std::lock_guard lock(handle_mutex); + if (providers.erase(provider)) erase_containers_of(provider); +} + +HRESULT WINAPI create_container(void*, void* provider, const char* name, void** out) { + if (!out) return E_POINTER; + *out = nullptr; + const auto generation = active_runtime_generation(); + std::lock_guard lock(handle_mutex); + if (!find_provider(provider, generation)) return stale_handle_error(generation); + if (!valid_container_name(name)) return kInvalidContainerName; + try { + return insert_handle(containers, kContainerTag, Container{provider, name}, out); + } catch (const std::bad_alloc&) { + return E_OUTOFMEMORY; + } +} + +void WINAPI close_container(void*, void* container) { + std::lock_guard lock(handle_mutex); + if (containers.erase(container)) erase_updates_of(container); +} + +HRESULT WINAPI create_update(void*, void* container, const char* display_name, void** out) { + if (!out) return E_POINTER; + *out = nullptr; + const auto generation = active_runtime_generation(); + std::lock_guard lock(handle_mutex); + const Provider* provider = nullptr; + if (!find_container(container, generation, &provider)) return stale_handle_error(generation); + try { + Update staged; + staged.container = container; + staged.keep_display_name = display_name == nullptr; + staged.display_name = display_name ? display_name : ""; + staged.pending = std::make_shared>(false); + return insert_handle(updates, kUpdateTag, std::move(staged), out); + } catch (const std::bad_alloc&) { + return E_OUTOFMEMORY; + } +} + +void WINAPI close_update(void*, void* update) { + std::lock_guard lock(handle_mutex); + updates.erase(update); +} + +HRESULT WINAPI submit_blob_write(void*, void* update, const char* blob_name, const uint8_t* data, size_t size) { + if (!blob_name) return E_INVALIDARG; + const size_t name_length = strnlen(blob_name, kMaxBlobName + 1); + if (name_length == 0 || name_length > kMaxBlobName) return E_INVALIDARG; + if (!data && size) return E_POINTER; + const auto generation = active_runtime_generation(); + std::lock_guard lock(handle_mutex); + const Container* container = nullptr; + const Provider* provider = nullptr; + auto* staged = find_update(update, generation, &container, &provider); + if (!staged) return stale_handle_error(generation); + if (staged->pending->load()) return kIllegalMethodCall; + if (staged->writes.contains(blob_name)) return E_INVALIDARG; + if (size > kMaxUpdateBytes - staged->staged_bytes || + name_length > kMaxUpdateBytes - staged->staged_bytes - size) { + return kUpdateTooBig; + } + try { + staged->writes.emplace(blob_name, std::vector(data, data + size)); + } catch (const std::bad_alloc&) { + return E_OUTOFMEMORY; + } + staged->staged_bytes += name_length + size; + return S_OK; +} + +HRESULT WINAPI submit_update_async(void*, void* update, void* async) { + if (!async) return E_POINTER; + std::unique_ptr op(new (std::nothrow) SubmitUpdateOp); + if (!op) return E_OUTOFMEMORY; + const auto generation = active_runtime_generation(); + { + std::lock_guard lock(handle_mutex); + const Container* container = nullptr; + const Provider* provider = nullptr; + auto* staged = find_update(update, generation, &container, &provider); + if (!staged) return stale_handle_error(generation); + if (staged->pending->load()) return kIllegalMethodCall; + try { + op->dir = provider->dir; + op->name = container->name; + op->keep_display_name = staged->keep_display_name; + op->display_name = staged->display_name; + op->writes = staged->writes; + } catch (const std::bad_alloc&) { + return E_OUTOFMEMORY; + } + staged->pending->store(true); + op->pending = staged->pending; + } + // On failure begin_async_op destroys op, whose destructor clears the pending flag. + return begin_async_op(async, std::move(op)); +} + +HRESULT WINAPI submit_update_result(void*, void* async) { + return consume_async_op(async, kSubmitUpdateOp, [](AsyncOp&) { return S_OK; }); +} + +HRESULT WINAPI read_blob_data_async(void*, void* container, const char** names, uint32_t count, void* async) { + if (!async) return E_POINTER; + if (count && !names) return E_INVALIDARG; + std::unique_ptr op(new (std::nothrow) ReadBlobsOp); + if (!op) return E_OUTOFMEMORY; + try { + for (uint32_t i = 0; i < count; ++i) { + if (!names[i] || !*names[i]) return E_INVALIDARG; + if (std::find(op->wanted.begin(), op->wanted.end(), names[i]) != op->wanted.end()) return E_INVALIDARG; + op->wanted.emplace_back(names[i]); + } + const auto generation = active_runtime_generation(); + std::lock_guard lock(handle_mutex); + const Provider* provider = nullptr; + const auto* open = find_container(container, generation, &provider); + if (!open) return stale_handle_error(generation); + op->dir = provider->dir; + op->name = open->name; + } catch (const std::bad_alloc&) { + return E_OUTOFMEMORY; + } + return begin_async_op(async, std::move(op)); +} + +HRESULT WINAPI read_blob_data_result(void*, void* async, size_t size, Blob* blobs, uint32_t* count) { + if (!count) return E_POINTER; + *count = 0; + return consume_async_op(async, kReadBlobsOp, [&](AsyncOp& base) { + const auto& op = static_cast(base); + if (size < op.bytes) return kProvidedBufferTooSmall; + if (op.bytes && !blobs) return E_POINTER; + op.copy_to(blobs); + *count = static_cast(op.found.size()); + return S_OK; + }); +} + +HRESULT WINAPI enumerate_container_info(void*, void* provider, void* context, ContainerInfoCallback callback) { + if (!callback) return E_INVALIDARG; + const auto generation = active_runtime_generation(); + std::vector list; + try { + std::wstring dir; + { + std::lock_guard lock(handle_mutex); + const auto* open = find_provider(provider, generation); + if (!open) return stale_handle_error(generation); + dir = open->dir; + } + DirectoryLock lock(dir); + if (FAILED(lock.status())) return lock.status(); + const auto hr = list_containers(dir, list); + if (FAILED(hr)) return hr; + } catch (const std::bad_alloc&) { + return E_OUTOFMEMORY; + } + std::sort(list.begin(), list.end(), [](const auto& a, const auto& b) { return a.name < b.name; }); + // No lock is held here, so the callback may call back into XGameSave. + for (const auto& data : list) { + const ContainerInfo info{data.name.c_str(), data.display_name.c_str(), + static_cast(data.blobs.size()), data.total_size, + static_cast(data.last_modified), false}; + if (!callback(&info, context)) break; + } + return S_OK; +} + +// --- COM object --- + +HRESULT WINAPI query_interface(void* self, const GUID* iid, void** out) { + if (!out) return E_POINTER; + *out = nullptr; + if (!iid) return E_INVALIDARG; + constexpr GUID own = synthetic::key(synthetic::kGameSave.iid); + if (IsEqualGUID(*iid, kIUnknownIid) || IsEqualGUID(*iid, own)) { + *out = self; + return S_OK; + } + return E_NOINTERFACE; +} + +// A process-lifetime singleton: reference counting has nothing to free. +ULONG WINAPI add_ref(void*) { return 1; } +ULONG WINAPI release(void*) { return 1; } + +template +const void* slot_fn(Fn fn) { + return reinterpret_cast(fn); +} + +constexpr size_t at(GameSaveSlot slot) { return static_cast(slot); } + +const std::array kVtbl = [] { + std::array v{}; + v[at(GameSaveSlot::QueryInterface)] = slot_fn(&query_interface); + v[at(GameSaveSlot::AddRef)] = slot_fn(&add_ref); + v[at(GameSaveSlot::Release)] = slot_fn(&release); + v[at(GameSaveSlot::InitializeProviderAsync)] = slot_fn(&initialize_provider_async); + v[at(GameSaveSlot::InitializeProviderResult)] = slot_fn(&initialize_provider_result); + v[at(GameSaveSlot::CloseProvider)] = slot_fn(&close_provider); + v[at(GameSaveSlot::CreateContainer)] = slot_fn(&create_container); + v[at(GameSaveSlot::CloseContainer)] = slot_fn(&close_container); + v[at(GameSaveSlot::CreateUpdate)] = slot_fn(&create_update); + v[at(GameSaveSlot::CloseUpdate)] = slot_fn(&close_update); + v[at(GameSaveSlot::SubmitBlobWrite)] = slot_fn(&submit_blob_write); + v[at(GameSaveSlot::SubmitUpdateAsync)] = slot_fn(&submit_update_async); + v[at(GameSaveSlot::SubmitUpdateResult)] = slot_fn(&submit_update_result); + v[at(GameSaveSlot::ReadBlobDataAsync)] = slot_fn(&read_blob_data_async); + v[at(GameSaveSlot::ReadBlobDataResult)] = slot_fn(&read_blob_data_result); + v[at(GameSaveSlot::EnumerateContainerInfo)] = slot_fn(&enumerate_container_info); + return v; +}(); + +struct ComObject { + const void* const* vtbl; +}; +const ComObject kObject{kVtbl.data()}; + +} // namespace + +const void* const game_save_object = &kObject; + +void release_game_save_state() { + std::lock_guard lock(handle_mutex); + updates.clear(); + containers.clear(); + providers.clear(); +} + +} // namespace bx::gdk diff --git a/shims/xgameruntime/package.cpp b/shims/xgameruntime/package.cpp new file mode 100644 index 00000000..1c96271c --- /dev/null +++ b/shims/xgameruntime/package.cpp @@ -0,0 +1,236 @@ +/* + * Offline XPackage identity and mount queries (#468). + * + * Reached only through QueryApiImpl with the BetterXen synthetic xpackage key; the key and + * the vtable slot order are in synthetic_keys.h. Nothing here is exported. + * + * Public reference (Microsoft Learn, gdk-2610, checked 2026-11-26): the XPackage members + * page, the pages for the functions below, and XPackageKind (enum class : uint32_t + * { Game, Content, PublisherContent }, so Game is 0): + * https://learn.microsoft.com/en-us/gaming/gdk/docs/reference/system/xpackage/xpackage_members + * No Microsoft header, source or binary was used. + * + * Offline behaviour: the running executable's directory stands in for the installed package. + * - The identifier is "BXPKG" + 16 hex digits of the FNV-1a hash of that directory + * (lowercased), so it is stable for a directory and differs between directories. + * XPACKAGE_IDENTIFIER_MAX_LENGTH has no published value; this identifier needs 22 bytes. + * - GetPackageKind reports Game for that identifier and ERROR_NOT_FOUND for any other. + * - Mount (the documented, deprecated XPackageMount) accepts only that identifier, and the + * mount path is the executable's directory. On Windows only content packages can be + * mounted; BetterXen allows the game's own package so titles can locate their files. + * - The last XGameRuntimeUninitialize closes every mount handle. + * - An executable path of MAX_PATH or more fails with ERROR_FILENAME_EXCED_RANGE. + */ +#include "runtime_internal.h" +#include "synthetic_keys.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace bx::gdk { +namespace { + +using synthetic::PackageSlot; + +constexpr uint32_t kPackageKindGame = 0; +constexpr HRESULT kNotFound = HRESULT_FROM_WIN32(ERROR_NOT_FOUND); +constexpr char kIdPrefix[] = "BXPKG"; +constexpr size_t kIdBytes = sizeof(kIdPrefix) - 1 + 16 + 1; + +HRESULT executable_directory(std::wstring& dir) { + wchar_t path[MAX_PATH]; + const auto hr = executable_path(path); + if (FAILED(hr)) return hr; + wchar_t* slash = std::wcsrchr(path, L'\\'); + if (!slash) return HRESULT_FROM_WIN32(ERROR_BAD_PATHNAME); + // Keep the separator of a drive root ("C:\"). + slash[slash == path + 2 && path[1] == L':' ? 1 : 0] = L'\0'; + dir = path; + return S_OK; +} + +HRESULT current_identifier(char (&id)[kIdBytes]) { + std::wstring dir; + auto hr = executable_directory(dir); + if (FAILED(hr)) return hr; + wchar_t lower[MAX_PATH]; + if (!LCMapStringEx(LOCALE_NAME_INVARIANT, LCMAP_LOWERCASE, dir.c_str(), -1, lower, MAX_PATH, nullptr, nullptr, 0)) { + return HRESULT_FROM_WIN32(GetLastError()); + } + std::snprintf(id, kIdBytes, "%s%016llx", kIdPrefix, static_cast(fnv1a(lower))); + return S_OK; +} + +HRESULT is_current_package(const char* identifier, bool& match) { + char id[kIdBytes]; + const auto hr = current_identifier(id); + match = SUCCEEDED(hr) && std::strcmp(identifier, id) == 0; + return hr; +} + +struct Mount { + uint32_t generation; + std::string path; // UTF-8 +}; + +std::mutex mount_mutex; +uintptr_t handle_counter = 0; +std::unordered_map mounts; + +// Mount handles use tag 4 in bits 40-43, a range no XGameSave handle uses (game_save.cpp). +constexpr uintptr_t kMountTag = 4; + +// Caller holds mount_mutex. +const Mount* find_mount(void* handle, uint32_t generation) { + const auto found = mounts.find(handle); + if (found == mounts.end() || generation == 0 || found->second.generation != generation) return nullptr; + return &found->second; +} + +HRESULT stale_handle_error(uint32_t generation) { + return generation ? kRuntimeInvalidHandle : kRuntimeNotInitialized; +} + +// --- Slots --- + +HRESULT WINAPI get_current_process_package_identifier(void*, size_t size, char* buffer) { + if (!buffer) return E_POINTER; + if (!active_runtime_generation()) return kRuntimeNotInitialized; + char id[kIdBytes]; + const auto hr = current_identifier(id); + if (FAILED(hr)) return hr; + if (size < kIdBytes) return kInsufficientBuffer; + std::memcpy(buffer, id, kIdBytes); + return S_OK; +} + +HRESULT WINAPI get_package_kind(void*, const char* identifier, uint32_t* kind) { + if (!kind) return E_POINTER; + if (!identifier) return E_INVALIDARG; + if (!active_runtime_generation()) return kRuntimeNotInitialized; + bool match = false; + const auto hr = is_current_package(identifier, match); + if (FAILED(hr)) return hr; + if (!match) return kNotFound; + *kind = kPackageKindGame; + return S_OK; +} + +HRESULT WINAPI mount(void*, const char* identifier, void** out) { + if (!out) return E_POINTER; + *out = nullptr; + if (!identifier) return E_INVALIDARG; + const auto generation = active_runtime_generation(); + if (!generation) return kRuntimeNotInitialized; + bool match = false; + auto hr = is_current_package(identifier, match); + if (FAILED(hr)) return hr; + if (!match) return kNotFound; + + std::wstring dir; + hr = executable_directory(dir); + if (FAILED(hr)) return hr; + const int bytes = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, dir.c_str(), -1, nullptr, 0, nullptr, nullptr); + if (bytes <= 0) return HRESULT_FROM_WIN32(GetLastError()); + try { + std::string path(static_cast(bytes), '\0'); + WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, dir.c_str(), -1, path.data(), bytes, nullptr, nullptr); + path.pop_back(); // The terminator is added back on copy-out. + std::lock_guard lock(mount_mutex); + ++handle_counter; + void* handle = reinterpret_cast(kMountTag << 40 | (handle_counter & 0xFFFFFFFFFu) << 4); + mounts.emplace(handle, Mount{generation, std::move(path)}); + *out = handle; + } catch (const std::bad_alloc&) { + return E_OUTOFMEMORY; + } + return S_OK; +} + +HRESULT WINAPI get_mount_path_size(void*, void* handle, size_t* size) { + if (!size) return E_POINTER; + *size = 0; + const auto generation = active_runtime_generation(); + std::lock_guard lock(mount_mutex); + const auto* open = find_mount(handle, generation); + if (!open) return stale_handle_error(generation); + *size = open->path.size() + 1; + return S_OK; +} + +HRESULT WINAPI get_mount_path(void*, void* handle, size_t size, char* path) { + if (!path) return E_POINTER; + const auto generation = active_runtime_generation(); + std::lock_guard lock(mount_mutex); + const auto* open = find_mount(handle, generation); + if (!open) return stale_handle_error(generation); + if (size < open->path.size() + 1) return kInsufficientBuffer; + std::memcpy(path, open->path.c_str(), open->path.size() + 1); + return S_OK; +} + +void WINAPI close_mount_handle(void*, void* handle) { + std::lock_guard lock(mount_mutex); + mounts.erase(handle); +} + +// --- COM object --- + +HRESULT WINAPI query_interface(void* self, const GUID* iid, void** out) { + if (!out) return E_POINTER; + *out = nullptr; + if (!iid) return E_INVALIDARG; + constexpr GUID own = synthetic::key(synthetic::kPackage.iid); + if (IsEqualGUID(*iid, kIUnknownIid) || IsEqualGUID(*iid, own)) { + *out = self; + return S_OK; + } + return E_NOINTERFACE; +} + +// A process-lifetime singleton: reference counting has nothing to free. +ULONG WINAPI add_ref(void*) { return 1; } +ULONG WINAPI release(void*) { return 1; } + +template +const void* slot_fn(Fn fn) { + return reinterpret_cast(fn); +} + +constexpr size_t at(PackageSlot slot) { return static_cast(slot); } + +const std::array kVtbl = [] { + std::array v{}; + v[at(PackageSlot::QueryInterface)] = slot_fn(&query_interface); + v[at(PackageSlot::AddRef)] = slot_fn(&add_ref); + v[at(PackageSlot::Release)] = slot_fn(&release); + v[at(PackageSlot::GetCurrentProcessPackageIdentifier)] = slot_fn(&get_current_process_package_identifier); + v[at(PackageSlot::GetPackageKind)] = slot_fn(&get_package_kind); + v[at(PackageSlot::Mount)] = slot_fn(&mount); + v[at(PackageSlot::GetMountPathSize)] = slot_fn(&get_mount_path_size); + v[at(PackageSlot::GetMountPath)] = slot_fn(&get_mount_path); + v[at(PackageSlot::CloseMountHandle)] = slot_fn(&close_mount_handle); + return v; +}(); + +struct ComObject { + const void* const* vtbl; +}; +const ComObject kObject{kVtbl.data()}; + +} // namespace + +const void* const package_object = &kObject; + +void release_package_state() { + std::lock_guard lock(mount_mutex); + mounts.clear(); +} + +} // namespace bx::gdk diff --git a/shims/xgameruntime/runtime_internal.h b/shims/xgameruntime/runtime_internal.h new file mode 100644 index 00000000..600e0e9b --- /dev/null +++ b/shims/xgameruntime/runtime_internal.h @@ -0,0 +1,75 @@ +#pragma once + +// Internal interfaces shared by the xgameruntime.dll translation units. Nothing here is exported. + +#include + +#include +#include +#include +#include + +namespace bx::gdk { + +// ABI values checked against Microsoft's public PC GDK 2510.5.6322 (see xgameruntime.cpp). +constexpr HRESULT kRuntimeNotInitialized = static_cast(0x89240100u); +constexpr HRESULT kRuntimeInvalidHandle = static_cast(0x8924010cu); +constexpr HRESULT kIllegalMethodCall = static_cast(0x8000000eu); +constexpr HRESULT kInsufficientBuffer = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); + +// Work for an XAsyncBlock, run on the block's work port. execute() is skipped, and the block +// completes with E_GAMERUNTIME_NOT_INITIALIZED (0x89240100), if the runtime was uninitialized +// after the operation started; an execute() that is already running finishes. A finished +// object, including its result data, is kept until its Result call consumes it, the same +// block starts another operation, or the last uninitialize. A caller that frees a block +// without calling Result leaves that result in memory until then; the retention is not +// bounded. +class AsyncOp { +public: + virtual ~AsyncOp() = default; + // Identifies the family/function, so a Result call can reject a foreign block. + virtual uint32_t kind() const = 0; + // Runs without the runtime lock held. Not called if the operation was canceled. + virtual HRESULT execute() = 0; + // Value reported by XAsyncGetResultSize after execute() succeeded. + virtual size_t result_size() const = 0; +}; + +// Starts op on block (an XAsyncBlock*). Returns the submission status, as XUserAddAsync does. +HRESULT begin_async_op(void* block, std::unique_ptr op); + +// Checks that block holds a finished op of this kind, then calls consume while the runtime +// lock is held. The result is marked consumed only when consume succeeds, so a caller can +// retry with a larger buffer. consume must not call back into the runtime. +HRESULT consume_async_op(void* block, uint32_t kind, const std::function& consume); + +// Zero while the runtime is not initialized; otherwise changes on every first initialize, +// so handles created before an uninitialize can be recognized as stale. +uint32_t active_runtime_generation(); + +bool is_valid_user(void* user); + +// Full Windows path of the running executable. +HRESULT executable_path(wchar_t (&path)[MAX_PATH]); + +// The executable's C:\bx_pls\ directory (XPersistentLocalStorageGetPath), created if needed. +HRESULT title_storage_directory(wchar_t (&path)[MAX_PATH]); + +// Creates path if missing. Fails if it exists and is not a plain directory. +HRESULT ensure_directory(const wchar_t* path); + +// FNV-1a over UTF-16 code units, as used for the storage directory name. +uint64_t fnv1a(const wchar_t* text); + +constexpr GUID kIUnknownIid = {0x00000000, 0x0000, 0x0000, {0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}}; + +// COM IUnknown objects QueryApiImpl returns for the synthetic xgamesave and xpackage keys. +extern const void* const game_save_object; // game_save.cpp +extern const void* const package_object; // package.cpp + +// Close every XGameSave / XPackage handle. Called by the last uninitialize, with the runtime +// lock held (the runtime lock is always taken before these files' own locks). +void release_game_save_state(); // game_save.cpp +void release_package_state(); // package.cpp + +} // namespace bx::gdk diff --git a/shims/xgameruntime/synthetic_keys.h b/shims/xgameruntime/synthetic_keys.h new file mode 100644 index 00000000..74c66e00 --- /dev/null +++ b/shims/xgameruntime/synthetic_keys.h @@ -0,0 +1,90 @@ +#pragma once + +/* + * BetterXen synthetic QueryApiImpl keys: the single place to find or change them. + * + * These class and interface ids are defined by BetterXen. They are NOT Microsoft + * identifiers and were not derived from any Microsoft binary. A title linked against + * Microsoft's xgameruntime.lib will not request them. They let BetterXen's own callers + * and conformance fixtures reach the offline families through QueryApiImpl until a + * properly sourced mapping exists. To replace a family's keys, change its entry here and + * the expected values in the fixtures listed below. The fixtures keep their own copies on + * purpose, so a wrong key here fails a test instead of agreeing with itself: + * tests/conformance/test_xgameruntime/main.cpp (all families) + * tests/conformance/test_xgameruntime_saves/main.cpp (xgamesave, xpackage) + * + * Encoding: Data1 is the key below. Data2 = 0x5853 ("XS"), Data3 = 0x4000, + * Data4 = 80 00 00 00 00 00 00 01. For example, 0xB7581601 is + * {B7581601-5853-4000-8000-000000000001}. + */ + +#include + +#include + +namespace bx::gdk::synthetic { + +constexpr uint16_t kData2 = 0x5853; +constexpr uint16_t kData3 = 0x4000; +constexpr uint8_t kData4[8] = {0x80, 0, 0, 0, 0, 0, 0, 0x01}; + +constexpr GUID key(uint32_t data1) { + return {data1, kData2, kData3, {kData4[0], kData4[1], kData4[2], kData4[3], + kData4[4], kData4[5], kData4[6], kData4[7]}}; +} + +struct FamilyKey { + uint32_t clsid; + uint32_t iid; +}; + +// Plain function tables (#439). QueryApiImpl returns a pointer to a C struct of +// function pointers; the layouts are the *Dispatch structs in xgameruntime.cpp. +constexpr FamilyKey kTaskQueue{0xB7581001, 0xB7581002}; +constexpr FamilyKey kAsync{0xB7581101, 0xB7581102}; +constexpr FamilyKey kUser{0xB7581201, 0xB7581202}; +constexpr FamilyKey kStore{0xB7581301, 0xB7581302}; +constexpr FamilyKey kSystem{0xB7581401, 0xB7581402}; +constexpr FamilyKey kPersistentLocalStorage{0xB7581501, 0xB7581502}; + +// COM IUnknown objects (#468). QueryApiImpl returns an object whose first member is a +// vtable pointer. Slots 0-2 are IUnknown; the remaining slots follow the enums below. +// Every slot takes the object pointer first, then the parameters of the Microsoft Learn +// function it names, in the documented order. +constexpr FamilyKey kGameSave{0xB7581601, 0xB7581602}; +constexpr FamilyKey kPackage{0xB7581701, 0xB7581702}; + +enum class GameSaveSlot : uint32_t { + QueryInterface, + AddRef, + Release, + InitializeProviderAsync, // (XUserHandle, const char* scid, bool syncOnDemand, XAsyncBlock*) + InitializeProviderResult, // (XAsyncBlock*, XGameSaveProviderHandle*) + CloseProvider, // (XGameSaveProviderHandle) + CreateContainer, // (XGameSaveProviderHandle, const char* name, XGameSaveContainerHandle*) + CloseContainer, // (XGameSaveContainerHandle) + CreateUpdate, // (XGameSaveContainerHandle, const char* displayName, XGameSaveUpdateHandle*) + CloseUpdate, // (XGameSaveUpdateHandle) + SubmitBlobWrite, // (XGameSaveUpdateHandle, const char* blobName, const uint8_t*, size_t) + SubmitUpdateAsync, // (XGameSaveUpdateHandle, XAsyncBlock*) + SubmitUpdateResult, // (XAsyncBlock*) + ReadBlobDataAsync, // (XGameSaveContainerHandle, const char** names, uint32_t count, XAsyncBlock*) + ReadBlobDataResult, // (XAsyncBlock*, size_t, XGameSaveBlob*, uint32_t* count) + EnumerateContainerInfo, // (XGameSaveProviderHandle, void* context, XGameSaveContainerInfoCallback*) + Count, +}; + +enum class PackageSlot : uint32_t { + QueryInterface, + AddRef, + Release, + GetCurrentProcessPackageIdentifier, // (size_t bufferSize, char* buffer) + GetPackageKind, // (const char* packageIdentifier, XPackageKind*) + Mount, // (const char* packageIdentifier, XPackageMountHandle*) + GetMountPathSize, // (XPackageMountHandle, size_t*) + GetMountPath, // (XPackageMountHandle, size_t, char*) + CloseMountHandle, // (XPackageMountHandle) + Count, +}; + +} // namespace bx::gdk::synthetic diff --git a/shims/xgameruntime/xgameruntime.cpp b/shims/xgameruntime/xgameruntime.cpp index 887068a4..e5263365 100644 --- a/shims/xgameruntime/xgameruntime.cpp +++ b/shims/xgameruntime/xgameruntime.cpp @@ -1,4 +1,6 @@ #include "com_dispatch.h" +#include "runtime_internal.h" +#include "synthetic_keys.h" #include "task_queue.h" #include @@ -6,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -18,10 +21,10 @@ namespace { using namespace bx::gdk; // ABI values and layouts checked against Microsoft's public PC GDK 2510.5.6322. -constexpr HRESULT runtime_not_initialized = static_cast(0x89240100u); -constexpr HRESULT runtime_invalid_handle = static_cast(0x8924010cu); -constexpr HRESULT illegal_method_call = static_cast(0x8000000eu); -constexpr HRESULT insufficient_buffer = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); +constexpr HRESULT runtime_not_initialized = kRuntimeNotInitialized; +constexpr HRESULT runtime_invalid_handle = kRuntimeInvalidHandle; +constexpr HRESULT illegal_method_call = kIllegalMethodCall; +constexpr HRESULT insufficient_buffer = kInsufficientBuffer; struct AsyncBlock { void* queue; @@ -56,7 +59,8 @@ struct SpaceInfo { uint64_t total_bytes; }; -enum class Operation : uint32_t { add_user, game_license }; +// custom: an AsyncOp from another translation unit (XGameSave), see runtime_internal.h. +enum class Operation : uint32_t { add_user, game_license, custom }; struct AsyncState { const AsyncBlock* owner; @@ -79,6 +83,8 @@ uint64_t next_operation = 1; uintptr_t next_handle = 2; std::unordered_set users; std::unordered_set stores; +// Finished custom operations awaiting their Result call, keyed by AsyncState::sequence. +std::map> finished_ops; HRESULT create_handle(std::unordered_set& handles, void** out) { auto handle = reinterpret_cast(next_handle); @@ -159,10 +165,12 @@ class AsyncTask final : public Task { public: AsyncBlock* block; Operation operation; + std::unique_ptr op; std::unique_ptr completion; bool queued = false; - AsyncTask(AsyncBlock* block, Operation operation) : block(block), operation(operation) {} + AsyncTask(AsyncBlock* block, Operation operation, std::unique_ptr op) + : block(block), operation(operation), op(std::move(op)) {} ~AsyncTask() override { if (!queued) return; @@ -185,11 +193,34 @@ public: private: void finish(const QueueRef& queue, bool canceled) { const bool entitled = !canceled && operation == Operation::game_license && fixture_entitlement(); + bool cancel_requested; + bool stale; + { + std::lock_guard lock(state_mutex); + const auto state = read_state(block); + cancel_requested = state.cancel_requested; + stale = !runtime_refs || state.runtime_generation != runtime_generation; + } + // The block stays E_PENDING meanwhile, so the caller cannot reuse it. Once an op has + // run, a later XAsyncCancel or uninitialize cannot undo it, so its own status is + // reported. An op whose runtime was uninitialized before it ran is not run. + const bool executed = op && !canceled && !cancel_requested && !stale; + const HRESULT op_status = executed ? op->execute() : S_OK; { std::lock_guard lock(state_mutex); auto state = read_state(block); - state.status = (canceled || state.cancel_requested) ? E_ABORT : S_OK; + state.status = executed ? op_status + : canceled || state.cancel_requested ? E_ABORT + : op && stale ? runtime_not_initialized + : S_OK; state.entitled = entitled; + if (op && SUCCEEDED(state.status) && state.runtime_generation == runtime_generation && runtime_refs) { + try { + finished_ops[state.sequence] = std::move(op); + } catch (const std::bad_alloc&) { + state.status = E_OUTOFMEMORY; + } + } if (completion) completion->sequence = state.sequence; queued = false; write_state(block, state); @@ -198,12 +229,12 @@ private: } }; -HRESULT begin(AsyncBlock* block, Operation operation, void* store = nullptr) { +HRESULT begin(AsyncBlock* block, Operation operation, void* store = nullptr, std::unique_ptr op = nullptr) { if (!block) return E_POINTER; const auto queue = acquire_queue(block->queue); if (!queue) return block->queue ? E_HANDLE : E_OUTOFMEMORY; - auto work = std::unique_ptr(new (std::nothrow) AsyncTask(block, operation)); + auto work = std::unique_ptr(new (std::nothrow) AsyncTask(block, operation, std::move(op))); if (!work) return E_OUTOFMEMORY; if (block->callback) { work->completion.reset(new (std::nothrow) CompletionTask(block)); @@ -222,6 +253,8 @@ HRESULT begin(AsyncBlock* block, Operation operation, void* store = nullptr) { callback_running(previous.sequence, GetCurrentThreadId()))) { return illegal_method_call; } + // An unconsumed result of an earlier operation on this block is abandoned. + if (previous.owner == block) finished_ops.erase(previous.sequence); write_state(block, {block, next_operation++, E_PENDING, operation, runtime_generation, false, block->callback != nullptr, false, false}); work->queued = true; @@ -277,19 +310,6 @@ bool fixture_entitlement() { GetProcAddress(GetModuleHandleW(nullptr), "BetterXenSyntheticStoreFixture") != nullptr; } -HRESULT ensure_directory(const wchar_t* path) { - if (CreateDirectoryW(path, nullptr)) return S_OK; - const auto error = GetLastError(); - if (error != ERROR_ALREADY_EXISTS) return HRESULT_FROM_WIN32(error); - - const auto attributes = GetFileAttributesW(path); - if (attributes == INVALID_FILE_ATTRIBUTES) return HRESULT_FROM_WIN32(GetLastError()); - if ((attributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT)) != FILE_ATTRIBUTE_DIRECTORY) { - return HRESULT_FROM_WIN32(ERROR_DIRECTORY); - } - return S_OK; -} - HRESULT storage_path(wchar_t (&path)[MAX_PATH]) { wchar_t module[MAX_PATH]; const wchar_t* name = nullptr; @@ -302,11 +322,7 @@ HRESULT storage_path(wchar_t (&path)[MAX_PATH]) { normalized, MAX_PATH, nullptr, nullptr, 0)) { return HRESULT_FROM_WIN32(GetLastError()); } - uint64_t path_id = 14695981039346656037ULL; - for (auto* ch = normalized; *ch; ++ch) { - path_id ^= static_cast(*ch); - path_id *= 1099511628211ULL; - } + const uint64_t path_id = bx::gdk::fnv1a(normalized); const auto length = std::swprintf(path, MAX_PATH, L"%ls\\%016llx", storage_root, static_cast(path_id)); return length < 0 ? HRESULT_FROM_WIN32(ERROR_FILENAME_EXCED_RANGE) : S_OK; @@ -323,6 +339,9 @@ bool release_runtime_ref() { if (!--runtime_refs) { users.clear(); stores.clear(); + finished_ops.clear(); + bx::gdk::release_game_save_state(); + bx::gdk::release_package_state(); } return true; } @@ -369,13 +388,10 @@ struct ApiInitOptions { }; static_assert(offsetof(ApiInitOptions, game_config) == 8); -constexpr uint16_t family_data2 = 0x5853; -constexpr uint16_t family_data3 = 0x4000; - +// The synthetic key encoding is defined in synthetic_keys.h. bool synthetic_guid(const GUID* guid) { - return guid->Data2 == family_data2 && guid->Data3 == family_data3 && guid->Data4[0] == 0x80 && - guid->Data4[1] == 0 && guid->Data4[2] == 0 && guid->Data4[3] == 0 && guid->Data4[4] == 0 && - guid->Data4[5] == 0 && guid->Data4[6] == 0 && guid->Data4[7] == 1; + return guid->Data2 == synthetic::kData2 && guid->Data3 == synthetic::kData3 && + std::memcmp(guid->Data4, synthetic::kData4, sizeof(synthetic::kData4)) == 0; } void format_guid(char* dst, size_t cap, const GUID* guid) { @@ -459,6 +475,75 @@ HRESULT check_loader_versions(uint32_t gdk_ver, uint32_t gs_ver, const char* eve } // namespace +namespace bx::gdk { + +HRESULT ensure_directory(const wchar_t* path) { + if (CreateDirectoryW(path, nullptr)) return S_OK; + const auto error = GetLastError(); + if (error != ERROR_ALREADY_EXISTS) return HRESULT_FROM_WIN32(error); + + const auto attributes = GetFileAttributesW(path); + if (attributes == INVALID_FILE_ATTRIBUTES) return HRESULT_FROM_WIN32(GetLastError()); + if ((attributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT)) != FILE_ATTRIBUTE_DIRECTORY) { + return HRESULT_FROM_WIN32(ERROR_DIRECTORY); + } + return S_OK; +} + +uint64_t fnv1a(const wchar_t* text) { + uint64_t hash = 14695981039346656037ULL; + for (auto* ch = text; *ch; ++ch) { + hash ^= static_cast(*ch); + hash *= 1099511628211ULL; + } + return hash; +} + +HRESULT executable_path(wchar_t (&path)[MAX_PATH]) { + const wchar_t* name = nullptr; + return executable_name(path, name); +} + +HRESULT title_storage_directory(wchar_t (&path)[MAX_PATH]) { + const auto hr = storage_path(path); + return FAILED(hr) ? hr : create_storage(path); +} + +uint32_t active_runtime_generation() { + std::lock_guard lock(state_mutex); + return runtime_refs ? runtime_generation : 0; +} + +bool is_valid_user(void* user) { + std::lock_guard lock(state_mutex); + return runtime_refs && users.contains(user); +} + +HRESULT begin_async_op(void* block, std::unique_ptr op) { + if (!op) return E_OUTOFMEMORY; + return begin(static_cast(block), Operation::custom, nullptr, std::move(op)); +} + +HRESULT consume_async_op(void* block, uint32_t kind, const std::function& consume) { + auto* async = static_cast(block); + std::lock_guard lock(state_mutex); + AsyncState state{}; + const auto hr = check_result(async, Operation::custom, state); + if (FAILED(hr)) return hr; + const auto found = finished_ops.find(state.sequence); + if (found == finished_ops.end() || found->second->kind() != kind) return illegal_method_call; + + const auto result = consume(*found->second); + if (SUCCEEDED(result)) { + finished_ops.erase(found); + state.result_consumed = true; + write_state(async, state); + } + return result; +} + +} // namespace bx::gdk + extern "C" { HRESULT WINAPI XGameRuntimeInitialize() { @@ -513,7 +598,16 @@ HRESULT WINAPI XAsyncGetResultSize(AsyncBlock* block, size_t* size) { const auto state = read_state(block); if (state.owner != block || state.result_consumed) return illegal_method_call; if (SUCCEEDED(state.status)) { - *size = state.operation == Operation::add_user ? sizeof(void*) : sizeof(GameLicense); + switch (state.operation) { + case Operation::add_user: *size = sizeof(void*); break; + case Operation::game_license: *size = sizeof(GameLicense); break; + case Operation::custom: { + const auto found = finished_ops.find(state.sequence); + if (found == finished_ops.end()) return illegal_method_call; + *size = found->second->result_size(); + break; + } + } } return state.status; } @@ -802,17 +896,21 @@ struct Family { uint32_t iid; const char* name; const void* table; + bool com; // table is a COM object, so IID_IUnknown also reaches it }; -// Synthetic BetterXen dispatch keys, not Microsoft CLSIDs. -// Data2 = 0x5853, Data3 = 0x4000, Data4 = 80 00 00 00 00 00 00 01. +// Synthetic BetterXen dispatch keys, not Microsoft CLSIDs. All keys and the COM slot +// orders live in synthetic_keys.h. const Family families[] = { - {0xB7581001, 0xB7581002, "xtaskqueue", &task_queue_api}, - {0xB7581101, 0xB7581102, "xasync", &async_api}, - {0xB7581201, 0xB7581202, "xuser", &user_api}, - {0xB7581301, 0xB7581302, "xstore", &store_api}, - {0xB7581401, 0xB7581402, "xsystem", &system_api}, - {0xB7581501, 0xB7581502, "xpersistentlocalstorage", &storage_api}, + {synthetic::kTaskQueue.clsid, synthetic::kTaskQueue.iid, "xtaskqueue", &task_queue_api, false}, + {synthetic::kAsync.clsid, synthetic::kAsync.iid, "xasync", &async_api, false}, + {synthetic::kUser.clsid, synthetic::kUser.iid, "xuser", &user_api, false}, + {synthetic::kStore.clsid, synthetic::kStore.iid, "xstore", &store_api, false}, + {synthetic::kSystem.clsid, synthetic::kSystem.iid, "xsystem", &system_api, false}, + {synthetic::kPersistentLocalStorage.clsid, synthetic::kPersistentLocalStorage.iid, "xpersistentlocalstorage", + &storage_api, false}, + {synthetic::kGameSave.clsid, synthetic::kGameSave.iid, "xgamesave", bx::gdk::game_save_object, true}, + {synthetic::kPackage.clsid, synthetic::kPackage.iid, "xpackage", bx::gdk::package_object, true}, }; const Family* find_family(const GUID* clsid) { @@ -844,7 +942,8 @@ HRESULT WINAPI QueryApiImpl(const GUID* clsid, const GUID* iid, void** out) { } const auto* family = find_family(clsid); - if (family && synthetic_guid(iid) && iid->Data1 == family->iid) { + if (family && ((synthetic_guid(iid) && iid->Data1 == family->iid) || + (family->com && IsEqualGUID(*iid, bx::gdk::kIUnknownIid)))) { *out = const_cast(family->table); char detail[64]; std::snprintf(detail, sizeof(detail), "dispatch family=%s", family->name); diff --git a/tests/conformance/test_xgameruntime_saves/CMakeLists.txt b/tests/conformance/test_xgameruntime_saves/CMakeLists.txt new file mode 100644 index 00000000..40ff7cd4 --- /dev/null +++ b/tests/conformance/test_xgameruntime_saves/CMakeLists.txt @@ -0,0 +1,2 @@ +add_executable(test_xgameruntime_saves main.cpp) +target_link_libraries(test_xgameruntime_saves PRIVATE xgameruntime kernel32 shell32) diff --git a/tests/conformance/test_xgameruntime_saves/main.cpp b/tests/conformance/test_xgameruntime_saves/main.cpp new file mode 100644 index 00000000..bf0e7353 --- /dev/null +++ b/tests/conformance/test_xgameruntime_saves/main.cpp @@ -0,0 +1,880 @@ +// Offline XGameSave and XPackage through QueryApiImpl (#468). +// +// This fixture declares its own copies of the BetterXen synthetic keys and slot orders, of +// the public structures, and of the documented storage layout, instead of including the +// shim's headers, so a mistake there fails here. The keys must match +// shims/xgameruntime/synthetic_keys.h. Structure layouts and error values follow the Microsoft +// Learn XGameSave and XPackage reference pages; the file layout and naming follow the header +// comment of shims/xgameruntime/game_save.cpp. +// +// Run with no arguments. "--writer " is the child mode used by the +// cross-process check. +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +#define CHECK(expr) do { \ + if (!(expr)) { std::fprintf(stderr, "FAIL: test_xgameruntime_saves line %d: %s\n", __LINE__, #expr); std::exit(1); } \ +} while (false) + +struct Async { + void* queue; + void* context; + void (CALLBACK* callback)(Async*); + unsigned char reserved[32]; +}; + +struct ContainerInfo { // XGameSaveContainerInfo + const char* name; + const char* display_name; + uint32_t blob_count; + uint64_t total_size; + time_t last_modified_time; + bool needs_sync; +}; +static_assert(offsetof(ContainerInfo, total_size) == 24 && offsetof(ContainerInfo, needs_sync) == 40); + +struct Blob { // XGameSaveBlob { XGameSaveBlobInfo { name, size }, data } + const char* name; + uint32_t size; + uint8_t* data; +}; +static_assert(sizeof(Blob) == 24 && offsetof(Blob, data) == 16); + +extern "C" { +HRESULT WINAPI XGameRuntimeInitialize(); +void WINAPI XGameRuntimeUninitialize(); +HRESULT WINAPI XTaskQueueCreate(uint32_t, uint32_t, void**); +void WINAPI XTaskQueueCloseHandle(void*); +bool WINAPI XTaskQueueDispatch(void*, uint32_t, uint32_t); +HRESULT WINAPI XUserAddAsync(uint32_t, Async*); +HRESULT WINAPI XUserAddResult(Async*, void**); +void WINAPI XUserCloseHandle(void*); +HRESULT WINAPI XAsyncGetStatus(Async*, bool); +HRESULT WINAPI XAsyncGetResultSize(Async*, size_t*); +void WINAPI XAsyncCancel(Async*); +HRESULT WINAPI XPersistentLocalStorageGetPath(size_t, char*, size_t*); +HRESULT WINAPI QueryApiImpl(const GUID*, const GUID*, void**); +} + +// Expected values, from the public reference pages and the existing runtime. +constexpr HRESULT kInvalidContainerName = static_cast(0x80830001u); +constexpr HRESULT kUpdateTooBig = static_cast(0x80830005u); +constexpr HRESULT kBufferTooSmall = static_cast(0x80830007u); +constexpr HRESULT kBlobNotFound = static_cast(0x80830008u); +constexpr HRESULT kInvalidHandle = static_cast(0x8924010cu); +constexpr HRESULT kNotInitialized = static_cast(0x89240100u); +constexpr HRESULT kIllegalCall = static_cast(0x8000000eu); +constexpr HRESULT kInsufficient = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); +constexpr HRESULT kNotFound = HRESULT_FROM_WIN32(ERROR_NOT_FOUND); +constexpr HRESULT kCorrupt = HRESULT_FROM_WIN32(ERROR_FILE_CORRUPT); +constexpr uint32_t kManual = 0, kWork = 0; +constexpr size_t kMiB16 = 16u * 1024u * 1024u; +constexpr const char* kScid = "00000000-0000-0000-0000-000000000000"; + +GUID synthetic(uint32_t data1) { + return {data1, 0x5853, 0x4000, {0x80, 0, 0, 0, 0, 0, 0, 0x01}}; +} + +// Slot numbers from the synthetic_keys.h contract, written out independently. +enum : int { + kQueryInterface = 0, kAddRef = 1, kRelease = 2, + kInitAsync = 3, kInitResult = 4, kCloseProvider = 5, kCreateContainer = 6, kCloseContainer = 7, + kCreateUpdate = 8, kCloseUpdate = 9, kSubmitBlobWrite = 10, kSubmitUpdateAsync = 11, + kSubmitUpdateResult = 12, kReadAsync = 13, kReadResult = 14, kEnumerate = 15, +}; +enum : int { kGetId = 3, kGetKind = 4, kMount = 5, kGetMountPathSize = 6, kGetMountPath = 7, kCloseMount = 8 }; + +template +Fn slot(void* object, int index) { + void** vtbl = *static_cast(object); + Fn fn; + std::memcpy(&fn, &vtbl[index], sizeof(fn)); + return fn; +} + +using QiFn = HRESULT(WINAPI*)(void*, const GUID*, void**); +using RefFn = ULONG(WINAPI*)(void*); +using InitAsyncFn = HRESULT(WINAPI*)(void*, void*, const char*, bool, Async*); +using InitResultFn = HRESULT(WINAPI*)(void*, Async*, void**); +using CloseFn = void(WINAPI*)(void*, void*); +using CreateContainerFn = HRESULT(WINAPI*)(void*, void*, const char*, void**); +using CreateUpdateFn = HRESULT(WINAPI*)(void*, void*, const char*, void**); +using BlobWriteFn = HRESULT(WINAPI*)(void*, void*, const char*, const uint8_t*, size_t); +using SubmitAsyncFn = HRESULT(WINAPI*)(void*, void*, Async*); +using AsyncResultFn = HRESULT(WINAPI*)(void*, Async*); +using ReadAsyncFn = HRESULT(WINAPI*)(void*, void*, const char**, uint32_t, Async*); +using ReadResultFn = HRESULT(WINAPI*)(void*, Async*, size_t, Blob*, uint32_t*); +using InfoCallback = bool(CALLBACK*)(const ContainerInfo*, void*); +using EnumerateFn = HRESULT(WINAPI*)(void*, void*, void*, InfoCallback); +using GetIdFn = HRESULT(WINAPI*)(void*, size_t, char*); +using GetKindFn = HRESULT(WINAPI*)(void*, const char*, uint32_t*); +using MountFn = HRESULT(WINAPI*)(void*, const char*, void**); +using PathSizeFn = HRESULT(WINAPI*)(void*, void*, size_t*); +using PathFn = HRESULT(WINAPI*)(void*, void*, size_t, char*); + +using Blobs = std::vector>; + +void* query(uint32_t clsid, uint32_t iid) { + const GUID c = synthetic(clsid), i = synthetic(iid); + void* api = nullptr; + CHECK(QueryApiImpl(&c, &i, &api) == S_OK && api); + return api; +} + +void* add_user(void* queue) { + Async async{queue, nullptr, nullptr, {}}; + void* user = nullptr; + CHECK(XUserAddAsync(0, &async) == S_OK); + if (queue) CHECK(XTaskQueueDispatch(queue, kWork, 0)); + else CHECK(XAsyncGetStatus(&async, true) == S_OK); + CHECK(XUserAddResult(&async, &user) == S_OK && user); + return user; +} + +// queue null: the process task queue (thread pool); otherwise a manual queue run inline. +struct Saves { + void* api; + void* queue; + + void wait(Async& async) const { + if (queue) CHECK(XTaskQueueDispatch(queue, kWork, 0)); + else XAsyncGetStatus(&async, true); + } + + void* provider(void* user, const char* scid = kScid) const { + Async async{queue, nullptr, nullptr, {}}; + CHECK(slot(api, kInitAsync)(api, user, scid, false, &async) == S_OK); + if (queue) CHECK(XAsyncGetStatus(&async, false) == E_PENDING); + wait(async); + size_t size = 0; + CHECK(XAsyncGetResultSize(&async, &size) == S_OK && size == sizeof(void*)); + void* provider = nullptr; + CHECK(slot(api, kInitResult)(api, &async, &provider) == S_OK && provider); + void* again = nullptr; + CHECK(slot(api, kInitResult)(api, &async, &again) == kIllegalCall && !again); + return provider; + } + + void* container(void* provider, const char* name) const { + void* handle = nullptr; + CHECK(slot(api, kCreateContainer)(api, provider, name, &handle) == S_OK && handle); + return handle; + } + + void* update(void* container, const char* display_name) const { + void* handle = nullptr; + CHECK(slot(api, kCreateUpdate)(api, container, display_name, &handle) == S_OK && handle); + return handle; + } + + HRESULT write(void* update, const char* blob, const void* data, size_t size) const { + return slot(api, kSubmitBlobWrite)(api, update, blob, static_cast(data), size); + } + + HRESULT submit_status(void* update) const { + Async async{queue, nullptr, nullptr, {}}; + const auto hr = slot(api, kSubmitUpdateAsync)(api, update, &async); + if (FAILED(hr)) return hr; + wait(async); + const auto status = XAsyncGetStatus(&async, false); + CHECK(slot(api, kSubmitUpdateResult)(api, &async) == status); + return status; + } + + void submit(void* update) const { + const auto status = submit_status(update); + if (status != S_OK) std::fprintf(stderr, "submit status 0x%08lx\n", static_cast(status)); + CHECK(status == S_OK); + } + + // One update writing one blob, submitted and closed. + void put(void* container, const char* blob, const std::string& data) const { + void* staged = update(container, nullptr); + CHECK(write(staged, blob, data.data(), data.size()) == S_OK); + submit(staged); + close(kCloseUpdate, staged); + } + + void close(int which, void* handle) const { slot(api, which)(api, handle); } + + // Reads blobs (all when names is empty) and returns them as name -> bytes. + Blobs read(void* container, std::vector names) const { + Async async{queue, nullptr, nullptr, {}}; + CHECK(slot(api, kReadAsync)(api, container, names.empty() ? nullptr : names.data(), + static_cast(names.size()), &async) == S_OK); + wait(async); + size_t size = 0; + CHECK(XAsyncGetResultSize(&async, &size) == S_OK); + std::vector buffer(size + 16, 0xCD); + auto* blobs = reinterpret_cast(buffer.data()); + uint32_t count = 7; + const auto read_result = slot(api, kReadResult); + if (size) CHECK(read_result(api, &async, size - 1, blobs, &count) == kBufferTooSmall && count == 0); + CHECK(read_result(api, &async, size, size ? blobs : nullptr, &count) == S_OK); + uint32_t consumed = 7; + CHECK(read_result(api, &async, size, blobs, &consumed) == kIllegalCall && consumed == 0); + for (size_t i = size; i < buffer.size(); ++i) CHECK(buffer[i] == 0xCD); + + Blobs out; + size_t expected = count * sizeof(Blob); + const auto* base = reinterpret_cast(buffer.data()); + for (uint32_t i = 0; i < count; ++i) { + CHECK(reinterpret_cast(blobs[i].name) >= base && + reinterpret_cast(blobs[i].name) < base + size); + CHECK(blobs[i].size == 0 || (blobs[i].data >= base && blobs[i].data + blobs[i].size <= base + size)); + out.emplace_back(blobs[i].name, std::string(reinterpret_cast(blobs[i].data), blobs[i].size)); + expected += std::strlen(blobs[i].name) + 1 + blobs[i].size; + } + CHECK(expected == size); + return out; + } + + HRESULT read_status(void* container, std::vector names) const { + Async async{queue, nullptr, nullptr, {}}; + const auto hr = slot(api, kReadAsync)(api, container, names.empty() ? nullptr : names.data(), + static_cast(names.size()), &async); + if (FAILED(hr)) return hr; + wait(async); + uint32_t count = 0; + const auto status = XAsyncGetStatus(&async, false); + size_t size = 0; + if (SUCCEEDED(status)) CHECK(XAsyncGetResultSize(&async, &size) == S_OK); + std::vector buffer(size); + CHECK(slot(api, kReadResult)(api, &async, size, + size ? reinterpret_cast(buffer.data()) : nullptr, + &count) == status); + return status; + } +}; + +const std::string* find_blob(const Blobs& blobs, const char* name) { + for (const auto& [blob, bytes] : blobs) { + if (blob == name) return &bytes; + } + return nullptr; +} + +struct Seen { + std::string name, display_name; + uint32_t blob_count; + uint64_t total_size; + time_t modified; + bool needs_sync; +}; + +struct Listing { + std::vector seen; + size_t stop_after = SIZE_MAX; +}; + +bool CALLBACK collect(const ContainerInfo* info, void* context) { + auto& listing = *static_cast(context); + listing.seen.push_back({info->name, info->display_name, info->blob_count, info->total_size, + info->last_modified_time, info->needs_sync}); + return listing.seen.size() < listing.stop_after; +} + +Listing list(const Saves& saves, void* provider) { + Listing listing; + CHECK(slot(saves.api, kEnumerate)(saves.api, provider, &listing, collect) == S_OK); + return listing; +} + +// --- The documented storage layout, re-derived here --- + +// FNV-1a (64-bit) over each byte widened to a UTF-16 code unit, printed as 16 hex digits. +std::string hex_id(const std::string& text) { + uint64_t hash = 14695981039346656037ULL; + for (unsigned char c : text) { + hash ^= c; + hash *= 1099511628211ULL; + } + char out[17]; + std::snprintf(out, sizeof(out), "%016llx", static_cast(hash)); + return out; +} + +std::string saves_directory(const char* scid) { + char path[MAX_PATH * 4]{}; + CHECK(XPersistentLocalStorageGetPath(sizeof(path), path, nullptr) == S_OK); + return std::string(path) + "\\saves\\" + hex_id(scid); +} + +std::string container_path(const std::string& dir, const std::string& name) { + return dir + "\\" + hex_id(name) + ".bxgs"; +} + +void put32(std::string& out, uint32_t value) { + for (int i = 0; i < 4; ++i) out.push_back(static_cast(value >> (8 * i))); +} + +void put_str(std::string& out, const std::string& text) { + put32(out, static_cast(text.size())); + out += text; +} + +// "BXGS", version 1, name, display name, i64 time, blob count, then name / size / bytes. +std::string container_bytes(const std::string& name, const std::vector>& blobs) { + std::string out = "BXGS"; + put32(out, 1); + put_str(out, name); + put_str(out, "crafted"); + put32(out, 1700000000); + put32(out, 0); + put32(out, static_cast(blobs.size())); + for (const auto& [blob, data] : blobs) { + put_str(out, blob); + put_str(out, data); + } + return out; +} + +void write_file(const std::string& path, const std::string& bytes) { + const HANDLE file = CreateFileA(path.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, + nullptr); + CHECK(file != INVALID_HANDLE_VALUE); + DWORD wrote = 0; + CHECK(WriteFile(file, bytes.data(), static_cast(bytes.size()), &wrote, nullptr) && wrote == bytes.size()); + CHECK(CloseHandle(file)); +} + +// Files matching pattern in dir; optionally deletes them. +size_t files(const std::string& dir, const char* pattern, bool remove) { + WIN32_FIND_DATAA found; + const HANDLE search = FindFirstFileA((dir + "\\" + pattern).c_str(), &found); + if (search == INVALID_HANDLE_VALUE) return 0; + size_t count = 0; + do { + if (found.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) continue; + ++count; + if (remove) CHECK(DeleteFileA((dir + "\\" + found.cFileName).c_str())); + } while (FindNextFileA(search, &found)); + FindClose(search); + return count; +} + +void check_com(void* object, const GUID& own, const GUID& other) { + const GUID iunknown = {0x00000000, 0x0000, 0x0000, {0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}}; + void* out = nullptr; + CHECK(slot(object, kQueryInterface)(object, &iunknown, &out) == S_OK && out == object); + CHECK(slot(object, kQueryInterface)(object, &own, &out) == S_OK && out == object); + CHECK(slot(object, kQueryInterface)(object, &other, &out) == E_NOINTERFACE && !out); + CHECK(slot(object, kQueryInterface)(object, &own, nullptr) == E_POINTER); + CHECK(slot(object, kAddRef)(object) >= 1 && slot(object, kRelease)(object) >= 1); +} + +// Committed private memory, summed over the address space (Wine reports PrivateUsage as 0). +uint64_t private_bytes() { + uint64_t total = 0; + MEMORY_BASIC_INFORMATION region{}; + for (auto* at = static_cast(nullptr); + VirtualQuery(at, ®ion, sizeof(region)) == sizeof(region); + at = static_cast(region.BaseAddress) + region.RegionSize) { + if (region.State == MEM_COMMIT && region.Type == MEM_PRIVATE) total += region.RegionSize; + if (region.RegionSize == 0) break; + } + return total; +} + +std::string utf8(const wchar_t* text) { + const int bytes = WideCharToMultiByte(CP_UTF8, 0, text, -1, nullptr, 0, nullptr, nullptr); + CHECK(bytes > 0); + std::string out(static_cast(bytes), '\0'); + WideCharToMultiByte(CP_UTF8, 0, text, -1, out.data(), bytes, nullptr, nullptr); + out.pop_back(); + return out; +} + +// --- Concurrency --- + +constexpr char kShared[] = "shared/race"; + +struct ThreadJob { + void* api; + void* container; + int id; + int count; +}; + +DWORD WINAPI thread_writer(void* context) { + const auto& job = *static_cast(context); + const Saves saves{job.api, nullptr}; + for (int k = 0; k < job.count; ++k) { + char blob[32]; + std::snprintf(blob, sizeof(blob), "t%d_%d", job.id, k); + saves.put(job.container, blob, blob); + } + return 0; +} + +// Cross-process payload: the blob name, then padding to 64 KiB so each rewrite takes a while. +std::string payload(const char* blob) { + std::string data(blob); + data.resize(64 * 1024, '.'); + return data; +} + +// Child process: submits count blobs "w_" to kShared once the parent's event is set. +int writer_main(int id, int count, const wchar_t* event_name) { + CHECK(XGameRuntimeInitialize() == S_OK); + const Saves saves{query(0xB7581601, 0xB7581602), nullptr}; + void* user = add_user(nullptr); + void* provider = saves.provider(user); + void* container = saves.container(provider, kShared); + const HANDLE go = OpenEventW(SYNCHRONIZE, FALSE, event_name); + CHECK(go && WaitForSingleObject(go, 30000) == WAIT_OBJECT_0); + CloseHandle(go); + for (int k = 0; k < count; ++k) { + char blob[32]; + std::snprintf(blob, sizeof(blob), "w%d_%d", id, k); + saves.put(container, blob, payload(blob)); + } + XGameRuntimeUninitialize(); + return 0; +} + +void check_blobs(const Blobs& blobs, char prefix, int writers, int count) { + for (int id = 0; id < writers; ++id) { + for (int k = 0; k < count; ++k) { + char blob[32]; + std::snprintf(blob, sizeof(blob), "%c%d_%d", prefix, id, k); + const auto* data = find_blob(blobs, blob); + CHECK(data && *data == (prefix == 'w' ? payload(blob) : std::string(blob))); + } + } +} + +} // namespace + +int main() { + int argc = 0; + wchar_t** argv = CommandLineToArgvW(GetCommandLineW(), &argc); + if (argc == 5 && std::wcscmp(argv[1], L"--writer") == 0) { + return writer_main(std::wcstol(argv[2], nullptr, 10), std::wcstol(argv[3], nullptr, 10), argv[4]); + } + + const time_t started = std::time(nullptr); + CHECK(XGameRuntimeInitialize() == S_OK); + + // --- QueryApiImpl reaches both families as COM objects --- + const GUID save_clsid = synthetic(0xB7581601), save_iid = synthetic(0xB7581602); + const GUID package_clsid = synthetic(0xB7581701), package_iid = synthetic(0xB7581702); + const GUID iunknown = {0x00000000, 0x0000, 0x0000, {0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}}; + void* api = query(0xB7581601, 0xB7581602); + void* package = query(0xB7581701, 0xB7581702); + CHECK(package != api); + void* wrong = reinterpret_cast(static_cast(1)); + CHECK(QueryApiImpl(&save_clsid, &package_iid, &wrong) == E_NOINTERFACE && !wrong); + void* via_unknown = nullptr; + CHECK(QueryApiImpl(&save_clsid, &iunknown, &via_unknown) == S_OK && via_unknown == api); + CHECK(QueryApiImpl(&package_clsid, &iunknown, &via_unknown) == S_OK && via_unknown == package); + check_com(api, save_iid, package_iid); + check_com(package, package_iid, save_iid); + + void* queue = nullptr; + CHECK(XTaskQueueCreate(kManual, kManual, &queue) == S_OK && queue); + const Saves saves{api, queue}; + void* user = add_user(queue); + + const std::string dir = saves_directory(kScid); + const std::string other_dir = saves_directory("scid-b"); + files(dir, "*", true); + files(other_dir, "*", true); + + // --- Provider --- + Async async{queue, nullptr, nullptr, {}}; + const auto init_async = slot(api, kInitAsync); + CHECK(init_async(api, nullptr, kScid, false, &async) == kInvalidHandle); + CHECK(init_async(api, user, nullptr, false, &async) == E_INVALIDARG); + CHECK(init_async(api, user, kScid, false, nullptr) == E_POINTER); + void* provider = saves.provider(user); + + // --- Container names (XGameSaveCreateContainer rules) --- + const auto create_container = slot(api, kCreateContainer); + const std::string too_long(257, 'a'); + for (const char* bad : {"", "a..b", "trail.", "has space", "dir.x/file", "dir/", "semi;colon", too_long.c_str()}) { + void* handle = nullptr; + CHECK(create_container(api, provider, bad, &handle) == kInvalidContainerName && !handle); + } + void* handle = nullptr; + CHECK(create_container(api, provider, nullptr, &handle) == kInvalidContainerName); + CHECK(create_container(api, nullptr, "slot", &handle) == kInvalidHandle); + const std::string longest(256, 'a'); + for (const char* good : {"slot_1", "profiles/main", "/a", "a-b.c_d", longest.c_str()}) { + saves.close(kCloseContainer, saves.container(provider, good)); + } + + // --- A container that was never submitted --- + void* main_container = saves.container(provider, "profiles/main"); + CHECK(saves.read(main_container, {}).empty()); + CHECK(saves.read_status(main_container, {"progress"}) == kBlobNotFound); + CHECK(saves.read_status(main_container, {"progress", "progress"}) == E_INVALIDARG); + { + Async read{queue, nullptr, nullptr, {}}; + CHECK(slot(api, kReadAsync)(api, main_container, nullptr, 1, &read) == E_INVALIDARG); + } + CHECK(files(dir, "*.bxgs", false) == 0); + + // --- Write, then read back --- + std::string progress(300, '\0'); + for (size_t i = 0; i < progress.size(); ++i) progress[i] = static_cast(i * 7 + 3); + const std::string settings = "volume=7"; + void* update = saves.update(main_container, "Main profile"); + CHECK(saves.write(update, "progress", progress.data(), progress.size()) == S_OK); + CHECK(saves.write(update, "progress", progress.data(), progress.size()) == E_INVALIDARG); + CHECK(saves.write(update, "", "x", 1) == E_INVALIDARG); + CHECK(saves.write(update, std::string(257, 'n').c_str(), "x", 1) == E_INVALIDARG); // 256-byte name limit + CHECK(saves.write(update, "settings", settings.data(), settings.size()) == S_OK); + { + Async submit{queue, nullptr, nullptr, {}}; + CHECK(slot(api, kSubmitUpdateAsync)(api, update, &submit) == S_OK); + Async twice{queue, nullptr, nullptr, {}}; + CHECK(slot(api, kSubmitUpdateAsync)(api, update, &twice) == kIllegalCall); // pending + CHECK(saves.write(update, "late", "x", 1) == kIllegalCall); + saves.wait(submit); + size_t size = 1; + CHECK(XAsyncGetResultSize(&submit, &size) == S_OK && size == 0); + CHECK(slot(api, kSubmitUpdateResult)(api, &submit) == S_OK); + } + saves.close(kCloseUpdate, update); + CHECK(saves.write(update, "closed", "x", 1) == kInvalidHandle); // CloseUpdate closes it + + auto blobs = saves.read(main_container, {}); + CHECK(blobs.size() == 2); + CHECK(find_blob(blobs, "progress") && *find_blob(blobs, "progress") == progress); + CHECK(find_blob(blobs, "settings") && *find_blob(blobs, "settings") == settings); + blobs = saves.read(main_container, {"settings"}); + CHECK(blobs.size() == 1 && blobs[0].first == "settings" && blobs[0].second == settings); + + // The 16 MiB limit counts blob names: "big" (3 bytes) plus 16 MiB - 3 bytes fills it exactly. + { + std::vector big(kMiB16); + void* full = saves.update(main_container, nullptr); + CHECK(saves.write(full, "big", big.data(), kMiB16 - 3 + 1) == kUpdateTooBig); + CHECK(saves.write(full, "big", big.data(), kMiB16 - 3) == S_OK); + CHECK(saves.write(full, "x", nullptr, 0) == kUpdateTooBig); + saves.close(kCloseUpdate, full); + } + + // --- A second container, then enumeration --- + void* slot_container = saves.container(provider, "slot_1"); + saves.put(slot_container, "a", "A"); + saves.close(kCloseContainer, slot_container); + CHECK(files(dir, "*.bxgs", false) == 2); + + const auto enumerate = slot(api, kEnumerate); + Listing listing = list(saves, provider); + CHECK(listing.seen.size() == 2); + const time_t now = std::time(nullptr); + for (const auto& seen : listing.seen) { + CHECK(!seen.needs_sync && seen.modified >= started - 5 && seen.modified <= now + 5); + if (seen.name == "profiles/main") { + CHECK(seen.display_name == "Main profile" && seen.blob_count == 2 && + seen.total_size == progress.size() + settings.size()); + } else { + CHECK(seen.name == "slot_1" && seen.display_name.empty() && seen.blob_count == 1 && seen.total_size == 1); + } + } + CHECK(listing.seen[0].name != listing.seen[1].name); + Listing first_only; + first_only.stop_after = 1; + CHECK(enumerate(api, provider, &first_only, collect) == S_OK && first_only.seen.size() == 1); + CHECK(enumerate(api, provider, nullptr, nullptr) == E_INVALIDARG); + + // --- Saves are separated by SCID --- + { + void* other = saves.provider(user, "scid-b"); + CHECK(list(saves, other).seen.empty()); + void* same_name = saves.container(other, "profiles/main"); + CHECK(saves.read(same_name, {}).empty()); + saves.put(same_name, "progress", "other scid"); + CHECK(files(other_dir, "*.bxgs", false) == 1); + void* staged = saves.update(same_name, nullptr); + { + std::vector big(kMiB16 - 16); + CHECK(saves.write(staged, "staged", big.data(), big.size()) == S_OK); + } + const uint64_t open_bytes = private_bytes(); + saves.close(kCloseProvider, other); + // Closing a provider closes its containers and their updates, and frees what they staged. + CHECK(private_bytes() + 8 * (1u << 20) < open_bytes); + CHECK(saves.read_status(same_name, {}) == kInvalidHandle); + CHECK(saves.write(staged, "x", "x", 1) == kInvalidHandle); + CHECK(*find_blob(saves.read(main_container, {"progress"}), "progress") == progress); + } + + // --- Files that are damaged, foreign or unreadable --- + { + const auto crafted = [&](const char* name, std::string bytes) { + write_file(container_path(dir, name), bytes); + void* container = saves.container(provider, name); + const auto status = saves.read_status(container, {}); + saves.close(kCloseContainer, container); + return status; + }; + CHECK(crafted("craft_ok", container_bytes("craft_ok", {{"a", "1"}})) == S_OK); // the format is as documented + CHECK(crafted("craft_tail", container_bytes("craft_tail", {{"a", "1"}}) + "!") == kCorrupt); + CHECK(crafted("craft_dup", container_bytes("craft_dup", {{"a", "1"}, {"a", "2"}})) == kCorrupt); + std::string truncated = container_bytes("craft_cut", {{"a", "12345"}}); + truncated.pop_back(); + CHECK(crafted("craft_cut", truncated) == kCorrupt); + CHECK(crafted("craft_nul", container_bytes(std::string("craft_nul\0x", 11), {})) == kCorrupt); + CHECK(crafted("craft_blobnul", container_bytes("craft_blobnul", {{std::string("a\0b", 3), "1"}})) == kCorrupt); + CHECK(crafted("craft_badname", container_bytes("bad name", {})) == kCorrupt); + // Enumeration lists the two real containers and the valid crafted one, skipping the rest. + CHECK(list(saves, provider).seen.size() == 3); + + // A file another process holds exclusively is skipped, not fatal to enumeration. + const HANDLE locked = CreateFileA(container_path(dir, "craft_ok").c_str(), GENERIC_READ, 0, nullptr, + OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + CHECK(locked != INVALID_HANDLE_VALUE); + CHECK(list(saves, provider).seen.size() == 2); + CloseHandle(locked); + CHECK(files(dir, "*.bxgs", false) == 9); + for (const char* name : {"craft_ok", "craft_tail", "craft_dup", "craft_cut", "craft_nul", "craft_blobnul", + "craft_badname"}) { + CHECK(DeleteFileA(container_path(dir, name).c_str())); + } + } + + // --- A failed replace keeps the old save; a successful one replaces the file --- + { + const auto file_id = [&] { + const HANDLE file = CreateFileA(container_path(dir, "profiles/main").c_str(), 0, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, + OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + CHECK(file != INVALID_HANDLE_VALUE); + BY_HANDLE_FILE_INFORMATION info{}; + CHECK(GetFileInformationByHandle(file, &info)); + CloseHandle(file); + return (static_cast(info.nFileIndexHigh) << 32) | info.nFileIndexLow; + }; + const uint64_t original = file_id(); + // A reader that allows writes but not deletion blocks the rename, not an in-place write. + const HANDLE reader = CreateFileA(container_path(dir, "profiles/main").c_str(), GENERIC_READ, + FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, nullptr); + CHECK(reader != INVALID_HANDLE_VALUE); + void* blocked = saves.update(main_container, nullptr); + CHECK(saves.write(blocked, "progress", "BLOCKED", 7) == S_OK); + CHECK(FAILED(saves.submit_status(blocked))); + CloseHandle(reader); + CHECK(*find_blob(saves.read(main_container, {"progress"}), "progress") == progress); + CHECK(files(dir, "*.tmp", false) == 0); + // The failed update was not consumed: submitting it again now succeeds. + CHECK(file_id() == original); + saves.submit(blocked); + saves.close(kCloseUpdate, blocked); + CHECK(*find_blob(saves.read(main_container, {"progress"}), "progress") == "BLOCKED"); + CHECK(file_id() != original); // written to a new file and renamed over, not in place + } + + // --- Persistence across provider close and reopen --- + saves.close(kCloseContainer, main_container); + saves.close(kCloseProvider, provider); + CHECK(create_container(api, provider, "slot_1", &handle) == kInvalidHandle && !handle); + provider = saves.provider(user); + main_container = saves.container(provider, "profiles/main"); + blobs = saves.read(main_container, {"settings", "progress"}); + CHECK(blobs.size() == 2 && *find_blob(blobs, "progress") == "BLOCKED" && *find_blob(blobs, "settings") == settings); + + // Overwrite one blob through the process task queue; the other blob and the display name stay. + const std::string progress2 = "lvl=9"; + { + const Saves pooled{api, nullptr}; + pooled.put(main_container, "progress", progress2); + } + blobs = saves.read(main_container, {}); + CHECK(blobs.size() == 2 && *find_blob(blobs, "progress") == progress2 && *find_blob(blobs, "settings") == settings); + for (const auto& seen : list(saves, provider).seen) { + if (seen.name == "profiles/main") CHECK(seen.display_name == "Main profile"); + } + + // A canceled submit writes nothing, and the update can then be submitted again. + update = saves.update(main_container, nullptr); + CHECK(saves.write(update, "progress", "X", 1) == S_OK); + { + Async canceled{queue, nullptr, nullptr, {}}; + CHECK(slot(api, kSubmitUpdateAsync)(api, update, &canceled) == S_OK); + XAsyncCancel(&canceled); + saves.wait(canceled); + CHECK(XAsyncGetStatus(&canceled, false) == E_ABORT); + CHECK(slot(api, kSubmitUpdateResult)(api, &canceled) == E_ABORT); + } + CHECK(*find_blob(saves.read(main_container, {"progress"}), "progress") == progress2); + saves.submit(update); + saves.close(kCloseUpdate, update); + CHECK(*find_blob(saves.read(main_container, {"progress"}), "progress") == "X"); + + // A closed container handle is rejected, and so are its updates. + void* orphan = saves.update(main_container, nullptr); + saves.close(kCloseContainer, main_container); + CHECK(saves.read_status(main_container, {}) == kInvalidHandle); + CHECK(saves.write(orphan, "x", "x", 1) == kInvalidHandle); + update = nullptr; + CHECK(slot(api, kCreateUpdate)(api, main_container, "x", &update) == kInvalidHandle && !update); + + // --- Concurrent submits to one container: threads, then processes --- + void* shared = saves.container(provider, kShared); + { + constexpr int kThreads = 8, kEach = 8; + ThreadJob jobs[kThreads]; + HANDLE threads[kThreads]; + for (int i = 0; i < kThreads; ++i) { + jobs[i] = {api, shared, i, kEach}; + threads[i] = CreateThread(nullptr, 0, thread_writer, &jobs[i], 0, nullptr); + CHECK(threads[i]); + } + CHECK(WaitForMultipleObjects(kThreads, threads, TRUE, 60000) == WAIT_OBJECT_0); + for (HANDLE thread : threads) CloseHandle(thread); + blobs = saves.read(shared, {}); + CHECK(blobs.size() == kThreads * kEach); + check_blobs(blobs, 't', kThreads, kEach); + } + { + constexpr int kWriters = 4, kEach = 40; + wchar_t event_name[64]; + std::swprintf(event_name, 64, L"Local\\bx_saves_go_%lu", GetCurrentProcessId()); + const HANDLE go = CreateEventW(nullptr, TRUE, FALSE, event_name); + CHECK(go); + wchar_t exe[MAX_PATH]; + CHECK(GetModuleFileNameW(nullptr, exe, MAX_PATH) > 0); + PROCESS_INFORMATION children[kWriters]; + for (int id = 0; id < kWriters; ++id) { + wchar_t command[MAX_PATH + 128]; + std::swprintf(command, MAX_PATH + 128, L"\"%ls\" --writer %d %d %ls", exe, id, kEach, event_name); + STARTUPINFOW startup{}; + startup.cb = sizeof(startup); + CHECK(CreateProcessW(exe, command, nullptr, nullptr, FALSE, 0, nullptr, nullptr, &startup, &children[id])); + } + CHECK(SetEvent(go)); + for (auto& child : children) { + DWORD code = 99; + CHECK(WaitForSingleObject(child.hProcess, 120000) == WAIT_OBJECT_0); + CHECK(GetExitCodeProcess(child.hProcess, &code) && code == 0); + CloseHandle(child.hProcess); + CloseHandle(child.hThread); + } + CloseHandle(go); + blobs = saves.read(shared, {}); + CHECK(blobs.size() == 8 * 8 + kWriters * kEach); + check_blobs(blobs, 'w', kWriters, kEach); + } + saves.close(kCloseContainer, shared); + + // --- XPackage --- + char id[64]{}; + CHECK(slot(package, kGetId)(package, sizeof(id), id) == S_OK); + CHECK(std::strncmp(id, "BXPKG", 5) == 0 && std::strlen(id) == 21); + for (const char* c = id + 5; *c; ++c) CHECK((*c >= '0' && *c <= '9') || (*c >= 'a' && *c <= 'f')); + char again[64]{}; + CHECK(slot(package, kGetId)(package, sizeof(again), again) == S_OK && std::strcmp(id, again) == 0); + CHECK(slot(package, kGetId)(package, std::strlen(id), again) == kInsufficient); + CHECK(slot(package, kGetId)(package, sizeof(again), nullptr) == E_POINTER); + + uint32_t kind = 99; + CHECK(slot(package, kGetKind)(package, id, &kind) == S_OK && kind == 0); // XPackageKind::Game + CHECK(slot(package, kGetKind)(package, "BXPKG0000000000000000", &kind) == kNotFound); + + // The mount path is the executable's directory in UTF-8 (W API, so non-ASCII paths work). + wchar_t exe_w[MAX_PATH]{}; + CHECK(GetModuleFileNameW(nullptr, exe_w, MAX_PATH) > 0); + *std::wcsrchr(exe_w, L'\\') = L'\0'; + const std::string exe_dir = utf8(exe_w); + void* mount = nullptr; + CHECK(slot(package, kMount)(package, "BXPKG0000000000000000", &mount) == kNotFound && !mount); + CHECK(slot(package, kMount)(package, id, &mount) == S_OK && mount); + size_t path_size = 0; + CHECK(slot(package, kGetMountPathSize)(package, mount, &path_size) == S_OK); + CHECK(path_size == exe_dir.size() + 1); + std::vector path(path_size); + CHECK(slot(package, kGetMountPath)(package, mount, path_size - 1, path.data()) == kInsufficient); + CHECK(slot(package, kGetMountPath)(package, mount, path_size, path.data()) == S_OK); + CHECK(exe_dir == path.data()); + // Handle types do not overlap: a mount handle is not a provider handle. + saves.close(kCloseProvider, mount); + CHECK(list(saves, provider).seen.size() == 3); + CHECK(slot(package, kGetMountPathSize)(package, mount, &path_size) == S_OK); + slot(package, kCloseMount)(package, mount); + CHECK(slot(package, kGetMountPathSize)(package, mount, &path_size) == kInvalidHandle); + + // --- Uninitialize then reinitialize: old handles stay dead, queued work does not run --- + { + void* old_container = saves.container(provider, "profiles/main"); + void* old_update = saves.update(old_container, nullptr); + CHECK(saves.write(old_update, "progress", "STALE", 5) == S_OK); + void* old_mount = nullptr; + CHECK(slot(package, kMount)(package, id, &old_mount) == S_OK); + + // Results and staged data held across the uninitialize must be released by it. + std::vector big(kMiB16 - 8); + void* heavy = saves.update(old_container, nullptr); + CHECK(saves.write(heavy, "heavy", big.data(), big.size()) == S_OK); + std::vector unread(6, Async{queue, nullptr, nullptr, {}}); + void* big_container = saves.container(provider, "big"); + { + void* filler = saves.update(big_container, nullptr); + CHECK(saves.write(filler, "data", big.data(), big.size()) == S_OK); + saves.submit(filler); + saves.close(kCloseUpdate, filler); + } + big = {}; + const uint64_t before = private_bytes(); + for (auto& read : unread) { + CHECK(slot(api, kReadAsync)(api, big_container, nullptr, 0, &read) == S_OK); + CHECK(XTaskQueueDispatch(queue, kWork, 0)); + } + const uint64_t held = private_bytes(); + // Queued last on the manual queue, so the dispatches above do not run it. + Async pending{queue, nullptr, nullptr, {}}; + CHECK(slot(api, kSubmitUpdateAsync)(api, old_update, &pending) == S_OK); + + XGameRuntimeUninitialize(); + CHECK(XGameRuntimeInitialize() == S_OK); + const uint64_t after = private_bytes(); + std::printf("memory: before reads %llu MiB, with 6 unread results %llu MiB, after uninitialize %llu MiB\n", + static_cast(before >> 20), static_cast(held >> 20), + static_cast(after >> 20)); + // The measurement sees the six results (about 16 MiB each)... + CHECK(held > before + 80 * (1u << 20)); + // ...and uninitialize released them and the open 16 MiB update counted in "before". + CHECK(after + 8 * (1u << 20) < before); + + // The submit queued before uninitialize must not write now. + CHECK(XTaskQueueDispatch(queue, kWork, 0)); + CHECK(XAsyncGetStatus(&pending, false) == kNotInitialized); + CHECK(slot(api, kSubmitUpdateResult)(api, &pending) == kNotInitialized); + CHECK(slot(api, kCreateContainer)(api, provider, "slot_1", &handle) == kInvalidHandle); + CHECK(saves.read_status(old_container, {}) == kInvalidHandle); + CHECK(saves.write(old_update, "x", "x", 1) == kInvalidHandle); + CHECK(slot(package, kGetMountPathSize)(package, old_mount, &path_size) == kInvalidHandle); + + void* fresh_user = add_user(queue); + void* fresh = saves.provider(fresh_user); + void* check = saves.container(fresh, "profiles/main"); + CHECK(*find_blob(saves.read(check, {"progress"}), "progress") == "X"); + XUserCloseHandle(fresh_user); + } + + // --- After the last uninitialize, handles are stale --- + XUserCloseHandle(user); + XTaskQueueCloseHandle(queue); + XGameRuntimeUninitialize(); + CHECK(create_container(api, provider, "slot_1", &handle) == kNotInitialized); + CHECK(slot(package, kGetId)(package, sizeof(id), id) == kNotInitialized); + + std::printf("PASS: test_xgameruntime_saves (round trip, SCID isolation, damaged files, failed replace, " + "64 threaded + 160 cross-process submits, uninitialize; package %s)\n", id); + return 0; +}