Merge pull request #1867 from azsekazvamdimitar/shadow-aliased-guard

d3d12: slot-133 shadows guard aliased title pages at every address instead of copying them each submission (RT-SHADOW-ALIAS-GUARD)
This commit is contained in:
Aslan2142
2026-11-26 23:35:54 +01:00
committed by GitHub
5 changed files with 326 additions and 45 deletions

View File

@ -380,8 +380,8 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w
| `LEONIDA_LOCAL_SPEECH` | unset | `1` forwards the title's speech-synthesis calls to the host's installed `xgameruntime.dll` where there is one. Unset, and wherever that library is missing, the silent voice answers. No profile sets it. |
| `LEONIDA_CONSOLE_FIX_US` | `0` | Microseconds one submission may spend fixing the changed slots of a console descriptor heap's copy; `0` sets no limit. Past it, each further changed slot is written as a null descriptor and queued for `LEONIDA_CONSOLE_RETRY_US`, so a shader reads it as empty until its turn comes: a limit changes results, and can hang the GPU. |
| `LEONIDA_CONSOLE_RETRY_US` | `500` | Microseconds one submission may spend retrying, round robin, the console heap slots not settled yet (a T# whose texture does not exist yet, or one deferred by `LEONIDA_CONSOLE_FIX_US`). `0` retries all of them at every submission. |
| `LEONIDA_SHADOW_ALIAS_MS` | `0` | The shortest time, in milliseconds, between two copies of the title-memory pages that XMem maps at two addresses (no write guard can watch them) into the slot-133 shadows and title windows. `0` copies them at every submission; a larger value lets a GPU read of them be up to that many milliseconds behind the title's writes. |
| `LEONIDA_SHADOW_KEEP` | on | The slot-133 shadows and title windows copy a page only in the 256-byte pieces where the title's bytes changed since the last copy, so what a shader stored in the copy stays, also on pages copied without a sign that the title wrote them (aliased, unguarded, pinned). A title writing the same bytes again to reset such a value is not seen. `0` copies those pages whole, as before, overwriting the GPU's writes. |
| `LEONIDA_SHADOW_ALIAS_MS` | `0` | The shortest time, in milliseconds, between two copies of the title-memory pages that XMem maps at two addresses into the slot-133 shadows and title windows: pages a write reached since they were guarded at every address, or every time while they can't be (a page pinned for a kernel write). `0` copies them at every submission; a larger value lets a GPU read of them be up to that many milliseconds behind the title's writes. |
| `LEONIDA_SHADOW_KEEP` | on | The slot-133 shadows and title windows copy a page only in the 256-byte pieces where the title's bytes changed since the last copy, so what a shader stored in the copy stays, also on pages copied without a sign that the title wrote them (aliased while they can't be guarded at every address, unguarded, pinned). A title writing the same bytes again to reset such a value is not seen. `0` copies those pages whole, as before, overwriting the GPU's writes. |
| `LEONIDA_REFRESH_PER_FRAME` | `0` | Trades correctness for speed. `1`: the slot-133 shadows, title windows and geometry copies are brought up to date only by the first submission after each present, not by every submission; `2`: the console descriptor heaps too. A GPU read of them can then be a frame behind the title's writes (wrong pixels). `0` refreshes all of them at every submission. |
| `LEONIDA_GEOMETRY_ASYNC` | unset | Trades correctness for speed. `1` refreshes the geometry copies (`shims/d3d12_geometry_views.h`) on a worker thread of the layer, started at submission and not waited for, instead of on the title's submitting thread. A draw may read a copy the worker is still writing: wrong vertices for a frame. |
| `LEONIDA_GEOMETRY_WHOLE_VIEWS` | unset | A geometry copy that is already filled copies only the 64 KiB tiles of title memory written since the last refresh (`shims/d3d12_geometry_views.h`). Any value other than `0` copies every view over a written tile whole, as before. |

View File

