diff options
| author | ubiquitarianism <283527159+ubiquitarianism@users.noreply.github.com> | 2026-11-23 22:36:12 -0500 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2026-11-23 22:36:12 -0500 |
| commit | fabe844cd88e6fd6469ffd3d869bbe062ebefe1f (patch) | |
| tree | ffd126d5d76910e65b140c235dfdcf629f292cc5 /runtime | |
| parent | f9e7e3e1bfa718eb4d8ca84fd1dbe617038d48d7 (diff) | |
| parent | 2d7be48dec529446e0ead3393e2b3acabb29ff64 (diff) | |
Merge pull request #131 from Mumogg/restore-directstorage
runtime: restore the console DirectStorage shim, with the typed-error inflate it needs (RT-DSTORAGE-RESTORE, #47)
Diffstat (limited to 'runtime')
| -rw-r--r-- | runtime/CMakeLists.txt | 21 | ||||
| -rw-r--r-- | runtime/shims/dstorage.cpp | 1125 | ||||
| -rw-r--r-- | runtime/shims/dstorage_xs_abi.h | 387 | ||||
| -rw-r--r-- | runtime/shims/registry.cpp | 7 | ||||
| -rw-r--r-- | runtime/src/shader_library.h | 74 | ||||
| -rw-r--r-- | runtime/test/dstorage_test.cpp | 1260 |
6 files changed, 2844 insertions, 30 deletions
diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 8fce889eb..52ae6c423 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt | |||
| @@ -129,7 +129,12 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) | |||
| 129 | shims/com_shim.cpp | 129 | shims/com_shim.cpp |
| 130 | shims/bcrypt_rng.cpp | 130 | shims/bcrypt_rng.cpp |
| 131 | shims/xapu_chad.cpp | 131 | shims/xapu_chad.cpp |
| 132 | shims/dstorage.cpp | ||
| 132 | ) | 133 | ) |
| 134 | # dstorage.cpp's guarded_move turns an access violation in a title's buffer into E_DSTORAGE_ACCESS_VIOLATION with | ||
| 135 | # __try. MSVC always catches it; clang-cl only with asynchronous exceptions (as for tiny_dll below). A source file | ||
| 136 | # property, so gta6rt and dstorage_test both get it. | ||
| 137 | set_source_files_properties(shims/dstorage.cpp PROPERTIES COMPILE_OPTIONS "$<$<CXX_COMPILER_ID:Clang>:/EHa>") | ||
| 133 | add_dependencies(gta6rt gta6rt_tls_host) | 138 | add_dependencies(gta6rt gta6rt_tls_host) |
| 134 | target_compile_definitions(gta6rt PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE) | 139 | target_compile_definitions(gta6rt PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE) |
| 135 | target_compile_options(gta6rt PRIVATE /W4 /permissive- /utf-8) | 140 | target_compile_options(gta6rt PRIVATE /W4 /permissive- /utf-8) |
| @@ -253,6 +258,19 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) | |||
| 253 | target_compile_definitions(cpu_emulation_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) | 258 | target_compile_definitions(cpu_emulation_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) |
| 254 | target_compile_options(cpu_emulation_test PRIVATE /W4 /permissive- /utf-8) | 259 | target_compile_options(cpu_emulation_test PRIVATE /W4 /permissive- /utf-8) |
| 255 | 260 | ||
| 261 | # Xbox DirectStorage (DStorageGetFactory under dstorage_xs.dll, xcrdapi.dll and dstorage.dll) over synthetic files: | ||
| 262 | # GAME: paths through the file shims, queues, status arrays, fences and errors. No GPU, no game data. | ||
| 263 | add_executable(dstorage_test | ||
| 264 | test/dstorage_test.cpp | ||
| 265 | shims/dstorage.cpp | ||
| 266 | shims/file_system.cpp | ||
| 267 | shims/registry.cpp | ||
| 268 | ) | ||
| 269 | target_include_directories(dstorage_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) | ||
| 270 | target_compile_definitions(dstorage_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) | ||
| 271 | target_compile_options(dstorage_test PRIVATE /W4 /permissive- /utf-8) | ||
| 272 | target_link_options(dstorage_test PRIVATE /OPT:NOREF) | ||
| 273 | |||
| 256 | # xapu.dll and chad.dll, the APU and audio DSP command queues, resolved through the registry like xmem_test. | 274 | # xapu.dll and chad.dll, the APU and audio DSP command queues, resolved through the registry like xmem_test. |
| 257 | add_executable(xapu_chad_test | 275 | add_executable(xapu_chad_test |
| 258 | test/xapu_chad_test.cpp | 276 | test/xapu_chad_test.cpp |
| @@ -1215,6 +1233,9 @@ if(BUILD_TESTING) | |||
| 1215 | set_tests_properties(wait_registration_${_case} PROPERTIES TIMEOUT 15) | 1233 | set_tests_properties(wait_registration_${_case} PROPERTIES TIMEOUT 15) |
| 1216 | endforeach() | 1234 | endforeach() |
| 1217 | endif() | 1235 | endif() |
| 1236 | if(WIN32 AND TARGET dstorage_test) | ||
| 1237 | add_test(NAME dstorage COMMAND dstorage_test) | ||
| 1238 | endif() | ||
| 1218 | if(WIN32 AND TARGET xgameruntime_test) | 1239 | if(WIN32 AND TARGET xgameruntime_test) |
| 1219 | add_test(NAME xgameruntime COMMAND xgameruntime_test) | 1240 | add_test(NAME xgameruntime COMMAND xgameruntime_test) |
| 1220 | add_test(NAME xgameruntime_user COMMAND xgameruntime_user_test) | 1241 | add_test(NAME xgameruntime_user COMMAND xgameruntime_user_test) |
diff --git a/runtime/shims/dstorage.cpp b/runtime/shims/dstorage.cpp new file mode 100644 index 000000000..81abaea3d --- /dev/null +++ b/runtime/shims/dstorage.cpp | |||
| @@ -0,0 +1,1125 @@ | |||
| 1 | // Xbox DirectStorage for a mapped title: DStorageGetFactory and the IDStorageFactoryX2 / IDStorageQueueX2 / | ||
| 2 | // IDStorageFileX / IDStorageStatusArrayX objects of the console API (dstorage_xs_abi.h). | ||
| 3 | // | ||
| 4 | // Served as dstorage_xs.dll, xcrdapi.dll and dstorage.dll!DStorageGetFactory; docs/directstorage.md has the evidence | ||
| 5 | // for those names, the console ABI and what each method does here. In short: | ||
| 6 | // - OpenFile resolves kernel32.dll!CreateFileW through the shim registry, so a GAME: path goes through the | ||
| 7 | // runtime's console path mapping and write overlay (file_system.cpp) exactly as the title's own CreateFileW. | ||
| 8 | // - Each queue has one worker thread that runs its submitted entries in order: a request reads a file range or | ||
| 9 | // copies a memory range into the destination, a status entry, fence signal or event runs when every entry before | ||
| 10 | // it has. Completion is therefore in queue order, as the API guarantees. | ||
| 11 | // - A zlib request (ZlibDecompress alone) reads its source into a staging buffer, inflates it on the worker with | ||
| 12 | // the runtime's RFC 1950 inflater (leonida::zlib_inflate, src/shader_library.h) and copies the result to the | ||
| 13 | // destination only when it is exactly DestinationSize bytes; a stream that fails leaves the destination as it was. | ||
| 14 | // - BCPack, swizzle and physical-page requests fail with E_NOTIMPL for now (later PRs: they become stages between | ||
| 15 | // the read and the destination write, BCPack after the inflate). | ||
| 16 | // Nothing here goes online or touches the GPU. | ||
| 17 | #include <windows.h> | ||
| 18 | #include <d3d12.h> | ||
| 19 | |||
| 20 | #include <algorithm> | ||
| 21 | #include <atomic> | ||
| 22 | #include <condition_variable> | ||
| 23 | #include <cstdio> | ||
| 24 | #include <cstring> | ||
| 25 | #include <deque> | ||
| 26 | #include <memory> | ||
| 27 | #include <mutex> | ||
| 28 | #include <new> | ||
| 29 | #include <set> | ||
| 30 | #include <string> | ||
| 31 | #include <thread> | ||
| 32 | #include <unordered_set> | ||
| 33 | #include <vector> | ||
| 34 | |||
| 35 | #include "../src/shader_library.h" // leonida::zlib_inflate | ||
| 36 | #include "dstorage_xs_abi.h" | ||
| 37 | #include "shims.h" | ||
| 38 | |||
| 39 | using namespace dsx; | ||
| 40 | |||
| 41 | namespace { | ||
| 42 | |||
| 43 | // ---- Logging ------------------------------------------------------------------------------------------------------ | ||
| 44 | |||
| 45 | // Process-lifetime state is allocated once and never freed: a worker thread may still run while statics are destroyed | ||
| 46 | // at exit. | ||
| 47 | std::mutex& log_mutex() { | ||
| 48 | static auto* m = new std::mutex; | ||
| 49 | return *m; | ||
| 50 | } | ||
| 51 | |||
| 52 | void log_once(const std::string& key, const std::string& line) { | ||
| 53 | static auto* seen = new std::set<std::string>; | ||
| 54 | std::lock_guard lock(log_mutex()); | ||
| 55 | if (!seen->insert(key).second) return; | ||
| 56 | std::fprintf(stderr, "[rt] dstorage: %s\n", line.c_str()); | ||
| 57 | } | ||
| 58 | |||
| 59 | std::string guid_text(const GUID& g) { | ||
| 60 | char b[48]; | ||
| 61 | std::snprintf(b, sizeof b, "{%08lx-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}", g.Data1, g.Data2, g.Data3, | ||
| 62 | g.Data4[0], g.Data4[1], g.Data4[2], g.Data4[3], g.Data4[4], g.Data4[5], g.Data4[6], g.Data4[7]); | ||
| 63 | return b; | ||
| 64 | } | ||
| 65 | |||
| 66 | bool same_guid(const GUID& a, const GUID& b) { return std::memcmp(&a, &b, sizeof(GUID)) == 0; } | ||
| 67 | |||
| 68 | std::string hr_text(HRESULT hr) { | ||
| 69 | char b[16]; | ||
| 70 | std::snprintf(b, sizeof b, "0x%08lx", static_cast<unsigned long>(hr)); | ||
| 71 | return b; | ||
| 72 | } | ||
| 73 | |||
| 74 | // ---- Interface ids ------------------------------------------------------------------------------------------------ | ||
| 75 | // | ||
| 76 | // The X interfaces' ids are not public. A creating call (DStorageGetFactory, CreateQueue*, OpenFile, | ||
| 77 | // CreateStatusArray) accepts an id it has not seen for the kind of object it hands out and logs it the first time, so | ||
| 78 | // the first boot records the console's ids. It refuses an id seen for another kind, a PC DirectStorage id of another | ||
| 79 | // shape, and the system COM interfaces (IMarshal, IAgileObject, ...), which a DirectStorage object never implements. | ||
| 80 | // QueryInterface is stricter (docs/d3d12_vulkan.md: an unknown id is E_NOINTERFACE): it accepts IUnknown, the | ||
| 81 | // declared ids (dstorage_xs_abi.h) and the ids a creating call accepted for that kind, and logs anything else. This is | ||
| 82 | // a policy, not a fact; it lives here so a measured id list can replace it. | ||
| 83 | |||
| 84 | enum class Kind { Factory, Queue, File, StatusArray }; | ||
| 85 | |||
| 86 | const char* kind_name(Kind k) { | ||
| 87 | switch (k) { | ||
| 88 | case Kind::Factory: return "factory"; | ||
| 89 | case Kind::Queue: return "queue"; | ||
| 90 | case Kind::File: return "file"; | ||
| 91 | case Kind::StatusArray: return "status array"; | ||
| 92 | } | ||
| 93 | return "?"; | ||
| 94 | } | ||
| 95 | |||
| 96 | // System interfaces: the COM base range {xxxxxxxx-0000-0000-C000-000000000046} (IClassFactory, IMarshal, | ||
| 97 | // IStdMarshalInfo, IExternalConnection, IMultiQI, IClientSecurity, IServerSecurity, IRpcOptions, IMarshal2, | ||
| 98 | // IWeakReferenceSource, IDispatch, IPersist, ...) and these others. | ||
| 99 | constexpr GUID kSystemInterfaceIds[] = { | ||
| 100 | {0x94ea2b94, 0xe9cc, 0x49e0, {0xc0, 0xff, 0xee, 0x64, 0xca, 0x8f, 0x5b, 0x90}}, // IAgileObject | ||
| 101 | {0xecc8691b, 0xc1db, 0x4dc0, {0x85, 0x5e, 0x65, 0xf6, 0xc5, 0x51, 0xaf, 0x49}}, // INoMarshal | ||
| 102 | {0x1c733a30, 0x2a1c, 0x11ce, {0xad, 0xe5, 0x00, 0xaa, 0x00, 0x44, 0x77, 0x3d}}, // ICallFactory | ||
| 103 | {0xaf86e2e0, 0xb12d, 0x4c6a, {0x9c, 0x5a, 0xd7, 0xaa, 0x65, 0x10, 0x1e, 0x90}}, // IInspectable | ||
| 104 | {0xdf0b3d60, 0x548f, 0x101b, {0x8e, 0x65, 0x08, 0x00, 0x2b, 0x2b, 0xd1, 0x19}}, // ISupportErrorInfo | ||
| 105 | {0xb196b283, 0xbab4, 0x101a, {0xb6, 0x9c, 0x00, 0xaa, 0x00, 0x34, 0x1d, 0x07}}, // IProvideClassInfo | ||
| 106 | {0xb196b284, 0xbab4, 0x101a, {0xb6, 0x9c, 0x00, 0xaa, 0x00, 0x34, 0x1d, 0x07}}, // IConnectionPointContainer | ||
| 107 | {0xfc4801a3, 0x2ba9, 0x11cf, {0xa2, 0x29, 0x00, 0xaa, 0x00, 0x3d, 0x73, 0x52}}, // IObjectWithSite | ||
| 108 | }; | ||
| 109 | |||
| 110 | bool system_interface(const GUID& g) { | ||
| 111 | static const uint8_t kComBase[8] = {0xc0, 0, 0, 0, 0, 0, 0, 0x46}; | ||
| 112 | if (g.Data2 == 0 && g.Data3 == 0 && std::memcmp(g.Data4, kComBase, 8) == 0) return true; | ||
| 113 | for (const GUID& s : kSystemInterfaceIds) | ||
| 114 | if (same_guid(g, s)) return true; | ||
| 115 | return false; | ||
| 116 | } | ||
| 117 | |||
| 118 | // The ids declared for a kind: the PC IDStorageStatusArray id, whose interface has the console one's shape (console | ||
| 119 | // D3D12 binaries reuse the PC SDK's ids). No other X interface id is known. | ||
| 120 | bool declared(const GUID& g, Kind kind) { | ||
| 121 | for (const GUID& id : kStatusArrayIds) | ||
| 122 | if (same_guid(g, id)) return kind == Kind::StatusArray; | ||
| 123 | return false; | ||
| 124 | } | ||
| 125 | |||
| 126 | bool declared_for_any(const GUID& g) { | ||
| 127 | for (const GUID& id : kStatusArrayIds) | ||
| 128 | if (same_guid(g, id)) return true; | ||
| 129 | return false; | ||
| 130 | } | ||
| 131 | |||
| 132 | class IidPolicy { | ||
| 133 | public: | ||
| 134 | bool accept_creating(REFIID riid, Kind kind, const char* caller) { | ||
| 135 | if (same_guid(riid, __uuidof(IUnknown)) || declared(riid, kind)) return true; | ||
| 136 | if (system_interface(riid)) return refuse(riid, caller, "a system COM interface"); | ||
| 137 | if (declared_for_any(riid)) return refuse(riid, caller, "an id declared for another kind of object"); | ||
| 138 | for (const GUID& pc : kPcInterfaceIds) | ||
| 139 | if (same_guid(riid, pc)) | ||
| 140 | return refuse(riid, caller, "a PC DirectStorage interface; only the console ABI is served"); | ||
| 141 | std::lock_guard lock(mutex_); | ||
| 142 | for (const auto& [id, k] : learned_) | ||
| 143 | if (same_guid(id, riid)) { | ||
| 144 | if (k == kind) return true; | ||
| 145 | return refuse(riid, caller, std::string("seen before as a ") + kind_name(k) + " interface"); | ||
| 146 | } | ||
| 147 | learned_.push_back({riid, kind}); | ||
| 148 | log_once("learn" + guid_text(riid), std::string(caller) + " asked for " + guid_text(riid) + ": serving the " + | ||
| 149 | kind_name(kind) + " interface"); | ||
| 150 | return true; | ||
| 151 | } | ||
| 152 | |||
| 153 | bool accept_query(REFIID riid, Kind kind, const char* caller) { | ||
| 154 | if (same_guid(riid, __uuidof(IUnknown)) || declared(riid, kind)) return true; | ||
| 155 | { | ||
| 156 | std::lock_guard lock(mutex_); | ||
| 157 | for (const auto& [id, k] : learned_) | ||
| 158 | if (same_guid(id, riid) && k == kind) return true; | ||
| 159 | } | ||
| 160 | return refuse(riid, caller, std::string("not an id a ") + kind_name(kind) + " was created with"); | ||
| 161 | } | ||
| 162 | |||
| 163 | private: | ||
| 164 | static bool refuse(REFIID riid, const char* caller, const std::string& why) { | ||
| 165 | log_once(std::string("refuse") + caller + guid_text(riid), | ||
| 166 | std::string(caller) + " asked for " + guid_text(riid) + ": " + why + " (E_NOINTERFACE)"); | ||
| 167 | return false; | ||
| 168 | } | ||
| 169 | |||
| 170 | std::mutex mutex_; | ||
| 171 | std::vector<std::pair<GUID, Kind>> learned_; | ||
| 172 | }; | ||
| 173 | |||
| 174 | IidPolicy& iid_policy() { | ||
| 175 | static auto* p = new IidPolicy; | ||
| 176 | return *p; | ||
| 177 | } | ||
| 178 | |||
| 179 | // A bad argument to a factory or queue method, logged once per method and kind: a wrong vtable guess for the console | ||
| 180 | // interfaces would show up here first, as arguments that make no sense for the method. | ||
| 181 | HRESULT bad_call(const char* method, HRESULT hr, const char* what) { | ||
| 182 | log_once(std::string("bad") + method + what, | ||
| 183 | std::string(method) + ": " + what + " (" + hr_text(hr) + | ||
| 184 | "; logged once; a wrong vtable slot guess would show up like this)"); | ||
| 185 | return hr; | ||
| 186 | } | ||
| 187 | |||
| 188 | // ---- Statistics (IDStorageFactoryX1::GetStats) -------------------------------------------------------------------- | ||
| 189 | |||
| 190 | struct Stats { | ||
| 191 | std::mutex mutex; | ||
| 192 | DSTORAGE_STATS s{}; | ||
| 193 | uint32_t live_queues = 0; // all priorities; SetStagingBufferSize is refused while queues or files exist | ||
| 194 | }; | ||
| 195 | |||
| 196 | Stats& stats() { | ||
| 197 | static auto* s = new Stats; | ||
| 198 | return *s; | ||
| 199 | } | ||
| 200 | |||
| 201 | DSTORAGE_PRIORITY_STATS& priority_stats(DSTORAGE_STATS& s, DSTORAGE_PRIORITY p) { | ||
| 202 | switch (p) { | ||
| 203 | case DSTORAGE_PRIORITY_LOW: return s.LowPriorityStats; | ||
| 204 | case DSTORAGE_PRIORITY_HIGH: return s.HighPriorityStats; | ||
| 205 | case DSTORAGE_PRIORITY_REALTIME: return s.RealtimePriorityStats; | ||
| 206 | default: return s.NormalPriorityStats; | ||
| 207 | } | ||
| 208 | } | ||
| 209 | |||
| 210 | void count_error() { | ||
| 211 | std::lock_guard lock(stats().mutex); | ||
| 212 | ++stats().s.ErrorCount; | ||
| 213 | } | ||
| 214 | |||
| 215 | // ---- Live objects --------------------------------------------------------------------------------------------------- | ||
| 216 | // | ||
| 217 | // A request names its file and a status entry its array by pointer. Only objects this shim made and that are still | ||
| 218 | // alive are used; anything else is an error in the request, never a call through a stranger's vtable. | ||
| 219 | |||
| 220 | std::mutex& live_mutex() { | ||
| 221 | static auto* m = new std::mutex; | ||
| 222 | return *m; | ||
| 223 | } | ||
| 224 | // One set per kind, so a status array passed as a file (or the other way round) is not found. | ||
| 225 | std::unordered_set<const void*>& live_files() { | ||
| 226 | static auto* s = new std::unordered_set<const void*>; | ||
| 227 | return *s; | ||
| 228 | } | ||
| 229 | std::unordered_set<const void*>& live_status_arrays() { | ||
| 230 | static auto* s = new std::unordered_set<const void*>; | ||
| 231 | return *s; | ||
| 232 | } | ||
| 233 | |||
| 234 | // AddRef only if the count has not reached zero (an object being released is not revived). | ||
| 235 | bool add_ref_if_live(std::atomic<ULONG>& refs) { | ||
| 236 | ULONG r = refs.load(); | ||
| 237 | while (r != 0) | ||
| 238 | if (refs.compare_exchange_weak(r, r + 1)) return true; | ||
| 239 | return false; | ||
| 240 | } | ||
| 241 | |||
| 242 | // ---- Status arrays ------------------------------------------------------------------------------------------------ | ||
| 243 | |||
| 244 | class StatusArray final : public IDStorageStatusArrayX { | ||
| 245 | public: | ||
| 246 | StatusArray(uint32_t capacity, std::unique_ptr<std::atomic<HRESULT>[]> entries) | ||
| 247 | : capacity_(capacity), entries_(std::move(entries)) { | ||
| 248 | for (uint32_t i = 0; i < capacity_; ++i) entries_[i].store(S_OK, std::memory_order_relaxed); | ||
| 249 | std::lock_guard lock(live_mutex()); | ||
| 250 | live_status_arrays().insert(static_cast<IDStorageStatusArrayX*>(this)); | ||
| 251 | } | ||
| 252 | |||
| 253 | HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override { | ||
| 254 | if (!ppv) return E_POINTER; | ||
| 255 | *ppv = nullptr; | ||
| 256 | if (!iid_policy().accept_query(riid, Kind::StatusArray, "IDStorageStatusArrayX::QueryInterface")) | ||
| 257 | return E_NOINTERFACE; | ||
| 258 | AddRef(); | ||
| 259 | *ppv = static_cast<IDStorageStatusArrayX*>(this); | ||
| 260 | return S_OK; | ||
| 261 | } | ||
| 262 | ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; } | ||
| 263 | ULONG STDMETHODCALLTYPE Release() override { | ||
| 264 | ULONG r; | ||
| 265 | { | ||
| 266 | std::lock_guard lock(live_mutex()); | ||
| 267 | r = --refs_; | ||
| 268 | if (r == 0) live_status_arrays().erase(static_cast<IDStorageStatusArrayX*>(this)); | ||
| 269 | } | ||
| 270 | if (r == 0) delete this; | ||
| 271 | return r; | ||
| 272 | } | ||
| 273 | |||
| 274 | // IsComplete is GetHResult(index) != E_PENDING (the reference says so); an index past the array is not pending. | ||
| 275 | bool STDMETHODCALLTYPE IsComplete(UINT32 index) override { return GetHResult(index) != E_PENDING; } | ||
| 276 | HRESULT STDMETHODCALLTYPE GetHResult(UINT32 index) override { | ||
| 277 | if (index >= capacity_) return E_DSTORAGE_INDEX_BOUND; | ||
| 278 | return entries_[index].load(std::memory_order_acquire); | ||
| 279 | } | ||
| 280 | |||
| 281 | uint32_t capacity() const { return capacity_; } | ||
| 282 | void set_pending(uint32_t index) { entries_[index].store(E_PENDING, std::memory_order_release); } | ||
| 283 | void complete(uint32_t index, HRESULT hr) { entries_[index].store(hr, std::memory_order_release); } | ||
| 284 | std::atomic<ULONG>& refs() { return refs_; } | ||
| 285 | |||
| 286 | private: | ||
| 287 | std::atomic<ULONG> refs_{1}; | ||
| 288 | const uint32_t capacity_; | ||
| 289 | std::unique_ptr<std::atomic<HRESULT>[]> entries_; | ||
| 290 | }; | ||
| 291 | |||
| 292 | // ---- Files -------------------------------------------------------------------------------------------------------- | ||
| 293 | |||
| 294 | class File final : public IDStorageFileX { | ||
| 295 | public: | ||
| 296 | File(HANDLE handle, std::wstring path) : handle_(handle), path_(std::move(path)) { | ||
| 297 | { | ||
| 298 | std::lock_guard lock(live_mutex()); | ||
| 299 | live_files().insert(static_cast<IDStorageFileX*>(this)); | ||
| 300 | } | ||
| 301 | std::lock_guard lock(stats().mutex); | ||
| 302 | auto& s = stats().s; | ||
| 303 | ++s.CurrentOpenFileCount; | ||
| 304 | ++s.CumulativeOpenFileCount; | ||
| 305 | s.MaxOpenFileCount = std::max(s.MaxOpenFileCount, s.CurrentOpenFileCount); | ||
| 306 | } | ||
| 307 | ~File() { | ||
| 308 | Close(); | ||
| 309 | std::lock_guard lock(stats().mutex); | ||
| 310 | --stats().s.CurrentOpenFileCount; | ||
| 311 | } | ||
| 312 | |||
| 313 | HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override { | ||
| 314 | if (!ppv) return E_POINTER; | ||
| 315 | *ppv = nullptr; | ||
| 316 | if (!iid_policy().accept_query(riid, Kind::File, "IDStorageFileX::QueryInterface")) return E_NOINTERFACE; | ||
| 317 | AddRef(); | ||
| 318 | *ppv = static_cast<IDStorageFileX*>(this); | ||
| 319 | return S_OK; | ||
| 320 | } | ||
| 321 | ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; } | ||
| 322 | ULONG STDMETHODCALLTYPE Release() override { | ||
| 323 | ULONG r; | ||
| 324 | { | ||
| 325 | std::lock_guard lock(live_mutex()); | ||
| 326 | r = --refs_; | ||
| 327 | if (r == 0) live_files().erase(static_cast<IDStorageFileX*>(this)); | ||
| 328 | } | ||
| 329 | if (r == 0) delete this; | ||
| 330 | return r; | ||
| 331 | } | ||
| 332 | |||
| 333 | // Waits for the submitted requests that read this file, then closes the handle. A request submitted later fails | ||
| 334 | // with E_DSTORAGE_FILE_NOT_OPEN. Waiting only for submitted requests keeps a Close from blocking forever on a | ||
| 335 | // request that sits unsubmitted in a queue with auto-submit disabled. | ||
| 336 | void STDMETHODCALLTYPE Close() override { | ||
| 337 | std::unique_lock lock(mutex_); | ||
| 338 | closed_ = true; | ||
| 339 | idle_.wait(lock, [&] { return pending_ == 0; }); | ||
| 340 | if (handle_ != INVALID_HANDLE_VALUE) { | ||
| 341 | CloseHandle(handle_); | ||
| 342 | handle_ = INVALID_HANDLE_VALUE; | ||
| 343 | } | ||
| 344 | } | ||
| 345 | |||
| 346 | // A new handle the caller closes (GENERIC_READ, FILE_SHARE_READ, as the reference describes it). ReOpenFile, | ||
| 347 | // not DuplicateHandle: a duplicate shares the file position with the shim's own reads, so the title's ReadFile | ||
| 348 | // through it would start wherever the worker's last read ended. | ||
| 349 | HANDLE STDMETHODCALLTYPE GetHandle() override { | ||
| 350 | std::lock_guard lock(mutex_); | ||
| 351 | if (closed_ || handle_ == INVALID_HANDLE_VALUE) { | ||
| 352 | SetLastError(ERROR_INVALID_HANDLE); | ||
| 353 | return INVALID_HANDLE_VALUE; | ||
| 354 | } | ||
| 355 | return ReOpenFile(handle_, GENERIC_READ, FILE_SHARE_READ, 0); | ||
| 356 | } | ||
| 357 | |||
| 358 | // Called when a request naming this file is submitted. False once the file is closed. | ||
| 359 | bool add_pending() { | ||
| 360 | std::lock_guard lock(mutex_); | ||
| 361 | if (closed_) return false; | ||
| 362 | ++pending_; | ||
| 363 | return true; | ||
| 364 | } | ||
| 365 | void finish_pending() { | ||
| 366 | std::lock_guard lock(mutex_); | ||
| 367 | if (--pending_ == 0) idle_.notify_all(); | ||
| 368 | } | ||
| 369 | // Valid while the caller holds a pending count: Close does not close the handle before it drops to zero. | ||
| 370 | HANDLE handle() const { return handle_; } | ||
| 371 | const std::wstring& path() const { return path_; } | ||
| 372 | std::atomic<ULONG>& refs() { return refs_; } | ||
| 373 | |||
| 374 | private: | ||
| 375 | std::atomic<ULONG> refs_{1}; | ||
| 376 | std::mutex mutex_; | ||
| 377 | std::condition_variable idle_; | ||
| 378 | HANDLE handle_; | ||
| 379 | const std::wstring path_; | ||
| 380 | uint32_t pending_ = 0; | ||
| 381 | bool closed_ = false; | ||
| 382 | }; | ||
| 383 | |||
| 384 | StatusArray* live_status_array(IDStorageStatusArrayX* p) { | ||
| 385 | std::lock_guard lock(live_mutex()); | ||
| 386 | if (!p || !live_status_arrays().count(p)) return nullptr; | ||
| 387 | auto* a = static_cast<StatusArray*>(p); | ||
| 388 | return add_ref_if_live(a->refs()) ? a : nullptr; | ||
| 389 | } | ||
| 390 | |||
| 391 | File* live_file(IDStorageFileX* p) { | ||
| 392 | std::lock_guard lock(live_mutex()); | ||
| 393 | if (!p || !live_files().count(p)) return nullptr; | ||
| 394 | auto* f = static_cast<File*>(p); | ||
| 395 | return add_ref_if_live(f->refs()) ? f : nullptr; | ||
| 396 | } | ||
| 397 | |||
| 398 | // ---- Reads -------------------------------------------------------------------------------------------------------- | ||
| 399 | |||
| 400 | // memmove that turns an access violation into an error instead of ending the process. No C++ objects here: a | ||
| 401 | // function with __try cannot have any that need unwinding. | ||
| 402 | bool guarded_move(void* destination, const void* source, size_t size) { | ||
| 403 | __try { | ||
| 404 | std::memmove(destination, source, size); | ||
| 405 | return true; | ||
| 406 | } __except (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER | ||
| 407 | : EXCEPTION_CONTINUE_SEARCH) { | ||
| 408 | return false; | ||
| 409 | } | ||
| 410 | } | ||
| 411 | |||
| 412 | HRESULT read_error(DWORD error) { | ||
| 413 | switch (error) { | ||
| 414 | case ERROR_NOACCESS: | ||
| 415 | case ERROR_INVALID_USER_BUFFER: return E_DSTORAGE_ACCESS_VIOLATION; | ||
| 416 | case ERROR_HANDLE_EOF: return E_DSTORAGE_END_OF_FILE; | ||
| 417 | default: return HRESULT_FROM_WIN32(error); | ||
| 418 | } | ||
| 419 | } | ||
| 420 | |||
| 421 | // Reads exactly "size" bytes at "offset" of a synchronous handle into "destination". | ||
| 422 | HRESULT read_file_range(HANDLE handle, uint64_t offset, void* destination, uint32_t size) { | ||
| 423 | LARGE_INTEGER length{}; | ||
| 424 | if (!GetFileSizeEx(handle, &length)) return HRESULT_FROM_WIN32(GetLastError()); | ||
| 425 | const uint64_t file_size = static_cast<uint64_t>(length.QuadPart); | ||
| 426 | if (offset > file_size || size > file_size - offset) return E_DSTORAGE_END_OF_FILE; | ||
| 427 | auto* out = static_cast<uint8_t*>(destination); | ||
| 428 | uint32_t done = 0; | ||
| 429 | while (done < size) { | ||
| 430 | OVERLAPPED at{}; | ||
| 431 | const uint64_t position = offset + done; | ||
| 432 | at.Offset = static_cast<DWORD>(position); | ||
| 433 | at.OffsetHigh = static_cast<DWORD>(position >> 32); | ||
| 434 | DWORD got = 0; | ||
| 435 | if (!ReadFile(handle, out + done, size - done, &got, &at)) return read_error(GetLastError()); | ||
| 436 | if (got == 0) return E_DSTORAGE_END_OF_FILE; // the file shrank since the size check | ||
| 437 | done += got; | ||
| 438 | } | ||
| 439 | return S_OK; | ||
| 440 | } | ||
| 441 | |||
| 442 | // ---- Queues ------------------------------------------------------------------------------------------------------- | ||
| 443 | |||
| 444 | struct Entry { | ||
| 445 | enum class Type { Request, Status, Signal, Event } type = Type::Request; | ||
| 446 | DSTORAGE_REQUEST request{}; | ||
| 447 | File* file = nullptr; // a reference, for a file request naming a live file | ||
| 448 | bool file_counted = false; // the file's pending count was raised at submit | ||
| 449 | bool cancelled = false; // CancelRequestsWithTag matched it before it started | ||
| 450 | bool counted = false; // a request the title passed: counted in the statistics when it is submitted | ||
| 451 | HRESULT enqueue_error = S_OK; // found at enqueue: reported when the entry is reached, in order | ||
| 452 | StatusArray* status = nullptr; // a reference | ||
| 453 | IDStorageStatusArrayX* status_as_given = nullptr; | ||
| 454 | uint32_t index = 0; | ||
| 455 | ID3D12Fence* fence = nullptr; // a reference | ||
| 456 | uint64_t value = 0; | ||
| 457 | HANDLE event = nullptr; // a duplicate the entry owns | ||
| 458 | }; | ||
| 459 | |||
| 460 | class Queue final : public IDStorageQueueX2 { | ||
| 461 | public: | ||
| 462 | explicit Queue(const DSTORAGE_QUEUE_DESC1& desc) : desc_(desc) { | ||
| 463 | error_event_ = CreateEventW(nullptr, TRUE, FALSE, nullptr); | ||
| 464 | clear_record_locked(); | ||
| 465 | std::lock_guard lock(stats().mutex); | ||
| 466 | auto& p = priority_stats(stats().s, desc_.Priority); | ||
| 467 | ++p.CurrentQueueCount; | ||
| 468 | ++p.CumulativeQueueCount; | ||
| 469 | p.MaxQueueCount = std::max(p.MaxQueueCount, p.CurrentQueueCount); | ||
| 470 | ++stats().live_queues; | ||
| 471 | } | ||
| 472 | // Separate from the constructor so a failure to start the thread can be reported. | ||
| 473 | bool start() { | ||
| 474 | if (!error_event_) return false; | ||
| 475 | try { | ||
| 476 | worker_ = std::thread([this] { run(); }); | ||
| 477 | } catch (...) { | ||
| 478 | return false; | ||
| 479 | } | ||
| 480 | return true; | ||
| 481 | } | ||
| 482 | ~Queue() { | ||
| 483 | Close(); | ||
| 484 | if (error_event_) CloseHandle(error_event_); | ||
| 485 | std::lock_guard lock(stats().mutex); | ||
| 486 | --priority_stats(stats().s, desc_.Priority).CurrentQueueCount; | ||
| 487 | --stats().live_queues; | ||
| 488 | } | ||
| 489 | |||
| 490 | HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override { | ||
| 491 | if (!ppv) return E_POINTER; | ||
| 492 | *ppv = nullptr; | ||
| 493 | if (!iid_policy().accept_query(riid, Kind::Queue, "IDStorageQueueX::QueryInterface")) return E_NOINTERFACE; | ||
| 494 | AddRef(); | ||
| 495 | *ppv = static_cast<IDStorageQueueX2*>(this); | ||
| 496 | return S_OK; | ||
| 497 | } | ||
| 498 | ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; } | ||
| 499 | // The last Release closes the queue, which runs everything enqueued first. | ||
| 500 | ULONG STDMETHODCALLTYPE Release() override { | ||
| 501 | const ULONG r = --refs_; | ||
| 502 | if (r == 0) delete this; | ||
| 503 | return r; | ||
| 504 | } | ||
| 505 | |||
| 506 | void STDMETHODCALLTYPE EnqueueRequest(const DSTORAGE_REQUEST* request) override { | ||
| 507 | Entry e; | ||
| 508 | e.type = Entry::Type::Request; | ||
| 509 | if (!request) { | ||
| 510 | e.enqueue_error = bad_call("IDStorageQueueX::EnqueueRequest", E_INVALIDARG, "null request"); | ||
| 511 | } else { | ||
| 512 | e.request = *request; // the title may reuse its structure as soon as this returns | ||
| 513 | const uint64_t o = e.request.Options.AsUINT64; | ||
| 514 | if (options::source_type(o) == DSTORAGE_REQUEST_SOURCE_FILE && | ||
| 515 | desc_.SourceType == DSTORAGE_REQUEST_SOURCE_FILE && e.request.File) { | ||
| 516 | e.file = live_file(e.request.File); | ||
| 517 | if (!e.file) e.enqueue_error = E_DSTORAGE_INVALID_FILE_HANDLE; | ||
| 518 | } | ||
| 519 | e.counted = true; // TotalRequestCount is "submitted requests" (DSTORAGE_PRIORITY_STATS): see submit_locked | ||
| 520 | } | ||
| 521 | enqueue(std::move(e)); | ||
| 522 | } | ||
| 523 | |||
| 524 | void STDMETHODCALLTYPE EnqueueStatus(IDStorageStatusArrayX* status_array, UINT32 index) override { | ||
| 525 | Entry e; | ||
| 526 | e.type = Entry::Type::Status; | ||
| 527 | e.status_as_given = status_array; | ||
| 528 | e.index = index; | ||
| 529 | e.status = live_status_array(status_array); | ||
| 530 | if (!e.status) { | ||
| 531 | e.enqueue_error = E_DSTORAGE_INVALID_STATUS_ARRAY; | ||
| 532 | } else if (index >= e.status->capacity()) { | ||
| 533 | e.enqueue_error = E_DSTORAGE_INDEX_BOUND; | ||
| 534 | } else { | ||
| 535 | e.status->set_pending(index); // polling after this call sees E_PENDING until the entry is reached | ||
| 536 | } | ||
| 537 | { | ||
| 538 | std::lock_guard lock(stats().mutex); | ||
| 539 | ++priority_stats(stats().s, desc_.Priority).TotalStatusCount; | ||
| 540 | } | ||
| 541 | enqueue(std::move(e)); | ||
| 542 | } | ||
| 543 | |||
| 544 | void STDMETHODCALLTYPE EnqueueSignal(ID3D12Fence* fence, UINT64 value) override { | ||
| 545 | Entry e; | ||
| 546 | e.type = Entry::Type::Signal; | ||
| 547 | e.fence = fence; | ||
| 548 | e.value = value; | ||
| 549 | if (fence) { | ||
| 550 | fence->AddRef(); | ||
| 551 | } else { | ||
| 552 | e.enqueue_error = E_DSTORAGE_INVALID_FENCE; | ||
| 553 | } | ||
| 554 | { | ||
| 555 | std::lock_guard lock(stats().mutex); | ||
| 556 | ++priority_stats(stats().s, desc_.Priority).TotalFenceCount; | ||
| 557 | } | ||
| 558 | enqueue(std::move(e)); | ||
| 559 | } | ||
| 560 | |||
| 561 | // The handle is duplicated here and the duplicate closed once it has been set (or dropped), so an event the | ||
| 562 | // title closes, and whose handle value is then reused for another object, is never the one set. | ||
| 563 | void STDMETHODCALLTYPE EnqueueSetEvent(HANDLE handle) override { | ||
| 564 | Entry e; | ||
| 565 | e.type = Entry::Type::Event; | ||
| 566 | if (!handle) { | ||
| 567 | e.enqueue_error = bad_call("IDStorageQueueX1::EnqueueSetEvent", HRESULT_FROM_WIN32(ERROR_INVALID_HANDLE), | ||
| 568 | "null event handle"); | ||
| 569 | } else if (!DuplicateHandle(GetCurrentProcess(), handle, GetCurrentProcess(), &e.event, 0, FALSE, | ||
| 570 | DUPLICATE_SAME_ACCESS)) { | ||
| 571 | e.event = nullptr; | ||
| 572 | e.enqueue_error = HRESULT_FROM_WIN32(GetLastError()); | ||
| 573 | } | ||
| 574 | enqueue(std::move(e)); | ||
| 575 | } | ||
| 576 | |||
| 577 | void STDMETHODCALLTYPE Submit() override { | ||
| 578 | std::lock_guard lock(mutex_); | ||
| 579 | submit_locked(); | ||
| 580 | } | ||
| 581 | |||
| 582 | // Marks the requests enqueued before this call that have not started. A cancelled request completes as a success | ||
| 583 | // without being read (the overview: the title may no longer use its result). | ||
| 584 | void STDMETHODCALLTYPE CancelRequestsWithTag(UINT64 mask, UINT64 value) override { | ||
| 585 | std::lock_guard lock(mutex_); | ||
| 586 | for (Entry& e : entries_) | ||
| 587 | if (e.type == Entry::Type::Request && (e.request.CancellationTag & mask) == value) e.cancelled = true; | ||
| 588 | } | ||
| 589 | |||
| 590 | // Submits what is enqueued, waits until the worker has run all of it and stops the worker. Later enqueues are | ||
| 591 | // dropped and recorded as E_DSTORAGE_QUEUE_CLOSED. | ||
| 592 | void STDMETHODCALLTYPE Close() override { | ||
| 593 | std::lock_guard close_lock(close_mutex_); | ||
| 594 | { | ||
| 595 | std::unique_lock lock(mutex_); | ||
| 596 | if (closed_) return; | ||
| 597 | closing_ = true; | ||
| 598 | submit_locked(); | ||
| 599 | space_.notify_all(); // an enqueue waiting for space gives up (the queue is closing) | ||
| 600 | idle_.wait(lock, [&] { return entries_.empty() && !in_flight_; }); | ||
| 601 | closed_ = true; | ||
| 602 | work_.notify_all(); | ||
| 603 | } | ||
| 604 | if (worker_.joinable()) worker_.join(); | ||
| 605 | } | ||
| 606 | |||
| 607 | HANDLE STDMETHODCALLTYPE GetErrorEvent() override { | ||
| 608 | HANDLE dup = nullptr; | ||
| 609 | if (!error_event_ || !DuplicateHandle(GetCurrentProcess(), error_event_, GetCurrentProcess(), &dup, 0, FALSE, | ||
| 610 | DUPLICATE_SAME_ACCESS)) | ||
| 611 | return nullptr; | ||
| 612 | return dup; // the reference says the title closes it | ||
| 613 | } | ||
| 614 | |||
| 615 | void STDMETHODCALLTYPE RetrieveErrorRecord(DSTORAGE_ERROR_RECORD* record) override { | ||
| 616 | if (!record) { | ||
| 617 | bad_call("IDStorageQueueX::RetrieveErrorRecord", E_POINTER, "null record"); | ||
| 618 | return; | ||
| 619 | } | ||
| 620 | std::lock_guard lock(error_mutex_); | ||
| 621 | *record = record_; | ||
| 622 | clear_record_locked(); | ||
| 623 | if (error_event_) ResetEvent(error_event_); | ||
| 624 | } | ||
| 625 | |||
| 626 | void STDMETHODCALLTYPE Query(DSTORAGE_QUEUE_INFO* info) override { | ||
| 627 | if (!info) { | ||
| 628 | bad_call("IDStorageQueueX::Query", E_POINTER, "null info"); | ||
| 629 | return; | ||
| 630 | } | ||
| 631 | DSTORAGE_QUEUE_INFO1 full{}; | ||
| 632 | Query1(&full); | ||
| 633 | info->Desc.SourceType = full.Desc.SourceType; | ||
| 634 | info->Desc.Capacity = full.Desc.Capacity; | ||
| 635 | info->Desc.Priority = full.Desc.Priority; | ||
| 636 | info->Desc.Name = full.Desc.Name; | ||
| 637 | info->EmptySlotCount = full.EmptySlotCount; | ||
| 638 | info->RequestCountUntilAutoSubmit = full.RequestCountUntilAutoSubmit; | ||
| 639 | } | ||
| 640 | |||
| 641 | // An empty queue has capacity - 1 empty slots (one slot tells empty from full). The automatic submit happens when | ||
| 642 | // the entries enqueued since the last submit reach half the capacity; with it disabled the count is 0. | ||
| 643 | void STDMETHODCALLTYPE Query1(DSTORAGE_QUEUE_INFO1* info) override { | ||
| 644 | if (!info) { | ||
| 645 | bad_call("IDStorageQueueX2::Query1", E_POINTER, "null info"); | ||
| 646 | return; | ||
| 647 | } | ||
| 648 | std::lock_guard lock(mutex_); | ||
| 649 | info->Desc = desc_; | ||
| 650 | info->EmptySlotCount = static_cast<UINT16>(usable() - used_locked()); | ||
| 651 | const size_t unsubmitted = entries_.size() - submitted_; | ||
| 652 | info->RequestCountUntilAutoSubmit = | ||
| 653 | auto_submit() ? static_cast<UINT16>(half() > unsubmitted ? half() - unsubmitted : 0) : 0; | ||
| 654 | } | ||
| 655 | |||
| 656 | private: | ||
| 657 | size_t usable() const { return desc_.Capacity - 1u; } | ||
| 658 | size_t half() const { return desc_.Capacity / 2u; } | ||
| 659 | bool auto_submit() const { return !desc_.Options.AutoSubmitDisabled; } | ||
| 660 | size_t used_locked() const { return entries_.size() + (in_flight_ ? 1 : 0); } | ||
| 661 | |||
| 662 | void enqueue(Entry&& e) { | ||
| 663 | { | ||
| 664 | std::unique_lock lock(mutex_); | ||
| 665 | // A full queue waits for the worker to free a slot. With auto-submit on, half the queue is always | ||
| 666 | // submitted by then; with it off, only a Submit from another thread frees one (as the reference warns). | ||
| 667 | space_.wait(lock, [&] { return closing_ || used_locked() < usable(); }); | ||
| 668 | if (!closing_) { | ||
| 669 | entries_.push_back(std::move(e)); | ||
| 670 | if (auto_submit() && entries_.size() - submitted_ >= half()) submit_locked(); | ||
| 671 | return; | ||
| 672 | } | ||
| 673 | } | ||
| 674 | DSTORAGE_ERROR_FIRST_FAILURE f{}; | ||
| 675 | f.HResult = E_DSTORAGE_QUEUE_CLOSED; | ||
| 676 | describe(e, f); | ||
| 677 | record_failure(f); | ||
| 678 | log_once("closed", "an entry was enqueued on a closed queue (E_DSTORAGE_QUEUE_CLOSED); it never completes"); | ||
| 679 | release_references(e); | ||
| 680 | } | ||
| 681 | |||
| 682 | void submit_locked() { | ||
| 683 | uint32_t requests = 0; | ||
| 684 | uint64_t source_bytes = 0, destination_bytes = 0; | ||
| 685 | for (size_t i = submitted_; i < entries_.size(); ++i) { | ||
| 686 | Entry& e = entries_[i]; | ||
| 687 | if (e.file) e.file_counted = e.file->add_pending(); | ||
| 688 | if (e.counted) { | ||
| 689 | ++requests; | ||
| 690 | source_bytes += e.request.SourceSize; | ||
| 691 | destination_bytes += e.request.DestinationSize; | ||
| 692 | } | ||
| 693 | } | ||
| 694 | if (requests) { | ||
| 695 | std::lock_guard stats_lock(stats().mutex); | ||
| 696 | auto& p = priority_stats(stats().s, desc_.Priority); | ||
| 697 | p.TotalRequestCount += requests; | ||
| 698 | p.TotalRequestSourceByteCount += source_bytes; | ||
| 699 | p.TotalRequestDestinationByteCount += destination_bytes; | ||
| 700 | } | ||
| 701 | if (entries_.size() > submitted_) { | ||
| 702 | submitted_ = entries_.size(); | ||
| 703 | work_.notify_one(); | ||
| 704 | } | ||
| 705 | } | ||
| 706 | |||
| 707 | void run() { | ||
| 708 | for (;;) { | ||
| 709 | Entry e; | ||
| 710 | { | ||
| 711 | std::unique_lock lock(mutex_); | ||
| 712 | work_.wait(lock, [&] { return submitted_ > 0 || closed_; }); | ||
| 713 | if (submitted_ == 0) return; // closed and drained | ||
| 714 | e = std::move(entries_.front()); | ||
| 715 | entries_.pop_front(); | ||
| 716 | --submitted_; | ||
| 717 | in_flight_ = true; | ||
| 718 | } | ||
| 719 | process(e); | ||
| 720 | release_references(e); | ||
| 721 | { | ||
| 722 | std::lock_guard lock(mutex_); | ||
| 723 | in_flight_ = false; | ||
| 724 | space_.notify_all(); | ||
| 725 | if (entries_.empty()) idle_.notify_all(); | ||
| 726 | } | ||
| 727 | } | ||
| 728 | } | ||
| 729 | |||
| 730 | // Runs on the worker. since_notify_ is the first failure since the last status entry or fence signal: the | ||
| 731 | // HRESULT a status entry reports. | ||
| 732 | void process(Entry& e) { | ||
| 733 | HRESULT hr = e.enqueue_error; | ||
| 734 | switch (e.type) { | ||
| 735 | case Entry::Type::Request: | ||
| 736 | // A cancelled request is a success whatever else is wrong with it (the GDK: not counted as a failure). | ||
| 737 | if (e.cancelled) { | ||
| 738 | hr = S_OK; | ||
| 739 | } else if (SUCCEEDED(hr)) { | ||
| 740 | // Pending: processing has started and not completed (DSTORAGE_PRIORITY_STATS). | ||
| 741 | set_pending(+1); | ||
| 742 | hr = execute_request(e); | ||
| 743 | set_pending(-1); | ||
| 744 | } | ||
| 745 | if (e.file && e.file_counted) e.file->finish_pending(); | ||
| 746 | if (FAILED(hr) && SUCCEEDED(since_notify_)) since_notify_ = hr; | ||
| 747 | break; | ||
| 748 | case Entry::Type::Status: | ||
| 749 | if (SUCCEEDED(hr)) { | ||
| 750 | e.status->complete(e.index, since_notify_); | ||
| 751 | since_notify_ = S_OK; | ||
| 752 | } | ||
| 753 | break; | ||
| 754 | case Entry::Type::Signal: | ||
| 755 | if (SUCCEEDED(hr)) hr = e.fence->Signal(e.value); | ||
| 756 | since_notify_ = S_OK; | ||
| 757 | break; | ||
| 758 | case Entry::Type::Event: | ||
| 759 | if (SUCCEEDED(hr) && !SetEvent(e.event)) hr = HRESULT_FROM_WIN32(GetLastError()); | ||
| 760 | break; | ||
| 761 | } | ||
| 762 | if (FAILED(hr)) { | ||
| 763 | DSTORAGE_ERROR_FIRST_FAILURE f{}; | ||
| 764 | f.HResult = hr; | ||
| 765 | describe(e, f); | ||
| 766 | record_failure(f); | ||
| 767 | } | ||
| 768 | } | ||
| 769 | |||
| 770 | HRESULT execute_request(const Entry& e) { | ||
| 771 | const DSTORAGE_REQUEST& r = e.request; | ||
| 772 | const uint64_t o = r.Options.AsUINT64; | ||
| 773 | if (o & options::kReservedMask) return E_DSTORAGE_RESERVED_FIELDS; | ||
| 774 | if (options::source_type(o) != desc_.SourceType) return E_DSTORAGE_INVALID_SOURCE_TYPE; | ||
| 775 | if (options::bcpack(o) > DSTORAGE_BCPACK_MODE_BC7) return E_DSTORAGE_INVALID_BCPACK_MODE; | ||
| 776 | if (options::swizzle(o) > DSTORAGE_SWIZZLE_MODE_4K_12K_4K_12K) return E_DSTORAGE_INVALID_SWIZZLE_MODE; | ||
| 777 | if (options::bcpack(o) != 0 || options::swizzle(o) != 0) { | ||
| 778 | log_once("decompress", "BCPack and swizzle requests are not implemented yet (E_NOTIMPL)"); | ||
| 779 | return E_NOTIMPL; | ||
| 780 | } | ||
| 781 | if (o & (options::kDestinationPages | options::kSourcePages)) { | ||
| 782 | log_once("pages", "physical-page requests are not implemented yet (E_NOTIMPL)"); | ||
| 783 | return E_NOTIMPL; | ||
| 784 | } | ||
| 785 | const bool zlib = options::zlib(o); | ||
| 786 | // IntermediateSize is the BCPack data's size between the inflate and the BCPack decode (DSTORAGE_REQUEST), so | ||
| 787 | // it is 0 for every request that gets here (BCPack is refused above). | ||
| 788 | if (r.IntermediateSize != 0) return E_DSTORAGE_INVALID_INTERMEDIATE_SIZE; | ||
| 789 | // E_DSTORAGE_INVALID_DESTINATION_SIZE: without decompression DestinationSize must equal the source's length, | ||
| 790 | // with it it must be larger (dstorageerr.h's description; DSTORAGE_REQUEST says the same of DestinationSize). | ||
| 791 | if (zlib ? r.DestinationSize <= r.SourceSize : r.DestinationSize != r.SourceSize) | ||
| 792 | return E_DSTORAGE_INVALID_DESTINATION_SIZE; | ||
| 793 | const bool memory = desc_.SourceType == DSTORAGE_REQUEST_SOURCE_MEMORY; | ||
| 794 | const uint64_t total = static_cast<uint64_t>(r.DestinationSize) + (memory ? r.SourceSize : 0u); | ||
| 795 | if (total > kMaxRequestBytes) return E_DSTORAGE_REQUEST_TOO_LARGE; | ||
| 796 | // DSTORAGE_REQUEST: a buffer over 32 MiB is allowed only with 64 KiB or 2 MiB pages, which are not implemented | ||
| 797 | // yet (refused above). The source is never larger than the destination here (the same size without zlib, | ||
| 798 | // smaller with it), so this covers both buffers, and bounds the staging buffers of a zlib request too. | ||
| 799 | if (r.DestinationSize > kMax4kPageDestinationSize) return E_DSTORAGE_REQUEST_TOO_LARGE; | ||
| 800 | // DSTORAGE_REQUEST: with ZlibDecompress the file offset must be 16-byte aligned. | ||
| 801 | if (zlib && !memory && r.FileOffset % 16 != 0) return E_DSTORAGE_INVALID_FILE_OFFSET; | ||
| 802 | if (!r.Destination) return E_INVALIDARG; | ||
| 803 | if (memory) { | ||
| 804 | if (!r.Source) return E_INVALIDARG; | ||
| 805 | } else { | ||
| 806 | if (!r.File) return E_INVALIDARG; | ||
| 807 | if (!e.file_counted) return E_DSTORAGE_FILE_NOT_OPEN; | ||
| 808 | } | ||
| 809 | if (zlib) return inflate_request(e, memory); | ||
| 810 | if (r.SourceSize == 0) return S_OK; // nothing to move; the reference does not say this fails | ||
| 811 | if (memory) return guarded_move(r.Destination, r.Source, r.SourceSize) ? S_OK : E_DSTORAGE_ACCESS_VIOLATION; | ||
| 812 | return read_file_range(e.file->handle(), r.FileOffset, r.Destination, r.SourceSize); | ||
| 813 | } | ||
| 814 | |||
| 815 | // A zlib request whose checks have passed: the source (SourceSize bytes of the file or of memory) goes into a | ||
| 816 | // staging buffer, inflates there, and only a result of exactly DestinationSize bytes is copied to the destination. | ||
| 817 | // So a failed stream leaves the destination as it was, and a memory source that overlaps its destination is safe. | ||
| 818 | // Both buffers are at most 32 MiB (execute_request). The stream is RFC 1950: the two header bytes, the deflate | ||
| 819 | // data, the Adler-32 of the result; bytes after the Adler-32 are not read. A failure is the matching | ||
| 820 | // dstorageerr.h code: a bad header (not deflate, a window over 32 KiB, a bad check value or a preset dictionary) | ||
| 821 | // E_DSTORAGE_ZLIB_BAD_HEADER, bad or truncated deflate data E_DSTORAGE_ZLIB_BAD_DATA, an Adler-32 mismatch | ||
| 822 | // E_DSTORAGE_ZLIB_PARITY_FAIL, and a stream that inflates to more or fewer bytes than DestinationSize | ||
| 823 | // E_DSTORAGE_DECOMPRESSION_ERROR (no code names a size mismatch; this is the header's generic one). | ||
| 824 | HRESULT inflate_request(const Entry& e, bool memory) { | ||
| 825 | const DSTORAGE_REQUEST& r = e.request; | ||
| 826 | std::vector<uint8_t> source, result; | ||
| 827 | try { | ||
| 828 | source.resize(r.SourceSize); | ||
| 829 | result.reserve(r.DestinationSize); | ||
| 830 | } catch (const std::bad_alloc&) { | ||
| 831 | return E_OUTOFMEMORY; | ||
| 832 | } | ||
| 833 | if (r.SourceSize != 0) { | ||
| 834 | if (memory) { | ||
| 835 | if (!guarded_move(source.data(), r.Source, r.SourceSize)) return E_DSTORAGE_ACCESS_VIOLATION; | ||
| 836 | } else if (const HRESULT hr = read_file_range(e.file->handle(), r.FileOffset, source.data(), r.SourceSize); | ||
| 837 | FAILED(hr)) { | ||
| 838 | return hr; | ||
| 839 | } | ||
| 840 | } | ||
| 841 | log_once("zlib", "zlib requests are inflated on the CPU (RFC 1950, leonida::zlib_inflate)"); | ||
| 842 | set_decompression_pending(+1); | ||
| 843 | leonida::ZlibError why = leonida::ZlibError::none; | ||
| 844 | const bool inflated = leonida::zlib_inflate(source, result, r.DestinationSize, &why); | ||
| 845 | set_decompression_pending(-1); | ||
| 846 | HRESULT hr = S_OK; | ||
| 847 | if (!inflated) { | ||
| 848 | switch (why) { | ||
| 849 | case leonida::ZlibError::header: hr = E_DSTORAGE_ZLIB_BAD_HEADER; break; | ||
| 850 | case leonida::ZlibError::checksum: hr = E_DSTORAGE_ZLIB_PARITY_FAIL; break; | ||
| 851 | case leonida::ZlibError::limit: hr = E_DSTORAGE_DECOMPRESSION_ERROR; break; // longer than the destination | ||
| 852 | default: hr = E_DSTORAGE_ZLIB_BAD_DATA; break; | ||
| 853 | } | ||
| 854 | } else if (result.size() != r.DestinationSize) { | ||
| 855 | hr = E_DSTORAGE_DECOMPRESSION_ERROR; // shorter than the destination | ||
| 856 | } | ||
| 857 | if (FAILED(hr)) { | ||
| 858 | std::lock_guard lock(stats().mutex); | ||
| 859 | ++stats().s.DecompressionErrors; | ||
| 860 | return hr; | ||
| 861 | } | ||
| 862 | return guarded_move(r.Destination, result.data(), result.size()) ? S_OK : E_DSTORAGE_ACCESS_VIOLATION; | ||
| 863 | } | ||
| 864 | |||
| 865 | void set_pending(int delta) { | ||
| 866 | std::lock_guard lock(stats().mutex); | ||
| 867 | priority_stats(stats().s, desc_.Priority).PendingRequestCount += static_cast<uint32_t>(delta); | ||
| 868 | } | ||
| 869 | |||
| 870 | // PendingDecompressionRequestCount is the zlib requests being inflated; TotalDecompressionRequestCount counts each | ||
| 871 | // one that reached its inflate (its source was read), DecompressionErrors those whose stream then failed. | ||
| 872 | static void set_decompression_pending(int delta) { | ||
| 873 | std::lock_guard lock(stats().mutex); | ||
| 874 | auto& s = stats().s; | ||
| 875 | s.PendingDecompressionRequestCount += static_cast<uint32_t>(delta); | ||
| 876 | if (delta > 0) ++s.TotalDecompressionRequestCount; | ||
| 877 | } | ||
| 878 | |||
| 879 | void describe(const Entry& e, DSTORAGE_ERROR_FIRST_FAILURE& f) const { | ||
| 880 | switch (e.type) { | ||
| 881 | case Entry::Type::Request: { | ||
| 882 | f.CommandType = DSTORAGE_COMMAND_TYPE_REQUEST; | ||
| 883 | auto& q = f.Request; | ||
| 884 | const DSTORAGE_REQUEST& r = e.request; | ||
| 885 | q.Options = r.Options; | ||
| 886 | q.Destination = r.Destination; | ||
| 887 | q.DestinationSize = r.DestinationSize; | ||
| 888 | q.SourceSize = r.SourceSize; | ||
| 889 | q.CancellationTag = r.CancellationTag; | ||
| 890 | if (options::source_type(r.Options.AsUINT64) == DSTORAGE_REQUEST_SOURCE_MEMORY) { | ||
| 891 | q.Source = r.Source; | ||
| 892 | } else { | ||
| 893 | q.FileOffset = r.FileOffset; | ||
| 894 | if (e.file) wcsncpy_s(q.Filename, e.file->path().c_str(), _TRUNCATE); | ||
| 895 | } | ||
| 896 | // The reference says the name stays readable until the request completes. | ||
| 897 | if (r.Name) | ||
| 898 | for (size_t i = 0; i + 1 < kRequestMaxName && r.Name[i]; ++i) q.Name[i] = r.Name[i]; | ||
| 899 | break; | ||
| 900 | } | ||
| 901 | case Entry::Type::Status: | ||
| 902 | f.CommandType = DSTORAGE_COMMAND_TYPE_STATUS; | ||
| 903 | f.Status.StatusArray = e.status_as_given; | ||
| 904 | f.Status.Index = e.index; | ||
| 905 | break; | ||
| 906 | case Entry::Type::Signal: | ||
| 907 | f.CommandType = DSTORAGE_COMMAND_TYPE_SIGNAL; | ||
| 908 | f.Signal.Fence = e.fence; | ||
| 909 | f.Signal.Value = e.value; | ||
| 910 | break; | ||
| 911 | case Entry::Type::Event: | ||
| 912 | f.CommandType = kCommandTypeEvent; | ||
| 913 | break; | ||
| 914 | } | ||
| 915 | } | ||
| 916 | |||
| 917 | void record_failure(const DSTORAGE_ERROR_FIRST_FAILURE& f) { | ||
| 918 | count_error(); | ||
| 919 | { | ||
| 920 | std::lock_guard lock(error_mutex_); | ||
| 921 | if (record_.FailureCount++ == 0) record_.FirstFailure = f; | ||
| 922 | if (error_event_) SetEvent(error_event_); | ||
| 923 | } | ||
| 924 | log_once("fail" + hr_text(f.HResult) + std::to_string(f.CommandType), | ||
| 925 | "an entry failed with " + hr_text(f.HResult) + " (command type " + std::to_string(f.CommandType) + | ||
| 926 | "; logged once per code)"); | ||
| 927 | } | ||
| 928 | |||
| 929 | void clear_record_locked() { | ||
| 930 | record_ = DSTORAGE_ERROR_RECORD{}; | ||
| 931 | record_.FirstFailure.CommandType = DSTORAGE_COMMAND_TYPE_NONE; | ||
| 932 | } | ||
| 933 | |||
| 934 | static void release_references(Entry& e) { | ||
| 935 | if (e.file) e.file->Release(); | ||
| 936 | if (e.status) e.status->Release(); | ||
| 937 | if (e.fence) e.fence->Release(); | ||
| 938 | if (e.event) CloseHandle(e.event); | ||
| 939 | e.event = nullptr; | ||
| 940 | e.file = nullptr; | ||
| 941 | e.status = nullptr; | ||
| 942 | e.fence = nullptr; | ||
| 943 | } | ||
| 944 | |||
| 945 | std::atomic<ULONG> refs_{1}; | ||
| 946 | const DSTORAGE_QUEUE_DESC1 desc_; | ||
| 947 | std::mutex close_mutex_; // one Close at a time | ||
| 948 | std::mutex mutex_; // entries_, submitted_, in_flight_, closing_, closed_ | ||
| 949 | std::condition_variable work_, space_, idle_; | ||
| 950 | std::deque<Entry> entries_; | ||
| 951 | size_t submitted_ = 0; // the first submitted_ entries are submitted | ||
| 952 | bool in_flight_ = false; | ||
| 953 | bool closing_ = false; | ||
| 954 | bool closed_ = false; | ||
| 955 | std::thread worker_; | ||
| 956 | HRESULT since_notify_ = S_OK; // worker only | ||
| 957 | std::mutex error_mutex_; | ||
| 958 | DSTORAGE_ERROR_RECORD record_{}; | ||
| 959 | HANDLE error_event_ = nullptr; | ||
| 960 | }; | ||
| 961 | |||
| 962 | // ---- The factory ---------------------------------------------------------------------------------------------------- | ||
| 963 | |||
| 964 | HRESULT validate_queue_desc(const DSTORAGE_QUEUE_DESC1& d) { | ||
| 965 | if (d.SourceType != DSTORAGE_REQUEST_SOURCE_FILE && d.SourceType != DSTORAGE_REQUEST_SOURCE_MEMORY) | ||
| 966 | return E_DSTORAGE_INVALID_SOURCE_TYPE; | ||
| 967 | if (d.Capacity < kMinQueueCapacity || d.Capacity > kMaxQueueCapacity) return E_DSTORAGE_INVALID_QUEUE_CAPACITY; | ||
| 968 | if (d.Priority < DSTORAGE_PRIORITY_FIRST || d.Priority > DSTORAGE_PRIORITY_LAST) | ||
| 969 | return E_DSTORAGE_INVALID_QUEUE_PRIORITY; | ||
| 970 | if (d.SourceType == DSTORAGE_REQUEST_SOURCE_MEMORY && d.Priority != DSTORAGE_PRIORITY_REALTIME) | ||
| 971 | return E_DSTORAGE_INVALID_MEMORY_QUEUE_PRIORITY; | ||
| 972 | if (d.Options.Reserved) return E_DSTORAGE_RESERVED_FIELDS; | ||
| 973 | return S_OK; | ||
| 974 | } | ||
| 975 | |||
| 976 | using CreateFileWFn = HANDLE(WINAPI*)(LPCWSTR, DWORD, DWORD, LPSECURITY_ATTRIBUTES, DWORD, DWORD, HANDLE); | ||
| 977 | |||
| 978 | // The title's own CreateFileW: the GAME: mapping and overlay when file_system.cpp is linked, else the host's. | ||
| 979 | CreateFileWFn create_file_w() { | ||
| 980 | if (void* fn = rt::shims::find("kernel32.dll", "CreateFileW")) return reinterpret_cast<CreateFileWFn>(fn); | ||
| 981 | return &::CreateFileW; | ||
| 982 | } | ||
| 983 | |||
| 984 | class Factory final : public IDStorageFactoryX2 { | ||
| 985 | public: | ||
| 986 | HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override { | ||
| 987 | if (!ppv) return E_POINTER; | ||
| 988 | *ppv = nullptr; | ||
| 989 | if (!iid_policy().accept_query(riid, Kind::Factory, "IDStorageFactoryX::QueryInterface")) return E_NOINTERFACE; | ||
| 990 | AddRef(); | ||
| 991 | *ppv = static_cast<IDStorageFactoryX2*>(this); | ||
| 992 | return S_OK; | ||
| 993 | } | ||
| 994 | ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; } | ||
| 995 | // One factory for the process; its count never drops below one, so it is never freed. | ||
| 996 | ULONG STDMETHODCALLTYPE Release() override { | ||
| 997 | ULONG r = refs_.load(); | ||
| 998 | while (r > 1 && !refs_.compare_exchange_weak(r, r - 1)) {} | ||
| 999 | return r > 1 ? r - 1 : 1; | ||
| 1000 | } | ||
| 1001 | |||
| 1002 | HRESULT STDMETHODCALLTYPE CreateQueue(const DSTORAGE_QUEUE_DESC* desc, REFIID riid, void** ppv) override { | ||
| 1003 | if (!ppv) return bad_call("IDStorageFactoryX::CreateQueue", E_POINTER, "null ppv"); | ||
| 1004 | *ppv = nullptr; | ||
| 1005 | if (!desc) return bad_call("IDStorageFactoryX::CreateQueue", E_INVALIDARG, "null desc"); | ||
| 1006 | DSTORAGE_QUEUE_DESC1 d{}; | ||
| 1007 | d.SourceType = desc->SourceType; | ||
| 1008 | d.Capacity = desc->Capacity; | ||
| 1009 | d.Priority = desc->Priority; | ||
| 1010 | d.Name = desc->Name; | ||
| 1011 | return create_queue(d, riid, ppv, "IDStorageFactoryX::CreateQueue"); | ||
| 1012 | } | ||
| 1013 | |||
| 1014 | HRESULT STDMETHODCALLTYPE CreateQueue1(const DSTORAGE_QUEUE_DESC1* desc, REFIID riid, void** ppv) override { | ||
| 1015 | if (!ppv) return bad_call("IDStorageFactoryX2::CreateQueue1", E_POINTER, "null ppv"); | ||
| 1016 | *ppv = nullptr; | ||
| 1017 | if (!desc) return bad_call("IDStorageFactoryX2::CreateQueue1", E_INVALIDARG, "null desc"); | ||
| 1018 | return create_queue(*desc, riid, ppv, "IDStorageFactoryX2::CreateQueue1"); | ||
| 1019 | } | ||
| 1020 | |||
| 1021 | HRESULT STDMETHODCALLTYPE OpenFile(const WCHAR* path, REFIID riid, void** ppv) override { | ||
| 1022 | if (!ppv) return bad_call("IDStorageFactoryX::OpenFile", E_POINTER, "null ppv"); | ||
| 1023 | *ppv = nullptr; | ||
| 1024 | if (!path || !*path) return bad_call("IDStorageFactoryX::OpenFile", E_INVALIDARG, "null or empty path"); | ||
| 1025 | if (!iid_policy().accept_creating(riid, Kind::File, "IDStorageFactoryX::OpenFile")) return E_NOINTERFACE; | ||
| 1026 | const HANDLE h = create_file_w()(path, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, | ||
| 1027 | FILE_ATTRIBUTE_NORMAL, nullptr); | ||
| 1028 | if (h == INVALID_HANDLE_VALUE) { | ||
| 1029 | const DWORD error = GetLastError(); | ||
| 1030 | return HRESULT_FROM_WIN32(error ? error : ERROR_FILE_NOT_FOUND); | ||
| 1031 | } | ||
| 1032 | File* f = new (std::nothrow) File(h, path); | ||
| 1033 | if (!f) { | ||
| 1034 | CloseHandle(h); | ||
| 1035 | return E_OUTOFMEMORY; | ||
| 1036 | } | ||
| 1037 | *ppv = static_cast<IDStorageFileX*>(f); | ||
| 1038 | return S_OK; | ||
| 1039 | } | ||
| 1040 | |||
| 1041 | HRESULT STDMETHODCALLTYPE CreateStatusArray(UINT32 capacity, PCSTR, REFIID riid, void** ppv) override { | ||
| 1042 | if (!ppv) return bad_call("IDStorageFactoryX::CreateStatusArray", E_POINTER, "null ppv"); | ||
| 1043 | *ppv = nullptr; | ||
| 1044 | if (capacity == 0) return bad_call("IDStorageFactoryX::CreateStatusArray", E_INVALIDARG, "capacity 0"); | ||
| 1045 | if (!iid_policy().accept_creating(riid, Kind::StatusArray, "IDStorageFactoryX::CreateStatusArray")) | ||
| 1046 | return E_NOINTERFACE; | ||
| 1047 | std::unique_ptr<std::atomic<HRESULT>[]> entries(new (std::nothrow) std::atomic<HRESULT>[capacity]); | ||
| 1048 | if (!entries) return E_OUTOFMEMORY; | ||
| 1049 | auto* a = new (std::nothrow) StatusArray(capacity, std::move(entries)); | ||
| 1050 | if (!a) return E_OUTOFMEMORY; | ||
| 1051 | *ppv = static_cast<IDStorageStatusArrayX*>(a); | ||
| 1052 | return S_OK; | ||
| 1053 | } | ||
| 1054 | |||
| 1055 | // DirectStorage's own worker work would be pinned to these cores on the console. The mask names console cores, | ||
| 1056 | // so it is stored and not applied to the host's. | ||
| 1057 | HRESULT STDMETHODCALLTYPE SetCpuAffinity(UINT64 affinity) override { | ||
| 1058 | cpu_affinity_.store(affinity); | ||
| 1059 | return S_OK; | ||
| 1060 | } | ||
| 1061 | void STDMETHODCALLTYPE SetDebugFlags(UINT32 flags) override { debug_flags_.store(flags); } | ||
| 1062 | |||
| 1063 | HRESULT STDMETHODCALLTYPE SetStagingBufferSize(UINT32 size) override { | ||
| 1064 | if (std::find(std::begin(kStagingBufferSizes), std::end(kStagingBufferSizes), size) == | ||
| 1065 | std::end(kStagingBufferSizes)) | ||
| 1066 | return bad_call("IDStorageFactoryX::SetStagingBufferSize", E_DSTORAGE_INVALID_STAGING_BUFFER_SIZE, | ||
| 1067 | "not one of 0, 16, 20, 24, 28 or 32 MiB"); | ||
| 1068 | std::lock_guard lock(stats().mutex); | ||
| 1069 | if (stats().live_queues || stats().s.CurrentOpenFileCount) return E_DSTORAGE_STAGING_BUFFER_LOCKED; | ||
| 1070 | staging_size_ = size; // there is no staging buffer here; the size is only kept | ||
| 1071 | return S_OK; | ||
| 1072 | } | ||
| 1073 | |||
| 1074 | void STDMETHODCALLTYPE GetStats(DSTORAGE_STATS* out) override { | ||
| 1075 | if (!out) { | ||
| 1076 | bad_call("IDStorageFactoryX1::GetStats", E_POINTER, "null stats"); | ||
| 1077 | return; | ||
| 1078 | } | ||
| 1079 | std::lock_guard lock(stats().mutex); | ||
| 1080 | *out = stats().s; | ||
| 1081 | } | ||
| 1082 | |||
| 1083 | private: | ||
| 1084 | HRESULT create_queue(const DSTORAGE_QUEUE_DESC1& desc, REFIID riid, void** ppv, const char* caller) { | ||
| 1085 | if (const HRESULT hr = validate_queue_desc(desc); FAILED(hr)) return bad_call(caller, hr, "invalid queue desc"); | ||
| 1086 | if (!iid_policy().accept_creating(riid, Kind::Queue, caller)) return E_NOINTERFACE; | ||
| 1087 | auto* q = new (std::nothrow) Queue(desc); | ||
| 1088 | if (!q) return E_OUTOFMEMORY; | ||
| 1089 | if (!q->start()) { | ||
| 1090 | q->Release(); | ||
| 1091 | return E_OUTOFMEMORY; | ||
| 1092 | } | ||
| 1093 | *ppv = static_cast<IDStorageQueueX2*>(q); | ||
| 1094 | return S_OK; | ||
| 1095 | } | ||
| 1096 | |||
| 1097 | std::atomic<ULONG> refs_{1}; | ||
| 1098 | std::atomic<uint64_t> cpu_affinity_{~0ull}; | ||
| 1099 | std::atomic<uint32_t> debug_flags_{0}; | ||
| 1100 | uint32_t staging_size_ = 32u << 20; // under stats().mutex | ||
| 1101 | }; | ||
| 1102 | |||
| 1103 | Factory& factory() { | ||
| 1104 | static auto* f = new Factory; | ||
| 1105 | return *f; | ||
| 1106 | } | ||
| 1107 | |||
| 1108 | HRESULT WINAPI dstorage_get_factory(REFIID riid, void** ppv) { | ||
| 1109 | if (!ppv) return bad_call("DStorageGetFactory", E_POINTER, "null ppv"); | ||
| 1110 | *ppv = nullptr; | ||
| 1111 | if (!iid_policy().accept_creating(riid, Kind::Factory, "DStorageGetFactory")) return E_NOINTERFACE; | ||
| 1112 | Factory& f = factory(); | ||
| 1113 | f.AddRef(); | ||
| 1114 | *ppv = static_cast<IDStorageFactoryX2*>(&f); | ||
| 1115 | return S_OK; | ||
| 1116 | } | ||
| 1117 | |||
| 1118 | } // namespace | ||
| 1119 | |||
| 1120 | // The console module names; docs/directstorage.md has the evidence and the confidence for each. | ||
| 1121 | SHIM_TABLE(dstorage, | ||
| 1122 | {"dstorage_xs.dll", "DStorageGetFactory", reinterpret_cast<void*>(&dstorage_get_factory)}, | ||
| 1123 | {"xcrdapi.dll", "DStorageGetFactory", reinterpret_cast<void*>(&dstorage_get_factory)}, | ||
| 1124 | {"dstorage.dll", "DStorageGetFactory", reinterpret_cast<void*>(&dstorage_get_factory)}, | ||
| 1125 | ); | ||
diff --git a/runtime/shims/dstorage_xs_abi.h b/runtime/shims/dstorage_xs_abi.h new file mode 100644 index 000000000..aec6ac59d --- /dev/null +++ b/runtime/shims/dstorage_xs_abi.h | |||
| @@ -0,0 +1,387 @@ | |||
| 1 | // Xbox DirectStorage ABI: the console API (dstorage_xs.h on the console) a title calls through DStorageGetFactory. | ||
| 2 | // | ||
| 3 | // These are Leonida's own declarations. Names, member order and types follow the public GDK reference | ||
| 4 | // (learn.microsoft.com/gaming/gdk/docs/reference/system/dstorage); docs/directstorage.md has the evidence for which | ||
| 5 | // DLL serves it and how sure each part is. No Microsoft header is copied. | ||
| 6 | // | ||
| 7 | // VERIFY (docs/directstorage.md "What is not public"): | ||
| 8 | // - Vtable order. The reference lists methods alphabetically; the order below is the PC dstorage.h order for the | ||
| 9 | // methods both APIs share, with the console-only ones (SetCpuAffinity, GetStats, CreateQueue1, GetHandle, | ||
| 10 | // Query1) where the GDK overview lists them. Reorder a declaration here and every object follows. | ||
| 11 | // - Interface ids. The X interfaces' ids are not public. The one declared id is the PC IDStorageStatusArray's, whose | ||
| 12 | // interface has the same shape (console D3D12 binaries reuse PC SDK ids); dstorage.cpp's creating calls learn and | ||
| 13 | // log the others. The other PC ids are declared only so they can be refused. | ||
| 14 | // - The capacity bounds, DSTORAGE_REQUEST_MAX_NAME and the E_DSTORAGE_* values are the PC header's. | ||
| 15 | #pragma once | ||
| 16 | #include <windows.h> | ||
| 17 | #include <unknwn.h> | ||
| 18 | |||
| 19 | #include <cstddef> | ||
| 20 | #include <cstdint> | ||
| 21 | |||
| 22 | struct ID3D12Fence; // d3d12.h; the shim calls Signal through it | ||
| 23 | |||
| 24 | namespace dsx { | ||
| 25 | |||
| 26 | #pragma warning(push) | ||
| 27 | #pragma warning(disable : 4201) // nameless struct/union: the reference declares the members that way | ||
| 28 | |||
| 29 | // ---- Constants and enumerations ----------------------------------------------------------------------------------- | ||
| 30 | |||
| 31 | constexpr uint16_t kMinQueueCapacity = 0x80; // DSTORAGE_MIN_QUEUE_CAPACITY (PC value) | ||
| 32 | constexpr uint16_t kMaxQueueCapacity = 0x2000; // DSTORAGE_MAX_QUEUE_CAPACITY (PC value) | ||
| 33 | constexpr size_t kRequestMaxName = 64; // DSTORAGE_REQUEST_MAX_NAME (PC value) | ||
| 34 | constexpr uint64_t kMaxRequestBytes = 1ull << 30; // DSTORAGE_MAX_REQUEST_SIZE: source + destination | ||
| 35 | constexpr uint32_t kMax4kPageDestinationSize = 32u << 20; // DSTORAGE_MAX_4K_PAGE_DESTINATION_SIZE | ||
| 36 | |||
| 37 | enum DSTORAGE_PRIORITY : int8_t { | ||
| 38 | DSTORAGE_PRIORITY_LOW = -1, | ||
| 39 | DSTORAGE_PRIORITY_NORMAL = 0, | ||
| 40 | DSTORAGE_PRIORITY_HIGH = 1, | ||
| 41 | DSTORAGE_PRIORITY_REALTIME = 2, | ||
| 42 | DSTORAGE_PRIORITY_FIRST = DSTORAGE_PRIORITY_LOW, | ||
| 43 | DSTORAGE_PRIORITY_LAST = DSTORAGE_PRIORITY_REALTIME, | ||
| 44 | DSTORAGE_PRIORITY_COUNT = 4, | ||
| 45 | }; | ||
| 46 | |||
| 47 | enum DSTORAGE_REQUEST_SOURCE_TYPE : uint64_t { | ||
| 48 | DSTORAGE_REQUEST_SOURCE_FILE = 0, | ||
| 49 | DSTORAGE_REQUEST_SOURCE_MEMORY = 1, | ||
| 50 | }; | ||
| 51 | |||
| 52 | enum DSTORAGE_BCPACK_MODE : uint64_t { | ||
| 53 | DSTORAGE_BCPACK_MODE_NONE = 0, | ||
| 54 | DSTORAGE_BCPACK_MODE_BC1 = 1, | ||
| 55 | DSTORAGE_BCPACK_MODE_BC2 = 2, | ||
| 56 | DSTORAGE_BCPACK_MODE_BC3 = 3, | ||
| 57 | DSTORAGE_BCPACK_MODE_BC4 = 4, | ||
| 58 | DSTORAGE_BCPACK_MODE_BC5 = 5, | ||
| 59 | DSTORAGE_BCPACK_MODE_BC6H = 6, | ||
| 60 | DSTORAGE_BCPACK_MODE_BC7 = 7, | ||
| 61 | }; | ||
| 62 | |||
| 63 | enum DSTORAGE_SWIZZLE_MODE : uint64_t { | ||
| 64 | DSTORAGE_SWIZZLE_MODE_NONE = 0, | ||
| 65 | DSTORAGE_SWIZZLE_MODE_4K_4K_8K = 1, | ||
| 66 | DSTORAGE_SWIZZLE_MODE_4K_4K_24K = 2, | ||
| 67 | DSTORAGE_SWIZZLE_MODE_4K_12K_4K_4K_8K = 3, | ||
| 68 | DSTORAGE_SWIZZLE_MODE_4K_12K_4K_12K = 4, | ||
| 69 | }; | ||
| 70 | |||
| 71 | enum DSTORAGE_COMMAND_TYPE : int32_t { | ||
| 72 | DSTORAGE_COMMAND_TYPE_NONE = -1, | ||
| 73 | DSTORAGE_COMMAND_TYPE_REQUEST = 0, | ||
| 74 | DSTORAGE_COMMAND_TYPE_STATUS = 1, | ||
| 75 | DSTORAGE_COMMAND_TYPE_SIGNAL = 2, | ||
| 76 | }; | ||
| 77 | // Not in the console enum: the PC API's DSTORAGE_COMMAND_TYPE_EVENT, used here for a failed EnqueueSetEvent. | ||
| 78 | constexpr DSTORAGE_COMMAND_TYPE kCommandTypeEvent = static_cast<DSTORAGE_COMMAND_TYPE>(3); | ||
| 79 | |||
| 80 | enum DSTORAGE_DEBUG : uint32_t { | ||
| 81 | DSTORAGE_DEBUG_NONE = 0x00, | ||
| 82 | DSTORAGE_DEBUG_SHOW_ERRORS = 0x01, | ||
| 83 | DSTORAGE_DEBUG_BREAK_ON_ERROR = 0x02, | ||
| 84 | DSTORAGE_DEBUG_RECORD_OBJECT_NAMES = 0x04, | ||
| 85 | }; | ||
| 86 | |||
| 87 | // The staging-buffer sizes the GDK overview lists as valid (its enumeration page is not public). | ||
| 88 | constexpr uint32_t kStagingBufferSizes[] = {0, 16u << 20, 20u << 20, 24u << 20, 28u << 20, 32u << 20}; | ||
| 89 | |||
| 90 | // ---- Errors (FACILITY_GAME, the PC dstorageerr.h values) ---------------------------------------------------------- | ||
| 91 | |||
| 92 | constexpr HRESULT E_DSTORAGE_INVALID_QUEUE_CAPACITY = static_cast<HRESULT>(0x89240003L); | ||
| 93 | constexpr HRESULT E_DSTORAGE_END_OF_FILE = static_cast<HRESULT>(0x89240007L); | ||
| 94 | constexpr HRESULT E_DSTORAGE_REQUEST_TOO_LARGE = static_cast<HRESULT>(0x89240008L); | ||
| 95 | constexpr HRESULT E_DSTORAGE_ACCESS_VIOLATION = static_cast<HRESULT>(0x89240009L); | ||
| 96 | constexpr HRESULT E_DSTORAGE_FILE_NOT_OPEN = static_cast<HRESULT>(0x8924000BL); | ||
| 97 | constexpr HRESULT E_DSTORAGE_RESERVED_FIELDS = static_cast<HRESULT>(0x8924000CL); | ||
| 98 | constexpr HRESULT E_DSTORAGE_INVALID_BCPACK_MODE = static_cast<HRESULT>(0x8924000DL); | ||
| 99 | constexpr HRESULT E_DSTORAGE_INVALID_SWIZZLE_MODE = static_cast<HRESULT>(0x8924000EL); | ||
| 100 | constexpr HRESULT E_DSTORAGE_INVALID_DESTINATION_SIZE = static_cast<HRESULT>(0x8924000FL); | ||
| 101 | constexpr HRESULT E_DSTORAGE_QUEUE_CLOSED = static_cast<HRESULT>(0x89240010L); | ||
| 102 | constexpr HRESULT E_DSTORAGE_INVALID_QUEUE_PRIORITY = static_cast<HRESULT>(0x89240013L); | ||
| 103 | constexpr HRESULT E_DSTORAGE_INDEX_BOUND = static_cast<HRESULT>(0x89240015L); | ||
| 104 | constexpr HRESULT E_DSTORAGE_INVALID_FILE_HANDLE = static_cast<HRESULT>(0x89240017L); | ||
| 105 | constexpr HRESULT E_DSTORAGE_INVALID_FILE_OFFSET = static_cast<HRESULT>(0x8924001AL); | ||
| 106 | constexpr HRESULT E_DSTORAGE_INVALID_SOURCE_TYPE = static_cast<HRESULT>(0x8924001BL); | ||
| 107 | constexpr HRESULT E_DSTORAGE_INVALID_INTERMEDIATE_SIZE = static_cast<HRESULT>(0x8924001CL); | ||
| 108 | constexpr HRESULT E_DSTORAGE_STAGING_BUFFER_LOCKED = static_cast<HRESULT>(0x8924001FL); | ||
| 109 | constexpr HRESULT E_DSTORAGE_INVALID_STAGING_BUFFER_SIZE = static_cast<HRESULT>(0x89240020L); | ||
| 110 | constexpr HRESULT E_DSTORAGE_INVALID_FENCE = static_cast<HRESULT>(0x89240022L); | ||
| 111 | constexpr HRESULT E_DSTORAGE_INVALID_STATUS_ARRAY = static_cast<HRESULT>(0x89240023L); | ||
| 112 | constexpr HRESULT E_DSTORAGE_INVALID_MEMORY_QUEUE_PRIORITY = static_cast<HRESULT>(0x89240024L); | ||
| 113 | // The decompression failures. E_DSTORAGE_DECOMPRESSION_ERROR ("a generic error has happened during decompression") | ||
| 114 | // is on the public DirectStorage constants page; the three zlib codes are in the same header (dstorageerr.h) with no | ||
| 115 | // public description: the names and values here are those of the header-generated bindings of the `direct-storage` | ||
| 116 | // crate (docs/directstorage.md "Sources"). PARITY_FAIL is read as the Adler-32 check, the only check value a zlib | ||
| 117 | // stream has. | ||
| 118 | constexpr HRESULT E_DSTORAGE_DECOMPRESSION_ERROR = static_cast<HRESULT>(0x89240030L); | ||
| 119 | constexpr HRESULT E_DSTORAGE_ZLIB_BAD_HEADER = static_cast<HRESULT>(0x89240031L); | ||
| 120 | constexpr HRESULT E_DSTORAGE_ZLIB_BAD_DATA = static_cast<HRESULT>(0x89240032L); | ||
| 121 | constexpr HRESULT E_DSTORAGE_ZLIB_PARITY_FAIL = static_cast<HRESULT>(0x89240033L); | ||
| 122 | |||
| 123 | // ---- Structures --------------------------------------------------------------------------------------------------- | ||
| 124 | |||
| 125 | // DSTORAGE_REQUEST_OPTIONS as the reference declares it. The shim reads AsUINT64 through the bit positions below | ||
| 126 | // (MSVC allocates bit-fields from bit 0 up); dstorage_test checks that the two agree. | ||
| 127 | union DSTORAGE_REQUEST_OPTIONS { | ||
| 128 | struct { | ||
| 129 | uint64_t ZlibDecompress : 1; | ||
| 130 | DSTORAGE_BCPACK_MODE BcpackMode : 4; | ||
| 131 | DSTORAGE_SWIZZLE_MODE SwizzleMode : 16; | ||
| 132 | uint64_t DestinationIsPhysicalPages : 1; | ||
| 133 | DSTORAGE_REQUEST_SOURCE_TYPE SourceType : 1; | ||
| 134 | uint64_t SourceIsPhysicalPages : 1; | ||
| 135 | uint64_t Reserved : 40; | ||
| 136 | }; | ||
| 137 | uint64_t AsUINT64; | ||
| 138 | }; | ||
| 139 | static_assert(sizeof(DSTORAGE_REQUEST_OPTIONS) == 8); | ||
| 140 | |||
| 141 | namespace options { | ||
| 142 | constexpr uint64_t kZlib = 1ull << 0; | ||
| 143 | constexpr unsigned kBcpackShift = 1; | ||
| 144 | constexpr uint64_t kBcpackMask = 0xFull << kBcpackShift; | ||
| 145 | constexpr unsigned kSwizzleShift = 5; | ||
| 146 | constexpr uint64_t kSwizzleMask = 0xFFFFull << kSwizzleShift; | ||
| 147 | constexpr uint64_t kDestinationPages = 1ull << 21; | ||
| 148 | constexpr uint64_t kSourceMemory = 1ull << 22; // SourceType == DSTORAGE_REQUEST_SOURCE_MEMORY | ||
| 149 | constexpr uint64_t kSourcePages = 1ull << 23; | ||
| 150 | constexpr uint64_t kReservedMask = ~((1ull << 24) - 1); | ||
| 151 | |||
| 152 | constexpr bool zlib(uint64_t o) { return (o & kZlib) != 0; } | ||
| 153 | constexpr uint64_t bcpack(uint64_t o) { return (o & kBcpackMask) >> kBcpackShift; } | ||
| 154 | constexpr uint64_t swizzle(uint64_t o) { return (o & kSwizzleMask) >> kSwizzleShift; } | ||
| 155 | constexpr DSTORAGE_REQUEST_SOURCE_TYPE source_type(uint64_t o) { | ||
| 156 | return (o & kSourceMemory) ? DSTORAGE_REQUEST_SOURCE_MEMORY : DSTORAGE_REQUEST_SOURCE_FILE; | ||
| 157 | } | ||
| 158 | } // namespace options | ||
| 159 | |||
| 160 | struct IDStorageFileX; | ||
| 161 | struct IDStorageStatusArrayX; | ||
| 162 | |||
| 163 | struct DSTORAGE_REQUEST { | ||
| 164 | DSTORAGE_REQUEST_OPTIONS Options; | ||
| 165 | union { | ||
| 166 | void* Destination; | ||
| 167 | struct { | ||
| 168 | PULONG_PTR DestinationPageArray; | ||
| 169 | UINT16 DestinationPageOffset; | ||
| 170 | }; | ||
| 171 | }; | ||
| 172 | UINT32 DestinationSize; | ||
| 173 | union { | ||
| 174 | struct { | ||
| 175 | IDStorageFileX* File; | ||
| 176 | UINT64 FileOffset; | ||
| 177 | }; | ||
| 178 | const void* Source; | ||
| 179 | struct { | ||
| 180 | PULONG_PTR SourcePageArray; | ||
| 181 | UINT16 SourcePageOffset; | ||
| 182 | }; | ||
| 183 | }; | ||
| 184 | UINT32 SourceSize; | ||
| 185 | UINT32 IntermediateSize; | ||
| 186 | UINT64 CancellationTag; | ||
| 187 | const CHAR* Name; | ||
| 188 | }; | ||
| 189 | static_assert(offsetof(DSTORAGE_REQUEST, Destination) == 8 && offsetof(DSTORAGE_REQUEST, DestinationPageOffset) == 16); | ||
| 190 | static_assert(offsetof(DSTORAGE_REQUEST, DestinationSize) == 24 && offsetof(DSTORAGE_REQUEST, File) == 32); | ||
| 191 | static_assert(offsetof(DSTORAGE_REQUEST, FileOffset) == 40 && offsetof(DSTORAGE_REQUEST, Source) == 32); | ||
| 192 | static_assert(offsetof(DSTORAGE_REQUEST, SourcePageOffset) == 40 && offsetof(DSTORAGE_REQUEST, SourceSize) == 48); | ||
| 193 | static_assert(offsetof(DSTORAGE_REQUEST, IntermediateSize) == 52 && offsetof(DSTORAGE_REQUEST, CancellationTag) == 56); | ||
| 194 | static_assert(offsetof(DSTORAGE_REQUEST, Name) == 64 && sizeof(DSTORAGE_REQUEST) == 72); | ||
| 195 | |||
| 196 | struct DSTORAGE_QUEUE_DESC { | ||
| 197 | DSTORAGE_REQUEST_SOURCE_TYPE SourceType; | ||
| 198 | UINT16 Capacity; | ||
| 199 | DSTORAGE_PRIORITY Priority; | ||
| 200 | const CHAR* Name; | ||
| 201 | }; | ||
| 202 | static_assert(offsetof(DSTORAGE_QUEUE_DESC, Capacity) == 8 && offsetof(DSTORAGE_QUEUE_DESC, Priority) == 10); | ||
| 203 | static_assert(offsetof(DSTORAGE_QUEUE_DESC, Name) == 16 && sizeof(DSTORAGE_QUEUE_DESC) == 24); | ||
| 204 | |||
| 205 | union DSTORAGE_QUEUE_OPTIONS { | ||
| 206 | struct { | ||
| 207 | uint64_t AutoSubmitDisabled : 1; | ||
| 208 | uint64_t Reserved : 63; | ||
| 209 | }; | ||
| 210 | uint64_t AsUINT64; | ||
| 211 | }; | ||
| 212 | static_assert(sizeof(DSTORAGE_QUEUE_OPTIONS) == 8); | ||
| 213 | |||
| 214 | struct DSTORAGE_QUEUE_DESC1 { | ||
| 215 | DSTORAGE_REQUEST_SOURCE_TYPE SourceType; | ||
| 216 | UINT16 Capacity; | ||
| 217 | DSTORAGE_PRIORITY Priority; | ||
| 218 | const CHAR* Name; | ||
| 219 | DSTORAGE_QUEUE_OPTIONS Options; | ||
| 220 | }; | ||
| 221 | static_assert(offsetof(DSTORAGE_QUEUE_DESC1, Options) == 24 && sizeof(DSTORAGE_QUEUE_DESC1) == 32); | ||
| 222 | |||
| 223 | struct DSTORAGE_QUEUE_INFO { | ||
| 224 | DSTORAGE_QUEUE_DESC Desc; | ||
| 225 | UINT16 EmptySlotCount; | ||
| 226 | UINT16 RequestCountUntilAutoSubmit; | ||
| 227 | }; | ||
| 228 | static_assert(offsetof(DSTORAGE_QUEUE_INFO, EmptySlotCount) == 24 && sizeof(DSTORAGE_QUEUE_INFO) == 32); | ||
| 229 | |||
| 230 | struct DSTORAGE_QUEUE_INFO1 { | ||
| 231 | DSTORAGE_QUEUE_DESC1 Desc; | ||
| 232 | UINT16 EmptySlotCount; | ||
| 233 | UINT16 RequestCountUntilAutoSubmit; | ||
| 234 | }; | ||
| 235 | static_assert(offsetof(DSTORAGE_QUEUE_INFO1, EmptySlotCount) == 32 && sizeof(DSTORAGE_QUEUE_INFO1) == 40); | ||
| 236 | |||
| 237 | // The reference declares the three failure kinds as unnamed structs inside DSTORAGE_ERROR_RECORD; they are named | ||
| 238 | // here (Leonida's names) so the shim can fill them. The layout is the same. | ||
| 239 | struct DSTORAGE_ERROR_REQUEST { | ||
| 240 | DSTORAGE_REQUEST_OPTIONS Options; | ||
| 241 | void* Destination; | ||
| 242 | UINT32 DestinationSize; | ||
| 243 | WCHAR Filename[MAX_PATH]; | ||
| 244 | UINT64 FileOffset; | ||
| 245 | const void* Source; | ||
| 246 | UINT32 SourceSize; | ||
| 247 | UINT64 CancellationTag; | ||
| 248 | CHAR Name[kRequestMaxName]; | ||
| 249 | }; | ||
| 250 | struct DSTORAGE_ERROR_STATUS { | ||
| 251 | IDStorageStatusArrayX* StatusArray; | ||
| 252 | UINT32 Index; | ||
| 253 | }; | ||
| 254 | struct DSTORAGE_ERROR_SIGNAL { | ||
| 255 | ID3D12Fence* Fence; | ||
| 256 | UINT64 Value; | ||
| 257 | }; | ||
| 258 | struct DSTORAGE_ERROR_FIRST_FAILURE { | ||
| 259 | HRESULT HResult; | ||
| 260 | DSTORAGE_COMMAND_TYPE CommandType; | ||
| 261 | union { | ||
| 262 | DSTORAGE_ERROR_REQUEST Request; | ||
| 263 | DSTORAGE_ERROR_STATUS Status; | ||
| 264 | DSTORAGE_ERROR_SIGNAL Signal; | ||
| 265 | }; | ||
| 266 | }; | ||
| 267 | struct DSTORAGE_ERROR_RECORD { | ||
| 268 | UINT32 FailureCount; | ||
| 269 | DSTORAGE_ERROR_FIRST_FAILURE FirstFailure; | ||
| 270 | }; | ||
| 271 | static_assert(offsetof(DSTORAGE_ERROR_RECORD, FirstFailure) == 8); | ||
| 272 | static_assert(offsetof(DSTORAGE_ERROR_FIRST_FAILURE, Request) == 8); | ||
| 273 | static_assert(offsetof(DSTORAGE_ERROR_REQUEST, Filename) == 20 && offsetof(DSTORAGE_ERROR_REQUEST, FileOffset) == 544); | ||
| 274 | static_assert(offsetof(DSTORAGE_ERROR_REQUEST, Name) == 576 && sizeof(DSTORAGE_ERROR_REQUEST) == 640); | ||
| 275 | static_assert(sizeof(DSTORAGE_ERROR_RECORD) == 656); | ||
| 276 | |||
| 277 | struct DSTORAGE_PRIORITY_STATS { | ||
| 278 | UINT32 CurrentQueueCount; | ||
| 279 | UINT32 MaxQueueCount; | ||
| 280 | UINT32 CumulativeQueueCount; | ||
| 281 | UINT32 TotalStatusCount; | ||
| 282 | UINT32 TotalFenceCount; | ||
| 283 | UINT32 PendingRequestCount; | ||
| 284 | UINT32 TotalRequestCount; | ||
| 285 | UINT64 TotalRequestSourceByteCount; | ||
| 286 | UINT64 TotalRequestDestinationByteCount; | ||
| 287 | }; | ||
| 288 | static_assert(sizeof(DSTORAGE_PRIORITY_STATS) == 48); | ||
| 289 | |||
| 290 | struct DSTORAGE_STATS { | ||
| 291 | DSTORAGE_PRIORITY_STATS LowPriorityStats; | ||
| 292 | DSTORAGE_PRIORITY_STATS NormalPriorityStats; | ||
| 293 | DSTORAGE_PRIORITY_STATS HighPriorityStats; | ||
| 294 | DSTORAGE_PRIORITY_STATS RealtimePriorityStats; | ||
| 295 | UINT8 CurrentOpenVirtualDiskCount; | ||
| 296 | UINT8 MaxOpenVirtualDiskCount; | ||
| 297 | UINT32 CumulativeOpenVirtualDiskCount; | ||
| 298 | UINT32 PendingStorageRequestCount; | ||
| 299 | UINT32 TotalStorageRequestCount; | ||
| 300 | UINT32 StorageRetries; | ||
| 301 | UINT32 StorageErrors; | ||
| 302 | UINT32 PendingDecompressionRequestCount; | ||
| 303 | UINT32 TotalDecompressionRequestCount; | ||
| 304 | UINT32 DecompressionErrors; | ||
| 305 | UINT32 StagingBufferStallCount; | ||
| 306 | UINT32 CurrentOpenFileCount; | ||
| 307 | UINT32 MaxOpenFileCount; | ||
| 308 | UINT32 CumulativeOpenFileCount; | ||
| 309 | UINT32 CurrentTitleMemoryUsageBytes; | ||
| 310 | UINT32 MaxTitleMemoryUsageBytes; | ||
| 311 | UINT32 ErrorCount; | ||
| 312 | }; | ||
| 313 | |||
| 314 | #pragma warning(pop) | ||
| 315 | |||
| 316 | // ---- Interfaces, in the vtable order chosen above --------------------------------------------------------------- | ||
| 317 | |||
| 318 | struct IDStorageStatusArrayX : IUnknown { | ||
| 319 | virtual bool STDMETHODCALLTYPE IsComplete(UINT32 index) = 0; | ||
| 320 | virtual HRESULT STDMETHODCALLTYPE GetHResult(UINT32 index) = 0; | ||
| 321 | }; | ||
| 322 | |||
| 323 | struct IDStorageFileX : IUnknown { | ||
| 324 | virtual void STDMETHODCALLTYPE Close() = 0; | ||
| 325 | virtual HANDLE STDMETHODCALLTYPE GetHandle() = 0; | ||
| 326 | }; | ||
| 327 | |||
| 328 | struct IDStorageQueueX : IUnknown { | ||
| 329 | virtual void STDMETHODCALLTYPE EnqueueRequest(const DSTORAGE_REQUEST* request) = 0; | ||
| 330 | virtual void STDMETHODCALLTYPE EnqueueStatus(IDStorageStatusArrayX* status_array, UINT32 index) = 0; | ||
| 331 | virtual void STDMETHODCALLTYPE EnqueueSignal(ID3D12Fence* fence, UINT64 value) = 0; | ||
| 332 | virtual void STDMETHODCALLTYPE Submit() = 0; | ||
| 333 | virtual void STDMETHODCALLTYPE CancelRequestsWithTag(UINT64 mask, UINT64 value) = 0; | ||
| 334 | virtual void STDMETHODCALLTYPE Close() = 0; | ||
| 335 | virtual HANDLE STDMETHODCALLTYPE GetErrorEvent() = 0; | ||
| 336 | virtual void STDMETHODCALLTYPE RetrieveErrorRecord(DSTORAGE_ERROR_RECORD* record) = 0; | ||
| 337 | virtual void STDMETHODCALLTYPE Query(DSTORAGE_QUEUE_INFO* info) = 0; | ||
| 338 | }; | ||
| 339 | |||
| 340 | struct IDStorageQueueX1 : IDStorageQueueX { | ||
| 341 | virtual void STDMETHODCALLTYPE EnqueueSetEvent(HANDLE handle) = 0; | ||
| 342 | }; | ||
| 343 | |||
| 344 | struct IDStorageQueueX2 : IDStorageQueueX1 { | ||
| 345 | virtual void STDMETHODCALLTYPE Query1(DSTORAGE_QUEUE_INFO1* info) = 0; | ||
| 346 | }; | ||
| 347 | |||
| 348 | struct IDStorageFactoryX : IUnknown { | ||
| 349 | virtual HRESULT STDMETHODCALLTYPE CreateQueue(const DSTORAGE_QUEUE_DESC* desc, REFIID riid, void** ppv) = 0; | ||
| 350 | virtual HRESULT STDMETHODCALLTYPE OpenFile(const WCHAR* path, REFIID riid, void** ppv) = 0; | ||
| 351 | virtual HRESULT STDMETHODCALLTYPE CreateStatusArray(UINT32 capacity, PCSTR name, REFIID riid, void** ppv) = 0; | ||
| 352 | virtual HRESULT STDMETHODCALLTYPE SetCpuAffinity(UINT64 affinity) = 0; | ||
| 353 | virtual void STDMETHODCALLTYPE SetDebugFlags(UINT32 flags) = 0; | ||
| 354 | virtual HRESULT STDMETHODCALLTYPE SetStagingBufferSize(UINT32 size) = 0; | ||
| 355 | }; | ||
| 356 | |||
| 357 | struct IDStorageFactoryX1 : IDStorageFactoryX { | ||
| 358 | virtual void STDMETHODCALLTYPE GetStats(DSTORAGE_STATS* stats) = 0; | ||
| 359 | }; | ||
| 360 | |||
| 361 | struct IDStorageFactoryX2 : IDStorageFactoryX1 { | ||
| 362 | virtual HRESULT STDMETHODCALLTYPE CreateQueue1(const DSTORAGE_QUEUE_DESC1* desc, REFIID riid, void** ppv) = 0; | ||
| 363 | }; | ||
| 364 | |||
| 365 | using DStorageGetFactoryFn = HRESULT(WINAPI*)(REFIID riid, void** ppv); | ||
| 366 | |||
| 367 | // ---- Interface ids ------------------------------------------------------------------------------------------------- | ||
| 368 | |||
| 369 | // Accepted for a status array: IDStorageStatusArray (PC dstorage.h 1.3.0), same methods in the same order. | ||
| 370 | constexpr GUID kStatusArrayIds[] = { | ||
| 371 | {0x82397587, 0x7cd5, 0x453b, {0xa0, 0x2e, 0x31, 0x37, 0x9b, 0xd6, 0x46, 0x56}}, | ||
| 372 | }; | ||
| 373 | |||
| 374 | // The other PC DirectStorage ids (dstorage.h 1.3.0), refused: their objects have another shape. | ||
| 375 | constexpr GUID kPcInterfaceIds[] = { | ||
| 376 | {0x6924ea0c, 0xc3cd, 0x4826, {0xb1, 0x0a, 0xf6, 0x4f, 0x4e, 0xd9, 0x27, 0xc1}}, // IDStorageFactory | ||
| 377 | {0x5de95e7b, 0x955a, 0x4868, {0xa7, 0x3c, 0x24, 0x3b, 0x29, 0xf4, 0xb8, 0xda}}, // IDStorageFile | ||
| 378 | {0xcfdbd83f, 0x9e06, 0x4fda, {0x8e, 0xa5, 0x69, 0x04, 0x21, 0x37, 0xf4, 0x9b}}, // IDStorageQueue | ||
| 379 | {0xdd2f482c, 0x5eff, 0x41e8, {0x9c, 0x9e, 0xd2, 0x37, 0x4b, 0x27, 0x81, 0x28}}, // IDStorageQueue1 | ||
| 380 | {0xb1c9d643, 0x3a49, 0x44a2, {0xb4, 0x6f, 0x65, 0x36, 0x49, 0x47, 0x0d, 0x18}}, // IDStorageQueue2 | ||
| 381 | {0xdeb54c52, 0xeca8, 0x46b3, {0x82, 0xa7, 0x03, 0x1b, 0x72, 0x26, 0x26, 0x53}}, // IDStorageQueue3 | ||
| 382 | {0x97179b2f, 0x2c21, 0x49ca, {0x82, 0x91, 0x4e, 0x1b, 0xf4, 0xa1, 0x60, 0xdf}}, // ...CustomDecompressionQueue | ||
| 383 | {0x0d47c6c9, 0xe61a, 0x4706, {0x93, 0xb4, 0x68, 0xbf, 0xe3, 0xf4, 0xaa, 0x4a}}, // ...CustomDecompressionQueue1 | ||
| 384 | {0x84ef5121, 0x9b43, 0x4d03, {0xb5, 0xc1, 0xcc, 0x34, 0x60, 0x6b, 0x26, 0x2d}}, // IDStorageCompressionCodec | ||
| 385 | }; | ||
| 386 | |||
| 387 | } // namespace dsx | ||
diff --git a/runtime/shims/registry.cpp b/runtime/shims/registry.cpp index 9b3ea0437..6ec36e31c 100644 --- a/runtime/shims/registry.cpp +++ b/runtime/shims/registry.cpp | |||
| @@ -80,7 +80,10 @@ std::vector<Lookup> g_lookups; | |||
| 80 | // xaudio2_9.dll XAudio2Create: HRESULT (learn.microsoft.com/windows/win32/api/xaudio2/ | 80 | // xaudio2_9.dll XAudio2Create: HRESULT (learn.microsoft.com/windows/win32/api/xaudio2/ |
| 81 | // xaudio2_9redist.dll nf-xaudio2-xaudio2create). xaudio2_9.dll is the console name (docs/d3d12_vulkan.md §7). | 81 | // xaudio2_9redist.dll nf-xaudio2-xaudio2create). xaudio2_9.dll is the console name (docs/d3d12_vulkan.md §7). |
| 82 | // dstorage.dll DStorageGetFactory: HRESULT (learn.microsoft.com/windows/win32/api/dstorage/ | 82 | // dstorage.dll DStorageGetFactory: HRESULT (learn.microsoft.com/windows/win32/api/dstorage/ |
| 83 | // dstorage_xs.dll nf-dstorage-dstoragegetfactory). dstorage_xs.dll is the console name. | 83 | // dstorage_xs.dll nf-dstorage-dstoragegetfactory, and the GDK's gaming/gdk/docs/reference/system/dstorage/ |
| 84 | // xcrdapi.dll functions/dstoragegetfactory). dstorage_xs.dll is the console name; xcrdapi.dll is a | ||
| 85 | // console module the title may import it from (docs/directstorage.md). dstorage.cpp serves | ||
| 86 | // it; the class is kept for a build without that shim. | ||
| 84 | const char* const kNotHResult[] = { | 87 | const char* const kNotHResult[] = { |
| 85 | "XAsyncCancel", "XAsyncComplete", | 88 | "XAsyncCancel", "XAsyncComplete", |
| 86 | "XTaskQueueCloseHandle", "XTaskQueueDispatch", "XTaskQueueGetCurrentProcessTaskQueue", | 89 | "XTaskQueueCloseHandle", "XTaskQueueDispatch", "XTaskQueueGetCurrentProcessTaskQueue", |
| @@ -111,7 +114,7 @@ ReturnClass classify(const std::string& dll, const std::string& name) { | |||
| 111 | if (name == "XAudio2Create") return ReturnClass::HResult; | 114 | if (name == "XAudio2Create") return ReturnClass::HResult; |
| 112 | } else if (dll == "gameinput.dll") { | 115 | } else if (dll == "gameinput.dll") { |
| 113 | if (name == "GameInputCreate") return ReturnClass::HResult; | 116 | if (name == "GameInputCreate") return ReturnClass::HResult; |
| 114 | } else if (dll == "dstorage.dll" || dll == "dstorage_xs.dll") { | 117 | } else if (dll == "dstorage.dll" || dll == "dstorage_xs.dll" || dll == "xcrdapi.dll") { |
| 115 | if (name == "DStorageGetFactory") return ReturnClass::HResult; | 118 | if (name == "DStorageGetFactory") return ReturnClass::HResult; |
| 116 | } else if (dll == "acphal.dll") { | 119 | } else if (dll == "acphal.dll") { |
| 117 | if (name == "AcpHalAllocateShapeContexts" || name == "AcpHalCreate" || | 120 | if (name == "AcpHalAllocateShapeContexts" || name == "AcpHalCreate" || |
diff --git a/runtime/src/shader_library.h b/runtime/src/shader_library.h index 2fe53d4ec..9f752317e 100644 --- a/runtime/src/shader_library.h +++ b/runtime/src/shader_library.h | |||
| @@ -33,6 +33,10 @@ namespace leonida { | |||
| 33 | // --------------------------------------------------------------------------------------------------------------- | 33 | // --------------------------------------------------------------------------------------------------------------- |
| 34 | // zlib inflate | 34 | // zlib inflate |
| 35 | 35 | ||
| 36 | // Why zlib_inflate failed, for a caller that reports the reason (runtime/shims/dstorage.cpp turns each into its | ||
| 37 | // E_DSTORAGE_ZLIB_* code). `limit`: the output would pass the caller's limit; the stream was not read to its end. | ||
| 38 | enum class ZlibError { none, header, data, checksum, limit }; | ||
| 39 | |||
| 36 | namespace detail { | 40 | namespace detail { |
| 37 | 41 | ||
| 38 | class BitReader { | 42 | class BitReader { |
| @@ -215,7 +219,7 @@ inline int decode(BitReader& in, const Huffman& h) { | |||
| 215 | return -1; | 219 | return -1; |
| 216 | } | 220 | } |
| 217 | 221 | ||
| 218 | inline bool inflate_codes(BitReader& in, std::vector<std::uint8_t>& out, const Huffman& lengths, | 222 | inline ZlibError inflate_codes(BitReader& in, std::vector<std::uint8_t>& out, const Huffman& lengths, |
| 219 | const Huffman& distances, std::size_t limit) { | 223 | const Huffman& distances, std::size_t limit) { |
| 220 | static constexpr std::int16_t length_base[29] = {3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, | 224 | static constexpr std::int16_t length_base[29] = {3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, |
| 221 | 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258}; | 225 | 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258}; |
| @@ -228,20 +232,21 @@ inline bool inflate_codes(BitReader& in, std::vector<std::uint8_t>& out, const H | |||
| 228 | 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13}; | 232 | 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13}; |
| 229 | for (;;) { | 233 | for (;;) { |
| 230 | int symbol = decode(in, lengths); | 234 | int symbol = decode(in, lengths); |
| 231 | if (symbol < 0 || in.failed()) return false; | 235 | if (symbol < 0 || in.failed()) return ZlibError::data; |
| 232 | if (symbol < 256) { | 236 | if (symbol < 256) { |
| 233 | if (out.size() >= limit) return false; | 237 | if (out.size() >= limit) return ZlibError::limit; |
| 234 | out.push_back(std::uint8_t(symbol)); | 238 | out.push_back(std::uint8_t(symbol)); |
| 235 | continue; | 239 | continue; |
| 236 | } | 240 | } |
| 237 | if (symbol == 256) return true; | 241 | if (symbol == 256) return ZlibError::none; |
| 238 | symbol -= 257; | 242 | symbol -= 257; |
| 239 | if (symbol >= 29) return false; | 243 | if (symbol >= 29) return ZlibError::data; |
| 240 | const std::size_t length = std::size_t(length_base[symbol]) + in.bits(length_extra[symbol]); | 244 | const std::size_t length = std::size_t(length_base[symbol]) + in.bits(length_extra[symbol]); |
| 241 | const int d = decode(in, distances); | 245 | const int d = decode(in, distances); |
| 242 | if (d < 0 || d >= 30) return false; | 246 | if (d < 0 || d >= 30) return ZlibError::data; |
| 243 | const std::size_t distance = std::size_t(distance_base[d]) + in.bits(distance_extra[d]); | 247 | const std::size_t distance = std::size_t(distance_base[d]) + in.bits(distance_extra[d]); |
| 244 | if (in.failed() || distance > out.size() || out.size() + length > limit) return false; | 248 | if (in.failed() || distance > out.size()) return ZlibError::data; |
| 249 | if (out.size() + length > limit) return ZlibError::limit; | ||
| 245 | const std::size_t from = out.size() - distance; | 250 | const std::size_t from = out.size() - distance; |
| 246 | for (std::size_t i = 0; i < length; ++i) out.push_back(out[from + i]); | 251 | for (std::size_t i = 0; i < length; ++i) out.push_back(out[from + i]); |
| 247 | } | 252 | } |
| @@ -250,28 +255,39 @@ inline bool inflate_codes(BitReader& in, std::vector<std::uint8_t>& out, const H | |||
| 250 | } // namespace detail | 255 | } // namespace detail |
| 251 | 256 | ||
| 252 | // Inflates a zlib stream (RFC 1950: header, deflate data, Adler-32). Returns false for a malformed stream, a | 257 | // Inflates a zlib stream (RFC 1950: header, deflate data, Adler-32). Returns false for a malformed stream, a |
| 253 | // preset dictionary, a checksum mismatch, or output beyond `limit` bytes. | 258 | // preset dictionary, a checksum mismatch, or output beyond `limit` bytes, and then stores the reason in `*why` when |
| 259 | // it is given: `header` for the two header bytes (not deflate, a window over 32 KiB, a bad check value, a preset | ||
| 260 | // dictionary), `data` for the deflate data or a missing trailer, `checksum` for an Adler-32 mismatch, `limit` for | ||
| 261 | // output beyond `limit`. Bytes after the Adler-32 trailer are not read. | ||
| 254 | inline bool zlib_inflate(std::span<const std::uint8_t> in, std::vector<std::uint8_t>& out, | 262 | inline bool zlib_inflate(std::span<const std::uint8_t> in, std::vector<std::uint8_t>& out, |
| 255 | std::size_t limit = std::size_t(1) << 30) { | 263 | std::size_t limit = std::size_t(1) << 30, ZlibError* why = nullptr) { |
| 256 | out.clear(); | 264 | out.clear(); |
| 257 | if (in.size() < 6) return false; | 265 | const auto fail = [why](ZlibError reason) { |
| 266 | if (why) *why = reason; | ||
| 267 | return false; | ||
| 268 | }; | ||
| 269 | if (why) *why = ZlibError::none; | ||
| 270 | if (in.size() < 2) return fail(ZlibError::header); | ||
| 258 | const unsigned cmf = in[0], flg = in[1]; | 271 | const unsigned cmf = in[0], flg = in[1]; |
| 259 | if ((cmf & 0x0f) != 8 || (cmf >> 4) > 7 || ((cmf << 8) | flg) % 31 != 0 || (flg & 0x20)) return false; | 272 | if ((cmf & 0x0f) != 8 || (cmf >> 4) > 7 || ((cmf << 8) | flg) % 31 != 0 || (flg & 0x20)) |
| 273 | return fail(ZlibError::header); | ||
| 274 | if (in.size() < 6) return fail(ZlibError::data); | ||
| 260 | detail::BitReader reader(in.subspan(2)); | 275 | detail::BitReader reader(in.subspan(2)); |
| 261 | for (bool last = false; !last;) { | 276 | for (bool last = false; !last;) { |
| 262 | last = reader.bits(1) != 0; | 277 | last = reader.bits(1) != 0; |
| 263 | const std::uint32_t type = reader.bits(2); | 278 | const std::uint32_t type = reader.bits(2); |
| 264 | if (reader.failed()) return false; | 279 | if (reader.failed()) return fail(ZlibError::data); |
| 265 | if (type == 0) { // stored | 280 | if (type == 0) { // stored |
| 266 | reader.align(); | 281 | reader.align(); |
| 267 | std::uint8_t b[4]; | 282 | std::uint8_t b[4]; |
| 268 | for (auto& x : b) | 283 | for (auto& x : b) |
| 269 | if (!reader.byte(x)) return false; | 284 | if (!reader.byte(x)) return fail(ZlibError::data); |
| 270 | const unsigned length = b[0] | (b[1] << 8), complement = b[2] | (b[3] << 8); | 285 | const unsigned length = b[0] | (b[1] << 8), complement = b[2] | (b[3] << 8); |
| 271 | if (length != (~complement & 0xffff) || out.size() + length > limit) return false; | 286 | if (length != (~complement & 0xffff)) return fail(ZlibError::data); |
| 287 | if (out.size() + length > limit) return fail(ZlibError::limit); | ||
| 272 | for (unsigned i = 0; i < length; ++i) { | 288 | for (unsigned i = 0; i < length; ++i) { |
| 273 | std::uint8_t x; | 289 | std::uint8_t x; |
| 274 | if (!reader.byte(x)) return false; | 290 | if (!reader.byte(x)) return fail(ZlibError::data); |
| 275 | out.push_back(x); | 291 | out.push_back(x); |
| 276 | } | 292 | } |
| 277 | } else if (type == 1) { // fixed Huffman | 293 | } else if (type == 1) { // fixed Huffman |
| @@ -287,19 +303,20 @@ inline bool zlib_inflate(std::span<const std::uint8_t> in, std::vector<std::uint | |||
| 287 | detail::build_huffman(t.second, lengths, 30); | 303 | detail::build_huffman(t.second, lengths, 30); |
| 288 | return t; | 304 | return t; |
| 289 | }(); | 305 | }(); |
| 290 | if (!detail::inflate_codes(reader, out, tables.first, tables.second, limit)) return false; | 306 | if (const ZlibError e = detail::inflate_codes(reader, out, tables.first, tables.second, limit); e != ZlibError::none) |
| 307 | return fail(e); | ||
| 291 | } else if (type == 2) { // dynamic Huffman | 308 | } else if (type == 2) { // dynamic Huffman |
| 292 | const int literal_count = int(reader.bits(5)) + 257, distance_count = int(reader.bits(5)) + 1; | 309 | const int literal_count = int(reader.bits(5)) + 257, distance_count = int(reader.bits(5)) + 1; |
| 293 | const int code_count = int(reader.bits(4)) + 4; | 310 | const int code_count = int(reader.bits(4)) + 4; |
| 294 | if (literal_count > 286 || distance_count > 30) return false; | 311 | if (literal_count > 286 || distance_count > 30) return fail(ZlibError::data); |
| 295 | static constexpr int order[19] = {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; | 312 | static constexpr int order[19] = {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; |
| 296 | std::int16_t lengths[320] = {}; | 313 | std::int16_t lengths[320] = {}; |
| 297 | for (int i = 0; i < code_count; ++i) lengths[order[i]] = std::int16_t(reader.bits(3)); | 314 | for (int i = 0; i < code_count; ++i) lengths[order[i]] = std::int16_t(reader.bits(3)); |
| 298 | detail::Huffman code_lengths; | 315 | detail::Huffman code_lengths; |
| 299 | if (!detail::build_huffman(code_lengths, lengths, 19)) return false; | 316 | if (!detail::build_huffman(code_lengths, lengths, 19)) return fail(ZlibError::data); |
| 300 | for (int i = 0; i < literal_count + distance_count;) { | 317 | for (int i = 0; i < literal_count + distance_count;) { |
| 301 | const int symbol = detail::decode(reader, code_lengths); | 318 | const int symbol = detail::decode(reader, code_lengths); |
| 302 | if (symbol < 0) return false; | 319 | if (symbol < 0) return fail(ZlibError::data); |
| 303 | if (symbol < 16) { | 320 | if (symbol < 16) { |
| 304 | lengths[i++] = std::int16_t(symbol); | 321 | lengths[i++] = std::int16_t(symbol); |
| 305 | continue; | 322 | continue; |
| @@ -307,7 +324,7 @@ inline bool zlib_inflate(std::span<const std::uint8_t> in, std::vector<std::uint | |||
| 307 | std::int16_t value = 0; | 324 | std::int16_t value = 0; |
| 308 | int repeat; | 325 | int repeat; |
| 309 | if (symbol == 16) { | 326 | if (symbol == 16) { |
| 310 | if (i == 0) return false; | 327 | if (i == 0) return fail(ZlibError::data); |
| 311 | value = lengths[i - 1]; | 328 | value = lengths[i - 1]; |
| 312 | repeat = 3 + int(reader.bits(2)); | 329 | repeat = 3 + int(reader.bits(2)); |
| 313 | } else if (symbol == 17) { | 330 | } else if (symbol == 17) { |
| @@ -315,23 +332,24 @@ inline bool zlib_inflate(std::span<const std::uint8_t> in, std::vector<std::uint | |||
| 315 | } else { | 332 | } else { |
| 316 | repeat = 11 + int(reader.bits(7)); | 333 | repeat = 11 + int(reader.bits(7)); |
| 317 | } | 334 | } |
| 318 | if (i + repeat > literal_count + distance_count) return false; | 335 | if (i + repeat > literal_count + distance_count) return fail(ZlibError::data); |
| 319 | while (repeat--) lengths[i++] = value; | 336 | while (repeat--) lengths[i++] = value; |
| 320 | } | 337 | } |
| 321 | if (lengths[256] == 0) return false; // no end-of-block code | 338 | if (lengths[256] == 0) return fail(ZlibError::data); // no end-of-block code |
| 322 | detail::Huffman literal, distance; | 339 | detail::Huffman literal, distance; |
| 323 | if (!detail::build_huffman(literal, lengths, literal_count) || | 340 | if (!detail::build_huffman(literal, lengths, literal_count) || |
| 324 | !detail::build_huffman(distance, lengths + literal_count, distance_count)) | 341 | !detail::build_huffman(distance, lengths + literal_count, distance_count)) |
| 325 | return false; | 342 | return fail(ZlibError::data); |
| 326 | if (!detail::inflate_codes(reader, out, literal, distance, limit)) return false; | 343 | if (const ZlibError e = detail::inflate_codes(reader, out, literal, distance, limit); e != ZlibError::none) |
| 344 | return fail(e); | ||
| 327 | } else { | 345 | } else { |
| 328 | return false; | 346 | return fail(ZlibError::data); |
| 329 | } | 347 | } |
| 330 | if (reader.failed()) return false; | 348 | if (reader.failed()) return fail(ZlibError::data); |
| 331 | } | 349 | } |
| 332 | // Adler-32, big-endian, after the deflate data's last whole byte. | 350 | // Adler-32, big-endian, after the deflate data's last whole byte. |
| 333 | const std::size_t at = 2 + reader.position(); | 351 | const std::size_t at = 2 + reader.position(); |
| 334 | if (at + 4 > in.size()) return false; | 352 | if (at + 4 > in.size()) return fail(ZlibError::data); |
| 335 | std::uint32_t a = 1, b = 0; | 353 | std::uint32_t a = 1, b = 0; |
| 336 | for (const std::uint8_t x : out) { | 354 | for (const std::uint8_t x : out) { |
| 337 | a = (a + x) % 65521; | 355 | a = (a + x) % 65521; |
| @@ -339,7 +357,7 @@ inline bool zlib_inflate(std::span<const std::uint8_t> in, std::vector<std::uint | |||
| 339 | } | 357 | } |
| 340 | const std::uint32_t expected = (std::uint32_t(in[at]) << 24) | (std::uint32_t(in[at + 1]) << 16) | | 358 | const std::uint32_t expected = (std::uint32_t(in[at]) << 24) | (std::uint32_t(in[at + 1]) << 16) | |
| 341 | (std::uint32_t(in[at + 2]) << 8) | in[at + 3]; | 359 | (std::uint32_t(in[at + 2]) << 8) | in[at + 3]; |
| 342 | return ((b << 16) | a) == expected; | 360 | return ((b << 16) | a) == expected || fail(ZlibError::checksum); |
| 343 | } | 361 | } |
| 344 | 362 | ||
| 345 | // --------------------------------------------------------------------------------------------------------------- | 363 | // --------------------------------------------------------------------------------------------------------------- |
diff --git a/runtime/test/dstorage_test.cpp b/runtime/test/dstorage_test.cpp new file mode 100644 index 000000000..1e8ea7318 --- /dev/null +++ b/runtime/test/dstorage_test.cpp | |||
| @@ -0,0 +1,1260 @@ | |||
| 1 | // DirectStorage shim (runtime/shims/dstorage.cpp): DStorageGetFactory resolved through the shim registry under its | ||
| 2 | // three module names, driven the way a console title calls it, over synthetic files in %TEMP%. No game data, no GPU. | ||
| 3 | #include <windows.h> | ||
| 4 | #include <d3d12.h> | ||
| 5 | |||
| 6 | #include <algorithm> | ||
| 7 | #include <atomic> | ||
| 8 | #include <chrono> | ||
| 9 | #include <cstdio> | ||
| 10 | #include <cstdlib> | ||
| 11 | #include <cstring> | ||
| 12 | #include <filesystem> | ||
| 13 | #include <functional> | ||
| 14 | #include <string> | ||
| 15 | #include <thread> | ||
| 16 | #include <vector> | ||
| 17 | |||
| 18 | #include "dstorage_xs_abi.h" | ||
| 19 | #include "file_system.h" | ||
| 20 | #include "shims.h" | ||
| 21 | |||
| 22 | using namespace dsx; | ||
| 23 | namespace fs = std::filesystem; | ||
| 24 | |||
| 25 | namespace { | ||
| 26 | |||
| 27 | int g_checks = 0; | ||
| 28 | int g_failures = 0; | ||
| 29 | |||
| 30 | void check(bool ok, const char* what) { | ||
| 31 | ++g_checks; | ||
| 32 | if (!ok) { | ||
| 33 | ++g_failures; | ||
| 34 | std::printf("FAIL: %s\n", what); | ||
| 35 | } | ||
| 36 | } | ||
| 37 | |||
| 38 | void check_hr(HRESULT got, HRESULT want, const char* what) { | ||
| 39 | ++g_checks; | ||
| 40 | if (got != want) { | ||
| 41 | ++g_failures; | ||
| 42 | std::printf("FAIL: %s (got 0x%08lx, want 0x%08lx)\n", what, static_cast<unsigned long>(got), | ||
| 43 | static_cast<unsigned long>(want)); | ||
| 44 | } | ||
| 45 | } | ||
| 46 | |||
| 47 | // Interface ids a title might pass. The console's own ids are not public, so these are made up; the shim accepts any | ||
| 48 | // id per kind of object. | ||
| 49 | constexpr GUID kFactoryId = {0x0d5e0001, 0x1111, 0x4111, {0x81, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x01}}; | ||
| 50 | constexpr GUID kQueueId = {0x0d5e0002, 0x1111, 0x4111, {0x81, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x02}}; | ||
| 51 | constexpr GUID kFileId = {0x0d5e0003, 0x1111, 0x4111, {0x81, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x03}}; | ||
| 52 | constexpr GUID kStatusId = {0x0d5e0004, 0x1111, 0x4111, {0x81, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x04}}; | ||
| 53 | // IDStorageFactory of the PC API (dstorage.h): refused, its object has another shape. | ||
| 54 | constexpr GUID kPcFactoryId = {0x6924ea0c, 0xc3cd, 0x4826, {0xb1, 0x0a, 0xf6, 0x4f, 0x4e, 0xd9, 0x27, 0xc1}}; | ||
| 55 | |||
| 56 | // A CPU fence with the PC ID3D12Fence vtable (the one the d3d12_xs fence proxies forward). It records the values it is | ||
| 57 | // signalled with and runs a check at each signal. | ||
| 58 | class TestFence final : public ID3D12Fence { | ||
| 59 | public: | ||
| 60 | std::function<void(UINT64)> on_signal; | ||
| 61 | std::atomic<UINT64> value{0}; | ||
| 62 | std::atomic<ULONG> refs{1}; | ||
| 63 | |||
| 64 | HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override { | ||
| 65 | if (!ppv) return E_POINTER; | ||
| 66 | *ppv = nullptr; | ||
| 67 | if (riid != __uuidof(IUnknown) && riid != __uuidof(ID3D12Fence)) return E_NOINTERFACE; | ||
| 68 | AddRef(); | ||
| 69 | *ppv = this; | ||
| 70 | return S_OK; | ||
| 71 | } | ||
| 72 | ULONG STDMETHODCALLTYPE AddRef() override { return ++refs; } | ||
| 73 | ULONG STDMETHODCALLTYPE Release() override { return --refs; } // lives on the test's stack | ||
| 74 | HRESULT STDMETHODCALLTYPE GetPrivateData(REFGUID, UINT*, void*) override { return E_NOTIMPL; } | ||
| 75 | HRESULT STDMETHODCALLTYPE SetPrivateData(REFGUID, UINT, const void*) override { return E_NOTIMPL; } | ||
| 76 | HRESULT STDMETHODCALLTYPE SetPrivateDataInterface(REFGUID, const IUnknown*) override { return E_NOTIMPL; } | ||
| 77 | HRESULT STDMETHODCALLTYPE SetName(LPCWSTR) override { return S_OK; } | ||
| 78 | HRESULT STDMETHODCALLTYPE GetDevice(REFIID, void** ppv) override { | ||
| 79 | if (ppv) *ppv = nullptr; | ||
| 80 | return E_NOTIMPL; | ||
| 81 | } | ||
| 82 | UINT64 STDMETHODCALLTYPE GetCompletedValue() override { return value.load(); } | ||
| 83 | HRESULT STDMETHODCALLTYPE SetEventOnCompletion(UINT64, HANDLE) override { return E_NOTIMPL; } | ||
| 84 | HRESULT STDMETHODCALLTYPE Signal(UINT64 v) override { | ||
| 85 | if (on_signal) on_signal(v); | ||
| 86 | value.store(v); | ||
| 87 | return S_OK; | ||
| 88 | } | ||
| 89 | }; | ||
| 90 | |||
| 91 | std::vector<uint8_t> pattern(size_t n, uint32_t seed) { | ||
| 92 | std::vector<uint8_t> v(n); | ||
| 93 | uint32_t x = seed * 2654435761u + 1; | ||
| 94 | for (auto& b : v) { | ||
| 95 | x ^= x << 13; | ||
| 96 | x ^= x >> 17; | ||
| 97 | x ^= x << 5; | ||
| 98 | b = static_cast<uint8_t>(x); | ||
| 99 | } | ||
| 100 | return v; | ||
| 101 | } | ||
| 102 | |||
| 103 | void write_file(const fs::path& p, const std::vector<uint8_t>& bytes) { | ||
| 104 | fs::create_directories(p.parent_path()); | ||
| 105 | FILE* f = nullptr; | ||
| 106 | if (_wfopen_s(&f, p.c_str(), L"wb") != 0 || !f) { | ||
| 107 | std::printf("FAIL: cannot write %ls\n", p.c_str()); | ||
| 108 | std::exit(1); | ||
| 109 | } | ||
| 110 | if (!bytes.empty()) std::fwrite(bytes.data(), 1, bytes.size(), f); | ||
| 111 | std::fclose(f); | ||
| 112 | } | ||
| 113 | |||
| 114 | bool wait_complete(IDStorageStatusArrayX* s, UINT32 index, int ms = 10000) { | ||
| 115 | const auto end = std::chrono::steady_clock::now() + std::chrono::milliseconds(ms); | ||
| 116 | while (!s->IsComplete(index)) { | ||
| 117 | if (std::chrono::steady_clock::now() > end) return false; | ||
| 118 | Sleep(1); | ||
| 119 | } | ||
| 120 | return true; | ||
| 121 | } | ||
| 122 | |||
| 123 | bool wait_until(const std::function<bool()>& done, int ms = 10000) { | ||
| 124 | const auto end = std::chrono::steady_clock::now() + std::chrono::milliseconds(ms); | ||
| 125 | while (!done()) { | ||
| 126 | if (std::chrono::steady_clock::now() > end) return false; | ||
| 127 | Sleep(1); | ||
| 128 | } | ||
| 129 | return true; | ||
| 130 | } | ||
| 131 | |||
| 132 | DSTORAGE_REQUEST file_request(IDStorageFileX* f, uint64_t offset, void* dst, uint32_t n, uint64_t tag = 0, | ||
| 133 | const char* name = nullptr) { | ||
| 134 | DSTORAGE_REQUEST r{}; | ||
| 135 | r.File = f; | ||
| 136 | r.FileOffset = offset; | ||
| 137 | r.Destination = dst; | ||
| 138 | r.DestinationSize = n; | ||
| 139 | r.SourceSize = n; | ||
| 140 | r.CancellationTag = tag; | ||
| 141 | r.Name = name; | ||
| 142 | return r; | ||
| 143 | } | ||
| 144 | |||
| 145 | struct Env { | ||
| 146 | fs::path root, game, overlay; | ||
| 147 | IDStorageFactoryX2* factory = nullptr; | ||
| 148 | std::vector<uint8_t> a_package, a_overlay, b, big; | ||
| 149 | }; | ||
| 150 | |||
| 151 | IDStorageQueueX2* make_queue(Env& env, uint16_t capacity = 0x80, bool auto_submit = true, | ||
| 152 | DSTORAGE_REQUEST_SOURCE_TYPE type = DSTORAGE_REQUEST_SOURCE_FILE, | ||
| 153 | DSTORAGE_PRIORITY priority = DSTORAGE_PRIORITY_NORMAL, const char* name = "test queue") { | ||
| 154 | DSTORAGE_QUEUE_DESC1 d{}; | ||
| 155 | d.SourceType = type; | ||
| 156 | d.Capacity = capacity; | ||
| 157 | d.Priority = priority; | ||
| 158 | d.Name = name; | ||
| 159 | d.Options.AutoSubmitDisabled = auto_submit ? 0 : 1; | ||
| 160 | void* q = nullptr; | ||
| 161 | const HRESULT hr = env.factory->CreateQueue1(&d, kQueueId, &q); | ||
| 162 | check_hr(hr, S_OK, "CreateQueue1"); | ||
| 163 | return static_cast<IDStorageQueueX2*>(q); | ||
| 164 | } | ||
| 165 | |||
| 166 | IDStorageFileX* open(Env& env, const wchar_t* path) { | ||
| 167 | void* f = nullptr; | ||
| 168 | check_hr(env.factory->OpenFile(path, kFileId, &f), S_OK, "OpenFile"); | ||
| 169 | return static_cast<IDStorageFileX*>(f); | ||
| 170 | } | ||
| 171 | |||
| 172 | IDStorageStatusArrayX* make_status(Env& env, UINT32 capacity) { | ||
| 173 | void* s = nullptr; | ||
| 174 | check_hr(env.factory->CreateStatusArray(capacity, "test status", kStatusId, &s), S_OK, "CreateStatusArray"); | ||
| 175 | return static_cast<IDStorageStatusArrayX*>(s); | ||
| 176 | } | ||
| 177 | |||
| 178 | // ---- tests ---------------------------------------------------------------------------------------------------------- | ||
| 179 | |||
| 180 | void test_layout_and_options() { | ||
| 181 | DSTORAGE_REQUEST_OPTIONS o{}; | ||
| 182 | o.ZlibDecompress = 1; | ||
| 183 | check(o.AsUINT64 == options::kZlib, "ZlibDecompress is bit 0"); | ||
| 184 | o.AsUINT64 = 0; | ||
| 185 | o.BcpackMode = DSTORAGE_BCPACK_MODE_BC7; | ||
| 186 | check(options::bcpack(o.AsUINT64) == 7 && o.AsUINT64 == (7ull << options::kBcpackShift), "BcpackMode is bits 1-4"); | ||
| 187 | o.AsUINT64 = 0; | ||
| 188 | o.SwizzleMode = DSTORAGE_SWIZZLE_MODE_4K_12K_4K_12K; | ||
| 189 | check(options::swizzle(o.AsUINT64) == 4 && o.AsUINT64 == (4ull << options::kSwizzleShift), | ||
| 190 | "SwizzleMode is bits 5-20"); | ||
| 191 | o.AsUINT64 = 0; | ||
| 192 | o.DestinationIsPhysicalPages = 1; | ||
| 193 | check(o.AsUINT64 == options::kDestinationPages, "DestinationIsPhysicalPages is bit 21"); | ||
| 194 | o.AsUINT64 = 0; | ||
| 195 | o.SourceType = DSTORAGE_REQUEST_SOURCE_MEMORY; | ||
| 196 | check(o.AsUINT64 == options::kSourceMemory, "SourceType is bit 22"); | ||
| 197 | o.AsUINT64 = 0; | ||
| 198 | o.SourceIsPhysicalPages = 1; | ||
| 199 | check(o.AsUINT64 == options::kSourcePages, "SourceIsPhysicalPages is bit 23"); | ||
| 200 | o.AsUINT64 = 0; | ||
| 201 | o.Reserved = 1; | ||
| 202 | check(o.AsUINT64 == (1ull << 24) && (o.AsUINT64 & options::kReservedMask), "Reserved starts at bit 24"); | ||
| 203 | DSTORAGE_QUEUE_OPTIONS q{}; | ||
| 204 | q.AutoSubmitDisabled = 1; | ||
| 205 | check(q.AsUINT64 == 1, "AutoSubmitDisabled is bit 0"); | ||
| 206 | } | ||
| 207 | |||
| 208 | void test_registry(Env& env) { | ||
| 209 | const char* names[] = {"dstorage_xs.dll", "xcrdapi.dll", "dstorage.dll"}; | ||
| 210 | void* first = rt::shims::find("dstorage_xs.dll", "DStorageGetFactory"); | ||
| 211 | check(first != nullptr, "dstorage_xs.dll!DStorageGetFactory is registered"); | ||
| 212 | for (const char* n : names) { | ||
| 213 | check(rt::shims::find(n, "DStorageGetFactory") == first, "every module name serves the same function"); | ||
| 214 | check(rt::shims::owns_dll(n), "the shims own the module (LoadLibrary gets a pseudo-handle)"); | ||
| 215 | } | ||
| 216 | auto get = reinterpret_cast<DStorageGetFactoryFn>(first); | ||
| 217 | if (!get) std::exit(1); | ||
| 218 | |||
| 219 | check_hr(get(kFactoryId, nullptr), E_POINTER, "DStorageGetFactory without ppv"); | ||
| 220 | void* pc = reinterpret_cast<void*>(1); | ||
| 221 | check_hr(get(kPcFactoryId, &pc), E_NOINTERFACE, "the PC IDStorageFactory id is refused"); | ||
| 222 | check(pc == nullptr, "a refused factory clears ppv"); | ||
| 223 | |||
| 224 | void* f1 = nullptr; | ||
| 225 | void* f2 = nullptr; | ||
| 226 | check_hr(get(kFactoryId, &f1), S_OK, "DStorageGetFactory"); | ||
| 227 | check_hr(reinterpret_cast<DStorageGetFactoryFn>(rt::shims::find("xcrdapi.dll", "DStorageGetFactory"))( | ||
| 228 | __uuidof(IUnknown), &f2), | ||
| 229 | S_OK, "DStorageGetFactory(IUnknown) under xcrdapi.dll"); | ||
| 230 | check(f1 && f1 == f2, "the factory is one object"); | ||
| 231 | env.factory = static_cast<IDStorageFactoryX2*>(f1); | ||
| 232 | static_cast<IUnknown*>(f2)->Release(); | ||
| 233 | check(env.factory->Release() >= 1 && env.factory->Release() >= 1, "the factory's count does not drop below one"); | ||
| 234 | env.factory->AddRef(); | ||
| 235 | |||
| 236 | void* again = nullptr; | ||
| 237 | check_hr(env.factory->QueryInterface(kFactoryId, &again), S_OK, "factory QueryInterface for its own id"); | ||
| 238 | if (again) static_cast<IUnknown*>(again)->Release(); | ||
| 239 | } | ||
| 240 | |||
| 241 | void test_factory_checks(Env& env) { | ||
| 242 | // Before any queue or file exists. | ||
| 243 | check_hr(env.factory->SetStagingBufferSize(17u << 20), E_DSTORAGE_INVALID_STAGING_BUFFER_SIZE, "staging 17 MiB"); | ||
| 244 | check_hr(env.factory->SetStagingBufferSize(16u << 20), S_OK, "staging 16 MiB"); | ||
| 245 | check_hr(env.factory->SetStagingBufferSize(0), S_OK, "staging 0"); | ||
| 246 | check_hr(env.factory->SetCpuAffinity(0x3c), S_OK, "SetCpuAffinity"); | ||
| 247 | env.factory->SetDebugFlags(DSTORAGE_DEBUG_SHOW_ERRORS); | ||
| 248 | |||
| 249 | auto create = [&](DSTORAGE_REQUEST_SOURCE_TYPE type, uint16_t cap, int prio, uint64_t opts = 0) { | ||
| 250 | DSTORAGE_QUEUE_DESC1 d{}; | ||
| 251 | d.SourceType = type; | ||
| 252 | d.Capacity = cap; | ||
| 253 | d.Priority = static_cast<DSTORAGE_PRIORITY>(prio); | ||
| 254 | d.Options.AsUINT64 = opts; | ||
| 255 | void* q = reinterpret_cast<void*>(1); | ||
| 256 | const HRESULT hr = env.factory->CreateQueue1(&d, kQueueId, &q); | ||
| 257 | if (SUCCEEDED(hr)) static_cast<IUnknown*>(q)->Release(); | ||
| 258 | else check(q == nullptr, "a failed CreateQueue1 clears ppv"); | ||
| 259 | return hr; | ||
| 260 | }; | ||
| 261 | check_hr(create(DSTORAGE_REQUEST_SOURCE_FILE, 0x7f, 0), E_DSTORAGE_INVALID_QUEUE_CAPACITY, "capacity 0x7f"); | ||
| 262 | check_hr(create(DSTORAGE_REQUEST_SOURCE_FILE, 0x2001, 0), E_DSTORAGE_INVALID_QUEUE_CAPACITY, "capacity 0x2001"); | ||
| 263 | check_hr(create(DSTORAGE_REQUEST_SOURCE_FILE, 0x80, 3), E_DSTORAGE_INVALID_QUEUE_PRIORITY, "priority 3"); | ||
| 264 | check_hr(create(DSTORAGE_REQUEST_SOURCE_FILE, 0x80, -2), E_DSTORAGE_INVALID_QUEUE_PRIORITY, "priority -2"); | ||
| 265 | check_hr(create(DSTORAGE_REQUEST_SOURCE_MEMORY, 0x80, 0), E_DSTORAGE_INVALID_MEMORY_QUEUE_PRIORITY, | ||
| 266 | "a memory queue must be realtime"); | ||
| 267 | check_hr(create(static_cast<DSTORAGE_REQUEST_SOURCE_TYPE>(2), 0x80, 0), E_DSTORAGE_INVALID_SOURCE_TYPE, | ||
| 268 | "source type 2"); | ||
| 269 | check_hr(create(DSTORAGE_REQUEST_SOURCE_FILE, 0x80, 0, 2), E_DSTORAGE_RESERVED_FIELDS, "queue option bit 1"); | ||
| 270 | check_hr(create(DSTORAGE_REQUEST_SOURCE_FILE, 0x2000, -1), S_OK, "capacity 0x2000, low priority"); | ||
| 271 | check_hr(create(DSTORAGE_REQUEST_SOURCE_MEMORY, 0x80, 2), S_OK, "a realtime memory queue"); | ||
| 272 | check_hr(env.factory->CreateQueue1(nullptr, kQueueId, nullptr), E_POINTER, "CreateQueue1 without ppv"); | ||
| 273 | void* q = nullptr; | ||
| 274 | check_hr(env.factory->CreateQueue(nullptr, kQueueId, &q), E_INVALIDARG, "CreateQueue without a desc"); | ||
| 275 | check_hr(env.factory->CreateQueue1(nullptr, kQueueId, &q), E_INVALIDARG, "CreateQueue1 without a desc"); | ||
| 276 | void* s = nullptr; | ||
| 277 | check_hr(env.factory->CreateStatusArray(0, nullptr, kStatusId, &s), E_INVALIDARG, "a status array of 0"); | ||
| 278 | |||
| 279 | // The id policy: an id seen for a queue is not a factory id. | ||
| 280 | void* wrong = nullptr; | ||
| 281 | check_hr(env.factory->QueryInterface(kQueueId, &wrong), E_NOINTERFACE, "a queue id is not a factory id"); | ||
| 282 | check_hr(env.factory->CreateStatusArray(4, nullptr, kFactoryId, &s), E_NOINTERFACE, | ||
| 283 | "a factory id is not a status array id"); | ||
| 284 | |||
| 285 | // CreateQueue (DSTORAGE_QUEUE_DESC) and Query reflect the desc. | ||
| 286 | DSTORAGE_QUEUE_DESC d{}; | ||
| 287 | d.SourceType = DSTORAGE_REQUEST_SOURCE_FILE; | ||
| 288 | d.Capacity = 0x100; | ||
| 289 | d.Priority = DSTORAGE_PRIORITY_HIGH; | ||
| 290 | d.Name = "named"; | ||
| 291 | check_hr(env.factory->CreateQueue(&d, kQueueId, &q), S_OK, "CreateQueue"); | ||
| 292 | auto* queue = static_cast<IDStorageQueueX2*>(q); | ||
| 293 | DSTORAGE_QUEUE_INFO info{}; | ||
| 294 | queue->Query(&info); | ||
| 295 | check(info.Desc.Capacity == 0x100 && info.Desc.Priority == DSTORAGE_PRIORITY_HIGH && info.Desc.Name == d.Name && | ||
| 296 | info.Desc.SourceType == DSTORAGE_REQUEST_SOURCE_FILE, | ||
| 297 | "Query returns the creation desc"); | ||
| 298 | check(info.EmptySlotCount == 0xff, "an empty queue has capacity - 1 empty slots"); | ||
| 299 | check(info.RequestCountUntilAutoSubmit == 0x80, "auto-submit at half the capacity"); | ||
| 300 | DSTORAGE_QUEUE_INFO1 info1{}; | ||
| 301 | queue->Query1(&info1); | ||
| 302 | check(info1.Desc.Options.AsUINT64 == 0 && info1.EmptySlotCount == 0xff, "Query1"); | ||
| 303 | check_hr(env.factory->SetStagingBufferSize(32u << 20), E_DSTORAGE_STAGING_BUFFER_LOCKED, | ||
| 304 | "staging size is locked while a queue exists"); | ||
| 305 | void* qi = nullptr; | ||
| 306 | check_hr(queue->QueryInterface(kQueueId, &qi), S_OK, "queue QueryInterface"); | ||
| 307 | if (qi) static_cast<IUnknown*>(qi)->Release(); | ||
| 308 | check(queue->Release() == 0, "the last queue reference frees it"); | ||
| 309 | check_hr(env.factory->SetStagingBufferSize(32u << 20), S_OK, "staging size unlocked again"); | ||
| 310 | } | ||
| 311 | |||
| 312 | void test_open_paths(Env& env) { | ||
| 313 | void* f = reinterpret_cast<void*>(1); | ||
| 314 | check_hr(env.factory->OpenFile(L"GAME:\\data\\missing.bin", kFileId, &f), HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND), | ||
| 315 | "a missing GAME: file"); | ||
| 316 | check(f == nullptr, "a failed OpenFile clears ppv"); | ||
| 317 | check_hr(env.factory->OpenFile(L"GAME:\\..\\outside.bin", kFileId, &f), HRESULT_FROM_WIN32(ERROR_INVALID_NAME), | ||
| 318 | "a GAME: path that climbs out is refused"); | ||
| 319 | check_hr(env.factory->OpenFile(nullptr, kFileId, &f), E_INVALIDARG, "OpenFile without a path"); | ||
| 320 | check_hr(env.factory->OpenFile(L"GAME:\\data\\a.bin", kFileId, nullptr), E_POINTER, "OpenFile without ppv"); | ||
| 321 | |||
| 322 | // The overlay copy wins over the package; a host path is passed through. | ||
| 323 | IDStorageFileX* a = open(env, L"GAME:\\data\\a.bin"); | ||
| 324 | IDStorageFileX* b = open(env, L"game:/data/b.bin"); | ||
| 325 | const std::wstring host = (env.game / L"data" / L"b.bin").wstring(); | ||
| 326 | IDStorageFileX* h = open(env, host.c_str()); | ||
| 327 | if (!a || !b || !h) std::exit(1); | ||
| 328 | |||
| 329 | IDStorageQueueX2* q = make_queue(env); | ||
| 330 | IDStorageStatusArrayX* s = make_status(env, 4); | ||
| 331 | std::vector<uint8_t> da(4096), db(1000), dh(1000); | ||
| 332 | DSTORAGE_REQUEST r = file_request(a, 0, da.data(), 4096); | ||
| 333 | q->EnqueueRequest(&r); | ||
| 334 | r = file_request(b, 500, db.data(), 1000); | ||
| 335 | q->EnqueueRequest(&r); | ||
| 336 | r = file_request(h, 500, dh.data(), 1000); | ||
| 337 | q->EnqueueRequest(&r); | ||
| 338 | q->EnqueueStatus(s, 0); | ||
| 339 | check_hr(s->GetHResult(0), E_PENDING, "a status entry is pending once enqueued"); | ||
| 340 | q->Submit(); | ||
| 341 | check(wait_complete(s, 0), "the reads complete"); | ||
| 342 | check_hr(s->GetHResult(0), S_OK, "the reads succeed"); | ||
| 343 | check(std::memcmp(da.data(), env.a_overlay.data(), 4096) == 0 && da != env.a_package, | ||
| 344 | "GAME: reads the overlay copy, not the package"); | ||
| 345 | |||
| 346 | // GetHandle: a handle of its own (ReOpenFile), so its file position does not follow the shim's reads, which | ||
| 347 | // just ended at byte 4096 of this file. | ||
| 348 | HANDLE own = a->GetHandle(); | ||
| 349 | LARGE_INTEGER size{}; | ||
| 350 | check(own != INVALID_HANDLE_VALUE && GetFileSizeEx(own, &size) && size.QuadPart == 5000, | ||
| 351 | "GetHandle names the overlay copy (5000 bytes, the package has 4096)"); | ||
| 352 | std::vector<uint8_t> via_handle(6000); | ||
| 353 | DWORD got = 0; | ||
| 354 | check(own != INVALID_HANDLE_VALUE && ReadFile(own, via_handle.data(), 6000, &got, nullptr) && got == 5000 && | ||
| 355 | std::memcmp(via_handle.data(), env.a_overlay.data(), 5000) == 0, | ||
| 356 | "a ReadFile through GetHandle's handle starts at byte 0 and reads the overlay copy"); | ||
| 357 | if (own != INVALID_HANDLE_VALUE) CloseHandle(own); | ||
| 358 | r = file_request(a, 100, da.data(), 50); | ||
| 359 | q->EnqueueRequest(&r); | ||
| 360 | q->EnqueueStatus(s, 1); | ||
| 361 | q->Submit(); | ||
| 362 | check(wait_complete(s, 1) && std::memcmp(da.data(), env.a_overlay.data() + 100, 50) == 0, | ||
| 363 | "the shim's reads do not follow a GetHandle handle's position either"); | ||
| 364 | check(std::memcmp(db.data(), env.b.data() + 500, 1000) == 0, | ||
| 365 | "a GAME: read at an offset (forward slashes, any case)"); | ||
| 366 | check(db == dh, "a host path reads the same file"); | ||
| 367 | a->Release(); | ||
| 368 | b->Release(); | ||
| 369 | h->Release(); | ||
| 370 | s->Release(); | ||
| 371 | q->Release(); | ||
| 372 | } | ||
| 373 | |||
| 374 | void test_reads_and_errors(Env& env) { | ||
| 375 | IDStorageFileX* b = open(env, L"GAME:\\data\\b.bin"); // 10,000 bytes | ||
| 376 | IDStorageFileX* big = open(env, L"GAME:\\data\\big.bin"); | ||
| 377 | IDStorageQueueX2* q = make_queue(env, 0x80, false); | ||
| 378 | IDStorageStatusArrayX* s = make_status(env, 32); | ||
| 379 | HANDLE error_event = q->GetErrorEvent(); | ||
| 380 | check(error_event != nullptr, "GetErrorEvent returns a handle"); | ||
| 381 | |||
| 382 | std::vector<uint8_t> big_out(env.big.size()); | ||
| 383 | std::vector<uint8_t> few(64, 0xAB); | ||
| 384 | std::vector<uint8_t> zero(16, 0xCD); | ||
| 385 | struct Case { | ||
| 386 | DSTORAGE_REQUEST r; | ||
| 387 | HRESULT want; | ||
| 388 | const char* what; | ||
| 389 | }; | ||
| 390 | std::vector<Case> cases; | ||
| 391 | cases.push_back({file_request(big, 0, big_out.data(), static_cast<uint32_t>(big_out.size())), S_OK, | ||
| 392 | "a 3 MiB read"}); | ||
| 393 | cases.push_back({file_request(b, 10000, zero.data(), 0), S_OK, "a zero-size read at the end of the file"}); | ||
| 394 | cases.push_back({file_request(b, 9990, few.data(), 11, 0x77, "past-the-end"), E_DSTORAGE_END_OF_FILE, | ||
| 395 | "a read one byte past the end"}); | ||
| 396 | cases.push_back({file_request(b, ~0ull - 4, few.data(), 8), E_DSTORAGE_END_OF_FILE, "an offset near 2^64"}); | ||
| 397 | cases.push_back({file_request(b, 0, few.data(), 8), S_OK, "a good read after failures"}); | ||
| 398 | { | ||
| 399 | DSTORAGE_REQUEST r = file_request(b, 0, few.data(), 8); | ||
| 400 | r.DestinationSize = 16; | ||
| 401 | cases.push_back({r, E_DSTORAGE_INVALID_DESTINATION_SIZE, "DestinationSize differs from SourceSize"}); | ||
| 402 | r = file_request(b, 0, few.data(), 8); | ||
| 403 | r.Options.ZlibDecompress = 1; | ||
| 404 | cases.push_back({r, E_DSTORAGE_INVALID_DESTINATION_SIZE, "zlib with DestinationSize equal to SourceSize"}); | ||
| 405 | r = file_request(b, 0, few.data(), 8); | ||
| 406 | r.Options.BcpackMode = DSTORAGE_BCPACK_MODE_BC1; | ||
| 407 | cases.push_back({r, E_NOTIMPL, "BCPack is not implemented yet"}); | ||
| 408 | r = file_request(b, 0, few.data(), 8); | ||
| 409 | r.Options.SwizzleMode = DSTORAGE_SWIZZLE_MODE_4K_4K_8K; | ||
| 410 | cases.push_back({r, E_NOTIMPL, "swizzle is not implemented yet"}); | ||
| 411 | r = file_request(b, 0, few.data(), 8); | ||
| 412 | r.Options.AsUINT64 = 8ull << options::kBcpackShift; | ||
| 413 | cases.push_back({r, E_DSTORAGE_INVALID_BCPACK_MODE, "BCPack mode 8"}); | ||
| 414 | r = file_request(b, 0, few.data(), 8); | ||
| 415 | r.Options.AsUINT64 = 5ull << options::kSwizzleShift; | ||
| 416 | cases.push_back({r, E_DSTORAGE_INVALID_SWIZZLE_MODE, "swizzle mode 5"}); | ||
| 417 | r = file_request(b, 0, few.data(), 8); | ||
| 418 | r.Options.Reserved = 1; | ||
| 419 | cases.push_back({r, E_DSTORAGE_RESERVED_FIELDS, "a reserved option bit"}); | ||
| 420 | r = file_request(b, 0, few.data(), 8); | ||
| 421 | r.Options.DestinationIsPhysicalPages = 1; | ||
| 422 | cases.push_back({r, E_NOTIMPL, "physical pages are not implemented yet"}); | ||
| 423 | r = file_request(b, 0, few.data(), 8); | ||
| 424 | r.IntermediateSize = 4; | ||
| 425 | cases.push_back({r, E_DSTORAGE_INVALID_INTERMEDIATE_SIZE, "IntermediateSize without zlib and BCPack"}); | ||
| 426 | r = file_request(b, 0, nullptr, 8); | ||
| 427 | cases.push_back({r, E_INVALIDARG, "a null destination"}); | ||
| 428 | r = file_request(nullptr, 0, few.data(), 8); | ||
| 429 | cases.push_back({r, E_INVALIDARG, "a null file"}); | ||
| 430 | r = file_request(reinterpret_cast<IDStorageFileX*>(s), 0, few.data(), 8); | ||
| 431 | cases.push_back({r, E_DSTORAGE_INVALID_FILE_HANDLE, "a status array passed as a file"}); | ||
| 432 | r = file_request(b, 0, few.data(), 8); | ||
| 433 | r.Options.SourceType = DSTORAGE_REQUEST_SOURCE_MEMORY; | ||
| 434 | cases.push_back({r, E_DSTORAGE_INVALID_SOURCE_TYPE, "a memory request on a file queue"}); | ||
| 435 | } | ||
| 436 | cases.push_back({file_request(b, 0, nullptr, 0), E_INVALIDARG, "a zero-size read still needs a destination"}); | ||
| 437 | cases.push_back({file_request(nullptr, 0, zero.data(), 0), E_INVALIDARG, "a zero-size read still needs a file"}); | ||
| 438 | void* reserved = VirtualAlloc(nullptr, 1 << 16, MEM_RESERVE, PAGE_READWRITE); | ||
| 439 | cases.push_back({file_request(b, 0, reserved, 4096), E_DSTORAGE_ACCESS_VIOLATION, | ||
| 440 | "a destination the process cannot write"}); | ||
| 441 | check(cases.size() <= 31, "the cases fit the status array"); | ||
| 442 | |||
| 443 | for (UINT32 i = 0; i < cases.size(); ++i) { | ||
| 444 | q->EnqueueRequest(&cases[i].r); | ||
| 445 | q->EnqueueStatus(s, i); | ||
| 446 | } | ||
| 447 | Sleep(30); | ||
| 448 | check(!s->IsComplete(0), "nothing runs before Submit when auto-submit is disabled"); | ||
| 449 | DSTORAGE_QUEUE_INFO1 info{}; | ||
| 450 | q->Query1(&info); | ||
| 451 | check(info.RequestCountUntilAutoSubmit == 0, "no auto-submit count when it is disabled"); | ||
| 452 | check(info.EmptySlotCount == 0x7f - 2 * cases.size(), "EmptySlotCount counts every entry"); | ||
| 453 | q->Submit(); | ||
| 454 | const UINT32 last = static_cast<UINT32>(cases.size() - 1); | ||
| 455 | check(wait_complete(s, last), "all cases complete"); | ||
| 456 | for (UINT32 i = 0; i < cases.size(); ++i) check_hr(s->GetHResult(i), cases[i].want, cases[i].what); | ||
| 457 | check(big_out == env.big, "the 3 MiB read has the file's bytes"); | ||
| 458 | check(zero == std::vector<uint8_t>(16, 0xCD), "a zero-size read writes nothing"); | ||
| 459 | check(std::memcmp(few.data(), env.b.data(), 8) == 0, "the good read after failures"); | ||
| 460 | |||
| 461 | check(WaitForSingleObject(error_event, 0) == WAIT_OBJECT_0, "the error event is set"); | ||
| 462 | DSTORAGE_ERROR_RECORD rec{}; | ||
| 463 | q->RetrieveErrorRecord(&rec); | ||
| 464 | size_t failures = 0; | ||
| 465 | for (const auto& c : cases) failures += FAILED(c.want) ? 1 : 0; | ||
| 466 | check(rec.FailureCount == failures, "FailureCount counts every failed request"); | ||
| 467 | check_hr(rec.FirstFailure.HResult, E_DSTORAGE_END_OF_FILE, "the first failure is recorded"); | ||
| 468 | check(rec.FirstFailure.CommandType == DSTORAGE_COMMAND_TYPE_REQUEST, "its command type is REQUEST"); | ||
| 469 | check(rec.FirstFailure.Request.FileOffset == 9990 && rec.FirstFailure.Request.SourceSize == 11 && | ||
| 470 | rec.FirstFailure.Request.CancellationTag == 0x77, | ||
| 471 | "the record has the request's offset, size and tag"); | ||
| 472 | check(std::wcscmp(rec.FirstFailure.Request.Filename, L"GAME:\\data\\b.bin") == 0, | ||
| 473 | "the record names the file as the title opened it"); | ||
| 474 | check(std::strcmp(rec.FirstFailure.Request.Name, "past-the-end") == 0, "the record has the request's name"); | ||
| 475 | check(WaitForSingleObject(error_event, 0) == WAIT_TIMEOUT, "RetrieveErrorRecord resets the event"); | ||
| 476 | q->RetrieveErrorRecord(&rec); | ||
| 477 | check(rec.FailureCount == 0 && rec.FirstFailure.CommandType == DSTORAGE_COMMAND_TYPE_NONE, | ||
| 478 | "a second RetrieveErrorRecord has nothing"); | ||
| 479 | |||
| 480 | // Status and fence entries that fail. | ||
| 481 | q->EnqueueStatus(s, 1000); | ||
| 482 | q->EnqueueStatus(nullptr, 0); | ||
| 483 | q->EnqueueSignal(nullptr, 1); | ||
| 484 | q->EnqueueStatus(s, 31); | ||
| 485 | q->Submit(); | ||
| 486 | check(wait_complete(s, 31), "the entries after the failed notifications complete"); | ||
| 487 | check_hr(s->GetHResult(31), S_OK, "notification failures do not fail the next status entry"); | ||
| 488 | check_hr(s->GetHResult(1000), E_DSTORAGE_INDEX_BOUND, "GetHResult past the array"); | ||
| 489 | check(s->IsComplete(1000), "IsComplete past the array is not pending"); | ||
| 490 | q->RetrieveErrorRecord(&rec); | ||
| 491 | check(rec.FailureCount == 3 && rec.FirstFailure.CommandType == DSTORAGE_COMMAND_TYPE_STATUS && | ||
| 492 | rec.FirstFailure.HResult == E_DSTORAGE_INDEX_BOUND && rec.FirstFailure.Status.Index == 1000 && | ||
| 493 | rec.FirstFailure.Status.StatusArray == s, | ||
| 494 | "an index past the array is recorded as a STATUS failure"); | ||
| 495 | |||
| 496 | VirtualFree(reserved, 0, MEM_RELEASE); | ||
| 497 | CloseHandle(error_event); | ||
| 498 | s->Release(); | ||
| 499 | q->Release(); | ||
| 500 | b->Release(); | ||
| 501 | big->Release(); | ||
| 502 | } | ||
| 503 | |||
| 504 | void test_fence_order_and_events(Env& env) { | ||
| 505 | IDStorageFileX* b = open(env, L"GAME:\\data\\b.bin"); | ||
| 506 | IDStorageQueueX2* q = make_queue(env, 0x200); | ||
| 507 | TestFence fence; | ||
| 508 | constexpr int kReads = 100; | ||
| 509 | std::vector<std::vector<uint8_t>> outs(kReads, std::vector<uint8_t>(100)); | ||
| 510 | std::atomic<bool> in_place{false}; | ||
| 511 | fence.on_signal = [&](UINT64 v) { | ||
| 512 | bool ok = v == 7; | ||
| 513 | for (int i = 0; i < kReads; ++i) ok = ok && std::memcmp(outs[i].data(), env.b.data() + i * 100, 100) == 0; | ||
| 514 | in_place.store(ok); | ||
| 515 | }; | ||
| 516 | for (int i = 0; i < kReads; ++i) { | ||
| 517 | DSTORAGE_REQUEST r = file_request(b, static_cast<uint64_t>(i) * 100, outs[i].data(), 100); | ||
| 518 | q->EnqueueRequest(&r); | ||
| 519 | } | ||
| 520 | q->EnqueueSignal(&fence, 7); | ||
| 521 | check(fence.refs.load() == 2, "an enqueued signal holds a fence reference"); | ||
| 522 | HANDLE ev = CreateEventW(nullptr, FALSE, FALSE, nullptr); | ||
| 523 | q->EnqueueSetEvent(ev); | ||
| 524 | q->Submit(); | ||
| 525 | check(WaitForSingleObject(ev, 10000) == WAIT_OBJECT_0, "EnqueueSetEvent sets the event"); | ||
| 526 | check(fence.GetCompletedValue() == 7, "EnqueueSignal signals the fence with its value"); | ||
| 527 | check(in_place.load(), "the fence is signalled after every read before it is in place"); | ||
| 528 | check(wait_until([&] { return fence.refs.load() == 1; }), "the fence reference is released after the signal"); | ||
| 529 | |||
| 530 | // A failed request before a fence: the fence still signals, and the status after the fence is clean. | ||
| 531 | IDStorageStatusArrayX* s = make_status(env, 2); | ||
| 532 | std::vector<uint8_t> tmp(8); | ||
| 533 | DSTORAGE_REQUEST bad = file_request(b, 20000, tmp.data(), 8); | ||
| 534 | q->EnqueueRequest(&bad); | ||
| 535 | q->EnqueueSignal(&fence, 8); | ||
| 536 | q->EnqueueStatus(s, 0); | ||
| 537 | q->Submit(); | ||
| 538 | check(wait_complete(s, 0), "the status after a fence completes"); | ||
| 539 | check_hr(s->GetHResult(0), S_OK, "a failure before a fence is not reported by a status after it"); | ||
| 540 | check(fence.GetCompletedValue() == 8, "a fence after a failed read still signals"); | ||
| 541 | CloseHandle(ev); | ||
| 542 | s->Release(); | ||
| 543 | q->Release(); | ||
| 544 | b->Release(); | ||
| 545 | } | ||
| 546 | |||
| 547 | void test_cancel(Env& env) { | ||
| 548 | IDStorageFileX* b = open(env, L"GAME:\\data\\b.bin"); | ||
| 549 | IDStorageQueueX2* q = make_queue(env, 0x80, false); | ||
| 550 | IDStorageStatusArrayX* s = make_status(env, 1); | ||
| 551 | std::vector<std::vector<uint8_t>> outs(6, std::vector<uint8_t>(16, 0)); | ||
| 552 | const uint64_t tags[] = {0x11, 0x12, 0x21, 0x22, 0x31}; | ||
| 553 | for (int i = 0; i < 5; ++i) { | ||
| 554 | DSTORAGE_REQUEST r = file_request(b, 0, outs[i].data(), 16, tags[i]); | ||
| 555 | q->EnqueueRequest(&r); | ||
| 556 | } | ||
| 557 | q->CancelRequestsWithTag(0xF0, 0x10); // 0x11 and 0x12 | ||
| 558 | q->CancelRequestsWithTag(0xFF, 0x22); // 0x22 | ||
| 559 | DSTORAGE_REQUEST later = file_request(b, 0, outs[5].data(), 16, 0x11); // enqueued after: not cancelled | ||
| 560 | q->EnqueueRequest(&later); | ||
| 561 | q->EnqueueStatus(s, 0); | ||
| 562 | q->Submit(); | ||
| 563 | check(wait_complete(s, 0), "cancelled requests complete"); | ||
| 564 | check_hr(s->GetHResult(0), S_OK, "a cancelled request is a success"); | ||
| 565 | const std::vector<uint8_t> zeros(16, 0); | ||
| 566 | check(outs[0] == zeros && outs[1] == zeros && outs[3] == zeros, "cancelled requests read nothing"); | ||
| 567 | check(std::memcmp(outs[2].data(), env.b.data(), 16) == 0 && std::memcmp(outs[4].data(), env.b.data(), 16) == 0, | ||
| 568 | "requests the mask did not match are read"); | ||
| 569 | check(std::memcmp(outs[5].data(), env.b.data(), 16) == 0, "a request enqueued after the cancel is read"); | ||
| 570 | s->Release(); | ||
| 571 | q->Release(); | ||
| 572 | b->Release(); | ||
| 573 | } | ||
| 574 | |||
| 575 | void test_auto_submit_and_full_queue(Env& env) { | ||
| 576 | IDStorageFileX* b = open(env, L"GAME:\\data\\b.bin"); | ||
| 577 | IDStorageQueueX2* q = make_queue(env, 0x80, true); | ||
| 578 | std::vector<std::vector<uint8_t>> outs(64, std::vector<uint8_t>(8, 0)); | ||
| 579 | for (int i = 0; i < 63; ++i) { | ||
| 580 | DSTORAGE_REQUEST r = file_request(b, i, outs[i].data(), 8); | ||
| 581 | q->EnqueueRequest(&r); | ||
| 582 | } | ||
| 583 | DSTORAGE_QUEUE_INFO info{}; | ||
| 584 | q->Query(&info); | ||
| 585 | check(info.RequestCountUntilAutoSubmit == 1, "one entry before the automatic submit"); | ||
| 586 | Sleep(20); | ||
| 587 | check(outs[0] == std::vector<uint8_t>(8, 0), "below half the capacity nothing is submitted"); | ||
| 588 | DSTORAGE_REQUEST r = file_request(b, 63, outs[63].data(), 8); | ||
| 589 | q->EnqueueRequest(&r); // the 64th: half of 0x80 | ||
| 590 | check(wait_until([&] { return std::memcmp(outs[63].data(), env.b.data() + 63, 8) == 0; }), | ||
| 591 | "reaching half the capacity submits without Submit"); | ||
| 592 | bool all = true; | ||
| 593 | for (int i = 0; i < 64; ++i) all = all && std::memcmp(outs[i].data(), env.b.data() + i, 8) == 0; | ||
| 594 | check(all, "every auto-submitted read has its bytes"); | ||
| 595 | q->Release(); | ||
| 596 | |||
| 597 | // Auto-submit disabled and full: an enqueue waits until another thread submits. | ||
| 598 | q = make_queue(env, 0x80, false); | ||
| 599 | IDStorageStatusArrayX* s = make_status(env, 1); | ||
| 600 | constexpr int kMany = 400; | ||
| 601 | std::vector<uint8_t> sink(kMany * 4); | ||
| 602 | std::atomic<bool> done{false}; | ||
| 603 | std::thread producer([&] { | ||
| 604 | for (int i = 0; i < kMany; ++i) { | ||
| 605 | DSTORAGE_REQUEST rr = file_request(b, i, sink.data() + i * 4, 4); | ||
| 606 | q->EnqueueRequest(&rr); | ||
| 607 | } | ||
| 608 | q->EnqueueStatus(s, 0); | ||
| 609 | done.store(true); | ||
| 610 | }); | ||
| 611 | check(wait_until([&] { | ||
| 612 | DSTORAGE_QUEUE_INFO i{}; | ||
| 613 | q->Query(&i); | ||
| 614 | return i.EmptySlotCount == 0; | ||
| 615 | }), | ||
| 616 | "the queue fills to capacity - 1"); | ||
| 617 | Sleep(20); | ||
| 618 | check(!done.load(), "an enqueue into a full queue waits"); | ||
| 619 | while (!done.load()) { | ||
| 620 | q->Submit(); | ||
| 621 | Sleep(1); | ||
| 622 | } | ||
| 623 | producer.join(); | ||
| 624 | q->Submit(); | ||
| 625 | check(wait_complete(s, 0), "the producer's reads complete"); | ||
| 626 | bool same = true; | ||
| 627 | for (int i = 0; i < kMany; ++i) same = same && std::memcmp(sink.data() + i * 4, env.b.data() + i, 4) == 0; | ||
| 628 | check(same, "every read of the full-queue run has its bytes"); | ||
| 629 | s->Release(); | ||
| 630 | q->Release(); | ||
| 631 | b->Release(); | ||
| 632 | } | ||
| 633 | |||
| 634 | void test_memory_queue(Env& env) { | ||
| 635 | IDStorageQueueX2* q = make_queue(env, 0x80, true, DSTORAGE_REQUEST_SOURCE_MEMORY, DSTORAGE_PRIORITY_REALTIME); | ||
| 636 | IDStorageStatusArrayX* s = make_status(env, 6); | ||
| 637 | std::vector<uint8_t> buf = pattern(8192, 9); | ||
| 638 | std::vector<uint8_t> want = buf; | ||
| 639 | std::memmove(want.data() + 1024, want.data(), 4096); | ||
| 640 | DSTORAGE_REQUEST r{}; | ||
| 641 | r.Options.SourceType = DSTORAGE_REQUEST_SOURCE_MEMORY; | ||
| 642 | r.Source = buf.data(); | ||
| 643 | r.Destination = buf.data() + 1024; | ||
| 644 | r.SourceSize = r.DestinationSize = 4096; | ||
| 645 | q->EnqueueRequest(&r); | ||
| 646 | q->EnqueueStatus(s, 0); | ||
| 647 | void* reserved = VirtualAlloc(nullptr, 1 << 16, MEM_RESERVE, PAGE_READWRITE); | ||
| 648 | DSTORAGE_REQUEST bad = r; | ||
| 649 | bad.Destination = reserved; | ||
| 650 | q->EnqueueRequest(&bad); | ||
| 651 | q->EnqueueStatus(s, 1); | ||
| 652 | DSTORAGE_REQUEST file_on_memory{}; // a file request on a memory queue | ||
| 653 | file_on_memory.Destination = buf.data(); | ||
| 654 | file_on_memory.SourceSize = file_on_memory.DestinationSize = 4; | ||
| 655 | q->EnqueueRequest(&file_on_memory); | ||
| 656 | q->EnqueueStatus(s, 2); | ||
| 657 | DSTORAGE_REQUEST huge = r; | ||
| 658 | huge.SourceSize = huge.DestinationSize = (1u << 29) + 1; // more than 1 GiB together | ||
| 659 | q->EnqueueRequest(&huge); | ||
| 660 | q->EnqueueStatus(s, 3); | ||
| 661 | // Buffers over 32 MiB need 64 KiB or 2 MiB pages (DSTORAGE_REQUEST). Reserved memory: a copy that is not refused | ||
| 662 | // faults and reports an access violation instead. | ||
| 663 | constexpr uint32_t k32MiB = 32u << 20; | ||
| 664 | void* wide = VirtualAlloc(nullptr, 2 * (k32MiB + 4096), MEM_RESERVE, PAGE_READWRITE); | ||
| 665 | check(wide != nullptr, "reserve 64 MiB for the over-limit copy"); | ||
| 666 | DSTORAGE_REQUEST over = r; | ||
| 667 | over.Source = wide; | ||
| 668 | over.Destination = static_cast<uint8_t*>(wide) + k32MiB + 4096; | ||
| 669 | over.SourceSize = over.DestinationSize = k32MiB + 1; | ||
| 670 | q->EnqueueRequest(&over); | ||
| 671 | q->EnqueueStatus(s, 4); | ||
| 672 | std::vector<uint8_t> at_limit_source = pattern(k32MiB, 10), at_limit(k32MiB, 0); | ||
| 673 | DSTORAGE_REQUEST limit = r; | ||
| 674 | limit.Source = at_limit_source.data(); | ||
| 675 | limit.Destination = at_limit.data(); | ||
| 676 | limit.SourceSize = limit.DestinationSize = k32MiB; | ||
| 677 | q->EnqueueRequest(&limit); | ||
| 678 | q->EnqueueStatus(s, 5); | ||
| 679 | q->Submit(); | ||
| 680 | check(wait_complete(s, 5), "memory requests complete"); | ||
| 681 | check_hr(s->GetHResult(4), E_DSTORAGE_REQUEST_TOO_LARGE, "an unpaged buffer over 32 MiB is refused untouched"); | ||
| 682 | check_hr(s->GetHResult(5), S_OK, "a 32 MiB unpaged copy"); | ||
| 683 | check(at_limit == at_limit_source, "the 32 MiB copy moved every byte"); | ||
| 684 | VirtualFree(wide, 0, MEM_RELEASE); | ||
| 685 | check_hr(s->GetHResult(0), S_OK, "a memory-to-memory copy"); | ||
| 686 | check(buf == want, "an overlapping memory copy moves like memmove"); | ||
| 687 | check_hr(s->GetHResult(1), E_DSTORAGE_ACCESS_VIOLATION, "a memory copy to memory the process cannot write"); | ||
| 688 | check_hr(s->GetHResult(2), E_DSTORAGE_INVALID_SOURCE_TYPE, "a file request on a memory queue"); | ||
| 689 | check_hr(s->GetHResult(3), E_DSTORAGE_REQUEST_TOO_LARGE, "source plus destination over 1 GiB"); | ||
| 690 | VirtualFree(reserved, 0, MEM_RELEASE); | ||
| 691 | s->Release(); | ||
| 692 | q->Release(); | ||
| 693 | } | ||
| 694 | |||
| 695 | void test_close_and_release(Env& env) { | ||
| 696 | IDStorageFileX* big = open(env, L"GAME:\\data\\big.bin"); | ||
| 697 | // Close with requests in flight: it returns after they all ran. | ||
| 698 | IDStorageQueueX2* q = make_queue(env, 0x100, true); | ||
| 699 | constexpr int kReads = 300; | ||
| 700 | constexpr uint32_t kChunk = 8192; | ||
| 701 | std::vector<uint8_t> out(kReads * kChunk); | ||
| 702 | for (int i = 0; i < kReads; ++i) { | ||
| 703 | DSTORAGE_REQUEST r = file_request(big, static_cast<uint64_t>(i) * kChunk, out.data() + i * kChunk, kChunk); | ||
| 704 | q->EnqueueRequest(&r); | ||
| 705 | } | ||
| 706 | q->Close(); | ||
| 707 | check(std::memcmp(out.data(), env.big.data(), out.size()) == 0, "Close returns after every enqueued read ran"); | ||
| 708 | IDStorageStatusArrayX* s = make_status(env, 1); | ||
| 709 | std::vector<uint8_t> tmp(8, 0); | ||
| 710 | DSTORAGE_REQUEST r = file_request(big, 0, tmp.data(), 8); | ||
| 711 | q->EnqueueRequest(&r); | ||
| 712 | q->EnqueueStatus(s, 0); | ||
| 713 | q->Submit(); | ||
| 714 | q->Close(); // a second Close is harmless | ||
| 715 | Sleep(20); | ||
| 716 | check(tmp == std::vector<uint8_t>(8, 0), "a request enqueued after Close is not run"); | ||
| 717 | DSTORAGE_ERROR_RECORD rec{}; | ||
| 718 | q->RetrieveErrorRecord(&rec); | ||
| 719 | check(rec.FailureCount == 2 && rec.FirstFailure.HResult == E_DSTORAGE_QUEUE_CLOSED, | ||
| 720 | "enqueues after Close are recorded"); | ||
| 721 | check(q->Release() == 0, "a closed queue is freed by its last Release"); | ||
| 722 | |||
| 723 | // The last Release with requests in flight finishes them first. | ||
| 724 | q = make_queue(env, 0x100, true); | ||
| 725 | std::fill(out.begin(), out.end(), uint8_t{0}); | ||
| 726 | for (int i = 0; i < kReads; ++i) { | ||
| 727 | DSTORAGE_REQUEST rr = file_request(big, static_cast<uint64_t>(i) * kChunk, out.data() + i * kChunk, kChunk); | ||
| 728 | q->EnqueueRequest(&rr); | ||
| 729 | } | ||
| 730 | q->Submit(); | ||
| 731 | big->Release(); // the requests hold the file | ||
| 732 | check(q->Release() == 0, "the last Release of a busy queue"); | ||
| 733 | check(std::memcmp(out.data(), env.big.data(), out.size()) == 0, "the last Release ran the reads in flight"); | ||
| 734 | |||
| 735 | // IDStorageFileX::Close: submitted reads finish, a later one fails with E_DSTORAGE_FILE_NOT_OPEN. | ||
| 736 | IDStorageFileX* b = open(env, L"GAME:\\data\\b.bin"); | ||
| 737 | q = make_queue(env, 0x80, false); | ||
| 738 | IDStorageStatusArrayX* s2 = make_status(env, 3); | ||
| 739 | std::vector<uint8_t> first(100, 0), second(100, 0); | ||
| 740 | DSTORAGE_REQUEST r1 = file_request(b, 0, first.data(), 100); | ||
| 741 | q->EnqueueRequest(&r1); | ||
| 742 | q->EnqueueStatus(s2, 0); | ||
| 743 | q->Submit(); | ||
| 744 | DSTORAGE_REQUEST r2 = file_request(b, 0, second.data(), 100); | ||
| 745 | q->EnqueueRequest(&r2); // not submitted yet | ||
| 746 | b->Close(); | ||
| 747 | check(std::memcmp(first.data(), env.b.data(), 100) == 0, | ||
| 748 | "IDStorageFileX::Close waits for the file's submitted reads"); | ||
| 749 | check(wait_complete(s2, 0) && s2->GetHResult(0) == S_OK, "the submitted read succeeded"); | ||
| 750 | check(b->GetHandle() == INVALID_HANDLE_VALUE, "GetHandle on a closed file"); | ||
| 751 | q->EnqueueStatus(s2, 1); | ||
| 752 | DSTORAGE_REQUEST r3 = file_request(b, 0, second.data(), 0); | ||
| 753 | q->EnqueueRequest(&r3); | ||
| 754 | q->EnqueueStatus(s2, 2); | ||
| 755 | q->Submit(); | ||
| 756 | check(wait_complete(s2, 2), "the reads after the close complete"); | ||
| 757 | check_hr(s2->GetHResult(1), E_DSTORAGE_FILE_NOT_OPEN, "a read of a closed file"); | ||
| 758 | check_hr(s2->GetHResult(2), E_DSTORAGE_FILE_NOT_OPEN, "a zero-size read of a closed file"); | ||
| 759 | check(second == std::vector<uint8_t>(100, 0), "a read of a closed file writes nothing"); | ||
| 760 | q->Release(); | ||
| 761 | b->Release(); | ||
| 762 | s->Release(); | ||
| 763 | s2->Release(); | ||
| 764 | } | ||
| 765 | |||
| 766 | void test_threads(Env& env) { | ||
| 767 | IDStorageFileX* big = open(env, L"GAME:\\data\\big.bin"); | ||
| 768 | IDStorageQueueX2* q = make_queue(env, 0x80, true); | ||
| 769 | constexpr int kThreads = 4, kPer = 250; | ||
| 770 | constexpr uint32_t kChunk = 512; | ||
| 771 | std::vector<std::vector<uint8_t>> outs(kThreads, std::vector<uint8_t>(kPer * kChunk)); | ||
| 772 | std::vector<IDStorageStatusArrayX*> arrays; | ||
| 773 | for (int t = 0; t < kThreads; ++t) arrays.push_back(make_status(env, 1)); | ||
| 774 | std::vector<std::thread> threads; | ||
| 775 | for (int t = 0; t < kThreads; ++t) | ||
| 776 | threads.emplace_back([&, t] { | ||
| 777 | for (int i = 0; i < kPer; ++i) { | ||
| 778 | const uint64_t offset = (static_cast<uint64_t>(t) * kPer + i) * kChunk % (env.big.size() - kChunk); | ||
| 779 | DSTORAGE_REQUEST r = file_request(big, offset, outs[t].data() + i * kChunk, kChunk, t); | ||
| 780 | q->EnqueueRequest(&r); | ||
| 781 | } | ||
| 782 | q->EnqueueStatus(arrays[t], 0); | ||
| 783 | q->Submit(); | ||
| 784 | }); | ||
| 785 | for (auto& th : threads) th.join(); | ||
| 786 | bool ok = true; | ||
| 787 | for (int t = 0; t < kThreads; ++t) { | ||
| 788 | ok = ok && wait_complete(arrays[t], 0) && arrays[t]->GetHResult(0) == S_OK; | ||
| 789 | for (int i = 0; i < kPer; ++i) { | ||
| 790 | const uint64_t offset = (static_cast<uint64_t>(t) * kPer + i) * kChunk % (env.big.size() - kChunk); | ||
| 791 | ok = ok && std::memcmp(outs[t].data() + i * kChunk, env.big.data() + offset, kChunk) == 0; | ||
| 792 | } | ||
| 793 | } | ||
| 794 | check(ok, "four threads enqueueing at once all read their bytes"); | ||
| 795 | for (auto* a : arrays) a->Release(); | ||
| 796 | q->Release(); | ||
| 797 | big->Release(); | ||
| 798 | } | ||
| 799 | |||
| 800 | void test_iid_policy_events_and_cancel(Env& env) { | ||
| 801 | // Well-known system interfaces and made-up ids: QueryInterface refuses all of them. | ||
| 802 | const GUID kRandom = {0x5eed0001, 0x2222, 0x4222, {0x82, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x01}}; | ||
| 803 | const GUID kIMarshal = {0x00000003, 0x0000, 0x0000, {0xc0, 0, 0, 0, 0, 0, 0, 0x46}}; | ||
| 804 | const GUID kIAgileObject = {0x94ea2b94, 0xe9cc, 0x49e0, {0xc0, 0xff, 0xee, 0x64, 0xca, 0x8f, 0x5b, 0x90}}; | ||
| 805 | const GUID kINoMarshal = {0xecc8691b, 0xc1db, 0x4dc0, {0x85, 0x5e, 0x65, 0xf6, 0xc5, 0x51, 0xaf, 0x49}}; | ||
| 806 | const GUID kIClientSecurity = {0x0000013d, 0x0000, 0x0000, {0xc0, 0, 0, 0, 0, 0, 0, 0x46}}; | ||
| 807 | const GUID kPcStatusArrayId = {0x82397587, 0x7cd5, 0x453b, {0xa0, 0x2e, 0x31, 0x37, 0x9b, 0xd6, 0x46, 0x56}}; | ||
| 808 | const GUID kPcQueueId = {0xcfdbd83f, 0x9e06, 0x4fda, {0x8e, 0xa5, 0x69, 0x04, 0x21, 0x37, 0xf4, 0x9b}}; | ||
| 809 | const GUID kQueueId2 = {0x0d5e0012, 0x1111, 0x4111, {0x81, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x12}}; | ||
| 810 | const GUID refused[] = {kRandom, kIMarshal, kIAgileObject, kINoMarshal, kIClientSecurity}; | ||
| 811 | |||
| 812 | IDStorageQueueX2* q = make_queue(env, 0x80, false); | ||
| 813 | IDStorageFileX* b = open(env, L"GAME:\\data\\b.bin"); | ||
| 814 | IDStorageStatusArrayX* s = make_status(env, 8); | ||
| 815 | IUnknown* objects[] = {env.factory, q, b, s}; | ||
| 816 | for (IUnknown* o : objects) | ||
| 817 | for (const GUID& g : refused) { | ||
| 818 | void* out = reinterpret_cast<void*>(1); | ||
| 819 | check_hr(o->QueryInterface(g, &out), E_NOINTERFACE, "QueryInterface refuses an unknown or system id"); | ||
| 820 | check(out == nullptr, "a refused QueryInterface clears ppv"); | ||
| 821 | } | ||
| 822 | void* out = nullptr; | ||
| 823 | check_hr(q->QueryInterface(kFileId, &out), E_NOINTERFACE, "a queue refuses a file id"); | ||
| 824 | check_hr(b->QueryInterface(kQueueId, &out), E_NOINTERFACE, "a file refuses a queue id"); | ||
| 825 | check_hr(s->QueryInterface(kFactoryId, &out), E_NOINTERFACE, "a status array refuses a factory id"); | ||
| 826 | check_hr(q->QueryInterface(__uuidof(IUnknown), &out), S_OK, "QueryInterface(IUnknown)"); | ||
| 827 | if (out) static_cast<IUnknown*>(out)->Release(); | ||
| 828 | |||
| 829 | // Creating calls learn a new id but refuse system ones. | ||
| 830 | auto get = reinterpret_cast<DStorageGetFactoryFn>(rt::shims::find("dstorage_xs.dll", "DStorageGetFactory")); | ||
| 831 | check_hr(get(kIMarshal, &out), E_NOINTERFACE, "DStorageGetFactory refuses IMarshal"); | ||
| 832 | check_hr(get(kIAgileObject, &out), E_NOINTERFACE, "DStorageGetFactory refuses IAgileObject"); | ||
| 833 | DSTORAGE_QUEUE_DESC1 d{}; | ||
| 834 | d.Capacity = 0x80; | ||
| 835 | check_hr(env.factory->CreateQueue1(&d, kINoMarshal, &out), E_NOINTERFACE, "CreateQueue1 refuses INoMarshal"); | ||
| 836 | check_hr(env.factory->OpenFile(L"GAME:\\data\\b.bin", kIClientSecurity, &out), E_NOINTERFACE, | ||
| 837 | "OpenFile refuses IClientSecurity"); | ||
| 838 | check_hr(env.factory->CreateQueue1(&d, kPcQueueId, &out), E_NOINTERFACE, "CreateQueue1 refuses the PC queue id"); | ||
| 839 | check_hr(env.factory->CreateQueue1(&d, kPcStatusArrayId, &out), E_NOINTERFACE, | ||
| 840 | "the status array id is not a queue id"); | ||
| 841 | check_hr(env.factory->CreateQueue1(&d, kQueueId2, &out), S_OK, "a creating call learns a new queue id"); | ||
| 842 | if (out) static_cast<IUnknown*>(out)->Release(); | ||
| 843 | check_hr(q->QueryInterface(kQueueId2, &out), S_OK, "QueryInterface accepts an id a queue was created with"); | ||
| 844 | if (out) static_cast<IUnknown*>(out)->Release(); | ||
| 845 | |||
| 846 | // The PC IDStorageStatusArray id has the console interface's shape and is accepted. | ||
| 847 | check_hr(env.factory->CreateStatusArray(2, nullptr, kPcStatusArrayId, &out), S_OK, | ||
| 848 | "CreateStatusArray accepts the PC IDStorageStatusArray id"); | ||
| 849 | if (out) static_cast<IUnknown*>(out)->Release(); | ||
| 850 | check_hr(s->QueryInterface(kPcStatusArrayId, &out), S_OK, "a status array answers the PC IDStorageStatusArray id"); | ||
| 851 | if (out) static_cast<IUnknown*>(out)->Release(); | ||
| 852 | |||
| 853 | // EnqueueSetEvent duplicates the handle: closing the title's handle, even with its value reused, changes nothing. | ||
| 854 | HANDLE first = CreateEventW(nullptr, TRUE, FALSE, nullptr); | ||
| 855 | q->EnqueueSetEvent(first); | ||
| 856 | CloseHandle(first); | ||
| 857 | HANDLE second = CreateEventW(nullptr, TRUE, FALSE, nullptr); // may get the same handle value | ||
| 858 | q->EnqueueSetEvent(reinterpret_cast<HANDLE>(static_cast<uintptr_t>(0x7ffffff0))); // not a handle | ||
| 859 | q->EnqueueSetEvent(nullptr); | ||
| 860 | q->EnqueueStatus(s, 0); | ||
| 861 | q->Submit(); | ||
| 862 | check(wait_complete(s, 0), "the event entries complete"); | ||
| 863 | check(WaitForSingleObject(second, 0) == WAIT_TIMEOUT, "a closed event's reused handle value is not set"); | ||
| 864 | DSTORAGE_ERROR_RECORD rec{}; | ||
| 865 | q->RetrieveErrorRecord(&rec); | ||
| 866 | check(rec.FailureCount == 2 && rec.FirstFailure.CommandType == kCommandTypeEvent && | ||
| 867 | FAILED(rec.FirstFailure.HResult), | ||
| 868 | "an invalid and a null event handle are recorded as EVENT failures; the closed one is not"); | ||
| 869 | CloseHandle(second); | ||
| 870 | |||
| 871 | // A cancelled request that also had an enqueue error is still a success, and not counted as a failure. | ||
| 872 | std::vector<uint8_t> tmp(8, 0); | ||
| 873 | DSTORAGE_REQUEST foreign = file_request(reinterpret_cast<IDStorageFileX*>(s), 0, tmp.data(), 8, 0x99); | ||
| 874 | q->EnqueueRequest(&foreign); | ||
| 875 | DSTORAGE_REQUEST null_file = file_request(nullptr, 0, tmp.data(), 8, 0x99); | ||
| 876 | q->EnqueueRequest(&null_file); | ||
| 877 | q->CancelRequestsWithTag(~0ull, 0x99); | ||
| 878 | q->EnqueueStatus(s, 1); | ||
| 879 | q->Submit(); | ||
| 880 | check(wait_complete(s, 1), "cancelled bad requests complete"); | ||
| 881 | check_hr(s->GetHResult(1), S_OK, "a cancelled request with an enqueue error is a success"); | ||
| 882 | q->RetrieveErrorRecord(&rec); | ||
| 883 | check(rec.FailureCount == 0, "a cancelled request is not counted as a failure"); | ||
| 884 | |||
| 885 | s->Release(); | ||
| 886 | b->Release(); | ||
| 887 | q->Release(); | ||
| 888 | } | ||
| 889 | |||
| 890 | // Holds the queue's worker inside a copy: the copy's source is a guard page, and this handler waits on the first | ||
| 891 | // touch until the test releases it. The guard is gone after that fault, so the copy then goes on. | ||
| 892 | struct GuardHold { | ||
| 893 | uint8_t* page = nullptr; | ||
| 894 | HANDLE entered = nullptr; | ||
| 895 | HANDLE release = nullptr; | ||
| 896 | }; | ||
| 897 | GuardHold* g_hold = nullptr; | ||
| 898 | |||
| 899 | LONG CALLBACK hold_on_guard(EXCEPTION_POINTERS* x) { | ||
| 900 | const EXCEPTION_RECORD* e = x->ExceptionRecord; | ||
| 901 | if (!g_hold || e->ExceptionCode != STATUS_GUARD_PAGE_VIOLATION || e->NumberParameters < 2) | ||
| 902 | return EXCEPTION_CONTINUE_SEARCH; | ||
| 903 | const auto* address = reinterpret_cast<const uint8_t*>(e->ExceptionInformation[1]); | ||
| 904 | if (address < g_hold->page || address >= g_hold->page + 4096) return EXCEPTION_CONTINUE_SEARCH; | ||
| 905 | SetEvent(g_hold->entered); | ||
| 906 | WaitForSingleObject(g_hold->release, 10000); | ||
| 907 | return EXCEPTION_CONTINUE_EXECUTION; | ||
| 908 | } | ||
| 909 | |||
| 910 | // DSTORAGE_PRIORITY_STATS: TotalRequestCount and the byte totals count submitted requests; PendingRequestCount counts | ||
| 911 | // requests whose processing has started and not completed. A memory queue (realtime, the only priority it may have): | ||
| 912 | // the counts are compared with the ones before. | ||
| 913 | void test_stats_timing(Env& env) { | ||
| 914 | auto realtime = [&] { | ||
| 915 | DSTORAGE_STATS st{}; | ||
| 916 | env.factory->GetStats(&st); | ||
| 917 | return st.RealtimePriorityStats; | ||
| 918 | }; | ||
| 919 | const DSTORAGE_PRIORITY_STATS before = realtime(); | ||
| 920 | IDStorageQueueX2* q = make_queue(env, 0x80, false, DSTORAGE_REQUEST_SOURCE_MEMORY, DSTORAGE_PRIORITY_REALTIME); | ||
| 921 | if (!q) return; | ||
| 922 | IDStorageStatusArrayX* s = make_status(env, 1); | ||
| 923 | GuardHold hold; | ||
| 924 | hold.page = static_cast<uint8_t*>(VirtualAlloc(nullptr, 4096, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); | ||
| 925 | hold.entered = CreateEventW(nullptr, TRUE, FALSE, nullptr); | ||
| 926 | hold.release = CreateEventW(nullptr, TRUE, FALSE, nullptr); | ||
| 927 | if (!hold.page || !hold.entered || !hold.release) { | ||
| 928 | check(false, "allocate the guard page and its events"); | ||
| 929 | return; | ||
| 930 | } | ||
| 931 | std::memset(hold.page, 0x5A, 4096); | ||
| 932 | DWORD old = 0; | ||
| 933 | VirtualProtect(hold.page, 4096, PAGE_READWRITE | PAGE_GUARD, &old); | ||
| 934 | std::vector<uint8_t> out(4096, 0); | ||
| 935 | DSTORAGE_REQUEST r{}; | ||
| 936 | r.Options.SourceType = DSTORAGE_REQUEST_SOURCE_MEMORY; | ||
| 937 | r.Source = hold.page; | ||
| 938 | r.Destination = out.data(); | ||
| 939 | r.SourceSize = r.DestinationSize = 4096; | ||
| 940 | q->EnqueueRequest(&r); | ||
| 941 | q->EnqueueStatus(s, 0); | ||
| 942 | DSTORAGE_PRIORITY_STATS p = realtime(); | ||
| 943 | check(p.TotalRequestCount == before.TotalRequestCount && | ||
| 944 | p.TotalRequestSourceByteCount == before.TotalRequestSourceByteCount && | ||
| 945 | p.TotalRequestDestinationByteCount == before.TotalRequestDestinationByteCount, | ||
| 946 | "an enqueued request is not counted before Submit"); | ||
| 947 | |||
| 948 | g_hold = &hold; | ||
| 949 | void* handler = AddVectoredExceptionHandler(1, hold_on_guard); | ||
| 950 | q->Submit(); | ||
| 951 | check(WaitForSingleObject(hold.entered, 10000) == WAIT_OBJECT_0, "the copy reached the guard page"); | ||
| 952 | p = realtime(); | ||
| 953 | check(p.TotalRequestCount == before.TotalRequestCount + 1 && | ||
| 954 | p.TotalRequestSourceByteCount == before.TotalRequestSourceByteCount + 4096 && | ||
| 955 | p.TotalRequestDestinationByteCount == before.TotalRequestDestinationByteCount + 4096, | ||
| 956 | "a submitted request is counted, with its sizes"); | ||
| 957 | check(p.PendingRequestCount == before.PendingRequestCount + 1, "a running request is pending"); | ||
| 958 | SetEvent(hold.release); | ||
| 959 | check(wait_complete(s, 0), "the held copy completes"); | ||
| 960 | check_hr(s->GetHResult(0), S_OK, "the held copy succeeds"); | ||
| 961 | check(out == std::vector<uint8_t>(4096, 0x5A), "the held copy moved every byte"); | ||
| 962 | check(realtime().PendingRequestCount == before.PendingRequestCount, "a completed request is no longer pending"); | ||
| 963 | RemoveVectoredExceptionHandler(handler); | ||
| 964 | g_hold = nullptr; | ||
| 965 | CloseHandle(hold.entered); | ||
| 966 | CloseHandle(hold.release); | ||
| 967 | VirtualFree(hold.page, 0, MEM_RELEASE); | ||
| 968 | s->Release(); | ||
| 969 | q->Release(); | ||
| 970 | } | ||
| 971 | |||
| 972 | void test_stats(Env& env) { | ||
| 973 | DSTORAGE_STATS st{}; | ||
| 974 | env.factory->GetStats(&st); | ||
| 975 | check(st.CurrentOpenFileCount == 0, "every file was released"); | ||
| 976 | check(st.NormalPriorityStats.CurrentQueueCount == 0 && st.RealtimePriorityStats.CurrentQueueCount == 0, | ||
| 977 | "every queue was released"); | ||
| 978 | check(st.NormalPriorityStats.TotalRequestCount > 1000 && st.NormalPriorityStats.TotalFenceCount >= 2 && | ||
| 979 | st.RealtimePriorityStats.TotalRequestCount == 7, | ||
| 980 | "requests and fences are counted per priority"); | ||
| 981 | check(st.CumulativeOpenFileCount >= 10 && st.MaxOpenFileCount >= 3, "files are counted"); | ||
| 982 | check(st.ErrorCount > 10, "errors are counted"); | ||
| 983 | } | ||
| 984 | |||
| 985 | |||
| 986 | // ---- zlib requests ------------------------------------------------------------------------------------------------ | ||
| 987 | // | ||
| 988 | // Synthetic streams only. The two Huffman streams were made with Python's zlib (3.14, zlib-ng 1.3.1 API) from the | ||
| 989 | // text zlib_text() builds, which in Python is | ||
| 990 | // text = lambda n: b"".join(b"line %04d: a zlib request for the queue, value %d\n" % (i, (i * i) % 97) | ||
| 991 | // for i in range(n)) | ||
| 992 | // kZlibDynamic = zlib.compress(text(64), 9): one final dynamic-Huffman block (BTYPE 2), 345 bytes for 3,191. | ||
| 993 | // kZlibFixed = zlib.compress(text(4), 1): one final fixed-Huffman block (BTYPE 1), 77 bytes for 196. | ||
| 994 | // Streams with stored blocks (BTYPE 0) are built here by stored_stream(); for a single block that is byte for byte | ||
| 995 | // what zlib.compress(data, 0) gives. | ||
| 996 | constexpr uint8_t kZlibDynamic[] = { | ||
| 997 | 0x78, 0xda, 0x95, 0xd4, 0x4d, 0x4e, 0x03, 0x31, 0x0c, 0x05, 0xe0, 0x3d, 0xa7, 0xc8, 0x01, 0x58, 0x4c, 0xfc, | ||
| 998 | 0x97, 0x84, 0xdb, 0x14, 0x69, 0x10, 0x95, 0x46, 0x20, 0x4a, 0xcb, 0x82, 0xd3, 0x33, 0x0b, 0xf4, 0xbc, 0x7d, | ||
| 999 | 0xee, 0x6e, 0xa4, 0x3e, 0x25, 0xce, 0x67, 0xfb, 0xb8, 0x7e, 0xec, 0x6d, 0x3b, 0x7f, 0x2f, 0xed, 0xd2, 0x7e, | ||
| 1000 | 0x8f, 0xeb, 0x6b, 0xbb, 0xed, 0x5f, 0x8f, 0xfd, 0xfb, 0xde, 0xde, 0x3e, 0x6f, 0xed, 0xfe, 0xbe, 0xb7, 0xf3, | ||
| 1001 | 0xeb, 0xb1, 0x3f, 0xb7, 0x9f, 0xcb, 0xf1, 0x38, 0xff, 0xf9, 0x74, 0xfc, 0x07, 0x3a, 0x17, 0xe8, 0x08, 0x08, | ||
| 1002 | 0x17, 0x30, 0x04, 0x94, 0x0b, 0x2c, 0x04, 0x8c, 0xbc, 0x52, 0x20, 0xe1, 0x5c, 0x42, 0x1c, 0x89, 0xe0, 0x12, | ||
| 1003 | 0x9a, 0x67, 0x0c, 0xb2, 0xee, 0xac, 0x63, 0x72, 0x89, 0xc8, 0xa7, 0x5a, 0x5c, 0x62, 0x42, 0xa3, 0x93, 0xde, | ||
| 1004 | 0x8a, 0x00, 0xe9, 0x2d, 0xb8, 0x54, 0x67, 0xc1, 0x07, 0x12, 0xa4, 0xf8, 0x10, 0x24, 0x48, 0xf2, 0x0c, 0x90, | ||
| 1005 | 0xe2, 0x9a, 0x2f, 0x45, 0x8a, 0x47, 0x9e, 0x41, 0x8a, 0x2f, 0x74, 0x55, 0x27, 0xc5, 0x35, 0x39, 0x48, 0xf1, | ||
| 1006 | 0x81, 0x81, 0x15, 0x52, 0xbc, 0xa3, 0x0e, 0x21, 0xc9, 0x1d, 0xb7, 0x12, 0x92, 0x7c, 0x61, 0x3a, 0x84, 0x24, | ||
| 1007 | 0x37, 0xb4, 0x95, 0x90, 0xe4, 0x0b, 0x82, 0x42, 0x9a, 0x5b, 0xd6, 0x41, 0x9a, 0xaf, 0xbc, 0x15, 0x69, 0xee, | ||
| 1008 | 0xe9, 0x41, 0x9a, 0x4f, 0x04, 0x48, 0xf2, 0x40, 0x5b, 0x29, 0x49, 0x2e, 0x98, 0x40, 0x25, 0xc9, 0x27, 0x6e, | ||
| 1009 | 0xa5, 0x24, 0xb9, 0xe3, 0xa9, 0x94, 0x24, 0x17, 0x34, 0xa2, 0x92, 0xe4, 0x13, 0x2b, 0x54, 0x49, 0xf2, 0x40, | ||
| 1010 | 0x93, 0x28, 0xbb, 0xd8, 0xf3, 0x75, 0x49, 0xf2, 0x9e, 0x67, 0xb0, 0xe4, 0x18, 0x0f, 0x65, 0xcd, 0x91, 0x30, | ||
| 1011 | 0xd2, 0xdc, 0x20, 0x68, 0xa4, 0xb9, 0xc2, 0xc3, 0x48, 0xf3, 0x9e, 0x67, 0x90, 0xe6, 0x59, 0x06, 0x3b, 0xe5, | ||
| 1012 | 0x98, 0x59, 0x23, 0xc9, 0x27, 0x00, 0x8d, 0x24, 0x1f, 0x68, 0x2b, 0x23, 0xc9, 0x47, 0x9e, 0x41, 0x92, 0x8f, | ||
| 1013 | 0xac, 0x63, 0x55, 0x13, 0xbe, 0x55, 0x6f, 0xe5, 0xbd, 0x5a, 0xb9, 0x4b, 0xf5, 0x75, 0x5d, 0xab, 0x82, 0x6e, | ||
| 1014 | 0xc5, 0x26, 0x71, 0xaf, 0xf6, 0xa1, 0x47, 0xb5, 0xd7, 0x7d, 0x54, 0xe7, 0xc9, 0x67, 0x75, 0x66, 0x7d, 0x55, | ||
| 1015 | 0xf7, 0x42, 0x6c, 0xd5, 0xdd, 0x13, 0xbd, 0xba, 0xdf, 0x42, 0xaa, 0x3b, 0x34, 0x94, 0xde, 0xd3, 0x7f, 0x97, | ||
| 1016 | 0x8b, 0x11, 0xce, | ||
| 1017 | }; | ||
| 1018 | constexpr uint8_t kZlibFixed[] = { | ||
| 1019 | 0x78, 0x01, 0xcb, 0xc9, 0xcc, 0x4b, 0x55, 0x30, 0x30, 0x30, 0x30, 0xb0, 0x52, 0x48, 0x54, 0xa8, 0xca, 0xc9, | ||
| 1020 | 0x4c, 0x52, 0x28, 0x4a, 0x2d, 0x2c, 0x4d, 0x2d, 0x2e, 0x51, 0x48, 0xcb, 0x2f, 0x52, 0x28, 0xc9, 0x48, 0x55, | ||
| 1021 | 0x28, 0x2c, 0x4d, 0x2d, 0x4d, 0xd5, 0x51, 0x28, 0x4b, 0xcc, 0x29, 0x4d, 0x55, 0x30, 0xe0, 0x82, 0x69, 0x30, | ||
| 1022 | 0x24, 0x4e, 0x83, 0x21, 0x5c, 0x83, 0x11, 0x71, 0x1a, 0x4c, 0xe0, 0x1a, 0x8c, 0x89, 0xd3, 0x60, 0xc9, 0x05, | ||
| 1023 | 0x00, 0xb0, 0x6e, 0x40, 0x49, | ||
| 1024 | }; | ||
| 1025 | |||
| 1026 | std::vector<uint8_t> zlib_text(int lines) { | ||
| 1027 | std::string t; | ||
| 1028 | char line[96]; | ||
| 1029 | for (int i = 0; i < lines; ++i) { | ||
| 1030 | std::snprintf(line, sizeof line, "line %04d: a zlib request for the queue, value %d\n", i, (i * i) % 97); | ||
| 1031 | t += line; | ||
| 1032 | } | ||
| 1033 | return {t.begin(), t.end()}; | ||
| 1034 | } | ||
| 1035 | |||
| 1036 | uint32_t adler32(const std::vector<uint8_t>& data) { | ||
| 1037 | uint32_t a = 1, b = 0; | ||
| 1038 | for (const uint8_t x : data) { | ||
| 1039 | a = (a + x) % 65521; | ||
| 1040 | b = (b + a) % 65521; | ||
| 1041 | } | ||
| 1042 | return (b << 16) | a; | ||
| 1043 | } | ||
| 1044 | |||
| 1045 | // A zlib stream (header 78 01) whose first block stores `stored` (a final block when there is no tail), followed by | ||
| 1046 | // the deflate blocks of the zlib stream `tail` (its header and Adler-32 dropped: a stored block ends on a byte | ||
| 1047 | // boundary, so they follow as they are) and the Adler-32 of the whole result, `stored` then `tail_plain`. | ||
| 1048 | std::vector<uint8_t> stored_stream(const std::vector<uint8_t>& stored, const uint8_t* tail = nullptr, | ||
| 1049 | size_t tail_size = 0, const std::vector<uint8_t>& tail_plain = {}) { | ||
| 1050 | const auto n = static_cast<uint16_t>(stored.size()); | ||
| 1051 | std::vector<uint8_t> z = {0x78, 0x01, static_cast<uint8_t>(tail ? 0 : 1), static_cast<uint8_t>(n), | ||
| 1052 | static_cast<uint8_t>(n >> 8), static_cast<uint8_t>(~n), static_cast<uint8_t>(~n >> 8)}; | ||
| 1053 | z.insert(z.end(), stored.begin(), stored.end()); | ||
| 1054 | if (tail) z.insert(z.end(), tail + 2, tail + tail_size - 4); | ||
| 1055 | std::vector<uint8_t> plain = stored; | ||
| 1056 | plain.insert(plain.end(), tail_plain.begin(), tail_plain.end()); | ||
| 1057 | const uint32_t check = adler32(plain); | ||
| 1058 | for (int shift = 24; shift >= 0; shift -= 8) z.push_back(static_cast<uint8_t>(check >> shift)); | ||
| 1059 | return z; | ||
| 1060 | } | ||
| 1061 | |||
| 1062 | void test_zlib(Env& env) { | ||
| 1063 | const std::vector<uint8_t> dynamic(std::begin(kZlibDynamic), std::end(kZlibDynamic)); | ||
| 1064 | const std::vector<uint8_t> fixed(std::begin(kZlibFixed), std::end(kZlibFixed)); | ||
| 1065 | const std::vector<uint8_t> dynamic_plain = zlib_text(64), fixed_plain = zlib_text(4); | ||
| 1066 | // The first block header is the low three bits after the two header bytes: BFINAL, then BTYPE (RFC 1951 3.2.3). | ||
| 1067 | check(dynamic.size() == 345 && (dynamic[2] & 7) == (1 | 2 << 1), "kZlibDynamic is one final dynamic block"); | ||
| 1068 | check(fixed.size() == 77 && (fixed[2] & 7) == (1 | 1 << 1), "kZlibFixed is one final fixed-Huffman block"); | ||
| 1069 | check(dynamic_plain.size() == 3191 && fixed_plain.size() == 196, "the synthetic text has the generator's sizes"); | ||
| 1070 | |||
| 1071 | const std::vector<uint8_t> stored_part = pattern(300, 21); | ||
| 1072 | const std::vector<uint8_t> mixed = stored_stream(stored_part, kZlibDynamic, sizeof kZlibDynamic, dynamic_plain); | ||
| 1073 | std::vector<uint8_t> mixed_plain = stored_part; | ||
| 1074 | mixed_plain.insert(mixed_plain.end(), dynamic_plain.begin(), dynamic_plain.end()); | ||
| 1075 | check((mixed[2] & 7) == 0, "the mixed stream starts with a stored block that is not the last"); | ||
| 1076 | const std::vector<uint8_t> stored_only = stored_stream(pattern(40, 22)); // larger than what it inflates to | ||
| 1077 | std::vector<uint8_t> bad_method = dynamic, bad_type = fixed, bad_check = dynamic, preset = dynamic; | ||
| 1078 | bad_method[0] ^= 1; // CM 9: not deflate | ||
| 1079 | preset[1] = 0xbb; // 78 BB: a valid check value with FDICT set (a preset dictionary) | ||
| 1080 | bad_type[2] |= 0x06; // BTYPE 3, reserved | ||
| 1081 | bad_check.back() ^= 1; // the Adler-32 | ||
| 1082 | |||
| 1083 | // One file, every stream at a 16-byte aligned offset and followed by 32 zero bytes. | ||
| 1084 | std::vector<uint8_t> file; | ||
| 1085 | auto put = [&](const std::vector<uint8_t>& z) { | ||
| 1086 | const uint64_t at = file.size(); | ||
| 1087 | file.insert(file.end(), z.begin(), z.end()); | ||
| 1088 | file.resize((file.size() + 32 + 15) & ~size_t{15}, 0); | ||
| 1089 | return at; | ||
| 1090 | }; | ||
| 1091 | const uint64_t at_dynamic = put(dynamic), at_fixed = put(fixed), at_mixed = put(mixed), | ||
| 1092 | at_stored = put(stored_only), at_method = put(bad_method), at_preset = put(preset), | ||
| 1093 | at_type = put(bad_type), at_check = put(bad_check); | ||
| 1094 | write_file(env.game / L"data" / L"zlib.bin", file); | ||
| 1095 | |||
| 1096 | struct Case { | ||
| 1097 | uint64_t offset; | ||
| 1098 | uint32_t source, destination; | ||
| 1099 | HRESULT want; | ||
| 1100 | const std::vector<uint8_t>* result; // the expected bytes; null when the destination stays untouched | ||
| 1101 | const char* what; | ||
| 1102 | uint64_t options = 0; | ||
| 1103 | uint32_t intermediate = 0; | ||
| 1104 | }; | ||
| 1105 | const auto z = static_cast<uint32_t>(dynamic.size()); | ||
| 1106 | std::vector<Case> cases = { | ||
| 1107 | {at_dynamic, z, 3191, S_OK, &dynamic_plain, "a zlib file request: dynamic Huffman"}, | ||
| 1108 | {at_fixed, 77, 196, S_OK, &fixed_plain, "a zlib file request: fixed Huffman"}, | ||
| 1109 | {at_mixed, static_cast<uint32_t>(mixed.size()), 3491, S_OK, &mixed_plain, | ||
| 1110 | "a zlib file request: a stored block, then dynamic Huffman"}, | ||
| 1111 | {at_dynamic, z + 16, 3191, S_OK, &dynamic_plain, "bytes after the Adler-32 are not read"}, | ||
| 1112 | {at_stored, static_cast<uint32_t>(stored_only.size()), 40, E_DSTORAGE_INVALID_DESTINATION_SIZE, nullptr, | ||
| 1113 | "a zlib DestinationSize not larger than SourceSize"}, | ||
| 1114 | {at_method, z, 3191, E_DSTORAGE_ZLIB_BAD_HEADER, nullptr, "a header that is not deflate"}, | ||
| 1115 | {at_preset, z, 3191, E_DSTORAGE_ZLIB_BAD_HEADER, nullptr, "a header with a preset dictionary"}, | ||
| 1116 | {at_type, 77, 196, E_DSTORAGE_ZLIB_BAD_DATA, nullptr, "a reserved block type"}, | ||
| 1117 | {at_dynamic, z - 10, 3191, E_DSTORAGE_ZLIB_BAD_DATA, nullptr, "a truncated stream"}, | ||
| 1118 | {at_check, z, 3191, E_DSTORAGE_ZLIB_PARITY_FAIL, nullptr, "an Adler-32 mismatch"}, | ||
| 1119 | {at_dynamic, z, 3192, E_DSTORAGE_DECOMPRESSION_ERROR, nullptr, "a stream shorter than DestinationSize"}, | ||
| 1120 | {at_dynamic, z, 3190, E_DSTORAGE_DECOMPRESSION_ERROR, nullptr, "a stream longer than DestinationSize"}, | ||
| 1121 | {at_dynamic + 8, z, 3191, E_DSTORAGE_INVALID_FILE_OFFSET, nullptr, "a zlib offset not 16-byte aligned"}, | ||
| 1122 | {file.size() - 16, 32, 64, E_DSTORAGE_END_OF_FILE, nullptr, "a zlib source past the end of the file"}, | ||
| 1123 | {at_dynamic, z, 3191, E_DSTORAGE_INVALID_INTERMEDIATE_SIZE, nullptr, "zlib with an IntermediateSize", 0, | ||
| 1124 | 16}, | ||
| 1125 | {at_dynamic, z, 3191, E_NOTIMPL, nullptr, "zlib and BCPack is not implemented yet", | ||
| 1126 | static_cast<uint64_t>(DSTORAGE_BCPACK_MODE_BC1) << options::kBcpackShift, 64}, | ||
| 1127 | {at_dynamic, z, 3191, E_NOTIMPL, nullptr, "zlib and swizzle is not implemented yet", | ||
| 1128 | static_cast<uint64_t>(DSTORAGE_SWIZZLE_MODE_4K_4K_8K) << options::kSwizzleShift}, | ||
| 1129 | }; | ||
| 1130 | |||
| 1131 | DSTORAGE_STATS before{}; | ||
| 1132 | env.factory->GetStats(&before); | ||
| 1133 | IDStorageFileX* f = open(env, L"GAME:\\data\\zlib.bin"); | ||
| 1134 | IDStorageQueueX2* q = make_queue(env, 0x80, false); | ||
| 1135 | IDStorageStatusArrayX* s = make_status(env, static_cast<UINT32>(cases.size())); | ||
| 1136 | constexpr size_t kSlack = 64; // past DestinationSize: must stay untouched | ||
| 1137 | std::vector<std::vector<uint8_t>> out(cases.size()); | ||
| 1138 | for (size_t i = 0; i < cases.size(); ++i) { | ||
| 1139 | const Case& c = cases[i]; | ||
| 1140 | out[i].assign(c.destination + kSlack, 0xEE); | ||
| 1141 | DSTORAGE_REQUEST r = file_request(f, c.offset, out[i].data(), c.destination); | ||
| 1142 | r.SourceSize = c.source; | ||
| 1143 | r.IntermediateSize = c.intermediate; | ||
| 1144 | r.Options.AsUINT64 = options::kZlib | c.options; | ||
| 1145 | q->EnqueueRequest(&r); | ||
| 1146 | q->EnqueueStatus(s, static_cast<UINT32>(i)); | ||
| 1147 | } | ||
| 1148 | q->Submit(); | ||
| 1149 | check(wait_complete(s, static_cast<UINT32>(cases.size() - 1)), "the zlib file requests complete"); | ||
| 1150 | for (size_t i = 0; i < cases.size(); ++i) { | ||
| 1151 | const Case& c = cases[i]; | ||
| 1152 | check_hr(s->GetHResult(static_cast<UINT32>(i)), c.want, c.what); | ||
| 1153 | const std::vector<uint8_t> untouched(c.destination, 0xEE); | ||
| 1154 | const bool head = c.result ? std::equal(c.result->begin(), c.result->end(), out[i].begin()) | ||
| 1155 | : std::equal(untouched.begin(), untouched.end(), out[i].begin()); | ||
| 1156 | const bool tail = std::all_of(out[i].end() - kSlack, out[i].end(), [](uint8_t x) { return x == 0xEE; }); | ||
| 1157 | check(head && tail, c.result ? "the inflated bytes are the synthetic text, and nothing past them" | ||
| 1158 | : "a failed zlib request leaves the destination untouched"); | ||
| 1159 | } | ||
| 1160 | s->Release(); | ||
| 1161 | q->Release(); | ||
| 1162 | f->Release(); | ||
| 1163 | |||
| 1164 | // A memory source: the same stream, one inflated in place (the compressed bytes sit at the end of their own | ||
| 1165 | // destination, as a title may load them), a corrupt one, a source and a destination the process cannot touch. | ||
| 1166 | IDStorageQueueX2* mq = make_queue(env, 0x80, true, DSTORAGE_REQUEST_SOURCE_MEMORY, DSTORAGE_PRIORITY_REALTIME); | ||
| 1167 | IDStorageStatusArrayX* ms = make_status(env, 5); | ||
| 1168 | void* reserved = VirtualAlloc(nullptr, 1 << 16, MEM_RESERVE, PAGE_READWRITE); | ||
| 1169 | std::vector<uint8_t> m0(3191, 0xEE), in_place(3191, 0xEE), m2(3191, 0xEE), m3(3191, 0xEE); | ||
| 1170 | std::copy(dynamic.begin(), dynamic.end(), in_place.end() - dynamic.size()); | ||
| 1171 | DSTORAGE_REQUEST r{}; | ||
| 1172 | r.Options.AsUINT64 = options::kZlib | options::kSourceMemory; | ||
| 1173 | r.SourceSize = z; | ||
| 1174 | r.DestinationSize = 3191; | ||
| 1175 | r.Source = dynamic.data(); | ||
| 1176 | r.Destination = m0.data(); | ||
| 1177 | mq->EnqueueRequest(&r); | ||
| 1178 | mq->EnqueueStatus(ms, 0); | ||
| 1179 | r.Source = in_place.data() + in_place.size() - dynamic.size(); | ||
| 1180 | r.Destination = in_place.data(); | ||
| 1181 | mq->EnqueueRequest(&r); | ||
| 1182 | mq->EnqueueStatus(ms, 1); | ||
| 1183 | r.Source = bad_check.data(); | ||
| 1184 | r.Destination = m2.data(); | ||
| 1185 | mq->EnqueueRequest(&r); | ||
| 1186 | mq->EnqueueStatus(ms, 2); | ||
| 1187 | r.Source = reserved; | ||
| 1188 | r.Destination = m3.data(); | ||
| 1189 | mq->EnqueueRequest(&r); | ||
| 1190 | mq->EnqueueStatus(ms, 3); | ||
| 1191 | r.Source = dynamic.data(); | ||
| 1192 | r.Destination = reserved; | ||
| 1193 | mq->EnqueueRequest(&r); | ||
| 1194 | mq->EnqueueStatus(ms, 4); | ||
| 1195 | mq->Submit(); | ||
| 1196 | check(wait_complete(ms, 4), "the zlib memory requests complete"); | ||
| 1197 | check_hr(ms->GetHResult(0), S_OK, "a zlib memory request"); | ||
| 1198 | check(m0 == dynamic_plain, "the zlib memory request inflates to the synthetic text"); | ||
| 1199 | check_hr(ms->GetHResult(1), S_OK, "a zlib memory request whose source lies inside its destination"); | ||
| 1200 | check(in_place == dynamic_plain, "inflating in place gives the synthetic text"); | ||
| 1201 | check_hr(ms->GetHResult(2), E_DSTORAGE_ZLIB_PARITY_FAIL, "a zlib memory request with an Adler-32 mismatch"); | ||
| 1202 | check(m2 == std::vector<uint8_t>(3191, 0xEE), "the failed zlib memory request leaves the destination untouched"); | ||
| 1203 | check_hr(ms->GetHResult(3), E_DSTORAGE_ACCESS_VIOLATION, "a zlib source the process cannot read"); | ||
| 1204 | check_hr(ms->GetHResult(4), E_DSTORAGE_ACCESS_VIOLATION, "a zlib destination the process cannot write"); | ||
| 1205 | VirtualFree(reserved, 0, MEM_RELEASE); | ||
| 1206 | ms->Release(); | ||
| 1207 | mq->Release(); | ||
| 1208 | |||
| 1209 | // Counted when the inflate starts: the 11 file requests (4 good, 7 bad streams) and 4 memory requests (all but the | ||
| 1210 | // unreadable source) whose checks passed and whose source was read. Failed: the 7 bad file streams and the memory | ||
| 1211 | // one with an Adler-32 mismatch; a destination the process cannot write is not a decompression error. | ||
| 1212 | DSTORAGE_STATS after{}; | ||
| 1213 | env.factory->GetStats(&after); | ||
| 1214 | check(after.TotalDecompressionRequestCount - before.TotalDecompressionRequestCount == 15, | ||
| 1215 | "TotalDecompressionRequestCount counts the zlib requests that reached the inflate"); | ||
| 1216 | check(after.DecompressionErrors - before.DecompressionErrors == 8, "DecompressionErrors counts the bad streams"); | ||
| 1217 | check(after.PendingDecompressionRequestCount == 0, "no decompression is pending afterwards"); | ||
| 1218 | } | ||
| 1219 | |||
| 1220 | } // namespace | ||
| 1221 | |||
| 1222 | int main() { | ||
| 1223 | wchar_t temp[MAX_PATH]; | ||
| 1224 | GetTempPathW(MAX_PATH, temp); | ||
| 1225 | Env env; | ||
| 1226 | env.root = fs::path(temp) / (L"leonida_dstorage_test_" + std::to_wstring(GetCurrentProcessId())); | ||
| 1227 | env.game = env.root / L"game"; | ||
| 1228 | env.overlay = env.root / L"overlay"; | ||
| 1229 | std::error_code ec; | ||
| 1230 | fs::remove_all(env.root, ec); | ||
| 1231 | env.a_package = pattern(4096, 1); | ||
| 1232 | env.a_overlay = pattern(5000, 2); // another size and other bytes than the package's copy | ||
| 1233 | env.b = pattern(10000, 3); | ||
| 1234 | env.big = pattern(3u << 20, 4); | ||
| 1235 | write_file(env.game / L"data" / L"a.bin", env.a_package); | ||
| 1236 | write_file(env.overlay / L"data" / L"a.bin", env.a_overlay); | ||
| 1237 | write_file(env.game / L"data" / L"b.bin", env.b); | ||
| 1238 | write_file(env.game / L"data" / L"big.bin", env.big); | ||
| 1239 | rt::fs::configure(env.game, env.overlay); | ||
| 1240 | |||
| 1241 | test_layout_and_options(); | ||
| 1242 | test_registry(env); | ||
| 1243 | test_factory_checks(env); | ||
| 1244 | test_open_paths(env); | ||
| 1245 | test_reads_and_errors(env); | ||
| 1246 | test_fence_order_and_events(env); | ||
| 1247 | test_cancel(env); | ||
| 1248 | test_auto_submit_and_full_queue(env); | ||
| 1249 | test_memory_queue(env); | ||
| 1250 | test_close_and_release(env); | ||
| 1251 | test_threads(env); | ||
| 1252 | test_iid_policy_events_and_cancel(env); | ||
| 1253 | test_stats_timing(env); | ||
| 1254 | test_stats(env); | ||
| 1255 | test_zlib(env); // after test_stats, whose request totals it would change | ||
| 1256 | |||
| 1257 | fs::remove_all(env.root, ec); | ||
| 1258 | std::printf("dstorage: %d checks, %d failures\n", g_checks, g_failures); | ||
| 1259 | return g_failures ? 1 : 0; | ||
| 1260 | } | ||