DirectStorage: refuse unpaged buffers over 32 MiB, count stats at submit, /EHa under clang-cl

Review fixes for #4348 (Flyander, AirKyzzZ):
- DSTORAGE_REQUEST allows a buffer over 32 MiB only with 64 KiB or 2 MiB
  pages, which are not implemented yet, so such a request now fails with
  E_DSTORAGE_REQUEST_TOO_LARGE before any memory is touched.
- TotalRequestCount and the byte totals grow when a request is submitted,
  not when it is enqueued, and PendingRequestCount counts the request the
  worker is processing (DSTORAGE_PRIORITY_STATS).
- dstorage.cpp is built with /EHa under clang-cl, so guarded_move's __try
  catches an access violation in a title's buffer there too.

Tests: an over-limit and an at-limit 32 MiB copy, and stats checked
before Submit and while a copy is held on a guard page. The three new
failing checks fail with the previous shim.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
mariuslozo-boop
2026-11-23 06:37:39 +01:00
parent d9a52b5520
commit ac1843da2e
4 changed files with 148 additions and 11 deletions

View File

@ -59,7 +59,10 @@ The first boot with the executable settles most of this: the dry-run report show
`SetDebugFlags` and `SetCpuAffinity` are stored only (a console core mask means nothing on the host).
`SetStagingBufferSize` accepts 0, 16, 20, 24, 28 and 32 MiB, fails with `E_DSTORAGE_INVALID_STAGING_BUFFER_SIZE`
otherwise and with `E_DSTORAGE_STAGING_BUFFER_LOCKED` while a queue or file exists; there is no staging buffer.
`GetStats` reports the counts the shim keeps (queues per priority, requests, bytes, files, errors). A bad
`GetStats` reports the counts the shim keeps (queues per priority, requests, bytes, files, errors). As
`DSTORAGE_PRIORITY_STATS` defines them, `TotalRequestCount` and the byte totals grow when a request is submitted
(not when it is enqueued), and `PendingRequestCount` counts the requests the worker is processing; status and fence
entries are counted when they are enqueued. A bad
argument (a null pointer, an invalid queue desc or staging size) is logged once per method and kind, so a wrong
vtable guess shows up in the log as arguments that make no sense for the method.
- **Files**: `OpenFile` goes through the registry's `kernel32.dll!CreateFileW`, the shim in `file_system.cpp`, so a
@ -87,11 +90,14 @@ The first boot with the executable settles most of this: the dry-run report show
4. BCPack mode above 7, swizzle mode above 4 (`_INVALID_BCPACK_MODE`, `_INVALID_SWIZZLE_MODE`), then zlib, BCPack
or swizzle, then physical pages (`E_NOTIMPL`, logged once: later PRs);
5. an `IntermediateSize` without zlib and BCPack (`_INVALID_INTERMEDIATE_SIZE`), `DestinationSize` other than
`SourceSize` (`_INVALID_DESTINATION_SIZE`), more than 1 GiB in total (`_REQUEST_TOO_LARGE`);
`SourceSize` (`_INVALID_DESTINATION_SIZE`), more than 1 GiB in total, then a buffer over 32 MiB
(`_REQUEST_TOO_LARGE` for both: `DSTORAGE_REQUEST` allows a buffer over 32 MiB only with 64 KiB or 2 MiB pages,
which are not implemented yet);
6. a null destination, a null source (memory) or a null file (`E_INVALIDARG`), a closed file (`_FILE_NOT_OPEN`);
7. a zero size: a success that touches no memory (an assumption: the reference does not say);
8. a range past the end of the file (`E_DSTORAGE_END_OF_FILE`), then a destination or source the process cannot
access (`E_DSTORAGE_ACCESS_VIOLATION`; the worker survives it).
access (`E_DSTORAGE_ACCESS_VIOLATION`; the worker survives it). This needs asynchronous exceptions under
clang-cl, so `runtime/CMakeLists.txt` builds `dstorage.cpp` with `/EHa` there; MSVC always catches it.
- **Cancel**: `CancelRequestsWithTag(mask, value)` marks every request enqueued before the call and not yet started
whose `(CancellationTag & mask) == value`. A cancelled request completes as a success without reading and is not
counted as a failure, as the overview and the reference say, even when it also had an error found at enqueue.

View File

