Compare commits

...
Author SHA1 Message Date
ates 34f97fd2d6 Merge remote-tracking branch 'origin/main' into track-c/value-wait-order
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-12-02 14:38:17 +03:00
Ateş bc66413f29 Merge pull request #796 from MacosPorters/track-b/769-xcrdapi-gdk-slots
[Picture] XCRDAPI: Xbox DirectStorage slots follow dstorage_xs.h; partial zlib reads are bounded (#769)
2026-12-02 14:38:10 +03:00
ates f98bb2de50 Merge remote-tracking branch 'origin/main' into track-b/769-xcrdapi-gdk-slots
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-12-02 14:38:00 +03:00
Ateş 11c8bf8209 Merge pull request #795 from MacosPorters/track-e/775-delayed-callbacks
[Picture] xgameruntime: a delayed task-queue callback no longer holds back later callbacks (#775)
2026-12-02 14:37:54 +03:00
ates 5fd69c0be2 d3d12_xs: keep GPU value waits after the writes they follow
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-12-02 14:29:04 +03:00
ates c76957b7c7 Merge remote-tracking branch 'origin/main' into track-b/769-xcrdapi-gdk-slots
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-12-02 11:36:33 +03:00
ates 2736f24ca2 XCRDAPI: Xbox DirectStorage slots follow dstorage_xs.h; partial zlib reads are bounded (#769)
Factory slots 3 CreateQueue, 6 SetCpuAffinity, 7 SetDebugFlags, 9
GetStats and 10 CreateQueue1; file slot 4 GetHandle; queue slots 10
RetrieveErrorRecord, 11 Query, 12 EnqueueSetEvent and 13 Query1, with
the X/X1/X2 IIDs. Requests are read as the 0x48-byte DSTORAGE_REQUEST.
A partial zlib read decodes through a 32 KiB window instead of a buffer
of 64 times the destination.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-12-02 05:08:20 +03:00
12 changed files with 750 additions and 171 deletions

No files matched your search

+8
View File
@@ -18,6 +18,14 @@ remains unsupported.
- Tests: `test_stub_caller`, plus unit tests for the report and the lookup.
### Fixed
- **GPU value waits recorded after a write no longer run before it.** Since #791 every `WaitOnBitValueX`-family wait of a command list ran before the list. A title that makes two queues hand over to each other (one list writes a value and then waits for the other's, the other waits and then writes) therefore waited in a cycle that only the 10 s timeout broke, on every frame. Waits recorded before the list's first write still run in front of it; a wait recorded after a write now runs after the list's GPU work and those writes, and later writes are stored once that wait holds. `test_d3d12_gpu_value_order` gains the two-queue case.
- **`XCRDAPI`: the Xbox DirectStorage interfaces have the `dstorage_xs.h` slots, and a partial zlib read no longer allocates up to 2 GiB** (#769).
- **Factory** (`IDStorageFactoryX`/`X1`/`X2`): slot 3 `CreateQueue(DSTORAGE_QUEUE_DESC*)` creates a queue with auto-submit on, where it used to return `E_NOTIMPL`. Slot 6 is `SetCpuAffinity` and returns an HRESULT; it used to be a `void` `SetDebugFlags`. Slot 7 is `SetDebugFlags`. Slot 9 `GetStats` writes a zeroed 256-byte `DSTORAGE_STATS`, logged as a stub. Slot 10 is `CreateQueue1`, which also checks `DSTORAGE_PRIORITY`. Slots 11 and 12, which don't exist, are gone. `DStorageGetFactory` and `QueryInterface` accept all three factory IIDs.
- **File:** slot 4 is `GetHandle`, a new handle the caller closes. It used to be `GetFileInformation`, which returned 0 as the "handle".
- **Queue** (`IDStorageQueueX`/`X1`/`X2`): slot 10 `RetrieveErrorRecord` fills the 656-byte `DSTORAGE_ERROR_RECORD`'s count, first HRESULT and command type. Slot 11 `Query` and slot 13 `Query1` report the queue. Slot 12 `EnqueueSetEvent` sets the event, so a waiter wakes; it used to be a stub. The queue answers all three queue IIDs.
- **Requests** are read as the 0x48-byte `DSTORAGE_REQUEST`, including `IntermediateSize`, `CancellationTag` and `Name`. `CancelRequestsWithTag` logs its mask and value; requests still run, as the header allows.
- **Partial zlib reads:** a read of the first part of a compressed block decodes the whole stream through a 32 KiB window, still checking Adler-32, and writes only `DestinationSize` bytes. It used to allocate `64 × DestinationSize + 256 KiB`, up to 2 GiB.
- **Tests:** `test_xcrdapi_xbox_slots` covers the corrected slots and the bounded partial read.
- **`xgameruntime`: a delayed task-queue callback no longer holds back the callbacks submitted after it** (#775, part 3). `XTaskQueueSubmitDelayedCallback` put the task in the port's FIFO, and the port waited for it to be due. So one multi-second retry timer blocked every later callback on that port, and on a pool lane a thread-pool thread slept meanwhile. In the GDK the delay elapses before the callback is submitted. Delayed tasks now wait outside the FIFO and a thread-pool timer moves them in when due, so a callback submitted later without a delay runs first. Delayed tasks still pending when the queue closes are drained or cancelled like the rest. `test_xgameruntime` checks both a manual and a serialized queue.
- **`d3d12_xs`: `D3D12ConfigureVirtualMemoryX` accepts the DEFAULT page count and the legacy lower bound; `WaitFrameEventX` reports PRIMARY** (#772). These follow the authorized GDK header `d3d12_xs.h`.
- `PageTableMemory4MBPageCount` = `D3D12XBOX_PAGE_TABLE_MEMORY_4MB_PAGE_COUNT_DEFAULT` (0) selects the default of 5 pages. It used to be refused with `E_INVALIDARG`.
+37 -12
View File
@@ -16,10 +16,15 @@
* A wait the worker cannot satisfy within 10 s is released anyway (logged), as is a GPU fence
* that does not complete; a host queue never stays blocked for good.
*
* Accepted difference: inside one list, its waits are treated as being at its start and its
* writes at its end (a host command list cannot be split once recorded). A write is never seen
* before the work in front of it; a wait in a list on a write earlier in the same list is
* released after 10 s.
* Accepted difference: a host command list cannot be split once recorded, so inside one list a
* write is stored at the list's end, and a wait is placed at the list's start when no write was
* recorded before it in that list, or at the list's end (after that list's writes are stored) when
* one was. A write is never seen before the work in front of it. A wait recorded after a write
* stays after it: a two-queue handshake, where one list writes then waits for the other queue
* while the other waits then writes, completes instead of each queue holding the other for the
* 10 s release (target build, #806 follow-up). Writes recorded after such a wait are stored only
* once it holds. The price is that GPU work recorded after such a wait in the same list may run
* before the wait holds.
*/
#include "xbox_facade.h"
@@ -272,25 +277,45 @@ void execute(void* self, UINT count, ID3D12CommandList* const* lists) {
std::lock_guard<std::mutex> guard(s->submit);
UINT start = 0;
for (UINT i = 0; i < count; ++i) {
bool has_wait = false, has_write = false;
for (const Write& w : ops[i]) (w.wait ? has_wait : has_write) = true;
if (has_wait) {
// In recording order: waits before the list's first write go in front of the list; the
// writes and any later waits go after it, the writes first.
bool has_pre_wait = false, has_write = false, has_post_wait = false;
for (const Write& w : ops[i]) {
if (!w.wait) has_write = true;
else if (has_write) has_post_wait = true;
else has_pre_wait = true;
}
if (has_pre_wait) {
if (i > start) queue->ExecuteCommandLists(i - start, host.data() + start);
start = i;
for (const Write& w : ops[i]) {
if (w.wait) enqueue_wait(s, w);
if (!w.wait) break;
enqueue_wait(s, w);
}
}
if (has_write) {
queue->ExecuteCommandLists(i + 1 - start, host.data() + start);
start = i + 1;
// The writes up to the list's first later wait are stored when the GPU has finished
// the list; each later wait follows, and the writes recorded after it are stored only
// once it holds (same GPU fence value: the list is already done by then).
const uint64_t done = ++s->gpu_value;
queue->Signal(s->gpu, done);
QueueState::Item item;
item.value = ++s->gpu_value;
item.value = done;
bool seen_write = false;
for (const Write& w : ops[i]) {
if (!w.wait) item.writes.push_back(w);
if (!w.wait) {
seen_write = true;
item.writes.push_back(w);
} else if (seen_write) {
if (!item.writes.empty()) s->push(std::move(item));
item = QueueState::Item{};
item.value = done;
enqueue_wait(s, w);
}
}
queue->Signal(s->gpu, item.value);
s->push(std::move(item));
if (!item.writes.empty()) s->push(std::move(item));
}
}
if (start < count) queue->ExecuteCommandLists(count - start, host.data() + start);
+2
View File
@@ -13,3 +13,5 @@
The package as a whole is under the proprietary *Microsoft DirectStorage SDK* licence terms (`LICENSE.txt`), whose distributable list (`distributable_files.txt`) names only `dstorage.dll` and `dstoragecore.dll`. BetterXen uses neither DLL and copies nothing else from the package.
The Xbox console interfaces (`IDStorageFactoryX` and others, `dstorage_xs.h`) are not included: their IIDs have no licence-compatible public source. See the discussion on #483.
`xcrdapi.cpp` declares its own copies of the Xbox console interfaces, which follow the authorized GDK header `dstorage_xs.h` (#769). That header itself is not vendored.
+191 -114
View File
@@ -485,19 +485,15 @@ CopyResult copy_staged(HANDLE file, const Request& request) {
}
/* A title may read only the first part of a compressed block: the stream then holds more than
DestinationSize bytes. The whole stream is decoded and checked (Adler-32), and its first
`output_size` bytes are delivered. A stream shorter than the destination stays an error. */
DestinationSize bytes. The whole stream is decoded and checked (Adler-32), and only its first
`output_size` bytes are written; the rest passes through a 32 KiB window, so a partial read
needs no buffer for the whole stream (#769: it used to allocate output_size * 64 bytes, up to
2 GiB for a 32 MiB destination). A stream shorter than the destination stays an error. */
BxInflateResult inflate_first_part(const uint8_t* compressed, const Request& request) {
const size_t capacity = static_cast<size_t>(request.output_size) * 64 + 0x40000;
auto* whole = static_cast<uint8_t*>(HeapAlloc(GetProcessHeap(), 0, capacity));
if (!whole) return BxInflateResult::output_mismatch;
size_t produced = 0;
BxInflateResult r = bx_zlib_inflate_any(compressed, request.size, whole, capacity, &produced);
if (r == BxInflateResult::ok && produced > request.output_size) {
std::memcpy(request.destination, whole, request.output_size);
} else if (r == BxInflateResult::ok) {
r = BxInflateResult::output_mismatch;
}
BxInflateResult r = bx_zlib_inflate_prefix(compressed, request.size, static_cast<uint8_t*>(request.destination),
request.output_size, &produced);
if (r == BxInflateResult::ok && produced <= request.output_size) r = BxInflateResult::output_mismatch;
static std::atomic<UINT> logged{0};
if (logged.fetch_add(1) < 16) {
char detail[160];
@@ -506,7 +502,6 @@ BxInflateResult inflate_first_part(const uint8_t* compressed, const Request& req
r == BxInflateResult::ok ? "first part delivered" : bx_inflate_result_name(r));
bx_log_emit(r == BxInflateResult::ok ? BX_LOG_INFO : BX_LOG_WARN, "xcrdapi", "dstorage_zlib_partial", detail);
}
HeapFree(GetProcessHeap(), 0, whole);
return r;
}
@@ -1535,47 +1530,81 @@ private:
};
// ---------------------------------------------------------------------------
// Xbox Series DirectStorage COM interfaces (IDStorage*X), inferred from call-site
// observation of a project-authorized target build (provenance pending maintainer
// review; not a public contract), layered over the same WorkQueue / StorageFile /
// StatusArray engine. Unimplemented vtable slots log through BX_VTABLE_STUB_LOG
// so any newly reached slot surfaces immediately in bx-cli trace.
// Xbox Series DirectStorage COM interfaces (IDStorage*X), as the authorized GDK header
// dstorage_xs.h declares them (#769), layered over the same WorkQueue / StorageFile /
// StatusArray engine. Methods the engine cannot honour log through BX_VTABLE_STUB_LOG so
// they surface in bx-cli trace.
// ---------------------------------------------------------------------------
constexpr IID kXboxFactoryIid{0x62959d11, 0xd45f, 0x4884, {0xa0, 0xa3, 0xf7, 0x86, 0x2e, 0xa2, 0x43, 0xae}};
// IIDs from dstorage_xs.h. One object answers its interface and the interfaces it extends: a
// factory implements IDStorageFactoryX2 (so X and X1 too), a queue IDStorageQueueX2.
constexpr IID kXboxFactoryIid{0xfb3b54ac, 0xbf82, 0x463a, {0xb7, 0x77, 0x73, 0x19, 0x58, 0x37, 0x86, 0x4d}};
constexpr IID kXboxFactory1Iid{0xc74c2a5b, 0x1e43, 0x46a5, {0xa2, 0x24, 0x91, 0x16, 0x35, 0x8e, 0x11, 0x18}};
constexpr IID kXboxFactory2Iid{0x62959d11, 0xd45f, 0x4884, {0xa0, 0xa3, 0xf7, 0x86, 0x2e, 0xa2, 0x43, 0xae}};
constexpr IID kXboxFileIid{0x43704f9f, 0x27c6, 0x4a9f, {0x88, 0x15, 0xd1, 0x65, 0x27, 0x89, 0x4d, 0xf4}};
constexpr IID kXboxStatusArrayIid{0xcd66d752, 0x2786, 0x44f7, {0x90, 0x70, 0xe2, 0xa6, 0xfd, 0xad, 0x3f, 0x1b}};
constexpr IID kXboxQueueIid{0x3c02cb0c, 0xc050, 0x4195, {0x99, 0xa1, 0xa1, 0xce, 0x94, 0xba, 0x33, 0xc5}};
constexpr IID kXboxQueueIid{0xa3f6649a, 0x8c2c, 0x4b3a, {0x8b, 0x6e, 0x10, 0x18, 0x6a, 0x04, 0xb9, 0xbc}};
constexpr IID kXboxQueue1Iid{0x3c02cb0c, 0xc050, 0x4195, {0x99, 0xa1, 0xa1, 0xce, 0x94, 0xba, 0x33, 0xc5}};
constexpr IID kXboxQueue2Iid{0x3af5c948, 0x6297, 0x426c, {0xbf, 0xfc, 0x8f, 0x18, 0x95, 0x9f, 0xb8, 0x7b}};
bool is_xbox_factory_iid(REFIID riid) {
return IsEqualIID(riid, kXboxFactoryIid) || IsEqualIID(riid, kXboxFactory1Iid) || IsEqualIID(riid, kXboxFactory2Iid);
}
// DSTORAGE_QUEUE_DESC1; DSTORAGE_QUEUE_DESC is its first 24 bytes (no Options).
struct XboxQueueDesc {
UINT64 source_type;
UINT16 capacity;
INT8 priority;
UINT8 reserved_pad[5];
PCSTR name;
UINT64 flags;
UINT64 flags; // DSTORAGE_QUEUE_OPTIONS
};
static_assert(sizeof(XboxQueueDesc) == 32, "XboxQueueDesc must be 32 bytes");
static_assert(sizeof(XboxQueueDesc) == 32, "DSTORAGE_QUEUE_DESC1 is 32 bytes");
static_assert(offsetof(XboxQueueDesc, source_type) == 0x00, "source_type offset");
static_assert(offsetof(XboxQueueDesc, capacity) == 0x08, "capacity offset");
static_assert(offsetof(XboxQueueDesc, priority) == 0x0a, "priority offset");
static_assert(offsetof(XboxQueueDesc, name) == 0x10, "name offset");
static_assert(offsetof(XboxQueueDesc, flags) == 0x18, "flags offset");
constexpr size_t kXboxQueueDescSize = 24; // DSTORAGE_QUEUE_DESC
// DSTORAGE_QUEUE_INFO (Desc is a DSTORAGE_QUEUE_DESC) and DSTORAGE_QUEUE_INFO1 (a DESC1).
struct XboxQueueInfo {
UINT64 source_type;
UINT16 capacity;
INT8 priority;
UINT8 reserved_pad[5];
PCSTR name;
UINT16 empty_slot_count;
UINT16 request_count_until_auto_submit;
};
static_assert(offsetof(XboxQueueInfo, empty_slot_count) == 24 && sizeof(XboxQueueInfo) == 32,
"DSTORAGE_QUEUE_INFO layout");
struct XboxQueueInfo1 {
XboxQueueDesc desc;
UINT16 empty_slot_count;
UINT16 request_count_until_auto_submit;
};
static_assert(offsetof(XboxQueueInfo1, empty_slot_count) == 32 && sizeof(XboxQueueInfo1) == 40,
"DSTORAGE_QUEUE_INFO1 layout");
// DSTORAGE_REQUEST, 0x48 bytes.
struct XboxRequest {
UINT64 options; // +0x00: bit 22 (0x400000) = memory source, bit 0 = compressed
UINT64 options; // +0x00: DSTORAGE_REQUEST_OPTIONS
void* destination; // +0x08: buffer, or the 64 KB page-number array (DestinationIsPhysicalPages)
UINT16 destination_page_offset; // +0x10: offset into the first page (DestinationIsPhysicalPages)
UINT16 reserved12;
UINT32 reserved14;
UINT32 destination_size; // +0x18
UINT32 reserved1c; // +0x1c
void* source_ptr; // +0x20: IXboxDStorageFile* (file) or const void* (memory)
void* source_ptr; // +0x20: IDStorageFileX* (file) or const void* (memory)
UINT64 file_offset; // +0x28
UINT32 source_size; // +0x30
UINT32 reserved34; // +0x34
UINT32 intermediate_size; // +0x34: BCPack bytes when ZlibDecompress and BcpackMode are both set
UINT64 cancellation_tag; // +0x38
PCSTR name; // +0x40
};
static_assert(sizeof(XboxRequest) == 56, "XboxRequest must be 56 bytes");
static_assert(sizeof(XboxRequest) == 0x48, "DSTORAGE_REQUEST must be 0x48 bytes");
static_assert(offsetof(XboxRequest, options) == 0x00, "options offset");
static_assert(offsetof(XboxRequest, destination) == 0x08, "destination offset");
static_assert(offsetof(XboxRequest, destination_page_offset) == 0x10, "destination_page_offset offset");
@@ -1583,6 +1612,26 @@ static_assert(offsetof(XboxRequest, destination_size) == 0x18, "destination_size
static_assert(offsetof(XboxRequest, source_ptr) == 0x20, "source_ptr offset");
static_assert(offsetof(XboxRequest, file_offset) == 0x28, "file_offset offset");
static_assert(offsetof(XboxRequest, source_size) == 0x30, "source_size offset");
static_assert(offsetof(XboxRequest, intermediate_size) == 0x34, "intermediate_size offset");
static_assert(offsetof(XboxRequest, cancellation_tag) == 0x38, "cancellation_tag offset");
static_assert(offsetof(XboxRequest, name) == 0x40, "name offset");
// DSTORAGE_ERROR_RECORD: FailureCount, then FirstFailure { HResult, CommandType, a union of
// the failed command's parameters (Request is the largest: options through Name[64]) }.
struct XboxErrorRecord {
UINT32 failure_count;
HRESULT hresult;
INT32 command_type; // DSTORAGE_COMMAND_TYPE
UINT32 pad;
unsigned char parameters[640];
};
static_assert(offsetof(XboxErrorRecord, hresult) == 4 && offsetof(XboxErrorRecord, command_type) == 8,
"DSTORAGE_ERROR_RECORD header");
static_assert(offsetof(XboxErrorRecord, parameters) == 16 && sizeof(XboxErrorRecord) == 656,
"DSTORAGE_ERROR_RECORD is 656 bytes");
// DSTORAGE_STATS: four 48-byte DSTORAGE_PRIORITY_STATS, two UINT8 and fifteen UINT32.
constexpr size_t kXboxStatsSize = 256;
// DSTORAGE_REQUEST_OPTIONS (authorized GDK documentation): ZlibDecompress:1, BcpackMode:4,
// SwizzleMode:16, DestinationIsPhysicalPages:1, SourceType:1, SourceIsPhysicalPages:1.
@@ -1618,20 +1667,19 @@ void log_request_options(UINT64 options, UINT32 source_size, UINT32 destination_
bx_log_emit(BX_LOG_INFO, "xcrdapi", "dstorage_request_options", detail);
}
// IDStorageFileX: slot 3 Close, slot 4 GetHandle.
struct IXboxDStorageFile : IUnknown {
virtual void STDMETHODCALLTYPE Close() = 0;
virtual HRESULT STDMETHODCALLTYPE GetFileInformation(BY_HANDLE_FILE_INFORMATION* info) = 0;
virtual HRESULT STDMETHODCALLTYPE StubSlot5() = 0;
virtual HRESULT STDMETHODCALLTYPE StubSlot6() = 0;
virtual HANDLE STDMETHODCALLTYPE GetHandle() = 0;
};
// IDStorageStatusArrayX: slot 3 IsComplete, slot 4 GetHResult.
struct IXboxDStorageStatusArray : IUnknown {
virtual bool STDMETHODCALLTYPE IsComplete(UINT32 index) = 0;
virtual HRESULT STDMETHODCALLTYPE GetHResult(UINT32 index) = 0;
virtual HRESULT STDMETHODCALLTYPE StubSlot5() = 0;
virtual HRESULT STDMETHODCALLTYPE StubSlot6() = 0;
};
// IDStorageQueueX (slots 3-11), IDStorageQueueX1 (12), IDStorageQueueX2 (13).
struct IXboxDStorageQueue : IUnknown {
virtual void STDMETHODCALLTYPE EnqueueRequest(const XboxRequest* request) = 0;
virtual void STDMETHODCALLTYPE EnqueueStatus(IXboxDStorageStatusArray* status_array, UINT32 index) = 0;
@@ -1640,25 +1688,22 @@ struct IXboxDStorageQueue : IUnknown {
virtual void STDMETHODCALLTYPE CancelRequestsWithTag(UINT64 mask, UINT64 value) = 0;
virtual void STDMETHODCALLTYPE Close() = 0;
virtual HANDLE STDMETHODCALLTYPE GetErrorEvent() = 0;
virtual void STDMETHODCALLTYPE RetrieveErrorRecord(void* record) = 0;
virtual void STDMETHODCALLTYPE Query(void* info) = 0;
virtual HRESULT STDMETHODCALLTYPE StubSlot12() = 0;
virtual HRESULT STDMETHODCALLTYPE StubSlot13() = 0;
virtual HRESULT STDMETHODCALLTYPE StubSlot14() = 0;
virtual HRESULT STDMETHODCALLTYPE StubSlot15() = 0;
virtual void STDMETHODCALLTYPE RetrieveErrorRecord(XboxErrorRecord* record) = 0;
virtual void STDMETHODCALLTYPE Query(XboxQueueInfo* info) = 0;
virtual void STDMETHODCALLTYPE EnqueueSetEvent(HANDLE handle) = 0;
virtual void STDMETHODCALLTYPE Query1(XboxQueueInfo1* info) = 0;
};
// IDStorageFactoryX (slots 3-8), IDStorageFactoryX1 (9), IDStorageFactoryX2 (10).
struct IXboxDStorageFactory : IUnknown {
virtual HRESULT STDMETHODCALLTYPE CreateQueue(const void* desc, REFIID riid, void** ppv) = 0;
virtual HRESULT STDMETHODCALLTYPE OpenFile(const WCHAR* path, REFIID riid, void** ppv) = 0;
virtual HRESULT STDMETHODCALLTYPE CreateStatusArray(UINT32 capacity, PCSTR name, REFIID riid, void** ppv) = 0;
virtual HRESULT STDMETHODCALLTYPE SetCpuAffinity(UINT64 affinity) = 0;
virtual void STDMETHODCALLTYPE SetDebugFlags(UINT32 flags) = 0;
virtual HRESULT STDMETHODCALLTYPE StubSlot7() = 0;
virtual HRESULT STDMETHODCALLTYPE SetStagingBufferSize(UINT32 size) = 0;
virtual HRESULT STDMETHODCALLTYPE StubSlot9() = 0;
virtual HRESULT STDMETHODCALLTYPE CreateQueueX(const XboxQueueDesc* desc, REFIID riid, void** ppv) = 0;
virtual HRESULT STDMETHODCALLTYPE StubSlot11() = 0;
virtual HRESULT STDMETHODCALLTYPE StubSlot12() = 0;
virtual void STDMETHODCALLTYPE GetStats(void* stats) = 0;
virtual HRESULT STDMETHODCALLTYPE CreateQueue1(const XboxQueueDesc* desc, REFIID riid, void** ppv) = 0;
};
class XboxFile final : public PublicObject<IXboxDStorageFile> {
@@ -1666,16 +1711,20 @@ public:
explicit XboxFile(StorageFile* file) : file_(file) {}
void STDMETHODCALLTYPE Close() override { (void)file_->Close(); }
HRESULT STDMETHODCALLTYPE GetFileInformation(BY_HANDLE_FILE_INFORMATION* info) override {
return file_->GetFileInformation(info);
}
HRESULT STDMETHODCALLTYPE StubSlot5() override {
BX_VTABLE_STUB_LOG("IDStorageFileX", 5u, "Slot5");
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE StubSlot6() override {
BX_VTABLE_STUB_LOG("IDStorageFileX", 6u, "Slot6");
return E_NOTIMPL;
// A new handle the caller closes, opened GENERIC_READ with FILE_SHARE_READ (dstorage_xs.h).
// ReOpenFile gives one without the engine's FILE_FLAG_OVERLAPPED; a duplicate of the engine's
// handle is the fallback. NULL if the file was closed.
HANDLE STDMETHODCALLTYPE GetHandle() override {
HANDLE engine = nullptr;
if (FAILED(file_->GetHandle(&engine)) || !engine) return nullptr;
using ReOpenFileFn = HANDLE(WINAPI*)(HANDLE, DWORD, DWORD, DWORD);
static const auto reopen = reinterpret_cast<ReOpenFileFn>(
reinterpret_cast<void*>(GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "ReOpenFile")));
const HANDLE fresh = reopen ? reopen(engine, GENERIC_READ, FILE_SHARE_READ, 0) : INVALID_HANDLE_VALUE;
if (fresh == INVALID_HANDLE_VALUE) return engine;
CloseHandle(engine);
return fresh;
}
File* inner() const { return file_; }
@@ -1693,14 +1742,6 @@ public:
bool STDMETHODCALLTYPE IsComplete(UINT32 index) override { return array_->GetResult(index) != E_PENDING; }
HRESULT STDMETHODCALLTYPE GetHResult(UINT32 index) override { return array_->GetResult(index); }
HRESULT STDMETHODCALLTYPE StubSlot5() override {
BX_VTABLE_STUB_LOG("IDStorageStatusArrayX", 5u, "Slot5");
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE StubSlot6() override {
BX_VTABLE_STUB_LOG("IDStorageStatusArrayX", 6u, "Slot6");
return E_NOTIMPL;
}
StatusArray* inner() const { return array_; }
@@ -1713,7 +1754,12 @@ private:
class XboxQueue final : public PublicObject<IXboxDStorageQueue> {
public:
XboxQueue(WorkQueue* queue, UINT64 source_type) : queue_(queue), source_type_(source_type) {}
XboxQueue(WorkQueue* queue, const XboxQueueDesc& desc) : queue_(queue), desc_(desc) {
if (desc.name) {
std::snprintf(name_, sizeof(name_), "%s", desc.name);
desc_.name = name_;
}
}
void STDMETHODCALLTYPE EnqueueRequest(const XboxRequest* request) override {
if (!request) {
@@ -1721,11 +1767,12 @@ public:
return;
}
const bool is_memory = (request->options & kXboxRequestSourceMemoryBit) != 0;
if ((is_memory && source_type_ == 0) || (!is_memory && source_type_ != 0)) {
if ((is_memory && desc_.source_type == 0) || (!is_memory && desc_.source_type != 0)) {
reject(E_DSTORAGE_INVALID_SOURCE_TYPE, Kind::request, "EnqueueRequest");
return;
}
log_request_options(request->options, request->source_size, request->destination_size, request->reserved34);
log_request_options(request->options, request->source_size, request->destination_size,
request->intermediate_size);
// BCPack (BcpackMode, DSTORAGE_BCPACK_MODE 1-7) is decoded by the GDK's BCPack.dll when
// BX_BCPACK_DLL names it; combined with zlib, or without the codec, it stays refused.
const UINT bcpack_mode = static_cast<UINT>((request->options & kXboxRequestBcpackMask) >> 1);
@@ -1821,7 +1868,13 @@ public:
}
}
void STDMETHODCALLTYPE CancelRequestsWithTag(UINT64, UINT64) override {
// The header allows cancelled requests to complete anyway, and the engine does not cancel:
// every request still runs. Logged with its tag so the trace shows it.
void STDMETHODCALLTYPE CancelRequestsWithTag(UINT64 mask, UINT64 value) override {
char detail[96];
std::snprintf(detail, sizeof(detail), "mask=0x%llx value=0x%llx: requests still run",
static_cast<unsigned long long>(mask), static_cast<unsigned long long>(value));
bx_log_emit(BX_LOG_INFO, "xcrdapi", "dstorage_cancel_requests", detail);
BX_VTABLE_STUB_LOG("IDStorageQueueX", 7u, "CancelRequestsWithTag");
}
@@ -1829,33 +1882,55 @@ public:
HANDLE STDMETHODCALLTYPE GetErrorEvent() override { return queue_->error_event(); }
void STDMETHODCALLTYPE RetrieveErrorRecord(void*) override {
// The size and layout of the Xbox caller's output are unverified.
// Do not write the public PC record into it.
BX_VTABLE_STUB_LOG("IDStorageQueueX", 10u, "RetrieveErrorRecord");
// FailureCount, FirstFailure.HResult and FirstFailure.CommandType are filled; the failed
// command's parameters are left zeroed, as on the public queue.
void STDMETHODCALLTYPE RetrieveErrorRecord(XboxErrorRecord* record) override {
if (!record) return;
std::memset(record, 0, sizeof(*record));
ErrorRecord errors{};
Kind first = Kind::request;
queue_->take_errors(&errors, &first);
record->failure_count = errors.failure_count > 0xffffffffull ? 0xffffffffu
: static_cast<UINT32>(errors.failure_count);
record->hresult = errors.failure_count ? errors.first_error : S_OK;
record->command_type = errors.failure_count ? static_cast<INT32>(command_type(first))
: static_cast<INT32>(DSTORAGE_COMMAND_TYPE_NONE);
}
void STDMETHODCALLTYPE Query(void*) override { BX_VTABLE_STUB_LOG("IDStorageQueueX", 11u, "Query"); }
HRESULT STDMETHODCALLTYPE StubSlot12() override {
BX_VTABLE_STUB_LOG("IDStorageQueueX", 12u, "Slot12");
return E_NOTIMPL;
void STDMETHODCALLTYPE Query(XboxQueueInfo* info) override {
if (!info) return;
XboxQueueInfo1 full{};
Query1(&full);
std::memset(info, 0, sizeof(*info));
std::memcpy(info, &full.desc, kXboxQueueDescSize);
info->empty_slot_count = full.empty_slot_count;
info->request_count_until_auto_submit = full.request_count_until_auto_submit;
}
HRESULT STDMETHODCALLTYPE StubSlot13() override {
BX_VTABLE_STUB_LOG("IDStorageQueueX", 13u, "Slot13");
return E_NOTIMPL;
void STDMETHODCALLTYPE EnqueueSetEvent(HANDLE handle) override {
if (!handle || handle == INVALID_HANDLE_VALUE) {
reject(E_INVALIDARG, Kind::event, "EnqueueSetEvent");
return;
}
accept(queue_->EnqueueSetEvent(handle), Kind::event, "EnqueueSetEvent");
}
HRESULT STDMETHODCALLTYPE StubSlot14() override {
BX_VTABLE_STUB_LOG("IDStorageQueueX", 14u, "Slot14");
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE StubSlot15() override {
BX_VTABLE_STUB_LOG("IDStorageQueueX", 15u, "Slot15");
return E_NOTIMPL;
void STDMETHODCALLTYPE Query1(XboxQueueInfo1* info) override {
if (!info) return;
UINT empty = 0;
UINT until_auto_submit = 0;
queue_->counts(&empty, &until_auto_submit);
std::memset(info, 0, sizeof(*info));
info->desc = desc_;
info->empty_slot_count = static_cast<UINT16>(empty);
info->request_count_until_auto_submit = static_cast<UINT16>(until_auto_submit);
}
private:
~XboxQueue() override { queue_->Release(); }
bool supports(REFIID riid) const override { return IsEqualIID(riid, kXboxQueueIid); }
bool supports(REFIID riid) const override {
return IsEqualIID(riid, kXboxQueueIid) || IsEqualIID(riid, kXboxQueue1Iid) || IsEqualIID(riid, kXboxQueue2Iid);
}
void reject(HRESULT hr, Kind kind, const char* method) {
char detail[96];
@@ -1876,15 +1951,20 @@ private:
}
WorkQueue* queue_;
UINT64 source_type_;
XboxQueueDesc desc_;
char name_[64] = {};
};
class XboxFactory final : public PublicObject<IXboxDStorageFactory> {
public:
HRESULT STDMETHODCALLTYPE CreateQueue(const void*, REFIID, void** ppv) override {
if (ppv) *ppv = nullptr;
BX_VTABLE_STUB_LOG("IDStorageFactoryX", 3u, "CreateQueue");
return E_NOTIMPL;
// A DSTORAGE_QUEUE_DESC is a DSTORAGE_QUEUE_DESC1 without Options: auto-submit stays on.
HRESULT STDMETHODCALLTYPE CreateQueue(const void* desc, REFIID riid, void** ppv) override {
if (!ppv) return E_POINTER;
*ppv = nullptr;
if (!desc) return E_INVALIDARG;
XboxQueueDesc full{};
std::memcpy(&full, desc, kXboxQueueDescSize);
return CreateQueue1(&full, riid, ppv);
}
HRESULT STDMETHODCALLTYPE OpenFile(const WCHAR* path, REFIID riid, void** ppv) override {
@@ -1926,13 +2006,16 @@ public:
return publish(wrapper, riid, ppv);
}
void STDMETHODCALLTYPE SetDebugFlags(UINT32 flags) override {
if (flags) BX_VTABLE_STUB_LOG("IDStorageFactoryX", 6u, "SetDebugFlags");
// The engine's work runs on the Win32 thread pool, which has no affinity to set.
HRESULT STDMETHODCALLTYPE SetCpuAffinity(UINT64 affinity) override {
char detail[64];
std::snprintf(detail, sizeof(detail), "affinity=0x%llx has no effect", static_cast<unsigned long long>(affinity));
bx_log_emit(BX_LOG_INFO, "xcrdapi", "dstorage_cpu_affinity", detail);
return S_OK;
}
HRESULT STDMETHODCALLTYPE StubSlot7() override {
BX_VTABLE_STUB_LOG("IDStorageFactoryX", 7u, "Slot7");
return E_NOTIMPL;
void STDMETHODCALLTYPE SetDebugFlags(UINT32 flags) override {
if (flags) BX_VTABLE_STUB_LOG("IDStorageFactoryX", 7u, "SetDebugFlags");
}
HRESULT STDMETHODCALLTYPE SetStagingBufferSize(UINT32 size) override {
@@ -1943,12 +2026,15 @@ public:
return S_OK;
}
HRESULT STDMETHODCALLTYPE StubSlot9() override {
BX_VTABLE_STUB_LOG("IDStorageFactoryX", 9u, "Slot9");
return E_NOTIMPL;
// The engine keeps no DSTORAGE_STATS counters: the structure is written as zeros, and the
// call logged so the trace shows that the values are not real.
void STDMETHODCALLTYPE GetStats(void* stats) override {
if (!stats) return;
std::memset(stats, 0, kXboxStatsSize);
BX_VTABLE_STUB_LOG("IDStorageFactoryX1", 9u, "GetStats");
}
HRESULT STDMETHODCALLTYPE CreateQueueX(const XboxQueueDesc* desc, REFIID riid, void** ppv) override {
HRESULT STDMETHODCALLTYPE CreateQueue1(const XboxQueueDesc* desc, REFIID riid, void** ppv) override {
if (!ppv) return E_POINTER;
*ppv = nullptr;
if (!desc) return E_INVALIDARG;
@@ -1958,9 +2044,10 @@ public:
if (desc->source_type > 1) {
return E_DSTORAGE_INVALID_SOURCE_TYPE;
}
/* desc->priority is ignored on purpose: the Xbox priority range is not part of
* the inferred contract, so no value is rejected (the public queue's
* E_DSTORAGE_INVALID_QUEUE_PRIORITY range check is not assumed to apply). */
// DSTORAGE_PRIORITY: LOW (-1) to REALTIME (2) (dstorage_xs.h). Queues are not prioritised.
if (desc->priority < -1 || desc->priority > 2) {
return E_DSTORAGE_INVALID_QUEUE_PRIORITY;
}
const UINT slots = desc->capacity - 1u;
auto* entries = new (std::nothrow) Entry[slots];
if (!entries) return E_OUTOFMEMORY;
@@ -1985,7 +2072,7 @@ public:
queue->Release();
return error;
}
auto* wrapper = new (std::nothrow) XboxQueue(queue, desc->source_type);
auto* wrapper = new (std::nothrow) XboxQueue(queue, *desc);
if (!wrapper) {
queue->Release();
return E_OUTOFMEMORY;
@@ -1993,24 +2080,14 @@ public:
return publish(wrapper, riid, ppv);
}
HRESULT STDMETHODCALLTYPE StubSlot11() override {
BX_VTABLE_STUB_LOG("IDStorageFactoryX", 11u, "Slot11");
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE StubSlot12() override {
BX_VTABLE_STUB_LOG("IDStorageFactoryX", 12u, "Slot12");
return E_NOTIMPL;
}
private:
bool supports(REFIID riid) const override { return IsEqualIID(riid, kXboxFactoryIid); }
bool supports(REFIID riid) const override { return is_xbox_factory_iid(riid); }
};
} // namespace
// Accepts BetterXen's synthetic factory IID and IUnknown (the synthetic factory),
// the public PC IDStorageFactory / IDStorageFactory1, and the inferred Xbox
// IDStorageFactoryX IID. Any other IID is logged with its value so `bx-cli trace`
// the public PC IDStorageFactory / IDStorageFactory1, and the Xbox IDStorageFactoryX, X1 and X2
// IIDs (dstorage_xs.h). Any other IID is logged with its value so `bx-cli trace`
// names the interface a guest asked for.
extern "C" HRESULT WINAPI DStorageGetFactory(REFIID riid, void** ppv) {
if (!ppv) return E_POINTER;
@@ -2019,7 +2096,7 @@ extern "C" HRESULT WINAPI DStorageGetFactory(REFIID riid, void** ppv) {
auto* factory = new (std::nothrow) PublicFactory;
return factory ? publish(factory, riid, ppv) : E_OUTOFMEMORY;
}
if (IsEqualIID(riid, kXboxFactoryIid)) {
if (is_xbox_factory_iid(riid)) {
auto* factory = new (std::nothrow) XboxFactory;
if (!factory) return E_OUTOFMEMORY;
bx_log_emit(BX_LOG_INFO, "xcrdapi", "dstorage_get_factory", "dispatch xbox_com=IDStorageFactoryX");
+90 -18
View File
@@ -1,6 +1,8 @@
/* zlib (RFC 1950) / deflate (RFC 1951) decoder; see zlib_inflate.h. */
#include "zlib_inflate.h"
#include <new>
namespace {
struct Bits {
@@ -84,19 +86,68 @@ constexpr uint16_t kDistBase[30] = {1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65,
257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577};
constexpr uint8_t kDistExtra[30] = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13};
// Writes the whole output into one buffer of `size` bytes.
struct Output {
uint8_t* data;
size_t size;
size_t pos = 0;
bool put(uint8_t byte) {
if (pos >= size) return false;
data[pos++] = byte;
return true;
}
BxInflateResult copy(size_t distance, size_t length) {
if (distance > pos) return BxInflateResult::bad_data;
if (length > size - pos) return BxInflateResult::output_mismatch;
for (size_t i = 0; i < length; ++i, ++pos) data[pos] = data[pos - distance];
return BxInflateResult::ok;
}
size_t produced() const { return pos; }
uint32_t adler() const;
};
BxInflateResult codes(Bits& in, Output& out, const Huffman& lit, const Huffman& dist) {
// Decodes a stream of any length, keeps only its first `limit` bytes at `data`, and checks
// Adler-32 over all of it. Back-references read a 32 KiB ring of the latest output (RFC 1951:
// distances are at most 32768), so memory does not grow with the stream (#769).
struct PrefixOutput {
static constexpr size_t kWindow = 32768;
uint8_t* data;
size_t limit;
uint64_t total = 0;
uint32_t a = 1, b = 0;
uint32_t pending = 0; // bytes summed since the last modulo
uint8_t window[kWindow];
bool put(uint8_t byte) {
if (total < limit) data[total] = byte;
window[total & (kWindow - 1)] = byte;
++total;
a += byte;
b += a;
if (++pending == 5552) { // largest n with no 32-bit overflow before the modulo
a %= 65521u;
b %= 65521u;
pending = 0;
}
return true;
}
BxInflateResult copy(size_t distance, size_t length) {
if (distance > total || distance > kWindow) return BxInflateResult::bad_data;
for (size_t i = 0; i < length; ++i) put(window[(total - distance) & (kWindow - 1)]);
return BxInflateResult::ok;
}
size_t produced() const { return static_cast<size_t>(total); }
uint32_t adler() const { return ((b % 65521u) << 16) | (a % 65521u); }
};
template<class Out>
BxInflateResult codes(Bits& in, Out& out, const Huffman& lit, const Huffman& dist) {
for (;;) {
const int symbol = lit.decode(in);
if (symbol < 0) return in.overrun ? BxInflateResult::truncated : BxInflateResult::bad_data;
if (symbol < 256) {
if (out.pos >= out.size) return BxInflateResult::output_mismatch;
out.data[out.pos++] = static_cast<uint8_t>(symbol);
if (!out.put(static_cast<uint8_t>(symbol))) return BxInflateResult::output_mismatch;
continue;
}
if (symbol == 256) return BxInflateResult::ok;
@@ -108,13 +159,13 @@ BxInflateResult codes(Bits& in, Output& out, const Huffman& lit, const Huffman&
if (ds >= 30) return BxInflateResult::bad_data;
const size_t distance = kDistBase[ds] + in.get(kDistExtra[ds]);
if (in.overrun) return BxInflateResult::truncated;
if (distance > out.pos) return BxInflateResult::bad_data;
if (length > out.size - out.pos) return BxInflateResult::output_mismatch;
for (size_t i = 0; i < length; ++i, ++out.pos) out.data[out.pos] = out.data[out.pos - distance];
const BxInflateResult r = out.copy(distance, length);
if (r != BxInflateResult::ok) return r;
}
}
BxInflateResult fixed_block(Bits& in, Output& out) {
template<class Out>
BxInflateResult fixed_block(Bits& in, Out& out) {
static Huffman lit, dist;
static bool built = [] {
uint8_t lengths[288];
@@ -133,7 +184,8 @@ BxInflateResult fixed_block(Bits& in, Output& out) {
return codes(in, out, lit, dist);
}
BxInflateResult dynamic_block(Bits& in, Output& out) {
template<class Out>
BxInflateResult dynamic_block(Bits& in, Out& out) {
const int hlit = static_cast<int>(in.get(5)) + 257;
const int hdist = static_cast<int>(in.get(5)) + 1;
const int hclen = static_cast<int>(in.get(4)) + 4;
@@ -189,17 +241,19 @@ uint32_t adler32(const uint8_t* data, size_t size) {
return (b << 16) | a;
}
uint32_t Output::adler() const { return adler32(data, pos); }
} // namespace
BxInflateResult inflate_impl(const uint8_t* input, size_t input_size, uint8_t* output, size_t output_size, size_t* produced) {
template<class Out>
BxInflateResult inflate_stream(const uint8_t* input, size_t input_size, Out& out, size_t* produced) {
// RFC 1950 2.2: CMF (method 8 = deflate, window <= 32 KiB), FLG (check bits, no FDICT).
if (!input || input_size < 6 || (!output && output_size)) return BxInflateResult::bad_header;
if (!input || input_size < 6) return BxInflateResult::bad_header;
const uint8_t cmf = input[0], flg = input[1];
if ((cmf & 0x0F) != 8 || (cmf >> 4) > 7 || ((cmf << 8) | flg) % 31 != 0 || (flg & 0x20)) {
return BxInflateResult::bad_header;
}
Bits in{input + 2, input_size - 2};
Output out{output, output_size};
for (;;) {
const uint32_t final_block = in.get(1);
const uint32_t type = in.get(2);
@@ -212,8 +266,9 @@ BxInflateResult inflate_impl(const uint8_t* input, size_t input_size, uint8_t* o
if ((len ^ 0xFFFFu) != nlen) return BxInflateResult::bad_data;
// After aligning, the bit buffer is empty: copy straight from the byte stream.
if (len > in.size - in.pos) return BxInflateResult::truncated;
if (len > out.size - out.pos) return BxInflateResult::output_mismatch;
for (uint32_t i = 0; i < len; ++i) out.data[out.pos++] = in.data[in.pos++];
for (uint32_t i = 0; i < len; ++i) {
if (!out.put(in.data[in.pos++])) return BxInflateResult::output_mismatch;
}
r = BxInflateResult::ok;
} else if (type == 1) {
r = fixed_block(in, out);
@@ -225,8 +280,7 @@ BxInflateResult inflate_impl(const uint8_t* input, size_t input_size, uint8_t* o
if (r != BxInflateResult::ok) return r;
if (final_block) break;
}
if (produced) *produced = out.pos;
else if (out.pos != out.size) return BxInflateResult::output_mismatch;
if (produced) *produced = out.produced();
// RFC 1950: the Adler-32 trailer follows the deflate data, byte-aligned, most significant first.
in.align_to_byte();
const size_t trailer = in.pos - static_cast<size_t>(in.count / 8);
@@ -234,16 +288,34 @@ BxInflateResult inflate_impl(const uint8_t* input, size_t input_size, uint8_t* o
const uint8_t* t = in.data + trailer;
const uint32_t expected = (static_cast<uint32_t>(t[0]) << 24) | (static_cast<uint32_t>(t[1]) << 16) |
(static_cast<uint32_t>(t[2]) << 8) | t[3];
return adler32(output, out.pos) == expected ? BxInflateResult::ok : BxInflateResult::bad_checksum;
return out.adler() == expected ? BxInflateResult::ok : BxInflateResult::bad_checksum;
}
BxInflateResult bx_zlib_inflate(const uint8_t* input, size_t input_size, uint8_t* output, size_t output_size) {
return inflate_impl(input, input_size, output, output_size, nullptr);
if (!output && output_size) return BxInflateResult::bad_header;
Output out{output, output_size};
size_t produced = 0;
const BxInflateResult r = inflate_stream(input, input_size, out, &produced);
if (r == BxInflateResult::ok && produced != output_size) return BxInflateResult::output_mismatch;
return r;
}
BxInflateResult bx_zlib_inflate_any(const uint8_t* input, size_t input_size, uint8_t* output, size_t capacity, size_t* produced) {
*produced = 0;
return inflate_impl(input, input_size, output, capacity, produced);
if (!output && capacity) return BxInflateResult::bad_header;
Output out{output, capacity};
return inflate_stream(input, input_size, out, produced);
}
BxInflateResult bx_zlib_inflate_prefix(const uint8_t* input, size_t input_size, uint8_t* output, size_t prefix_size,
size_t* produced) {
*produced = 0;
if (!output && prefix_size) return BxInflateResult::bad_header;
auto* out = new (std::nothrow) PrefixOutput{output, prefix_size};
if (!out) return BxInflateResult::output_mismatch;
const BxInflateResult r = inflate_stream(input, input_size, *out, produced);
delete out;
return r;
}
const char* bx_inflate_result_name(BxInflateResult result) {
+6
View File
@@ -29,4 +29,10 @@ BxInflateResult bx_zlib_inflate(const uint8_t* input, size_t input_size, uint8_t
(checksum verified over those bytes). */
BxInflateResult bx_zlib_inflate_any(const uint8_t* input, size_t input_size, uint8_t* output, size_t capacity, size_t* produced);
/* Decodes the whole of `input`, checks its Adler-32, writes only its first `prefix_size` bytes to
`output` and reports how many bytes the stream produced. Memory use does not depend on the
stream's length. */
BxInflateResult bx_zlib_inflate_prefix(const uint8_t* input, size_t input_size, uint8_t* output, size_t prefix_size,
size_t* produced);
const char* bx_inflate_result_name(BxInflateResult result);
@@ -198,6 +198,37 @@ int main() {
execute(queue, 1, &lists[3]);
CHECK(becomes(e, 2u, 5000), "case 3: E=%u, expected 2", *e);
// 5. A two-queue handshake: queue 0's list writes F, then waits for G, then writes H; queue 1's
// list waits for F, then writes G. On the console this completes at once. Treating every wait
// as at its list's start made queue 0 wait for G before writing F: each queue held the other
// until the 10 s release (seen on the target build).
void* queue1 = nullptr;
slot<CreateQueueXFn>(dev, kDevCreateCommandQueueX)(dev, &qdesc, __uuidof(ID3D12CommandQueue), &queue1);
void* hs_allocators[2] = {};
void* hs_lists[2] = {make_list(dev, &hs_allocators[0]), make_list(dev, &hs_allocators[1])};
CHECK(queue1 && hs_lists[0] && hs_lists[1], "case 5: second queue and lists");
volatile uint64_t* f = cells + 5;
volatile uint64_t* g = cells + 6;
volatile uint64_t* h = cells + 7;
double case5_ms = -1;
if (queue1 && hs_lists[0] && hs_lists[1]) {
slot<Write64Fn>(hs_lists[0], kListWrite64Bop)(hs_lists[0], va(f), 1, 0, 0);
slot<Wait64Fn>(hs_lists[0], kListWait64)(hs_lists[0], va(g), D3D12_COMPARISON_FUNC_GREATER_EQUAL, 1, 0);
slot<Write64Fn>(hs_lists[0], kListWrite64Bop)(hs_lists[0], va(h), 1, 0, 0);
CHECK(slot<CloseFn>(hs_lists[0], kListClose)(hs_lists[0]) == S_OK, "case 5: list on queue 0 Close");
slot<Wait64Fn>(hs_lists[1], kListWait64)(hs_lists[1], va(f), D3D12_COMPARISON_FUNC_GREATER_EQUAL, 1, 0);
slot<Write64Fn>(hs_lists[1], kListWrite64Bop)(hs_lists[1], va(g), 1, 0, 0);
CHECK(slot<CloseFn>(hs_lists[1], kListClose)(hs_lists[1]) == S_OK, "case 5: list on queue 1 Close");
const ULONGLONG t0 = GetTickCount64();
execute(queue, 1, &hs_lists[0]);
slot<ExecuteFn>(queue1, kQueueExecuteCommandLists)(queue1, 1, &hs_lists[1]);
CHECK(becomes(h, uint64_t{1}, 3000), "case 5: the handshake did not complete within 3 s (F=%llu G=%llu H=%llu)",
static_cast<unsigned long long>(*f), static_cast<unsigned long long>(*g), static_cast<unsigned long long>(*h));
case5_ms = static_cast<double>(GetTickCount64() - t0);
CHECK(*f == 1 && *g == 1, "case 5: F=%llu G=%llu, expected 1 and 1", static_cast<unsigned long long>(*f),
static_cast<unsigned long long>(*g));
}
// 4. No wait ran into the 10 s limit.
const std::string log = read_log();
if (!log.empty()) {
@@ -207,7 +238,12 @@ int main() {
std::printf("note: no BX_LOG_FILE; case 4 did not run\n");
}
std::printf("case 1 Execute: %.1f ms, case 2 Execute: %.1f ms\n", case1_ms, case2_ms);
std::printf("case 1 Execute: %.1f ms, case 2 Execute: %.1f ms, case 5 handshake: %.0f ms\n", case1_ms, case2_ms, case5_ms);
for (int i = 1; i >= 0; --i) {
if (hs_lists[i]) slot<ReleaseFn>(hs_lists[i], kRelease)(hs_lists[i]);
if (hs_allocators[i]) slot<ReleaseFn>(hs_allocators[i], kRelease)(hs_allocators[i]);
}
if (queue1) slot<ReleaseFn>(queue1, kRelease)(queue1);
for (int i = 3; i >= 0; --i) {
slot<ReleaseFn>(lists[i], kRelease)(lists[i]);
slot<ReleaseFn>(allocators[i], kRelease)(allocators[i]);
@@ -52,12 +52,14 @@ struct XboxRequest {
UINT64 file_offset;
UINT32 source_size;
UINT32 reserved34;
UINT64 cancellation_tag; /* DSTORAGE_REQUEST is 0x48 bytes (dstorage_xs.h) */
PCSTR name;
};
static_assert(sizeof(XboxRequest) == 56, "DSTORAGE_REQUEST is 56 bytes");
static_assert(sizeof(XboxRequest) == 0x48, "DSTORAGE_REQUEST is 0x48 bytes (dstorage_xs.h)");
struct IXboxDStorageFile : IUnknown {
virtual void STDMETHODCALLTYPE Close() = 0;
virtual HRESULT STDMETHODCALLTYPE GetFileInformation(BY_HANDLE_FILE_INFORMATION* info) = 0;
virtual HANDLE STDMETHODCALLTYPE GetHandle() = 0;
};
struct IXboxDStorageStatusArray : IUnknown {
@@ -78,10 +80,10 @@ struct IXboxDStorageFactory : IUnknown {
virtual HRESULT STDMETHODCALLTYPE CreateQueue(const void* desc, REFIID riid, void** ppv) = 0;
virtual HRESULT STDMETHODCALLTYPE OpenFile(const WCHAR* path, REFIID riid, void** ppv) = 0;
virtual HRESULT STDMETHODCALLTYPE CreateStatusArray(UINT32 capacity, PCSTR name, REFIID riid, void** ppv) = 0;
virtual HRESULT STDMETHODCALLTYPE SetCpuAffinity(UINT64 affinity) = 0;
virtual void STDMETHODCALLTYPE SetDebugFlags(UINT32 flags) = 0;
virtual HRESULT STDMETHODCALLTYPE StubSlot7() = 0;
virtual HRESULT STDMETHODCALLTYPE SetStagingBufferSize(UINT32 size) = 0;
virtual HRESULT STDMETHODCALLTYPE StubSlot9() = 0;
virtual void STDMETHODCALLTYPE GetStats(void* stats) = 0;
virtual HRESULT STDMETHODCALLTYPE CreateQueueX(const XboxQueueDesc* desc, REFIID riid, void** ppv) = 0;
};
@@ -52,14 +52,16 @@ struct XboxRequest {
UINT64 file_offset;
UINT32 source_size;
UINT32 reserved34;
UINT64 cancellation_tag; /* DSTORAGE_REQUEST is 0x48 bytes (dstorage_xs.h) */
PCSTR name;
};
static_assert(sizeof(XboxRequest) == 56, "DSTORAGE_REQUEST is 56 bytes");
static_assert(sizeof(XboxRequest) == 0x48, "DSTORAGE_REQUEST is 0x48 bytes (dstorage_xs.h)");
static_assert(offsetof(XboxRequest, destination_page_offset) == 0x10, "DestinationPageOffset at +0x10");
static_assert(offsetof(XboxRequest, destination_size) == 0x18, "DestinationSize at +0x18");
struct IXboxDStorageFile : IUnknown {
virtual void STDMETHODCALLTYPE Close() = 0;
virtual HRESULT STDMETHODCALLTYPE GetFileInformation(BY_HANDLE_FILE_INFORMATION* info) = 0;
virtual HANDLE STDMETHODCALLTYPE GetHandle() = 0;
};
struct IXboxDStorageStatusArray : IUnknown {
@@ -80,10 +82,10 @@ struct IXboxDStorageFactory : IUnknown {
virtual HRESULT STDMETHODCALLTYPE CreateQueue(const void* desc, REFIID riid, void** ppv) = 0;
virtual HRESULT STDMETHODCALLTYPE OpenFile(const WCHAR* path, REFIID riid, void** ppv) = 0;
virtual HRESULT STDMETHODCALLTYPE CreateStatusArray(UINT32 capacity, PCSTR name, REFIID riid, void** ppv) = 0;
virtual HRESULT STDMETHODCALLTYPE SetCpuAffinity(UINT64 affinity) = 0;
virtual void STDMETHODCALLTYPE SetDebugFlags(UINT32 flags) = 0;
virtual HRESULT STDMETHODCALLTYPE StubSlot7() = 0;
virtual HRESULT STDMETHODCALLTYPE SetStagingBufferSize(UINT32 size) = 0;
virtual HRESULT STDMETHODCALLTYPE StubSlot9() = 0;
virtual void STDMETHODCALLTYPE GetStats(void* stats) = 0;
virtual HRESULT STDMETHODCALLTYPE CreateQueueX(const XboxQueueDesc* desc, REFIID riid, void** ppv) = 0;
};
+25 -18
View File
@@ -37,11 +37,13 @@ struct XboxRequest {
UINT64 file_offset;
UINT32 source_size;
UINT32 reserved34;
UINT64 cancellation_tag; /* DSTORAGE_REQUEST is 0x48 bytes (dstorage_xs.h) */
PCSTR name;
};
struct IXboxDStorageFile : IUnknown {
virtual void STDMETHODCALLTYPE Close() = 0;
virtual HRESULT STDMETHODCALLTYPE GetFileInformation(BY_HANDLE_FILE_INFORMATION* info) = 0;
virtual HANDLE STDMETHODCALLTYPE GetHandle() = 0;
};
struct IXboxDStorageStatusArray : IUnknown {
@@ -65,10 +67,10 @@ struct IXboxDStorageFactory : IUnknown {
virtual HRESULT STDMETHODCALLTYPE CreateQueue(const void* desc, REFIID riid, void** ppv) = 0;
virtual HRESULT STDMETHODCALLTYPE OpenFile(const WCHAR* path, REFIID riid, void** ppv) = 0;
virtual HRESULT STDMETHODCALLTYPE CreateStatusArray(UINT32 capacity, PCSTR name, REFIID riid, void** ppv) = 0;
virtual HRESULT STDMETHODCALLTYPE SetCpuAffinity(UINT64 affinity) = 0;
virtual void STDMETHODCALLTYPE SetDebugFlags(UINT32 flags) = 0;
virtual HRESULT STDMETHODCALLTYPE StubSlot7() = 0;
virtual HRESULT STDMETHODCALLTYPE SetStagingBufferSize(UINT32 size) = 0;
virtual HRESULT STDMETHODCALLTYPE StubSlot9() = 0;
virtual void STDMETHODCALLTYPE GetStats(void* stats) = 0;
virtual HRESULT STDMETHODCALLTYPE CreateQueueX(const XboxQueueDesc* desc, REFIID riid, void** ppv) = 0;
};
@@ -250,10 +252,12 @@ int main() {
hr = factory->OpenFile(temp_file, kXboxFileIid, reinterpret_cast<void**>(&file));
check(hr == S_OK && file != nullptr, "OpenFile(Xbox) must succeed (hr=0x%08lx)", static_cast<unsigned long>(hr));
if (file) {
BY_HANDLE_FILE_INFORMATION info{};
hr = file->GetFileInformation(&info);
check(hr == S_OK && info.nFileSizeLow == sizeof(payload) && info.nFileSizeHigh == 0,
"GetFileInformation must report exact payload size");
/* Slot 4: GetHandle, a new GENERIC_READ handle the caller closes (dstorage_xs.h). */
HANDLE own = file->GetHandle();
LARGE_INTEGER size{};
check(own && own != INVALID_HANDLE_VALUE && GetFileSizeEx(own, &size) && size.QuadPart == sizeof(payload),
"GetHandle must return a handle reporting the exact payload size");
if (own && own != INVALID_HANDLE_VALUE) CloseHandle(own);
}
/* Slot 5: CreateStatusArray. */
@@ -364,15 +368,20 @@ int main() {
}
DeleteFileW(zlib_file);
/* The Xbox output layout is unverified. A PC-sized test buffer
* detects any accidental writes while keeping the test memory safe. */
DSTORAGE_ERROR_RECORD record;
std::memset(&record, 0xa5, sizeof(record));
unsigned char before[sizeof(record)];
std::memcpy(before, &record, sizeof(record));
file_q->RetrieveErrorRecord(&record);
check(std::memcmp(&record, before, sizeof(record)) == 0,
"Xbox RetrieveErrorRecord must leave the caller's buffer unchanged");
/* DSTORAGE_ERROR_RECORD (dstorage_xs.h) is 656 bytes: FailureCount, then FirstFailure's
* HResult and CommandType. The corrupted zlib request above failed on this queue. */
unsigned char record[656 + 16];
std::memset(record, 0xa5, sizeof(record));
file_q->RetrieveErrorRecord(record);
UINT32 failures = 0;
HRESULT first_hr = S_OK;
std::memcpy(&failures, record, sizeof(failures));
std::memcpy(&first_hr, record + 4, sizeof(first_hr));
check(failures >= 1 && FAILED(first_hr), "Xbox RetrieveErrorRecord must report the failed request (count=%u hr=0x%08lx)",
failures, static_cast<unsigned long>(first_hr));
bool tail_untouched = true;
for (size_t i = 656; i < sizeof(record); ++i) tail_untouched = tail_untouched && record[i] == 0xa5;
check(tail_untouched, "Xbox RetrieveErrorRecord must write no more than 656 bytes");
file_q->Close();
file_q->Release();
}
@@ -622,8 +631,6 @@ int main() {
check(file_contains(log_path, "IDStorageQueueX[3]::EnqueueRequest_bcpack"),
"log must record the BCPack request stub");
check(file_contains(log_path, "dstorage_zlib_failed"), "log must record the corrupted zlib stream");
check(file_contains(log_path, "IDStorageQueueX[10]::RetrieveErrorRecord"),
"log must record the unimplemented Xbox error-record output");
const auto check_rejection = [&](const char* method, HRESULT hr) {
char needle[96];
std::snprintf(needle, sizeof(needle), "xbox %s hr=0x%08lx", method, static_cast<unsigned long>(hr));
@@ -0,0 +1,4 @@
# Xbox DirectStorage slots as dstorage_xs.h declares them (#769).
add_executable(test_xcrdapi_xbox_slots main.cpp)
target_include_directories(test_xcrdapi_xbox_slots PRIVATE "${BX_ABI_INCLUDE_DIR}" "${BX_ROOT_DIR}/shims/xcrdapi/dstorage")
target_link_libraries(test_xcrdapi_xbox_slots PRIVATE xcrdapi bx_runtime_veh kernel32)
@@ -0,0 +1,338 @@
/*
* Xbox DirectStorage slots as the authorized GDK header dstorage_xs.h declares them (#769).
* Expected values come from the header:
* IDStorageFactoryX 3 CreateQueue(DSTORAGE_QUEUE_DESC*), 4 OpenFile, 5 CreateStatusArray,
* 6 SetCpuAffinity(UINT64) -> HRESULT, 7 SetDebugFlags(UINT32),
* 8 SetStagingBufferSize; X1: 9 GetStats(DSTORAGE_STATS*);
* X2: 10 CreateQueue1(DSTORAGE_QUEUE_DESC1*).
* IDStorageFileX 3 Close, 4 GetHandle (a new GENERIC_READ handle the caller closes).
* IDStorageQueueX 3-11 (... 10 RetrieveErrorRecord, 11 Query(DSTORAGE_QUEUE_INFO*));
* X1: 12 EnqueueSetEvent(HANDLE); X2: 13 Query1(DSTORAGE_QUEUE_INFO1*).
* DSTORAGE_PRIORITY LOW -1 .. REALTIME 2.
* IIDs of the factory X/X1/X2 and queue X/X1/X2 interfaces.
* Also: a zlib stream that holds far more than the destination delivers its first
* DestinationSize bytes without a buffer for the whole stream.
*/
#include <windows.h>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <vector>
/* Public DirectStorage error codes (SDK 1.4.0, MIT). */
#include "dstorageerr.h"
extern "C" __declspec(dllimport) HRESULT WINAPI DStorageGetFactory(REFIID riid, void** ppv);
// The interfaces have external linkage: in an anonymous namespace with no class deriving from them
// in this file, GCC may resolve their calls to the pure-virtual stubs.
struct QueueDesc1 {
UINT64 source_type;
UINT16 capacity;
INT8 priority;
UINT8 pad[5];
PCSTR name;
UINT64 options;
};
static_assert(sizeof(QueueDesc1) == 32);
struct Request {
UINT64 options;
void* destination;
UINT64 destination_page_offset;
UINT32 destination_size;
UINT32 pad1c;
const void* source;
UINT64 file_offset;
UINT32 source_size;
UINT32 intermediate_size;
UINT64 cancellation_tag;
PCSTR name;
};
static_assert(sizeof(Request) == 0x48);
struct IFileX : IUnknown {
virtual void STDMETHODCALLTYPE Close() = 0;
virtual HANDLE STDMETHODCALLTYPE GetHandle() = 0;
};
struct IStatusX : IUnknown {
virtual bool STDMETHODCALLTYPE IsComplete(UINT32 index) = 0;
virtual HRESULT STDMETHODCALLTYPE GetHResult(UINT32 index) = 0;
};
struct IQueueX2 : IUnknown {
virtual void STDMETHODCALLTYPE EnqueueRequest(const Request* request) = 0;
virtual void STDMETHODCALLTYPE EnqueueStatus(IStatusX* status, UINT32 index) = 0;
virtual void STDMETHODCALLTYPE EnqueueSignal(void* fence, UINT64 value) = 0;
virtual void STDMETHODCALLTYPE Submit() = 0;
virtual void STDMETHODCALLTYPE CancelRequestsWithTag(UINT64 mask, UINT64 value) = 0;
virtual void STDMETHODCALLTYPE Close() = 0;
virtual HANDLE STDMETHODCALLTYPE GetErrorEvent() = 0;
virtual void STDMETHODCALLTYPE RetrieveErrorRecord(void* record) = 0;
virtual void STDMETHODCALLTYPE Query(void* info) = 0;
virtual void STDMETHODCALLTYPE EnqueueSetEvent(HANDLE handle) = 0;
virtual void STDMETHODCALLTYPE Query1(void* info) = 0;
};
struct IFactoryX2 : IUnknown {
virtual HRESULT STDMETHODCALLTYPE CreateQueue(const void* desc, REFIID riid, void** ppv) = 0;
virtual HRESULT STDMETHODCALLTYPE OpenFile(const WCHAR* path, REFIID riid, void** ppv) = 0;
virtual HRESULT STDMETHODCALLTYPE CreateStatusArray(UINT32 capacity, PCSTR name, REFIID riid, void** ppv) = 0;
virtual HRESULT STDMETHODCALLTYPE SetCpuAffinity(UINT64 affinity) = 0;
virtual void STDMETHODCALLTYPE SetDebugFlags(UINT32 flags) = 0;
virtual HRESULT STDMETHODCALLTYPE SetStagingBufferSize(UINT32 size) = 0;
virtual void STDMETHODCALLTYPE GetStats(void* stats) = 0;
virtual HRESULT STDMETHODCALLTYPE CreateQueue1(const QueueDesc1* desc, REFIID riid, void** ppv) = 0;
};
namespace {
// dstorage_xs.h IIDs.
constexpr IID kFactoryX{0xfb3b54ac, 0xbf82, 0x463a, {0xb7, 0x77, 0x73, 0x19, 0x58, 0x37, 0x86, 0x4d}};
constexpr IID kFactoryX1{0xc74c2a5b, 0x1e43, 0x46a5, {0xa2, 0x24, 0x91, 0x16, 0x35, 0x8e, 0x11, 0x18}};
constexpr IID kFactoryX2{0x62959d11, 0xd45f, 0x4884, {0xa0, 0xa3, 0xf7, 0x86, 0x2e, 0xa2, 0x43, 0xae}};
constexpr IID kFileX{0x43704f9f, 0x27c6, 0x4a9f, {0x88, 0x15, 0xd1, 0x65, 0x27, 0x89, 0x4d, 0xf4}};
constexpr IID kStatusX{0xcd66d752, 0x2786, 0x44f7, {0x90, 0x70, 0xe2, 0xa6, 0xfd, 0xad, 0x3f, 0x1b}};
constexpr IID kQueueX{0xa3f6649a, 0x8c2c, 0x4b3a, {0x8b, 0x6e, 0x10, 0x18, 0x6a, 0x04, 0xb9, 0xbc}};
constexpr IID kQueueX1{0x3c02cb0c, 0xc050, 0x4195, {0x99, 0xa1, 0xa1, 0xce, 0x94, 0xba, 0x33, 0xc5}};
constexpr IID kQueueX2{0x3af5c948, 0x6297, 0x426c, {0xbf, 0xfc, 0x8f, 0x18, 0x95, 0x9f, 0xb8, 0x7b}};
// DSTORAGE_REQUEST_OPTIONS: ZlibDecompress bit 0, SourceType bit 22.
constexpr UINT64 kZlib = 1;
constexpr UINT64 kSourceMemory = 1ull << 22;
constexpr HRESULT kInvalidPriority = E_DSTORAGE_INVALID_QUEUE_PRIORITY;
int g_failed = 0;
#define CHECK(cond, ...) \
do { \
if (!(cond)) { \
++g_failed; \
std::fprintf(stderr, "FAIL: test_xcrdapi_xbox_slots:%d: ", __LINE__); \
std::fprintf(stderr, __VA_ARGS__); \
std::fprintf(stderr, "\n"); \
} \
} while (0)
bool wait_complete(IStatusX* status, UINT32 index) {
for (int i = 0; i < 1000 && !status->IsComplete(index); ++i) Sleep(5);
return status->IsComplete(index);
}
// RFC 1950/1951 by hand: one fixed-Huffman block holding a literal 0 and `matches` copies of
// (length 258, distance 1), so the stream expands to 1 + 258 * matches zero bytes.
struct BitWriter {
std::vector<uint8_t> bytes;
uint32_t buffer = 0;
int count = 0;
void bits(uint32_t value, int n) { // least significant bit first
for (int i = 0; i < n; ++i) {
buffer |= ((value >> i) & 1u) << count;
if (++count == 8) {
bytes.push_back(static_cast<uint8_t>(buffer));
buffer = 0;
count = 0;
}
}
}
void huffman(uint32_t code, int n) { // Huffman codes are packed most significant bit first
for (int i = n - 1; i >= 0; --i) bits((code >> i) & 1u, 1);
}
void flush() {
if (count) bytes.push_back(static_cast<uint8_t>(buffer));
buffer = 0;
count = 0;
}
};
std::vector<uint8_t> zero_stream(uint32_t matches, size_t* produced) {
BitWriter w;
w.bytes = {0x78, 0x01};
w.bits(1, 1); // BFINAL
w.bits(1, 2); // BTYPE = 01, fixed Huffman
w.huffman(0x30, 8); // literal 0: codes 0x30 + value, 8 bits
for (uint32_t i = 0; i < matches; ++i) {
w.huffman(0xC0 + (285 - 280), 8); // length symbol 285 (258, no extra bits)
w.huffman(0, 5); // distance code 0 (distance 1)
}
w.huffman(0, 7); // end of block (256)
w.flush();
const uint64_t n = 1 + 258ull * matches;
const uint32_t adler = (static_cast<uint32_t>(n % 65521u) << 16) | 1u; // all zeros: a = 1, b = n
for (int shift = 24; shift >= 0; shift -= 8) w.bytes.push_back(static_cast<uint8_t>(adler >> shift));
*produced = static_cast<size_t>(n);
return w.bytes;
}
} // namespace
int main() {
// Every factory IID gives the factory.
IFactoryX2* factory = nullptr;
for (const IID* iid : {&kFactoryX, &kFactoryX1, &kFactoryX2}) {
IFactoryX2* f = nullptr;
const HRESULT hr = DStorageGetFactory(*iid, reinterpret_cast<void**>(&f));
CHECK(hr == S_OK && f, "DStorageGetFactory(factory IID %08lx) hr=0x%08lx", static_cast<unsigned long>(iid->Data1),
static_cast<unsigned long>(hr));
if (f && !factory) factory = f;
else if (f) f->Release();
}
if (!factory) return 1;
// Slot 6 SetCpuAffinity returns an HRESULT; slot 7 SetDebugFlags; slot 8 SetStagingBufferSize.
CHECK(factory->SetCpuAffinity(0x3) == S_OK, "SetCpuAffinity must return S_OK");
factory->SetDebugFlags(0);
CHECK(factory->SetStagingBufferSize(16u * 1048576u) == S_OK, "SetStagingBufferSize");
// Slot 9 GetStats writes the 256-byte DSTORAGE_STATS and nothing past it.
unsigned char stats[256 + 16];
std::memset(stats, 0xA5, sizeof(stats));
factory->GetStats(stats);
bool stats_written = true, tail_kept = true;
for (size_t i = 0; i < 256; ++i) stats_written = stats_written && stats[i] != 0xA5;
for (size_t i = 256; i < sizeof(stats); ++i) tail_kept = tail_kept && stats[i] == 0xA5;
CHECK(stats_written && tail_kept, "GetStats must write exactly 256 bytes");
// Slot 10 CreateQueue1 checks DSTORAGE_PRIORITY.
QueueDesc1 desc{};
desc.source_type = 1; // memory
desc.capacity = 128;
desc.priority = 3;
desc.name = "slots";
IQueueX2* queue = nullptr;
CHECK(factory->CreateQueue1(&desc, kQueueX1, reinterpret_cast<void**>(&queue)) == kInvalidPriority && !queue,
"priority 3 must fail with E_DSTORAGE_INVALID_QUEUE_PRIORITY");
desc.priority = -1;
desc.options = 1; // AutoSubmitDisabled
HRESULT hr = factory->CreateQueue1(&desc, kQueueX2, reinterpret_cast<void**>(&queue));
CHECK(hr == S_OK && queue, "CreateQueue1(priority LOW) hr=0x%08lx", static_cast<unsigned long>(hr));
if (!queue) return 1;
for (const IID* iid : {&kQueueX, &kQueueX1, &kQueueX2}) {
IUnknown* other = nullptr;
CHECK(queue->QueryInterface(*iid, reinterpret_cast<void**>(&other)) == S_OK && other,
"queue must answer IID %08lx", static_cast<unsigned long>(iid->Data1));
if (other) other->Release();
}
// Slot 11 Query (DSTORAGE_QUEUE_INFO: a 24-byte DESC, then EmptySlotCount, RequestCountUntilAutoSubmit).
unsigned char info[32 + 8];
std::memset(info, 0xA5, sizeof(info));
queue->Query(info);
UINT16 capacity = 0, empty = 0;
INT8 priority = 0;
PCSTR name = nullptr;
std::memcpy(&capacity, info + 8, 2);
std::memcpy(&priority, info + 10, 1);
std::memcpy(&name, info + 16, 8);
std::memcpy(&empty, info + 24, 2);
CHECK(capacity == 128 && priority == -1 && name && std::strcmp(name, "slots") == 0 && empty == 127,
"Query: capacity=%u priority=%d empty=%u", capacity, priority, empty);
bool info_tail = true;
for (size_t i = 32; i < sizeof(info); ++i) info_tail = info_tail && info[i] == 0xA5;
CHECK(info_tail, "Query must write exactly 32 bytes");
// Slot 13 Query1 (DSTORAGE_QUEUE_INFO1: a 32-byte DESC1 with Options, then the counts).
unsigned char info1[40];
queue->Query1(info1);
UINT64 options = 0;
std::memcpy(&options, info1 + 24, 8);
std::memcpy(&empty, info1 + 32, 2);
CHECK(options == 1 && empty == 127, "Query1: options=%llu empty=%u", static_cast<unsigned long long>(options), empty);
// Slot 12 EnqueueSetEvent: the event is set once the commands before it are done.
static const char kText[] = "event after request";
char copy[sizeof(kText)] = {};
Request request{};
request.options = kSourceMemory;
request.destination = copy;
request.destination_size = sizeof(kText);
request.source = kText;
request.source_size = sizeof(kText);
HANDLE done = CreateEventW(nullptr, TRUE, FALSE, nullptr);
queue->EnqueueRequest(&request);
queue->EnqueueSetEvent(done);
CHECK(WaitForSingleObject(done, 0) == WAIT_TIMEOUT, "AutoSubmitDisabled: nothing runs before Submit");
queue->Submit();
CHECK(WaitForSingleObject(done, 5000) == WAIT_OBJECT_0, "EnqueueSetEvent must set the event");
CHECK(std::memcmp(copy, kText, sizeof(kText)) == 0, "the request before the event must be done");
CloseHandle(done);
// A zlib stream holding about 8 MiB, read into a 64 KiB destination, delivers its first 64 KiB.
size_t produced = 0;
const std::vector<uint8_t> stream = zero_stream(32512, &produced);
std::vector<uint8_t> destination(65536, 0xCC);
IStatusX* status = nullptr;
CHECK(factory->CreateStatusArray(4, "slots", kStatusX, reinterpret_cast<void**>(&status)) == S_OK && status,
"CreateStatusArray");
if (status) {
Request partial{};
partial.options = kSourceMemory | kZlib;
partial.destination = destination.data();
partial.destination_size = static_cast<UINT32>(destination.size());
partial.source = stream.data();
partial.source_size = static_cast<UINT32>(stream.size());
CHECK(stream.size() < destination.size() && produced > 64 * destination.size() + 0x40000,
"the stream must be smaller than the destination and expand past the old buffer");
queue->EnqueueRequest(&partial);
queue->EnqueueStatus(status, 0);
queue->Submit();
CHECK(wait_complete(status, 0) && status->GetHResult(0) == S_OK, "partial zlib read hr=0x%08lx",
static_cast<unsigned long>(status->GetHResult(0)));
bool zeros = true;
for (uint8_t b : destination) zeros = zeros && b == 0;
CHECK(zeros, "the first 64 KiB of the stream must be delivered");
}
// Slot 3 CreateQueue takes a 24-byte DSTORAGE_QUEUE_DESC (no Options).
unsigned char short_desc[24 + 8];
std::memset(short_desc, 0xEE, sizeof(short_desc)); // bytes past the DESC must not be read as Options
std::memcpy(short_desc, &desc, 24);
IQueueX2* plain = nullptr;
hr = factory->CreateQueue(short_desc, kQueueX, reinterpret_cast<void**>(&plain));
CHECK(hr == S_OK && plain, "CreateQueue(DSTORAGE_QUEUE_DESC) hr=0x%08lx", static_cast<unsigned long>(hr));
if (plain) {
unsigned char plain_info[40];
plain->Query1(plain_info);
std::memcpy(&options, plain_info + 24, 8);
CHECK(options == 0, "a queue from CreateQueue has no Options (got %llu)", static_cast<unsigned long long>(options));
plain->Close();
plain->Release();
}
// IDStorageFileX slot 4 GetHandle: a new handle the caller closes, valid after the file object.
WCHAR dir[MAX_PATH], path[MAX_PATH];
GetTempPathW(MAX_PATH, dir);
GetTempFileNameW(dir, L"bxs", 0, path);
HANDLE writer = CreateFileW(path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
DWORD written = 0;
WriteFile(writer, kText, sizeof(kText), &written, nullptr);
CloseHandle(writer);
IFileX* file = nullptr;
CHECK(factory->OpenFile(path, kFileX, reinterpret_cast<void**>(&file)) == S_OK && file, "OpenFile");
if (file) {
HANDLE own = file->GetHandle();
CHECK(own && own != INVALID_HANDLE_VALUE, "GetHandle must return a handle");
file->Close();
file->Release();
LARGE_INTEGER size{};
char head[4] = {};
DWORD got = 0;
CHECK(own && GetFileSizeEx(own, &size) && size.QuadPart == sizeof(kText), "the handle reports the file size");
CHECK(own && ReadFile(own, head, sizeof(head), &got, nullptr) && got == sizeof(head) &&
std::memcmp(head, kText, sizeof(head)) == 0,
"the handle reads the file synchronously after the file object is gone");
if (own && own != INVALID_HANDLE_VALUE) CloseHandle(own);
}
DeleteFileW(path);
if (status) status->Release();
queue->Close();
queue->Release();
factory->Release();
if (g_failed) {
std::fprintf(stderr, "FAIL: test_xcrdapi_xbox_slots (%d failed)\n", g_failed);
return 1;
}
std::puts("PASS: test_xcrdapi_xbox_slots");
return 0;
}