@ -324,8 +324,10 @@ void copy_run(std::uint8_t* to, const std::uint8_t* from, std::size_t bytes, boo
// - other readable pages (read-only or copy-on-write pages of the title's own, pages another tracker protected)
// can't be watched: copied every time, as before;
// - pages not committed, or not readable, are zero in the copies (written once);
// - pages xmem reports mapped at another address too (title_page_watch.h) are copied every time: a write
// through the other address doesn't fault here;
// - pages xmem reports mapped at another address too (title_page_watch.h): a write through the other address
// doesn't fault here, so their 64 KiB blocks are guarded at every address by the geometry watch's cells
// (update_aliased) and copied when a cell's version moved. Without the other addresses (no xmem), or while a
// cell can't be armed, they are copied every time;
// - pages a file shim pinned for a kernel write (ReadFile into title memory, which fails with ERROR_NOACCESS on a
// read-only page instead of faulting) are left writable and copied every time until the pin ends.
// If the protection can't be changed (VirtualProtect refuses, or the fault handler couldn't be installed), those
@ -393,6 +395,8 @@ public:
if (std::any_of(state_.begin(), state_.end(), [](std::uint8_t s) { return s & kProtected; }))
reopen_locked(first_, last_);
ReleaseSRWLockExclusive(&lock_);
for (auto& [va, block] : aliased_blocks_) release_cells(va, block);
aliased_blocks_.clear();
}
ShadowPages(const ShadowPages&) = delete;
ShadowPages& operator=(const ShadowPages&) = delete;
@ -512,11 +516,11 @@ public:
const auto walk_start = std::chrono::steady_clock::now();
pieces_ = {};
copy_aliased_ = copy_aliased;
update_aliased();
jobs_.clear();
zeroed_.clear();
copy_bytes_ = {};
std::uint64_t queries = 0;
const std::uint64_t generation = leonida::title_page_aliases::generation();
// LEONIDA_SHADOW_FULL_WALK=1 queries every page at every refresh, as before the generation skip.
static const bool always_full_walk = [] {
char value[8] = {};
@ -539,15 +543,7 @@ public:
}))
full_walk = true;
refresh_walked_all_ = full_walk;
refresh_protects_ = 0;
if (generation != alias_generation_) {
alias_generation_ = generation;
for (std::uint8_t& s : state_) s &= ~kAliased;
leonida::title_page_aliases::for_each_in(first_, last_, [&](std::uintptr_t va) {
const std::uintptr_t from = std::max(va, first_), to = std::min(va + kBlock, last_);
for (std::uintptr_t p = from; p < to; p += kPage) state_[(p - first_) / kPage] |= kAliased;
});
}
refresh_protects_ = alias_arms_;
if (pinned_) {
for (std::uint8_t& s : state_) s &= ~kPinned;
pinned_ = false;
@ -573,13 +569,16 @@ public:
// passed over like unchanged ones and queried at the next such refresh: a mapping change over them is in
// the journal (kRequery) anyway. speed-16/17/18: 730-820 VirtualQuery calls a refresh, ~19 us each under
// Wine (NtQueryVirtualMemory waits for Wine's virtual-memory lock, which the mapping threads hold), a
// fifth of the submitting thread's time.
const auto skip = [&](std::uint8_t s) {
return unchanged(s) || (!copy_aliased_ && (s == kAliased || s == kZero || s == (kZero | kAliased)));
// fifth of the submitting thread's time. So are aliased pages whose cells no write reached (aliased_clean):
// a mapping, commitment or protection change over a cell moves its version too.
const auto skip = [&](std::size_t i) {
const std::uint8_t s = state_[i];
return unchanged(s) || ((s & ~(kZero | kProtected)) == kAliased && aliased_clean(i)) ||
(!copy_aliased_ && (s == kAliased || s == kZero || s == (kZero | kAliased)));
};
if (!full_walk && skip(state_[i0])) {
if (!full_walk && skip(i0)) {
std::size_t i = i0 + 1;
while (i < state_.size() && skip(state_[i])) ++i;
while (i < state_.size() && skip(i)) ++i;
at = first_ + i * kPage;
continue;
}
@ -768,6 +767,7 @@ public:
leonida::title_write_watch::merge_reader(reader_, other.reader_);
}
watch_generation_ = ~std::uint64_t(0);
alias_generation_ = ~std::uint64_t(0);
pinned_ |= other.pinned_;
watch_ = watch_ && other.watch_;
faults_.fetch_add(other.faults(), std::memory_order_relaxed);
@ -784,6 +784,7 @@ public:
targets_.push_back({begin, end, shadow});
for (std::uintptr_t p = begin & ~(kPage - 1); p < end; p += kPage) ++cover_[(p - first_) / kPage];
index_targets();
alias_generation_ = ~std::uint64_t(0); // the aliased blocks the copies read
ReleaseSRWLockExclusive(&lock_);
}
@ -858,6 +859,7 @@ public:
targets_.erase(it);
index_targets();
watch_generation_ = ~std::uint64_t(0); // recounts the write-watched pages covered
alias_generation_ = ~std::uint64_t(0); // and the aliased blocks the copies read
ReleaseSRWLockExclusive(&lock_);
return true;
}
@ -1030,7 +1032,11 @@ private:
const bool unwatched = state_[i] & (kAliased | kPinned);
std::size_t j = i + 1;
while (j < i1 && bool(state_[j] & (kAliased | kPinned)) == unwatched) ++j;
for (std::size_t k = i; k < j; ++k) state_[k] &= ~(kZero | kProtected);
for (std::size_t k = i; k < j; ++k) {
state_[k] &= ~(kZero | kProtected);
// Writable with no write seen: its cells must be armed again (update_aliased).
if (aliased_clean(k) && (rearm_.empty() || rearm_.back() != block_of(k))) rearm_.push_back(block_of(k));
}
if (!unwatched && watch_) protect(i, j, current);
if (unwatched && !copy_aliased_ && (state_[i] & kAliased)) {
i = j;
@ -1044,13 +1050,18 @@ private:
}
}
// Guarded pages [i, j) of a read-only region: pages this tracker protected are as the last refresh left them;
// any other is copied again.
// Guarded pages [i, j) of a read-only region: pages this tracker protected, and aliased pages whose cells no write
// reached, are as the last refresh left them; any other is copied again.
void guard_read_only(std::size_t i0, std::size_t i1, bool streaming) {
const auto clean_at = [&](std::size_t k) {
const std::uint8_t s = state_[k];
return (s & (kProtected | kAliased | kPinned)) == kProtected ||
((s & (kAliased | kPinned)) == kAliased && aliased_clean(k));
};
for (std::size_t i = i0; i < i1;) {
const bool clean = (state_[i] & (kProtected | kAliased | kPinned)) == kProtected;
const bool clean = clean_at(i);
std::size_t j = i + 1;
while (j < i1 && ((state_[j] & (kProtected | kAliased | kPinned)) == kProtected) == clean) ++j;
while (j < i1 && clean_at(j) == clean) ++j;
if (!clean && !(!copy_aliased_ && (state_[i] & kAliased))) {
for (std::size_t k = i; k < j; ++k) state_[k] &= ~kZero;
add_job(i, j, streaming,
@ -1062,6 +1073,99 @@ private:
}
}
// An aliased block's cell, its other addresses' cells, and their mapping and version when it was last armed.
struct AliasedBlock {
leonida::geometry_writes::Cell* cell = nullptr;
Vector<std::pair<std::uintptr_t, leonida::geometry_writes::Cell*>> peers;
std::uint64_t mapping = 0, version = 0;
bool armed = false;
};
// The 64 KiB block of page i, and whether update_aliased found no write reached it.
std::uintptr_t block_of(std::size_t i) const { return (first_ + i * kPage) & ~(kBlock - 1); }
bool aliased_clean(std::size_t i) const {
return !clean_.empty() && clean_[((first_ & (kBlock - 1)) + i * kPage) / kBlock];
}
// At the start of refresh(), outside lock_ (the cells' lock is the write-fault handler's, and the other addresses
// are asked for on the process heap). Each aliased block the copies read is guarded at every address xmem maps it
// by a cell of the geometry watch, whose faults shadow_write_fault answers: a write through any of the addresses,
// a remap or a protection change moves a cell's version. A block whose cells kept their versions since they were
// armed is clean (clean_); any other is armed again before the walk copies it, so a write after the arming is
// copied at the next refresh. A block is copied every time while its cells can't be armed: no other address
// known, a page pinned for a kernel write, or the refreshes that leave aliased pages alone (copy_aliased_).
void update_aliased() {
namespace watch = leonida::geometry_writes;
const std::uint64_t generation = leonida::title_page_aliases::generation();
AcquireSRWLockExclusive(&lock_);
if (generation != alias_generation_) {
alias_generation_ = generation;
aliased_list_.clear();
for (std::uint8_t& s : state_) s &= ~kAliased;
leonida::title_page_aliases::for_each_in(first_, last_, [&](std::uintptr_t va) {
const std::uintptr_t from = std::max(va, first_), to = std::min(va + kBlock, last_);
bool read = false;
for (std::uintptr_t p = from; p < to; p += kPage) {
state_[(p - first_) / kPage] |= kAliased;
read |= cover_[(p - first_) / kPage] != 0;
}
if (read) aliased_list_.push_back(va);
});
}
Vector<std::uintptr_t> rearm;
rearm.swap(rearm_);
ReleaseSRWLockExclusive(&lock_);
const std::uintptr_t base = first_ & ~(kBlock - 1);
clean_.assign(aliased_list_.empty() ? 0 : (last_ - base + kBlock - 1) / kBlock, 0);
alias_arms_ = 0;
const auto aliases = watch::aliases.load(std::memory_order_acquire);
const bool guard = aliases && watch_;
for (auto it = aliased_blocks_.begin(); it != aliased_blocks_.end();) {
if (guard && std::binary_search(aliased_list_.begin(), aliased_list_.end(), it->first)) {
++it;
continue;
}
release_cells(it->first, it->second);
it = aliased_blocks_.erase(it);
}
if (!guard) return;
for (const std::uintptr_t va : rearm)
if (const auto it = aliased_blocks_.find(va); it != aliased_blocks_.end()) it->second.armed = false;
for (const std::uintptr_t va : aliased_list_) {
AliasedBlock& b = aliased_blocks_[va];
if (!b.cell) b.cell = watch::acquire(va);
std::uint64_t version = b.cell->version.load(std::memory_order_acquire);
const std::uint64_t mapping = b.cell->mapping.load(std::memory_order_acquire);
if (mapping != b.mapping) {
std::vector<std::uintptr_t> others;
if (aliases) aliases(va, others);
auto old = std::move(b.peers);
b.peers.clear();
for (const std::uintptr_t other : others) b.peers.emplace_back(other, watch::acquire(other));
for (const auto& [other, cell] : old) watch::release(other);
b.mapping = mapping;
b.armed = false;
}
for (const auto& [other, cell] : b.peers)
version = std::max(version, cell->version.load(std::memory_order_acquire));
if (b.armed && version == b.version) {
clean_[(va - base) / kBlock] = 1;
continue;
}
b.armed = false;
if (!copy_aliased_ || b.peers.empty()) continue;
b.armed = watch::arm(va, *b.cell);
for (const auto& [other, cell] : b.peers) b.armed = watch::arm(other, *cell) && b.armed;
alias_arms_ += 1 + b.peers.size();
b.version = version;
}
}
static void release_cells(std::uintptr_t va, AliasedBlock& b) {
if (b.cell) leonida::geometry_writes::release(va);
for (const auto& [other, cell] : b.peers) leonida::geometry_writes::release(other);
b = {};
}
// With the lock held, when this tracker opens a new write-watch reader: no page is clean until that reader has
// asked and the walk has copied it. The runs may have closed (their reservation released) and come back over a
// reservation made at the same address since, which a page's watched mark alone doesn't tell (re-review of #61).
@ -1306,6 +1410,13 @@ private:
Vector<std::uintptr_t> reach_; // see index_targets
std::size_t target_bytes_ = 0;
std::uint64_t alias_generation_ = ~std::uint64_t(0);
// Aliased blocks (update_aliased), refresh() only: those the copies read, in address order; their cells; per 64 KiB
// block from first_ rounded down, whether no write reached it; and the clean blocks the walk found writable.
Vector<std::uintptr_t> aliased_list_;
leonida::host_heap::map<std::uintptr_t, AliasedBlock> aliased_blocks_;
Vector<std::uint8_t> clean_;
Vector<std::uintptr_t> rearm_;
std::uint64_t alias_arms_ = 0; // arm() calls of the last update_aliased()
std::uint64_t map_generation_ = ~std::uint64_t(0);
bool pinned_ = false; // some page has kPinned
Vector<Job> jobs_; // refresh() only, which DeviceState::shadow_mutex serializes
@ -1340,15 +1451,6 @@ leonida::host_heap::vector<ShadowPages*>& shadow_pages_list() {
return *list;
}
// A write to a page a shadow made read-only: the page is made writable again and the write retried. First in the
// handler chain, so a startup trace doesn't log these as exceptions; any other access violation goes on down it.
// Whatever thread wrote: the title's, or a host thread of the runtime's (a DirectStorage queue's copy).
//
// A physical page xmem maps at two addresses (a stream pool's CPU view and its GPU-only twin) has a protection per
// address: a guard on one view never faults a write through the other, which the shadows see by copying aliased
// pages at every submission (title_page_aliases), so the guard to look for is the faulting address's own. When none
// answers for it (each guard reopens only what it protected), xmem makes the page writable again if its window is
// (kernel_writes' unguarder): a read-only page nobody reopens would fault that write, and every later one, for good.
// A title write into a committed, private, read-only page of title memory that no guard owns (the geometry watch,
// the slot-133 shadows and the kernel-write unguarder all declined it): a guard of ours left behind, since the title
// never writes memory it made read-only itself on the console. Said for the first 32 pages, with whether a shadow's
@ -1392,6 +1494,16 @@ bool stray_read_only(EXCEPTION_POINTERS* info, std::uintptr_t address) {
return ok;
}
// A write to a page a shadow made read-only: the page is made writable again and the write retried. First in the
// handler chain, so a startup trace doesn't log these as exceptions; any other access violation goes on down it.
// Whatever thread wrote: the title's, or a host thread of the runtime's (a DirectStorage queue's copy).
//
// A physical page xmem maps at two addresses (a stream pool's CPU view and its GPU-only twin) has a protection per
// address: a guard on one view never faults a write through the other, which the shadows see through the geometry
// watch's cells they arm at every address of an aliased page (ShadowPages::update_aliased), so the guard to look for
// is the faulting address's own. When none answers for it (each guard reopens only what it protected), xmem makes the
// page writable again if its window is (kernel_writes' unguarder): a read-only page nobody reopens would fault that
// write, and every later one, for good.
LONG CALLBACK shadow_write_fault(EXCEPTION_POINTERS* info) {
const EXCEPTION_RECORD* record = info ? info->ExceptionRecord : nullptr;
if (!record || record->ExceptionCode != EXCEPTION_ACCESS_VIOLATION || record->NumberParameters < 2 ||
@ -2807,9 +2919,10 @@ struct DeviceState {
write_back_titles(); // what the last submission wrote in the copies, before the forward copy below
if (shadows.empty()) return;
const auto start = clock::now();
// LEONIDA_SHADOW_ALIAS_MS (0 by default: every submission): pages xmem maps at two addresses, which no guard
// can watch, are copied at most this often. After the story load they were 59 MiB a submission (speed-6); a
// GPU read of them is at most this many milliseconds behind the title's writes.
// LEONIDA_SHADOW_ALIAS_MS (0 by default: every submission): pages xmem maps at two addresses that a write
// reached, or whose cells can't be armed (ShadowPages::update_aliased), are copied at most this often. After
// the story load they were 59 MiB a submission (speed-6), copied every time; a GPU read of them is at most
// this many milliseconds behind the title's writes.
static const auto alias_period = std::chrono::milliseconds([] {
char text[16] = {};
const DWORD n = GetEnvironmentVariableA("LEONIDA_SHADOW_ALIAS_MS", text, sizeof(text));

View File

@ -543,8 +543,8 @@ using AddressList = std::vector<uintptr_t, leonida::host_heap::Allocator<uintptr
HostUnorderedMap<uintptr_t, AddressList> g_alias_peers;
// With g_phys_mutex held. Keeps leonida::title_page_aliases in step: a page mapped at two or more addresses is
// aliased at each of them (the D3D12 layer's slot-133 shadows copy those pages at every submission instead of
// waiting for a write fault, which a write through another address doesn't raise).
// aliased at each of them (the D3D12 layer's slot-133 shadows guard those pages at every address, since a write
// through one address doesn't fault a guard on another).
void note_mapping(uint64_t page, uintptr_t address, bool mapped) {
auto& addresses = g_page_addresses[page];
if (mapped) {
@ -553,12 +553,6 @@ void note_mapping(uint64_t page, uintptr_t address, bool mapped) {
addresses.erase(address);
leonida::title_page_aliases::set(address, false);
}
using namespace leonida::geometry_writes;
if (state().count.load(std::memory_order_acquire)) {
notify(address, address + kPhysicalPageSize, Event::mapping);
for (auto other : addresses)
if (other != address) notify(other, other + kPhysicalPageSize, Event::mapping);
}
const bool aliased = addresses.size() > 1;
for (const uintptr_t at : addresses) leonida::title_page_aliases::set(at, aliased);
const std::unique_lock aliases(g_alias_lock);
@ -573,6 +567,13 @@ void note_mapping(uint64_t page, uintptr_t address, bool mapped) {
for (const uintptr_t other : addresses)
if (other != at) peers.push_back(other);
}
// After the peers: a cell's watcher that sees the new mapping asks geometry_aliases for the addresses again.
using namespace leonida::geometry_writes;
if (state().count.load(std::memory_order_acquire)) {
notify(address, address + kPhysicalPageSize, Event::mapping);
for (auto other : addresses)
if (other != address) notify(other, other + kPhysicalPageSize, Event::mapping);
}
if (addresses.empty()) g_page_addresses.erase(page);
}
@ -2767,6 +2768,8 @@ bool write_title_bytes(const void* address, const void* bytes, std::size_t size)
std::memcpy(host + offset, static_cast<const std::uint8_t*>(bytes) + done, chunk);
done += chunk;
}
// Through the section, not the title's views: no fault tells a guard of them (a shadow's cells) of the write.
leonida::geometry_writes::notify(start, start + size, leonida::geometry_writes::Event::write);
return true;
}

View File

@ -9,7 +9,8 @@
//
// 1. Aliases (title_page_aliases). xmem maps one physical page at as many VAs as the title asks
// (XMemMapPhysicalPages): a write through one VA changes what the others read without touching them. xmem
// reports each 64 KiB page mapped at more than one address; a shadow copies those at every submission.
// reports each 64 KiB page mapped at more than one address; a shadow guards those at every address with the
// geometry watch's cells (title_geometry_watch.h), or copies them at every submission while it can't.
//
// 2. Kernel writes (kernel_writes). A read-only page makes ReadFile fail with ERROR_NOACCESS instead of faulting
// into a user-mode handler. The file shims (read_file and the rest, below) pin the destination before the kernel

View File

@ -13,6 +13,7 @@
#include "host_wine.h"
#include "../shims/d3d12_com.h"
#include "../src/title_page_watch.h"
#include "../src/title_geometry_watch.h"
#include "../src/gfx10_descriptors.h"
#include "../src/deferred_image_binding.h"
#include <dxgi1_4.h>
@ -922,6 +923,167 @@ int check_aliased_write(ID3D12Device* device) {
return 0;
}
// The same page, guarded at both addresses instead of copied at every submission. With the other address known (what
// xmem answers through leonida::geometry_writes::aliases), the shadow at A arms the geometry watch's cells of the
// aliased 64 KiB at A and at B: both read-only between submissions, and a submission that follows no write copies
// nothing of it. The control: a write through a third view nobody reported doesn't fault, so it stays stale until a
// write through B (which faults) marks the block; then both arrive. Each view commits its pages itself: Wine shows a
// page of a SEC_RESERVE view as committed only in the view that committed it.
std::uintptr_t g_alias_a, g_alias_b;
void aliases_of_test_views(std::uintptr_t va, std::vector<std::uintptr_t>& others) {
if (va >= g_alias_a && va < g_alias_a + 4 * 0x10000) others.push_back(va - g_alias_a + g_alias_b);
if (va >= g_alias_b && va < g_alias_b + 4 * 0x10000) others.push_back(va - g_alias_b + g_alias_a);
}
int check_aliased_guard(ID3D12Device* device) {
const char* who = "vulkan slot-133 aliased page, guarded";
constexpr SIZE_T size = 4 * 0x10000;
constexpr UINT64 committed = size / 2, block = 0x10000, at = 0x11000;
HANDLE section = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE | SEC_RESERVE, 0, DWORD(size),
nullptr);
EXPECT(section != nullptr);
std::uint8_t* views[3]{};
for (auto& view : views) {
view = static_cast<std::uint8_t*>(MapViewOfFile(section, FILE_MAP_ALL_ACCESS, 0, 0, size));
EXPECT(view != nullptr && VirtualAlloc(view, committed, MEM_COMMIT, PAGE_READWRITE) == view);
}
std::uint8_t *a = views[0], *b = views[1], *c = views[2];
g_alias_a = reinterpret_cast<std::uintptr_t>(a);
g_alias_b = reinterpret_cast<std::uintptr_t>(b);
leonida::geometry_writes::aliases.store(&aliases_of_test_views, std::memory_order_release);
leonida::title_page_aliases::set(g_alias_a + block, true);
leonida::title_page_aliases::set(g_alias_b + block, true);
long long unreported = -1, faulted = -1;
DWORD at_a = 0, at_b = 0, b_written = 0;
{
Ref<ID3D12Resource> buffer;
buffer.p = place_shadow(device, a, size);
EXPECT(buffer.p != nullptr);
GpuReader reader;
if (reader.init(device, size)) return 1;
std::vector<std::uint8_t> want(size, 0), got;
for (UINT64 i = 0; i < committed; ++i) want[i] = a[i] = pattern_byte(i, 23);
EXPECT(reader.read(buffer.p, got) == 0);
EXPECT(first_difference(got, want) == -1);
at_a = protection_of(a + at);
at_b = protection_of(b + at);
EXPECT((at_a & 0xff) == PAGE_READONLY);
EXPECT((at_b & 0xff) == PAGE_READONLY);
// Nothing written: the block is not copied, so a write the cells can't see is not either.
for (UINT64 i = at; i < at + 64; ++i) want[i] = c[i] = 0x5a;
EXPECT(reader.read(buffer.p, got) == 0);
unreported = first_difference(got, want);
// Through B: faults, and the block is copied again (the write through C with it).
for (UINT64 i = at + 0x800; i < at + 0x1000; ++i) want[i] = b[i] = pattern_byte(i, 151);
b_written = protection_of(b + at);
EXPECT(reader.read(buffer.p, got) == 0);
faulted = first_difference(got, want);
EXPECT((protection_of(b + at) & 0xff) == PAGE_READONLY);
// Through A, the shadow's own address.
for (UINT64 i = at; i < at + 16; ++i) want[i] = a[i] = 0xc3;
EXPECT(reader.read(buffer.p, got) == 0);
EXPECT(first_difference(got, want) == -1);
}
// Released: both addresses are writable again.
EXPECT((protection_of(a + at) & 0xff) == PAGE_READWRITE);
EXPECT((protection_of(b + at) & 0xff) == PAGE_READWRITE);
leonida::title_page_aliases::set(g_alias_a + block, false);
leonida::title_page_aliases::set(g_alias_b + block, false);
leonida::geometry_writes::aliases.store(nullptr, std::memory_order_release);
for (auto* view : views) UnmapViewOfFile(view);
CloseHandle(section);
std::printf("%s: protection between submissions 0x%lx at A, 0x%lx at B (0x%lx after the write through B); an "
"unreported view's write: first stale byte at %lld (expected 69632); after a write through B: %s\n",
who, at_a, at_b, b_written, unreported, faulted == -1 ? "arrives" : "STILL STALE");
EXPECT(unreported == static_cast<long long>(at));
EXPECT((b_written & 0xff) == PAGE_READWRITE);
EXPECT(faulted == -1);
return 0;
}
// An alias that appears after the cells were armed. The page is mapped at A and B and guarded at both; then xmem maps
// it at C too and, as note_mapping does once the peers are updated, moves the mapping of the cells at every address.
// The next submission asks for the other addresses again and guards C as well, so a write through C faults and is
// copied at the submission after it.
std::uintptr_t g_alias_c;
void aliases_of_late_views(std::uintptr_t va, std::vector<std::uintptr_t>& others) {
const std::uintptr_t views[3] = {g_alias_a, g_alias_b, g_alias_c};
for (const std::uintptr_t from : views) {
if (!from || va < from || va >= from + 4 * 0x10000) continue;
for (const std::uintptr_t to : views)
if (to && to != from) others.push_back(va - from + to);
}
}
int check_aliased_guard_late_peer(ID3D12Device* device) {
const char* who = "vulkan slot-133 aliased page, guarded, alias added later";
constexpr SIZE_T size = 4 * 0x10000;
constexpr UINT64 committed = size / 2, block = 0x10000, at = 0x11000;
HANDLE section = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE | SEC_RESERVE, 0, DWORD(size),
nullptr);
EXPECT(section != nullptr);
std::uint8_t* views[3]{};
for (auto& view : views) {
view = static_cast<std::uint8_t*>(MapViewOfFile(section, FILE_MAP_ALL_ACCESS, 0, 0, size));
EXPECT(view != nullptr && VirtualAlloc(view, committed, MEM_COMMIT, PAGE_READWRITE) == view);
}
std::uint8_t *a = views[0], *b = views[1], *c = views[2];
g_alias_a = reinterpret_cast<std::uintptr_t>(a);
g_alias_b = reinterpret_cast<std::uintptr_t>(b);
g_alias_c = 0; // not mapped there yet, as far as xmem knows
leonida::geometry_writes::aliases.store(&aliases_of_late_views, std::memory_order_release);
leonida::title_page_aliases::set(g_alias_a + block, true);
leonida::title_page_aliases::set(g_alias_b + block, true);
DWORD c_before = 0, c_armed = 0, c_written = 0;
long long late = -1;
{
Ref<ID3D12Resource> buffer;
buffer.p = place_shadow(device, a, size);
EXPECT(buffer.p != nullptr);
GpuReader reader;
if (reader.init(device, size)) return 1;
std::vector<std::uint8_t> want(size, 0), got;
for (UINT64 i = 0; i < committed; ++i) want[i] = a[i] = pattern_byte(i, 41);
EXPECT(reader.read(buffer.p, got) == 0);
EXPECT(first_difference(got, want) == -1);
EXPECT((protection_of(a + at) & 0xff) == PAGE_READONLY);
EXPECT((protection_of(b + at) & 0xff) == PAGE_READONLY);
c_before = protection_of(c + at);
// Mapped at C now: the peers first, then the cells' mapping at every address (xmem's note_mapping).
g_alias_c = reinterpret_cast<std::uintptr_t>(c);
leonida::title_page_aliases::set(g_alias_c + block, true);
namespace watch = leonida::geometry_writes;
for (const std::uintptr_t view : {g_alias_a, g_alias_b, g_alias_c})
watch::notify(view + block, view + 2 * block, watch::Event::mapping);
EXPECT(reader.read(buffer.p, got) == 0);
EXPECT(first_difference(got, want) == -1);
c_armed = protection_of(c + at);
// Through C: faults, and the block is copied at the next submission.
for (UINT64 i = at + 0x400; i < at + 0xc00; ++i) want[i] = c[i] = pattern_byte(i, 97);
c_written = protection_of(c + at);
EXPECT(reader.read(buffer.p, got) == 0);
late = first_difference(got, want);
}
EXPECT((protection_of(a + at) & 0xff) == PAGE_READWRITE);
EXPECT((protection_of(b + at) & 0xff) == PAGE_READWRITE);
EXPECT((protection_of(c + at) & 0xff) == PAGE_READWRITE);
leonida::title_page_aliases::set(g_alias_a + block, false);
leonida::title_page_aliases::set(g_alias_b + block, false);
leonida::title_page_aliases::set(g_alias_c + block, false);
leonida::geometry_writes::aliases.store(nullptr, std::memory_order_release);
g_alias_c = 0;
for (auto* view : views) UnmapViewOfFile(view);
CloseHandle(section);
std::printf("%s: protection at C 0x%lx before it was reported, 0x%lx after (0x%lx after the write through C); "
"the write through C: %s\n",
who, c_before, c_armed, c_written, late == -1 ? "arrives" : "STILL STALE");
EXPECT((c_before & 0xff) == PAGE_READWRITE);
EXPECT((c_armed & 0xff) == PAGE_READONLY);
EXPECT((c_written & 0xff) == PAGE_READWRITE);
EXPECT(late == -1);
return 0;
}
// Kernel writes into a watched page. ReadFile writes from kernel mode, so a page a shadow made read-only fails it
// with ERROR_NOACCESS instead of faulting into the layer: the plain call fails (the control). Through the file shims'
// path (leonida::kernel_writes::read_file, what the title's ReadFile import resolves to), the destination is pinned
@ -2095,6 +2257,8 @@ int check_written_pages_all(ID3D12Device* device) {
failures += check_concurrent_writes(device, false);
if (leonida::title_write_watch::enabled()) failures += check_concurrent_writes(device, true);
failures += check_aliased_write(device);
failures += check_aliased_guard(device);
failures += check_aliased_guard_late_peer(device);
failures += check_kernel_write(device);
failures += check_shared_pages(device);
return failures;