@ -116,6 +116,10 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME)
shims/process.cpp
shims/dstorage.cpp
)
# dstorage.cpp's guarded_move turns an access violation in a title's buffer into E_DSTORAGE_ACCESS_VIOLATION with
# __try. MSVC always catches it; clang-cl only with asynchronous exceptions (as for tiny_dll below). A source file
# property, so gta6rt and dstorage_test both get it.
set_source_files_properties(shims/dstorage.cpp PROPERTIES COMPILE_OPTIONS "$<$<CXX_COMPILER_ID:Clang>:/EHa>")
add_dependencies(gta6rt gta6rt_tls_host)
target_compile_definitions(gta6rt PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE)
target_compile_options(gta6rt PRIVATE /W4 /permissive- /utf-8)

View File

@ -443,6 +443,7 @@ struct Entry {
File* file = nullptr; // a reference, for a file request naming a live file
bool file_counted = false; // the file's pending count was raised at submit
bool cancelled = false; // CancelRequestsWithTag matched it before it started
bool counted = false; // a request the title passed: counted in the statistics when it is submitted
HRESULT enqueue_error = S_OK; // found at enqueue: reported when the entry is reached, in order
StatusArray* status = nullptr; // a reference
IDStorageStatusArrayX* status_as_given = nullptr;
@ -511,11 +512,7 @@ public:
e.file = live_file(e.request.File);
if (!e.file) e.enqueue_error = E_DSTORAGE_INVALID_FILE_HANDLE;
}
std::lock_guard lock(stats().mutex);
auto& p = priority_stats(stats().s, desc_.Priority);
++p.TotalRequestCount;
p.TotalRequestSourceByteCount += request->SourceSize;
p.TotalRequestDestinationByteCount += request->DestinationSize;
e.counted = true; // TotalRequestCount is "submitted requests" (DSTORAGE_PRIORITY_STATS): see submit_locked
}
enqueue(std::move(e));
}
@ -679,9 +676,23 @@ private:
}
void submit_locked() {
uint32_t requests = 0;
uint64_t source_bytes = 0, destination_bytes = 0;
for (size_t i = submitted_; i < entries_.size(); ++i) {
Entry& e = entries_[i];
if (e.file) e.file_counted = e.file->add_pending();
if (e.counted) {
++requests;
source_bytes += e.request.SourceSize;
destination_bytes += e.request.DestinationSize;
}
}
if (requests) {
std::lock_guard stats_lock(stats().mutex);
auto& p = priority_stats(stats().s, desc_.Priority);
p.TotalRequestCount += requests;
p.TotalRequestSourceByteCount += source_bytes;
p.TotalRequestDestinationByteCount += destination_bytes;
}
if (entries_.size() > submitted_) {
submitted_ = entries_.size();
@ -722,7 +733,10 @@ private:
if (e.cancelled) {
hr = S_OK;
} else if (SUCCEEDED(hr)) {
// Pending: processing has started and not completed (DSTORAGE_PRIORITY_STATS).
set_pending(+1);
hr = execute_request(e);
set_pending(-1);
}
if (e.file && e.file_counted) e.file->finish_pending();
if (FAILED(hr) && SUCCEEDED(since_notify_)) since_notify_ = hr;
@ -769,6 +783,9 @@ private:
const bool memory = desc_.SourceType == DSTORAGE_REQUEST_SOURCE_MEMORY;
const uint64_t total = static_cast<uint64_t>(r.DestinationSize) + (memory ? r.SourceSize : 0u);
if (total > kMaxRequestBytes) return E_DSTORAGE_REQUEST_TOO_LARGE;
// DSTORAGE_REQUEST: a destination over 32 MiB is allowed only with 64 KiB or 2 MiB pages, which are not
// implemented yet (refused above). The source equals the destination here, so this covers both buffers.
if (r.DestinationSize > kMax4kPageDestinationSize) return E_DSTORAGE_REQUEST_TOO_LARGE;
if (!r.Destination) return E_INVALIDARG;
if (memory) {
if (!r.Source) return E_INVALIDARG;
@ -781,6 +798,11 @@ private:
return read_file_range(e.file->handle(), r.FileOffset, r.Destination, r.SourceSize);
}
void set_pending(int delta) {
std::lock_guard lock(stats().mutex);
priority_stats(stats().s, desc_.Priority).PendingRequestCount += static_cast<uint32_t>(delta);
}
void describe(const Entry& e, DSTORAGE_ERROR_FIRST_FAILURE& f) const {
switch (e.type) {
case Entry::Type::Request: {

View File

@ -629,7 +629,7 @@ void test_auto_submit_and_full_queue(Env& env) {
void test_memory_queue(Env& env) {
IDStorageQueueX2* q = make_queue(env, 0x80, true, DSTORAGE_REQUEST_SOURCE_MEMORY, DSTORAGE_PRIORITY_REALTIME);
IDStorageStatusArrayX* s = make_status(env, 4);
IDStorageStatusArrayX* s = make_status(env, 6);
std::vector<uint8_t> buf = pattern(8192, 9);
std::vector<uint8_t> want = buf;
std::memmove(want.data() + 1024, want.data(), 4096);
@ -654,8 +654,30 @@ void test_memory_queue(Env& env) {
huge.SourceSize = huge.DestinationSize = (1u << 29) + 1; // more than 1 GiB together
q->EnqueueRequest(&huge);
q->EnqueueStatus(s, 3);
// Buffers over 32 MiB need 64 KiB or 2 MiB pages (DSTORAGE_REQUEST). Reserved memory: a copy that is not refused
// faults and reports an access violation instead.
constexpr uint32_t k32MiB = 32u << 20;
void* wide = VirtualAlloc(nullptr, 2 * (k32MiB + 4096), MEM_RESERVE, PAGE_READWRITE);
check(wide != nullptr, "reserve 64 MiB for the over-limit copy");
DSTORAGE_REQUEST over = r;
over.Source = wide;
over.Destination = static_cast<uint8_t*>(wide) + k32MiB + 4096;
over.SourceSize = over.DestinationSize = k32MiB + 1;
q->EnqueueRequest(&over);
q->EnqueueStatus(s, 4);
std::vector<uint8_t> at_limit_source = pattern(k32MiB, 10), at_limit(k32MiB, 0);
DSTORAGE_REQUEST limit = r;
limit.Source = at_limit_source.data();
limit.Destination = at_limit.data();
limit.SourceSize = limit.DestinationSize = k32MiB;
q->EnqueueRequest(&limit);
q->EnqueueStatus(s, 5);
q->Submit();
check(wait_complete(s, 3), "memory requests complete");
check(wait_complete(s, 5), "memory requests complete");
check_hr(s->GetHResult(4), E_DSTORAGE_REQUEST_TOO_LARGE, "an unpaged buffer over 32 MiB is refused untouched");
check_hr(s->GetHResult(5), S_OK, "a 32 MiB unpaged copy");
check(at_limit == at_limit_source, "the 32 MiB copy moved every byte");
VirtualFree(wide, 0, MEM_RELEASE);
check_hr(s->GetHResult(0), S_OK, "a memory-to-memory copy");
check(buf == want, "an overlapping memory copy moves like memmove");
check_hr(s->GetHResult(1), E_DSTORAGE_ACCESS_VIOLATION, "a memory copy to memory the process cannot write");
@ -861,6 +883,88 @@ void test_iid_policy_events_and_cancel(Env& env) {
q->Release();
}
// Holds the queue's worker inside a copy: the copy's source is a guard page, and this handler waits on the first
// touch until the test releases it. The guard is gone after that fault, so the copy then goes on.
struct GuardHold {
uint8_t* page = nullptr;
HANDLE entered = nullptr;
HANDLE release = nullptr;
};
GuardHold* g_hold = nullptr;
LONG CALLBACK hold_on_guard(EXCEPTION_POINTERS* x) {
const EXCEPTION_RECORD* e = x->ExceptionRecord;
if (!g_hold || e->ExceptionCode != STATUS_GUARD_PAGE_VIOLATION || e->NumberParameters < 2)
return EXCEPTION_CONTINUE_SEARCH;
const auto* address = reinterpret_cast<const uint8_t*>(e->ExceptionInformation[1]);
if (address < g_hold->page || address >= g_hold->page + 4096) return EXCEPTION_CONTINUE_SEARCH;
SetEvent(g_hold->entered);
WaitForSingleObject(g_hold->release, 10000);
return EXCEPTION_CONTINUE_EXECUTION;
}
// DSTORAGE_PRIORITY_STATS: TotalRequestCount and the byte totals count submitted requests; PendingRequestCount counts
// requests whose processing has started and not completed. A memory queue (realtime, the only priority it may have):
// the counts are compared with the ones before.
void test_stats_timing(Env& env) {
auto realtime = [&] {
DSTORAGE_STATS st{};
env.factory->GetStats(&st);
return st.RealtimePriorityStats;
};
const DSTORAGE_PRIORITY_STATS before = realtime();
IDStorageQueueX2* q = make_queue(env, 0x80, false, DSTORAGE_REQUEST_SOURCE_MEMORY, DSTORAGE_PRIORITY_REALTIME);
if (!q) return;
IDStorageStatusArrayX* s = make_status(env, 1);
GuardHold hold;
hold.page = static_cast<uint8_t*>(VirtualAlloc(nullptr, 4096, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE));
hold.entered = CreateEventW(nullptr, TRUE, FALSE, nullptr);
hold.release = CreateEventW(nullptr, TRUE, FALSE, nullptr);
if (!hold.page || !hold.entered || !hold.release) {
check(false, "allocate the guard page and its events");
return;
}
std::memset(hold.page, 0x5A, 4096);
DWORD old = 0;
VirtualProtect(hold.page, 4096, PAGE_READWRITE | PAGE_GUARD, &old);
std::vector<uint8_t> out(4096, 0);
DSTORAGE_REQUEST r{};
r.Options.SourceType = DSTORAGE_REQUEST_SOURCE_MEMORY;
r.Source = hold.page;
r.Destination = out.data();
r.SourceSize = r.DestinationSize = 4096;
q->EnqueueRequest(&r);
q->EnqueueStatus(s, 0);
DSTORAGE_PRIORITY_STATS p = realtime();
check(p.TotalRequestCount == before.TotalRequestCount &&
p.TotalRequestSourceByteCount == before.TotalRequestSourceByteCount &&
p.TotalRequestDestinationByteCount == before.TotalRequestDestinationByteCount,
"an enqueued request is not counted before Submit");
g_hold = &hold;
void* handler = AddVectoredExceptionHandler(1, hold_on_guard);
q->Submit();
check(WaitForSingleObject(hold.entered, 10000) == WAIT_OBJECT_0, "the copy reached the guard page");
p = realtime();
check(p.TotalRequestCount == before.TotalRequestCount + 1 &&
p.TotalRequestSourceByteCount == before.TotalRequestSourceByteCount + 4096 &&
p.TotalRequestDestinationByteCount == before.TotalRequestDestinationByteCount + 4096,
"a submitted request is counted, with its sizes");
check(p.PendingRequestCount == before.PendingRequestCount + 1, "a running request is pending");
SetEvent(hold.release);
check(wait_complete(s, 0), "the held copy completes");
check_hr(s->GetHResult(0), S_OK, "the held copy succeeds");
check(out == std::vector<uint8_t>(4096, 0x5A), "the held copy moved every byte");
check(realtime().PendingRequestCount == before.PendingRequestCount, "a completed request is no longer pending");
RemoveVectoredExceptionHandler(handler);
g_hold = nullptr;
CloseHandle(hold.entered);
CloseHandle(hold.release);
VirtualFree(hold.page, 0, MEM_RELEASE);
s->Release();
q->Release();
}
void test_stats(Env& env) {
DSTORAGE_STATS st{};
env.factory->GetStats(&st);
@ -868,7 +972,7 @@ void test_stats(Env& env) {
check(st.NormalPriorityStats.CurrentQueueCount == 0 && st.RealtimePriorityStats.CurrentQueueCount == 0,
"every queue was released");
check(st.NormalPriorityStats.TotalRequestCount > 1000 && st.NormalPriorityStats.TotalFenceCount >= 2 &&
st.RealtimePriorityStats.TotalRequestCount == 4,
st.RealtimePriorityStats.TotalRequestCount == 7,
"requests and fences are counted per priority");
check(st.CumulativeOpenFileCount >= 10 && st.MaxOpenFileCount >= 3, "files are counted");
check(st.ErrorCount > 10, "errors are counted");
@ -907,6 +1011,7 @@ int main() {
test_close_and_release(env);
test_threads(env);
test_iid_policy_events_and_cancel(env);
test_stats_timing(env);
test_stats(env);
fs::remove_all(env.root, ec);