// Xbox-ABI queue and fence proxies (d3d12_xs_device.h) over synthetic COM objects, with no D3D12 runtime and no GPU: // - devices that stop at ID3D12Device, Device1, Device3 and Device9: the slots of a missing interface (45/46, // 50, 75) are refused without reaching the device, the others get the real objects behind the proxies; // - fences with and without ID3D12Fence1: 11 or 12 public slots, QueryInterface and slot 11 to match; // - creation that fails, that returns S_OK with no object, a null IID or output, and an interface the real object // has but the proxy does not model; // - OpenSharedHandle of a fence (as ID3D12Fence, IUnknown, Fence1), of a non-fence object, of an invalid handle, // and with a null output or IID, with the references of every object it touches; // - allocation failures in the proxy (operator new, the arrays it unwraps), injected in this executable only; // - --fail-virtualalloc / --fail-virtualprotect / --fail-veh: the guard region's setup failing, injected by // patching this executable's own import table before the first proxy table is built (one process each). // Every device, queue, fence and resource here is a mock that records the calls it gets. No game data, no Xbox DLLs. #include "../shims/d3d12_xs_device.h" #include #include #include #include #include #include #include #include #include #include #include namespace { const char* g_label = "xs_proxy_mock"; #define EXPECT(condition) do { \ if (!(condition)) { std::fprintf(stderr, "%s line %d: %s\n", g_label, __LINE__, #condition); return 1; } \ } while (0) // ---- Allocation failures: this executable's global operator new fails the next g_fail_news calls ---- int g_fail_news = 0; // single-threaded: armed right before the call it is meant for int g_failed_news = 0; // allocations refused so far } // namespace // The annotations are vcruntime_new.h's, so /analyze sees the same contract as for the CRT's own operator new. _NODISCARD _Ret_notnull_ _Post_writable_byte_size_(size) _VCRT_ALLOCATOR void* __CRTDECL operator new(std::size_t size) { if (g_fail_news > 0) { --g_fail_news; ++g_failed_news; throw std::bad_alloc(); } if (void* p = std::malloc(size ? size : 1)) return p; throw std::bad_alloc(); } _NODISCARD _Ret_maybenull_ _Success_(return != NULL) _Post_writable_byte_size_(size) _VCRT_ALLOCATOR void* __CRTDECL operator new(std::size_t size, const std::nothrow_t&) noexcept { try { return ::operator new(size); } catch (const std::bad_alloc&) { return nullptr; } } void __CRTDECL operator delete(void* p) noexcept { std::free(p); } void __CRTDECL operator delete(void* p, std::size_t) noexcept { std::free(p); } void __CRTDECL operator delete(void* p, const std::nothrow_t&) noexcept { std::free(p); } namespace { namespace xs = rt::d3d12_xs; // ---- Mocks ---- enum class Kind { device, queue, fence, resource }; constexpr unsigned kMockSlots = 128; constexpr std::uint64_t kFenceHandle = 0x1000, kResourceHandle = 0x2000; // the handles the mock device opens constexpr std::uint64_t kCompletedValue = 7; // what a mock fence's slot 8 returns // {5d1e0c4a-2b7f-4e61-9a3d-8c4b2f1e6a70}: an interface the mock queue implements that the proxy does not model. constexpr GUID kExtraIid{0x5d1e0c4a, 0x2b7f, 0x4e61, {0x9a, 0x3d, 0x8c, 0x4b, 0x2f, 0x1e, 0x6a, 0x70}}; struct Mock { void** vtable; Kind kind; long refs; int device_level; // device: highest ID3D12DeviceN it answers (0 = ID3D12Device only) bool fence1; // fence: answers ID3D12Fence1; device: the fences it makes do bool create_null; // device: creation returns create_result with no object HRESULT create_result; // device: what creation returns (S_OK makes the object) Mock* last_child; // device: the object its last creation or open made unsigned calls[kMockSlots]; std::uint64_t args[kMockSlots][5]; std::uint64_t array[kMockSlots][4]; // device: the first entries of the array argument, as received }; Mock g_pool[256]; unsigned g_pool_used = 0; void** mock_vtable(); Mock* new_mock(Kind kind) { if (g_pool_used == std::size(g_pool)) { std::fprintf(stderr, "%s: mock pool exhausted\n", g_label); std::exit(1); } Mock* m = &g_pool[g_pool_used++]; std::memset(m, 0, sizeof(*m)); m->vtable = mock_vtable(); m->kind = kind; return m; } bool mock_has(const Mock* m, REFIID iid) { if (IsEqualIID(iid, __uuidof(IUnknown)) || IsEqualIID(iid, __uuidof(ID3D12Object))) return true; if (m->kind == Kind::device) { if (IsEqualIID(iid, __uuidof(ID3D12Device))) return true; const IID levels[] = {__uuidof(ID3D12Device1), __uuidof(ID3D12Device2), __uuidof(ID3D12Device3), __uuidof(ID3D12Device4), __uuidof(ID3D12Device5), __uuidof(ID3D12Device6), __uuidof(ID3D12Device7), __uuidof(ID3D12Device8), __uuidof(ID3D12Device9)}; for (int i = 0; i < m->device_level && i < static_cast(std::size(levels)); ++i) if (IsEqualIID(iid, levels[i])) return true; return false; } if (IsEqualIID(iid, __uuidof(ID3D12DeviceChild)) || IsEqualIID(iid, __uuidof(ID3D12Pageable))) return true; switch (m->kind) { case Kind::queue: return IsEqualIID(iid, __uuidof(ID3D12CommandQueue)) || IsEqualIID(iid, kExtraIid); case Kind::fence: return IsEqualIID(iid, __uuidof(ID3D12Fence)) || (m->fence1 && IsEqualIID(iid, __uuidof(ID3D12Fence1))); case Kind::resource: return IsEqualIID(iid, __uuidof(ID3D12Resource)); default: return false; } } HRESULT mock_query(Mock* m, const IID* riid, void** out) { if (!out) return E_POINTER; *out = nullptr; if (!riid || !mock_has(m, *riid)) return E_NOINTERFACE; *out = m; ++m->refs; return S_OK; } // A device creating (or opening) a `kind` object as `riid`: S_FALSE without an output, as the PC runtime answers a // capability check; the device's create_result and create_null otherwise. HRESULT mock_create(Mock* device, Kind kind, std::uint64_t riid, std::uint64_t out_word) { auto** out = reinterpret_cast(out_word); if (!out) return S_FALSE; *out = nullptr; if (device->create_null || FAILED(device->create_result)) return device->create_result; Mock* child = new_mock(kind); child->fence1 = device->fence1; device->last_child = child; return mock_query(child, reinterpret_cast(riid), out); } void copy_array(Mock* m, unsigned slot, std::uint64_t objects, std::uint64_t count) { const auto* in = reinterpret_cast(objects); for (std::uint32_t i = 0; in && i < static_cast(count) && i < 4; ++i) m->array[slot][i] = in[i]; } // `words` are the call's first five words (a1..a5), copied into the thunk's own frame. std::uint64_t mock_call(Mock* m, unsigned slot, const std::uint64_t* words) { const std::uint64_t a1 = words[0], a2 = words[1], a3 = words[2], a4 = words[3]; if (m->kind == Kind::device) { switch (slot) { case 8: return static_cast(mock_create(m, Kind::queue, a2, a3)); // CreateCommandQueue case 75: return static_cast(mock_create(m, Kind::queue, a3, a4)); // CreateCommandQueue1 case 36: return static_cast(mock_create(m, Kind::fence, a3, a4)); // CreateFence case 32: // OpenSharedHandle if (a1 == kFenceHandle) return static_cast(mock_create(m, Kind::fence, a2, a3)); if (a1 == kResourceHandle) return static_cast(mock_create(m, Kind::resource, a2, a3)); return static_cast(E_INVALIDARG); case 34: case 35: case 46: copy_array(m, slot, a2, a1); break; // (count, objects, ...) case 45: copy_array(m, slot, a1, a3); break; // (fences, values, count, ...) case 50: copy_array(m, slot, a3, a2); break; // (flags, count, objects, fence, value) default: break; } return S_OK; } if (m->kind == Kind::fence && slot == 8) return kCompletedValue; // GetCompletedValue return S_OK; } template std::uint64_t WINAPI mock_slot(Mock* self, std::uint64_t a1, std::uint64_t a2, std::uint64_t a3, std::uint64_t a4, std::uint64_t a5) { if constexpr (Slot == 0) { return static_cast(mock_query(self, reinterpret_cast(a1), reinterpret_cast(a2))); } else if constexpr (Slot == 1) { return static_cast(++self->refs); } else if constexpr (Slot == 2) { return static_cast(--self->refs); } else { // A caller may pass fewer words than this thunk declares (OpenSharedHandle passes three), so its frame // has no room past the four register homes. The words are copied into this frame and passed by pointer: // forwarding them as stack arguments let MSVC tail-call mock_call and write into the caller's saved // registers (an optimized build corrupted the test's own locals that way). ++self->calls[Slot]; const std::uint64_t words[] = {a1, a2, a3, a4, a5}; std::memcpy(self->args[Slot], words, sizeof(words)); return mock_call(self, Slot, words); } } template void fill_mock_vtable(void** vtable, std::index_sequence) { ((vtable[I] = reinterpret_cast(&mock_slot(I)>)), ...); } void** mock_vtable() { static void* table[kMockSlots]; static const bool filled = [] { fill_mock_vtable(table, std::make_index_sequence{}); return true; }(); (void)filled; return table; } // ---- Calls by slot, the way a title compiled against the console headers makes them ---- using SlotFn = std::uint64_t(WINAPI*)(void*, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t); std::uint64_t raw(const void* object, unsigned slot, std::uint64_t a1 = 0, std::uint64_t a2 = 0, std::uint64_t a3 = 0, std::uint64_t a4 = 0, std::uint64_t a5 = 0) { void* const* vtable = *reinterpret_cast(object); return reinterpret_cast(vtable[slot])(const_cast(object), a1, a2, a3, a4, a5, 0, 0, 0, 0, 0, 0, 0, 0, 0); } HRESULT hr_of(std::uint64_t value) { return static_cast(static_cast(value)); } template std::uint64_t word(const T* p) { return reinterpret_cast(p); } const IID kQueueIid = __uuidof(ID3D12CommandQueue); const IID kFenceIid = __uuidof(ID3D12Fence); const IID kFence1Iid = __uuidof(ID3D12Fence1); const IID kUnknownIid = __uuidof(IUnknown); const IID kResourceIid = __uuidof(ID3D12Resource); const IID kDevice1Iid = __uuidof(ID3D12Device1); const D3D12_COMMAND_QUEUE_DESC kQueueDesc{}; // A device proxy over a new mock device. The proxy takes the mock's one reference. void* make_device(Mock*& mock, int level, bool fence1) { mock = new_mock(Kind::device); mock->device_level = level; mock->fence1 = fence1; mock->refs = 1; void* device = nullptr; if (FAILED(xs::create_device_proxy(reinterpret_cast(mock), __uuidof(ID3D12Device), &device))) return nullptr; return device; } void* make_queue(void* device) { void* queue = nullptr; return SUCCEEDED(hr_of(raw(device, 8, word(&kQueueDesc), word(&kQueueIid), word(&queue)))) ? queue : nullptr; } void* make_fence(void* device, const IID& iid = kFenceIid) { void* fence = nullptr; return SUCCEEDED(hr_of(raw(device, 36, 0, 0, word(&iid), word(&fence)))) ? fence : nullptr; } unsigned long release(void* object) { return static_cast(raw(object, 2)); } // ---- 1. Device interface levels ---- int check_levels() { struct Level { int level; unsigned slots; } const levels[] = {{0, 44}, {1, 47}, {3, 51}, {9, 76}}; for (const Level& l : levels) { Mock* mock = nullptr; void* device = make_device(mock, l.level, true); EXPECT(device && xs::device_proxy_slot_count(device) == l.slots); void* queue = make_queue(device); void* fence = make_fence(device); EXPECT(xs::is_queue_proxy(queue) && xs::is_fence_proxy(fence)); const auto real_queue = word(xs::queue_proxy_real_queue(queue)); const auto real_fence = word(xs::fence_proxy_real_fence(fence)); EXPECT(real_queue && real_fence && real_queue != word(queue) && real_fence != word(fence)); // What every residency call gets, with the proxies in it replaced by their real objects. const std::uint64_t objects[4] = {word(queue), word(fence), real_queue, 0}; const std::uint64_t unwrapped[4] = {real_queue, real_fence, real_queue, 0}; const std::uint64_t fences[2] = {word(fence), word(fence)}; const std::uint64_t values[2] = {1, 2}; const D3D12_RESIDENCY_PRIORITY priorities[4] = {}; const auto same = [](const std::uint64_t* got, const std::uint64_t* want, int n) { return std::memcmp(got, want, n * sizeof(std::uint64_t)) == 0; }; // 34 MakeResident, with a count whose high dword is not zero: the PC prototype takes a UINT. EXPECT(hr_of(raw(device, 34, 0xdeadbeef00000002ull, word(objects))) == S_OK); EXPECT(mock->calls[34] == 1 && static_cast(mock->args[34][0]) == 2); EXPECT(same(mock->array[34], unwrapped, 2) && mock->array[34][2] == 0); // 31 CreateSharedHandle EXPECT(hr_of(raw(device, 31, word(fence), 0, GENERIC_ALL, 0, 0)) == S_OK); EXPECT(mock->calls[31] == 1 && mock->args[31][0] == real_fence); // 45/46: ID3D12Device1 const HRESULT r45 = hr_of(raw(device, 45, word(fences), word(values), 2, 0, 0)); const HRESULT r46 = hr_of(raw(device, 46, 4, word(objects), word(priorities))); if (l.level >= 1) { EXPECT(r45 == S_OK && mock->calls[45] == 1 && mock->array[45][0] == real_fence && mock->array[45][1] == real_fence); EXPECT(r46 == S_OK && mock->calls[46] == 1 && same(mock->array[46], unwrapped, 4)); } else { EXPECT(r45 == E_NOTIMPL && r46 == E_NOTIMPL && mock->calls[45] == 0 && mock->calls[46] == 0); void* device1 = nullptr; EXPECT(FAILED(hr_of(raw(device, 0, word(&kDevice1Iid), word(&device1)))) && !device1); } // 50: ID3D12Device3, with the fence argument unwrapped too const HRESULT r50 = hr_of(raw(device, 50, 0, 4, word(objects), word(fence), 1)); if (l.level >= 3) { EXPECT(r50 == S_OK && mock->calls[50] == 1 && same(mock->array[50], unwrapped, 4) && mock->args[50][3] == real_fence); } else { EXPECT(r50 == E_NOTIMPL && mock->calls[50] == 0); } // 75: ID3D12Device9::CreateCommandQueue1 void* queue1 = reinterpret_cast(1); // cleared on every failure (bc59ef46's convention) const HRESULT r75 = hr_of(raw(device, 75, word(&kQueueDesc), 0, word(&kQueueIid), word(&queue1))); if (l.level >= 9) { EXPECT(r75 == S_OK && xs::is_queue_proxy(queue1) && mock->calls[75] == 1); EXPECT(release(queue1) == 0 && mock->last_child->refs == 0); } else { EXPECT(r75 == E_NOTIMPL && !queue1 && mock->calls[75] == 0); } Mock* const queue_mock = reinterpret_cast(real_queue); Mock* const fence_mock = reinterpret_cast(real_fence); EXPECT(release(queue) == 0 && release(fence) == 0); EXPECT(queue_mock->refs == 0 && fence_mock->refs == 0); EXPECT(release(device) == 0 && mock->refs == 0); } std::printf("%s: devices up to ID3D12Device, Device1, Device3, Device9: 44/47/51/76 slots, 45/46/50/75 refused " "without the interface, residency arrays and fences unwrapped otherwise\n", g_label); return 0; } // ---- 2. Fences with and without ID3D12Fence1 ---- int check_fence1() { for (const bool fence1 : {false, true}) { Mock* mock = nullptr; void* device = make_device(mock, 9, fence1); EXPECT(device); const unsigned long device_refs = xs::device_proxy_ref_count(device); void* fence = make_fence(device); EXPECT(xs::is_fence_proxy(fence) && xs::fence_proxy_slot_count(fence) == (fence1 ? 12u : 11u)); Mock* const fence_mock = mock->last_child; void* as_fence1 = nullptr; const HRESULT qi = hr_of(raw(fence, 0, word(&kFence1Iid), word(&as_fence1))); if (fence1) { EXPECT(qi == S_OK && as_fence1 == fence && release(as_fence1) == 1); } else { EXPECT(qi == E_NOINTERFACE && !as_fence1); } EXPECT(raw(fence, 8) == kCompletedValue); // GetCompletedValue forwarded const HRESULT slot11 = hr_of(raw(fence, 11)); if (fence1) { EXPECT(slot11 == S_OK && fence_mock->calls[11] == 1); } else { EXPECT(slot11 == E_NOTIMPL && fence_mock->calls[11] == 0); // not forwarded past an 11-slot vtable } EXPECT(release(fence) == 0 && fence_mock->refs == 0); // Asked for as ID3D12Fence1: made as ID3D12Fence, then refused when the fence lacks Fence1, and released. void* created1 = nullptr; const HRESULT made1 = hr_of(raw(device, 36, 0, 0, word(&kFence1Iid), word(&created1))); if (fence1) { EXPECT(made1 == S_OK && xs::is_fence_proxy(created1) && release(created1) == 0); } else { EXPECT(made1 == E_NOINTERFACE && !created1); } EXPECT(mock->last_child->refs == 0); EXPECT(xs::device_proxy_ref_count(device) == device_refs); EXPECT(release(device) == 0 && mock->refs == 0); } std::printf("%s: fences without and with ID3D12Fence1: 11/12 slots, QueryInterface, slot 11 and creation as " "Fence1 refused or forwarded to match\n", g_label); return 0; } // ---- 3. Creation failures and refused interfaces ---- int check_create_failures() { Mock* mock = nullptr; void* device = make_device(mock, 9, true); EXPECT(device); const unsigned long device_refs = xs::device_proxy_ref_count(device); void* out = reinterpret_cast(1); mock->create_null = true; // S_OK with no object mock->create_result = S_OK; EXPECT(hr_of(raw(device, 8, word(&kQueueDesc), word(&kQueueIid), word(&out))) == E_FAIL && !out); out = reinterpret_cast(1); EXPECT(hr_of(raw(device, 36, 0, 0, word(&kFenceIid), word(&out))) == E_FAIL && !out); mock->create_null = false; mock->create_result = E_OUTOFMEMORY; // the real failure, passed on out = reinterpret_cast(1); EXPECT(hr_of(raw(device, 8, word(&kQueueDesc), word(&kQueueIid), word(&out))) == E_OUTOFMEMORY && !out); out = reinterpret_cast(1); EXPECT(hr_of(raw(device, 75, word(&kQueueDesc), 0, word(&kQueueIid), word(&out))) == E_OUTOFMEMORY && !out); mock->create_result = S_OK; const unsigned calls8 = mock->calls[8]; out = reinterpret_cast(1); // a null IID: E_POINTER, the output cleared, nothing created EXPECT(hr_of(raw(device, 8, word(&kQueueDesc), 0, word(&out))) == E_POINTER && !out && mock->calls[8] == calls8); out = reinterpret_cast(1); EXPECT(hr_of(raw(device, 36, 0, 0, 0, word(&out))) == E_POINTER && !out); out = reinterpret_cast(1); EXPECT(hr_of(raw(device, 75, word(&kQueueDesc), 0, 0, word(&out))) == E_POINTER && !out); // No output: the device's own answer (S_FALSE here), as the PC runtime gives it. EXPECT(hr_of(raw(device, 8, word(&kQueueDesc), word(&kQueueIid), 0)) == S_FALSE && mock->calls[8] == calls8 + 1); EXPECT(hr_of(raw(device, 36, 0, 0, word(&kFenceIid), 0)) == S_FALSE); // An interface the real queue implements but the proxy does not model: created, refused, released. out = reinterpret_cast(1); EXPECT(hr_of(raw(device, 8, word(&kQueueDesc), word(&kExtraIid), word(&out))) == E_NOINTERFACE && !out); EXPECT(mock->last_child->refs == 0); void* queue = make_queue(device); EXPECT(queue); Mock* const queue_mock = mock->last_child; void* extra = reinterpret_cast(1); EXPECT(hr_of(raw(queue, 0, word(&kExtraIid), word(&extra))) == E_NOINTERFACE && !extra); EXPECT(xs::command_object_proxy_ref_count(queue) == 1 && queue_mock->refs == 1); EXPECT(release(queue) == 0 && queue_mock->refs == 0); EXPECT(xs::device_proxy_ref_count(device) == device_refs); EXPECT(release(device) == 0 && mock->refs == 0); std::printf("%s: creation with no object (E_FAIL), a failing device, null IID and output, and an interface the " "proxy does not model leave no reference\n", g_label); return 0; } // ---- 4. OpenSharedHandle ---- int check_open_shared() { Mock* mock = nullptr; void* device = make_device(mock, 9, false); EXPECT(device); const unsigned long device_refs = xs::device_proxy_ref_count(device); for (const IID* iid : {&kFenceIid, &kUnknownIid}) { // a fence, whatever it is asked for as, comes back wrapped void* opened = nullptr; EXPECT(hr_of(raw(device, 32, kFenceHandle, word(iid), word(&opened))) == S_OK); Mock* const fence_mock = mock->last_child; EXPECT(xs::is_fence_proxy(opened) && word(xs::fence_proxy_real_fence(opened)) == word(fence_mock)); EXPECT(xs::command_object_proxy_ref_count(opened) == 1 && fence_mock->refs == 1); EXPECT(xs::device_proxy_ref_count(device) == device_refs + 1); EXPECT(release(opened) == 0 && fence_mock->refs == 0); } void* out = reinterpret_cast(1); // as Fence1, which this fence lacks: the real open fails, passed on EXPECT(hr_of(raw(device, 32, kFenceHandle, word(&kFence1Iid), word(&out))) == E_NOINTERFACE && !out); EXPECT(mock->last_child->refs == 0); for (const IID* iid : {&kResourceIid, &kUnknownIid}) { // not a fence: the real object, unchanged void* opened = nullptr; EXPECT(hr_of(raw(device, 32, kResourceHandle, word(iid), word(&opened))) == S_OK); Mock* const resource_mock = mock->last_child; EXPECT(opened == resource_mock && !xs::is_fence_proxy(opened) && !xs::is_queue_proxy(opened)); EXPECT(resource_mock->refs == 1 && release(opened) == 0); } EXPECT(xs::device_proxy_ref_count(device) == device_refs); out = reinterpret_cast(1); EXPECT(hr_of(raw(device, 32, 0xbad, word(&kFenceIid), word(&out))) == E_INVALIDARG && !out); EXPECT(hr_of(raw(device, 32, kFenceHandle, word(&kFenceIid), 0)) == S_FALSE); // the device's own answer out = reinterpret_cast(1); EXPECT(hr_of(raw(device, 32, kFenceHandle, 0, word(&out))) == E_POINTER && !out); EXPECT(xs::device_proxy_ref_count(device) == device_refs); EXPECT(release(device) == 0 && mock->refs == 0); std::printf("%s: OpenSharedHandle wraps a fence (as ID3D12Fence and IUnknown), passes a resource, a failed open, " "an invalid handle and a null output through, with balanced references\n", g_label); return 0; } // ---- 5. Allocation failures in the proxy ---- int check_alloc_failures() { Mock* mock = nullptr; void* device = make_device(mock, 9, true); EXPECT(device); const unsigned long device_refs = xs::device_proxy_ref_count(device); void* queue = make_queue(device); void* fence = make_fence(device); EXPECT(queue && fence); const std::uint64_t objects[2] = {word(queue), word(fence)}; const auto failing = [&](auto call) { // one allocation refused, the result of the call const int before = g_failed_news; g_fail_news = 1; const HRESULT hr = call(); g_fail_news = 0; return g_failed_news == before + 1 ? hr : S_OK; }; void* out = reinterpret_cast(1); EXPECT(failing([&] { return hr_of(raw(device, 36, 0, 0, word(&kFenceIid), word(&out))); }) == E_OUTOFMEMORY); EXPECT(!out && mock->last_child->refs == 0); // the real fence was made and released out = reinterpret_cast(1); EXPECT(failing([&] { return hr_of(raw(device, 8, word(&kQueueDesc), word(&kQueueIid), word(&out))); }) == E_OUTOFMEMORY); EXPECT(!out && mock->last_child->refs == 0); out = reinterpret_cast(1); EXPECT(failing([&] { return hr_of(raw(device, 32, kFenceHandle, word(&kFenceIid), word(&out))); }) == E_OUTOFMEMORY); EXPECT(!out && mock->last_child->refs == 0); // Up to 16 entries the unwrapped copy is inline: an armed failure is not even reached, and the call goes on. g_fail_news = 1; const HRESULT inline_result = hr_of(raw(device, 34, 2, word(objects))); const bool untouched = g_fail_news == 1; g_fail_news = 0; EXPECT(inline_result == S_OK && untouched && mock->array[34][0] == word(xs::queue_proxy_real_queue(queue))); // A longer array is allocated; refused, the call returns E_OUTOFMEMORY and reaches no device. constexpr unsigned kLong = 32; std::uint64_t many[kLong], many_fences[kLong], values[kLong]; D3D12_RESIDENCY_PRIORITY priorities[kLong] = {}; for (unsigned i = 0; i < kLong; ++i) { many[i] = (i % 2 != 0) ? word(fence) : word(queue); many_fences[i] = word(fence); values[i] = 1; } const unsigned calls34 = mock->calls[34], calls45 = mock->calls[45], calls46 = mock->calls[46]; const unsigned calls50 = mock->calls[50]; EXPECT(failing([&] { return hr_of(raw(device, 34, kLong, word(many))); }) == E_OUTOFMEMORY); EXPECT(failing([&] { return hr_of(raw(device, 45, word(many_fences), word(values), kLong, 0, 0)); }) == E_OUTOFMEMORY); EXPECT(failing([&] { return hr_of(raw(device, 46, kLong, word(many), word(priorities))); }) == E_OUTOFMEMORY); EXPECT(failing([&] { return hr_of(raw(device, 50, 0, kLong, word(many), word(fence), 1)); }) == E_OUTOFMEMORY); EXPECT(mock->calls[34] == calls34 && mock->calls[45] == calls45 && mock->calls[46] == calls46 && mock->calls[50] == calls50); // nothing reached the device // And without the failure the long array arrives unwrapped. EXPECT(hr_of(raw(device, 34, kLong, word(many))) == S_OK && mock->calls[34] == calls34 + 1); EXPECT(mock->array[34][0] == word(xs::queue_proxy_real_queue(queue)) && mock->array[34][1] == word(xs::fence_proxy_real_fence(fence))); // The device proxy itself: on failure the caller keeps its reference. Mock* other = new_mock(Kind::device); other->refs = 1; void* second = reinterpret_cast(1); EXPECT(failing([&] { return xs::create_device_proxy(reinterpret_cast(other), __uuidof(ID3D12Device), &second); }) == E_OUTOFMEMORY); EXPECT(!second && other->refs == 1); Mock* const queue_mock = reinterpret_cast(xs::queue_proxy_real_queue(queue)); Mock* const fence_mock = reinterpret_cast(xs::fence_proxy_real_fence(fence)); EXPECT(release(queue) == 0 && release(fence) == 0 && queue_mock->refs == 0 && fence_mock->refs == 0); EXPECT(xs::device_proxy_ref_count(device) == device_refs); EXPECT(release(device) == 0 && mock->refs == 0); std::printf("%s: a refused allocation in queue, fence, shared-fence and device proxy creation and in the four " "unwrapped arrays returns E_OUTOFMEMORY, reaches no device and leaks nothing\n", g_label); return 0; } // ---- 6. The refused tail and the guard region ---- int check_tail(bool want_guarded) { Mock* mock = nullptr; void* device = make_device(mock, 9, true); EXPECT(device); void* queue = make_queue(device); void* fence = make_fence(device); EXPECT(queue && fence); EXPECT(xs::command_object_tables_guarded() == want_guarded); Mock* const queue_mock = reinterpret_cast(xs::queue_proxy_real_queue(queue)); // Signal (14) still reaches the real queue, with the real fence. EXPECT(hr_of(raw(queue, 14, word(fence), 5)) == S_OK && queue_mock->calls[14] == 1 && queue_mock->args[14][0] == word(xs::fence_proxy_real_fence(fence)) && queue_mock->args[14][1] == 5); for (unsigned slot = 19; slot < xs::queue_proxy_table_size(); ++slot) EXPECT(hr_of(raw(queue, slot)) == E_NOTIMPL && queue_mock->calls[slot] == 0); for (unsigned slot = 12; slot < xs::fence_proxy_table_size(); ++slot) EXPECT(hr_of(raw(fence, slot)) == E_NOTIMPL); EXPECT(xs::queue_table_overruns() == 0 && xs::fence_table_overruns() == 0); EXPECT(release(queue) == 0 && release(fence) == 0 && release(device) == 0 && mock->refs == 0); return 0; } // ---- Guard-region setup failures: this executable's import table, patched before the first proxy table ---- std::atomic g_injected{0}; bool g_armed = false; void* g_real = nullptr; LPVOID WINAPI fail_virtual_alloc(LPVOID address, SIZE_T size, DWORD type, DWORD protect) { if (g_armed && (type & MEM_RESERVE) && size == 64 * 1024) { ++g_injected; SetLastError(ERROR_NOT_ENOUGH_MEMORY); return nullptr; } return reinterpret_cast(g_real)(address, size, type, protect); } BOOL WINAPI fail_virtual_protect(LPVOID address, SIZE_T size, DWORD protect, PDWORD old) { if (g_armed && protect == PAGE_READONLY) { ++g_injected; SetLastError(ERROR_ACCESS_DENIED); return FALSE; } return reinterpret_cast(g_real)(address, size, protect, old); } PVOID WINAPI fail_add_veh(ULONG, PVECTORED_EXCEPTION_HANDLER) { ++g_injected; SetLastError(ERROR_NOT_ENOUGH_MEMORY); return nullptr; } // Points this executable's import of `function` (by name) at `replacement`; the proxy code is linked into it. bool patch_import(const char* function, void* replacement) { auto* base = reinterpret_cast(GetModuleHandleW(nullptr)); const auto* dos = reinterpret_cast(base); const auto* nt = reinterpret_cast(base + dos->e_lfanew); const IMAGE_DATA_DIRECTORY& imports = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]; if (!imports.VirtualAddress) return false; for (auto* desc = reinterpret_cast(base + imports.VirtualAddress); desc->Name; ++desc) { const DWORD lookup = desc->OriginalFirstThunk ? desc->OriginalFirstThunk : desc->FirstThunk; auto* names = reinterpret_cast(base + lookup); auto* slots = reinterpret_cast(base + desc->FirstThunk); for (; names->u1.AddressOfData; ++names, ++slots) { if (IMAGE_SNAP_BY_ORDINAL(names->u1.Ordinal)) continue; const auto* by_name = reinterpret_cast(base + names->u1.AddressOfData); if (std::strcmp(reinterpret_cast(by_name->Name), function) != 0) continue; DWORD old = 0; if (!VirtualProtect(&slots->u1.Function, sizeof(void*), PAGE_READWRITE, &old)) return false; g_real = reinterpret_cast(slots->u1.Function); slots->u1.Function = reinterpret_cast(replacement); VirtualProtect(&slots->u1.Function, sizeof(void*), old, &old); // through the replacement, not armed yet return true; } } return false; } int run_fault_mode(const char* mode) { struct Mode { const char* flag; const char* function; void* replacement; bool guarded; } const modes[] = { {"--fail-virtualalloc", "VirtualAlloc", reinterpret_cast(&fail_virtual_alloc), false}, {"--fail-virtualprotect", "VirtualProtect", reinterpret_cast(&fail_virtual_protect), true}, {"--fail-veh", "AddVectoredExceptionHandler", reinterpret_cast(&fail_add_veh), false}, }; for (const Mode& m : modes) { if (std::strcmp(mode, m.flag) != 0) continue; g_label = m.flag; EXPECT(patch_import(m.function, m.replacement)); g_armed = true; const int failed = check_tail(m.guarded); // Disarmed once the tables exist: with a static CRT the CRT's own calls go through this import table too // (its exit path asks VirtualProtect for read-only pages), and only the proxy's calls are meant here. g_armed = false; if (failed) return 1; EXPECT(g_injected.load() > 0); // the proxy's own call was the one refused std::printf("%s: %s refused %d time(s): the tables %s guarded, the proxies forward and refuse their tail as " "before\n", m.flag, m.function, g_injected.load(), m.guarded ? "stay" : "are not"); return 0; } return 2; } } // namespace // A failure ends the process with a message on stderr, never in a dialog a test run would wait on: abort() (an // exception that escapes, for one), the debug CRT's reports, and Windows' fault and critical-error boxes. static void no_dialogs() { _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT); #ifdef _DEBUG // the report functions exist only in the debug CRT (empty macros otherwise) for (const int type : {_CRT_WARN, _CRT_ERROR, _CRT_ASSERT}) { _CrtSetReportMode(type, _CRTDBG_MODE_FILE); _CrtSetReportFile(type, _CRTDBG_FILE_STDERR); } #endif SetErrorMode(GetErrorMode() | SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX); } int main(int argc, char** argv) { no_dialogs(); std::setvbuf(stdout, nullptr, _IONBF, 0); if (argc == 2) return run_fault_mode(argv[1]); if (argc != 1) return 2; if (check_tail(true) || check_levels() || check_fence1() || check_create_failures() || check_open_shared() || check_alloc_failures()) return 1; std::printf("xs_proxy_mock_test: PASS (%d allocations refused on purpose)\n", g_failed_news); return 0; }