upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/runtime/test
diff options
context:
space:
mode:
authorDadaCap <167002618+DadaCap@users.noreply.github.com>2026-11-24 21:09:02 +0100
committerDadaCap <167002618+DadaCap@users.noreply.github.com>2026-11-24 21:09:02 +0100
commitbc245e5046124941bbdc7bb5c3bd7c739da4e03e (patch)
tree5b780fbcbc1dd131ee635980dfe3e996ac72928f /runtime/test
parent30450e0e96e1df700bbfa9505433c9b9940e8694 (diff)
parent58be9cdf8df9a31bc7f6c068991f1aed381f7f4d (diff)
Merge remote-tracking branch 'origin/main' into vcc-tuple-resync
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'runtime/test')
-rw-r--r--runtime/test/acphal_test.cpp628
-rw-r--r--runtime/test/check_sparse_queue_family.py138
-rw-r--r--runtime/test/cpu_emulation_test.cpp77
-rw-r--r--runtime/test/d3d12_clear_test.cpp42
-rw-r--r--runtime/test/d3d12_dxr_validation_test.cpp26
-rw-r--r--runtime/test/d3d12_mesh_test.cpp31
-rw-r--r--runtime/test/d3d12_pipeline_library_host_test.cpp10
-rw-r--r--runtime/test/d3d12_pipeline_library_test.cpp9
-rw-r--r--runtime/test/d3d12_state_map_test.cpp8
-rw-r--r--runtime/test/d3d12_vulkan_device_test.cpp6
-rw-r--r--runtime/test/frame_pacer_test.cpp149
-rw-r--r--runtime/test/gfx10_descriptors_test.cpp13
-rw-r--r--runtime/test/loader_tls_test.cpp3
-rw-r--r--runtime/test/mods_test.cpp5
-rw-r--r--runtime/test/replay_copy_offset_test.cpp97
-rw-r--r--runtime/test/replay_query_edges_test.cpp90
-rw-r--r--runtime/test/replay_query_predication_test.cpp25
-rw-r--r--runtime/test/replay_uav_clear_offset_test.cpp12
-rw-r--r--runtime/test/retire_tickets_test.cpp18
-rw-r--r--runtime/test/shader_library_test.cpp9
-rw-r--r--runtime/test/shaders/build.py5
-rw-r--r--runtime/test/shaders/check.py42
-rw-r--r--runtime/test/shaders/cs_div_fmas_f64.asm3
-rw-r--r--runtime/test/shaders/cs_div_fmas_f64_rt.asm18
-rw-r--r--runtime/test/shaders/cs_imgatomic_ext.asm313
-rw-r--r--runtime/test/shaders/cs_imgload_d16_tfe.asm16
-rw-r--r--runtime/test/shaders/cs_imgload_tfe.asm19
-rw-r--r--runtime/test/shaders/cs_imgstore_cube.asm95
-rw-r--r--runtime/test/shaders/cs_w32_lds_subdword.asm7
-rw-r--r--runtime/test/shaders/cs_w32_shift64.asm29
-rw-r--r--runtime/test/shaders/mullit_readback.py122
-rw-r--r--runtime/test/vk_command_replay_test.cpp77
-rw-r--r--runtime/test/vk_compute_test.cpp26
-rw-r--r--runtime/test/vk_host_at_aliasing_test.cpp257
-rw-r--r--runtime/test/vk_queue_test.cpp59
-rw-r--r--runtime/test/vk_store_test.cpp110
-rw-r--r--runtime/test/vk_test_device.h11
-rw-r--r--runtime/test/vulkan_scratch_test.cpp21
-rw-r--r--runtime/test/ws2_offline_test.cpp547
-rw-r--r--runtime/test/xdxr_builder_validation_test.cpp183
-rw-r--r--runtime/test/xdxr_descs_test.cpp13
-rw-r--r--runtime/test/xgameruntime_offline_test.cpp83
-rw-r--r--runtime/test/xs_proxy_mock_test.cpp174
43 files changed, 3385 insertions, 241 deletions
diff --git a/runtime/test/acphal_test.cpp b/runtime/test/acphal_test.cpp
index bd93f7040..be2c6f1e1 100644
--- a/runtime/test/acphal_test.cpp
+++ b/runtime/test/acphal_test.cpp
@@ -6,13 +6,44 @@
6 6
7#include <windows.h> 7#include <windows.h>
8 8
9#include <algorithm>
10#include <atomic>
9#include <cstddef> 11#include <cstddef>
10#include <cstdint> 12#include <cstdint>
11#include <cstdio> 13#include <cstdio>
14#include <cstdlib>
12#include <cstring> 15#include <cstring>
16#include <new>
17#include <thread>
18#include <vector>
13 19
14#include "shims.h" 20#include "shims.h"
15 21
22// Fail only the calling test thread's designated allocation.
23static thread_local int allocations_before_failure = -1;
24static std::atomic<bool> fail_worker_allocation{false};
25static std::atomic<bool> count_worker_allocations{false};
26static std::atomic<unsigned> worker_allocations{0};
27static DWORD test_thread_id;
28void* operator new(std::size_t size) {
29 if (allocations_before_failure == 0) {
30 allocations_before_failure = -1;
31 throw std::bad_alloc();
32 }
33 if (fail_worker_allocation.load() && GetCurrentThreadId() != test_thread_id &&
34 fail_worker_allocation.exchange(false)) {
35 throw std::bad_alloc();
36 }
37 if (count_worker_allocations.load() && GetCurrentThreadId() != test_thread_id) {
38 worker_allocations.fetch_add(1, std::memory_order_relaxed);
39 }
40 if (allocations_before_failure > 0) --allocations_before_failure;
41 if (void* memory = std::malloc(size ? size : 1)) return memory;
42 throw std::bad_alloc();
43}
44void operator delete(void* memory) noexcept { std::free(memory); }
45void operator delete(void* memory, std::size_t) noexcept { std::free(memory); }
46
16namespace { 47namespace {
17 48
18using AcpHalCreateFn = HRESULT(__stdcall*)(void**); 49using AcpHalCreateFn = HRESULT(__stdcall*)(void**);
@@ -66,9 +97,62 @@ static_assert(sizeof(TestShapeContexts) == 120, "TestShapeContexts is 120 bytes"
66static_assert(offsetof(TestShapeContexts, xmaContextArray) == 0x38, 97static_assert(offsetof(TestShapeContexts, xmaContextArray) == 0x38,
67 "xmaContextArray is at offset +0x38"); 98 "xmaContextArray is at offset +0x38");
68 99
100struct XmaWords {
101 uint32_t* data;
102
103 std::atomic_ref<uint32_t> operator[](std::size_t index) const {
104 return std::atomic_ref(data[index]);
105 }
106};
107
108// Synthetic XMA2 with one nonzero spectral coefficient per channel and frame.
109void write_xma_packet(uint8_t* packet, uint32_t frames, uint8_t packet_skip,
110 uint32_t rate_index = 3, bool stereo = false) {
111 constexpr uint32_t scale_bands[] = {23, 24, 23, 23};
112 const uint32_t bands = scale_bands[rate_index];
113 const uint32_t channels = stereo ? 2u : 1u;
114 const uint32_t frame_bits = stereo ? 90 + 2 * bands : 59 + bands;
115 std::memset(packet, 0xFF, 2048);
116 std::size_t at = 0;
117 auto put = [&](uint32_t value, std::size_t width) {
118 for (std::size_t i = 0; i < width; ++i, ++at) {
119 const auto mask = static_cast<uint8_t>(0x80u >> (at % 8));
120 packet[at / 8] &= static_cast<uint8_t>(~mask);
121 if ((value >> (width - 1 - i)) & 1u) packet[at / 8] |= mask;
122 }
123 };
124 put((frames << 26) | (1u << 8) | packet_skip, 32);
125 for (uint32_t frame = 0; frame < frames; ++frame) {
126 put(frame_bits, 15);
127 put(0b10u, 2); // Fixed layout, one 512-sample subframe.
128 if (stereo) put(0, 1); // No optional decorrelation matrix.
129 put(0, 11); // Gain, trim, fill and subframe error flag.
130 if (stereo) put(0b010u, 3); // Two channels without decorrelation.
131 put((1u << channels) - 1, channels); // Coefficients are present in each channel.
132 put(1, 1); // Explicit vector coefficient count.
133 put(0, 8 * channels); // Use only run/level coding.
134 put(0, 6); // Quantizer adjustment.
135 if (stereo) put(0, 5); // No per-channel quantizer modifiers.
136 for (uint32_t channel = 0; channel < channels; ++channel) {
137 put(0, 2); // Scale factor step.
138 put((1u << bands) - 1, bands); // One zero delta per scale band.
139 }
140 for (uint32_t channel = 0; channel < channels; ++channel) {
141 put(0, 1); // Run/level table 0.
142 put(0b00u, 2); // Run 0, level 1.
143 put(channel == 0 ? 1u : 0u, 1);
144 put(0b0101011u, 7); // End of coefficients.
145 }
146 put(0, 1); // Frame padding bit.
147 put(frame + 1 < frames ? 1 : 0, 1);
148 }
149}
150
69} // namespace 151} // namespace
70 152
71int main() { 153int main(int argc, char** argv) {
154 std::setvbuf(stdout, nullptr, _IONBF, 0);
155 test_thread_id = GetCurrentThreadId();
72 std::printf("acphal_test: registered acphal.dll shim verification\n"); 156 std::printf("acphal_test: registered acphal.dll shim verification\n");
73 157
74 const auto create = reinterpret_cast<AcpHalCreateFn>( 158 const auto create = reinterpret_cast<AcpHalCreateFn>(
@@ -107,18 +191,44 @@ int main() {
107 return 1; 191 return 1;
108 } 192 }
109 193
194 // Heap configuration is process-wide, so CTest exercises this mode separately.
195 if (argc == 2 && std::strcmp(argv[1], "--noncached-only") == 0) {
196 check(create_heap(0, 0x6000u) == S_OK, "Create only the non-cached APU heap");
197 void* noncached = nullptr;
198 uint32_t noncached_address = 0;
199 check(alloc(&noncached, &noncached_address, 0x1000, 0x800, 2) == S_OK && noncached != nullptr,
200 "Allocate from the non-cached heap");
201 void* cached = noncached;
202 uint32_t cached_address = noncached_address;
203 check(alloc(&cached, &cached_address, 0x1000, 0x800, 1) == E_OUTOFMEMORY &&
204 cached == nullptr && cached_address == 0,
205 "A missing cached heap stays unavailable after explicit configuration");
206 check(map_apu(noncached_address) == noncached && map_virtual(noncached) == noncached_address,
207 "A failed cached allocation leaves the non-cached mapping unchanged");
208 free_mem(noncached);
209 std::printf("acphal_test complete: %d checks, %d failures\n", g_checks, g_failures);
210 return g_failures != 0;
211 }
212
110 // 1. AcpHalCreate 213 // 1. AcpHalCreate
111 void* acp = nullptr; 214 void* acp = nullptr;
112 check(create(&acp) == S_OK && acp != nullptr, 215 check(create(&acp) == S_OK && acp != nullptr,
113 "AcpHalCreate returns S_OK with a non-null object"); 216 "AcpHalCreate returns S_OK with a non-null object");
114 check(create(nullptr) == E_POINTER, 217 check(create(nullptr) == E_POINTER,
115 "AcpHalCreate(nullptr) returns E_POINTER"); 218 "AcpHalCreate(nullptr) returns E_POINTER");
219 void* failed_hal = acp;
220 allocations_before_failure = 0;
221 const HRESULT create_failure = create(&failed_hal);
222 allocations_before_failure = -1;
223 check(create_failure == E_OUTOFMEMORY && failed_hal == nullptr,
224 "AcpHalCreate returns E_OUTOFMEMORY and clears the output");
116 225
117 if (acp) { 226 if (acp) {
118 using Slot0Fn = HRESULT(__stdcall*)(void*, uint32_t, uint32_t); 227 using Slot0Fn = HRESULT(__stdcall*)(void*, uint32_t, uint32_t);
119 using Slot1Fn = HRESULT(__stdcall*)(void*); 228 using Slot1Fn = HRESULT(__stdcall*)(void*);
120 using Slot2Fn = HRESULT(__stdcall*)(void*, uint32_t, uint32_t, uint32_t, const void*, uint32_t); 229 using Slot2Fn = HRESULT(__stdcall*)(void*, uint32_t, uint64_t, uint32_t, const void*, uint32_t);
121 using Slot3Fn = uint32_t(__stdcall*)(void*); 230 using Slot3Fn = uint32_t(__stdcall*)(void*, void*);
231 using Slot4Fn = uint32_t(__stdcall*)(void*);
122 using Slot5Fn = HRESULT(__stdcall*)(void*); 232 using Slot5Fn = HRESULT(__stdcall*)(void*);
123 233
124 auto vtable = *static_cast<void* const* const*>(acp); 234 auto vtable = *static_cast<void* const* const*>(acp);
@@ -139,8 +249,8 @@ int main() {
139 "IAcpHal slot 2 (submit_command) returns S_OK (vital boot unblocker)"); 249 "IAcpHal slot 2 (submit_command) returns S_OK (vital boot unblocker)");
140 250
141 // Slots 3 and 4: Message polling returns 0 251 // Slots 3 and 4: Message polling returns 0
142 check(reinterpret_cast<Slot3Fn>(vtable[3])(acp) == 0, "IAcpHal slot 3 returns 0"); 252 check(reinterpret_cast<Slot3Fn>(vtable[3])(acp, nullptr) == 0, "IAcpHal slot 3 returns 0");
143 check(reinterpret_cast<Slot3Fn>(vtable[4])(acp) == 0, "IAcpHal slot 4 returns 0"); 253 check(reinterpret_cast<Slot4Fn>(vtable[4])(acp) == 0, "IAcpHal slot 4 returns 0");
144 254
145 // Slot 1: Disconnect returns S_OK 255 // Slot 1: Disconnect returns S_OK
146 check(reinterpret_cast<Slot1Fn>(vtable[1])(acp) == S_OK, "IAcpHal slot 1 returns S_OK"); 256 check(reinterpret_cast<Slot1Fn>(vtable[1])(acp) == S_OK, "IAcpHal slot 1 returns S_OK");
@@ -150,8 +260,8 @@ int main() {
150 } 260 }
151 261
152 // 2. ApuCreateHeap: title passes (cachedSize, nonCachedSize=0x226e00) 262 // 2. ApuCreateHeap: title passes (cachedSize, nonCachedSize=0x226e00)
153 check(create_heap(4 * 1024 * 1024, 0x226e00) == S_OK, 263 check(create_heap(4 * 1024 * 1024 + 0x400, 0x226e00) == S_OK,
154 "ApuCreateHeap(4 MiB, 0x226e00) succeeds"); 264 "ApuCreateHeap succeeds with an unaligned cached heap size");
155 check(create_heap(4 * 1024 * 1024, 0x226e00) != S_OK, 265 check(create_heap(4 * 1024 * 1024, 0x226e00) != S_OK,
156 "ApuCreateHeap second call fails (heap already created)"); 266 "ApuCreateHeap second call fails (heap already created)");
157 267
@@ -252,11 +362,513 @@ int main() {
252 check(ctx_all.xmaContextArray != nullptr, "xmaContextArray is allocated"); 362 check(ctx_all.xmaContextArray != nullptr, "xmaContextArray is allocated");
253 check(ctx_all.pcmContextArray != nullptr, "pcmContextArray is allocated"); 363 check(ctx_all.pcmContextArray != nullptr, "pcmContextArray is allocated");
254 364
365 TestShapeContexts retry_ctx{};
366 retry_ctx.numXmaContexts = 2;
367 allocations_before_failure = 1; // The tracked allocation can grow, then voice slot allocation fails.
368 HRESULT allocation_result = E_UNEXPECTED;
369 try {
370 allocation_result = alloc_ctx(&retry_ctx);
371 } catch (const std::bad_alloc&) {
372 // An exception across the AcpHal boundary is a regression.
373 }
374 allocations_before_failure = -1;
375 check(allocation_result == E_OUTOFMEMORY && retry_ctx.xmaContextArray == nullptr,
376 "A failed XMA slot allocation returns E_OUTOFMEMORY without publishing a context");
377 check(alloc_ctx(&retry_ctx) == S_OK && retry_ctx.xmaContextArray != nullptr,
378 "SHAPE allocation can be retried after memory pressure");
379
255 // Release shape contexts 380 // Release shape contexts
381 std::memset(&ctx_all, 0x55, sizeof(ctx_all));
256 check(release_ctx(&ctx_all) == S_OK, "AcpHalReleaseShapeContexts succeeds"); 382 check(release_ctx(&ctx_all) == S_OK, "AcpHalReleaseShapeContexts succeeds");
257 check(ctx_all.xmaContextArray == nullptr, "xmaContextArray is reset to null"); 383 const auto* released_argument = reinterpret_cast<const uint8_t*>(&ctx_all);
384 check(std::all_of(released_argument, released_argument + sizeof(ctx_all),
385 [](uint8_t b) { return b == 0x55; }),
386 "SHAPE release does not write through an opaque or recycled argument");
258 check(release_ctx(nullptr) == S_OK, "AcpHalReleaseShapeContexts(nullptr) succeeds"); 387 check(release_ctx(nullptr) == S_OK, "AcpHalReleaseShapeContexts(nullptr) succeeds");
259 388
389 // 7. ACP command/message queue protocol (register, complete, overflow drops, disconnect, notify word)
390 {
391 #pragma pack(push, 1)
392 struct TestAcpMessage {
393 uint32_t kind;
394 uint32_t dropped;
395 uint32_t usec;
396 uint8_t data[16];
397 };
398 #pragma pack(pop)
399 static_assert(sizeof(TestAcpMessage) == 28, "ACP message is 28 bytes");
400
401 using ConnectFn = HRESULT(__stdcall*)(void*, uint32_t, uint32_t);
402 using DisconnectFn = HRESULT(__stdcall*)(void*);
403 using SubmitFn = HRESULT(__stdcall*)(void*, uint32_t, uint64_t, uint32_t, const void*, uint32_t);
404 using PopFn = uint32_t(__stdcall*)(void*, TestAcpMessage*);
405 using CountFn = uint32_t(__stdcall*)(void*);
406 using ReleaseFn = HRESULT(__stdcall*)(void*);
407
408 void* q_acp = nullptr;
409 check(create(&q_acp) == S_OK && q_acp != nullptr, "AcpHalCreate for queue test");
410 auto vt = *static_cast<void* const* const*>(q_acp);
411 const auto fn_connect = reinterpret_cast<ConnectFn>(vt[0]);
412 const auto fn_disconnect = reinterpret_cast<DisconnectFn>(vt[1]);
413 const auto fn_submit = reinterpret_cast<SubmitFn>(vt[2]);
414 const auto fn_pop = reinterpret_cast<PopFn>(vt[3]);
415 const auto fn_count = reinterpret_cast<CountFn>(vt[4]);
416 const auto fn_release = reinterpret_cast<ReleaseFn>(vt[5]);
417
418 check(fn_connect(q_acp, 0, 16) == E_INVALIDARG, "Connect(commands=0) returns E_INVALIDARG");
419 check(fn_disconnect(q_acp) == E_FAIL, "Disconnect before Connect returns E_FAIL");
420 check(fn_connect(q_acp, 16, 2) == S_OK, "Connect(16, 2) succeeds");
421
422 // Allocate a 4-byte notification word in APU memory.
423 void* notify_va = nullptr;
424 uint32_t notify_apu = 0;
425 check(alloc(&notify_va, &notify_apu, 16, 16, 1) == S_OK && notify_va != nullptr,
426 "ApuAlloc notification word succeeds");
427 *static_cast<uint32_t*>(notify_va) = 0;
428
429 const uint32_t reg_mask = 0x92u; // FLOWGRAPH_COMPLETED(0x02) | COMMAND_COMPLETED(0x10) | DISCONNECTED(0x80)
430 check(fn_submit(q_acp, 2, 0x1122334455667788ull, 0xffffffffu, &reg_mask, notify_apu) == S_OK,
431 "REGISTER_MESSAGES with id and notify word succeeds");
432 check(*static_cast<volatile uint32_t*>(notify_va) == 1u,
433 "SubmitCommand writes 1 to APU notification word");
434 check(fn_count(q_acp) == 1u, "COMMAND_COMPLETED queued after REGISTER_MESSAGES");
435
436 TestAcpMessage msg{};
437 check(fn_pop(q_acp, &msg) == 1u, "PopMessage retrieves COMMAND_COMPLETED");
438 uint32_t ack_cmd = 0;
439 uint64_t ack_id = 0;
440 std::memcpy(&ack_cmd, msg.data, 4);
441 std::memcpy(&ack_id, msg.data + 4, 8);
442 check(msg.kind == 0x10u && msg.dropped == 0u && ack_cmd == 2u && ack_id == 0x1122334455667788ull,
443 "COMMAND_COMPLETED payload carries command id and 64-bit token");
444
445 // Overflow queue of capacity 2 with 4 commands -> 2 dropped, reported on the 5th.
446 for (uint64_t tok = 1; tok <= 4; ++tok) {
447 check(fn_submit(q_acp, 12, tok, 0xffffffffu, nullptr, 0) == S_OK,
448 "SubmitCommand during overflow succeeds");
449 }
450 check(fn_count(q_acp) == 2u, "Message queue caps at capacity 2");
451 check(fn_pop(q_acp, &msg) == 1u && fn_pop(q_acp, &msg) == 1u,
452 "Drained the 2 queued messages");
453 check(fn_submit(q_acp, 12, 5, 0xffffffffu, nullptr, 0) == S_OK,
454 "SubmitCommand 5 after drain succeeds");
455 check(fn_pop(q_acp, &msg) == 1u && msg.dropped == 2u,
456 "Next queued message reports dropped == 2");
457
458 // LOAD_FLOWGRAPH posts FLOWGRAPH_COMPLETED carrying word(1).
459 const uint32_t fg_cfg[2] = {0, 0x42u};
460 check(fn_submit(q_acp, 1, 0, 0xffffffffu, fg_cfg, 0) == S_OK, "LOAD_FLOWGRAPH succeeds");
461 check(fn_pop(q_acp, &msg) == 1u && msg.kind == 0x02u, "FLOWGRAPH_COMPLETED queued");
462 uint32_t fg_id = 0;
463 std::memcpy(&fg_id, msg.data, 4);
464 check(fg_id == 0x42u, "FLOWGRAPH_COMPLETED carries flowgraph word");
465
466 const uint32_t command_completed_mask = 0x10u;
467 check(fn_submit(q_acp, 3, 0x100u, 0xffffffffu, &command_completed_mask, 0) == S_OK &&
468 fn_count(q_acp) == 0u,
469 "UNREGISTER_MESSAGES suppresses command-completed messages");
470
471 // Disconnect posts DISCONNECTED.
472 check(fn_disconnect(q_acp) == S_OK, "Disconnect succeeds when connected");
473 check(fn_count(q_acp) == 1u, "Disconnect queued DISCONNECTED message");
474 check(fn_pop(q_acp, &msg) == 1u && msg.kind == 0x80u, "Popped DISCONNECTED message");
475
476 free_mem(notify_va);
477 check(fn_release(q_acp) == S_OK, "Release queue AcpHal succeeds");
478 }
479
480 // 8. End-to-end XMA2 context ring decoding via background decoder thread
481 {
482 // Two synthetic XMA2 packets with three mono frames each. Each frame
483 // transmits one positive spectral coefficient so decoded PCM differs from fallback silence.
484 TestShapeContexts xma_ctx{};
485 xma_ctx.numXmaContexts = 4;
486 check(alloc_ctx(&xma_ctx) == S_OK && xma_ctx.xmaContextArray != nullptr,
487 "Allocate 4 XMA SHAPE contexts");
488
489 void* in_va = nullptr;
490 uint32_t in_apu = 0;
491 check(alloc(&in_va, &in_apu, 0x1000, 0x800, 1) == S_OK && in_va != nullptr,
492 "ApuAlloc 2-packet XMA2 input buffer");
493 auto* packets = static_cast<uint8_t*>(in_va);
494 write_xma_packet(packets, 3, 0);
495 write_xma_packet(packets + 2048, 3, 0);
496
497 void* out_va = nullptr;
498 uint32_t out_apu = 0;
499 check(alloc(&out_va, &out_apu, 0x400, 0x100, 2) == S_OK && out_va != nullptr,
500 "ApuAlloc 4-block XMA2 output ring");
501 std::memset(out_va, 0x55, 0x400);
502
503 // Configure voice index 1: 2 packets in input 0, input 0 valid, 4 output blocks,
504 // writable = 1, 48 kHz mono, read_bit = 32.
505 const XmaWords words{static_cast<uint32_t*>(xma_ctx.xmaContextArray) + 16};
506 words[0] = 2u | (1u << 20) | (4u << 22);
507 words[1] = (1u << 31) | (3u << 27);
508 words[2] = 32u;
509 words[5] = in_apu;
510 words[7] = out_apu;
511
512 using ConnectFn = HRESULT(__stdcall*)(void*, uint32_t, uint32_t);
513 using SubmitFn = HRESULT(__stdcall*)(void*, uint32_t, uint64_t, uint32_t, const void*, uint32_t);
514 using ReleaseFn = HRESULT(__stdcall*)(void*);
515
516 void* x_acp = nullptr;
517 check(create(&x_acp) == S_OK && x_acp != nullptr, "AcpHalCreate for XMA decode test");
518 auto vt = *static_cast<void* const* const*>(x_acp);
519 const auto fn_connect = reinterpret_cast<ConnectFn>(vt[0]);
520 const auto fn_submit = reinterpret_cast<SubmitFn>(vt[2]);
521 const auto fn_release = reinterpret_cast<ReleaseFn>(vt[5]);
522
523 check(fn_connect(x_acp, 0x1000, 0x1000) == S_OK, "Connect for XMA decode test");
524
525 // ENABLE_XMA (cmd 5) on voice 1.
526 const uint32_t enable_arg = 1u;
527 worker_allocations.store(0);
528 count_worker_allocations.store(true);
529 check(fn_submit(x_acp, 5, 0xf1, 0xffffffffu, &enable_arg, 0) == S_OK,
530 "ENABLE_XMA voice 1 succeeds");
531
532 // Wait up to 500 ms for the background decoder thread to fill the 4-block ring.
533 for (int wait = 0; wait < 500 && ((words[1] >> 31) & 1u) == 1u; ++wait) {
534 Sleep(1);
535 }
536 const bool ring_full = (words[1] >> 31) == 0u;
537 check(ring_full, "Background XMA2 decoder fills ring and clears writable flag");
538 check(((words[0] >> 27) & 0x1Fu) == 0u,
539 "Write block wrapped back to 0 after filling 4 blocks");
540
541 const auto* ring_bytes = static_cast<const uint8_t*>(out_va);
542#if defined(LEONIDA_HAVE_XMA2_DECODER)
543 check(ring_full && std::any_of(ring_bytes, ring_bytes + 0x400,
544 [](uint8_t b) { return b != 0 && b != 0x55; }),
545 "The Rust decoder writes non-silent PCM");
546#else
547 check(ring_full && std::all_of(ring_bytes, ring_bytes + 0x400, [](uint8_t b) { return b == 0; }),
548 "The fallback writes silence");
549#endif
550
551 // Advance read pointer 4 blocks at a time until input exhausts and INPUT_INVALID fires.
552 const uint32_t advance_args[2] = {1u, 4u};
553 int written_blocks = ring_full ? 4 : 0;
554 bool advanced = true;
555 for (int step = 0; step < 6; ++step) {
556 advanced &= fn_submit(x_acp, 18, 0xf2 + static_cast<uint64_t>(step),
557 0xffffffffu, advance_args, 0) == S_OK;
558 // Wait until either ring fills again (writable == 0) or stream hits error bit.
559 for (int wait = 0; wait < 200; ++wait) {
560 const uint32_t w1 = words[1];
561 const uint32_t w2 = words[2];
562 if (((w1 >> 31) & 1u) == 0u || ((w2 >> 31) & 1u) == 1u) break;
563 Sleep(1);
564 }
565 if (((words[2] >> 31) & 1u) == 1u && ((words[1] >> 31) & 1u) == 1u) {
566 break;
567 }
568 if ((words[1] >> 31) != 0u) break;
569 written_blocks += 4;
570 }
571 check(advanced, "ADVANCE_XMA_READ succeeds");
572 check(written_blocks == 24, "Six frames write exactly 24 blocks before input exhaustion");
573 count_worker_allocations.store(false);
574 const unsigned allocation_count = worker_allocations.load();
575 std::printf("C++ worker allocations for six PCM frames: %u\n", allocation_count);
576 check(allocation_count > 0 && allocation_count < 16,
577 "PCM storage is reused across packets instead of allocating per sample block");
578 check(((words[0] >> 20) & 3u) == 0u, "XMA input buffer valid bits cleared on exhaustion");
579 check(((words[2] >> 31) & 1u) == 1u, "XMA error flag set on exhaustion");
580 check(((words[2] >> 26) & 0x1Fu) == 4u, "XMA error status is INPUT_INVALID (4)");
581
582 // DISABLE_XMA (cmd 7) on voice 1.
583 const uint32_t disable_arg = 1u;
584 check(fn_submit(x_acp, 7, 0xf9, 0xffffffffu, &disable_arg, 0) == S_OK,
585 "DISABLE_XMA voice 1 succeeds");
586 check(fn_release(x_acp) == S_OK, "Release XMA AcpHal succeeds");
587 free_mem(in_va);
588 free_mem(out_va);
589 check(release_ctx(&xma_ctx) == S_OK, "Release XMA SHAPE contexts joins decoder cleanly");
590 }
591
592 // 8b. Loops are rounded to whole packets: the loop end packet plays in full and the read
593 // restarts at the packet holding the loop start. One 1-frame packet = 512 samples = 4 blocks.
594 {
595 TestShapeContexts xma_ctx{};
596 xma_ctx.numXmaContexts = 4;
597 check(alloc_ctx(&xma_ctx) == S_OK && xma_ctx.xmaContextArray != nullptr,
598 "Allocate 4 XMA SHAPE contexts for the packet loop test");
599
600 void* in_va = nullptr;
601 uint32_t in_apu = 0;
602 check(alloc(&in_va, &in_apu, 0x2000, 0x800, 2) == S_OK && in_va != nullptr &&
603 (in_apu & 0x7FFu) == 0 && map_apu(in_apu) == in_va,
604 "Non-cached XMA input keeps its requested alignment and round trips");
605 auto* packets = static_cast<uint8_t*>(in_va);
606 write_xma_packet(packets, 1, 1); // Packet 1 belongs to another stream.
607 write_xma_packet(packets + 0x800, 2, 0);
608 write_xma_packet(packets + 0x1000, 1, 0);
609
610 void* out_va = nullptr;
611 uint32_t out_apu = 0;
612 check(alloc(&out_va, &out_apu, 0x1000, 0x100, 2) == S_OK && out_va != nullptr,
613 "ApuAlloc 16-block loop output ring");
614
615 // Voice index 2.
616 const XmaWords words{static_cast<uint32_t*>(xma_ctx.xmaContextArray) + 32};
617
618 using ConnectFn = HRESULT(__stdcall*)(void*, uint32_t, uint32_t);
619 using SubmitFn = HRESULT(__stdcall*)(void*, uint32_t, uint64_t, uint32_t, const void*, uint32_t);
620 using ReleaseFn = HRESULT(__stdcall*)(void*);
621
622 void* x_acp = nullptr;
623 check(create(&x_acp) == S_OK && x_acp != nullptr, "AcpHalCreate for packet loop test");
624 auto vt = *static_cast<void* const* const*>(x_acp);
625 const auto fn_connect = reinterpret_cast<ConnectFn>(vt[0]);
626 const auto fn_submit = reinterpret_cast<SubmitFn>(vt[2]);
627 const auto fn_release = reinterpret_cast<ReleaseFn>(vt[5]);
628 check(fn_connect(x_acp, 0x1000, 0x1000) == S_OK, "Connect for packet loop test");
629
630 auto configure_voice = [&](uint32_t loops, uint32_t input_0_packets, uint32_t ring_size,
631 uint32_t write, uint32_t read) {
632 std::memset(out_va, 0x55, 0x1000);
633 const uint32_t input_1_packets = 3u - input_0_packets;
634 words[0] = input_0_packets | (loops << 12) |
635 ((input_1_packets != 0 ? 3u : 1u) << 20) | (ring_size << 22) | (write << 27);
636 words[1] = (1u << 31) | (3u << 27) | input_1_packets;
637 words[2] = 32u; // read at packet 0
638 words[3] = 32u; // loop start: packet 0
639 words[4] = 100u; // loop end: packet 0
640 words[5] = in_apu;
641 words[6] = in_apu + input_0_packets * 2048u;
642 words[7] = out_apu;
643 words[9] = read;
644 };
645
646 const uint32_t voice_index = 2u;
647 // Returns the number of blocks written before input exhaustion, or -1 on timeout.
648 auto run_blocks = [&](uint32_t loops, uint32_t input_0_packets = 3,
649 uint32_t initial_skip = 0, uint32_t loop_skip = 0) -> int {
650 configure_voice(loops, input_0_packets, 16, 0, 0);
651 words[1].fetch_or((initial_skip << 24) | (loop_skip << 17));
652 check(fn_submit(x_acp, 5, 0xf3, 0xffffffffu, &voice_index, 0) == S_OK,
653 "ENABLE_XMA voice 2 succeeds");
654 int wait = 0;
655 for (; wait < 1000 && ((words[2] >> 31) & 1u) == 0u; ++wait) {
656 Sleep(1);
657 }
658 const int blocks = ((words[2] >> 31) & 1u) != 0u
659 ? static_cast<int>((words[0] >> 27) & 0x1Fu)
660 : -1;
661 check(fn_submit(x_acp, 7, 0xf4, 0xffffffffu, &voice_index, 0) == S_OK,
662 "DISABLE_XMA voice 2 succeeds");
663 return blocks;
664 };
665
666 check(run_blocks(0) == 8, "Packets 0 and 2 write 8 blocks, skipping packet 1");
667 check(run_blocks(1) == 12, "One loop of packet 0 writes 12 blocks (packets 0, 0, 2)");
668 check(((words[0] >> 12) & 0xFFu) == 0u, "Loop count is consumed by the single loop");
669 const auto* ring_bytes = static_cast<const uint8_t*>(out_va);
670#if defined(LEONIDA_HAVE_XMA2_DECODER)
671 auto has_signal = [](const uint8_t* start) {
672 return std::any_of(start, start + 0x400, [](uint8_t b) { return b != 0 && b != 0x55; });
673 };
674 check(has_signal(ring_bytes) && has_signal(ring_bytes + 0x400) && has_signal(ring_bytes + 0x800),
675 "Rust produces signal before and after rewinding the loop");
676 check(std::memcmp(ring_bytes, ring_bytes + 0x400, 0x400) == 0,
677 "Rewind decodes the first packet from fresh decoder state");
678#endif
679 check(run_blocks(1, 3, 2, 1) == 9 && ((words[1] >> 24) & 7u) == 0,
680 "Initial and loop subframe skips consume 3 blocks and clear the initial skip");
681 check(run_blocks(0, 2) == 8,
682 "A skip to the end of input 0 continues at input 1");
683 check(run_blocks(0, 1) == 8,
684 "An overshooting skip starts at packet 1 of input 1");
685#if defined(LEONIDA_HAVE_XMA2_DECODER)
686 check(has_signal(ring_bytes) && has_signal(ring_bytes + 0x400),
687 "Rust produces signal on both sides of the buffer switch");
688#endif
689
690 configure_voice(255, 3, 4, 7, 9);
691 check(fn_submit(x_acp, 5, 0xf3, 0xffffffffu, &voice_index, 0) == S_OK,
692 "Enable infinite loop with out-of-range ring indices");
693 for (int wait = 0; wait < 1000 && (words[1] >> 31) != 0u; ++wait) Sleep(1);
694 check((words[1] >> 31) == 0u && ((words[0] >> 27) & 0x1Fu) == 1u,
695 "Ring stops at the normalized read index");
696 check(fn_submit(x_acp, 7, 0xf4, 0xffffffffu, &voice_index, 0) == S_OK,
697 "Disable infinite loop after filling bounded ring");
698 check(((words[0] >> 12) & 0xFFu) == 255u, "Infinite loop does not consume its loop count");
699 check(std::all_of(ring_bytes + 0x400, ring_bytes + 0x1000,
700 [](uint8_t b) { return b == 0x55; }),
701 "Output never writes beyond the configured four-block ring");
702
703 words[0] = 3u << 22; // three ring blocks
704 words[9] = 2u;
705 const uint32_t advance_args[2] = {2u, UINT32_MAX};
706 check(fn_submit(x_acp, 18, 0xf5, 0xffffffffu, advance_args, 0) == S_OK && words[9] == 2u,
707 "ADVANCE_XMA_READ wraps at the ring size without overflowing");
708
709 auto wait_for_ring = [&]() {
710 for (int wait = 0; wait < 1000 && (words[1] >> 31) != 0u; ++wait) Sleep(1);
711 return (words[1] >> 31) == 0u;
712 };
713 const uint32_t refill_read_args[2] = {voice_index, 4};
714
715 configure_voice(0, 3, 4, 0, 0);
716 words[0] = 1u | (1u << 20) | (4u << 22);
717 write_xma_packet(packets, 3, 0);
718 check(fn_submit(x_acp, 5, 0xf6, 0xffffffffu, &voice_index, 0) == S_OK && wait_for_ring(),
719 "First packet fills the ring and leaves queued PCM");
720 TestShapeContexts source_only{};
721 source_only.numSrcContexts = 1;
722 check(alloc_ctx(&source_only) == S_OK && source_only.srcContextArray != nullptr,
723 "A non-XMA allocation can coexist with the active XMA table");
724 words[0].fetch_or(1u << 20);
725 check(fn_submit(x_acp, 5, 0xf7, 0xffffffffu, &voice_index, 0) == S_OK,
726 "Re-enable while refilling the current input");
727 int refills = 0;
728 for (int i = 0; i < 5; ++i) {
729 if (fn_submit(x_acp, 18, 0xf8, 0xffffffffu, refill_read_args, 0) != S_OK || !wait_for_ring()) break;
730 ++refills;
731 }
732 check(refills == 5 && (words[2] >> 31) == 0u && ((words[0] >> 20) & 3u) == 0u,
733 "Refill and repeated enable preserve all six frames and consume the reused input");
734 check(fn_submit(x_acp, 7, 0xf9, 0xffffffffu, &voice_index, 0) == S_OK,
735 "Disable the single-buffer refill voice");
736
737 // The next same-stream packet is in the first input's refill, after a short second input.
738 write_xma_packet(packets, 1, 2);
739 write_xma_packet(packets + 0x1000, 2, 0);
740 write_xma_packet(packets + 0x1800, 1, 0);
741 configure_voice(0, 1, 4, 0, 0);
742 words[1] = (words[1] & ~0xFFFu) | 1u;
743 check(fn_submit(x_acp, 5, 0xfa, 0xffffffffu, &voice_index, 0) == S_OK && wait_for_ring(),
744 "Voice fills the ring before the skip crosses two buffers");
745 words[5] = in_apu + 0x1000u;
746 words[0] = (words[0] & ~0xFFFu) | 2u | (1u << 20);
747 check(fn_submit(x_acp, 18, 0xfb, 0xffffffffu, refill_read_args, 0) == S_OK && wait_for_ring(),
748 "The same-stream packet fills the ring after two buffer crossings");
749 check(((words[0] >> 20) & 3u) == 0u && (words[4] >> 31) == 0u,
750 "A skip across both buffers lands on the last packet of the reloaded input");
751 check(fn_submit(x_acp, 7, 0xfc, 0xffffffffu, &voice_index, 0) == S_OK,
752 "Disable the two-buffer refill voice");
753
754 // Both sides were empty. When both are refilled, the title's first input wins.
755 write_xma_packet(packets, 1, 0);
756 configure_voice(0, 3, 4, 0, 0);
757 words[0] = 1u | (1u << 20) | (4u << 22);
758 const uint32_t voice_bit = 1u << voice_index;
759 check(fn_submit(x_acp, 6, 0, 0xffffffffu, &voice_bit, 0) == S_OK && wait_for_ring(),
760 "ENABLE_XMAS starts the selected voice and exhausts the first input");
761 write_xma_packet(packets, 2, 0);
762 write_xma_packet(packets + 0x800, 1, 0);
763 words[6] = in_apu + 0x800u;
764 words[1].fetch_or(1u);
765 words[0].fetch_or(3u << 20);
766 check(fn_submit(x_acp, 18, 0, 0xffffffffu, refill_read_args, 0) == S_OK && wait_for_ring(),
767 "A double refill supplies the next PCM blocks");
768 check(((words[0] >> 20) & 3u) == 2u && (words[4] >> 31) == 1u,
769 "A double refill plays input 0 before input 1");
770#if defined(LEONIDA_HAVE_XMA2_DECODER)
771 check(has_signal(ring_bytes), "Rust decodes non-silent PCM after a double refill");
772#endif
773
774 check(fn_submit(x_acp, 8, 0, 0xffffffffu, &voice_bit, 0) == S_OK,
775 "Reset the voice before exhausting both inputs");
776 write_xma_packet(packets, 1, 0);
777 write_xma_packet(packets + 0x800, 1, 0);
778 configure_voice(0, 1, 8, 0, 0);
779 words[1] = (words[1] & ~0xFFFu) | 1u;
780 check(fn_submit(x_acp, 6, 0, 0xffffffffu, &voice_bit, 0) == S_OK && wait_for_ring() &&
781 ((words[0] >> 20) & 3u) == 0u,
782 "The voice exhausts input 0 and then input 1");
783 write_xma_packet(packets, 2, 0);
784 words[0].fetch_or(3u << 20);
785 const uint32_t full_ring[2] = {voice_index, 8};
786 check(fn_submit(x_acp, 18, 0, 0xffffffffu, full_ring, 0) == S_OK && wait_for_ring() &&
787 ((words[0] >> 20) & 3u) == 2u,
788 "A double refill plays input 0 first even after exhausting input 1");
789
790 // Reconfigure the still-enabled slot and verify that no queued PCM or old format survives.
791 bool reconfigured = true;
792 for (uint32_t rate = 0; rate < 4; ++rate) {
793 const bool stereo = (rate & 1u) == 0;
794 write_xma_packet(packets, 1, 0, rate, stereo);
795 words[0] = 1u | (1u << 20) | (16u << 22);
796 words[2] = 32u;
797 words[4] = 0u;
798 words[9] = 12u;
799 std::memset(out_va, 0, 0x1000);
800 // Enable applies the new format before making the output writable.
801 words[1] = ((rate | (stereo ? 4u : 0u)) << 27);
802 reconfigured &= fn_submit(x_acp, 5, 0, 0xffffffffu, &voice_index, 0) == S_OK;
803 reconfigured &= fn_submit(x_acp, 18, 0, 0xffffffffu, refill_read_args, 0) == S_OK;
804 for (int wait = 0; wait < 1000 && (words[2] >> 31) == 0u; ++wait) Sleep(1);
805 reconfigured &= (words[2] >> 31) == 1u && ((words[0] >> 27) & 0x1Fu) == (stereo ? 8u : 4u);
806#if defined(LEONIDA_HAVE_XMA2_DECODER)
807 reconfigured &= has_signal(ring_bytes);
808#endif
809 }
810 check(reconfigured, "Re-enabled voices select mono or stereo PCM at all four sample rates");
811 check(fn_submit(x_acp, 8, 0, 0xffffffffu, &voice_bit, 0) == S_OK,
812 "DISABLE_XMAS stops the selected voice");
813
814 configure_voice(0, 3, 4, 0, 0);
815 write_xma_packet(packets, 1, 1);
816 fail_worker_allocation.store(true);
817 check(fn_submit(x_acp, 5, 0, 0xffffffffu, &voice_index, 0) == S_OK,
818 "Enable a voice before an injected worker allocation failure");
819 for (int wait = 0; wait < 1000 && (words[2] >> 31) == 0u; ++wait) Sleep(1);
820 check(!fail_worker_allocation.exchange(false) && (words[2] >> 31) != 0u,
821 "Worker allocation failure surfaces an XMA error without terminating the process");
822 check(fn_submit(x_acp, 5, 0, 0xffffffffu, &voice_index, 0) == S_OK && wait_for_ring(),
823 "A voice can run again after a worker allocation failure");
824
825 check(release_ctx(x_acp) == S_OK, "Release SHAPE contexts through the opaque AcpHal handle");
826 check(fn_release(x_acp) == S_OK, "Release packet loop AcpHal succeeds");
827 free_mem(in_va);
828 free_mem(out_va);
829 check(release_ctx(&xma_ctx) == S_OK, "Release packet loop SHAPE contexts");
830 }
831
832 // 9. ENABLE_XMA racing SHAPE allocation and release, including concurrent releases.
833 {
834 using RaceConnectFn = HRESULT(__stdcall*)(void*, uint32_t, uint32_t);
835 using RaceSubmitFn = HRESULT(__stdcall*)(void*, uint32_t, uint64_t, uint32_t, const void*, uint32_t);
836 using RaceReleaseFn = HRESULT(__stdcall*)(void*);
837
838 void* race_acp = nullptr;
839 check(create(&race_acp) == S_OK && race_acp != nullptr, "AcpHalCreate for XMA race test");
840 auto race_vt = *static_cast<void* const* const*>(race_acp);
841 const auto race_connect = reinterpret_cast<RaceConnectFn>(race_vt[0]);
842 const auto race_submit = reinterpret_cast<RaceSubmitFn>(race_vt[2]);
843 const auto race_release = reinterpret_cast<RaceReleaseFn>(race_vt[5]);
844 check(race_connect(race_acp, 0x1000, 0x1000) == S_OK, "Connect for XMA race test");
845
846 constexpr int kRaceIterations = 20000;
847 std::atomic<int> bind_failures{0};
848 std::thread enabler([&]() {
849 const uint32_t enable_arg = 1u;
850 for (int i = 0; i < kRaceIterations; ++i) {
851 race_submit(race_acp, 5, 0xe000u + static_cast<uint64_t>(i), 0xffffffffu,
852 &enable_arg, 0);
853 }
854 });
855 std::thread releaser([&]() {
856 for (int i = 0; i < kRaceIterations; ++i) {
857 if (release_ctx(nullptr) != S_OK) ++bind_failures;
858 }
859 });
860 for (int i = 0; i < kRaceIterations; ++i) {
861 TestShapeContexts race_ctx{};
862 race_ctx.numXmaContexts = 4;
863 if (alloc_ctx(&race_ctx) != S_OK) ++bind_failures;
864 if (release_ctx(&race_ctx) != S_OK) ++bind_failures;
865 }
866 enabler.join();
867 releaser.join();
868 check(bind_failures == 0, "20000 bind/release cycles race ENABLE_XMA and independent releases");
869 check(race_release(race_acp) == S_OK, "Release race AcpHal succeeds");
870 }
871
260 std::printf("acphal_test complete: %d checks, %d failures\n", g_checks, g_failures); 872 std::printf("acphal_test complete: %d checks, %d failures\n", g_checks, g_failures);
261 return g_failures ? 1 : 0; 873 return g_failures ? 1 : 0;
262} 874}
diff --git a/runtime/test/check_sparse_queue_family.py b/runtime/test/check_sparse_queue_family.py
index 27ebc1f5d..b16e4121c 100644
--- a/runtime/test/check_sparse_queue_family.py
+++ b/runtime/test/check_sparse_queue_family.py
@@ -29,6 +29,19 @@ SPARSE_FLAGS = "VkBufferCreateFlags = 7 (VK_BUFFER_CREATE_SPARSE_BINDING_BIT"
29MODE = re.compile(r"sharingMode:\s+VkSharingMode = (VK_SHARING_MODE_\w+)") 29MODE = re.compile(r"sharingMode:\s+VkSharingMode = (VK_SHARING_MODE_\w+)")
30COUNT = re.compile(r"queueFamilyIndexCount:\s+uint32_t = (\d+)") 30COUNT = re.compile(r"queueFamilyIndexCount:\s+uint32_t = (\d+)")
31INDICES = re.compile(r"pQueueFamilyIndices\[(\d+)\]:\s+const uint32_t = (\d+)") 31INDICES = re.compile(r"pQueueFamilyIndices\[(\d+)\]:\s+const uint32_t = (\d+)")
32CREATE_DEVICE = re.compile(r"^vkCreateDevice\(.*?(?=^vk\w+\(|\Z)", re.M | re.S)
33QUEUE_FAMILY_PROPS = re.compile(r"^vkGetPhysicalDeviceQueueFamilyProperties\(.*?(?=^vk\w+\(|\Z)", re.M | re.S)
34PHYS_DEVICE = re.compile(r"physicalDevice:\s+VkPhysicalDevice\s*=\s*([0-9a-fA-Fx]+)")
35QUEUE_CREATE_COUNT = re.compile(r"queueCreateInfoCount:\s+uint32_t\s*=\s*(\d+)")
36QUEUE_FAMILY_INDEX = re.compile(
37 r"pQueueCreateInfos\[0\]:(?:(?!pQueueCreateInfos\[|enabledLayerCount).)*?queueFamilyIndex:\s+uint32_t\s*=\s*(\d+)",
38 re.S,
39)
40QUEUE_FAMILY_PROP_COUNT = re.compile(r"pQueueFamilyPropertyCount:\s+uint32_t\*\s*=\s*(\d+)")
41VK_QUEUE_GRAPHICS_BIT = 0x1
42VK_QUEUE_COMPUTE_BIT = 0x2
43VK_QUEUE_TRANSFER_BIT = 0x4
44VK_QUEUE_SPARSE_BINDING_BIT = 0x8
32# Each of the two runs gets 30 s, so both together stay inside the CTest TIMEOUT of 65 s (runtime/CMakeLists.txt). 45# Each of the two runs gets 30 s, so both together stay inside the CTest TIMEOUT of 65 s (runtime/CMakeLists.txt).
33RUN_TIMEOUT = 30 46RUN_TIMEOUT = 30
34ACCESS_VIOLATION = 0xC0000005 # STATUS_ACCESS_VIOLATION, as Windows reports it in the exit code 47ACCESS_VIOLATION = 0xC0000005 # STATUS_ACCESS_VIOLATION, as Windows reports it in the exit code
@@ -38,7 +51,118 @@ CALL_HEAD = re.compile(r"^(vk\w+)\(", re.M)
38CASE = re.compile(r"^RESULT (LAYER_MAP_(?:DIRECT|COPY|COMPUTE)_COPY_COMPUTE) PASS mapped_mismatch=0/65536 unmapped_nonzero=0/65536$", re.M) 51CASE = re.compile(r"^RESULT (LAYER_MAP_(?:DIRECT|COPY|COMPUTE)_COPY_COMPUTE) PASS mapped_mismatch=0/65536 unmapped_nonzero=0/65536$", re.M)
39 52
40 53
41def check_trace(path: Path, expect_exclusive: bool) -> tuple[int, int]: 54def _pick_sparse_queue_families(families: list[tuple[int, int, int, int, int]],
55 graphics: int) -> tuple[int, int, int]:
56 """Mirror runtime/src/queue_families.h (pick_queue_families + sparse_capable_queue_families)."""
57 def fine_grained(family: tuple[int, int, int, int, int]) -> bool:
58 return family[2:] == (1, 1, 1)
59
60 compute = copy = graphics
61 have_compute = have_copy = False
62 for i, family in enumerate(families):
63 flags, count = family[0], family[1]
64 if count == 0:
65 continue
66 if not have_compute and (flags & VK_QUEUE_COMPUTE_BIT) and not (flags & VK_QUEUE_GRAPHICS_BIT):
67 compute = i
68 have_compute = True
69 if (not have_copy and (flags & VK_QUEUE_TRANSFER_BIT)
70 and not (flags & (VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT)) and fine_grained(family)):
71 copy = i
72 have_copy = True
73 if not have_copy and have_compute and fine_grained(families[compute]):
74 copy = compute
75 if not (families[compute][0] & VK_QUEUE_SPARSE_BINDING_BIT):
76 compute = graphics
77 if not (families[copy][0] & VK_QUEUE_SPARSE_BINDING_BIT):
78 copy = graphics
79 return graphics, compute, copy
80
81
82def single_sparse_queue_family(path: Path) -> bool:
83 """True when vkCreateDevice uses 1 queue family and the physical device yields only 1 sparse-capable family.
84
85 Mirrors runtime/src/queue_families.h (pick_queue_families + sparse_capable_queue_families): Leonida picks the
86 first non-graphics async compute or fine-grained (1x1x1) DMA transfer family, then falls back to graphics if the
87 chosen family lacks SPARSE_BINDING. On single-family GPUs (e.g. Intel Xe-LP iGPUs), VK_SHARING_MODE_CONCURRENT
88 is illegal (VUID-00914).
89 """
90 text = path.read_text(encoding="utf-8", errors="replace")
91 devices = CREATE_DEVICE.findall(text)
92 if len(devices) != 1:
93 return False
94 pdev_m = PHYS_DEVICE.search(devices[0])
95 qci_m = QUEUE_CREATE_COUNT.search(devices[0])
96 if not pdev_m or not qci_m or int(qci_m.group(1)) != 1:
97 return False
98 pdev = pdev_m.group(1)
99 created_graphics: int | None = None
100 if "pQueueCreateInfos[" in devices[0]:
101 qfi_m = QUEUE_FAMILY_INDEX.search(devices[0])
102 if not qfi_m:
103 return False
104 created_graphics = int(qfi_m.group(1))
105
106 families: list[tuple[int, int, int, int, int]] | None = None
107 max_expected = 0
108 for call in QUEUE_FAMILY_PROPS.findall(text):
109 after = call.split("<after returning from implementation>", 1)
110 if "<before calling into implementation>" in call and len(after) != 2:
111 pm = PHYS_DEVICE.search(call)
112 if pm and pm.group(1) == pdev:
113 return False
114 continue
115 body = after[1] if len(after) == 2 else call
116 pm = PHYS_DEVICE.search(body)
117 if not pm or pm.group(1) != pdev:
118 continue
119 cnt_m = QUEUE_FAMILY_PROP_COUNT.search(body)
120 if cnt_m:
121 max_expected = max(max_expected, int(cnt_m.group(1)))
122 if "pQueueFamilyProperties[" not in body:
123 continue
124 if not cnt_m:
125 return False
126 expected = int(cnt_m.group(1))
127 if expected <= 0:
128 return False
129 chunks = re.split(r"(?=pQueueFamilyProperties\[\d+\]:)", body)[1:]
130 if len(chunks) != expected:
131 return False
132 parsed: dict[int, tuple[int, int, int, int, int]] = {}
133 for chunk in chunks:
134 im = re.match(r"pQueueFamilyProperties\[(\d+)\]:", chunk)
135 fm = re.search(r"queueFlags:\s+VkQueueFlags\s*=\s*(\d+)", chunk)
136 cm = re.search(r"queueCount:\s+uint32_t\s*=\s*(\d+)", chunk)
137 wm = re.search(r"width:\s+uint32_t\s*=\s*(\d+)", chunk)
138 hm = re.search(r"height:\s+uint32_t\s*=\s*(\d+)", chunk)
139 dm = re.search(r"depth:\s+uint32_t\s*=\s*(\d+)", chunk)
140 if not (im and fm and cm and wm and hm and dm):
141 return False
142 idx = int(im.group(1))
143 if idx >= expected or idx in parsed:
144 return False
145 parsed[idx] = (int(fm.group(1)), int(cm.group(1)), int(wm.group(1)), int(hm.group(1)), int(dm.group(1)))
146 if len(parsed) != expected:
147 return False
148 families = [parsed[i] for i in range(expected)]
149 if not families or len(families) != max_expected:
150 return False
151
152 graphics = (created_graphics if created_graphics is not None
153 else next((i for i, (flags, count, *_) in enumerate(families)
154 if count > 0 and (flags & VK_QUEUE_GRAPHICS_BIT)), None))
155 if graphics is None or graphics >= len(families):
156 return False
157 g_flags, g_count = families[graphics][0], families[graphics][1]
158 if g_count == 0 or not (g_flags & VK_QUEUE_GRAPHICS_BIT) or not (g_flags & VK_QUEUE_SPARSE_BINDING_BIT):
159 return False
160
161 direct, compute, copy = _pick_sparse_queue_families(families, graphics)
162 return compute == direct and copy == direct
163
164
165def check_trace(path: Path, expect_exclusive: bool, *, single_family: bool = False) -> tuple[int, int]:
42 rows = path.read_text(encoding="utf-8", errors="replace").splitlines() 166 rows = path.read_text(encoding="utf-8", errors="replace").splitlines()
43 records = 0 167 records = 0
44 for i, line in enumerate(rows): 168 for i, line in enumerate(rows):
@@ -53,8 +177,11 @@ def check_trace(path: Path, expect_exclusive: bool) -> tuple[int, int]:
53 raise AssertionError(f"incomplete API dump sparse VkBuffer at line {i+1}") 177 raise AssertionError(f"incomplete API dump sparse VkBuffer at line {i+1}")
54 sharing, n = mode.group(1), int(count.group(1)) 178 sharing, n = mode.group(1), int(count.group(1))
55 indices = [(int(slot), int(family)) for slot, family in INDICES.findall(tail)] 179 indices = [(int(slot), int(family)) for slot, family in INDICES.findall(tail)]
56 if expect_exclusive: 180 if expect_exclusive or single_family:
57 if sharing != "VK_SHARING_MODE_EXCLUSIVE" or n != 0 or indices: 181 if sharing != "VK_SHARING_MODE_EXCLUSIVE" or n != 0 or indices:
182 if single_family and not expect_exclusive:
183 raise AssertionError(f"invalid sparse buffer on single-family device at line {i+1}: "
184 f"{sharing}, count={n}, indices={indices}")
58 raise AssertionError(f"baseline negative control not reproduced at line {i+1}") 185 raise AssertionError(f"baseline negative control not reproduced at line {i+1}")
59 elif (sharing != "VK_SHARING_MODE_CONCURRENT" or n < 2 or len(indices) != n 186 elif (sharing != "VK_SHARING_MODE_CONCURRENT" or n < 2 or len(indices) != n
60 or len({slot for slot, _ in indices if slot < n}) != n 187 or len({slot for slot, _ in indices if slot < n}) != n
@@ -101,13 +228,18 @@ def main() -> int:
101 if not candidates: 228 if not candidates:
102 print("SKIP 77: Vulkan SDK VK_LAYER_LUNARG_api_dump unavailable or did not write trace") 229 print("SKIP 77: Vulkan SDK VK_LAYER_LUNARG_api_dump unavailable or did not write trace")
103 return 77 230 return 77
104 calls, infos = check_trace(candidates[0], args.expect_baseline_exclusive) 231 single_family = single_sparse_queue_family(candidates[0])
232 calls, infos = check_trace(candidates[0], args.expect_baseline_exclusive, single_family=single_family)
105 validation_out, skip = run_pass(exe, validation_env, path) 233 validation_out, skip = run_pass(exe, validation_env, path)
106 if skip: 234 if skip:
107 return skip 235 return skip
108 errors = [line for line in validation_out.splitlines() if "Validation Error" in line or "VUID-" in line] 236 errors = [line for line in validation_out.splitlines() if "Validation Error" in line or "VUID-" in line]
109 if errors: 237 if errors:
110 raise AssertionError(f"Khronos validation reported {len(errors)} error line(s); first: {errors[0][:300]}") 238 raise AssertionError(f"Khronos validation reported {len(errors)} error line(s); first: {errors[0][:300]}")
239 if single_family:
240 print(f"SKIP 77: GPU exposes only 1 sparse-capable queue family; cross-family CONCURRENT sparse buffer "
241 f"contract requires 2+ families ({calls} EXCLUSIVE sparse VkBuffer creations and Khronos validation passed)")
242 return 77
111 kinds = sorted(CASE.findall(dump_out)) 243 kinds = sorted(CASE.findall(dump_out))
112 print(f"GPU PASS: {len(kinds)} COPY/COMPUTE sparse queue cases, mapped 65,536 bytes exact, unmapped 65,536 zeros") 244 print(f"GPU PASS: {len(kinds)} COPY/COMPUTE sparse queue cases, mapped 65,536 bytes exact, unmapped 65,536 zeros")
113 print(f"VK API CONTRACT PASS: {calls} sparse VkBuffer creations / {infos} create-info records = " 245 print(f"VK API CONTRACT PASS: {calls} sparse VkBuffer creations / {infos} create-info records = "
diff --git a/runtime/test/cpu_emulation_test.cpp b/runtime/test/cpu_emulation_test.cpp
index 4e1ef3cdb..f94f08044 100644
--- a/runtime/test/cpu_emulation_test.cpp
+++ b/runtime/test/cpu_emulation_test.cpp
@@ -145,6 +145,56 @@ void test_apply() {
145 check(fault.ExceptionCode == STATUS_ACCESS_VIOLATION && fault.NumberParameters == 2 && 145 check(fault.ExceptionCode == STATUS_ACCESS_VIOLATION && fault.NumberParameters == 2 &&
146 fault.ExceptionInformation[0] == 1 && fault.ExceptionInformation[1] == 0, 146 fault.ExceptionInformation[0] == 1 && fault.ExceptionInformation[1] == 0,
147 "clzero on an unwritable line reports a write access violation at the line"); 147 "clzero on an unwritable line reports a write access violation at the line");
148
149 // try_clzero_loop EFlags: first-line fault keeps incoming flags, post-prefix fault and >64 MiB batch apply CMP.
150 const uint8_t loop12[] = {0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x48, 0x39, 0xD0, 0x72, 0xF4};
151 if (auto* two_pages = static_cast<uint8_t*>(VirtualAlloc(nullptr, 8192, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE))) {
152 const uint64_t start = reinterpret_cast<uint64_t>(two_pages);
153 DWORD old = 0;
154 VirtualProtect(two_pages, 8192, PAGE_READONLY, &old);
155 c = {};
156 c.Rax = start;
157 c.Rdx = start + 8192;
158 c.Rip = rip;
159 c.EFlags = 0x202;
160 check(ce::try_clzero_loop(loop12, sizeof loop12, &c, &fault) == ce::ClzeroLoopResult::faulted &&
161 c.Rax == start && c.Rip == rip && c.EFlags == 0x202,
162 "clzero loop fault on first line preserves entry EFlags");
163
164 VirtualProtect(two_pages, 4096, PAGE_READWRITE, &old);
165 std::memset(two_pages, 0x5A, 4096);
166 c = {};
167 c.Rax = start;
168 c.Rdx = start + 8192;
169 c.Rip = rip;
170 c.EFlags = 0x246; // ZF=1, CF=0 on entry
171 check(ce::try_clzero_loop(loop12, sizeof loop12, &c, &fault) == ce::ClzeroLoopResult::faulted,
172 "clzero loop post-prefix fault reported");
173 bool prefix_zeroed = true;
174 for (int i = 0; i < 4096; ++i) prefix_zeroed &= two_pages[i] == 0;
175 check(prefix_zeroed && c.Rax == start + 4096 && c.Rip == rip &&
176 fault.ExceptionCode == STATUS_ACCESS_VIOLATION && fault.ExceptionInformation[1] == start + 4096 &&
177 (c.EFlags & 0xC1u) == 0x81u,
178 "clzero loop post-prefix fault zeroes prefix and applies CMP flags (CF=1, ZF=0, SF=1)");
179 VirtualFree(two_pages, 0, MEM_RELEASE);
180 }
181
182 constexpr size_t kLargeSpan = (size_t(64) << 20) + 4096;
183 if (auto* large = static_cast<uint8_t*>(VirtualAlloc(nullptr, kLargeSpan, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE))) {
184 const uint64_t base = reinterpret_cast<uint64_t>(large);
185 c = {};
186 c.Rax = base;
187 c.Rdx = base + kLargeSpan;
188 c.Rip = rip;
189 c.EFlags = 0x202;
190 check(ce::try_clzero_loop(loop12, sizeof loop12, &c, &fault) == ce::ClzeroLoopResult::ok &&
191 c.Rip == rip && c.Rax == base + (uint64_t(64) << 20) && (c.EFlags & 0xC1u) == 0x81u,
192 "clzero loop >64 MiB first batch applies CMP flags (CF=1, ZF=0, SF=1)");
193 check(ce::try_clzero_loop(loop12, sizeof loop12, &c, &fault) == ce::ClzeroLoopResult::ok &&
194 c.Rip == rip + 12 && c.Rax == base + kLargeSpan && (c.EFlags & 0xC1u) == 0x40u,
195 "clzero loop >64 MiB second batch completes with CF=0, ZF=1, SF=0");
196 VirtualFree(large, 0, MEM_RELEASE);
197 }
148} 198}
149 199
150// ---- Running the real encodings ---- 200// ---- Running the real encodings ----
@@ -244,6 +294,33 @@ void test_live(const ce::Host& host) {
244 "clzero with 66 emulated"); 294 "clzero with 66 emulated");
245 } 295 }
246 296
297 // clzero loop fast-path: mov rax, rcx; clzero; add rax, 0x40; cmp rax, rdx; jb -12; ret
298 {
299 alignas(64) static uint8_t buf[512];
300 std::memset(buf, 0xA5, sizeof buf);
301 Code clz_loop({0x48, 0x89, 0xC8, 0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x48, 0x39, 0xD0, 0x72, 0xF4, 0xC3});
302 check(run(clz_loop, buf + 64, buf + 320, &ex), "clzero loop ran");
303 bool loop_ok = true;
304 for (int i = 0; i < 512; ++i) loop_ok &= buf[i] == ((i >= 64 && i < 320) ? 0 : 0xA5);
305 check(loop_ok, "clzero loop zeroed exact span [64, 320)");
306
307 // REX.R limit register (r8): mov rax, rcx; mov r8, rdx; clzero; add rax, 0x40; cmp rax, r8; jb -12; ret
308 std::memset(buf, 0xA5, sizeof buf);
309 Code clz_r8({0x48, 0x89, 0xC8, 0x49, 0x89, 0xD0, 0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x4C, 0x39, 0xC0,
310 0x72, 0xF4, 0xC3});
311 check(run(clz_r8, buf + 64, buf + 320, &ex), "clzero loop (r8) ran");
312 bool r8_ok = true;
313 for (int i = 0; i < 512; ++i) r8_ok &= buf[i] == ((i >= 64 && i < 320) ? 0 : 0xA5);
314 check(r8_ok, "clzero loop (r8) zeroed exact span [64, 320)");
315
316 // Non-multiple-of-64 limit (300): rounds up to 320, matching native do-while `cmp rax, limit; jb`.
317 std::memset(buf, 0xA5, sizeof buf);
318 check(run(clz_loop, buf + 64, buf + 300, &ex), "clzero loop (unaligned limit) ran");
319 bool unaligned_ok = true;
320 for (int i = 0; i < 512; ++i) unaligned_ok &= buf[i] == ((i >= 64 && i < 320) ? 0 : 0xA5);
321 check(unaligned_ok, "clzero loop (unaligned limit 300) zeroed span [64, 320)");
322 }
323
247 // mov rax,rcx; xor ecx,ecx; xor edx,edx; monitorx; xor eax,eax; xor ecx,ecx; mwaitx; ret 324 // mov rax,rcx; xor ecx,ecx; xor edx,edx; monitorx; xor eax,eax; xor ecx,ecx; mwaitx; ret
248 // (no timer: an interrupt or a store ends a native wait; the emulated one returns at once) 325 // (no timer: an interrupt or a store ends a native wait; the emulated one returns at once)
249 Code mon({0x48, 0x89, 0xC8, 0x31, 0xC9, 0x31, 0xD2, 0x0F, 0x01, 0xFA, 0x31, 0xC0, 0x31, 0xC9, 0x0F, 0x01, 0xFB, 326 Code mon({0x48, 0x89, 0xC8, 0x31, 0xC9, 0x31, 0xD2, 0x0F, 0x01, 0xFA, 0x31, 0xC0, 0x31, 0xC9, 0x0F, 0x01, 0xFB,
diff --git a/runtime/test/d3d12_clear_test.cpp b/runtime/test/d3d12_clear_test.cpp
index 46c467ca9..abc3b0bd7 100644
--- a/runtime/test/d3d12_clear_test.cpp
+++ b/runtime/test/d3d12_clear_test.cpp
@@ -6,7 +6,9 @@
6#include "vk_test_device.h" 6#include "vk_test_device.h"
7#include "../shims/d3d12_com.h" 7#include "../shims/d3d12_com.h"
8#include <dxgi1_4.h> 8#include <dxgi1_4.h>
9#include <algorithm>
9#include <array> 10#include <array>
11#include <cmath>
10#include <vector> 12#include <vector>
11#include <cstring> 13#include <cstring>
12#include <cstdint> 14#include <cstdint>
@@ -375,10 +377,9 @@ bool check_unlisted_rtvs(ID3D12Device* device) {
375} // namespace 377} // namespace
376 378
377// ClearDepthStencilView values at the edge of what D3D12 accepts: on a D32_FLOAT target a depth outside [0, 1] and a 379// ClearDepthStencilView values at the edge of what D3D12 accepts: on a D32_FLOAT target a depth outside [0, 1] and a
378// NaN are stored exactly as given, and flags that name no plane clear nothing (the target keeps the value of the clear 380// NaN are stored exactly as given by WARP; flags that name no plane clear nothing. On Vulkan the float values
379// before it). WARP shows both in the read-back, and the layer must show the same texels; a call the layer refuses fails 381// can be preserved with unrestricted depth. Also check the legal [0, 1] clear values on a restricted device.
380// Close() inside clear_depth_and_read. 382bool check_depth_clear_edge_values(ID3D12Device* host, ID3D12Device* ours, bool unrestricted_depth) {
381bool check_depth_clear_edge_values(ID3D12Device* host, ID3D12Device* ours) {
382 constexpr UINT width = 5, height = 3; 383 constexpr UINT width = 5, height = 3;
383 const auto read = [](ID3D12Device* device, FLOAT depth_full, FLOAT depth_part, bool part_no_flags, 384 const auto read = [](ID3D12Device* device, FLOAT depth_full, FLOAT depth_part, bool part_no_flags,
384 std::vector<unsigned char>& depth) { 385 std::vector<unsigned char>& depth) {
@@ -402,34 +403,40 @@ bool check_depth_clear_edge_values(ID3D12Device* host, ID3D12Device* ours) {
402 std::memcpy(&warp_value, expected.data() + at, 4); 403 std::memcpy(&warp_value, expected.data() + at, 4);
403 std::fprintf(stderr, "%s (%u,%u): WARP cleared %g, expected %g\n", what, x, y, warp_value, want); 404 std::fprintf(stderr, "%s (%u,%u): WARP cleared %g, expected %g\n", what, x, y, warp_value, want);
404 ++wrong; 405 ++wrong;
405 } else if (std::memcmp(got.data() + at, expected.data() + at, 4)) { 406 }
406 FLOAT warp_value, layer_value; 407 FLOAT want_layer = want;
407 std::memcpy(&warp_value, expected.data() + at, 4); 408 if (!unrestricted_depth)
409 want_layer = std::isnan(want) ? 0.0f : std::clamp(want, 0.0f, 1.0f);
410 if (std::memcmp(got.data() + at, &want_layer, 4)) {
411 FLOAT layer_value;
408 std::memcpy(&layer_value, got.data() + at, 4); 412 std::memcpy(&layer_value, got.data() + at, 4);
409 std::fprintf(stderr, "%s (%u,%u): layer cleared %g, WARP %g\n", what, x, y, layer_value, 413 std::fprintf(stderr, "%s (%u,%u): layer cleared %g, expected %g\n", what, x, y, layer_value,
410 warp_value); 414 want_layer);
411 ++wrong; 415 ++wrong;
412 } 416 }
413 } 417 }
414 if (wrong) return false; 418 if (wrong) return false;
415 std::printf("%s: %ux%u depth texels match WARP\n", what, width, height); 419 std::printf("%s: %ux%u depth texels matched (%s)\n", what, width, height,
420 unrestricted_depth ? "WARP parity" : "restricted Vulkan depth");
416 return true; 421 return true;
417 }; 422 };
418 if (!compare("depth 1.5 and -0.5 are stored as given", 1.5f, -0.5f, false, 1.5f, -0.5f)) return false; 423 if (!compare("depth clear with 1.5 and -0.5", 1.5f, -0.5f, false, 1.5f, -0.5f)) return false;
419 // NaN is likewise not clamped away; WARP stores the quiet NaN it was given. 424 // NaN is likewise not clamped away; WARP stores the quiet NaN it was given.
420 const FLOAT nan = std::numeric_limits<float>::quiet_NaN(); 425 const FLOAT nan = std::numeric_limits<float>::quiet_NaN();
421 if (!compare("a NaN depth stays NaN", nan, nan, false, nan, nan)) return false; 426 if (!compare("depth clear with NaN", nan, nan, false, nan, nan)) return false;
422 return compare("flags 0 leaves the target alone", 0.25f, 0.75f, true, 0.25f, 0.25f); 427 return compare("flags 0 leaves the target alone", 0.25f, 0.75f, true, 0.25f, 0.25f);
423} 428}
424 429
425int main(int argc, char** argv) { 430int main(int argc, char** argv) {
426 const bool volume_only = argc == 2 && std::strcmp(argv[1], "--volume") == 0; 431 const bool volume_only = argc == 2 && std::strcmp(argv[1], "--volume") == 0;
427 const bool rgb9e5_only = argc == 2 && std::strcmp(argv[1], "--rgb9e5") == 0; 432 const bool rgb9e5_only = argc == 2 && std::strcmp(argv[1], "--rgb9e5") == 0;
428 if (argc != 1 && !volume_only && !rgb9e5_only) { 433 const bool restricted_depth = argc == 2 && std::strcmp(argv[1], "--restricted-depth") == 0;
429 std::fprintf(stderr, "usage: d3d12_clear_test [--volume|--rgb9e5]\n"); 434 if (argc != 1 && !volume_only && !rgb9e5_only && !restricted_depth) {
435 std::fprintf(stderr, "usage: d3d12_clear_test [--volume|--rgb9e5|--restricted-depth]\n");
430 return 2; 436 return 2;
431 } 437 }
432 vktest::Device vk; 438 vktest::Device vk;
439 vk.request_depth_range_unrestricted = !restricted_depth && !volume_only && !rgb9e5_only;
433 const auto device_status = vk.initialize(); 440 const auto device_status = vk.initialize();
434 if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU: ctest skips 441 if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU: ctest skips
435 if (device_status != vktest::DeviceStatus::ready) return 1; 442 if (device_status != vktest::DeviceStatus::ready) return 1;
@@ -444,6 +451,7 @@ int main(int argc, char** argv) {
444 info.device = vk.device; 451 info.device = vk.device;
445 info.queue = vk.queue; 452 info.queue = vk.queue;
446 info.queue_family = vk.family; 453 info.queue_family = vk.family;
454 info.depth_range_unrestricted = vk.depth_range_unrestricted;
447 if (FAILED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&ours.p)))) return 1; 455 if (FAILED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&ours.p)))) return 1;
448 if (rgb9e5_only) { 456 if (rgb9e5_only) {
449 D3D12_FEATURE_DATA_FORMAT_SUPPORT fs{DXGI_FORMAT_R9G9B9E5_SHAREDEXP}; 457 D3D12_FEATURE_DATA_FORMAT_SUPPORT fs{DXGI_FORMAT_R9G9B9E5_SHAREDEXP};
@@ -470,10 +478,12 @@ int main(int argc, char** argv) {
470 std::fprintf(stderr, "WARP reference unavailable: differential test cannot run\n"); 478 std::fprintf(stderr, "WARP reference unavailable: differential test cannot run\n");
471 return 1; 479 return 1;
472 } 480 }
481 if (restricted_depth)
482 return check_depth_clear_edge_values(host.p, ours.p, false) ? 0 : 1;
473 if (!check_volume_rtvs(host.p, ours.p)) return 1; 483 if (!check_volume_rtvs(host.p, ours.p)) return 1;
474 if (volume_only) return 0; 484 if (volume_only) return 0;
475 if (!check_unlisted_rtvs(ours.p)) return 1; 485 if (!check_unlisted_rtvs(ours.p)) return 1;
476 if (!check_depth_clear_edge_values(host.p, ours.p)) return 1; 486 if (!check_depth_clear_edge_values(host.p, ours.p, vk.depth_range_unrestricted)) return 1;
477 const float nan = std::numeric_limits<float>::quiet_NaN(), inf = std::numeric_limits<float>::infinity(); 487 const float nan = std::numeric_limits<float>::quiet_NaN(), inf = std::numeric_limits<float>::infinity();
478 // Integer-format values: negatives, fractions, NaN and overflow exercise the numeric float->int conversion. 488 // Integer-format values: negatives, fractions, NaN and overflow exercise the numeric float->int conversion.
479 const std::array<float, 4> int_values[] = { 489 const std::array<float, 4> int_values[] = {
@@ -677,7 +687,7 @@ int main(int argc, char** argv) {
677 static_cast<unsigned long long>(validation_errors)); 687 static_cast<unsigned long long>(validation_errors));
678 if (validation_errors) return 1; 688 if (validation_errors) return 1;
679 if (compare_failed) return compare_failed; 689 if (compare_failed) return compare_failed;
680 if (volume_only || rgb9e5_only) return 0; 690 if (volume_only || rgb9e5_only || restricted_depth) return 0;
681 std::printf("RTV and DSV clears: %u full/rectangle readbacks matched WARP\n", cases_checked); 691 std::printf("RTV and DSV clears: %u full/rectangle readbacks matched WARP\n", cases_checked);
682 return 0; 692 return 0;
683} 693}
diff --git a/runtime/test/d3d12_dxr_validation_test.cpp b/runtime/test/d3d12_dxr_validation_test.cpp
index 2e09a39ee..a3749acfd 100644
--- a/runtime/test/d3d12_dxr_validation_test.cpp
+++ b/runtime/test/d3d12_dxr_validation_test.cpp
@@ -93,6 +93,28 @@ int run_suite(ID3D12Device* base_dev, const char* name, bool check_strict_valida
93 std::printf("%s: raytracing not supported (tier=%d), skipping\n", name, static_cast<int>(o5.RaytracingTier)); 93 std::printf("%s: raytracing not supported (tier=%d), skipping\n", name, static_cast<int>(o5.RaytracingTier));
94 return 77; 94 return 77;
95 } 95 }
96 if (check_strict_validation && o5.RaytracingTier == D3D12_RAYTRACING_TIER_NOT_SUPPORTED) {
97 // Leonida reports RaytracingTier == NOT_SUPPORTED even when XDXR or KHR acceleration structures are
98 // available. Probe PrebuildInfo before creating RAYTRACING_ACCELERATION_STRUCTURE buffers, which
99 // CreateCommittedResource refuses when neither backend is active (e.g. LEONIDA_RT_AS=khr on a non-RT GPU).
100 D3D12_RAYTRACING_GEOMETRY_DESC probe_tri{};
101 probe_tri.Type = D3D12_RAYTRACING_GEOMETRY_TYPE_TRIANGLES;
102 probe_tri.Flags = D3D12_RAYTRACING_GEOMETRY_FLAG_OPAQUE;
103 probe_tri.Triangles.VertexFormat = DXGI_FORMAT_R32G32B32_FLOAT;
104 probe_tri.Triangles.VertexCount = 3;
105 probe_tri.Triangles.VertexBuffer.StrideInBytes = 12;
106 D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS probe_in{};
107 probe_in.Type = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL;
108 probe_in.DescsLayout = D3D12_ELEMENTS_LAYOUT_ARRAY;
109 probe_in.NumDescs = 1;
110 probe_in.pGeometryDescs = &probe_tri;
111 D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO probe_info{};
112 dev->GetRaytracingAccelerationStructurePrebuildInfo(&probe_in, &probe_info);
113 if (probe_info.ResultDataMaxSizeInBytes == 0 || probe_info.ScratchDataSizeInBytes == 0) {
114 std::printf("%s: neither XDXR nor KHR acceleration structures supported, skipping\n", name);
115 return 77;
116 }
117 }
96 118
97 Ref<ID3D12Resource> vb, inst_buf, scratch, blas_buf, tlas_buf, src_as, post_buf; 119 Ref<ID3D12Resource> vb, inst_buf, scratch, blas_buf, tlas_buf, src_as, post_buf;
98 if (!make_buffer(dev.p, 4096, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_FLAG_NONE, 120 if (!make_buffer(dev.p, 4096, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_FLAG_NONE,
@@ -164,10 +186,6 @@ int run_suite(ID3D12Device* base_dev, const char* name, bool check_strict_valida
164 in.pGeometryDescs = &tri; 186 in.pGeometryDescs = &tri;
165 dev->GetRaytracingAccelerationStructurePrebuildInfo(&in, &info); 187 dev->GetRaytracingAccelerationStructurePrebuildInfo(&in, &info);
166 if (info.ResultDataMaxSizeInBytes == 0 || info.ScratchDataSizeInBytes == 0) { 188 if (info.ResultDataMaxSizeInBytes == 0 || info.ScratchDataSizeInBytes == 0) {
167 if (check_strict_validation && o5.RaytracingTier == D3D12_RAYTRACING_TIER_NOT_SUPPORTED) {
168 std::printf("%s: neither XDXR nor KHR acceleration structures supported, skipping\n", name);
169 return 77;
170 }
171 std::fprintf(stderr, "%s: valid BLAS ARRAY prebuild returned zero\n", name); 189 std::fprintf(stderr, "%s: valid BLAS ARRAY prebuild returned zero\n", name);
172 return 1; 190 return 1;
173 } 191 }
diff --git a/runtime/test/d3d12_mesh_test.cpp b/runtime/test/d3d12_mesh_test.cpp
index df430c11a..1b99b8d0b 100644
--- a/runtime/test/d3d12_mesh_test.cpp
+++ b/runtime/test/d3d12_mesh_test.cpp
@@ -138,6 +138,7 @@ int main() {
138 info.buffer_device_address = true; 138 info.buffer_device_address = true;
139 info.shader_dir = library.string(); 139 info.shader_dir = library.string();
140 info.mesh_shader = mesh; 140 info.mesh_shader = mesh;
141 info.mesh_shader_queries = mesh && d.mesh_shader_queries;
141 info.pipeline_statistics_query = d.pipeline_statistics_query; 142 info.pipeline_statistics_query = d.pipeline_statistics_query;
142 return info; 143 return info;
143 }; 144 };
@@ -405,8 +406,15 @@ int main() {
405 // query 2 the two vertex draws alone. A mesh draw has no input assembly or vertex shader, so those fields 406 // query 2 the two vertex draws alone. A mesh draw has no input assembly or vertex shader, so those fields
406 // count only the two full-screen triangles (3 vertices, 1 primitive each). How many clipping and pixel 407 // count only the two full-screen triangles (3 vertices, 1 primitive each). How many clipping and pixel
407 // shader invocations a draw makes is the driver's (RADV's PSInvocations is not the pixel count), so query 408 // shader invocations a draw makes is the driver's (RADV's PSInvocations is not the pixel count), so query
408 // 0 is checked against query 2: more of both is the mesh segment's share. Under LEONIDA_VK_VALIDATION=1 the 409 // 0 is checked against query 2: more pixel shader invocations is the mesh segment's share. A mesh segment
409 // run must stay free of VUID-vkCmdDrawMeshTasksEXT-pipelineStatistics-07076. 410 // runs in a pool that counts the fragment and compute invocations only, because
411 // VUID-vkCmdDrawMeshTasksEXT-pipelineStatistics-07076 leaves the clipping counters out of a pool that is
412 // active during a mesh draw; D3D12 counts the clipping invocations and primitives of a mesh pipeline, so
413 // those two fields read 0 here. Under LEONIDA_VK_VALIDATION=1 the run must stay free of the VUID.
414 // Where the device has the meshShaderQueries feature, the clipping invocations of a mesh segment come
415 // from a mesh-primitives query instead (D3D-MESH-CLIPPING-COUNTER): the number of primitives the mesh
416 // shader emitted that reached the fragment shader. How many that is depends on the driver, so the counts
417 // are compared with each other and not written down.
410 if (d.pipeline_statistics_query) { 418 if (d.pipeline_statistics_query) {
411 const D3D12_QUERY_HEAP_DESC statistics_desc{D3D12_QUERY_HEAP_TYPE_PIPELINE_STATISTICS, 3, 0}; 419 const D3D12_QUERY_HEAP_DESC statistics_desc{D3D12_QUERY_HEAP_TYPE_PIPELINE_STATISTICS, 3, 0};
412 Ref<ID3D12QueryHeap> statistics; 420 Ref<ID3D12QueryHeap> statistics;
@@ -472,11 +480,26 @@ int main() {
472 EXPECT(vertex_only.IAVertices == 6 && vertex_only.IAPrimitives == 2); 480 EXPECT(vertex_only.IAVertices == 6 && vertex_only.IAPrimitives == 2);
473 EXPECT(mixed.GSInvocations == 0 && mixed.GSPrimitives == 0 && mixed.HSInvocations == 0 && 481 EXPECT(mixed.GSInvocations == 0 && mixed.GSPrimitives == 0 && mixed.HSInvocations == 0 &&
474 mixed.DSInvocations == 0 && mixed.CSInvocations == 0); 482 mixed.DSInvocations == 0 && mixed.CSInvocations == 0);
475 EXPECT(mixed.CInvocations > vertex_only.CInvocations && mixed.PSInvocations > vertex_only.PSInvocations); 483 // The clipping invocations of the mesh segments (D3D-MESH-CLIPPING-COUNTER). Without the feature they
484 // read 0; with it they are the mesh-primitives count of those segments.
485 const auto mesh_clipping = mixed.CInvocations - vertex_only.CInvocations;
486 if (d.mesh_shader_queries) {
487 // The count has to be wired up, not merely self-consistent. A layer that reported the feature but
488 // never created the third pool would leave both counts at 0, and 0 >= 0 would still hold. How many
489 // primitives the mesh shader emits is the driver's, so ask for a positive count and not for a
490 // number: the mesh draw above fills the top-left quadrant, so it emits at least one.
491 EXPECT(mesh_clipping >= mesh_only.CInvocations);
492 EXPECT(mesh_only.CInvocations > 0);
493 } else {
494 EXPECT(mesh_clipping == 0);
495 }
496 EXPECT(mixed.PSInvocations > vertex_only.PSInvocations);
476 EXPECT(mesh_only.IAVertices == 0 && mesh_only.IAPrimitives == 0 && mesh_only.VSInvocations == 0 && 497 EXPECT(mesh_only.IAVertices == 0 && mesh_only.IAPrimitives == 0 && mesh_only.VSInvocations == 0 &&
477 mesh_only.GSInvocations == 0 && mesh_only.GSPrimitives == 0 && mesh_only.HSInvocations == 0 && 498 mesh_only.GSInvocations == 0 && mesh_only.GSPrimitives == 0 && mesh_only.HSInvocations == 0 &&
478 mesh_only.DSInvocations == 0 && mesh_only.CSInvocations == 0); 499 mesh_only.DSInvocations == 0 && mesh_only.CSInvocations == 0);
479 EXPECT(mesh_only.CInvocations > 0 && mesh_only.PSInvocations > 0); 500 // Vulkan has no clipped-primitive counter, so the clipping primitives of a mesh segment stay 0.
501 EXPECT(mesh_only.CPrimitives == 0 && mesh_only.PSInvocations > 0);
502 if (!d.mesh_shader_queries) EXPECT(mesh_only.CInvocations == 0);
480 } else { 503 } else {
481 std::printf("pipelineStatisticsQuery not available: the D3D-291 statistics check is skipped\n"); 504 std::printf("pipelineStatisticsQuery not available: the D3D-291 statistics check is skipped\n");
482 } 505 }
diff --git a/runtime/test/d3d12_pipeline_library_host_test.cpp b/runtime/test/d3d12_pipeline_library_host_test.cpp
index e8b8c5795..3ed6341d8 100644
--- a/runtime/test/d3d12_pipeline_library_host_test.cpp
+++ b/runtime/test/d3d12_pipeline_library_host_test.cpp
@@ -3,9 +3,9 @@
3// corrupt blobs, the other device's serialized blob, the null-output capability check and other interfaces, and on 3// corrupt blobs, the other device's serialized blob, the null-output capability check and other interfaces, and on
4// an empty library StorePipeline / LoadComputePipeline / LoadGraphicsPipeline / LoadPipeline with null, empty and 4// an empty library StorePipeline / LoadComputePipeline / LoadGraphicsPipeline / LoadPipeline with null, empty and
5// unknown names and null PSOs, descriptions or outputs, and Serialize with null, short and long buffers. Every HRESULT 5// unknown names and null PSOs, descriptions or outputs, and Serialize with null, short and long buffers. Every HRESULT
6// is recorded, with whether the output pointer was written; the two records must be the same, step by step. The 6// and output pointer state are recorded. The public argument checks must agree step by step. Serialized sizes and
7// serialized size and bytes are each device's own format and are not compared. A step the host runtime faults on is 7// the result of changing a trailing byte are reported for each device's own format. Host faults are reported
8// reported and not compared. No shaders or game data. Skips (77) without a Vulkan GPU; without a host D3D12 device 8// separately. No shaders or game data. Skips (77) without a Vulkan GPU. Without a host D3D12 device,
9// only the layer's own record is printed. Set LEONIDA_D3D49_VERBOSE=1 to print every step. 9// only the layer's own record is printed. Set LEONIDA_D3D49_VERBOSE=1 to print every step.
10#include "vk_test_device.h" 10#include "vk_test_device.h"
11#include "../shims/d3d12_com.h" 11#include "../shims/d3d12_com.h"
@@ -105,7 +105,9 @@ const Step kSteps[] = {
105 longer.resize(longer.size() + 64, 0); 105 longer.resize(longer.size() + 64, 0);
106 return create(c, longer.data(), longer.size()); 106 return create(c, longer.data(), longer.size());
107 }}, 107 }},
108 {"create: its own blob, last byte flipped", [](Context& c) { 108 // The layer's empty LPL1 library contains only the header, so its last byte is in the reserved field.
109 // The native library has its own driver-specific layout.
110 {"create: its own blob, last byte flipped [own format]", [](Context& c) {
109 std::vector<std::uint8_t> flipped(c.own); 111 std::vector<std::uint8_t> flipped(c.own);
110 flipped.back() ^= 0xFF; 112 flipped.back() ^= 0xFF;
111 return create(c, flipped.data(), flipped.size()); 113 return create(c, flipped.data(), flipped.size());
diff --git a/runtime/test/d3d12_pipeline_library_test.cpp b/runtime/test/d3d12_pipeline_library_test.cpp
index 1ba930cc7..fb3c3ad03 100644
--- a/runtime/test/d3d12_pipeline_library_test.cpp
+++ b/runtime/test/d3d12_pipeline_library_test.cpp
@@ -206,8 +206,9 @@ int main() {
206 EXPECT(lib->LoadPipeline(L"gfx", &empty_stream, IID_PPV_ARGS(&wrong.p)) == E_INVALIDARG && !wrong.p); 206 EXPECT(lib->LoadPipeline(L"gfx", &empty_stream, IID_PPV_ARGS(&wrong.p)) == E_INVALIDARG && !wrong.p);
207 EXPECT(SUCCEEDED(lib->LoadPipeline(L"gfx", &stream_desc, IID_PPV_ARGS(&loaded_any.p))) && loaded_any.p); 207 EXPECT(SUCCEEDED(lib->LoadPipeline(L"gfx", &stream_desc, IID_PPV_ARGS(&loaded_any.p))) && loaded_any.p);
208 208
209 constexpr SIZE_T lpl1_header_size = 4 * sizeof(std::uint32_t);
209 const SIZE_T blob_size = lib->GetSerializedSize(); 210 const SIZE_T blob_size = lib->GetSerializedSize();
210 EXPECT(blob_size >= 16); 211 EXPECT(blob_size >= lpl1_header_size);
211 std::vector<std::uint8_t> blob(blob_size); 212 std::vector<std::uint8_t> blob(blob_size);
212 EXPECT(lib->Serialize(nullptr, blob_size) == E_INVALIDARG); 213 EXPECT(lib->Serialize(nullptr, blob_size) == E_INVALIDARG);
213 EXPECT(lib->Serialize(blob.data(), blob_size - 1) == E_INVALIDARG); 214 EXPECT(lib->Serialize(blob.data(), blob_size - 1) == E_INVALIDARG);
@@ -216,6 +217,12 @@ int main() {
216 Ref<ID3D12PipelineLibrary> reloaded; 217 Ref<ID3D12PipelineLibrary> reloaded;
217 EXPECT(SUCCEEDED(device->CreatePipelineLibrary(blob.data(), blob.size(), IID_PPV_ARGS(&reloaded.p))) && reloaded.p); 218 EXPECT(SUCCEEDED(device->CreatePipelineLibrary(blob.data(), blob.size(), IID_PPV_ARGS(&reloaded.p))) && reloaded.p);
218 219
220 // The final word in the LPL1 header is reserved and must be zero.
221 blob[lpl1_header_size - 1] ^= 0xFF;
222 Ref<ID3D12PipelineLibrary> rejected;
223 EXPECT(device->CreatePipelineLibrary(blob.data(), blob.size(), IID_PPV_ARGS(&rejected.p)) == E_INVALIDARG &&
224 !rejected.p);
225
219 // 4. Execute the loaded compute PSO and loaded graphics PSO on the GPU. 226 // 4. Execute the loaded compute PSO and loaded graphics PSO on the GPU.
220 Ref<ID3D12CommandQueue> queue; 227 Ref<ID3D12CommandQueue> queue;
221 const D3D12_COMMAND_QUEUE_DESC qd{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, D3D12_COMMAND_QUEUE_FLAG_NONE, 0}; 228 const D3D12_COMMAND_QUEUE_DESC qd{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, D3D12_COMMAND_QUEUE_FLAG_NONE, 0};
diff --git a/runtime/test/d3d12_state_map_test.cpp b/runtime/test/d3d12_state_map_test.cpp
index 9db6ad0c1..2fec30ba4 100644
--- a/runtime/test/d3d12_state_map_test.cpp
+++ b/runtime/test/d3d12_state_map_test.cpp
@@ -404,7 +404,10 @@ int main() {
404 CHECK(vulkan_sync(y::split) == VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT); 404 CHECK(vulkan_sync(y::split) == VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT);
405 CHECK(vulkan_sync(y::render_target) == VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT); 405 CHECK(vulkan_sync(y::render_target) == VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT);
406 CHECK(vulkan_sync(y::copy | y::pixel_shading) == 406 CHECK(vulkan_sync(y::copy | y::pixel_shading) ==
407 (VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT)); 407 (VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_CLEAR_BIT | VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT));
408 // SYNC_COPY covers WriteBufferImmediate (vkCmdUpdateBuffer) and ResolveQueryData's zero fill (vkCmdFillBuffer),
409 // which synchronization2 runs in the CLEAR stage, not COPY (D3D-838).
410 CHECK(vulkan_sync(y::copy) == (VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_CLEAR_BIT));
408 CHECK(vulkan_sync(y::raytracing) == VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT); 411 CHECK(vulkan_sync(y::raytracing) == VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT);
409 CHECK(vulkan_barrier_access(a::no_access) == VK_ACCESS_2_NONE); 412 CHECK(vulkan_barrier_access(a::no_access) == VK_ACCESS_2_NONE);
410 const auto cb_scope = vulkan_barrier_scope(y::pixel_shading, a::constant_buffer); 413 const auto cb_scope = vulkan_barrier_scope(y::pixel_shading, a::constant_buffer);
@@ -427,7 +430,8 @@ int main() {
427 widened = scope(y::clear_unordered_access_view, a::copy_source); // CLEAR only writes 430 widened = scope(y::clear_unordered_access_view, a::copy_source); // CLEAR only writes
428 CHECK(widened.stages & VK_PIPELINE_STAGE_2_ALL_TRANSFER_BIT); 431 CHECK(widened.stages & VK_PIPELINE_STAGE_2_ALL_TRANSFER_BIT);
429 widened = scope(y::copy, a::unordered_access); 432 widened = scope(y::copy, a::unordered_access);
430 CHECK(widened.stages == (VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_PRE_RASTERIZATION_SHADERS_BIT | 433 CHECK(widened.stages == (VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_CLEAR_BIT |
434 VK_PIPELINE_STAGE_2_PRE_RASTERIZATION_SHADERS_BIT |
431 VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT)); 435 VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT));
432 // Pairs Vulkan already accepts are left exactly as vulkan_sync / vulkan_barrier_access map them. 436 // Pairs Vulkan already accepts are left exactly as vulkan_sync / vulkan_barrier_access map them.
433 const std::pair<std::uint32_t, std::uint32_t> unchanged[] = { 437 const std::pair<std::uint32_t, std::uint32_t> unchanged[] = {
diff --git a/runtime/test/d3d12_vulkan_device_test.cpp b/runtime/test/d3d12_vulkan_device_test.cpp
index 056e82561..99bb6d1a4 100644
--- a/runtime/test/d3d12_vulkan_device_test.cpp
+++ b/runtime/test/d3d12_vulkan_device_test.cpp
@@ -5168,6 +5168,12 @@ int main() {
5168 EXPECT(SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof(options)))); 5168 EXPECT(SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof(options))));
5169 EXPECT(options.ResourceBindingTier == D3D12_RESOURCE_BINDING_TIER_3); 5169 EXPECT(options.ResourceBindingTier == D3D12_RESOURCE_BINDING_TIER_3);
5170 EXPECT(options.MaxGPUVirtualAddressBitsPerResource == 40); 5170 EXPECT(options.MaxGPUVirtualAddressBitsPerResource == 40);
5171 // Console 0x40-byte (16-dword) D3D12_OPTIONS query (docs/d3d12_xs_surface.md §7.1): 0x3C PC prefix + zero tail.
5172 UINT console_opts[16]{};
5173 console_opts[15] = 0xdeadbeefu;
5174 EXPECT(SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, console_opts, sizeof(console_opts))));
5175 EXPECT(std::memcmp(console_opts, &options, sizeof(options)) == 0);
5176 EXPECT(console_opts[15] == 0);
5171 5177
5172 D3D12_FEATURE_DATA_GPU_VIRTUAL_ADDRESS_SUPPORT va_support{}; 5178 D3D12_FEATURE_DATA_GPU_VIRTUAL_ADDRESS_SUPPORT va_support{};
5173 EXPECT(SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_GPU_VIRTUAL_ADDRESS_SUPPORT, &va_support, sizeof(va_support)))); 5179 EXPECT(SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_GPU_VIRTUAL_ADDRESS_SUPPORT, &va_support, sizeof(va_support))));
diff --git a/runtime/test/frame_pacer_test.cpp b/runtime/test/frame_pacer_test.cpp
index 8d089acda..81b647fd2 100644
--- a/runtime/test/frame_pacer_test.cpp
+++ b/runtime/test/frame_pacer_test.cpp
@@ -586,6 +586,155 @@ int main() {
586 EXPECT(ms.count() >= 45 && ms.count() < 1000); 586 EXPECT(ms.count() >= 45 && ms.count() < 1000);
587 } 587 }
588 588
589 // TOKEN_ON_TIMEOUT (flag 2) and multi-event pacing (origin poll + blocking flip/vblank wait).
590 {
591 ManualFrameClock clock;
592 FramePacer pacer(clock);
593 EXPECT(pacer.set_frame_interval(period, 3, 0) == pacer_hr::ok);
594 EXPECT(pacer.schedule_frame_event(frame_event_origin, 0, 0) == pacer_hr::ok);
595 EXPECT(pacer.schedule_frame_event(frame_event_vblank, 0, 0) == pacer_hr::ok);
596 EXPECT(pacer.schedule_frame_event(frame_event_flip, 0, 0) == pacer_hr::ok);
597
598 // Origin poll with timeout 0 and TOKEN_ON_TIMEOUT issues a consecutive token and returns S_FALSE.
599 std::uint64_t tok1 = 0;
600 EXPECT(pacer.wait_frame_event(frame_event_origin, 0, frame_wait_flag_token_on_timeout, &tok1) ==
601 pacer_hr::false_);
602 EXPECT(tok1 == 1);
603 EXPECT(pacer.check_present_token(tok1) == pacer_hr::ok);
604
605 // A blocking flip wait paces to the next tick and preserves the caller's token unchanged.
606 auto flip_wait = std::async(std::launch::async, [&] {
607 std::uint64_t preserved = tok1;
608 const std::int32_t hr = pacer.wait_frame_event(frame_event_flip, infinite_timeout_ms, 0, &preserved);
609 return Result{hr, preserved};
610 });
611 EXPECT(blocked(flip_wait));
612 clock.advance_us(period);
613 const Result fr = flip_wait.get();
614 EXPECT(fr.hr == pacer_hr::ok && fr.token == tok1);
615
616 // Second flip wait blocks for the following tick; vblank wait on tick 1 succeeds immediately (independent).
617 EXPECT(pacer.wait_frame_event(frame_event_vblank, 0, 0, nullptr) == pacer_hr::ok);
618 auto flip_wait2 = std::async(std::launch::async, [&] {
619 return Result{pacer.wait_frame_event(frame_event_flip, infinite_timeout_ms, 0, nullptr), 0};
620 });
621 EXPECT(blocked(flip_wait2));
622 clock.advance_us(period);
623 EXPECT(flip_wait2.get().hr == pacer_hr::ok);
624
625 // Origin wait at tick 2 advances consecutively after the early-started token 1.
626 std::uint64_t tok2 = 0;
627 EXPECT(pacer.wait_frame_event(frame_event_origin, 0, 0, &tok2) == pacer_hr::ok && tok2 == 2);
628 }
629
630 // BL-6: frame pacing drift reporting (p50/p95/p99 frame times, mean drift vs target interval,
631 // origin-to-present latency, ring-buffer wrap-around, suspend/resume gap exclusion, and uncapped mode).
632 {
633 auto near = [](double a, double b) { return (a > b ? a - b : b - a) < 1e-6; };
634
635 // 1) Empty and single-frame edge cases.
636 ManualFrameClock clock;
637 FramePacer pacer(clock);
638 EXPECT(setup(pacer, 2));
639 FramePacingSummary s0 = pacer.pacing_summary();
640 EXPECT(s0.frames == 0 && s0.samples == 0 && s0.target_interval_us == period);
641 EXPECT(near(s0.mean_us, 0.0) && near(s0.drift_us, 0.0));
642 EXPECT(s0.p50_us == 0 && s0.p95_us == 0 && s0.p99_us == 0 && s0.latency_samples == 0);
643
644 clock.advance_us(period);
645 std::uint64_t tok = 0;
646 EXPECT(pacer.wait_frame_event(frame_event_origin, 0, 0, &tok) == pacer_hr::ok);
647 clock.advance_us(2000);
648 pacer.commit_present_token(tok, 1);
649 FramePacingSummary s1 = pacer.pacing_summary();
650 EXPECT(s1.frames == 1 && s1.samples == 0 && s1.latency_samples == 1 && s1.latency_p50_us == 2000);
651 EXPECT(near(s1.mean_us, 0.0) && near(s1.drift_us, 0.0));
652
653 // 2) 100 known intervals (16000 + 100*i us for i = 1..100) and known origin->present latencies:
654 // mean = 16000 + 5050 = 21050.0 us, drift = +5050.0 us,
655 // nearest-rank p50 = 16000 + 50*100 = 21000, p95 = 25500, p99 = 25900.
656 ManualFrameClock clock2;
657 FramePacer pacer2(clock2);
658 EXPECT(setup(pacer2, 4));
659 // Present an anchor frame first at t = period + 1000 (latency = 1000 us).
660 clock2.advance_us(period);
661 std::uint64_t t = 0;
662 EXPECT(pacer2.wait_frame_event(frame_event_origin, 0, 0, &t) == pacer_hr::ok);
663 clock2.advance_us(1000);
664 pacer2.commit_present_token(t, 1);
665 for (std::uint64_t i = 1; i <= 100; ++i) {
666 const std::uint64_t dt = period + i * 100;
667 clock2.advance_us(dt);
668 // Issue token after dt - (i * 50)? Simpler: issue token at origin (which passed), present immediately.
669 std::uint64_t tok_i = 0;
670 EXPECT(pacer2.wait_frame_event(frame_event_origin, 0, 0, &tok_i) == pacer_hr::ok);
671 pacer2.commit_present_token(tok_i, 1);
672 }
673 const FramePacingSummary s100 = pacer2.pacing_summary();
674 EXPECT(s100.frames == 101 && s100.samples == 100 && s100.target_interval_us == period);
675 EXPECT(near(s100.mean_us, 21050.0));
676 EXPECT(near(s100.drift_us, 5050.0));
677 EXPECT(s100.p50_us == 21000 && s100.p95_us == 25500 && s100.p99_us == 25900);
678 EXPECT(s100.latency_samples == 101);
679
680 // 3) Negative drift (untokened/early presents faster than target period) + exact origin-to-present latency.
681 ManualFrameClock clock3;
682 FramePacer pacer3(clock3);
683 EXPECT(setup(pacer3, 4));
684 clock3.advance_us(period);
685 EXPECT(pacer3.wait_frame_event(frame_event_origin, 0, 0, &t) == pacer_hr::ok);
686 clock3.advance_us(3000); // latency = 3000
687 pacer3.commit_present_token(t, 1);
688 clock3.advance_us(10000); // dt = 10000 (< 16000) -> drift = -6000
689 pacer3.note_untokened_present();
690 const FramePacingSummary sneg = pacer3.pacing_summary();
691 EXPECT(sneg.frames == 2 && sneg.samples == 1 && sneg.target_interval_us == period);
692 EXPECT(near(sneg.mean_us, 10000.0) && near(sneg.drift_us, -6000.0));
693 EXPECT(sneg.p50_us == 10000 && sneg.p95_us == 10000 && sneg.p99_us == 10000);
694 EXPECT(sneg.latency_samples == 1 && sneg.latency_p50_us == 3000 && sneg.latency_p99_us == 3000);
695
696 // 4) Suspend/resume gap is excluded from frame intervals.
697 pacer3.suspend();
698 clock3.advance_us(5'000'000); // 5 second pause while suspended
699 pacer3.resume();
700 EXPECT(setup(pacer3, 2));
701 clock3.advance_us(period);
702 EXPECT(pacer3.wait_frame_event(frame_event_origin, 0, 0, &t) == pacer_hr::ok);
703 pacer3.commit_present_token(t, 1);
704 const FramePacingSummary ssusp = pacer3.pacing_summary();
705 EXPECT(ssusp.frames == 3 && ssusp.samples == 1 && ssusp.p99_us == 10000); // 5s gap not recorded
706
707 // 5) Ring-buffer wrap-around: fill with slow 32000 us frames, then overwrite entire window with steady 16000 us.
708 ManualFrameClock clock4;
709 FramePacer pacer4(clock4);
710 EXPECT(setup(pacer4, 2));
711 clock4.advance_us(period);
712 EXPECT(pacer4.wait_frame_event(frame_event_origin, 0, 0, &t) == pacer_hr::ok);
713 pacer4.commit_present_token(t, 1);
714 for (std::size_t i = 0; i < frame_pacing_window; ++i) {
715 clock4.advance_us(period * 2);
716 EXPECT(pacer4.wait_frame_event(frame_event_origin, 0, 0, &t) == pacer_hr::ok);
717 pacer4.commit_present_token(t, 1);
718 }
719 const FramePacingSummary slow = pacer4.pacing_summary();
720 EXPECT(slow.samples == frame_pacing_window && near(slow.mean_us, double(period * 2)) &&
721 near(slow.drift_us, double(period)));
722 for (std::size_t i = 0; i < frame_pacing_window; ++i) {
723 clock4.advance_us(period);
724 EXPECT(pacer4.wait_frame_event(frame_event_origin, 0, 0, &t) == pacer_hr::ok);
725 pacer4.commit_present_token(t, 1);
726 }
727 const FramePacingSummary steady = pacer4.pacing_summary();
728 EXPECT(steady.frames == 1 + 2 * frame_pacing_window && steady.samples == frame_pacing_window);
729 EXPECT(near(steady.mean_us, double(period)) && near(steady.drift_us, 0.0));
730 EXPECT(steady.p50_us == period && steady.p95_us == period && steady.p99_us == period);
731
732 // 6) Uncapped mode: target_interval_us == 0 and drift_us == 0 while intervals are still tracked.
733 pacer4.set_uncapped(true);
734 const FramePacingSummary uncap = pacer4.pacing_summary();
735 EXPECT(uncap.target_interval_us == 0 && near(uncap.drift_us, 0.0) && uncap.p50_us == period);
736 }
737
589 std::printf("frame_pacer_test: all cases pass\n"); 738 std::printf("frame_pacer_test: all cases pass\n");
590 return 0; 739 return 0;
591} 740}
diff --git a/runtime/test/gfx10_descriptors_test.cpp b/runtime/test/gfx10_descriptors_test.cpp
index 523180ee7..85843edb8 100644
--- a/runtime/test/gfx10_descriptors_test.cpp
+++ b/runtime/test/gfx10_descriptors_test.cpp
@@ -359,18 +359,21 @@ int main() {
359 CHECK(info.addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE && info.mipLodBias == -0.75f); 359 CHECK(info.addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE && info.mipLodBias == -0.75f);
360 CHECK(info.minLod == 0.5f && info.maxLod == 4.25f); 360 CHECK(info.minLod == 0.5f && info.maxLod == 4.25f);
361 info = vulkan_sampler({.mag_filter = Filter::aniso_point, .mip_filter = MipFilter::linear, .max_anisotropy = 8, 361 info = vulkan_sampler({.mag_filter = Filter::aniso_point, .mip_filter = MipFilter::linear, .max_anisotropy = 8,
362 .compare = CompareFunction::greater, .max_lod = 9.0f, .unnormalized = true}); 362 .compare = CompareFunction::greater, .min_lod = 1.5f, .max_lod = 9.0f,
363 .lod_bias = 2.5f, .unnormalized = true});
363 CHECK(info.unnormalizedCoordinates == VK_TRUE && info.mipmapMode == VK_SAMPLER_MIPMAP_MODE_NEAREST); 364 CHECK(info.unnormalizedCoordinates == VK_TRUE && info.mipmapMode == VK_SAMPLER_MIPMAP_MODE_NEAREST);
364 CHECK(info.maxLod == 0.0f && info.anisotropyEnable == VK_FALSE && info.compareEnable == VK_FALSE); 365 CHECK(info.minLod == 0.0f && info.maxLod == 0.0f && info.mipLodBias == 0.0f);
366 CHECK(info.anisotropyEnable == VK_FALSE && info.compareEnable == VK_FALSE);
365 // Unnormalised: U and V clamp (wrap, the default S# mode, would be invalid: VUID ...-01075), border stays border, 367 // Unnormalised: U and V clamp (wrap, the default S# mode, would be invalid: VUID ...-01075), border stays border,
366 // W is free; min and mag filter agree (VUID ...-01072). 368 // W is free; min and mag filter agree (VUID ...-01072); mipLodBias is zero (VUID ...-01074).
367 CHECK(info.addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE && 369 CHECK(info.addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE &&
368 info.addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE && 370 info.addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE &&
369 info.addressModeW == VK_SAMPLER_ADDRESS_MODE_REPEAT && info.minFilter == info.magFilter); 371 info.addressModeW == VK_SAMPLER_ADDRESS_MODE_REPEAT && info.minFilter == info.magFilter);
370 info = vulkan_sampler({.address_u = AddressMode::clamp_border, .address_v = AddressMode::mirror, 372 info = vulkan_sampler({.address_u = AddressMode::clamp_border, .address_v = AddressMode::mirror,
371 .min_filter = Filter::bilinear, .unnormalized = true}); 373 .min_filter = Filter::bilinear, .lod_bias = -3.25f, .unnormalized = true});
372 CHECK(info.addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER && 374 CHECK(info.addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER &&
373 info.addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE && info.minFilter == VK_FILTER_NEAREST); 375 info.addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE && info.minFilter == VK_FILTER_NEAREST &&
376 info.mipLodBias == 0.0f);
374 CHECK(vulkan_address_mode(AddressMode::mirror) == VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT); 377 CHECK(vulkan_address_mode(AddressMode::mirror) == VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT);
375 CHECK(vulkan_address_mode(AddressMode::mirror_once_last_texel) == VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE); 378 CHECK(vulkan_address_mode(AddressMode::mirror_once_last_texel) == VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE);
376 CHECK(vulkan_address_mode(AddressMode::clamp_half_border) == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE); 379 CHECK(vulkan_address_mode(AddressMode::clamp_half_border) == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE);
diff --git a/runtime/test/loader_tls_test.cpp b/runtime/test/loader_tls_test.cpp
index 625ff6d86..133b27c81 100644
--- a/runtime/test/loader_tls_test.cpp
+++ b/runtime/test/loader_tls_test.cpp
@@ -790,7 +790,8 @@ void test_ga_tls_existing_thread(const fs::path& exe) {
790 { 790 {
791 rt::Loader loader(exe.parent_path()); 791 rt::Loader loader(exe.parent_path());
792 rt::Module& m = loader.load(exe); 792 rt::Module& m = loader.load(exe);
793 check(m.tls_index != 0, "the /GA fixture gets a module TLS index other than the process EXE's 0"); 793 check(m.tls_index != rt::kNoTlsIndex && m.tls_index != 0,
794 "the /GA fixture gets a valid module TLS index other than the process EXE's 0");
794 check(m.tls_ga_slot != rt::kNoTlsIndex, "load() rewrites the /GA fixture's index-0 TLS reads"); 795 check(m.tls_ga_slot != rt::kNoTlsIndex, "load() rewrites the /GA fixture's index-0 TLS reads");
795 get = find_export<int(__cdecl*)()>(m, "ga_tls_get"); 796 get = find_export<int(__cdecl*)()>(m, "ga_tls_get");
796 set = find_export<void(__cdecl*)(int)>(m, "ga_tls_set"); 797 set = find_export<void(__cdecl*)(int)>(m, "ga_tls_set");
diff --git a/runtime/test/mods_test.cpp b/runtime/test/mods_test.cpp
index a29979b25..e95bc4e16 100644
--- a/runtime/test/mods_test.cpp
+++ b/runtime/test/mods_test.cpp
@@ -41,6 +41,9 @@ int main() {
41 check(!parse_model_id("0x123456789", id), "a hash wider than 32 bits is refused"); 41 check(!parse_model_id("0x123456789", id), "a hash wider than 32 bits is refused");
42 check(!parse_model_id("0xZZ", id), "a malformed hash is refused"); 42 check(!parse_model_id("0xZZ", id), "a malformed hash is refused");
43 check(!parse_model_id("", id), "an empty name is refused"); 43 check(!parse_model_id("", id), "an empty name is refused");
44 id = 0xCAFEBABEu;
45 check(!parse_model_id("0x", id) && id == 0xCAFEBABEu, "a bare 0x prefix is refused");
46 check(!parse_model_id("0X", id) && id == 0xCAFEBABEu, "a bare 0X prefix is refused");
44 47
45 Mod mod; 48 Mod mod;
46 std::string error; 49 std::string error;
@@ -53,6 +56,8 @@ int main() {
53 "a condition the runtime cannot honour yet is refused, not ignored"); 56 "a condition the runtime cannot honour yet is refused, not ignored");
54 check(!parse_mod(R"({"archetype_swaps":[{"from":"cs_mandy","to":"0xD7C0CDFF"}]})", "m", mod, error), 57 check(!parse_mod(R"({"archetype_swaps":[{"from":"cs_mandy","to":"0xD7C0CDFF"}]})", "m", mod, error),
55 "a swap of a model with itself is refused"); 58 "a swap of a model with itself is refused");
59 check(!parse_mod(R"({"archetype_swaps":[{"from":"0x","to":"cs_mandy"}]})", "m", mod, error),
60 "a bare 0x prefix in an archetype swap is refused");
56 check(!parse_mod(R"({"enabled":"yes"})", "m", mod, error), "\"enabled\" must be a boolean"); 61 check(!parse_mod(R"({"enabled":"yes"})", "m", mod, error), "\"enabled\" must be a boolean");
57 check(!parse_mod("[1,2]", "m", mod, error), "a manifest that is not an object is refused"); 62 check(!parse_mod("[1,2]", "m", mod, error), "a manifest that is not an object is refused");
58 check(parse_mod("{}", "folder_name", mod, error) && mod.name == "folder_name", "the name defaults to the folder"); 63 check(parse_mod("{}", "folder_name", mod, error) && mod.name == "folder_name", "the name defaults to the folder");
diff --git a/runtime/test/replay_copy_offset_test.cpp b/runtime/test/replay_copy_offset_test.cpp
index 7392344ff..b5f93c102 100644
--- a/runtime/test/replay_copy_offset_test.cpp
+++ b/runtime/test/replay_copy_offset_test.cpp
@@ -310,6 +310,103 @@ int main() {
310 dst_buf = saved_dst; 310 dst_buf = saved_dst;
311 } 311 }
312 312
313 // 6. tile_footprint unaligned staging honors format alignment (8B, 16B, BC1) and 3D slice layout.
314 {
315 const auto saved_src = src_buf, saved_dst = dst_buf;
316 VkDeviceSize scratch_req = 0;
317 vk.copy_scratch = [&](std::uint64_t bytes, VkBuffer& buf, VkDeviceSize& off) {
318 scratch_req = bytes;
319 buf = handle<VkBuffer>(0xA000);
320 off = 256;
321 return true;
322 };
323
324 ResourceBinding rgba16f_img{};
325 rgba16f_img.image = handle<VkImage>(6);
326 rgba16f_img.format = VK_FORMAT_R16G16B16A16_SFLOAT; // 8 bytes/texel
327 rgba16f_img.aspects = VK_IMAGE_ASPECT_COLOR_BIT;
328 rgba16f_img.width = 8;
329 rgba16f_img.height = 4;
330 rgba16f_img.mip_levels = 1;
331 rgba16f_img.array_layers = 1;
332 rgba16f_img.depth = 2;
333 rgba16f_img.volume = true;
334 rgba16f_img.samples = 1;
335
336 ResourceBinding bc1_img{};
337 bc1_img.image = handle<VkImage>(7);
338 bc1_img.format = VK_FORMAT_BC1_RGBA_UNORM_BLOCK; // 8 bytes per 4x4 block
339 bc1_img.aspects = VK_IMAGE_ASPECT_COLOR_BIT;
340 bc1_img.width = 12;
341 bc1_img.height = 8;
342 bc1_img.mip_levels = 1;
343 bc1_img.array_layers = 1;
344 bc1_img.depth = 1;
345 bc1_img.samples = 1;
346
347 const auto resolve_tile = [&](ResourceId id) -> const ResourceBinding* {
348 if (id == 6) return &rgba16f_img;
349 if (id == 7) return &bc1_img;
350 return resolve(id);
351 };
352
353 // 6a. 8-byte 3D texture with bufferOffset = 4 (4-byte aligned, NOT 8-byte aligned): must stage both slices.
354 src_buf.buffer_offset = 0;
355 src_buf.size = 4096;
356 {
357 const CopyLocation tex{6, false, 0, 0, 0, 0, 0, 0};
358 // footprint: width=8, height=4, depth=2, row_pitch=256 (32 texels/row, slice_pitch=1024), offset=4
359 const CopyLocation fp{1, true, 0, 4, 8, 4, 2, 256};
360 CopyTexture copy{tex, 0, 0, 0, fp, true, {0, 0, 0, 4, 2, 2}}; // 4x2x2 texels -> 32B/row, 2 rows, 2 slices = 128B
361 copy.tile_footprint = true;
362 CommandList list;
363 expect(list.copy_texture(copy) && list.close(), "record 8B 3D tile_footprint upload");
364 buffer_copies.clear();
365 b2i_copies.clear();
366 scratch_req = 0;
367 expect(replay(list, VK_NULL_HANDLE, resolve_tile, vk) == ReplayResult::success,
368 "8B 3D tile_footprint upload with offset=4 replays");
369 expect(scratch_req == 128, "8B 3D tile_footprint allocates 4*8 * 2 * 2 = 128 bytes of scratch");
370 expect(buffer_copies.size() == 4, "8B 3D tile_footprint stages 2 rows x 2 slices");
371 expect(buffer_copies.size() == 4 &&
372 buffer_copies[0].srcOffset == 4 && buffer_copies[0].dstOffset == 256 && buffer_copies[0].size == 32 &&
373 buffer_copies[1].srcOffset == 260 && buffer_copies[1].dstOffset == 288 && buffer_copies[1].size == 32 &&
374 buffer_copies[2].srcOffset == 1028 && buffer_copies[2].dstOffset == 320 && buffer_copies[2].size == 32 &&
375 buffer_copies[3].srcOffset == 1284 && buffer_copies[3].dstOffset == 352 && buffer_copies[3].size == 32,
376 "8B 3D tile_footprint row/slice strides match 256B row_pitch and 1024B slice_pitch");
377 expect(b2i_copies.size() == 1 && b2i_copies[0].bufferOffset == 256 &&
378 b2i_copies[0].bufferRowLength == 0 && b2i_copies[0].bufferImageHeight == 0,
379 "8B 3D tile_footprint emits aligned scratch offset and clears row/image height");
380 }
381
382 // 6b. BC1 (8B per 4x4 block) with bufferOffset = 4: must stage 2x2 blocks = 32B, not texels*4.
383 {
384 const CopyLocation tex{7, false, 0, 0, 0, 0, 0, 0};
385 // footprint: width=12 (3 blocks), height=8 (2 blocks), row_pitch=256 (32*8B), offset=4
386 const CopyLocation fp{1, true, 0, 4, 12, 8, 1, 256};
387 CopyTexture copy{tex, 0, 0, 0, fp, true, {0, 0, 0, 8, 8, 1}}; // 2x2 blocks: 16B/row, 2 rows = 32B
388 copy.tile_footprint = true;
389 CommandList list;
390 expect(list.copy_texture(copy) && list.close(), "record BC1 tile_footprint upload");
391 buffer_copies.clear();
392 b2i_copies.clear();
393 scratch_req = 0;
394 expect(replay(list, VK_NULL_HANDLE, resolve_tile, vk) == ReplayResult::success,
395 "BC1 tile_footprint upload with offset=4 replays");
396 expect(scratch_req == 32, "BC1 tile_footprint allocates 2*8 * 2 = 32 bytes of scratch");
397 expect(buffer_copies.size() == 2 &&
398 buffer_copies[0].srcOffset == 4 && buffer_copies[0].dstOffset == 256 && buffer_copies[0].size == 16 &&
399 buffer_copies[1].srcOffset == 260 && buffer_copies[1].dstOffset == 272 && buffer_copies[1].size == 16,
400 "BC1 tile_footprint copies 16B block rows at 256B pitch");
401 expect(b2i_copies.size() == 1 && b2i_copies[0].bufferOffset == 256 && b2i_copies[0].bufferRowLength == 0,
402 "BC1 tile_footprint emits aligned scratch offset");
403 }
404
405 vk.copy_scratch = {};
406 src_buf = saved_src;
407 dst_buf = saved_dst;
408 }
409
313 if (failures) return 1; 410 if (failures) return 1;
314 std::printf("replay_copy_offset: CopyResource and CopyTexture apply ResourceBinding::buffer_offset\n"); 411 std::printf("replay_copy_offset: CopyResource and CopyTexture apply ResourceBinding::buffer_offset\n");
315 return 0; 412 return 0;
diff --git a/runtime/test/replay_query_edges_test.cpp b/runtime/test/replay_query_edges_test.cpp
index 820dc0dc1..1e3da7c29 100644
--- a/runtime/test/replay_query_edges_test.cpp
+++ b/runtime/test/replay_query_edges_test.cpp
@@ -1,6 +1,7 @@
1// Query heap boundaries, resolve helper chunking, arena offsets, query reuse across lists/submissions, and 1// Query heap boundaries, resolve helper chunking, arena offsets, query reuse across lists/submissions, the mesh
2// predication around copies. These edge cases are only reached by GPU tests today; this CPU mock lets CI 2// pool of a statistics query and predication around copies. These edge cases are only reached by GPU tests today;
3// without a GPU check replay planning, emitted commands, destination guards, and pool ownership on submit failure. 3// this CPU mock lets CI without a GPU check replay planning, emitted commands, destination guards, and pool ownership
4// on submit failure.
4// Shader arithmetic and Vulkan entry points are mocked; no driver is loaded. No GPU or game data. 5// Shader arithmetic and Vulkan entry points are mocked; no driver is loaded. No GPU or game data.
5#include "../src/vulkan_backend.h" 6#include "../src/vulkan_backend.h"
6 7
@@ -61,7 +62,10 @@ struct MockReplay {
61 std::vector<Call> copies; 62 std::vector<Call> copies;
62 std::vector<std::pair<VkQueryPool, unsigned>> resets; 63 std::vector<std::pair<VkQueryPool, unsigned>> resets;
63 std::set<VkQueryPool> statistics_pools; 64 std::set<VkQueryPool> statistics_pools;
65 std::set<VkQueryPool> mesh_pools; // pools with the two counters a mesh draw allows (D3D-291)
66 std::set<VkQueryPool> primitives_pools; // the mesh-primitives count of a mesh segment (D3D-MESH-CLIPPING-COUNTER)
64 std::vector<unsigned> chunks; 67 std::vector<unsigned> chunks;
68 std::vector<unsigned> meshes; // statistics_sum.comp's mesh flag, one per chunk
65 std::vector<unsigned> groups; 69 std::vector<unsigned> groups;
66 std::vector<VkBufferCopy> transfers; 70 std::vector<VkBufferCopy> transfers;
67 std::vector<std::string> events; 71 std::vector<std::string> events;
@@ -111,8 +115,12 @@ struct MockReplay {
111 copies.push_back({p, first, count, off, stride}); 115 copies.push_back({p, first, count, off, stride});
112 auto& q = values.at(p); 116 auto& q = values.at(p);
113 expect(first <= q.size() && count <= q.size() - first, "mock query access out of bounds"); 117 expect(first <= q.size() && count <= q.size() - first, "mock query access out of bounds");
118 // A mesh pool counts two counters, not the eleven of the full pool (D3D-291).
119 const unsigned counters = mesh_pools.count(p) ? 2u
120 : primitives_pools.count(p) ? 1u
121 : (stride == statistics_size ? statistics_counters : 1u);
114 for (unsigned i = 0; i < count; ++i) { 122 for (unsigned i = 0; i < count; ++i) {
115 for (unsigned j = 0; j < (stride == statistics_size ? statistics_counters : 1u); ++j) { 123 for (unsigned j = 0; j < counters; ++j) {
116 word(b, off + i * stride + word_size * j, q[first + i][j]); 124 word(b, off + i * stride + word_size * j, q[first + i][j]);
117 } 125 }
118 } 126 }
@@ -239,8 +247,8 @@ struct MockReplay {
239 VkDeviceSize off) { 247 VkDeviceSize off) {
240 helper(false, false, p, f, n, b, off); 248 helper(false, false, p, f, n, b, off);
241 }; 249 };
242 v.sum_statistics = [helper](VkCommandBuffer, VkQueryPool p, VkQueryPool, const std::uint8_t*, unsigned f, 250 v.sum_statistics = [helper](VkCommandBuffer, VkQueryPool p, VkQueryPool, VkQueryPool, const std::uint8_t*,
243 unsigned n, VkBuffer b, VkDeviceSize off) { 251 unsigned f, unsigned n, VkBuffer b, VkDeviceSize off) {
244 helper(true, false, p, f, n, b, off); 252 helper(true, false, p, f, n, b, off);
245 }; 253 };
246 v.resolve_binary_occlusion = [helper](VkCommandBuffer, VkQueryPool p, unsigned f, unsigned n, VkBuffer b, 254 v.resolve_binary_occlusion = [helper](VkCommandBuffer, VkQueryPool p, unsigned f, unsigned n, VkBuffer b,
@@ -286,26 +294,33 @@ void test_helper_chunks() {
286 const VkDescriptorSet*, unsigned, const unsigned*) {}; 294 const VkDescriptorSet*, unsigned, const unsigned*) {};
287 vk.vkCmdPushConstants = +[](VkCommandBuffer, VkPipelineLayout, VkShaderStageFlags, unsigned off, unsigned size, 295 vk.vkCmdPushConstants = +[](VkCommandBuffer, VkPipelineLayout, VkShaderStageFlags, unsigned off, unsigned size,
288 const void*p) { 296 const void*p) {
289 // The count, then statistics_sum.comp's mesh flag (D3D-291), which no segment here sets. 297 // The count, then statistics_sum.comp's mesh flag (D3D-291).
290 expect(off == 0 && size == 2 * sizeof(unsigned), "chunk push constants"); 298 expect(off == 0 && size == 2 * sizeof(unsigned), "chunk push constants");
291 expect(static_cast<const unsigned *>(p)[1] == 0, "chunk push constants: no mesh segment"); 299 MockReplay::current->chunks.push_back(static_cast<const unsigned *>(p)[0]);
292 MockReplay::current->chunks.push_back(*static_cast<const unsigned *>(p)); 300 MockReplay::current->meshes.push_back(static_cast<const unsigned *>(p)[1]);
293 }; 301 };
294 vk.vkCmdDispatch = +[](VkCommandBuffer, unsigned x, unsigned y, unsigned z) { 302 vk.vkCmdDispatch = +[](VkCommandBuffer, unsigned x, unsigned y, unsigned z) {
295 auto& c = *MockReplay::current; 303 auto& c = *MockReplay::current;
296 c.groups.push_back(x); 304 c.groups.push_back(x);
297 expect(y == 1 && z == 1, "dispatch dimensions"); 305 expect(y == 1 && z == 1, "dispatch dimensions");
298 auto n = c.chunks.back(); 306 auto n = c.chunks.back();
307 const bool mesh = c.meshes.back() != 0;
299 if (c.mode == MockReplay::binary) { 308 if (c.mode == MockReplay::binary) {
300 for (unsigned i = 0; i < n; ++i) { 309 for (unsigned i = 0; i < n; ++i) {
301 c.word(VK_NULL_HANDLE, word_size * i, c.word(VK_NULL_HANDLE, word_size * i) != 0); 310 c.word(VK_NULL_HANDLE, word_size * i, c.word(VK_NULL_HANDLE, word_size * i) != 0);
302 } 311 }
303 } else { 312 } else {
304 for (unsigned j = 0; j < (c.mode == MockReplay::statistics ? statistics_counters : 1u); ++j) { 313 const bool statistics = c.mode == MockReplay::statistics;
305 unsigned width = c.mode == MockReplay::statistics ? statistics_counters : 1; 314 for (unsigned j = 0; j < (statistics ? statistics_counters : 1u); ++j) {
315 // A mesh segment counts the mesh-primitives count, the fragment and the compute invocations,
316 // and they land in CInvocations, PSInvocations and CSInvocations (statistics_sum.comp, D3D-291 and
317 // D3D-MESH-CLIPPING-COUNTER).
318 if (mesh && statistics && j != 5 && j != 7 && j != 10) continue;
319 const unsigned source = mesh && j == 10 ? 8 : j;
320 unsigned width = statistics ? statistics_counters : 1;
306 auto total = c.word(VK_NULL_HANDLE, word_size * j); 321 auto total = c.word(VK_NULL_HANDLE, word_size * j);
307 for (unsigned i = 0; i < n; ++i) { 322 for (unsigned i = 0; i < n; ++i) {
308 total += c.word(VK_NULL_HANDLE, word_size * (width * (i + 1) + j)); 323 total += c.word(VK_NULL_HANDLE, word_size * (width * (i + 1) + source));
309 } 324 }
310 c.word(VK_NULL_HANDLE, word_size * j, total); 325 c.word(VK_NULL_HANDLE, word_size * j, total);
311 } 326 }
@@ -338,6 +353,7 @@ void test_helper_chunks() {
338 auto expected = c.buffers[dst]; 353 auto expected = c.buffers[dst];
339 c.copies.clear(); 354 c.copies.clear();
340 c.chunks.clear(); 355 c.chunks.clear();
356 c.meshes.clear();
341 c.groups.clear(); 357 c.groups.clear();
342 c.transfers.clear(); 358 c.transfers.clear();
343 if (mode == MockReplay::binary) { 359 if (mode == MockReplay::binary) {
@@ -348,7 +364,8 @@ void test_helper_chunks() {
348 } 364 }
349 } else { 365 } else {
350 if (mode == MockReplay::statistics) { 366 if (mode == MockReplay::statistics) {
351 helper.sum_statistics({}, qp, VK_NULL_HANDLE, nullptr, first, n, dst, output_offset); 367 helper.sum_statistics({}, qp, VK_NULL_HANDLE, VK_NULL_HANDLE, nullptr, first, n, dst,
368 output_offset);
352 } else { 369 } else {
353 helper.sum({}, qp, first, n, dst, output_offset); 370 helper.sum({}, qp, first, n, dst, output_offset);
354 } 371 }
@@ -363,6 +380,8 @@ void test_helper_chunks() {
363 expect(c.buffers[dst] == expected, "numeric helper result and destination guard bytes"); 380 expect(c.buffers[dst] == expected, "numeric helper result and destination guard bytes");
364 expect(c.chunks == (extra ? std::vector<unsigned>{capacity, 1} 381 expect(c.chunks == (extra ? std::vector<unsigned>{capacity, 1}
365 : std::vector<unsigned>{capacity}), "exact chunk sizes"); 382 : std::vector<unsigned>{capacity}), "exact chunk sizes");
383 expect(std::all_of(c.meshes.begin(), c.meshes.end(), [](unsigned m) { return m == 0; }),
384 "no mesh segment in these chunks");
366 expect(c.copies.size() == 1 + extra && c.copies[0].first == first && (!extra 385 expect(c.copies.size() == 1 + extra && c.copies[0].first == first && (!extra
367 || c.copies[1].first == first + capacity), "chunk query indices end exactly at heap boundary"); 386 || c.copies[1].first == first + capacity), "chunk query indices end exactly at heap boundary");
368 std::vector<unsigned> expected_groups(1 + extra, 1); 387 std::vector<unsigned> expected_groups(1 + extra, 1);
@@ -388,10 +407,53 @@ void test_helper_chunks() {
388 expect(c.word(dst, output_offset) == reset_sum, "sum accumulator reset between calls"); 407 expect(c.word(dst, output_offset) == reset_sum, "sum accumulator reset between calls");
389 c.mode = MockReplay::statistics; 408 c.mode = MockReplay::statistics;
390 c.values[qp][first_query].fill(reset_counter); 409 c.values[qp][first_query].fill(reset_counter);
391 helper.sum_statistics({}, qp, VK_NULL_HANDLE, nullptr, first_query, 1, dst, output_offset); 410 helper.sum_statistics({}, qp, VK_NULL_HANDLE, VK_NULL_HANDLE, nullptr, first_query, 1, dst, output_offset);
392 for (unsigned j = 0; j < statistics_counters; ++j) { 411 for (unsigned j = 0; j < statistics_counters; ++j) {
393 expect(c.word(dst, output_offset + word_size * j) == reset_counter, "statistics accumulator reset"); 412 expect(c.word(dst, output_offset + word_size * j) == reset_counter, "statistics accumulator reset");
394 } 413 }
414
415 // A statistics query that holds a mesh draw is split so the mesh segments run in the mesh pool (D3D-291). That
416 // pool counts the fragment and compute invocations only, so the sum copies them into the PSInvocations and
417 // CSInvocations fields of their record, and the clipping fields a mesh draw cannot count stay 0.
418 {
419 constexpr unsigned mesh_segments = 3;
420 constexpr std::uint64_t fragment = 40;
421 constexpr std::uint64_t compute = 7;
422 constexpr std::uint64_t generated = 5; // the primitives a mesh segment emits (D3D-MESH-CLIPPING-COUNTER)
423 const std::uint8_t mesh_flags[mesh_segments] = {1, 1, 1};
424 auto mesh_pool = handle<VkQueryPool>(3);
425 auto primitives_pool = handle<VkQueryPool>(4);
426 c.mesh_pools.insert(mesh_pool);
427 c.primitives_pools.insert(primitives_pool);
428 c.values[mesh_pool].resize(mesh_segments);
429 c.values[primitives_pool].resize(mesh_segments);
430 std::uint64_t fragment_total = 0, compute_total = 0, generated_total = 0;
431 for (unsigned i = 0; i < mesh_segments; ++i) {
432 c.values[mesh_pool][i][0] = fragment + i; // the fragment shader invocations
433 c.values[mesh_pool][i][1] = compute + i; // the compute shader invocations
434 c.values[primitives_pool][i][0] = generated + i; // the primitives the mesh shader emitted
435 fragment_total += c.values[mesh_pool][i][0];
436 compute_total += c.values[mesh_pool][i][1];
437 generated_total += c.values[primitives_pool][i][0];
438 }
439 c.buffers[dst].assign(buffer_bytes, guard_byte);
440 auto expected = c.buffers[dst];
441 c.copies.clear();
442 c.chunks.clear();
443 c.meshes.clear();
444 c.groups.clear();
445 c.transfers.clear();
446 helper.sum_statistics({}, qp, mesh_pool, primitives_pool, mesh_flags, 0, mesh_segments, dst, output_offset);
447 for (unsigned j = 0; j < statistics_counters; ++j) {
448 const std::uint64_t v = j == 5 ? generated_total : j == 7 ? fragment_total : j == 10 ? compute_total : 0;
449 std::memcpy(expected.data() + output_offset + word_size * j, &v, word_size);
450 }
451 expect(c.buffers[dst] == expected,
452 "a mesh segment fills CInvocations, PSInvocations and CSInvocations, and no other field");
453 expect(c.meshes.size() == 1 && c.meshes[0] == 1, "the mesh chunk says its segments are mesh ones");
454 expect(c.copies.size() == 2 && c.copies[0].pool == mesh_pool && c.copies[1].pool == primitives_pool,
455 "the mesh segment is read from the mesh pool and the mesh-primitives pool");
456 }
395} 457}
396 458
397void test_query_state() { 459void test_query_state() {
diff --git a/runtime/test/replay_query_predication_test.cpp b/runtime/test/replay_query_predication_test.cpp
index 3ef0b484a..87056a499 100644
--- a/runtime/test/replay_query_predication_test.cpp
+++ b/runtime/test/replay_query_predication_test.cpp
@@ -127,8 +127,8 @@ int main() {
127 vk.query_pool = [&](QueryHeapId id) -> QueryPool* { 127 vk.query_pool = [&](QueryHeapId id) -> QueryPool* {
128 return id == 1 ? &heap : id == 6 ? &statistics_heap : nullptr; 128 return id == 1 ? &heap : id == 6 ? &statistics_heap : nullptr;
129 }; 129 };
130 vk.sum_statistics = [](VkCommandBuffer, VkQueryPool pool, VkQueryPool, const std::uint8_t*, std::uint32_t first, 130 vk.sum_statistics = [](VkCommandBuffer, VkQueryPool pool, VkQueryPool, VkQueryPool, const std::uint8_t*,
131 std::uint32_t count, VkBuffer, VkDeviceSize) { 131 std::uint32_t first, std::uint32_t count, VkBuffer, VkDeviceSize) {
132 g_trace->events.push_back(query_event("sum_statistics", pool, first) + "+" + std::to_string(count)); 132 g_trace->events.push_back(query_event("sum_statistics", pool, first) + "+" + std::to_string(count));
133 }; 133 };
134 vk.resolve_binary_occlusion = [](VkCommandBuffer, VkQueryPool, std::uint32_t, std::uint32_t, VkBuffer, 134 vk.resolve_binary_occlusion = [](VkCommandBuffer, VkQueryPool, std::uint32_t, std::uint32_t, VkBuffer,
@@ -685,14 +685,18 @@ int main() {
685 auto segments = std::make_shared<OcclusionSegmentPool>(); 685 auto segments = std::make_shared<OcclusionSegmentPool>();
686 segments->pool = handle<VkQueryPool>(9); 686 segments->pool = handle<VkQueryPool>(9);
687 segments->mesh_pool = handle<VkQueryPool>(10); 687 segments->mesh_pool = handle<VkQueryPool>(10);
688 segments->primitives_pool = handle<VkQueryPool>(11);
688 segments->mesh = prepared.statistics_mesh; 689 segments->mesh = prepared.statistics_mesh;
689 segments->destroy = mock_destroy_pool; 690 segments->destroy = mock_destroy_pool;
690 QueryReplay queries; 691 QueryReplay queries;
691 expect(queries.plan(prepared, {}, 0, true, segments, 0) == ReplayResult::success, "plan mixed list"); 692 expect(queries.plan(prepared, {}, 0, true, segments, 0) == ReplayResult::success, "plan mixed list");
692 expect(prepared.statistics_mesh_pool == handle<VkQueryPool>(10), "mixed list: the mesh pool is the list's"); 693 expect(prepared.statistics_mesh_pool == handle<VkQueryPool>(10), "mixed list: the mesh pool is the list's");
694 expect(prepared.statistics_primitives_pool == handle<VkQueryPool>(11),
695 "mixed list: the mesh-primitives pool is the list's");
693 expect(q[6].resolves.size() == 1 && q[6].resolves[0].sum && q[6].resolves[0].first == 3 && 696 expect(q[6].resolves.size() == 1 && q[6].resolves[0].sum && q[6].resolves[0].first == 3 &&
694 q[6].resolves[0].count == 1 && q[6].resolves[0].mesh_pool == handle<VkQueryPool>(10) && 697 q[6].resolves[0].count == 1 && q[6].resolves[0].mesh_pool == handle<VkQueryPool>(10) &&
695 q[6].resolves[0].mesh && q[6].resolves[0].mesh[3] == 1, 698 q[6].resolves[0].primitives_pool == handle<VkQueryPool>(11) && q[6].resolves[0].mesh &&
699 q[6].resolves[0].mesh[3] == 1,
696 "mixed list: the mesh-only query's resolve sums its one mesh segment"); 700 "mixed list: the mesh-only query's resolve sums its one mesh segment");
697 expect(queries.needs_statistics_sum, "mixed list: the statistics sum helper is needed"); 701 expect(queries.needs_statistics_sum, "mixed list: the statistics sum helper is needed");
698 702
@@ -755,6 +759,21 @@ int main() {
755 expect(q[3].statistics_first == 1 && q[3].statistics_count == 3, "overlap-mesh: query 1 sums segments 1-3"); 759 expect(q[3].statistics_first == 1 && q[3].statistics_count == 3, "overlap-mesh: query 1 sums segments 1-3");
756 } 760 }
757 761
762 // 17. D3D-291: the pool a mesh draw runs in must not enable a counter
763 // VUID-vkCmdDrawMeshTasksEXT-pipelineStatistics-07076 forbids, or the validation layer reports the VUID on
764 // every DispatchMesh inside a statistics query. The VUID leaves the fragment and compute invocations
765 // allowed, and those are the two the mesh pool counts; the nine it names are the rest of the eleven.
766 {
767 constexpr VkQueryPipelineStatisticFlags all_counters = 0x7ff; // the counters of a D3D12 statistics heap
768 expect((kMeshStatisticsFlags & kForbiddenMeshStatisticsFlags) == 0,
769 "the mesh pool enables none of the counters the VUID forbids");
770 expect((all_counters & ~kForbiddenMeshStatisticsFlags) == kMeshStatisticsFlags,
771 "the mesh pool counts every counter the VUID leaves allowed");
772 expect(kMeshStatisticsFlags == (VK_QUERY_PIPELINE_STATISTIC_FRAGMENT_SHADER_INVOCATIONS_BIT |
773 VK_QUERY_PIPELINE_STATISTIC_COMPUTE_SHADER_INVOCATIONS_BIT),
774 "the mesh pool counts the fragment and compute invocations");
775 }
776
758 if (failures) return 1; 777 if (failures) return 1;
759 std::puts("replay_query_predication_test: query resolves suspend conditional rendering around fills, copies and dispatches"); 778 std::puts("replay_query_predication_test: query resolves suspend conditional rendering around fills, copies and dispatches");
760 return 0; 779 return 0;
diff --git a/runtime/test/replay_uav_clear_offset_test.cpp b/runtime/test/replay_uav_clear_offset_test.cpp
index 35818fe8e..b315ed30d 100644
--- a/runtime/test/replay_uav_clear_offset_test.cpp
+++ b/runtime/test/replay_uav_clear_offset_test.cpp
@@ -173,6 +173,18 @@ int main() {
173 range.buffer_offset = UINT64_MAX - 2; 173 range.buffer_offset = UINT64_MAX - 2;
174 expect(run({1, true, VK_FORMAT_R8_UINT, 1, 2, 1, 0, 0, 1}) == ReplayResult::invalid_clear && writes.empty(), 174 expect(run({1, true, VK_FORMAT_R8_UINT, 1, 2, 1, 0, 0, 1}) == ReplayResult::invalid_clear && writes.empty(),
175 "backing range overflow is rejected before scratch allocation or emission"); 175 "backing range overflow is rejected before scratch allocation or emission");
176 // Misaligned backing buffer_offset must be rejected for multi-byte elements (e.g., e > 4 violates
177 // VUID-vkCmdUpdateBuffer-dstOffset-00032; e == 2/4 would byte-swap/rotate elements in vkCmdFillBuffer).
178 range.buffer_offset = at + 2;
179 expect(run({1, true, VK_FORMAT_R32G32B32A32_UINT, 0, 32, 16, 0, 0, 1}) == ReplayResult::unsupported && writes.empty(),
180 "misaligned backing buffer_offset for 16-byte element clear is rejected before vkCmdUpdateBuffer");
181 expect(run({1, true, VK_FORMAT_R32_UINT, 0, 16, 4, 0, 0, 1}) == ReplayResult::unsupported && writes.empty(),
182 "misaligned backing buffer_offset for 4-byte element clear is rejected before vkCmdFillBuffer");
183 range.buffer_offset = at + 1;
184 expect(run({1, true, VK_FORMAT_R16_UINT, 0, 16, 2, 0, 0, 1}) == ReplayResult::unsupported && writes.empty(),
185 "odd backing buffer_offset for 2-byte element clear is rejected before vkCmdFillBuffer");
186 expect(run({1, true, VK_FORMAT_R8_UINT, 0, 16, 1, 0, 0, 1}) == ReplayResult::success,
187 "odd backing buffer_offset for 1-byte R8 element clear still replays");
176 range.buffer_offset = at; 188 range.buffer_offset = at;
177 vk.copy_scratch = {}; 189 vk.copy_scratch = {};
178 190
diff --git a/runtime/test/retire_tickets_test.cpp b/runtime/test/retire_tickets_test.cpp
index 8eb5e02d0..f1dc836de 100644
--- a/runtime/test/retire_tickets_test.cpp
+++ b/runtime/test/retire_tickets_test.cpp
@@ -30,6 +30,24 @@ int main() {
30 queue_one_destroyed = true; 30 queue_one_destroyed = true;
31 if (tickets.completed(query) != 4 || queried_destroyed) return 4; 31 if (tickets.completed(query) != 4 || queried_destroyed) return 4;
32 32
33 // pending_through() must coalesce repeated submissions on the same queue to the highest
34 // timeline value, omit idle queues, and exclude tickets past the requested cutoff.
35 tickets.record(5, 1, 10);
36 tickets.record(6, 2, 20);
37 tickets.record(7, 1, 12);
38 tickets.record(8, 1, 15);
39 tickets.record(9, 2, 25);
40 tickets.queue_idle(2);
41 const auto wait_list = tickets.pending_through(7);
42 if (wait_list.size() != 1 || wait_list[0].first != 1 || wait_list[0].second != 12) return 5;
43
44 // A non-monotonic ticket must not move the completed prefix backward.
45 done[1] = 15;
46 if (tickets.completed(query) != 9) return 6;
47 tickets.record(3, 1, 16);
48 done[1] = 16;
49 if (tickets.completed(query) != 9) return 7;
50
33 std::puts("out-of-order queue completion kept the retirement prefix safe"); 51 std::puts("out-of-order queue completion kept the retirement prefix safe");
34 return 0; 52 return 0;
35} 53}
diff --git a/runtime/test/shader_library_test.cpp b/runtime/test/shader_library_test.cpp
index bf7ad80d1..55105d987 100644
--- a/runtime/test/shader_library_test.cpp
+++ b/runtime/test/shader_library_test.cpp
@@ -8,6 +8,7 @@
8#include <filesystem> 8#include <filesystem>
9#include <fstream> 9#include <fstream>
10#include <initializer_list> 10#include <initializer_list>
11#include <limits>
11#include <sstream> 12#include <sstream>
12#include <string> 13#include <string>
13#include <vector> 14#include <vector>
@@ -570,6 +571,10 @@ int main() {
570 broken.resize(100); // truncated 571 broken.resize(100); // truncated
571 CHECK(!zlib_inflate(broken, out)); 572 CHECK(!zlib_inflate(broken, out));
572 CHECK(!zlib_inflate(dynamic, out, 599)); // larger than the limit 573 CHECK(!zlib_inflate(dynamic, out, 599)); // larger than the limit
574 const auto max_limit = (std::numeric_limits<std::size_t>::max)();
575 CHECK(zlib_inflate(stored, out, max_limit) && out.size() == 40);
576 CHECK(zlib_inflate(fixed, out, max_limit) && out == bytes("hello hello hello leonida"));
577 CHECK(zlib_inflate(dynamic, out, max_limit) && out == skewed(600));
573 CHECK(!zlib_inflate(bytes("not zlib"), out)); 578 CHECK(!zlib_inflate(bytes("not zlib"), out));
574 579
575 Json json; 580 Json json;
@@ -642,7 +647,9 @@ int main() {
642 "{\"semantic\": \"TEXCOORD\", \"semantic_index\": 3, \"register\": -1, \"system_value\": 0, " 647 "{\"semantic\": \"TEXCOORD\", \"semantic_index\": 3, \"register\": -1, \"system_value\": 0, "
643 "\"component_type\": \"float\"}]},\n" 648 "\"component_type\": \"float\"}]},\n"
644 " \"ps_out\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << hash << "\", \"inputs\": [0, 1, 28, 29], " 649 " \"ps_out\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << hash << "\", \"inputs\": [0, 1, 28, 29], "
645 "\"outputs\": [0, 2], \"f16_halves\": {\"0\": [28, 29], \"bad\": [1], \"7\": [20, 21]}},\n" 650 "\"outputs\": [0, 2], \"f16_halves\": {\"0\": [28, 29], \"bad\": [1], \"-1\": [1, 2], "
651 "\"+2\": [3, 4], \" 3\": [5, 6], \"4294967296\": [9, 10], \"99999999999999999999\": [11, 12], "
652 "\"7\": [20, 21]}},\n"
646 " \"ps_native\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << hash2 << "\", \"wave64\": true, " 653 " \"ps_native\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << hash2 << "\", \"wave64\": true, "
647 "\"subgroup_size\": 64},\n" 654 "\"subgroup_size\": 64},\n"
648 " \"cs_emulated\": {\"stage\": \"cs\", \"fssm_sha256\": \"" << hash2 << "\", \"wave64\": true, " 655 " \"cs_emulated\": {\"stage\": \"cs\", \"fssm_sha256\": \"" << hash2 << "\", \"wave64\": true, "
diff --git a/runtime/test/shaders/build.py b/runtime/test/shaders/build.py
index c9fd70e4a..03a7ecd22 100644
--- a/runtime/test/shaders/build.py
+++ b/runtime/test/shaders/build.py
@@ -124,8 +124,6 @@ def cs_fssm_extra(path):
124 124
125 125
126def shader_source(name): 126def shader_source(name):
127 if name == "ps_mullit":
128 return "../../../tests/semantic/fixtures/ps_mullit"
129 return "vs_clip" if name in CLIP_CASES else name 127 return "vs_clip" if name in CLIP_CASES else name
130 128
131 129
@@ -216,8 +214,7 @@ def main():
216 out = Path(sys.argv[1]) 214 out = Path(sys.argv[1])
217 available = sorted({p.stem for p in Path(HERE).glob("*.asm")} | CLIP_CASES.keys()) 215 available = sorted({p.stem for p in Path(HERE).glob("*.asm")} | CLIP_CASES.keys())
218 names = sys.argv[2:] or available 216 names = sys.argv[2:] or available
219 # mullit_readback.py uses the CPU semantic fixture as an explicit build target. 217 unknown = sorted(set(names) - set(available))
220 unknown = sorted(set(names) - set(available) - {"ps_mullit"})
221 if unknown: 218 if unknown:
222 sys.exit("Unknown test shaders: " + ", ".join(unknown)) 219 sys.exit("Unknown test shaders: " + ", ".join(unknown))
223 skipped = [n for n in names if n.startswith("ms_")] 220 skipped = [n for n in names if n.startswith("ms_")]
diff --git a/runtime/test/shaders/check.py b/runtime/test/shaders/check.py
index 7b3777287..7b4bcdf13 100644
--- a/runtime/test/shaders/check.py
+++ b/runtime/test/shaders/check.py
@@ -358,6 +358,33 @@ def heap_init_env():
358 return {"VKC_HEAP_INIT": path, "VKC_OUT_WORDS": str(len(HEAP_INIT_FILE) // 4)} 358 return {"VKC_HEAP_INIT": path, "VKC_OUT_WORDS": str(len(HEAP_INIT_FILE) // 4)}
359 359
360 360
361def shift64_words():
362 """cs_w32_shift64: input heap and full expected readback, using Python integers as the oracle."""
363 values = (0, 1, 0xFFFFFFFF, 0x100000000, 0x7FFFFFFFFFFFFFFF,
364 0x8000000000000000, 0xFFFFFFFFFFFFFFFF, 0x8123456789ABCDEF)
365 counts = (0, 1, 31, 32, 33, 63, 64, 65)
366 inputs, results = [], []
367 for value in values:
368 for count in counts:
369 inputs.extend((value & 0xFFFFFFFF, value >> 32, count, 0xA5A5A5A5))
370 signed = value if value < (1 << 63) else value - (1 << 64)
371 shift = count & 63
372 for result in (value << shift, value >> shift, signed >> shift):
373 results.extend((result & 0xFFFFFFFF, (result >> 32) & 0xFFFFFFFF))
374 return [0xEEEEEEEE] * len(results) + inputs, results + inputs
375
376
377def shift64_test(tools, spirv, env=None):
378 """Verify all three 64-bit shifts for 64 memory-fed cases, including the untouched input records."""
379 initial, expected = shift64_words()
380 with tempfile.TemporaryDirectory(prefix="leonida-shift64-") as tmp:
381 path = Path(tmp) / "input.bin"
382 path.write_bytes(struct.pack(f"<{len(initial)}I", *initial))
383 child = dict(os.environ if env is None else env, VKC_HEAP_INIT=str(path))
384 child.setdefault("VKC_SUBGROUP_SIZE", str(subgroup_size(spirv, "cs_w32_shift64") or 32))
385 return dump_test(tools, spirv, "cs_w32_shift64", expected, len(expected), child)
386
387
361# cs_user_sgprs.asm: vk_compute_test puts these words in s4..s7 and the shader stores them back. 388# cs_user_sgprs.asm: vk_compute_test puts these words in s4..s7 and the shader stores them back.
362USER_SGPRS = [0x4F000000, 0xDEADBEEF, 7, 0xFFFFFFFF] 389USER_SGPRS = [0x4F000000, 0xDEADBEEF, 7, 0xFFFFFFFF]
363USER_SGPRS_ENV = {"VKC_SGPRS": ",".join(hex(w) for w in USER_SGPRS)} 390USER_SGPRS_ENV = {"VKC_SGPRS": ",".join(hex(w) for w in USER_SGPRS)}
@@ -597,6 +624,17 @@ STORE_WORDS = {
597 # 3D image atomics: the data register afterwards (sint image) and the six texels afterwards (volume) 624 # 3D image atomics: the data register afterwards (sint image) and the six texels afterwards (volume)
598 "cs_imgatomic3d": ({}, dict(enumerate([0x101, 0xDB, 0xF4, 0xCE, 0xE6, 0xFF])), 625 "cs_imgatomic3d": ({}, dict(enumerate([0x101, 0xDB, 0xF4, 0xCE, 0xE6, 0xFF])),
599 {57: 0x111, 19: 3, 44: 0xF4, 6: 0xD00D, 30: 0xE6, 39: 0x10}), 626 {57: 0x111, 19: 3, 44: 0xF4, 6: 0xD00D, 30: 0xE6, 39: 0x10}),
627 # GPU-IMG-ATOMIC-EXT: swap, inc, dec, fmin, fmax and fcmpswap. The 2D cases' texels afterwards (uint image, with the
628 # four that all 64 threads hit at 40..43), the data registers afterwards (sint image: 2D cases at 0..20, 3D cases
629 # at 32..37) and the 3D cases' texels afterwards (volume)
630 "cs_imgatomic_ext": ({0: 0x12345678, 1: 0xABCDEF01, 2: 0, 3: 0x68, 4: 0, 5: 0x68, 6: 0x32, 7: 9, 8: 0x6D,
631 9: 0x3FC00000, 10: 0xC0400000, 11: 0x40200000, 12: 0x3FC00000, 13: 0x3FC00000,
632 14: 0x3FC00000, 15: 0x40490FDB, 16: 0x3FC00000, 17: 0x3F800000, 18: 0x7FC00000,
633 19: 0x78, 20: 0x77, 40: 0xCC, 41: 0x4D, 42: 0x427C0000, 43: 0xC27C0000},
634 {0: 0x64, 1: 0xABCDEF01, 2: 0x66, 3: 0x67, 4: 0x68, 5: 0x69, 6: 0x6A, 7: 0, 8: 0x1F4,
635 **dict.fromkeys(range(9, 17), 0x3FC00000), 17: 0, 18: 0x7FC00000, 19: 0x77, 20: 0x78,
636 32: 0x101, 33: 0xDB, 34: 0xF4, 35: 0x3FC00000, 36: 0x3FC00000, 37: 0x3FC00000},
637 {6: 0xC0400000, 19: 0xDC, 30: 0x40200000, 39: 0x40490FDB, 44: 0x64, 57: 0x0BADF00D}),
600 # image_get_resinfo on a 16x4 image with five levels: (width, height, depth, levels) of levels 0, 1 and 3, then 638 # image_get_resinfo on a 16x4 image with five levels: (width, height, depth, levels) of levels 0, 1 and 3, then
601 # width and height of level 2 and an untouched register, height and levels of level 1, the levels alone, and 639 # width and height of level 2 and an untouched register, height and levels of level 1, the levels alone, and
602 # level 5, past the last (2D depth 0 and the past-the-end zeros measured on RDNA2, SHADER-388) 640 # level 5, past the last (2D depth 0 and the past-the-end zeros measured on RDNA2, SHADER-388)
@@ -1842,6 +1880,7 @@ def main():
1842 expected_words=USER_SGPRS_WORDS, env=USER_SGPRS_ENV))) 1880 expected_words=USER_SGPRS_WORDS, env=USER_SGPRS_ENV)))
1843 results.append(("cs_heap_init", compute_test(tools, spirv, "cs_heap_init", "1", "dump", 1881 results.append(("cs_heap_init", compute_test(tools, spirv, "cs_heap_init", "1", "dump",
1844 expected_words=HEAP_INIT_EXPECTED, env=heap_init_env()))) 1882 expected_words=HEAP_INIT_EXPECTED, env=heap_init_env())))
1883 results.append(("cs_w32_shift64", shift64_test(tools, spirv)))
1845 results.append(("cs_cvt_f32_sat", cvt_f32_sat_test(tools, spirv))) 1884 results.append(("cs_cvt_f32_sat", cvt_f32_sat_test(tools, spirv)))
1846 results.append(("cs_fma_fused", fma_fused_test(tools, spirv))) 1885 results.append(("cs_fma_fused", fma_fused_test(tools, spirv)))
1847 results.append(("cs_cvt_pk_u8", compute_test(tools, spirv, "cs_cvt_pk_u8", "1", "dump", 1886 results.append(("cs_cvt_pk_u8", compute_test(tools, spirv, "cs_cvt_pk_u8", "1", "dump",
@@ -1857,7 +1896,8 @@ def main():
1857 results.append(("ms_wave_info_s3", mesh_w64x_test(tools, spirv, "ms_wave_info_s3"))) 1896 results.append(("ms_wave_info_s3", mesh_w64x_test(tools, spirv, "ms_wave_info_s3")))
1858 with tempfile.TemporaryDirectory(prefix="leonida-mesh-") as tmp: 1897 with tempfile.TemporaryDirectory(prefix="leonida-mesh-") as tmp:
1859 results.append(("ms_v5_workgroup", mesh_v5_test(tools, spirv, Path(tmp) / "groups.raw"))) 1898 results.append(("ms_v5_workgroup", mesh_v5_test(tools, spirv, Path(tmp) / "groups.raw")))
1860 for name, args in (("cs_imgstore", []), ("cs_imgload", ["load"]), ("cs_imgload_tfe", ["load"]), 1899 for name, args in (("cs_imgstore", []), ("cs_imgstore_cube", ["cube"]), ("cs_imgload", ["load"]),
1900 ("cs_imgload_tfe", ["load"]),
1861 ("cs_imgload_d16", ["load-d16"]), ("cs_imgload_d16_tfe", ["load-d16"]), 1901 ("cs_imgload_d16", ["load-d16"]), ("cs_imgload_d16_tfe", ["load-d16"]),
1862 ("cs_sample_lz_int_d16", ["load-d16"])): 1902 ("cs_sample_lz_int_d16", ["load-d16"])):
1863 code, out = run(os.path.join(tools, "vk_store_test" + EXE), os.path.join(spirv, name + ".spv"), *args) 1903 code, out = run(os.path.join(tools, "vk_store_test" + EXE), os.path.join(spirv, name + ".spv"), *args)
diff --git a/runtime/test/shaders/cs_div_fmas_f64.asm b/runtime/test/shaders/cs_div_fmas_f64.asm
index 41b594752..dfede7187 100644
--- a/runtime/test/shaders/cs_div_fmas_f64.asm
+++ b/runtime/test/shaders/cs_div_fmas_f64.asm
@@ -4,7 +4,8 @@
4; fma(a, a, c) = 2^-60 = 0x3c300000_00000000 fused; rounding a*a first gives 1 + 2^-29 and a result of 0 ("split"). 4; fma(a, a, c) = 2^-60 = 0x3c300000_00000000 fused; rounding a*a first gives 1 + 2^-29 and a result of 0 ("split").
5; out[0..1] = 0x00000000 0x3c300000 (split: 0x00000000 0x00000000). Under --fma khr (LEONIDA_FMA=khr) the translator 5; out[0..1] = 0x00000000 0x3c300000 (split: 0x00000000 0x00000000). Under --fma khr (LEONIDA_FMA=khr) the translator
6; emits OpFmaKHR on doubles (feature shaderFmaFloat64) and only the fused words pass; under the default GLSL Fma a 6; emits OpFmaKHR on doubles (feature shaderFmaFloat64) and only the fused words pass; under the default GLSL Fma a
7; driver may split (NVIDIA RTX 4090, 621.24, does). 7; driver may split. The operands here are literals, so a driver that folds the constant Fma while compiling can
8; round it twice: NVIDIA RTX 4090 (621.24) does, while the same values as run-time operands are fused there.
8s_mov_b64 vcc, 0 9s_mov_b64 vcc, 0
9v_mov_b32 v0, 0x00400000 10v_mov_b32 v0, 0x00400000
10v_mov_b32 v1, 0x3ff00000 11v_mov_b32 v1, 0x3ff00000
diff --git a/runtime/test/shaders/cs_div_fmas_f64_rt.asm b/runtime/test/shaders/cs_div_fmas_f64_rt.asm
new file mode 100644
index 000000000..cf95b23bb
--- /dev/null
+++ b/runtime/test/shaders/cs_div_fmas_f64_rt.asm
@@ -0,0 +1,18 @@
1; group: 1,1,1
2; rsrc2: 0x8090
3; cs_div_fmas_f64 with its operands read at run time: s4..s7 hold a = 1 + 2^-30 (0x3ff00000_00400000) and
4; c = -(1 + 2^-29) (0xbff00000_00800000), seeded by vk_compute_test's VKC_SGPRS, so the driver cannot fold the Fma
5; while compiling the pipeline. v_div_fmas_f64 with VCC = 0 is fma(a, a, c) = 2^-60 with one rounding, 0 with two.
6; Run: VKC_SGPRS=0x00400000,0x3ff00000,0x00800000,0xbff00000 vk_compute_test cs_div_fmas_f64_rt.spv 1 dump
7; out[0..1] = 0x00000000 0x3c300000 (split: 0x00000000 0x00000000). Measured fused under the default GLSL Fma on the
8; NVIDIA RTX 4090 (621.24), RTX 3070 (621.01) and RTX 5060 Laptop (621.24), all of which except the 5060 split the
9; all-constant cs_div_fmas_f64.
10s_mov_b64 vcc, 0
11v_mov_b32 v0, s4
12v_mov_b32 v1, s5
13v_mov_b32 v2, s6
14v_mov_b32 v3, s7
15v_div_fmas_f64 v[4:5], v[0:1], v[0:1], v[2:3]
16v_mov_b32 v6, 0
17buffer_store_dwordx2 v[4:5], v6, s[0:3], 0 offen
18s_endpgm
diff --git a/runtime/test/shaders/cs_imgatomic_ext.asm b/runtime/test/shaders/cs_imgatomic_ext.asm
new file mode 100644
index 000000000..e58ecbcb6
--- /dev/null
+++ b/runtime/test/shaders/cs_imgatomic_ext.asm
@@ -0,0 +1,313 @@
1; The six image atomics that cs_imgatomic.asm and cs_imgatomic3d.asm don't run: image_atomic_swap, inc, dec, fmin, fmax
2; and fcmpswap, on the 2D r32 uint image (binding 4) and the 3D r32 uint volume (binding 7) (GPU-IMG-ATOMIC-EXT).
3; RDNA2 ISA (MIMG), M = the texel before the op, D = the data register, C = the comparand (fcmpswap's second data
4; register): swap writes D; inc writes (M >= D) ? 0 : M + 1 and dec (M == 0 || M > D) ? D : M - 1, both compares
5; unsigned (cases 19 and 20 have a D that is negative as a signed number); fmin and fmax write the smaller / larger
6; of M and D as floats; fcmpswap writes D where M equals C as floats (never with a NaN, +0 equals -0). With glc the
7; data register returns M; without glc it is left alone. The cases avoid what the ISA and SPIR-V leave open: no NaN
8; in memory for fmin/fmax (the ISA's compare and GLSL NMin differ there), no fmin/fmax of +0 against -0 (NMin may
9; return either), and no denormals (RDNA2's flush behaviour is unmeasured).
10; Run: vk_store_test cs_imgatomic_ext.spv words. The tool fills the uint image (T# 0x2000...) with M = 100 + i at
11; texel i = 8y + x, the sint image (T# 0x3000...) with -2i and the volume (T# 0x5000...) with 200 + i at
12; i = 16z + 4y + x. 1.5 = 0x3fc00000, 2.5 = 0x40200000, -3.0 = 0xc0400000, 2.0 = 0x40000000, 1.0 = 0x3f800000,
13; pi = 0x40490fdb, NaN = 0x7fc00000.
14; First, all 64 threads (no glc), each on one shared texel: inc with D = 0xffffffff on texel 40 (140 + 64 = 0xcc),
15; dec with D = 0xffffffff on 41 (141 - 64 = 0x4d), fmax with D = float(t) on 42 (63.0 = 0x427c0000), fmin with
16; D = -float(t) on 43 (-63.0 = 0xc27c0000); the fills there are small positive denormals as floats, below every D
17; of fmax but 0.0 and above every D of fmin, so the result does not depend on them. Then every lane sets the trap:
18; coordinates (2, 3, 3) and data 1 in every data register. After that only thread 0 is on, so the 63 inactive lanes
19; keep the trap: an op they ran anyway would land on uint texel 26 or volume texel 62 (swap writes 1 there; the
20; fills, 126 and 262, must survive), and an inc applied by every lane would show in its case. 2D case c works on
21; uint texel c and stores its data register afterwards into sint texel c; "preset" is what a swap without glc
22; puts in the texel first.
23; c op D C glc M (preset) uint word c afterwards sint word c
24; 0 swap 0x12345678 - yes 100 0x12345678 0x00000064
25; 1 swap 0xabcdef01 - no 101 0xabcdef01 0xabcdef01
26; 2 inc 102 - yes 102 0x00000000 0x00000066
27; 3 inc 200 - yes 103 0x00000068 0x00000067
28; 4 inc 50 - yes 104 0x00000000 0x00000068
29; 5 dec 200 - yes 105 0x00000068 0x00000069
30; 6 dec 50 - yes 106 0x00000032 0x0000006a
31; 7 dec 9 - yes 0 (preset) 0x00000009 0x00000000
32; 8 inc 500 - no 108 0x0000006d 0x000001f4
33; 9 fmin 2.5 - yes 1.5 (preset) 0x3fc00000 0x3fc00000
34; 10 fmin -3.0 - yes 1.5 (preset) 0xc0400000 0x3fc00000
35; 11 fmax 2.5 - yes 1.5 (preset) 0x40200000 0x3fc00000
36; 12 fmax -3.0 - yes 1.5 (preset) 0x3fc00000 0x3fc00000
37; 13 fmin NaN - yes 1.5 (preset) 0x3fc00000 0x3fc00000
38; 14 fmax NaN - yes 1.5 (preset) 0x3fc00000 0x3fc00000
39; 15 fcmpswap pi 1.5 yes 1.5 (preset) 0x40490fdb 0x3fc00000
40; 16 fcmpswap pi 2.0 yes 1.5 (preset) 0x3fc00000 0x3fc00000
41; 17 fcmpswap 1.0 -0.0 yes 0 (preset) 0x3f800000 0x00000000
42; 18 fcmpswap 1.0 NaN yes NaN (preset) 0x7fc00000 0x7fc00000
43; 19 inc 0xfffffff0 - yes 119 0x00000078 0x00000077
44; 20 dec 0xfffffff0 - yes 120 0x00000077 0x00000078
45; 3D case j works on volume texel i = 16z + 4y + x (three different coordinates, so a swapped pair lands elsewhere),
46; always with glc, and stores its data register afterwards into sint texel 32 + j.
47; j op D C (x, y, z) i V (preset) volume word i afterwards sint word 32 + j
48; 0 swap 0x0badf00d - (1, 2, 3) 57 257 0x0badf00d 0x00000101
49; 1 inc 300 - (3, 0, 1) 19 219 0x000000dc 0x000000db
50; 2 dec 100 - (0, 3, 2) 44 244 0x00000064 0x000000f4
51; 3 fmin -3.0 - (2, 1, 0) 6 1.5 (preset) 0xc0400000 0x3fc00000
52; 4 fmax 2.5 - (2, 3, 1) 30 1.5 (preset) 0x40200000 0x3fc00000
53; 5 fcmpswap pi 1.5 (3, 1, 2) 39 1.5 (preset) 0x40490fdb 0x3fc00000
54; Every other word keeps its fill.
55s_mov_b32 s8, 0x5000
56s_mov_b32 s9, 0x1400000
57s_mov_b32 s10, 0x55
58s_mov_b32 s11, 0x55
59s_mov_b32 s12, 0x55
60s_mov_b32 s13, 0x55
61s_mov_b32 s14, 0x55
62s_mov_b32 s15, 0x55
63s_mov_b32 s16, 0x2000
64s_mov_b32 s17, 0x1400000
65s_mov_b32 s18, 0x22
66s_mov_b32 s19, 0x22
67s_mov_b32 s20, 0x22
68s_mov_b32 s21, 0x22
69s_mov_b32 s22, 0x22
70s_mov_b32 s23, 0x22
71s_mov_b32 s24, 0x3000
72s_mov_b32 s25, 0x1500000
73s_mov_b32 s26, 0x33
74s_mov_b32 s27, 0x33
75s_mov_b32 s28, 0x33
76s_mov_b32 s29, 0x33
77s_mov_b32 s30, 0x33
78s_mov_b32 s31, 0x33
79v_mov_b32_e32 v2, 5
80v_mov_b32_e32 v1, 0
81v_mov_b32_e32 v10, -1
82image_atomic_inc v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
83v_mov_b32_e32 v1, 1
84v_mov_b32_e32 v10, -1
85image_atomic_dec v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
86v_mov_b32_e32 v1, 2
87v_cvt_f32_u32_e32 v10, v0
88image_atomic_fmax v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
89v_mov_b32_e32 v1, 3
90v_cvt_f32_u32_e32 v10, v0
91v_xor_b32_e32 v10, 0x80000000, v10
92image_atomic_fmin v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
93v_mov_b32_e32 v1, 2
94v_mov_b32_e32 v2, 3
95v_mov_b32_e32 v3, 3
96v_mov_b32_e32 v6, 2
97v_mov_b32_e32 v7, 3
98v_mov_b32_e32 v10, 1
99v_mov_b32_e32 v11, 1
100v_mov_b32_e32 v12, 1
101v_cmpx_eq_u32_e32 0, v0
102v_mov_b32_e32 v1, 0
103v_mov_b32_e32 v2, 0
104v_mov_b32_e32 v10, 0x12345678
105image_atomic_swap v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc
106s_waitcnt vmcnt(0)
107image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
108v_mov_b32_e32 v1, 1
109v_mov_b32_e32 v2, 0
110v_mov_b32_e32 v10, 0xabcdef01
111image_atomic_swap v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
112image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
113v_mov_b32_e32 v1, 2
114v_mov_b32_e32 v2, 0
115v_mov_b32_e32 v10, 0x66
116image_atomic_inc v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc
117s_waitcnt vmcnt(0)
118image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
119v_mov_b32_e32 v1, 3
120v_mov_b32_e32 v2, 0
121v_mov_b32_e32 v10, 0xc8
122image_atomic_inc v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc
123s_waitcnt vmcnt(0)
124image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
125v_mov_b32_e32 v1, 4
126v_mov_b32_e32 v2, 0
127v_mov_b32_e32 v10, 50
128image_atomic_inc v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc
129s_waitcnt vmcnt(0)
130image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
131v_mov_b32_e32 v1, 5
132v_mov_b32_e32 v2, 0
133v_mov_b32_e32 v10, 0xc8
134image_atomic_dec v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc
135s_waitcnt vmcnt(0)
136image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
137v_mov_b32_e32 v1, 6
138v_mov_b32_e32 v2, 0
139v_mov_b32_e32 v10, 50
140image_atomic_dec v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc
141s_waitcnt vmcnt(0)
142image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
143v_mov_b32_e32 v1, 7
144v_mov_b32_e32 v2, 0
145v_mov_b32_e32 v12, 0
146image_atomic_swap v12, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
147v_mov_b32_e32 v10, 9
148image_atomic_dec v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc
149s_waitcnt vmcnt(0)
150image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
151v_mov_b32_e32 v1, 0
152v_mov_b32_e32 v2, 1
153v_mov_b32_e32 v10, 0x1f4
154image_atomic_inc v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
155image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
156v_mov_b32_e32 v1, 1
157v_mov_b32_e32 v2, 1
158v_mov_b32_e32 v12, 0x3fc00000
159image_atomic_swap v12, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
160v_mov_b32_e32 v10, 0x40200000
161image_atomic_fmin v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc
162s_waitcnt vmcnt(0)
163image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
164v_mov_b32_e32 v1, 2
165v_mov_b32_e32 v2, 1
166v_mov_b32_e32 v12, 0x3fc00000
167image_atomic_swap v12, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
168v_mov_b32_e32 v10, 0xc0400000
169image_atomic_fmin v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc
170s_waitcnt vmcnt(0)
171image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
172v_mov_b32_e32 v1, 3
173v_mov_b32_e32 v2, 1
174v_mov_b32_e32 v12, 0x3fc00000
175image_atomic_swap v12, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
176v_mov_b32_e32 v10, 0x40200000
177image_atomic_fmax v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc
178s_waitcnt vmcnt(0)
179image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
180v_mov_b32_e32 v1, 4
181v_mov_b32_e32 v2, 1
182v_mov_b32_e32 v12, 0x3fc00000
183image_atomic_swap v12, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
184v_mov_b32_e32 v10, 0xc0400000
185image_atomic_fmax v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc
186s_waitcnt vmcnt(0)
187image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
188v_mov_b32_e32 v1, 5
189v_mov_b32_e32 v2, 1
190v_mov_b32_e32 v12, 0x3fc00000
191image_atomic_swap v12, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
192v_mov_b32_e32 v10, 0x7fc00000
193image_atomic_fmin v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc
194s_waitcnt vmcnt(0)
195image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
196v_mov_b32_e32 v1, 6
197v_mov_b32_e32 v2, 1
198v_mov_b32_e32 v12, 0x3fc00000
199image_atomic_swap v12, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
200v_mov_b32_e32 v10, 0x7fc00000
201image_atomic_fmax v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc
202s_waitcnt vmcnt(0)
203image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
204v_mov_b32_e32 v1, 7
205v_mov_b32_e32 v2, 1
206v_mov_b32_e32 v12, 0x3fc00000
207image_atomic_swap v12, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
208v_mov_b32_e32 v10, 0x40490fdb
209v_mov_b32_e32 v11, 0x3fc00000
210image_atomic_fcmpswap v[10:11], v[1:2], s[16:23] dmask:0x3 dim:SQ_RSRC_IMG_2D unorm glc
211s_waitcnt vmcnt(0)
212image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
213v_mov_b32_e32 v1, 0
214v_mov_b32_e32 v2, 2
215v_mov_b32_e32 v12, 0x3fc00000
216image_atomic_swap v12, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
217v_mov_b32_e32 v10, 0x40490fdb
218v_mov_b32_e32 v11, 0x40000000
219image_atomic_fcmpswap v[10:11], v[1:2], s[16:23] dmask:0x3 dim:SQ_RSRC_IMG_2D unorm glc
220s_waitcnt vmcnt(0)
221image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
222v_mov_b32_e32 v1, 1
223v_mov_b32_e32 v2, 2
224v_mov_b32_e32 v12, 0
225image_atomic_swap v12, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
226v_mov_b32_e32 v10, 0x3f800000
227v_mov_b32_e32 v11, 0x80000000
228image_atomic_fcmpswap v[10:11], v[1:2], s[16:23] dmask:0x3 dim:SQ_RSRC_IMG_2D unorm glc
229s_waitcnt vmcnt(0)
230image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
231v_mov_b32_e32 v1, 2
232v_mov_b32_e32 v2, 2
233v_mov_b32_e32 v12, 0x7fc00000
234image_atomic_swap v12, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
235v_mov_b32_e32 v10, 0x3f800000
236v_mov_b32_e32 v11, 0x7fc00000
237image_atomic_fcmpswap v[10:11], v[1:2], s[16:23] dmask:0x3 dim:SQ_RSRC_IMG_2D unorm glc
238s_waitcnt vmcnt(0)
239image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
240v_mov_b32_e32 v1, 3
241v_mov_b32_e32 v2, 2
242v_mov_b32_e32 v10, 0xfffffff0
243image_atomic_inc v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc
244s_waitcnt vmcnt(0)
245image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
246v_mov_b32_e32 v1, 4
247v_mov_b32_e32 v2, 2
248v_mov_b32_e32 v10, 0xfffffff0
249image_atomic_dec v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc
250s_waitcnt vmcnt(0)
251image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
252v_mov_b32_e32 v1, 1
253v_mov_b32_e32 v2, 2
254v_mov_b32_e32 v3, 3
255v_mov_b32_e32 v10, 0xbadf00d
256image_atomic_swap v10, v[1:3], s[8:15] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm glc
257s_waitcnt vmcnt(0)
258v_mov_b32_e32 v6, 0
259v_mov_b32_e32 v7, 4
260image_store v10, v[6:7], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
261v_mov_b32_e32 v1, 3
262v_mov_b32_e32 v2, 0
263v_mov_b32_e32 v3, 1
264v_mov_b32_e32 v10, 0x12c
265image_atomic_inc v10, v[1:3], s[8:15] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm glc
266s_waitcnt vmcnt(0)
267v_mov_b32_e32 v6, 1
268v_mov_b32_e32 v7, 4
269image_store v10, v[6:7], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
270v_mov_b32_e32 v1, 0
271v_mov_b32_e32 v2, 3
272v_mov_b32_e32 v3, 2
273v_mov_b32_e32 v10, 0x64
274image_atomic_dec v10, v[1:3], s[8:15] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm glc
275s_waitcnt vmcnt(0)
276v_mov_b32_e32 v6, 2
277v_mov_b32_e32 v7, 4
278image_store v10, v[6:7], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
279v_mov_b32_e32 v1, 2
280v_mov_b32_e32 v2, 1
281v_mov_b32_e32 v3, 0
282v_mov_b32_e32 v12, 0x3fc00000
283image_atomic_swap v12, v[1:3], s[8:15] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm
284v_mov_b32_e32 v10, 0xc0400000
285image_atomic_fmin v10, v[1:3], s[8:15] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm glc
286s_waitcnt vmcnt(0)
287v_mov_b32_e32 v6, 3
288v_mov_b32_e32 v7, 4
289image_store v10, v[6:7], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
290v_mov_b32_e32 v1, 2
291v_mov_b32_e32 v2, 3
292v_mov_b32_e32 v3, 1
293v_mov_b32_e32 v12, 0x3fc00000
294image_atomic_swap v12, v[1:3], s[8:15] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm
295v_mov_b32_e32 v10, 0x40200000
296image_atomic_fmax v10, v[1:3], s[8:15] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm glc
297s_waitcnt vmcnt(0)
298v_mov_b32_e32 v6, 4
299v_mov_b32_e32 v7, 4
300image_store v10, v[6:7], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
301v_mov_b32_e32 v1, 3
302v_mov_b32_e32 v2, 1
303v_mov_b32_e32 v3, 2
304v_mov_b32_e32 v12, 0x3fc00000
305image_atomic_swap v12, v[1:3], s[8:15] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm
306v_mov_b32_e32 v10, 0x40490fdb
307v_mov_b32_e32 v11, 0x3fc00000
308image_atomic_fcmpswap v[10:11], v[1:3], s[8:15] dmask:0x3 dim:SQ_RSRC_IMG_3D unorm glc
309s_waitcnt vmcnt(0)
310v_mov_b32_e32 v6, 5
311v_mov_b32_e32 v7, 4
312image_store v10, v[6:7], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
313s_endpgm
diff --git a/runtime/test/shaders/cs_imgload_d16_tfe.asm b/runtime/test/shaders/cs_imgload_d16_tfe.asm
index 0739810d1..119653577 100644
--- a/runtime/test/shaders/cs_imgload_d16_tfe.asm
+++ b/runtime/test/shaders/cs_imgload_d16_tfe.asm
@@ -1,8 +1,10 @@
1; tfe status VGPR on a d16 image_load (SHADER-1266): cs_imgload_d16 with tfe on both loads. Under d16 one 1; tfe status VGPR on a d16 image_load (SHADER-1266): cs_imgload_d16 with tfe on both loads. Under d16 one
2; component fills one VGPR, and with tfe the fetch status follows it, so vdata is v[7:8] and v[11:12]. Every texel is 2; component fills one VGPR, and with tfe the fetch status follows it, so vdata is v[7:8] and v[11:12]. On a resident
3; resident, so the status is 0. Each status VGPR is seeded with 1000 and added into the result, so a stale status 3; texel, RDNA2 hardware leaves the status VGPR unchanged. The two status VGPRs are seeded with distinct values
4; moves every texel by 2000. The unpacking and the result are cs_imgload_d16's, checked by vk_store_test load-d16 4; (v8 = 0x3e8, v12 = 0x7d0) and independently checked via (v8 ^ 0x3e8) | (v12 ^ 0x7d0) before adding into v11, so
5; (including its saturation row). Suggested by @nnonno91, who ran the same companion on gfx1036 and an RTX 5090 in #8968. 5; zeroing or modifying either status VGPR shifts every texel. The unpacking and the result are cs_imgload_d16's,
6; checked by vk_store_test load-d16 (including its saturation row). Suggested by @nnonno91, who ran the same
7; companion on gfx1036 and an RTX 5090 in #8968.
6v_and_b32_e32 v1, 7, v0 8v_and_b32_e32 v1, 7, v0
7v_lshrrev_b32_e32 v2, 3, v0 9v_lshrrev_b32_e32 v2, 3, v0
8v_cvt_f32_u32_e32 v3, v1 10v_cvt_f32_u32_e32 v3, v1
@@ -38,14 +40,16 @@ s_mov_b32 s28, 0x33
38s_mov_b32 s29, 0x33 40s_mov_b32 s29, 0x33
39s_mov_b32 s30, 0x33 41s_mov_b32 s30, 0x33
40s_mov_b32 s31, 0x33 42s_mov_b32 s31, 0x33
41v_mov_b32_e32 v12, 0x3e8 43v_mov_b32_e32 v12, 0x7d0
42image_load v[11:12], v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm tfe d16 44image_load v[11:12], v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm tfe d16
43s_waitcnt vmcnt(0) 45s_waitcnt vmcnt(0)
44v_and_b32_e32 v7, 0xffff, v7 46v_and_b32_e32 v7, 0xffff, v7
45v_bfe_i32 v11, v11, 0, 16 47v_bfe_i32 v11, v11, 0, 16
46v_add_nc_u32_e32 v11, v7, v11 48v_add_nc_u32_e32 v11, v7, v11
49v_xor_b32_e32 v8, 0x3e8, v8
50v_xor_b32_e32 v12, 0x7d0, v12
51v_or_b32_e32 v8, v8, v12
47v_add_nc_u32_e32 v11, v8, v11 52v_add_nc_u32_e32 v11, v8, v11
48v_add_nc_u32_e32 v11, v12, v11
49v_mov_b32_e32 v12, 0 53v_mov_b32_e32 v12, 0
50v_mov_b32_e32 v13, 0 54v_mov_b32_e32 v13, 0
51v_mov_b32_e32 v14, 0 55v_mov_b32_e32 v14, 0
diff --git a/runtime/test/shaders/cs_imgload_tfe.asm b/runtime/test/shaders/cs_imgload_tfe.asm
index 63ad9dc71..6eb3e76f6 100644
--- a/runtime/test/shaders/cs_imgload_tfe.asm
+++ b/runtime/test/shaders/cs_imgload_tfe.asm
@@ -1,9 +1,10 @@
1; tfe status VGPR on image_load (SHADER-1266): cs_imgload with tfe on both loads. With tfe an MIMG read returns one 1; tfe status VGPR on image_load (SHADER-1266): cs_imgload with tfe on both loads. With tfe an MIMG read reserves one
2; more dword after its data, the fetch status, at vdata[data_count] (RDNA2 ISA, MIMG TFE/LWE). Every texel here is 2; more dword after its data, the fetch status, at vdata[data_count] (RDNA2 ISA, MIMG TFE/LWE). On a resident texel,
3; resident, so the status is 0. Each status VGPR is seeded with 1000 before its load and added into the result, so a 3; RDNA2 hardware leaves the status VGPR unchanged. The two status VGPRs are seeded with distinct values (v8 = 0x3e8,
4; status that keeps its old value moves every texel by 1000 or 2000. vk_store_test fills the r32 uint image with 4; v12 = 0x7d0) and independently checked via (v8 ^ 0x3e8) | (v12 ^ 0x7d0) before adding into v11, so zeroing or
5; 100 + 8y + x and the r32 sint image with -2 (8y + x) before the dispatch; the rgba8 image is stored as in 5; modifying either status VGPR shifts every texel. vk_store_test fills the r32 uint image with 100 + 8y + x and the
6; cs_imgstore. Run: vk_store_test cs_imgload_tfe.spv load -> sint = 100 - (8y + x), uint unchanged. 6; r32 sint image with -2 (8y + x) before the dispatch; the rgba8 image is stored as in cs_imgstore.
7; Run: vk_store_test cs_imgload_tfe.spv load -> sint = 100 - (8y + x), uint unchanged.
7v_and_b32_e32 v1, 7, v0 8v_and_b32_e32 v1, 7, v0
8v_lshrrev_b32_e32 v2, 3, v0 9v_lshrrev_b32_e32 v2, 3, v0
9v_cvt_f32_u32_e32 v3, v1 10v_cvt_f32_u32_e32 v3, v1
@@ -39,12 +40,14 @@ s_mov_b32 s28, 0x33
39s_mov_b32 s29, 0x33 40s_mov_b32 s29, 0x33
40s_mov_b32 s30, 0x33 41s_mov_b32 s30, 0x33
41s_mov_b32 s31, 0x33 42s_mov_b32 s31, 0x33
42v_mov_b32_e32 v12, 0x3e8 43v_mov_b32_e32 v12, 0x7d0
43image_load v[11:12], v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm tfe 44image_load v[11:12], v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm tfe
44s_waitcnt vmcnt(0) 45s_waitcnt vmcnt(0)
45v_add_nc_u32_e32 v11, v7, v11 46v_add_nc_u32_e32 v11, v7, v11
47v_xor_b32_e32 v8, 0x3e8, v8
48v_xor_b32_e32 v12, 0x7d0, v12
49v_or_b32_e32 v8, v8, v12
46v_add_nc_u32_e32 v11, v8, v11 50v_add_nc_u32_e32 v11, v8, v11
47v_add_nc_u32_e32 v11, v12, v11
48v_mov_b32_e32 v12, 0 51v_mov_b32_e32 v12, 0
49v_mov_b32_e32 v13, 0 52v_mov_b32_e32 v13, 0
50v_mov_b32_e32 v14, 0 53v_mov_b32_e32 v14, 0
diff --git a/runtime/test/shaders/cs_imgstore_cube.asm b/runtime/test/shaders/cs_imgstore_cube.asm
new file mode 100644
index 000000000..9763e233f
--- /dev/null
+++ b/runtime/test/shaders/cs_imgstore_cube.asm
@@ -0,0 +1,95 @@
1; Typed image_store on dim:SQ_RSRC_IMG_CUBE (GPU-CUBE-STORE): three T#s built in SGPRs (FORMAT 56 rgba8 unorm, 20 r32
2; uint, 21 r32 sint; word3 TYPE = 0xB, SQ_RSRC_IMG_CUBE), 64 threads, thread t at (x, y) = (t & 7, t >> 3) of an 8x8
3; face, each store to all six faces (v3 = face). The translator writes a cube through a six-layer 2D-array storage
4; view (bindings 11/12/13, the layer is the face), as the runtime binds a cube UAV (runtime/src/vulkan_bindless.h).
5; Run: vk_store_test cs_imgstore_cube.spv cube (checks every texel of all six layers of all three images):
6; rgba8 unorm: (x / 7, y / 7, face / 5, 1)
7; r32 uint: 100 + 1000 face + 8y + x
8; r32 sint: -(1000 face + 8y + x)
9v_and_b32_e32 v1, 7, v0
10v_lshrrev_b32_e32 v2, 3, v0
11v_cvt_f32_u32_e32 v4, v1
12v_cvt_f32_u32_e32 v5, v2
13v_mul_f32_e32 v4, 0x3e124925, v4
14v_mul_f32_e32 v5, 0x3e124925, v5
15v_mov_b32_e32 v7, 1.0
16v_add_nc_u32_e32 v16, 100, v0
17v_mov_b32_e32 v9, 0
18v_mov_b32_e32 v10, 0
19v_mov_b32_e32 v11, 0
20v_mov_b32_e32 v13, 0
21v_mov_b32_e32 v14, 0
22v_mov_b32_e32 v15, 0
23s_mov_b32 s8, 0x1000
24s_mov_b32 s9, 0x3800000
25s_mov_b32 s10, 0x11
26s_mov_b32 s11, 0xb0000011
27s_mov_b32 s12, 0x11
28s_mov_b32 s13, 0x11
29s_mov_b32 s14, 0x11
30s_mov_b32 s15, 0x11
31s_mov_b32 s16, 0x2000
32s_mov_b32 s17, 0x1400000
33s_mov_b32 s18, 0x22
34s_mov_b32 s19, 0xb0000022
35s_mov_b32 s20, 0x22
36s_mov_b32 s21, 0x22
37s_mov_b32 s22, 0x22
38s_mov_b32 s23, 0x22
39s_mov_b32 s24, 0x3000
40s_mov_b32 s25, 0x1500000
41s_mov_b32 s26, 0x33
42s_mov_b32 s27, 0xb0000033
43s_mov_b32 s28, 0x33
44s_mov_b32 s29, 0x33
45s_mov_b32 s30, 0x33
46s_mov_b32 s31, 0x33
47v_mov_b32_e32 v3, 0
48v_cvt_f32_u32_e32 v6, v3
49v_mul_f32_e32 v6, 0x3e4ccccd, v6
50image_store v[4:7], v[1:3], s[8:15] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm
51v_add_nc_u32_e32 v8, 0, v16
52image_store v[8:11], v[1:3], s[16:23] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm
53v_sub_nc_u32_e32 v12, 0, v0
54image_store v[12:15], v[1:3], s[24:31] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm
55v_mov_b32_e32 v3, 1
56v_cvt_f32_u32_e32 v6, v3
57v_mul_f32_e32 v6, 0x3e4ccccd, v6
58image_store v[4:7], v[1:3], s[8:15] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm
59v_add_nc_u32_e32 v8, 1000, v16
60image_store v[8:11], v[1:3], s[16:23] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm
61v_sub_nc_u32_e32 v12, -1000, v0
62image_store v[12:15], v[1:3], s[24:31] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm
63v_mov_b32_e32 v3, 2
64v_cvt_f32_u32_e32 v6, v3
65v_mul_f32_e32 v6, 0x3e4ccccd, v6
66image_store v[4:7], v[1:3], s[8:15] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm
67v_add_nc_u32_e32 v8, 2000, v16
68image_store v[8:11], v[1:3], s[16:23] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm
69v_sub_nc_u32_e32 v12, -2000, v0
70image_store v[12:15], v[1:3], s[24:31] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm
71v_mov_b32_e32 v3, 3
72v_cvt_f32_u32_e32 v6, v3
73v_mul_f32_e32 v6, 0x3e4ccccd, v6
74image_store v[4:7], v[1:3], s[8:15] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm
75v_add_nc_u32_e32 v8, 3000, v16
76image_store v[8:11], v[1:3], s[16:23] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm
77v_sub_nc_u32_e32 v12, -3000, v0
78image_store v[12:15], v[1:3], s[24:31] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm
79v_mov_b32_e32 v3, 4
80v_cvt_f32_u32_e32 v6, v3
81v_mul_f32_e32 v6, 0x3e4ccccd, v6
82image_store v[4:7], v[1:3], s[8:15] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm
83v_add_nc_u32_e32 v8, 4000, v16
84image_store v[8:11], v[1:3], s[16:23] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm
85v_sub_nc_u32_e32 v12, -4000, v0
86image_store v[12:15], v[1:3], s[24:31] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm
87v_mov_b32_e32 v3, 5
88v_cvt_f32_u32_e32 v6, v3
89v_mul_f32_e32 v6, 0x3e4ccccd, v6
90image_store v[4:7], v[1:3], s[8:15] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm
91v_add_nc_u32_e32 v8, 5000, v16
92image_store v[8:11], v[1:3], s[16:23] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm
93v_sub_nc_u32_e32 v12, -5000, v0
94image_store v[12:15], v[1:3], s[24:31] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm
95s_endpgm
diff --git a/runtime/test/shaders/cs_w32_lds_subdword.asm b/runtime/test/shaders/cs_w32_lds_subdword.asm
index cb2f94243..10c5bd214 100644
--- a/runtime/test/shaders/cs_w32_lds_subdword.asm
+++ b/runtime/test/shaders/cs_w32_lds_subdword.asm
@@ -12,23 +12,27 @@
12; out[2] ds_read_i8 offset:2 -> 0xFFFFFFB2 out[3] ds_read_u8 offset:2 -> 0x000000B2 12; out[2] ds_read_i8 offset:2 -> 0xFFFFFFB2 out[3] ds_read_u8 offset:2 -> 0x000000B2
13; out[4] ds_read_i8 offset:3 -> 0x00000011 out[5] ds_read_i16 offset:6 -> 0xFFFFA1B2 13; out[4] ds_read_i8 offset:3 -> 0x00000011 out[5] ds_read_i16 offset:6 -> 0xFFFFA1B2
14; out[6] ds_read_u16 offset:6 -> 0x0000A1B2 out[7] ds_read_i16 offset:4 -> 0xFFFFC3D4 14; out[6] ds_read_u16 offset:6 -> 0x0000A1B2 out[7] ds_read_i16 offset:4 -> 0xFFFFC3D4
15; Every lane writes the same bytes, so the result does not depend on lane order. 15; Only lane zero accesses LDS and writes the results, avoiding concurrent writes to the same word.
16; Workgroup barriers separate the initial stores, narrow writes, and reads of the same words.
16; group: 32,1,1 17; group: 32,1,1
17; Run: vk_compute_test cs_w32_lds_subdword.spv 1 dump 18; Run: vk_compute_test cs_w32_lds_subdword.spv 1 dump
18; -> out[0..7] = 0x11B2D444 0xA1B2C3D4 0xFFFFFFB2 0x000000B2 0x00000011 0xFFFFA1B2 0x0000A1B2 0xFFFFC3D4 19; -> out[0..7] = 0x11B2D444 0xA1B2C3D4 0xFFFFFFB2 0x000000B2 0x00000011 0xFFFFA1B2 0x0000A1B2 0xFFFFC3D4
19; mattr: +wavefrontsize32,-wavefrontsize64 20; mattr: +wavefrontsize32,-wavefrontsize64
21v_cmpx_eq_u32_e32 0, v0
20v_mov_b32_e32 v2, 0 22v_mov_b32_e32 v2, 0
21v_mov_b32_e32 v4, 0x11223344 23v_mov_b32_e32 v4, 0x11223344
22v_mov_b32_e32 v5, 0x55667788 24v_mov_b32_e32 v5, 0x55667788
23ds_write_b32 v2, v4 25ds_write_b32 v2, v4
24ds_write_b32 v2, v5 offset:4 26ds_write_b32 v2, v5 offset:4
25s_waitcnt lgkmcnt(0) 27s_waitcnt lgkmcnt(0)
28s_barrier
26v_mov_b32_e32 v3, 0xa1b2c3d4 29v_mov_b32_e32 v3, 0xa1b2c3d4
27ds_write_b8 v2, v3 offset:1 30ds_write_b8 v2, v3 offset:1
28ds_write_b8_d16_hi v2, v3 offset:2 31ds_write_b8_d16_hi v2, v3 offset:2
29ds_write_b16 v2, v3 offset:4 32ds_write_b16 v2, v3 offset:4
30ds_write_b16_d16_hi v2, v3 offset:6 33ds_write_b16_d16_hi v2, v3 offset:6
31s_waitcnt lgkmcnt(0) 34s_waitcnt lgkmcnt(0)
35s_barrier
32ds_read_b32 v10, v2 36ds_read_b32 v10, v2
33ds_read_b32 v11, v2 offset:4 37ds_read_b32 v11, v2 offset:4
34ds_read_i8 v12, v2 offset:2 38ds_read_i8 v12, v2 offset:2
@@ -38,7 +42,6 @@ ds_read_i16 v15, v2 offset:6
38ds_read_u16 v16, v2 offset:6 42ds_read_u16 v16, v2 offset:6
39ds_read_i16 v17, v2 offset:4 43ds_read_i16 v17, v2 offset:4
40s_waitcnt lgkmcnt(0) 44s_waitcnt lgkmcnt(0)
41v_cmpx_eq_u32_e32 0, v0
42v_mov_b32_e32 v21, 0 45v_mov_b32_e32 v21, 0
43buffer_store_dword v10, v21, s[0:3], 0 offen 46buffer_store_dword v10, v21, s[0:3], 0 offen
44v_mov_b32_e32 v21, 4 47v_mov_b32_e32 v21, 4
diff --git a/runtime/test/shaders/cs_w32_shift64.asm b/runtime/test/shaders/cs_w32_shift64.asm
new file mode 100644
index 000000000..97920b114
--- /dev/null
+++ b/runtime/test/shaders/cs_w32_shift64.asm
@@ -0,0 +1,29 @@
1; GPU-VALU64-SHIFTS: dynamic 64-bit shifts, including overlapping destinations.
2; group: 64,1,1
3; mattr: +wavefrontsize32,-wavefrontsize64
4; check.py seeds 64 records at byte 0x600: {value.lo, value.hi, count, padding}.
5; They are the Cartesian product of eight signed/unsigned boundary values and
6; counts 0, 1, 31, 32, 33, 63, 64, 65. Each thread reads one record from memory,
7; so neither the translator nor the driver can fold the shifts of literal inputs.
8; RDNA2 ISA VOP3 opcodes 767..769: count is S0[5:0]; logical shifts zero-fill,
9; arithmetic right shift sign-extends. Results are modulo 2^64, low word first.
10; Thread i writes six words at 24*i: left, logical right, arithmetic right.
11; Left overwrites its count register; logical right overlaps its source's high
12; word; arithmetic right overwrites both source words. All inputs must be read
13; before either destination word is written. The input records remain unchanged.
14; Run with the heap initialized by check.py's shift64_test; compare all 640 words.
15v_lshlrev_b32_e32 v1, 4, v0
16v_mul_lo_u32 v10, v0, 24
17buffer_load_dwordx4 v[2:5], v1, s[0:3], 0 offen offset:1536
18s_waitcnt vmcnt(0)
19v_lshlrev_b64 v[4:5], v4, v[2:3]
20buffer_store_dwordx2 v[4:5], v10, s[0:3], 0 offen
21buffer_load_dwordx4 v[2:5], v1, s[0:3], 0 offen offset:1536
22s_waitcnt vmcnt(0)
23v_lshrrev_b64 v[3:4], v4, v[2:3]
24buffer_store_dwordx2 v[3:4], v10, s[0:3], 0 offen offset:8
25buffer_load_dwordx4 v[2:5], v1, s[0:3], 0 offen offset:1536
26s_waitcnt vmcnt(0)
27v_ashrrev_i64 v[2:3], v4, v[2:3]
28buffer_store_dwordx2 v[2:3], v10, s[0:3], 0 offen offset:16
29s_endpgm
diff --git a/runtime/test/shaders/mullit_readback.py b/runtime/test/shaders/mullit_readback.py
deleted file mode 100644
index 007b516b1..000000000
--- a/runtime/test/shaders/mullit_readback.py
+++ /dev/null
@@ -1,122 +0,0 @@
1"""Check the ps_mullit semantic fixture with runtime SGPR inputs and RGBA32F readback.
2
3python -I runtime/test/shaders/build.py <work> vs_ids ps_mullit
4python -I runtime/test/shaders/mullit_readback.py <work> <harness directory>
5"""
6import argparse
7import itertools
8import os
9from pathlib import Path
10import random
11import struct
12import sys
13import tempfile
14
15sys.path.insert(0, str(Path(__file__).resolve().parent))
16from check import EXE, run
17
18SIGN = 0x80000000
19INF = 0x7f800000
20MIN_NORMAL = 0x00800000
21ONE = 0x3f800000
22LIGHT_OFF = 0xff7fffff
23PAYLOAD_MASK = 0x40000000
24
25
26def lighting_product(x, y, gate):
27 """Return the expected f32 word using integer significands throughout."""
28 ax, ay = x & ~SIGN, y & ~SIGN
29 if not MIN_NORMAL <= gate <= INF or y in (LIGHT_OFF, SIGN | INF) or ay > INF:
30 return LIGHT_OFF
31 if min(ax, ay) < MIN_NORMAL:
32 return 0
33 if ax > INF:
34 return x
35 sign = (x ^ y) & SIGN
36 if INF in (ax, ay):
37 return sign | INF
38
39 product = (MIN_NORMAL + ax % MIN_NORMAL) * (MIN_NORMAL + ay % MIN_NORMAL)
40 shift = product.bit_length() - 24
41 unit = 1 << shift
42 mantissa, remainder = divmod(product, unit)
43 if 2 * remainder > unit or (2 * remainder == unit and mantissa % 2):
44 mantissa += 1
45 exponent = (ax >> 23) + (ay >> 23) - 127 + shift - 23
46 if mantissa == 2 * MIN_NORMAL:
47 mantissa //= 2
48 exponent += 1
49 # Round before flushing. A product just below MIN_NORMAL can carry into it.
50 if exponent <= 0:
51 return sign
52 if exponent >= 255:
53 return sign | INF
54 return sign | (exponent << 23) | (mantissa - MIN_NORMAL)
55
56
57def operand_triples():
58 gates = (ONE, INF, MIN_NORMAL, 1, MIN_NORMAL - 1, 0, SIGN, SIGN | ONE, 0x7fc23456, 0xffa54321)
59 yield from ((0x40400000, 0xc0200000, gate) for gate in gates)
60 yield from itertools.product(
61 (0, SIGN, 1, SIGN | (MIN_NORMAL - 1), 0x7fa12345, 0xffc12345, INF),
62 (0, SIGN | 1, LIGHT_OFF, INF, SIGN | INF, 0x7fc09876, ONE), (ONE,))
63 yield from itertools.product(
64 (ONE - 4, ONE - 3, ONE - 2, ONE - 1, ONE, SIGN | ONE, 0xbf7ffffe, 0xbf7fffff),
65 (MIN_NORMAL, MIN_NORMAL + 1, MIN_NORMAL + 2), (ONE,))
66 for x, y in ((INF - 1, 0x40000000), (LIGHT_OFF, 0x40000000), (INF - 1, MIN_NORMAL),
67 (MIN_NORMAL, 0x3f000000), (SIGN | MIN_NORMAL, 0x3f000000),
68 (INF, SIGN | ONE), (ONE, LIGHT_OFF - 1)):
69 yield x, y, ONE
70 # Halfway products round up to 0x3fc00002 and down to 0x3fc00004.
71 yield 0x3fc00000, ONE + 1, ONE
72 yield 0x3fc00000, ONE + 3, ONE
73 rng = random.Random(578)
74 for _ in range(28):
75 x = rng.randrange(MIN_NORMAL, INF) | rng.choice((0, SIGN))
76 y = rng.randrange(MIN_NORMAL, INF) | rng.choice((0, SIGN))
77 yield x, y, ONE
78
79
80def mismatch(data, x, y, gate):
81 result = lighting_product(x, y, gate)
82 modified = lighting_product(x ^ SIGN, y & ~SIGN, gate)
83 expected = (result, modified, LIGHT_OFF, result ^ PAYLOAD_MASK)
84 if len(data) != 4 * 4 * 16:
85 return f"expected 256 bytes, got {len(data)}"
86 for i, pixel in enumerate(struct.iter_unpack("<4I", data)):
87 for channel, want, got in zip("RGBA", expected, pixel):
88 # A float attachment can change a NaN payload. Alpha exposes the raw
89 # R payload as a finite word in exactly those cases.
90 if want & ~SIGN > INF and got & ~SIGN > INF:
91 continue
92 if got != want:
93 return f"pixel {i} {channel}: got {got:#010x}, expected {want:#010x}"
94 return None
95
96
97def main():
98 parser = argparse.ArgumentParser(description=__doc__)
99 parser.add_argument("work", type=Path)
100 parser.add_argument("build", type=Path)
101 args = parser.parse_args()
102 spirv = args.work / "spirv"
103 cases = dict.fromkeys(operand_triples())
104 with tempfile.TemporaryDirectory() as tmp:
105 raw = Path(tmp) / "pixels.raw"
106 for inputs in cases:
107 raw.unlink(missing_ok=True)
108 words = ",".join(map(hex, inputs))
109 code, output = run(args.build / ("vk_harness" + EXE), spirv / "vs_ids.spv",
110 spirv / "ps_mullit.spv", raw, "4", "4", env=dict(os.environ, VKH_SGPRS=words))
111 if code:
112 print(f"{words}: vk_harness exited {code}\n{output}", file=sys.stderr)
113 return code
114 problem = mismatch(raw.read_bytes(), *inputs) if raw.is_file() else "missing readback"
115 if problem:
116 sys.exit(f"{words}: {problem}")
117 print(f"{len(cases)} operand triples, {16 * len(cases)} pixels matched")
118 return 0
119
120
121if __name__ == "__main__":
122 sys.exit(main())
diff --git a/runtime/test/vk_command_replay_test.cpp b/runtime/test/vk_command_replay_test.cpp
index 9769e70be..c31c23b60 100644
--- a/runtime/test/vk_command_replay_test.cpp
+++ b/runtime/test/vk_command_replay_test.cpp
@@ -1265,6 +1265,81 @@ int part_j(vktest::Device& d) {
1265 return 0; 1265 return 0;
1266} 1266}
1267 1267
1268// Part K (D3D-838): an enhanced barrier with SYNC_COPY orders a WriteBufferImmediate before it. The write is recorded
1269// as vkCmdUpdateBuffer, which synchronization2 runs in the CLEAR stage, not COPY, and a DEFAULT-mode write gets no
1270// barrier of its own (replay leaves it to the application's). So: the write puts a word in src, a SYNC_COPY ->
1271// SYNC_COPY buffer barrier (COPY_DEST -> COPY_SOURCE) follows, and CopyBufferRegion copies the word to dst. Under
1272// LEONIDA_VK_VALIDATION=1 synchronization validation reports the read-after-write hazard when the barrier's source
1273// stages leave CLEAR out; in every run the copied word is checked.
1274int part_k(vktest::Device& d) {
1275 constexpr VkDeviceSize bytes = 256;
1276 constexpr std::uint64_t va_src = 0x50000;
1277 constexpr std::uint32_t value = 0x5eed1234;
1278 constexpr VkBufferUsageFlags usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
1279 void *src_mapped = nullptr, *dst_mapped = nullptr;
1280 const VkBuffer src = d.buffer(bytes, usage, &src_mapped);
1281 const VkBuffer dst = d.buffer(bytes, usage, &dst_mapped);
1282 EXPECT(src && dst && src_mapped && dst_mapped);
1283 std::memset(src_mapped, 0, bytes);
1284 std::memset(dst_mapped, 0, bytes);
1285
1286 constexpr ResourceId src_id = 50, dst_id = 51;
1287 ResourceBinding src_binding{}, dst_binding{};
1288 src_binding.buffer = src;
1289 src_binding.size = bytes;
1290 src_binding.va = va_src;
1291 dst_binding.buffer = dst;
1292 dst_binding.size = bytes;
1293 const auto resolve = [&](ResourceId id) -> const ResourceBinding* {
1294 if (id == src_id) return &src_binding;
1295 if (id == dst_id) return &dst_binding;
1296 return nullptr;
1297 };
1298 ReplayFunctions vk{};
1299 vk.pipeline_barrier = d.fn<PFN_vkCmdPipelineBarrier>("vkCmdPipelineBarrier");
1300 vk.pipeline_barrier2 = d.fn<PFN_vkCmdPipelineBarrier2>("vkCmdPipelineBarrier2");
1301 vk.copy_buffer = d.fn<PFN_vkCmdCopyBuffer>("vkCmdCopyBuffer"); // replay wants all four copy functions
1302 vk.copy_buffer_to_image = d.fn<PFN_vkCmdCopyBufferToImage>("vkCmdCopyBufferToImage");
1303 vk.copy_image_to_buffer = d.fn<PFN_vkCmdCopyImageToBuffer>("vkCmdCopyImageToBuffer");
1304 vk.copy_image = d.fn<PFN_vkCmdCopyImage>("vkCmdCopyImage");
1305 vk.update_buffer = d.fn<PFN_vkCmdUpdateBuffer>("vkCmdUpdateBuffer");
1306 vk.buffer_at = [&](std::uint64_t va, std::uint64_t length, VkBuffer& buffer, VkDeviceSize& offset) {
1307 if (va < va_src || va - va_src >= bytes || length > bytes - (va - va_src)) return false;
1308 buffer = src;
1309 offset = va - va_src;
1310 return true;
1311 };
1312
1313 namespace ac = d3d12_access;
1314 namespace y = d3d12_sync;
1315 CommandList list;
1316 EXPECT(list.write_immediate({va_src + 8, value, write_immediate_mode::normal}));
1317 EXPECT(list.barrier(BufferBarrier{y::copy, y::copy, ac::copy_dest, ac::copy_source, src_id}));
1318 EXPECT(list.copy_buffer({dst_id, 16, src_id, 8, 4}));
1319 EXPECT(list.close());
1320
1321 const unsigned errors_before = d.validation_errors();
1322 ReplayResult result = ReplayResult::success;
1323 EXPECT(d.run([&](VkCommandBuffer cb) {
1324 result = replay(list, cb, resolve, vk);
1325 if (result != ReplayResult::success) std::fprintf(stderr, "K: replay returned %d\n", int(result));
1326 return result == ReplayResult::success;
1327 }));
1328 const unsigned errors = d.validation_errors() - errors_before;
1329 std::uint32_t copied = 0;
1330 std::memcpy(&copied, static_cast<const std::uint8_t*>(dst_mapped) + 16, 4);
1331 if (copied != value) {
1332 std::fprintf(stderr, "K: copied 0x%08x, want 0x%08x\n", copied, value);
1333 ++g_mismatches;
1334 }
1335 if (errors) {
1336 std::fprintf(stderr, "K: %u validation errors: a SYNC_COPY barrier does not cover vkCmdUpdateBuffer\n", errors);
1337 return 1;
1338 }
1339 std::printf("K: SYNC_COPY orders WriteBufferImmediate (vkCmdUpdateBuffer, CLEAR stage) before a copy\n");
1340 return 0;
1341}
1342
1268} // namespace 1343} // namespace
1269 1344
1270int main() { 1345int main() {
@@ -1276,7 +1351,7 @@ int main() {
1276 } 1351 }
1277 EXPECT(status == vktest::DeviceStatus::ready); 1352 EXPECT(status == vktest::DeviceStatus::ready);
1278 if (part_a(device) || part_b(device) || part_c(device) || part_d(device) || part_e(device) || part_f(device) || 1353 if (part_a(device) || part_b(device) || part_c(device) || part_d(device) || part_e(device) || part_f(device) ||
1279 part_g(device) || part_h(device) || part_i(device) || part_j(device)) 1354 part_g(device) || part_h(device) || part_i(device) || part_j(device) || part_k(device))
1280 return 1; 1355 return 1;
1281 if (g_mismatches) return 1; 1356 if (g_mismatches) return 1;
1282 if (device.validation_errors()) { 1357 if (device.validation_errors()) {
diff --git a/runtime/test/vk_compute_test.cpp b/runtime/test/vk_compute_test.cpp
index 5ac0bb1bb..8cc6a2a2f 100644
--- a/runtime/test/vk_compute_test.cpp
+++ b/runtime/test/vk_compute_test.cpp
@@ -152,7 +152,8 @@ static int run(int argc, char** argv) {
152 } 152 }
153 // VKC_HEAP_FILE=<path>[@<offset>]: copy a file into the heap so a shader can read a buffer (a BVH, its 153 // VKC_HEAP_FILE=<path>[@<offset>]: copy a file into the heap so a shader can read a buffer (a BVH, its
154 // descriptor blocks and the records) without the test hard-coding it. The offset is a decimal or 0x hex byte 154 // descriptor blocks and the records) without the test hard-coding it. The offset is a decimal or 0x hex byte
155 // offset (no octal, sign or spaces); addresses the shader sees are Xbox VAs, i.e. heap offsets, as for every 155 // offset (no octal, sign or spaces) below 2^32, and the whole file must fit below 2^32 too (the heap is the
156 // 32-bit GPU window); addresses the shader sees are Xbox VAs, i.e. heap offsets, as for every
156 // other heap buffer here. Two overlaps to keep in mind: "bvh" mode writes its synthetic scene after this copy, 157 // other heap buffer here. Two overlaps to keep in mind: "bvh" mode writes its synthetic scene after this copy,
157 // so a file at 0x100..0x264 is overwritten there, and the output V# starts at heap offset 0, so a file at @0 158 // so a file at 0x100..0x264 is overwritten there, and the output V# starts at heap offset 0, so a file at @0
158 // shares bytes with the dispatch's output. 159 // shares bytes with the dispatch's output.
@@ -175,15 +176,30 @@ static int run(int argc, char** argv) {
175 } 176 }
176 char* end = nullptr; 177 char* end = nullptr;
177 const unsigned long long parsed = std::strtoull(body, &end, hex ? 16 : 10); 178 const unsigned long long parsed = std::strtoull(body, &end, hex ? 16 : 10);
178 if (end == body || *end || parsed > (1ull << 32) || heap_file_path.empty()) { 179 // The heap is the 32-bit Xbox GPU window: an offset of 2^32 is one past it (RT-439).
180 if (end == body || *end || parsed >= (1ull << 32) || heap_file_path.empty()) {
179 std::fprintf(stderr, "VKC_HEAP_FILE: expected <path>[@<offset>], got \"%s\"\n", heap_file_env); 181 std::fprintf(stderr, "VKC_HEAP_FILE: expected <path>[@<offset>], got \"%s\"\n", heap_file_env);
180 return 2; 182 return 2;
181 } 183 }
182 heap_file_at = parsed; 184 heap_file_at = parsed;
183 } 185 }
184 std::ifstream hf(heap_file_path, std::ios::binary); 186 // The size is checked on the open file before anything is read, so a file that can't fit is refused
185 heap_file.assign(std::istreambuf_iterator<char>(hf), {}); 187 // without reading it into memory (@shdann on #5878).
186 if (heap_file.empty()) { 188 std::ifstream hf(heap_file_path, std::ios::binary | std::ios::ate);
189 const std::streamoff length = hf ? static_cast<std::streamoff>(hf.tellg()) : std::streamoff(-1);
190 if (length <= 0) {
191 std::fprintf(stderr, "VKC_HEAP_FILE: cannot read %s\n", heap_file_path.c_str());
192 return 2;
193 }
194 if (static_cast<unsigned long long>(length) > (1ull << 32) - heap_file_at) { // the last byte too must fit
195 std::fprintf(stderr, "VKC_HEAP_FILE: %s (%lld bytes) at 0x%llx runs past the 4 GiB heap\n",
196 heap_file_path.c_str(), static_cast<long long>(length),
197 static_cast<unsigned long long>(heap_file_at));
198 return 2;
199 }
200 heap_file.resize(static_cast<std::size_t>(length));
201 hf.seekg(0);
202 if (!hf.read(heap_file.data(), length)) {
187 std::fprintf(stderr, "VKC_HEAP_FILE: cannot read %s\n", heap_file_path.c_str()); 203 std::fprintf(stderr, "VKC_HEAP_FILE: cannot read %s\n", heap_file_path.c_str());
188 return 2; 204 return 2;
189 } 205 }
diff --git a/runtime/test/vk_host_at_aliasing_test.cpp b/runtime/test/vk_host_at_aliasing_test.cpp
new file mode 100644
index 000000000..06ce1946d
--- /dev/null
+++ b/runtime/test/vk_host_at_aliasing_test.cpp
@@ -0,0 +1,257 @@
1// VulkanContext::replay_.host_at resolution across aliasing placed buffers (via KHR TLAS array-of-pointers staging).
2// Public runtime classes with fake Vulkan procedures: no loader, GPU, or game data.
3#include "../src/vulkan_backend.h"
4
5#include <array>
6#include <cstdint>
7#include <cstdio>
8#include <cstring>
9#include <type_traits>
10#include <vector>
11
12namespace {
13
14int failures = 0;
15int live_buffers = 0;
16int live_memories = 0;
17int mapped_count = 0;
18int as_builds = 0;
19bool build_saw_array_of_pointers = false;
20VkDeviceAddress build_instances_address = 0;
21std::array<std::uint8_t, 256> stage_bytes{};
22std::vector<std::uint64_t> staged_addresses;
23
24void expect(bool ok, const char* what) {
25 if (!ok) {
26 std::fprintf(stderr, "FAIL: %s\n", what);
27 ++failures;
28 }
29}
30
31template<typename Handle>
32Handle handle(std::uintptr_t value) {
33 if constexpr (std::is_pointer_v<Handle>)
34 return reinterpret_cast<Handle>(value);
35 else
36 return static_cast<Handle>(value);
37}
38
39constexpr VkDeviceAddress kStageDeviceAddress = 0xfeed0000ull;
40
41VKAPI_ATTR VkResult VKAPI_CALL mock_create_pool(VkDevice, const VkCommandPoolCreateInfo*,
42 const VkAllocationCallbacks*, VkCommandPool* out) {
43 *out = handle<VkCommandPool>(1);
44 return VK_SUCCESS;
45}
46VKAPI_ATTR void VKAPI_CALL mock_destroy_pool(VkDevice, VkCommandPool, const VkAllocationCallbacks*) {}
47VKAPI_ATTR VkResult VKAPI_CALL mock_create_semaphore(VkDevice, const VkSemaphoreCreateInfo*,
48 const VkAllocationCallbacks*, VkSemaphore* out) {
49 *out = handle<VkSemaphore>(1);
50 return VK_SUCCESS;
51}
52VKAPI_ATTR void VKAPI_CALL mock_destroy_semaphore(VkDevice, VkSemaphore, const VkAllocationCallbacks*) {}
53VKAPI_ATTR VkResult VKAPI_CALL mock_semaphore_counter(VkDevice, VkSemaphore, std::uint64_t* out) {
54 *out = UINT64_MAX;
55 return VK_SUCCESS;
56}
57VKAPI_ATTR VkResult VKAPI_CALL mock_queue_wait_idle(VkQueue) { return VK_SUCCESS; }
58VKAPI_ATTR VkResult VKAPI_CALL mock_allocate_commands(VkDevice, const VkCommandBufferAllocateInfo*,
59 VkCommandBuffer* out) {
60 *out = handle<VkCommandBuffer>(1);
61 return VK_SUCCESS;
62}
63VKAPI_ATTR VkResult VKAPI_CALL mock_reset_command(VkCommandBuffer, VkCommandBufferResetFlags) { return VK_SUCCESS; }
64VKAPI_ATTR VkResult VKAPI_CALL mock_begin_command(VkCommandBuffer, const VkCommandBufferBeginInfo*) { return VK_SUCCESS; }
65VKAPI_ATTR VkResult VKAPI_CALL mock_end_command(VkCommandBuffer) { return VK_SUCCESS; }
66VKAPI_ATTR VkResult VKAPI_CALL mock_queue_submit(VkQueue, std::uint32_t, const VkSubmitInfo*, VkFence) {
67 return VK_SUCCESS;
68}
69VKAPI_ATTR void VKAPI_CALL mock_cmd_barrier(VkCommandBuffer, VkPipelineStageFlags, VkPipelineStageFlags,
70 VkDependencyFlags, std::uint32_t, const VkMemoryBarrier*, std::uint32_t,
71 const VkBufferMemoryBarrier*, std::uint32_t,
72 const VkImageMemoryBarrier*) {}
73VKAPI_ATTR VkResult VKAPI_CALL mock_create_buffer(VkDevice, const VkBufferCreateInfo*, const VkAllocationCallbacks*,
74 VkBuffer* out) {
75 ++live_buffers;
76 *out = handle<VkBuffer>(0x100 + live_buffers);
77 return VK_SUCCESS;
78}
79VKAPI_ATTR void VKAPI_CALL mock_destroy_buffer(VkDevice, VkBuffer, const VkAllocationCallbacks*) { --live_buffers; }
80VKAPI_ATTR void VKAPI_CALL mock_buffer_memory_reqs(VkDevice, VkBuffer, VkMemoryRequirements* reqs) {
81 reqs->size = stage_bytes.size();
82 reqs->alignment = 16;
83 reqs->memoryTypeBits = 1u;
84}
85VKAPI_ATTR VkResult VKAPI_CALL mock_allocate_memory(VkDevice, const VkMemoryAllocateInfo*, const VkAllocationCallbacks*,
86 VkDeviceMemory* out) {
87 ++live_memories;
88 *out = handle<VkDeviceMemory>(0x200 + live_memories);
89 return VK_SUCCESS;
90}
91VKAPI_ATTR void VKAPI_CALL mock_free_memory(VkDevice, VkDeviceMemory, const VkAllocationCallbacks*) { --live_memories; }
92VKAPI_ATTR VkResult VKAPI_CALL mock_bind_buffer_memory(VkDevice, VkBuffer, VkDeviceMemory, VkDeviceSize) {
93 return VK_SUCCESS;
94}
95VKAPI_ATTR VkResult VKAPI_CALL mock_map_memory(VkDevice, VkDeviceMemory, VkDeviceSize offset, VkDeviceSize,
96 VkMemoryMapFlags, void** data) {
97 ++mapped_count;
98 *data = stage_bytes.data() + offset;
99 return VK_SUCCESS;
100}
101VKAPI_ATTR void VKAPI_CALL mock_unmap_memory(VkDevice, VkDeviceMemory) { --mapped_count; }
102VKAPI_ATTR VkDeviceAddress VKAPI_CALL mock_buffer_device_address(VkDevice, const VkBufferDeviceAddressInfo*) {
103 return kStageDeviceAddress;
104}
105VKAPI_ATTR void VKAPI_CALL mock_build_as(VkCommandBuffer, std::uint32_t info_count,
106 const VkAccelerationStructureBuildGeometryInfoKHR* infos,
107 const VkAccelerationStructureBuildRangeInfoKHR* const* ranges) {
108 ++as_builds;
109 if (info_count && infos && infos[0].geometryCount && infos[0].pGeometries &&
110 infos[0].pGeometries[0].geometryType == VK_GEOMETRY_TYPE_INSTANCES_KHR) {
111 const auto& inst = infos[0].pGeometries[0].geometry.instances;
112 build_saw_array_of_pointers = inst.arrayOfPointers == VK_TRUE;
113 build_instances_address = inst.data.deviceAddress;
114 const std::uint32_t n = ranges && ranges[0] ? ranges[0][0].primitiveCount : 0;
115 staged_addresses.resize(n);
116 for (std::uint32_t i = 0; i < n; ++i)
117 std::memcpy(&staged_addresses[i], stage_bytes.data() + 8ull * i, sizeof(std::uint64_t));
118 }
119}
120
121VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL mock_proc(VkDevice, const char* name) {
122#define PROC(vk_name, impl) \
123 if (std::strcmp(name, #vk_name) == 0) return reinterpret_cast<PFN_vkVoidFunction>(impl)
124 PROC(vkCreateCommandPool, mock_create_pool);
125 PROC(vkDestroyCommandPool, mock_destroy_pool);
126 PROC(vkCreateSemaphore, mock_create_semaphore);
127 PROC(vkDestroySemaphore, mock_destroy_semaphore);
128 PROC(vkGetSemaphoreCounterValue, mock_semaphore_counter);
129 PROC(vkQueueWaitIdle, mock_queue_wait_idle);
130 PROC(vkAllocateCommandBuffers, mock_allocate_commands);
131 PROC(vkResetCommandBuffer, mock_reset_command);
132 PROC(vkBeginCommandBuffer, mock_begin_command);
133 PROC(vkEndCommandBuffer, mock_end_command);
134 PROC(vkQueueSubmit, mock_queue_submit);
135 PROC(vkCmdPipelineBarrier, mock_cmd_barrier);
136 PROC(vkCreateBuffer, mock_create_buffer);
137 PROC(vkDestroyBuffer, mock_destroy_buffer);
138 PROC(vkGetBufferMemoryRequirements, mock_buffer_memory_reqs);
139 PROC(vkAllocateMemory, mock_allocate_memory);
140 PROC(vkFreeMemory, mock_free_memory);
141 PROC(vkBindBufferMemory, mock_bind_buffer_memory);
142 PROC(vkMapMemory, mock_map_memory);
143 PROC(vkUnmapMemory, mock_unmap_memory);
144 PROC(vkGetBufferDeviceAddress, mock_buffer_device_address);
145 PROC(vkCmdBuildAccelerationStructuresKHR, mock_build_as);
146#undef PROC
147 return nullptr;
148}
149
150leonida::ResourceBinding make_buffer(std::uintptr_t id, std::uint64_t va, std::uint64_t size,
151 const std::uint8_t* host) {
152 leonida::ResourceBinding b{};
153 b.buffer = handle<VkBuffer>(id);
154 b.va = va;
155 b.size = size;
156 b.host = host;
157 return b;
158}
159
160leonida::ReplayResult run_tlas_pointers(leonida::VulkanContext& ctx, std::uint64_t dst_va, std::uint64_t pointers_va,
161 std::uint32_t instance_count) {
162 leonida::BuildAccelerationStructure b{};
163 b.is_tlas = true;
164 b.dst_va = dst_va;
165 b.scratch_va = 0x20000;
166 b.instances_va = pointers_va;
167 b.instance_count = instance_count;
168 b.instance_pointers = true;
169
170 leonida::CommandList list;
171 expect(list.build_acceleration_structure(std::move(b)) && list.close(), "invalid TLAS test command list");
172 leonida::VulkanQueue queue(ctx, handle<VkQueue>(1), 0);
173 expect(queue.ok(), "mock VulkanQueue did not initialize");
174 const leonida::CommandList* lists[] = {&list};
175 return queue.execute(lists);
176}
177
178} // namespace
179
180int main() {
181 constexpr std::uint64_t kHeapBase = 0x1000000ull;
182 constexpr std::uint64_t kDstVa = 0x10000ull;
183 constexpr std::uint64_t kInstVa = 0x4000ull;
184 constexpr std::uint64_t kPtrVa = 0x8000ull;
185 constexpr std::uint64_t kGpuVa = 0xc000ull;
186 constexpr std::uint64_t kBaseVa = 0xe000ull;
187
188 {
189 leonida::VulkanContext ctx(mock_proc, handle<VkDevice>(1), false, false, true, false);
190 VkPhysicalDeviceMemoryProperties mem{};
191 mem.memoryHeapCount = 1;
192 mem.memoryHeaps[0].size = 1024 * 1024;
193 mem.memoryTypes[0].propertyFlags =
194 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
195 mem.memoryTypes[0].heapIndex = 0;
196 mem.memoryTypeCount = 1;
197 ctx.set_occlusion_resolve_memory(mem);
198 ctx.set_heap_base(kHeapBase);
199 ctx.register_acceleration_structure(kDstVa, handle<VkAccelerationStructureKHR>(0x500));
200
201 // Backing buffer covering both 64-byte instance descriptors.
202 std::array<std::uint8_t, 128> inst_storage{};
203 ctx.add_resource(1, make_buffer(1, kInstVa, inst_storage.size(), inst_storage.data()));
204
205 // Case 1: Tied-start aliasing upload buffers: ID 10 holds 64 bytes, higher-ID 20 holds only 8 bytes.
206 // host_at(kPtrVa, 16) must pick ID 10 instead of failing on ID 20.
207 std::array<std::uint64_t, 8> big_ptrs{kInstVa, kInstVa + 64};
208 std::array<std::uint64_t, 1> small_ptrs{kInstVa + 64};
209 ctx.add_resource(10, make_buffer(10, kPtrVa, big_ptrs.size() * sizeof(std::uint64_t),
210 reinterpret_cast<const std::uint8_t*>(big_ptrs.data())));
211 ctx.add_resource(20, make_buffer(20, kPtrVa, small_ptrs.size() * sizeof(std::uint64_t),
212 reinterpret_cast<const std::uint8_t*>(small_ptrs.data())));
213
214 as_builds = 0;
215 staged_addresses.clear();
216 expect(run_tlas_pointers(ctx, kDstVa, kPtrVa, 2) == leonida::ReplayResult::success,
217 "host_at must resolve aliasing larger placed upload buffer for full byte range");
218 expect(as_builds == 1 && build_saw_array_of_pointers && build_instances_address == kStageDeviceAddress,
219 "TLAS build did not consume staged KHR pointer buffer");
220 expect(staged_addresses.size() == 2 && staged_addresses[0] == kHeapBase + kInstVa &&
221 staged_addresses[1] == kHeapBase + kInstVa + 64,
222 "staged instance device addresses came from wrong aliasing buffer");
223
224 // Case 2: Request larger than every aliasing buffer (80 > 64) still fails with invalid_copy.
225 as_builds = 0;
226 expect(run_tlas_pointers(ctx, kDstVa, kPtrVa, 10) == leonida::ReplayResult::invalid_copy && as_builds == 0,
227 "oversized range past every aliasing buffer must fail");
228
229 // Case 3: Non-CPU-written (DEFAULT/READBACK, host == nullptr) buffer returns unsupported without falling through.
230 ctx.add_resource(30, make_buffer(30, kGpuVa, 64, nullptr));
231 expect(run_tlas_pointers(ctx, kDstVa, kGpuVa, 2) == leonida::ReplayResult::unsupported,
232 "GPU-only buffer must return unsupported");
233
234 // Case 4: Offset aliasing: small placed buffer starting inside a larger CPU-mapped placed buffer.
235 std::array<std::uint64_t, 16> offset_big{};
236 offset_big[4] = kInstVa;
237 offset_big[5] = kInstVa + 64;
238 std::array<std::uint64_t, 1> offset_small{kInstVa};
239 ctx.add_resource(40, make_buffer(40, kBaseVa, offset_big.size() * sizeof(std::uint64_t),
240 reinterpret_cast<const std::uint8_t*>(offset_big.data())));
241 ctx.add_resource(41, make_buffer(41, kBaseVa + 32, offset_small.size() * sizeof(std::uint64_t),
242 reinterpret_cast<const std::uint8_t*>(offset_small.data())));
243 as_builds = 0;
244 staged_addresses.clear();
245 expect(run_tlas_pointers(ctx, kDstVa, kBaseVa + 32, 2) == leonida::ReplayResult::success && as_builds == 1,
246 "host_at at offset must fall back to aliasing container buffer holding full range");
247 expect(staged_addresses.size() == 2 && staged_addresses[0] == kHeapBase + kInstVa &&
248 staged_addresses[1] == kHeapBase + kInstVa + 64,
249 "offset aliasing staged wrong addresses");
250 }
251
252 expect(live_buffers == 0 && live_memories == 0 && mapped_count == 0,
253 "mock staging buffers/memories leaked after VulkanContext teardown");
254 if (failures) return 1;
255 std::puts("vk_host_at_aliasing: ok");
256 return 0;
257}
diff --git a/runtime/test/vk_queue_test.cpp b/runtime/test/vk_queue_test.cpp
index 744adfab8..8dad391b0 100644
--- a/runtime/test/vk_queue_test.cpp
+++ b/runtime/test/vk_queue_test.cpp
@@ -64,6 +64,33 @@ VKAPI_ATTR VkResult VKAPI_CALL stalling_wait_semaphores(VkDevice device, const V
64 return real_wait_semaphores(device, info, timeout); 64 return real_wait_semaphores(device, info, timeout);
65} 65}
66 66
67// Each submission's command buffer starts with a full memory barrier (D3D12's ExecuteCommandLists boundary): counts
68// the command buffers begun and those whose first barrier is that one.
69PFN_vkBeginCommandBuffer real_begin = nullptr;
70PFN_vkCmdPipelineBarrier real_barrier = nullptr;
71std::uint32_t begun = 0, led_by_full_barrier = 0;
72bool awaiting_first_barrier = false;
73
74VKAPI_ATTR VkResult VKAPI_CALL counting_begin(VkCommandBuffer cb, const VkCommandBufferBeginInfo* info) {
75 ++begun;
76 awaiting_first_barrier = true;
77 return real_begin(cb, info);
78}
79
80VKAPI_ATTR void VKAPI_CALL watching_barrier(VkCommandBuffer cb, VkPipelineStageFlags src, VkPipelineStageFlags dst,
81 VkDependencyFlags flags, std::uint32_t memory_count,
82 const VkMemoryBarrier* memory, std::uint32_t buffer_count,
83 const VkBufferMemoryBarrier* buffers, std::uint32_t image_count,
84 const VkImageMemoryBarrier* images) {
85 if (awaiting_first_barrier) {
86 awaiting_first_barrier = false;
87 if (src == VK_PIPELINE_STAGE_ALL_COMMANDS_BIT && dst == VK_PIPELINE_STAGE_ALL_COMMANDS_BIT &&
88 memory_count == 1 && (memory[0].srcAccessMask & VK_ACCESS_MEMORY_WRITE_BIT))
89 ++led_by_full_barrier;
90 }
91 real_barrier(cb, src, dst, flags, memory_count, memory, buffer_count, buffers, image_count, images);
92}
93
67const char* flags_text(VkQueueFlags f) { 94const char* flags_text(VkQueueFlags f) {
68 static char buf[32]; 95 static char buf[32];
69 std::snprintf(buf, sizeof buf, "%s%s%s", f & VK_QUEUE_GRAPHICS_BIT ? "G" : "", f & VK_QUEUE_COMPUTE_BIT ? "C" : "", 96 std::snprintf(buf, sizeof buf, "%s%s%s", f & VK_QUEUE_GRAPHICS_BIT ? "G" : "", f & VK_QUEUE_COMPUTE_BIT ? "C" : "",
@@ -347,6 +374,38 @@ int main() {
347 EXPECT(compute.execute(clear_lists) == ReplayResult::unsupported); 374 EXPECT(compute.execute(clear_lists) == ReplayResult::unsupported);
348 std::printf("copy and compute queues refuse a render-target clear\n"); 375 std::printf("copy and compute queues refuse a render-target clear\n");
349 376
377 // 4b. Two ExecuteCommandLists copying into the same buffer, with no barrier in either list: D3D12 orders them (each
378 // ends with its work done and visible), so each submission's command buffer must start with a full memory barrier.
379 // Before, none did, and synchronization validation reported WRITE_AFTER_WRITE between them (in 5 below).
380 {
381 void* map = nullptr;
382 VkBuffer twice_src = d.buffer(4096, usage, &map);
383 VkBuffer twice_dst = d.buffer(4096, usage, &map);
384 EXPECT(twice_src && twice_dst);
385 add_buffer(9, twice_src, 4096);
386 add_buffer(10, twice_dst, 4096);
387 CommandList twice;
388 EXPECT(twice.copy_buffer({10, 0, 9, 0, 4096}));
389 EXPECT(twice.close());
390 const CommandList* twice_lists[] = {&twice};
391 real_begin = context.vk.vkBeginCommandBuffer;
392 real_barrier = context.vk.vkCmdPipelineBarrier;
393 context.vk.vkBeginCommandBuffer = counting_begin;
394 context.vk.vkCmdPipelineBarrier = watching_barrier;
395 begun = led_by_full_barrier = 0;
396 for (Kind kind : {Kind::direct, Kind::copy}) {
397 VulkanQueue& q = kind == Kind::direct ? direct : copy;
398 EXPECT(q.execute(twice_lists) == ReplayResult::success);
399 EXPECT(q.execute(twice_lists) == ReplayResult::success);
400 EXPECT(q.idle());
401 }
402 context.vk.vkBeginCommandBuffer = real_begin;
403 context.vk.vkCmdPipelineBarrier = real_barrier;
404 std::printf("ExecuteCommandLists boundary: %u of %u submissions start with a full memory barrier\n",
405 led_by_full_barrier, begun);
406 EXPECT(begun >= 4 && led_by_full_barrier == begun);
407 }
408
350 // 5. A caller that submits faster than the GPU finishes must not grow the queue's command buffers without bound: 409 // 5. A caller that submits faster than the GPU finishes must not grow the queue's command buffers without bound:
351 // at the cap it waits for the oldest one. Big host-visible copies keep the GPU behind the submitting loop. The first 410 // at the cap it waits for the oldest one. Big host-visible copies keep the GPU behind the submitting loop. The first
352 // waits time out (injected), as on a stalled GPU: the cap must hold through a timeout too. 411 // waits time out (injected), as on a stalled GPU: the cap must hold through a timeout too.
diff --git a/runtime/test/vk_store_test.cpp b/runtime/test/vk_store_test.cpp
index 5567511d0..99a602aeb 100644
--- a/runtime/test/vk_store_test.cpp
+++ b/runtime/test/vk_store_test.cpp
@@ -16,6 +16,10 @@
16// at binding 7, where 2D and 3D image atomics address their image, and at index 4 of the sampled array a 16x4 rgba8 16// at binding 7, where 2D and 3D image atomics address their image, and at index 4 of the sampled array a 16x4 rgba8
17// image with all five mip levels (never read, only queried), behind the T# the runtime writes for such an image. 17// image with all five mip levels (never read, only queried), behind the T# the runtime writes for such an image.
18// "signed-zero" checks three direct float stores and all remaining RGBA32 guard words (SHADER-605). 18// "signed-zero" checks three direct float stores and all remaining RGBA32 guard words (SHADER-605).
19// "cube" (cs_imgstore_cube.asm, GPU-CUBE-STORE): the shader stores to three cube images (the same three formats, T#
20// word3 TYPE = SQ_RSRC_IMG_CUBE). As the runtime binds a cube UAV (runtime/src/vulkan_bindless.h), each is a
21// cube-compatible 8x8 image of six layers whose storage view is a six-layer 2D array, at index k + 1 of the 2D-array
22// storage arrays (bindings 11 / 12 / 13 for float / uint / sint). Checks every texel of every layer (the face).
19#include "vulkan_loader.h" 23#include "vulkan_loader.h"
20#include "vk_device_pick.h" 24#include "vk_device_pick.h"
21#include "vk_shader_fma.h" 25#include "vk_shader_fma.h"
@@ -60,7 +64,10 @@ static void table_insert(std::vector<uint32_t>& t, const uint32_t key[8], uint32
60} 64}
61 65
62int main(int argc, char** argv) { 66int main(int argc, char** argv) {
63 if (argc < 2) { std::fprintf(stderr, "usage: vk_store_test cs.spv [load|load-d16|words|signed-zero]\n"); return 2; } 67 if (argc < 2) {
68 std::fprintf(stderr, "usage: vk_store_test cs.spv [load|load-d16|words|signed-zero|cube]\n");
69 return 2;
70 }
64 gipa = load_vulkan(); 71 gipa = load_vulkan();
65 if (!gipa) return 1; 72 if (!gipa) return 1;
66#define LOADI(name) auto name = reinterpret_cast<PFN_##name>(gipa(inst, #name)) 73#define LOADI(name) auto name = reinterpret_cast<PFN_##name>(gipa(inst, #name))
@@ -126,6 +133,7 @@ int main(int argc, char** argv) {
126 // "words" mode: the two images filled as for "load"; the shader's results are whatever it leaves in them. 133 // "words" mode: the two images filled as for "load"; the shader's results are whatever it leaves in them.
127 const bool words_mode = argc > 2 && !std::strcmp(argv[2], "words"); 134 const bool words_mode = argc > 2 && !std::strcmp(argv[2], "words");
128 const bool signed_zero = argc > 2 && !std::strcmp(argv[2], "signed-zero"); 135 const bool signed_zero = argc > 2 && !std::strcmp(argv[2], "signed-zero");
136 const bool cube_mode = argc > 2 && !std::strcmp(argv[2], "cube");
129 if (signed_zero) { 137 if (signed_zero) {
130 LOADI(vkGetPhysicalDeviceProperties2); 138 LOADI(vkGetPhysicalDeviceProperties2);
131 VkPhysicalDeviceFloatControlsProperties controls{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FLOAT_CONTROLS_PROPERTIES}; 139 VkPhysicalDeviceFloatControlsProperties controls{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FLOAT_CONTROLS_PROPERTIES};
@@ -224,6 +232,10 @@ int main(int argc, char** argv) {
224 uint32_t t[8] = {0x1000 * (k + 1), fmts[k] << 20}; 232 uint32_t t[8] = {0x1000 * (k + 1), fmts[k] << 20};
225 for (int j = 2; j < 8; j++) t[j] = 0x11 * (k + 1); 233 for (int j = 2; j < 8; j++) t[j] = 0x11 * (k + 1);
226 table_insert(table, t, k + 1); // its index in the 2D arrays; 0 is the fallback, as in the runtime 234 table_insert(table, t, k + 1); // its index in the 2D arrays; 0 is the fallback, as in the runtime
235 if (cube_mode) { // the cube T# (cs_imgstore_cube.asm): word3 also has TYPE = 0xB, index k + 1 of the 2D arrays
236 t[3] |= 0xB0000000u;
237 table_insert(table, t, k + 1);
238 }
227 } 239 }
228 // Index 4: a 16x4 rgba8 image with its whole mip chain (16x4, 8x2, 4x1, 2x1, 1x1) for image_get_resinfo. Its key 240 // Index 4: a 16x4 rgba8 image with its whole mip chain (16x4, 8x2, 4x1, 2x1, 1x1) for image_get_resinfo. Its key
229 // is the T# of exactly that image (gfx10_descriptors.h), which cs_resinfo.asm builds word for word. 241 // is the T# of exactly that image (gfx10_descriptors.h), which cs_resinfo.asm builds word for word.
@@ -296,6 +308,26 @@ int main(int argc, char** argv) {
296 vi.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; 308 vi.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
297 CHECK(vkCreateImageView(dev, &vi, nullptr, &vol_view)); 309 CHECK(vkCreateImageView(dev, &vi, nullptr, &vol_view));
298 } 310 }
311 // Cube mode: three cube-compatible 8x8 images of six layers, each seen through a six-layer 2D-array view.
312 const uint32_t FACES = 6;
313 VkImage cube[3]{}; VkImageView cube_view[3]{};
314 for (int k = 0; cube_mode && k < 3; k++) {
315 VkImageCreateInfo ii{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO};
316 ii.flags = VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT;
317 ii.imageType = VK_IMAGE_TYPE_2D; ii.format = vkf[k]; ii.extent = {W, W, 1}; ii.mipLevels = 1;
318 ii.arrayLayers = FACES; ii.samples = VK_SAMPLE_COUNT_1_BIT; ii.tiling = VK_IMAGE_TILING_OPTIMAL;
319 ii.usage = VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
320 CHECK(vkCreateImage(dev, &ii, nullptr, &cube[k]));
321 VkMemoryRequirements mr; vkGetImageMemoryRequirements(dev, cube[k], &mr);
322 VkMemoryAllocateInfo mai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO};
323 mai.allocationSize = mr.size; mai.memoryTypeIndex = memtype(mr.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
324 VkDeviceMemory m; CHECK(vkAllocateMemory(dev, &mai, nullptr, &m));
325 CHECK(vkBindImageMemory(dev, cube[k], m, 0));
326 VkImageViewCreateInfo vi{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO};
327 vi.image = cube[k]; vi.viewType = VK_IMAGE_VIEW_TYPE_2D_ARRAY; vi.format = vkf[k];
328 vi.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, FACES};
329 CHECK(vkCreateImageView(dev, &vi, nullptr, &cube_view[k]));
330 }
299 VkSamplerCreateInfo sci{VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO}; 331 VkSamplerCreateInfo sci{VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO};
300 VkSampler sampler; CHECK(vkCreateSampler(dev, &sci, nullptr, &sampler)); 332 VkSampler sampler; CHECK(vkCreateSampler(dev, &sci, nullptr, &sampler));
301 // Set 0: binding 0 = sampled images, 1 = samplers, 2 = hash table, 8/9/10 = float/uint/sint 2D storage image arrays. 333 // Set 0: binding 0 = sampled images, 1 = samplers, 2 = hash table, 8/9/10 = float/uint/sint 2D storage image arrays.
@@ -303,23 +335,27 @@ int main(int argc, char** argv) {
303 // index 4. Binding 0 holds each image's view in its own format (typed image_load reads the uint and sint ones 335 // index 4. Binding 0 holds each image's view in its own format (typed image_load reads the uint and sint ones
304 // through integer aliases); every element of a storage array holds the image of its class, so all of them are 336 // through integer aliases); every element of a storage array holds the image of its class, so all of them are
305 // valid descriptors. Bindings 4 and 7 = the 2D and 3D r32ui storage images of the image atomics: the uint image 337 // valid descriptors. Bindings 4 and 7 = the 2D and 3D r32ui storage images of the image atomics: the uint image
306 // and the volume, in every element. 338 // and the volume, in every element. Cube mode adds 11/12/13 = the float/uint/sint 2D-array storage arrays, which
339 // hold the cube image of their class in every element.
307 constexpr uint32_t N = 5; 340 constexpr uint32_t N = 5;
308 VkDescriptorSetLayoutBinding b[8]{}; 341 const uint32_t bindings = cube_mode ? 11 : 8;
342 VkDescriptorSetLayoutBinding b[11]{};
309 b[0] = {0, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, N, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; 343 b[0] = {0, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, N, VK_SHADER_STAGE_COMPUTE_BIT, nullptr};
310 b[1] = {1, VK_DESCRIPTOR_TYPE_SAMPLER, 1, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; 344 b[1] = {1, VK_DESCRIPTOR_TYPE_SAMPLER, 1, VK_SHADER_STAGE_COMPUTE_BIT, nullptr};
311 b[2] = {2, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; 345 b[2] = {2, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT, nullptr};
312 for (int k = 0; k < 3; k++) b[3 + k] = {uint32_t(8 + k), VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, N, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; 346 for (int k = 0; k < 3; k++) b[3 + k] = {uint32_t(8 + k), VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, N, VK_SHADER_STAGE_COMPUTE_BIT, nullptr};
313 b[6] = {4, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, N, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; 347 b[6] = {4, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, N, VK_SHADER_STAGE_COMPUTE_BIT, nullptr};
314 b[7] = {7, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, N, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; 348 b[7] = {7, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, N, VK_SHADER_STAGE_COMPUTE_BIT, nullptr};
349 for (int k = 0; k < 3; k++)
350 b[8 + k] = {uint32_t(11 + k), VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, N, VK_SHADER_STAGE_COMPUTE_BIT, nullptr};
315 VkDescriptorSetLayoutCreateInfo dli{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; 351 VkDescriptorSetLayoutCreateInfo dli{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO};
316 dli.bindingCount = 8; dli.pBindings = b; 352 dli.bindingCount = bindings; dli.pBindings = b;
317 VkDescriptorSetLayout dsl; CHECK(vkCreateDescriptorSetLayout(dev, &dli, nullptr, &dsl)); 353 VkDescriptorSetLayout dsl; CHECK(vkCreateDescriptorSetLayout(dev, &dli, nullptr, &dsl));
318 VkDescriptorPoolSize ps[4] = { 354 VkDescriptorPoolSize ps[4] = {
319 {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, N}, 355 {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, N},
320 {VK_DESCRIPTOR_TYPE_SAMPLER, 1}, 356 {VK_DESCRIPTOR_TYPE_SAMPLER, 1},
321 {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1}, 357 {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1},
322 {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 5 * N}, 358 {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, (bindings - 3) * N},
323 }; 359 };
324 VkDescriptorPoolCreateInfo dpi{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; 360 VkDescriptorPoolCreateInfo dpi{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO};
325 dpi.maxSets = 1; dpi.poolSizeCount = 4; dpi.pPoolSizes = ps; 361 dpi.maxSets = 1; dpi.poolSizeCount = 4; dpi.pPoolSizes = ps;
@@ -335,8 +371,8 @@ int main(int argc, char** argv) {
335 {VK_NULL_HANDLE, wide_view, VK_IMAGE_LAYOUT_GENERAL}}; 371 {VK_NULL_HANDLE, wide_view, VK_IMAGE_LAYOUT_GENERAL}};
336 VkDescriptorImageInfo smpi{sampler, VK_NULL_HANDLE, VK_IMAGE_LAYOUT_UNDEFINED}; 372 VkDescriptorImageInfo smpi{sampler, VK_NULL_HANDLE, VK_IMAGE_LAYOUT_UNDEFINED};
337 VkDescriptorImageInfo dii[3][N]; 373 VkDescriptorImageInfo dii[3][N];
338 VkDescriptorImageInfo r32ui[N], r32ui_3d[N]; 374 VkDescriptorImageInfo r32ui[N], r32ui_3d[N], cube_ii[3][N];
339 VkWriteDescriptorSet wr[8]{}; 375 VkWriteDescriptorSet wr[11]{};
340 for (auto& w : wr) { w.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; w.dstSet = ds; w.descriptorCount = 1; } 376 for (auto& w : wr) { w.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; w.dstSet = ds; w.descriptorCount = 1; }
341 wr[0].dstBinding = 0; wr[0].descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; wr[0].pImageInfo = sii; 377 wr[0].dstBinding = 0; wr[0].descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; wr[0].pImageInfo = sii;
342 wr[0].descriptorCount = N; 378 wr[0].descriptorCount = N;
@@ -353,7 +389,12 @@ int main(int argc, char** argv) {
353 for (uint32_t e = 0; e < N; e++) r32ui_3d[e] = {VK_NULL_HANDLE, vol_view, VK_IMAGE_LAYOUT_GENERAL}; 389 for (uint32_t e = 0; e < N; e++) r32ui_3d[e] = {VK_NULL_HANDLE, vol_view, VK_IMAGE_LAYOUT_GENERAL};
354 wr[7].dstBinding = 7; wr[7].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; 390 wr[7].dstBinding = 7; wr[7].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
355 wr[7].pImageInfo = r32ui_3d; wr[7].descriptorCount = N; 391 wr[7].pImageInfo = r32ui_3d; wr[7].descriptorCount = N;
356 vkUpdateDescriptorSets(dev, 8, wr, 0, nullptr); 392 for (int k = 0; cube_mode && k < 3; k++) {
393 for (uint32_t e = 0; e < N; e++) cube_ii[k][e] = {VK_NULL_HANDLE, cube_view[k], VK_IMAGE_LAYOUT_GENERAL};
394 wr[8 + k].dstBinding = 11 + k; wr[8 + k].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
395 wr[8 + k].pImageInfo = cube_ii[k]; wr[8 + k].descriptorCount = N;
396 }
397 vkUpdateDescriptorSets(dev, bindings, wr, 0, nullptr);
357 398
358 VkShaderModuleCreateInfo smi{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; 399 VkShaderModuleCreateInfo smi{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO};
359 smi.codeSize = code.size(); smi.pCode = reinterpret_cast<const uint32_t*>(code.data()); 400 smi.codeSize = code.size(); smi.pCode = reinterpret_cast<const uint32_t*>(code.data());
@@ -383,6 +424,11 @@ int main(int argc, char** argv) {
383 const uint32_t image_words = W * W * (signed_zero ? 4 : 1); 424 const uint32_t image_words = W * W * (signed_zero ? 4 : 1);
384 VkBuffer rb[3]; void* rbp[3]; 425 VkBuffer rb[3]; void* rbp[3];
385 for (int k = 0; k < 3; k++) CHECK(make_buffer(image_words * 4, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &rb[k], &rbp[k])); 426 for (int k = 0; k < 3; k++) CHECK(make_buffer(image_words * 4, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &rb[k], &rbp[k]));
427 // Cube mode: each cube image's six layers read back one after another, texel (x, y) of face f at 64f + 8y + x.
428 const uint32_t cube_words = W * W * FACES;
429 VkBuffer cube_rb[3]{}; void* cube_rbp[3]{};
430 for (int k = 0; cube_mode && k < 3; k++)
431 CHECK(make_buffer(cube_words * 4, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &cube_rb[k], &cube_rbp[k]));
386 // Load and words modes: what the uint and sint images hold before the dispatch, texel (x, y) at i = 8y + x. 432 // Load and words modes: what the uint and sint images hold before the dispatch, texel (x, y) at i = 8y + x.
387 // The last row of the D16 fixture ("load-d16" only) exercises both sides of each 16-bit boundary. 433 // The last row of the D16 fixture ("load-d16" only) exercises both sides of each 16-bit boundary.
388 struct PackedLoad { uint32_t u; int32_t s, sum; }; 434 struct PackedLoad { uint32_t u; int32_t s, sum; };
@@ -471,6 +517,17 @@ int main(int argc, char** argv) {
471 vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, 517 vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0,
472 nullptr, 0, nullptr, 3 - first_fill, ib + first_fill); 518 nullptr, 0, nullptr, 3 - first_fill, ib + first_fill);
473 } 519 }
520 VkImageMemoryBarrier cube_ib[3]{};
521 for (int k = 0; cube_mode && k < 3; k++) {
522 cube_ib[k] = ib[0];
523 cube_ib[k].image = cube[k]; cube_ib[k].oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
524 cube_ib[k].newLayout = VK_IMAGE_LAYOUT_GENERAL; cube_ib[k].srcAccessMask = 0;
525 cube_ib[k].dstAccessMask = VK_ACCESS_SHADER_WRITE_BIT;
526 cube_ib[k].subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, FACES};
527 }
528 if (cube_mode)
529 vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr,
530 0, nullptr, 3, cube_ib);
474 vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pipe); 531 vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pipe);
475 vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pl, 0, 1, &ds, 0, nullptr); 532 vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pl, 0, 1, &ds, 0, nullptr);
476 uint32_t pc[36] = {}; 533 uint32_t pc[36] = {};
@@ -493,6 +550,19 @@ int main(int argc, char** argv) {
493 bic.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; bic.imageExtent = {W, W, 1}; 550 bic.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; bic.imageExtent = {W, W, 1};
494 vkCmdCopyImageToBuffer(cmd, img[k], VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, rb[k], 1, &bic); 551 vkCmdCopyImageToBuffer(cmd, img[k], VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, rb[k], 1, &bic);
495 } 552 }
553 if (cube_mode) {
554 for (int k = 0; k < 3; k++) {
555 cube_ib[k].oldLayout = VK_IMAGE_LAYOUT_GENERAL; cube_ib[k].newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
556 cube_ib[k].srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; cube_ib[k].dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
557 }
558 vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0,
559 nullptr, 3, cube_ib);
560 for (int k = 0; k < 3; k++) {
561 VkBufferImageCopy bic{}; // all six layers, tightly packed one after another
562 bic.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, FACES}; bic.imageExtent = {W, W, 1};
563 vkCmdCopyImageToBuffer(cmd, cube[k], VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, cube_rb[k], 1, &bic);
564 }
565 }
496 if (words_mode) { 566 if (words_mode) {
497 vol_ib.oldLayout = VK_IMAGE_LAYOUT_GENERAL; vol_ib.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; 567 vol_ib.oldLayout = VK_IMAGE_LAYOUT_GENERAL; vol_ib.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
498 vol_ib.srcAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; 568 vol_ib.srcAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
@@ -514,6 +584,30 @@ int main(int argc, char** argv) {
514 CHECK(vkQueueSubmit(q, 1, &si, VK_NULL_HANDLE)); 584 CHECK(vkQueueSubmit(q, 1, &si, VK_NULL_HANDLE));
515 CHECK(vkQueueWaitIdle(q)); 585 CHECK(vkQueueWaitIdle(q));
516 586
587 if (cube_mode) { // every texel of every face, against what cs_imgstore_cube.asm writes there
588 uint32_t bad[3] = {};
589 for (uint32_t face = 0; face < FACES; face++)
590 for (uint32_t y = 0; y < W; y++)
591 for (uint32_t x = 0; x < W; x++) {
592 const uint32_t i = y * W + x, at = face * W * W + i;
593 const uint8_t* c = static_cast<const uint8_t*>(cube_rbp[0]) + 4 * at;
594 const int er = int(std::lround(x / 7.0 * 255)), eg = int(std::lround(y / 7.0 * 255));
595 const int eb = int(std::lround(face / 5.0 * 255));
596 if (std::abs(c[0] - er) > 1 || std::abs(c[1] - eg) > 1 || std::abs(c[2] - eb) > 1 || c[3] != 255)
597 bad[0]++;
598 if (static_cast<const uint32_t*>(cube_rbp[1])[at] != 100 + 1000 * face + i) bad[1]++;
599 if (static_cast<const int32_t*>(cube_rbp[2])[at] != -int32_t(1000 * face + i)) bad[2]++;
600 }
601 const uint32_t at = 4 * W * W + 3 * W + 5; // texel (5, 3) of face 4
602 const uint8_t* c = static_cast<const uint8_t*>(cube_rbp[0]) + 4 * at;
603 std::printf("rgba8 unorm cube (float view): %u bad, face 4 texel(5,3) = %u %u %u %u\n", bad[0], c[0], c[1],
604 c[2], c[3]);
605 std::printf("r32 uint cube (uint view): %u bad, face 4 texel(5,3) = %u\n", bad[1],
606 static_cast<const uint32_t*>(cube_rbp[1])[at]);
607 std::printf("r32 sint cube (sint view): %u bad, face 4 texel(5,3) = %d\n", bad[2],
608 static_cast<const int32_t*>(cube_rbp[2])[at]);
609 return (bad[0] || bad[1] || bad[2]) ? 1 : 0;
610 }
517 if (signed_zero) { 611 if (signed_zero) {
518 constexpr uint32_t neg = 0x80000000; 612 constexpr uint32_t neg = 0x80000000;
519 constexpr uint32_t stores[] = {neg, 0, 0, 0, neg, 0x3f800000, 0, 0, neg, neg, 0, 0}; 613 constexpr uint32_t stores[] = {neg, 0, 0, 0, neg, 0x3f800000, 0, 0, neg, neg, 0, 0};
diff --git a/runtime/test/vk_test_device.h b/runtime/test/vk_test_device.h
index 5cccd1836..f1083231b 100644
--- a/runtime/test/vk_test_device.h
+++ b/runtime/test/vk_test_device.h
@@ -106,6 +106,8 @@ public:
106 bool storage_buffer_8bit = false; // storageBuffer8BitAccess enabled 106 bool storage_buffer_8bit = false; // storageBuffer8BitAccess enabled
107 bool conditional_rendering = false; // VK_EXT_conditional_rendering enabled, where available 107 bool conditional_rendering = false; // VK_EXT_conditional_rendering enabled, where available
108 bool host_image_copy = false; // VK_EXT_host_image_copy and hostImageCopy enabled 108 bool host_image_copy = false; // VK_EXT_host_image_copy and hostImageCopy enabled
109 bool request_depth_range_unrestricted = false;
110 bool depth_range_unrestricted = false; // VK_EXT_depth_range_unrestricted enabled
109 // create(true) only: VK_KHR (else EXT) swapchain_maintenance1 and its feature enabled, with the surface half on the 111 // create(true) only: VK_KHR (else EXT) swapchain_maintenance1 and its feature enabled, with the surface half on the
110 // instance, so a vsync swapchain can switch to IMMEDIATE or FIFO_RELAXED per present. 112 // instance, so a vsync swapchain can switch to IMMEDIATE or FIFO_RELAXED per present.
111 bool swapchain_maintenance1 = false; 113 bool swapchain_maintenance1 = false;
@@ -118,6 +120,7 @@ public:
118 bool conservative_rasterization = false; // VK_EXT_conservative_rasterization enabled where available 120 bool conservative_rasterization = false; // VK_EXT_conservative_rasterization enabled where available
119 bool request_mesh_shader = false; // set before create(): enable VK_EXT_mesh_shader (meshShader) where available 121 bool request_mesh_shader = false; // set before create(): enable VK_EXT_mesh_shader (meshShader) where available
120 bool mesh_shader = false; // VK_EXT_mesh_shader and meshShader are enabled 122 bool mesh_shader = false; // VK_EXT_mesh_shader and meshShader are enabled
123 bool mesh_shader_queries = false; // the meshShaderQueries feature is enabled on the device
121 bool debug_utils = false; // VK_EXT_debug_utils is enabled on the instance 124 bool debug_utils = false; // VK_EXT_debug_utils is enabled on the instance
122 // The subgroup sizes of the device, with subgroupSizeControl and computeFullSubgroups enabled where it has them. 125 // The subgroup sizes of the device, with subgroupSizeControl and computeFullSubgroups enabled where it has them.
123 leonida::SubgroupSizeCaps subgroup; 126 leonida::SubgroupSizeCaps subgroup;
@@ -523,10 +526,13 @@ public:
523 VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &mesh_features}; 526 VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &mesh_features};
524 instance_fn<PFN_vkGetPhysicalDeviceFeatures2>("vkGetPhysicalDeviceFeatures2")(physical, &query); 527 instance_fn<PFN_vkGetPhysicalDeviceFeatures2>("vkGetPhysicalDeviceFeatures2")(physical, &query);
525 mesh_shader = mesh_features.meshShader == VK_TRUE; 528 mesh_shader = mesh_features.meshShader == VK_TRUE;
529 mesh_shader_queries = mesh_features.meshShaderQueries == VK_TRUE;
526 } 530 }
527 if (mesh_shader) { 531 if (mesh_shader) {
528 mesh_features = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT, *v13_.next()}; 532 mesh_features = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT, *v13_.next()};
529 mesh_features.meshShader = VK_TRUE; 533 mesh_features.meshShader = VK_TRUE;
534 // The mesh-primitives query, which counts the primitives a mesh shader emits (D3D-MESH-CLIPPING-COUNTER).
535 mesh_features.meshShaderQueries = mesh_shader_queries ? VK_TRUE : VK_FALSE;
530 *v13_.next() = &mesh_features; 536 *v13_.next() = &mesh_features;
531 } 537 }
532 enable.occlusionQueryPrecise = features.features.occlusionQueryPrecise; // query heaps, where available 538 enable.occlusionQueryPrecise = features.features.occlusionQueryPrecise; // query heaps, where available
@@ -567,6 +573,11 @@ public:
567 enabled = enable; 573 enabled = enable;
568 std::vector<const char*> device_extensions; 574 std::vector<const char*> device_extensions;
569 v13_.add_extensions(device_extensions); 575 v13_.add_extensions(device_extensions);
576 depth_range_unrestricted = request_depth_range_unrestricted &&
577 std::any_of(extensions.begin(), extensions.end(), [](const auto& e) {
578 return std::strcmp(e.extensionName, VK_EXT_DEPTH_RANGE_UNRESTRICTED_EXTENSION_NAME) == 0;
579 });
580 if (depth_range_unrestricted) device_extensions.push_back(VK_EXT_DEPTH_RANGE_UNRESTRICTED_EXTENSION_NAME);
570 conservative_rasterization = std::any_of(extensions.begin(), extensions.end(), [](const auto& e) { 581 conservative_rasterization = std::any_of(extensions.begin(), extensions.end(), [](const auto& e) {
571 return std::strcmp(e.extensionName, VK_EXT_CONSERVATIVE_RASTERIZATION_EXTENSION_NAME) == 0; 582 return std::strcmp(e.extensionName, VK_EXT_CONSERVATIVE_RASTERIZATION_EXTENSION_NAME) == 0;
572 }); 583 });
diff --git a/runtime/test/vulkan_scratch_test.cpp b/runtime/test/vulkan_scratch_test.cpp
index 8ca6a819a..f63610615 100644
--- a/runtime/test/vulkan_scratch_test.cpp
+++ b/runtime/test/vulkan_scratch_test.cpp
@@ -8,6 +8,7 @@
8#include <cstdint> 8#include <cstdint>
9#include <cstdio> 9#include <cstdio>
10#include <cstring> 10#include <cstring>
11#include <limits>
11#include <unordered_map> 12#include <unordered_map>
12#include <unordered_set> 13#include <unordered_set>
13 14
@@ -289,6 +290,26 @@ int main() {
289 EXPECT(vk.live_buffers.empty() && vk.live_memory.empty()); 290 EXPECT(vk.live_buffers.empty() && vk.live_memory.empty());
290 } 291 }
291 292
293 // A chunk whose used byte count is within 255 bytes of UINT64_MAX must not wrap alignment back to offset 0.
294 {
295 FakeVulkan vk;
296 g_vk = &vk;
297 {
298 ScratchBuffers scratch(fake_get_device_proc, k_device, fake_allocate);
299 VkBuffer buf1 = VK_NULL_HANDLE, buf2 = VK_NULL_HANDLE;
300 VkDeviceSize off1 = 1, off2 = 1;
301 const std::uint64_t near_max = std::numeric_limits<std::uint64_t>::max() - 100u;
302 EXPECT(scratch.get(near_max, buf1, off1));
303 EXPECT(buf1 != VK_NULL_HANDLE && off1 == 0 && vk.create_buffer_calls == 1);
304
305 EXPECT(scratch.get(16, buf2, off2));
306 EXPECT(buf2 != VK_NULL_HANDLE && buf2 != buf1 && off2 == 0);
307 EXPECT(vk.create_buffer_calls == 2 && vk.allocate_calls == 2);
308 EXPECT(vk.live_buffers.size() == 2 && vk.live_memory.size() == 2);
309 }
310 EXPECT(vk.live_buffers.empty() && vk.live_memory.empty());
311 }
312
292 std::printf("vulkan_scratch: all checks passed\n"); 313 std::printf("vulkan_scratch: all checks passed\n");
293 return 0; 314 return 0;
294} 315}
diff --git a/runtime/test/ws2_offline_test.cpp b/runtime/test/ws2_offline_test.cpp
new file mode 100644
index 000000000..32cdda48c
--- /dev/null
+++ b/runtime/test/ws2_offline_test.cpp
@@ -0,0 +1,547 @@
1// Checks the offline Winsock2 (ws2_32.dll) shim (runtime/shims/ws2_offline.cpp).
2//
3// Resolves every shimmed symbol through rt::shims::find under ws2_32.dll (by name and by standard Windows ordinal),
4// checks that wsock32.dll resolves its shared entries to the same wrappers, and verifies that external addresses
5// (RFC 5737 192.0.2.1 / RFC 3849 2001:db8::1), .invalid hostnames, octal-looking 0127.0.0.1 and name-service queries
6// are refused in-process while loopback (127.0.0.1 / ::1 / localhost) still works. Sends on unbound UDP sockets bind
7// them to loopback, and multicast joins (setsockopt on both DLLs, WSAJoinLeaf) are refused. Nothing touches the network.
8#ifndef _WINSOCK_DEPRECATED_NO_WARNINGS
9#define _WINSOCK_DEPRECATED_NO_WARNINGS
10#endif
11#ifndef WIN32_LEAN_AND_MEAN
12#define WIN32_LEAN_AND_MEAN
13#endif
14#ifndef NOMINMAX
15#define NOMINMAX
16#endif
17
18#include <winsock2.h>
19#include <ws2tcpip.h>
20#include <mswsock.h>
21#include <windows.h>
22
23#include <cstdint>
24#include <cstdio>
25#include <cstring>
26
27#include "shims.h"
28
29#ifndef SIO_GET_MULTIPLE_EXTENSION_FUNCTION_POINTER
30#define SIO_GET_MULTIPLE_EXTENSION_FUNCTION_POINTER 0xC8000024u
31#endif
32
33namespace {
34
35int g_checks = 0;
36int g_failures = 0;
37
38void check(bool condition, const char* what) {
39 ++g_checks;
40 std::printf("%s %s\n", condition ? "PASS" : "FAIL", what);
41 if (!condition) ++g_failures;
42}
43
44template <typename Fn>
45Fn resolve(const char* sym) {
46 return reinterpret_cast<Fn>(rt::shims::find("ws2_32.dll", sym));
47}
48
49sockaddr_in make_v4(uint8_t a, uint8_t b, uint8_t c, uint8_t d, uint16_t port) {
50 sockaddr_in sa{};
51 sa.sin_family = AF_INET;
52 sa.sin_port = htons(port);
53 auto* bytes = reinterpret_cast<uint8_t*>(&sa.sin_addr);
54 bytes[0] = a;
55 bytes[1] = b;
56 bytes[2] = c;
57 bytes[3] = d;
58 return sa;
59}
60
61sockaddr_in6 make_v6_doc(uint16_t port) {
62 // 2001:db8::1 (RFC 3849 documentation prefix, non-loopback)
63 sockaddr_in6 sa{};
64 sa.sin6_family = AF_INET6;
65 sa.sin6_port = htons(port);
66 auto* bytes = reinterpret_cast<uint8_t*>(&sa.sin6_addr);
67 bytes[0] = 0x20;
68 bytes[1] = 0x01;
69 bytes[2] = 0x0d;
70 bytes[3] = 0xb8;
71 bytes[15] = 0x01;
72 return sa;
73}
74
75} // namespace
76
77int main() {
78 WSADATA wsa{};
79 if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) {
80 std::fprintf(stderr, "WSAStartup failed (%d)\n", WSAGetLastError());
81 return 1;
82 }
83
84 using BindFn = int(WSAAPI*)(SOCKET, const sockaddr*, int);
85 using ConnectFn = int(WSAAPI*)(SOCKET, const sockaddr*, int);
86 using SendToFn = int(WSAAPI*)(SOCKET, const char*, int, int, const sockaddr*, int);
87 using WsaConnectFn = int(WSAAPI*)(SOCKET, const sockaddr*, int, LPWSABUF, LPWSABUF, LPQOS, LPQOS);
88 using WsaConnectByNameAFn = BOOL(WSAAPI*)(SOCKET, LPCSTR, LPCSTR, LPDWORD, LPSOCKADDR, LPDWORD, LPSOCKADDR,
89 const timeval*, LPWSAOVERLAPPED);
90 using WsaConnectByNameWFn = BOOL(WSAAPI*)(SOCKET, LPWSTR, LPWSTR, LPDWORD, LPSOCKADDR, LPDWORD, LPSOCKADDR,
91 const timeval*, LPWSAOVERLAPPED);
92 using WsaConnectByListFn = BOOL(WSAAPI*)(SOCKET, PSOCKET_ADDRESS_LIST, LPDWORD, LPSOCKADDR, LPDWORD, LPSOCKADDR,
93 const timeval*, LPWSAOVERLAPPED);
94 using WsaSendToFn = int(WSAAPI*)(SOCKET, LPWSABUF, DWORD, LPDWORD, DWORD, const sockaddr*, int, LPWSAOVERLAPPED,
95 LPWSAOVERLAPPED_COMPLETION_ROUTINE);
96 using WsaSendMsgFn = int(WSAAPI*)(SOCKET, LPWSAMSG, DWORD, LPDWORD, LPWSAOVERLAPPED,
97 LPWSAOVERLAPPED_COMPLETION_ROUTINE);
98 using WsaIoctlFn = int(WSAAPI*)(SOCKET, DWORD, LPVOID, DWORD, LPVOID, DWORD, LPDWORD, LPWSAOVERLAPPED,
99 LPWSAOVERLAPPED_COMPLETION_ROUTINE);
100 using GetAddrInfoAFn = INT(WSAAPI*)(PCSTR, PCSTR, const ADDRINFOA*, PADDRINFOA*);
101 using GetAddrInfoWFn = INT(WSAAPI*)(PCWSTR, PCWSTR, const ADDRINFOW*, PADDRINFOW*);
102 using GetNameInfoAFn = INT(WSAAPI*)(const sockaddr*, socklen_t, PCHAR, DWORD, PCHAR, DWORD, INT);
103 using GetHostByNameFn = hostent*(WSAAPI*)(const char*);
104 using GetHostByAddrFn = hostent*(WSAAPI*)(const char*, int, int);
105 using LookupBeginWFn = int(WSAAPI*)(LPWSAQUERYSETW, DWORD, LPHANDLE);
106
107 const auto sh_bind = resolve<BindFn>("bind");
108 const auto sh_bind_ord = resolve<BindFn>("#2");
109 const auto sh_connect = resolve<ConnectFn>("connect");
110 const auto sh_connect_ord = resolve<ConnectFn>("#4");
111 const auto sh_sendto = resolve<SendToFn>("sendto");
112 const auto sh_sendto_ord = resolve<SendToFn>("#20");
113 const auto sh_wsa_connect = resolve<WsaConnectFn>("WSAConnect");
114 const auto sh_connect_name_a = resolve<WsaConnectByNameAFn>("WSAConnectByNameA");
115 const auto sh_connect_name_w = resolve<WsaConnectByNameWFn>("WSAConnectByNameW");
116 const auto sh_connect_list = resolve<WsaConnectByListFn>("WSAConnectByList");
117 const auto sh_wsa_sendto = resolve<WsaSendToFn>("WSASendTo");
118 const auto sh_wsa_sendmsg = resolve<WsaSendMsgFn>("WSASendMsg");
119 const auto sh_wsa_ioctl = resolve<WsaIoctlFn>("WSAIoctl");
120 const auto sh_getaddrinfo = resolve<GetAddrInfoAFn>("getaddrinfo");
121 const auto sh_getaddrinfo_w = resolve<GetAddrInfoWFn>("GetAddrInfoW");
122 const auto sh_getnameinfo = resolve<GetNameInfoAFn>("getnameinfo");
123 const auto sh_gethostbyname = resolve<GetHostByNameFn>("gethostbyname");
124 const auto sh_gethostbyname_ord = resolve<GetHostByNameFn>("#52");
125 const auto sh_gethostbyaddr = resolve<GetHostByAddrFn>("gethostbyaddr");
126 const auto sh_gethostbyaddr_ord = resolve<GetHostByAddrFn>("#51");
127
128 check(sh_bind && sh_bind == sh_bind_ord, "bind and #2 resolve to the same shim");
129 check(sh_connect && sh_connect == sh_connect_ord, "connect and #4 resolve to the same shim");
130 check(sh_sendto && sh_sendto == sh_sendto_ord, "sendto and #20 resolve to the same shim");
131 check(sh_gethostbyname && sh_gethostbyname == sh_gethostbyname_ord, "gethostbyname and #52 resolve to the same shim");
132 check(sh_gethostbyaddr && sh_gethostbyaddr == sh_gethostbyaddr_ord, "gethostbyaddr and #51 resolve to the same shim");
133 check(sh_wsa_connect && sh_connect_name_a && sh_connect_name_w && sh_connect_list && sh_wsa_sendto &&
134 sh_wsa_sendmsg && sh_wsa_ioctl && sh_getaddrinfo && sh_getaddrinfo_w && sh_getnameinfo &&
135 rt::shims::find("ws2_32.dll", "#102") && rt::shims::find("ws2_32.dll", "#103"),
136 "all offline Winsock2 shims resolve through the registry");
137 check(!rt::shims::owns_dll("ws2_32.dll"),
138 "ws2_32.dll stays partially overridden (host socket bookkeeping remains available)");
139 check(!rt::shims::owns_dll("wsock32.dll"),
140 "wsock32.dll stays partially overridden (host socket bookkeeping remains available)");
141
142 // wsock32.dll resolves its shared entries to the same wrappers as ws2_32.dll, by name and by ordinal.
143 check(rt::shims::find("wsock32.dll", "connect") == sh_connect && rt::shims::find("wsock32.dll", "#4") == sh_connect,
144 "wsock32.dll connect and #4 resolve to the ws2_32.dll connect shim");
145 check(rt::shims::find("wsock32.dll", "bind") == sh_bind && rt::shims::find("wsock32.dll", "#2") == sh_bind,
146 "wsock32.dll bind and #2 resolve to the ws2_32.dll bind shim");
147 check(rt::shims::find("wsock32.dll", "gethostbyname") == sh_gethostbyname &&
148 rt::shims::find("wsock32.dll", "#52") == sh_gethostbyname,
149 "wsock32.dll gethostbyname and #52 resolve to the ws2_32.dll shim");
150
151 // 1. External connect / WSAConnect / WSAConnectByName / WSAConnectByList refused with WSAENETUNREACH.
152 {
153 const SOCKET tcp = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
154 check(tcp != INVALID_SOCKET, "create IPv4 TCP socket");
155 const sockaddr_in ext4 = make_v4(192, 0, 2, 1, 443);
156 const sockaddr_in6 ext6 = make_v6_doc(443);
157
158 WSASetLastError(0);
159 check(sh_connect(tcp, reinterpret_cast<const sockaddr*>(&ext4), sizeof(ext4)) == SOCKET_ERROR &&
160 WSAGetLastError() == WSAENETUNREACH,
161 "connect refuses external IPv4 with WSAENETUNREACH");
162
163 WSASetLastError(0);
164 check(sh_connect(tcp, reinterpret_cast<const sockaddr*>(&ext6), sizeof(ext6)) == SOCKET_ERROR &&
165 WSAGetLastError() == WSAENETUNREACH,
166 "connect refuses external IPv6 with WSAENETUNREACH");
167
168 WSASetLastError(0);
169 check(sh_wsa_connect(tcp, reinterpret_cast<const sockaddr*>(&ext4), sizeof(ext4), nullptr, nullptr, nullptr,
170 nullptr) == SOCKET_ERROR &&
171 WSAGetLastError() == WSAENETUNREACH,
172 "WSAConnect refuses external IPv4 with WSAENETUNREACH");
173
174 WSASetLastError(0);
175 check(sh_connect_name_a(tcp, "example.invalid", "443", nullptr, nullptr, nullptr, nullptr, nullptr, nullptr) ==
176 FALSE &&
177 WSAGetLastError() == WSAENETUNREACH,
178 "WSAConnectByNameA refuses external hostname with WSAENETUNREACH");
179
180 wchar_t bad_host[] = L"example.invalid";
181 wchar_t port_w[] = L"443";
182 WSASetLastError(0);
183 check(sh_connect_name_w(tcp, bad_host, port_w, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr) == FALSE &&
184 WSAGetLastError() == WSAENETUNREACH,
185 "WSAConnectByNameW refuses external hostname with WSAENETUNREACH");
186
187 SOCKET_ADDRESS_LIST list{};
188 sockaddr_in ext4_mut = ext4;
189 list.iAddressCount = 1;
190 list.Address[0].lpSockaddr = reinterpret_cast<LPSOCKADDR>(&ext4_mut);
191 list.Address[0].iSockaddrLength = sizeof(ext4_mut);
192 WSASetLastError(0);
193 check(sh_connect_list(tcp, &list, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr) == FALSE &&
194 WSAGetLastError() == WSAENETUNREACH,
195 "WSAConnectByList refuses non-loopback address list with WSAENETUNREACH");
196
197 // ConnectEx via WSAIoctl is wrapped and refuses external targets.
198 GUID connect_ex_guid = WSAID_CONNECTEX;
199 LPFN_CONNECTEX connect_ex = nullptr;
200 DWORD returned = 0;
201 const int ioctl_rc = sh_wsa_ioctl(tcp, SIO_GET_EXTENSION_FUNCTION_POINTER, &connect_ex_guid,
202 sizeof(connect_ex_guid), &connect_ex, sizeof(connect_ex), &returned, nullptr,
203 nullptr);
204 check(ioctl_rc == 0 && connect_ex != nullptr && returned == sizeof(connect_ex),
205 "WSAIoctl returns wrapped ConnectEx");
206 if (connect_ex) {
207 OVERLAPPED ov{};
208 WSASetLastError(0);
209 check(connect_ex(tcp, reinterpret_cast<const sockaddr*>(&ext4), sizeof(ext4), nullptr, 0, nullptr, &ov) ==
210 FALSE &&
211 WSAGetLastError() == WSAENETUNREACH,
212 "wrapped ConnectEx refuses external IPv4 with WSAENETUNREACH");
213 }
214
215 // SIO_GET_MULTIPLE_EXTENSION_FUNCTION_POINTER is refused.
216 DWORD dummy_ret = 0;
217 WSASetLastError(0);
218 check(sh_wsa_ioctl(tcp, SIO_GET_MULTIPLE_EXTENSION_FUNCTION_POINTER, nullptr, 0, nullptr, 0, &dummy_ret,
219 nullptr, nullptr) == SOCKET_ERROR &&
220 WSAGetLastError() == WSAEINVAL,
221 "WSAIoctl refuses SIO_GET_MULTIPLE_EXTENSION_FUNCTION_POINTER");
222
223 closesocket(tcp);
224 }
225
226 // 2. External datagram sends (sendto, WSASendTo, WSASendMsg direct & via WSAIoctl) refused with WSAENETUNREACH.
227 {
228 const SOCKET udp = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
229 check(udp != INVALID_SOCKET, "create IPv4 UDP socket");
230 const sockaddr_in ext4 = make_v4(192, 0, 2, 2, 53);
231 char payload[] = "ping";
232
233 WSASetLastError(0);
234 check(sh_sendto(udp, payload, 4, 0, reinterpret_cast<const sockaddr*>(&ext4), sizeof(ext4)) == SOCKET_ERROR &&
235 WSAGetLastError() == WSAENETUNREACH,
236 "sendto refuses external IPv4 with WSAENETUNREACH");
237
238 WSABUF wbuf{4, payload};
239 DWORD sent = 0;
240 WSASetLastError(0);
241 check(sh_wsa_sendto(udp, &wbuf, 1, &sent, 0, reinterpret_cast<const sockaddr*>(&ext4), sizeof(ext4), nullptr,
242 nullptr) == SOCKET_ERROR &&
243 WSAGetLastError() == WSAENETUNREACH,
244 "WSASendTo refuses external IPv4 with WSAENETUNREACH");
245
246 sockaddr_in ext4_mut = ext4;
247 WSAMSG msg{};
248 msg.name = reinterpret_cast<LPSOCKADDR>(&ext4_mut);
249 msg.namelen = sizeof(ext4_mut);
250 msg.lpBuffers = &wbuf;
251 msg.dwBufferCount = 1;
252 WSASetLastError(0);
253 check(sh_wsa_sendmsg(udp, &msg, 0, &sent, nullptr, nullptr) == SOCKET_ERROR &&
254 WSAGetLastError() == WSAENETUNREACH,
255 "WSASendMsg refuses external IPv4 with WSAENETUNREACH");
256
257 GUID sendmsg_guid = WSAID_WSASENDMSG;
258 LPFN_WSASENDMSG sendmsg_ext = nullptr;
259 DWORD returned = 0;
260 const int ioctl_rc = sh_wsa_ioctl(udp, SIO_GET_EXTENSION_FUNCTION_POINTER, &sendmsg_guid, sizeof(sendmsg_guid),
261 &sendmsg_ext, sizeof(sendmsg_ext), &returned, nullptr, nullptr);
262 check(ioctl_rc == 0 && sendmsg_ext != nullptr, "WSAIoctl returns wrapped WSASendMsg");
263 if (sendmsg_ext) {
264 WSASetLastError(0);
265 check(sendmsg_ext(udp, &msg, 0, &sent, nullptr, nullptr) == SOCKET_ERROR &&
266 WSAGetLastError() == WSAENETUNREACH,
267 "wrapped WSASendMsg extension refuses external IPv4 with WSAENETUNREACH");
268 }
269
270 closesocket(udp);
271 }
272
273 // 3. bind narrows wildcard 0.0.0.0 to 127.0.0.1 and refuses non-loopback addresses.
274 {
275 const SOCKET s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
276 const sockaddr_in ext4 = make_v4(192, 0, 2, 1, 0);
277 WSASetLastError(0);
278 check(sh_bind(s, reinterpret_cast<const sockaddr*>(&ext4), sizeof(ext4)) == SOCKET_ERROR &&
279 WSAGetLastError() == WSAEADDRNOTAVAIL,
280 "bind refuses non-loopback IPv4 with WSAEADDRNOTAVAIL");
281
282 const sockaddr_in any4 = make_v4(0, 0, 0, 0, 0);
283 check(sh_bind(s, reinterpret_cast<const sockaddr*>(&any4), sizeof(any4)) == 0,
284 "bind accepts wildcard 0.0.0.0 and rewrites to loopback");
285 sockaddr_in bound{};
286 int bound_len = sizeof(bound);
287 check(getsockname(s, reinterpret_cast<sockaddr*>(&bound), &bound_len) == 0 &&
288 bound.sin_addr.s_addr == htonl(INADDR_LOOPBACK),
289 "wildcard bind narrowed socket address to 127.0.0.1");
290 closesocket(s);
291 }
292
293 // 4. DNS lookups refuse external hostnames and permit localhost / 127.0.0.1.
294 {
295 ADDRINFOA* res = nullptr;
296 check(sh_getaddrinfo("example.invalid", "443", nullptr, &res) == WSAHOST_NOT_FOUND && res == nullptr,
297 "getaddrinfo refuses external hostname with WSAHOST_NOT_FOUND");
298 // Windows reads a leading-zero octet as octal, so 0127.0.0.1 is 87.0.0.1 there; it is refused, not loopback.
299 res = nullptr;
300 check(sh_getaddrinfo("0127.0.0.1", "80", nullptr, &res) == WSAHOST_NOT_FOUND && res == nullptr,
301 "getaddrinfo refuses octal-looking 0127.0.0.1 with WSAHOST_NOT_FOUND");
302 check(sh_getaddrinfo("127.0.0.1", "80", nullptr, &res) == 0 && res != nullptr,
303 "getaddrinfo permits 127.0.0.1");
304 if (res) freeaddrinfo(res);
305 res = nullptr;
306 check(sh_getaddrinfo("localhost", "80", nullptr, &res) == 0 && res != nullptr,
307 "getaddrinfo permits localhost");
308 if (res) freeaddrinfo(res);
309
310 ADDRINFOW* res_w = nullptr;
311 check(sh_getaddrinfo_w(L"example.invalid", L"443", nullptr, &res_w) == WSAHOST_NOT_FOUND && res_w == nullptr,
312 "GetAddrInfoW refuses external hostname with WSAHOST_NOT_FOUND");
313 check(sh_getaddrinfo_w(L"localhost", L"80", nullptr, &res_w) == 0 && res_w != nullptr,
314 "GetAddrInfoW permits localhost");
315 if (res_w) FreeAddrInfoW(res_w);
316
317 WSASetLastError(0);
318 check(sh_gethostbyname("example.invalid") == nullptr && WSAGetLastError() == WSAHOST_NOT_FOUND,
319 "gethostbyname refuses external hostname with WSAHOST_NOT_FOUND");
320
321 const uint8_t ext_bytes[4] = {192, 0, 2, 1};
322 WSASetLastError(0);
323 check(sh_gethostbyaddr(reinterpret_cast<const char*>(ext_bytes), 4, AF_INET) == nullptr &&
324 WSAGetLastError() == WSAHOST_NOT_FOUND,
325 "gethostbyaddr refuses external IPv4 with WSAHOST_NOT_FOUND");
326
327 const sockaddr_in ext4 = make_v4(192, 0, 2, 1, 80);
328 char host_buf[64] = {};
329 check(sh_getnameinfo(reinterpret_cast<const sockaddr*>(&ext4), sizeof(ext4), host_buf, sizeof(host_buf),
330 nullptr, 0, NI_NAMEREQD) == WSAHOST_NOT_FOUND,
331 "getnameinfo with NI_NAMEREQD refuses external IPv4");
332 check(sh_getnameinfo(reinterpret_cast<const sockaddr*>(&ext4), sizeof(ext4), host_buf, sizeof(host_buf),
333 nullptr, 0, 0) == 0 &&
334 std::strcmp(host_buf, "192.0.2.1") == 0,
335 "getnameinfo without NI_NAMEREQD returns numeric IP without reverse DNS");
336 }
337
338 // 5. Real loopback UDP round-trip through the shimmed bind and sendto succeeds.
339 {
340 const SOCKET recv_sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
341 const SOCKET send_sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
342 const sockaddr_in loop = make_v4(127, 0, 0, 1, 0);
343 check(sh_bind(recv_sock, reinterpret_cast<const sockaddr*>(&loop), sizeof(loop)) == 0,
344 "loopback UDP receiver bind succeeds");
345 sockaddr_in dst{};
346 int dst_len = sizeof(dst);
347 check(getsockname(recv_sock, reinterpret_cast<sockaddr*>(&dst), &dst_len) == 0,
348 "getsockname returns loopback UDP port");
349 const char msg[] = "ok";
350 check(sh_sendto(send_sock, msg, 2, 0, reinterpret_cast<const sockaddr*>(&dst), sizeof(dst)) == 2,
351 "loopback sendto succeeds");
352 char got[8] = {};
353 const int n = recv(recv_sock, got, sizeof(got), 0);
354 check(n == 2 && got[0] == 'o' && got[1] == 'k', "loopback UDP payload received");
355 closesocket(send_sock);
356 closesocket(recv_sock);
357 }
358
359 // 6. Name-service queries are refused with WSASERVICE_NOT_FOUND.
360 {
361 const auto sh_lookup_w = resolve<LookupBeginWFn>("WSALookupServiceBeginW");
362 wchar_t service[] = L"example.invalid";
363 WSAQUERYSETW restrictions{};
364 restrictions.dwSize = sizeof(restrictions);
365 restrictions.lpszServiceInstanceName = service;
366 HANDLE lookup = nullptr;
367 WSASetLastError(0);
368 check(sh_lookup_w && sh_lookup_w(&restrictions, 0, &lookup) == SOCKET_ERROR &&
369 WSAGetLastError() == WSASERVICE_NOT_FOUND && lookup == nullptr,
370 "WSALookupServiceBeginW refuses with WSASERVICE_NOT_FOUND");
371 }
372
373 // 7. ConnectEx from WSAIoctl connects to a loopback listener through the host's per-socket pointer.
374 {
375 const SOCKET listener = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
376 sockaddr_in any = make_v4(127, 0, 0, 1, 0);
377 sockaddr_in listen_addr{};
378 int listen_len = sizeof(listen_addr);
379 check(sh_bind(listener, reinterpret_cast<const sockaddr*>(&any), sizeof(any)) == 0 &&
380 listen(listener, 1) == 0 && getsockname(listener, reinterpret_cast<sockaddr*>(&listen_addr),
381 &listen_len) == 0,
382 "loopback TCP listener is up");
383
384 const SOCKET client = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
385 check(sh_bind(client, reinterpret_cast<const sockaddr*>(&any), sizeof(any)) == 0,
386 "ConnectEx client socket is bound to loopback (ConnectEx requires a bound socket)");
387 GUID connect_ex_guid = WSAID_CONNECTEX;
388 LPFN_CONNECTEX connect_ex = nullptr;
389 DWORD returned = 0;
390 check(sh_wsa_ioctl(client, SIO_GET_EXTENSION_FUNCTION_POINTER, &connect_ex_guid, sizeof(connect_ex_guid),
391 &connect_ex, sizeof(connect_ex), &returned, nullptr, nullptr) == 0 &&
392 connect_ex != nullptr,
393 "WSAIoctl returns a ConnectEx pointer for a bound TCP socket");
394
395 if (connect_ex) {
396 OVERLAPPED ov{};
397 ov.hEvent = WSACreateEvent();
398 check(connect_ex(client, reinterpret_cast<const sockaddr*>(&listen_addr), sizeof(listen_addr), nullptr, 0,
399 nullptr, &ov) == TRUE ||
400 (WSAGetLastError() == WSA_IO_PENDING &&
401 WSAWaitForMultipleEvents(1, &ov.hEvent, TRUE, 5000, FALSE) == WSA_WAIT_EVENT_0),
402 "wrapped ConnectEx connects to the loopback listener");
403 DWORD transferred = 0, flags = 0;
404 check(WSAGetOverlappedResult(client, &ov, &transferred, FALSE, &flags) == TRUE,
405 "ConnectEx completes with no error");
406 WSACloseEvent(ov.hEvent);
407 }
408
409 const SOCKET ext = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
410 sockaddr_in ext_any = make_v4(127, 0, 0, 1, 0);
411 check(sh_bind(ext, reinterpret_cast<const sockaddr*>(&ext_any), sizeof(ext_any)) == 0,
412 "second ConnectEx socket is bound to loopback");
413 if (connect_ex) {
414 const sockaddr_in ext4 = make_v4(192, 0, 2, 1, 443);
415 OVERLAPPED ov{};
416 WSASetLastError(0);
417 check(connect_ex(ext, reinterpret_cast<const sockaddr*>(&ext4), sizeof(ext4), nullptr, 0, nullptr, &ov) ==
418 FALSE &&
419 WSAGetLastError() == WSAENETUNREACH,
420 "wrapped ConnectEx refuses non-loopback 192.0.2.1 with WSAENETUNREACH");
421 }
422 closesocket(ext);
423 closesocket(client);
424 closesocket(listener);
425 }
426
427 // Implicit binds, multicast joins and WSAJoinLeaf. A send on an unbound datagram socket binds it to the wildcard
428 // address (Microsoft's sendto remarks); the shim binds it to loopback first. Joins are refused before the host.
429 {
430 using SetSockOptFn = int(WSAAPI*)(SOCKET, int, int, const char*, int);
431 using JoinLeafFn = SOCKET(WSAAPI*)(SOCKET, const sockaddr*, int, LPWSABUF, LPWSABUF, LPQOS, LPQOS, DWORD);
432 const auto sh_setsockopt = resolve<SetSockOptFn>("setsockopt");
433 const auto sh_join_leaf = resolve<JoinLeafFn>("WSAJoinLeaf");
434 const auto ws1_setsockopt = reinterpret_cast<SetSockOptFn>(rt::shims::find("wsock32.dll", "setsockopt"));
435 check(sh_setsockopt && sh_setsockopt == resolve<SetSockOptFn>("#21"),
436 "setsockopt and #21 resolve to the same shim");
437 check(sh_join_leaf != nullptr, "WSAJoinLeaf resolves to a shim");
438 check(ws1_setsockopt && ws1_setsockopt == reinterpret_cast<SetSockOptFn>(rt::shims::find("wsock32.dll", "#21")) &&
439 ws1_setsockopt != sh_setsockopt,
440 "wsock32.dll setsockopt and #21 resolve to their own Winsock 1.1 shim");
441
442 const SOCKET receiver = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
443 sockaddr_in to = make_v4(127, 0, 0, 1, 0);
444 int to_len = sizeof(to);
445 check(bind(receiver, reinterpret_cast<const sockaddr*>(&to), sizeof(to)) == 0 &&
446 getsockname(receiver, reinterpret_cast<sockaddr*>(&to), &to_len) == 0,
447 "bind a loopback UDP receiver");
448 const auto local_v4_first_byte = [](SOCKET s) {
449 sockaddr_in local{};
450 int len = sizeof(local);
451 if (getsockname(s, reinterpret_cast<sockaddr*>(&local), &len) != 0 || local.sin_port == 0) return -1;
452 return static_cast<int>(reinterpret_cast<const uint8_t*>(&local.sin_addr)[0]);
453 };
454 char payload[] = "ping";
455
456 const SOCKET control = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
457 check(sendto(control, payload, 4, 0, reinterpret_cast<const sockaddr*>(&to), sizeof(to)) == 4 &&
458 local_v4_first_byte(control) == 0,
459 "control: the host sendto binds an unbound UDP socket to 0.0.0.0");
460 const SOCKET unbound = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
461 check(sh_sendto(unbound, payload, 4, 0, reinterpret_cast<const sockaddr*>(&to), sizeof(to)) == 4 &&
462 local_v4_first_byte(unbound) == 127,
463 "sendto binds an unbound UDP socket to 127.0.0.1 before sending");
464 const SOCKET unbound_wsa = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
465 WSABUF wbuf{4, payload};
466 DWORD sent = 0;
467 check(sh_wsa_sendto(unbound_wsa, &wbuf, 1, &sent, 0, reinterpret_cast<const sockaddr*>(&to), sizeof(to), nullptr,
468 nullptr) == 0 &&
469 sent == 4 && local_v4_first_byte(unbound_wsa) == 127,
470 "WSASendTo binds an unbound UDP socket to 127.0.0.1 before sending");
471 check(sh_sendto(unbound, payload, 4, 0, reinterpret_cast<const sockaddr*>(&to), sizeof(to)) == 4 &&
472 local_v4_first_byte(unbound) == 127,
473 "a second sendto on the now-bound socket keeps its loopback binding");
474
475 const SOCKET receiver6 = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP);
476 if (receiver6 != INVALID_SOCKET) {
477 sockaddr_in6 to6{};
478 to6.sin6_family = AF_INET6;
479 reinterpret_cast<uint8_t*>(&to6.sin6_addr)[15] = 1; // ::1
480 int to6_len = sizeof(to6);
481 const bool bound6 = bind(receiver6, reinterpret_cast<const sockaddr*>(&to6), sizeof(to6)) == 0 &&
482 getsockname(receiver6, reinterpret_cast<sockaddr*>(&to6), &to6_len) == 0;
483 const SOCKET unbound6 = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP);
484 sockaddr_in6 local6{};
485 int local6_len = sizeof(local6);
486 check(bound6 && sh_sendto(unbound6, payload, 4, 0, reinterpret_cast<const sockaddr*>(&to6), sizeof(to6)) == 4 &&
487 getsockname(unbound6, reinterpret_cast<sockaddr*>(&local6), &local6_len) == 0 &&
488 reinterpret_cast<const uint8_t*>(&local6.sin6_addr)[15] == 1 &&
489 reinterpret_cast<const uint8_t*>(&local6.sin6_addr)[0] == 0,
490 "sendto binds an unbound IPv6 UDP socket to ::1 before sending");
491 closesocket(unbound6);
492 closesocket(receiver6);
493 }
494
495 // 239.255.0.1 (administratively scoped group); every join is refused before it reaches the host.
496 ip_mreq mreq{};
497 auto* group = reinterpret_cast<uint8_t*>(&mreq.imr_multiaddr);
498 group[0] = 239;
499 group[1] = 255;
500 group[3] = 1;
501 const auto refused = [](int rc) { return rc == SOCKET_ERROR && WSAGetLastError() == WSAEADDRNOTAVAIL; };
502 const char* mreq_bytes = reinterpret_cast<const char*>(&mreq);
503 WSASetLastError(0);
504 check(refused(sh_setsockopt(unbound, IPPROTO_IP, IP_ADD_MEMBERSHIP, mreq_bytes, sizeof(mreq))),
505 "setsockopt refuses IP_ADD_MEMBERSHIP with WSAEADDRNOTAVAIL");
506 WSASetLastError(0);
507 check(refused(sh_setsockopt(unbound, IPPROTO_IP, IP_ADD_SOURCE_MEMBERSHIP, mreq_bytes, sizeof(mreq))),
508 "setsockopt refuses IP_ADD_SOURCE_MEMBERSHIP");
509 WSASetLastError(0);
510 check(refused(sh_setsockopt(unbound, IPPROTO_IP, MCAST_JOIN_GROUP, mreq_bytes, sizeof(mreq))),
511 "setsockopt refuses MCAST_JOIN_GROUP");
512 WSASetLastError(0);
513 check(refused(sh_setsockopt(unbound, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, mreq_bytes, sizeof(mreq))),
514 "setsockopt refuses IPV6_ADD_MEMBERSHIP");
515 WSASetLastError(0);
516 check(refused(ws1_setsockopt(unbound, IPPROTO_IP, 5, mreq_bytes, sizeof(mreq))),
517 "wsock32 setsockopt refuses the Winsock 1.1 IP_ADD_MEMBERSHIP (5)");
518 WSASetLastError(0);
519 check(refused(ws1_setsockopt(unbound, IPPROTO_IP, IP_ADD_MEMBERSHIP, mreq_bytes, sizeof(mreq))),
520 "wsock32 setsockopt refuses the Winsock 2 IP_ADD_MEMBERSHIP (12) it would pass through");
521 int value = 3;
522 const char* value_bytes = reinterpret_cast<const char*>(&value);
523 check(sh_setsockopt(unbound, IPPROTO_IP, IP_MULTICAST_TTL, value_bytes, sizeof(value)) == 0,
524 "setsockopt passes other IPPROTO_IP options (IP_MULTICAST_TTL)");
525 check(ws1_setsockopt(unbound, IPPROTO_IP, 7, value_bytes, sizeof(value)) == 0,
526 "wsock32 setsockopt passes the Winsock 1.1 IP_TTL (7) to the host's remap");
527 value = 65536;
528 check(sh_setsockopt(unbound, SOL_SOCKET, SO_RCVBUF, value_bytes, sizeof(value)) == 0,
529 "setsockopt passes SOL_SOCKET options");
530
531 const sockaddr_in group_addr = make_v4(239, 255, 0, 1, 5000);
532 WSASetLastError(0);
533 check(sh_join_leaf(unbound, reinterpret_cast<const sockaddr*>(&group_addr), sizeof(group_addr), nullptr, nullptr,
534 nullptr, nullptr, JL_BOTH) == INVALID_SOCKET &&
535 WSAGetLastError() == WSAENETUNREACH,
536 "WSAJoinLeaf refuses a multicast group with WSAENETUNREACH");
537
538 closesocket(unbound_wsa);
539 closesocket(unbound);
540 closesocket(control);
541 closesocket(receiver);
542 }
543
544 WSACleanup();
545 std::printf("%d check(s), %d failure(s)\n", g_checks, g_failures);
546 return g_failures ? 1 : 0;
547}
diff --git a/runtime/test/xdxr_builder_validation_test.cpp b/runtime/test/xdxr_builder_validation_test.cpp
new file mode 100644
index 000000000..5ea6226ff
--- /dev/null
+++ b/runtime/test/xdxr_builder_validation_test.cpp
@@ -0,0 +1,183 @@
1// Unit tests for XdxrBuilder pre-validation in src/xdxr_build.h (no Vulkan instance, no GPU).
2// Mismatched geometry sums, null device addresses, uncomputed layouts, and 32-bit overflow counts must fail before
3// recording any command into the Vulkan command buffer.
4#include "../src/xdxr_build.h"
5
6#include <cstdint>
7#include <cstdio>
8#include <cstring>
9#include <type_traits>
10#include <vector>
11
12#define CHECK(condition) do { \
13 if (!(condition)) { \
14 std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); \
15 return 1; \
16 } \
17} while (0)
18
19namespace {
20
21template<typename Handle>
22Handle fake_handle(std::uintptr_t value) {
23 if constexpr (std::is_pointer_v<Handle>)
24 return reinterpret_cast<Handle>(value);
25 else
26 return static_cast<Handle>(value);
27}
28
29struct MockRecorder {
30 unsigned binds = 0;
31 unsigned pushes = 0;
32 unsigned dispatches = 0;
33 unsigned barriers = 0;
34 std::uint32_t last_group_count_x = 0;
35 std::uint32_t last_copy_count = 0;
36
37 void reset() { *this = MockRecorder{}; }
38 bool empty() const { return !binds && !pushes && !dispatches && !barriers; }
39};
40
41MockRecorder g_rec;
42
43VKAPI_ATTR VkResult VKAPI_CALL mock_create_shader_module(VkDevice, const VkShaderModuleCreateInfo*,
44 const VkAllocationCallbacks*, VkShaderModule* out) {
45 *out = fake_handle<VkShaderModule>(1);
46 return VK_SUCCESS;
47}
48
49VKAPI_ATTR void VKAPI_CALL mock_destroy_shader_module(VkDevice, VkShaderModule, const VkAllocationCallbacks*) {}
50
51VKAPI_ATTR VkResult VKAPI_CALL mock_create_pipeline_layout(VkDevice, const VkPipelineLayoutCreateInfo*,
52 const VkAllocationCallbacks*, VkPipelineLayout* out) {
53 *out = fake_handle<VkPipelineLayout>(2);
54 return VK_SUCCESS;
55}
56
57VKAPI_ATTR void VKAPI_CALL mock_destroy_pipeline_layout(VkDevice, VkPipelineLayout, const VkAllocationCallbacks*) {}
58
59VKAPI_ATTR VkResult VKAPI_CALL mock_create_compute_pipelines(VkDevice, VkPipelineCache, std::uint32_t count,
60 const VkComputePipelineCreateInfo*,
61 const VkAllocationCallbacks*, VkPipeline* out) {
62 for (std::uint32_t i = 0; i < count; ++i) out[i] = fake_handle<VkPipeline>(3 + i);
63 return VK_SUCCESS;
64}
65
66VKAPI_ATTR void VKAPI_CALL mock_destroy_pipeline(VkDevice, VkPipeline, const VkAllocationCallbacks*) {}
67
68VKAPI_ATTR void VKAPI_CALL mock_cmd_bind_pipeline(VkCommandBuffer, VkPipelineBindPoint, VkPipeline) { ++g_rec.binds; }
69
70VKAPI_ATTR void VKAPI_CALL mock_cmd_push_constants(VkCommandBuffer, VkPipelineLayout, VkShaderStageFlags,
71 std::uint32_t, std::uint32_t size, const void* values) {
72 ++g_rec.pushes;
73 if (size >= 80 && values) {
74 std::uint32_t mode = 0, count = 0;
75 std::memcpy(&mode, static_cast<const std::uint8_t*>(values) + 48, 4);
76 std::memcpy(&count, static_cast<const std::uint8_t*>(values) + 52, 4);
77 if (mode == 12) g_rec.last_copy_count = count;
78 }
79}
80
81VKAPI_ATTR void VKAPI_CALL mock_cmd_dispatch(VkCommandBuffer, std::uint32_t x, std::uint32_t, std::uint32_t) {
82 ++g_rec.dispatches;
83 g_rec.last_group_count_x = x;
84}
85
86VKAPI_ATTR void VKAPI_CALL mock_cmd_pipeline_barrier(VkCommandBuffer, VkPipelineStageFlags, VkPipelineStageFlags,
87 VkDependencyFlags, std::uint32_t, const VkMemoryBarrier*,
88 std::uint32_t, const VkBufferMemoryBarrier*, std::uint32_t,
89 const VkImageMemoryBarrier*) {
90 ++g_rec.barriers;
91}
92
93VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL mock_get_device_proc_addr(VkDevice, const char* name) {
94 if (!name) return nullptr;
95 if (std::strcmp(name, "vkCreateShaderModule") == 0) return reinterpret_cast<PFN_vkVoidFunction>(mock_create_shader_module);
96 if (std::strcmp(name, "vkDestroyShaderModule") == 0) return reinterpret_cast<PFN_vkVoidFunction>(mock_destroy_shader_module);
97 if (std::strcmp(name, "vkCreatePipelineLayout") == 0) return reinterpret_cast<PFN_vkVoidFunction>(mock_create_pipeline_layout);
98 if (std::strcmp(name, "vkDestroyPipelineLayout") == 0) return reinterpret_cast<PFN_vkVoidFunction>(mock_destroy_pipeline_layout);
99 if (std::strcmp(name, "vkCreateComputePipelines") == 0) return reinterpret_cast<PFN_vkVoidFunction>(mock_create_compute_pipelines);
100 if (std::strcmp(name, "vkDestroyPipeline") == 0) return reinterpret_cast<PFN_vkVoidFunction>(mock_destroy_pipeline);
101 if (std::strcmp(name, "vkCmdBindPipeline") == 0) return reinterpret_cast<PFN_vkVoidFunction>(mock_cmd_bind_pipeline);
102 if (std::strcmp(name, "vkCmdPushConstants") == 0) return reinterpret_cast<PFN_vkVoidFunction>(mock_cmd_push_constants);
103 if (std::strcmp(name, "vkCmdDispatch") == 0) return reinterpret_cast<PFN_vkVoidFunction>(mock_cmd_dispatch);
104 if (std::strcmp(name, "vkCmdPipelineBarrier") == 0) return reinterpret_cast<PFN_vkVoidFunction>(mock_cmd_pipeline_barrier);
105 return nullptr;
106}
107
108} // namespace
109
110int main() {
111 using namespace leonida;
112
113 const VkDevice dev = fake_handle<VkDevice>(0x1000);
114 const VkCommandBuffer cb = fake_handle<VkCommandBuffer>(0x2000);
115 XdxrBuilder builder(mock_get_device_proc_addr, dev);
116 CHECK(builder.loaded());
117
118 XdxrLayout blas1;
119 CHECK(blas1.compute(1, false));
120 XdxrLayout blas4;
121 CHECK(blas4.compute(4, false));
122 XdxrLayout tlas0;
123 CHECK(tlas0.compute(0, true));
124 XdxrLayout tlas4;
125 CHECK(tlas4.compute(4, true));
126 const XdxrLayout uncomputed{};
127
128 const std::uint64_t dst = 0x100000;
129 const std::uint64_t scratch = 0x200000;
130 const std::uint64_t instances = 0x300000;
131
132 // 1. Fewer triangles than layout.elements must fail cleanly without recording any commands.
133 g_rec.reset();
134 CHECK(!builder.record_blas(cb, blas4, {XdxrTriangles{.triangle_count = 3}}, dst, scratch));
135 CHECK(g_rec.empty());
136
137 // 2. More triangles than layout.elements must fail cleanly without recording any commands.
138 g_rec.reset();
139 CHECK(!builder.record_blas(cb, blas4,
140 {XdxrTriangles{.triangle_count = 2}, XdxrTriangles{.triangle_count = 3}},
141 dst, scratch));
142 CHECK(g_rec.empty());
143
144 // 3. Sums that would wrap uint32_t back to layout.elements must be rejected before any dispatch.
145 g_rec.reset();
146 CHECK(!builder.record_blas(cb, blas1,
147 {XdxrTriangles{.triangle_count = 0x80000001u},
148 XdxrTriangles{.triangle_count = 0x80000000u}},
149 dst, scratch));
150 CHECK(g_rec.empty());
151
152 // 4. Null addresses, uncomputed layouts, and non-empty TLAS with null instances record nothing.
153 g_rec.reset();
154 CHECK(!builder.record_blas(cb, blas1, {XdxrTriangles{.triangle_count = 1}}, 0, scratch));
155 CHECK(!builder.record_blas(cb, blas1, {XdxrTriangles{.triangle_count = 1}}, dst, 0));
156 CHECK(!builder.record_blas(cb, uncomputed, {}, dst, scratch));
157 CHECK(!builder.record_tlas(cb, tlas4, instances, 0, scratch));
158 CHECK(!builder.record_tlas(cb, tlas4, instances, dst, 0));
159 CHECK(!builder.record_tlas(cb, tlas4, 0, dst, scratch));
160 CHECK(!builder.record_tlas(cb, uncomputed, instances, dst, scratch));
161 CHECK(g_rec.empty());
162
163 // 5. Empty TLAS with null instances pointer is valid and records a build.
164 g_rec.reset();
165 CHECK(builder.record_tlas(cb, tlas0, 0, dst, scratch));
166 CHECK(g_rec.binds > 0 && g_rec.dispatches > 0);
167
168 // 6. Valid multi-geometry BLAS records dispatches.
169 g_rec.reset();
170 CHECK(builder.record_blas(cb, blas4,
171 {XdxrTriangles{.triangle_count = 1}, XdxrTriangles{.triangle_count = 3}},
172 dst, scratch));
173 CHECK(g_rec.binds > 0 && g_rec.dispatches > 0 && g_rec.pushes == g_rec.dispatches);
174
175 // 7. Large record_copy dispatches compute group counts without 32-bit overflow.
176 g_rec.reset();
177 CHECK(builder.record_copy(cb, dst, dst + 0x10000, 0xffffffffull));
178 CHECK(g_rec.dispatches == 1 && g_rec.last_copy_count == 0x3fffffffu &&
179 g_rec.last_group_count_x == (0x3fffffffu + 63u) / 64u);
180
181 std::puts("xdxr_builder_validation: all checks passed");
182 return 0;
183}
diff --git a/runtime/test/xdxr_descs_test.cpp b/runtime/test/xdxr_descs_test.cpp
index 209fd4fcc..8b857b8d7 100644
--- a/runtime/test/xdxr_descs_test.cpp
+++ b/runtime/test/xdxr_descs_test.cpp
@@ -69,6 +69,19 @@ int stream_lookup() {
69 records[1].type = 0; 69 records[1].type = 0;
70 CHECK(find_stream_record(stream_of(records, 1), 0) == nullptr); 70 CHECK(find_stream_record(stream_of(records, 1), 0) == nullptr);
71 CHECK(find_stream_record(stream_of(records, 2), 0) == &records[1]); 71 CHECK(find_stream_record(stream_of(records, 2), 0) == &records[1]);
72
73 // Trailing bytes shorter than one complete StreamRecord are never read.
74 records[0].type = 0;
75 const size_t small_sizes[] = {1, 4, sizeof(StreamRecord) - 1};
76 for (size_t bytes : small_sizes)
77 CHECK(find_stream_record(StreamDesc{bytes, records}, 0) == nullptr);
78 records[0].type = 1;
79 records[1].type = 0;
80 const size_t partial_second_sizes[] = {sizeof(StreamRecord) + 1, 2 * sizeof(StreamRecord) - 1};
81 for (size_t bytes : partial_second_sizes) {
82 CHECK(find_stream_record(StreamDesc{bytes, records}, 1) == &records[0]);
83 CHECK(find_stream_record(StreamDesc{bytes, records}, 0) == nullptr);
84 }
72 return 0; 85 return 0;
73} 86}
74 87
diff --git a/runtime/test/xgameruntime_offline_test.cpp b/runtime/test/xgameruntime_offline_test.cpp
index 7668b6164..66b110054 100644
--- a/runtime/test/xgameruntime_offline_test.cpp
+++ b/runtime/test/xgameruntime_offline_test.cpp
@@ -8,6 +8,7 @@
8#include <cstdio> 8#include <cstdio>
9#include <cstdlib> 9#include <cstdlib>
10#include <cstring> 10#include <cstring>
11#include <string>
11 12
12#include <XAsync.h> 13#include <XAsync.h>
13#include <XAsyncProvider.h> 14#include <XAsyncProvider.h>
@@ -74,7 +75,16 @@ constexpr GUID kAccessibilityClass = {0x3e241977, 0x6237, 0x41e9, {0x85, 0x59, 0
74constexpr GUID kAccessibility2 = {0xd722b373, 0x8c4d, 0x4692, {0x9e, 0x51, 0xd6, 0xad, 0x9b, 0x37, 0xaa, 0x7d}}; 75constexpr GUID kAccessibility2 = {0xd722b373, 0x8c4d, 0x4692, {0x9e, 0x51, 0xd6, 0xad, 0x9b, 0x37, 0xaa, 0x7d}};
75constexpr GUID kLauncherClass = {0x1b339674, 0x328d, 0x4283, {0xa2, 0x00, 0x31, 0x71, 0xf1, 0x8d, 0x36, 0x39}}; 76constexpr GUID kLauncherClass = {0x1b339674, 0x328d, 0x4283, {0xa2, 0x00, 0x31, 0x71, 0xf1, 0x8d, 0x36, 0x39}};
76 77
77using EnumVoices = HRESULT(STDMETHODCALLTYPE*)(void*, void*, void*); 78struct VoiceInformation { // XSpeechSynthesizerVoiceInformation, the GDK reference's member order
79 const char* description;
80 const char* display_name;
81 uint32_t gender;
82 const char* voice_id;
83 const char* language;
84};
85using VoiceCallback = bool(CALLBACK*)(const VoiceInformation*, void*);
86using EnumVoices = HRESULT(STDMETHODCALLTYPE*)(void*, void* context, VoiceCallback callback);
87using SetCustomVoice = HRESULT(STDMETHODCALLTYPE*)(void*, void*, const char*);
78using SpeechCreate = HRESULT(STDMETHODCALLTYPE*)(void*, void**); 88using SpeechCreate = HRESULT(STDMETHODCALLTYPE*)(void*, void**);
79using SpeechClose = HRESULT(STDMETHODCALLTYPE*)(void*, void*); 89using SpeechClose = HRESULT(STDMETHODCALLTYPE*)(void*, void*);
80using SpeechStream = HRESULT(STDMETHODCALLTYPE*)(void*, void*, const char*, void**); 90using SpeechStream = HRESULT(STDMETHODCALLTYPE*)(void*, void*, const char*, void**);
@@ -93,6 +103,19 @@ void* user_object(HRESULT(WINAPI* query)(const GUID*, REFIID, void**)) {
93 103
94void CALLBACK on_state(void*, uint64_t, uint32_t) {} 104void CALLBACK on_state(void*, uint64_t, uint32_t) {}
95 105
106struct VoicesSeen {
107 int count = 0;
108 std::string voice_id;
109 std::string language;
110};
111bool CALLBACK on_voice(const VoiceInformation* info, void* context) {
112 auto* seen = static_cast<VoicesSeen*>(context);
113 ++seen->count;
114 seen->voice_id = info && info->voice_id ? info->voice_id : "";
115 seen->language = info && info->language ? info->language : "";
116 return true;
117}
118
96// XUserDeviceImpl slots 4/5 (device association) and 7/8 (default audio endpoint): kept until unregistered, never 119// XUserDeviceImpl slots 4/5 (device association) and 7/8 (default audio endpoint): kept until unregistered, never
97// called back offline. 120// called back offline.
98long g_device_callbacks = 0; 121long g_device_callbacks = 0;
@@ -290,22 +313,45 @@ int main() {
290 "XHighContrastGetMode reports Off"); 313 "XHighContrastGetMode reports Off");
291 check(at<SetEnabled>(acc, 4)(acc, true) == S_OK, "XClosedCaptionSetEnabled is accepted"); 314 check(at<SetEnabled>(acc, 4)(acc, true) == S_OK, "XClosedCaptionSetEnabled is accepted");
292 check(FAILED(at<NoArgs>(acc, 3)(acc)), "the closed-caption properties are not available offline"); 315 check(FAILED(at<NoArgs>(acc, 3)(acc)), "the closed-caption properties are not available offline");
293 check(at<EnumVoices>(acc, 8)(acc, reinterpret_cast<void*>(&on_state), nullptr) == S_OK && 316 VoicesSeen seen;
294 at<EnumVoices>(acc, 8)(acc, nullptr, nullptr) == E_INVALIDARG, 317 check(at<EnumVoices>(acc, 8)(acc, &seen, &on_voice) == S_OK && seen.count == 1 &&
295 "XSpeechSynthesizerEnumerateInstalledVoices: no voices, S_OK (a callback is required)"); 318 seen.voice_id == "leonida-silent" && seen.language == "en-US",
296 void* synth = reinterpret_cast<void*>(1); 319 "XSpeechSynthesizerEnumerateInstalledVoices(context, callback): one silent voice, its context passed back");
297 check(at<SpeechCreate>(acc, 9)(acc, &synth) == E_FAIL && synth == nullptr, 320 check(at<EnumVoices>(acc, 8)(acc, nullptr, nullptr) == E_INVALIDARG,
298 "XSpeechSynthesizerCreate fails offline and nulls the handle"); 321 "XSpeechSynthesizerEnumerateInstalledVoices: a callback is required");
299 void* stream = reinterpret_cast<void*>(1); 322 void* synth = nullptr;
300 size_t size = 5, got = 5; 323 check(at<SpeechCreate>(acc, 9)(acc, &synth) == S_OK && synth != nullptr &&
324 at<SpeechCreate>(acc, 9)(acc, nullptr) == E_POINTER,
325 "XSpeechSynthesizerCreate returns a silent synthesizer handle");
326 void* stream = nullptr;
327 size_t size = 0, got = 0;
301 check(at<SpeechClose>(acc, 10)(acc, nullptr) == E_INVALIDARG && at<SpeechClose>(acc, 11)(acc, nullptr) == E_INVALIDARG && 328 check(at<SpeechClose>(acc, 10)(acc, nullptr) == E_INVALIDARG && at<SpeechClose>(acc, 11)(acc, nullptr) == E_INVALIDARG &&
302 at<SpeechClose>(acc, 12)(acc, nullptr) == E_INVALIDARG && at<SpeechClose>(acc, 14)(acc, nullptr) == E_INVALIDARG, 329 at<SpeechClose>(acc, 12)(acc, nullptr) == E_INVALIDARG && at<SpeechClose>(acc, 14)(acc, nullptr) == E_INVALIDARG,
303 "close and set-voice calls on a null handle: E_INVALIDARG"); 330 "close and set-voice calls on a null handle: E_INVALIDARG");
331 check(at<SpeechClose>(acc, 11)(acc, synth) == S_OK, "XSpeechSynthesizerSetDefaultVoice succeeds on valid handle");
332 check(at<SetCustomVoice>(acc, 12)(acc, synth, seen.voice_id.c_str()) == S_OK &&
333 at<SetCustomVoice>(acc, 12)(acc, synth, "not-installed") == E_INVALIDARG &&
334 at<SetCustomVoice>(acc, 12)(acc, synth, nullptr) == E_INVALIDARG,
335 "XSpeechSynthesizerSetCustomVoice accepts the enumerated voice only");
304 check(at<SpeechStream>(acc, 13)(acc, nullptr, "hi", &stream) == E_INVALIDARG && stream == nullptr, 336 check(at<SpeechStream>(acc, 13)(acc, nullptr, "hi", &stream) == E_INVALIDARG && stream == nullptr,
305 "CreateStreamFromText on a null synthesizer: E_INVALIDARG, no stream"); 337 "CreateStreamFromText on a null synthesizer: E_INVALIDARG, no stream");
306 stream = reinterpret_cast<void*>(1); 338 check(at<SpeechStream>(acc, 13)(acc, synth, "Hello", &stream) == S_OK && stream != nullptr,
307 check(at<SpeechStream>(acc, 21)(acc, nullptr, "<speak/>", &stream) == E_INVALIDARG && stream == nullptr, 339 "CreateStreamFromText returns a silent WAVE stream");
308 "CreateStreamFromSsml on a null synthesizer: E_INVALIDARG, no stream"); 340 check(at<StreamSize>(acc, 15)(acc, stream, &size) == S_OK && size == 44,
341 "GetStreamDataSize reports the 44-byte empty WAVE header");
342 uint8_t wav[64] = {};
343 check(at<StreamData>(acc, 16)(acc, stream, 8, wav, &got) == HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER) && got == 0,
344 "GetStreamData rejects an undersized buffer with ERROR_INSUFFICIENT_BUFFER");
345 check(at<StreamData>(acc, 16)(acc, stream, sizeof(wav), wav, &got) == S_OK && got == 44 &&
346 std::memcmp(wav, "RIFF", 4) == 0 && std::memcmp(wav + 8, "WAVEfmt ", 8) == 0 &&
347 std::memcmp(wav + 36, "data", 4) == 0,
348 "GetStreamData writes a valid silent 16 kHz mono 16-bit PCM WAVE header");
349 check(at<SpeechClose>(acc, 14)(acc, stream) == S_OK, "XSpeechSynthesizerCloseStreamHandle succeeds");
350 stream = nullptr;
351 check(at<SpeechStream>(acc, 21)(acc, synth, "<speak/>", &stream) == S_OK && stream != nullptr &&
352 at<SpeechClose>(acc, 14)(acc, stream) == S_OK,
353 "CreateStreamFromSsml returns a silent WAVE stream");
354 check(at<SpeechClose>(acc, 10)(acc, synth) == S_OK, "XSpeechSynthesizerCloseHandle succeeds");
309 check(at<StreamSize>(acc, 15)(acc, nullptr, &size) == E_INVALIDARG && size == 0 && 355 check(at<StreamSize>(acc, 15)(acc, nullptr, &size) == E_INVALIDARG && size == 0 &&
310 at<StreamData>(acc, 16)(acc, nullptr, 8, nullptr, &got) == E_INVALIDARG && got == 0, 356 at<StreamData>(acc, 16)(acc, nullptr, 8, nullptr, &got) == E_INVALIDARG && got == 0,
311 "stream size and data on a null stream: E_INVALIDARG, zero written"); 357 "stream size and data on a null stream: E_INVALIDARG, zero written");
@@ -317,12 +363,17 @@ int main() {
317 void* launcher = nullptr; 363 void* launcher = nullptr;
318 check(query(&kLauncherClass, kLauncherClass, &launcher) == S_OK && launcher, "XLauncherImpl for its class id"); 364 check(query(&kLauncherClass, kLauncherClass, &launcher) == S_OK && launcher, "XLauncherImpl for its class id");
319 if (!launcher) return 1; 365 if (!launcher) return 1;
320 void* deferral = reinterpret_cast<void*>(1); 366 void* deferral = nullptr;
367 using CloseDeferral = void(STDMETHODCALLTYPE*)(void*, void*);
321 check(at<LaunchUri>(launcher, 3)(launcher, nullptr, "https://example.com") == E_FAIL, 368 check(at<LaunchUri>(launcher, 3)(launcher, nullptr, "https://example.com") == E_FAIL,
322 "XLaunchUri is not available offline"); 369 "XLaunchUri is not available offline");
323 check(at<AcquireDeferral>(launcher, 4)(launcher, &deferral) == E_FAIL && deferral == nullptr && 370 check(at<AcquireDeferral>(launcher, 4)(launcher, nullptr) == E_POINTER,
324 at<NoArgs>(launcher, 5)(launcher) == E_FAIL, 371 "XDisplayAcquireTimeoutDeferral rejects null out pointer");
325 "the display timeout deferral is not available offline"); 372 check(at<AcquireDeferral>(launcher, 4)(launcher, &deferral) == S_OK && deferral != nullptr,
373 "XDisplayAcquireTimeoutDeferral acquires a display power request handle");
374 at<CloseDeferral>(launcher, 5)(launcher, deferral);
375 at<CloseDeferral>(launcher, 5)(launcher, nullptr);
376 check(true, "XDisplayCloseTimeoutDeferralHandle closes handle and ignores null");
326 GUID other = kLauncherClass; 377 GUID other = kLauncherClass;
327 other.Data1 ^= 1; 378 other.Data1 ^= 1;
328 void* none = reinterpret_cast<void*>(1); 379 void* none = reinterpret_cast<void*>(1);
diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp
index 224030247..888bedf24 100644
--- a/runtime/test/xs_proxy_mock_test.cpp
+++ b/runtime/test/xs_proxy_mock_test.cpp
@@ -91,6 +91,8 @@ struct Mock {
91 bool allocator_tag; // allocator: answers kLeonidaCommandAllocatorTag; device: the allocators it makes do 91 bool allocator_tag; // allocator: answers kLeonidaCommandAllocatorTag; device: the allocators it makes do
92 bool create_null; // device: creation returns create_result with no object 92 bool create_null; // device: creation returns create_result with no object
93 HRESULT create_result; // device: what creation returns (S_OK makes the object) 93 HRESULT create_result; // device: what creation returns (S_OK makes the object)
94 bool list_refuse; // device: CreateCommandList refuses every riid with E_NOINTERFACE
95 IID create_riid; // device: copy of the riid its last CreateCommandList got (the caller's may be a local)
94 Mock* last_child; // device: the object its last creation or open made 96 Mock* last_child; // device: the object its last creation or open made
95 unsigned calls[kMockSlots]; 97 unsigned calls[kMockSlots];
96 std::uint64_t args[kMockSlots][5]; 98 std::uint64_t args[kMockSlots][5];
@@ -276,8 +278,10 @@ HRESULT WINAPI mock_create_command_list(Mock* self, std::uint64_t node_mask, std
276 self->args[12][2] = allocator; 278 self->args[12][2] = allocator;
277 self->args[12][3] = initial_state; 279 self->args[12][3] = initial_state;
278 self->args[12][4] = reinterpret_cast<std::uint64_t>(riid); 280 self->args[12][4] = reinterpret_cast<std::uint64_t>(riid);
281 if (riid) self->create_riid = *riid;
279 if (!out) return S_FALSE; 282 if (!out) return S_FALSE;
280 *out = nullptr; 283 *out = nullptr;
284 if (self->list_refuse) return E_NOINTERFACE;
281 if (self->create_null || FAILED(self->create_result)) return self->create_result; 285 if (self->create_null || FAILED(self->create_result)) return self->create_result;
282 Mock* child = new_mock(Kind::command_list); 286 Mock* child = new_mock(Kind::command_list);
283 child->list_level = self->list_level; 287 child->list_level = self->list_level;
@@ -981,17 +985,27 @@ int check_xbox_slots() {
981 985
982// ---- 8. Environment overrides for the Xbox device slots (one process each, read once) ---- 986// ---- 8. Environment overrides for the Xbox device slots (one process each, read once) ----
983 987
988struct EnvPresenter {
989 int stats = 0, present = 0, suspend = 0, resume = 0;
990};
991
984int run_env_slots(bool valid) { 992int run_env_slots(bool valid) {
985 const char* frame_interval = valid ? "96" : "2"; 993 const char* frame_interval = valid ? "96" : "2";
986 const char* schedule_event = valid ? "97" : "2"; 994 const char* schedule_event = valid ? "97" : "2";
987 const char* wait_event = valid ? "98" : "2"; 995 const char* wait_event = valid ? "98" : "2";
988 const char* queue_x = valid ? "99" : "2"; 996 const char* queue_x = valid ? "99" : "2";
989 const char* list_x = valid ? "100" : "2"; 997 const char* list_x = valid ? "100" : "2";
998 const char* frame_statistics = valid ? "101" : "2";
999 const char* suspend_x = valid ? "33" : "2"; // a queue slot beyond the PC table, as SuspendX would be
1000 const char* resume_x = valid ? "30" : "2"; // equal to PresentX's default: ResumeX is unrouted (logged)
990 EXPECT(SetEnvironmentVariableA("LEONIDA_XS_FRAME_INTERVAL_SLOT", frame_interval) != FALSE); 1001 EXPECT(SetEnvironmentVariableA("LEONIDA_XS_FRAME_INTERVAL_SLOT", frame_interval) != FALSE);
991 EXPECT(SetEnvironmentVariableA("LEONIDA_XS_SCHEDULE_EVENT_SLOT", schedule_event) != FALSE); 1002 EXPECT(SetEnvironmentVariableA("LEONIDA_XS_SCHEDULE_EVENT_SLOT", schedule_event) != FALSE);
992 EXPECT(SetEnvironmentVariableA("LEONIDA_XS_WAIT_EVENT_SLOT", wait_event) != FALSE); 1003 EXPECT(SetEnvironmentVariableA("LEONIDA_XS_WAIT_EVENT_SLOT", wait_event) != FALSE);
1004 EXPECT(SetEnvironmentVariableA("LEONIDA_XS_FRAME_STATISTICS_SLOT", frame_statistics) != FALSE);
993 EXPECT(SetEnvironmentVariableA("LEONIDA_XS_QUEUE_X_SLOT", queue_x) != FALSE); 1005 EXPECT(SetEnvironmentVariableA("LEONIDA_XS_QUEUE_X_SLOT", queue_x) != FALSE);
994 EXPECT(SetEnvironmentVariableA("LEONIDA_XS_LIST_X_SLOT", list_x) != FALSE); 1006 EXPECT(SetEnvironmentVariableA("LEONIDA_XS_LIST_X_SLOT", list_x) != FALSE);
1007 EXPECT(SetEnvironmentVariableA("LEONIDA_XS_SUSPEND_X_SLOT", suspend_x) != FALSE);
1008 EXPECT(SetEnvironmentVariableA("LEONIDA_XS_RESUME_X_SLOT", resume_x) != FALSE);
995 1009
996 Mock* mock = nullptr; 1010 Mock* mock = nullptr;
997 void* device = make_device(mock, 11, true); 1011 void* device = make_device(mock, 11, true);
@@ -1018,6 +1032,36 @@ int run_env_slots(bool valid) {
1018 EXPECT(hr_of(raw(device, 78, 0, 16667, 1, 0)) == S_OK && mock->calls[78] == 1); 1032 EXPECT(hr_of(raw(device, 78, 0, 16667, 1, 0)) == S_OK && mock->calls[78] == 1);
1019 EXPECT(release(list) == 0); 1033 EXPECT(release(list) == 0);
1020 EXPECT(release(allocator) == 0); 1034 EXPECT(release(allocator) == 0);
1035
1036 // The presenter answers frame statistics at 101 only (81 is not routed, so the mock refuses it); PresentX
1037 // stays at 30, SuspendX answers at 33, and ResumeX, asked for 30, is unrouted, so 32 is refused.
1038 EnvPresenter env{};
1039 xs::PresentationHandler h{};
1040 h.context = &env;
1041 h.get_frame_statistics = [](void* ctx, std::uint64_t, UINT, UINT*, void*) -> HRESULT {
1042 ++static_cast<EnvPresenter*>(ctx)->stats;
1043 return S_FALSE;
1044 };
1045 h.present_x = [](void* ctx, UINT, const void*, const void*) -> HRESULT {
1046 ++static_cast<EnvPresenter*>(ctx)->present;
1047 return S_OK;
1048 };
1049 h.suspend_x = [](void* ctx, UINT) -> HRESULT {
1050 ++static_cast<EnvPresenter*>(ctx)->suspend;
1051 return S_OK;
1052 };
1053 h.resume_x = [](void* ctx) -> HRESULT {
1054 ++static_cast<EnvPresenter*>(ctx)->resume;
1055 return S_OK;
1056 };
1057 EXPECT(xs::set_presentation_handler(device, &h));
1058 UINT count = 0;
1059 EXPECT(hr_of(raw(device, 101, 77, 0x1a, word(&count), 0)) == S_FALSE && env.stats == 1);
1060 EXPECT(hr_of(raw(device, 81, 77, 0x1a, word(&count), 0)) == E_NOTIMPL && env.stats == 1);
1061 EXPECT(hr_of(raw(queue, 30, 1, 0, 0)) == S_OK && env.present == 1);
1062 EXPECT(hr_of(raw(queue, 33)) == S_OK && env.suspend == 1);
1063 EXPECT(hr_of(raw(queue, 32)) == E_NOTIMPL && env.resume == 0);
1064 EXPECT(xs::set_presentation_handler(device, nullptr));
1021 EXPECT(release(queue) == 0); 1065 EXPECT(release(queue) == 0);
1022 } else { 1066 } else {
1023 // Values outside 3..127 are ignored: the five defaults still answer, and a PC slot that is not a default is 1067 // Values outside 3..127 are ignored: the five defaults still answer, and a PC slot that is not a default is
@@ -1025,6 +1069,7 @@ int run_env_slots(bool valid) {
1025 EXPECT(hr_of(raw(device, 78, 0, 16667, 1, 0)) == S_OK && mock->calls[78] == 0); 1069 EXPECT(hr_of(raw(device, 78, 0, 16667, 1, 0)) == S_OK && mock->calls[78] == 0);
1026 EXPECT(hr_of(raw(device, 79, 0, 0, 0, 0)) == S_OK && mock->calls[79] == 0); 1070 EXPECT(hr_of(raw(device, 79, 0, 0, 0, 0)) == S_OK && mock->calls[79] == 0);
1027 EXPECT(hr_of(raw(device, 80, 0, 0, 0, 0, word(&token))) == S_OK && token && mock->calls[80] == 0); 1071 EXPECT(hr_of(raw(device, 80, 0, 0, 0, 0, word(&token))) == S_OK && token && mock->calls[80] == 0);
1072 EXPECT(hr_of(raw(device, 81, 0, 0, 0, 0)) == S_FALSE); // the default GetFrameStatisticsX slot, unattached
1028 EXPECT(hr_of(raw(device, 71)) == S_OK && mock->calls[71] == 1); // not an Xbox slot: forwarded 1073 EXPECT(hr_of(raw(device, 71)) == S_OK && mock->calls[71] == 1); // not an Xbox slot: forwarded
1029 } 1074 }
1030 EXPECT(release(device) == 0 && mock->refs == 0); 1075 EXPECT(release(device) == 0 && mock->refs == 0);
@@ -1504,6 +1549,39 @@ int check_console_command_list() {
1504 EXPECT(real_queue->array[10][0] == word(unwrapped_list)); 1549 EXPECT(real_queue->array[10][0] == word(unwrapped_list));
1505 EXPECT(real_queue->array[10][1] == word(real_list)); 1550 EXPECT(real_queue->array[10][1] == word(real_list));
1506 1551
1552 // 5b. Public list revisions the proxy does not model and unknown private IIDs must not trigger a retry.
1553 // Spell out the Windows SDK's ID3D12GraphicsCommandList9 IID so this also builds with older headers.
1554 const IID list9_iid = {0x34ed2808, 0xffe6, 0x4c2b, {0xb1, 0x1a, 0xca, 0xbd, 0x2b, 0x0c, 0x59, 0xe1}};
1555 const IID unknown_iid = {0x12345678, 0x1234, 0x1234, {1, 2, 3, 4, 5, 6, 7, 8}};
1556 for (const IID* iid : {&list9_iid, &unknown_iid}) {
1557 const unsigned calls_before = mock_device->calls[12];
1558 void* unsupported_list = list_proxy;
1559 EXPECT(hr_of(raw(device, 73, word(&desc), word(allocator), 0, word(iid), word(&unsupported_list))) ==
1560 E_NOINTERFACE);
1561 EXPECT(!unsupported_list && mock_device->calls[12] == calls_before + 1);
1562 }
1563
1564 // The measured Xbox list IID is created as ID3D12GraphicsCommandList in one call and stays queryable on the proxy.
1565 const IID console_iid = {0xc3827890, 0x4024, 0x474c, {0x98, 0xcf, 0x64, 0x5b, 0x51, 0xdc, 0x48, 0x74}};
1566 const unsigned calls12_before = mock_device->calls[12];
1567 void* console_list = nullptr;
1568 EXPECT(hr_of(raw(device, 73, word(&desc), word(allocator), 0, word(&console_iid), word(&console_list))) == S_OK);
1569 EXPECT(xs::is_command_list_proxy(console_list) && mock_device->calls[12] == calls12_before + 1);
1570 EXPECT(IsEqualIID(mock_device->create_riid, __uuidof(ID3D12GraphicsCommandList)));
1571 void* console_list_qi = nullptr;
1572 EXPECT(hr_of(raw(console_list, 0, word(&console_iid), word(&console_list_qi))) == S_OK);
1573 EXPECT(console_list_qi == console_list && release(console_list_qi) == 1);
1574 EXPECT(release(console_list) == 0);
1575
1576 // The PC device refuses even ID3D12GraphicsCommandList for a PC IID: E_NOINTERFACE comes back as is, no retry.
1577 mock_device->list_refuse = true;
1578 const unsigned calls12_refused = mock_device->calls[12];
1579 console_list = nullptr;
1580 EXPECT(hr_of(raw(device, 73, word(&desc), word(allocator), 0, word(&list_iid), word(&console_list))) ==
1581 E_NOINTERFACE);
1582 EXPECT(!console_list && mock_device->calls[12] == calls12_refused + 1);
1583 mock_device->list_refuse = false;
1584
1507 // 6. Test with list_level = 7 (supporting ID3D12GraphicsCommandList7, 81 slots) 1585 // 6. Test with list_level = 7 (supporting ID3D12GraphicsCommandList7, 81 slots)
1508 mock_device->list_level = 7; 1586 mock_device->list_level = 7;
1509 void* list7_proxy = nullptr; 1587 void* list7_proxy = nullptr;
@@ -1534,6 +1612,99 @@ int check_console_command_list() {
1534 return 0; 1612 return 0;
1535} 1613}
1536 1614
1615// ---- 11. Presentation handler wiring (device slots 78–81 + queue PresentX/SuspendX/ResumeX) ----
1616
1617struct MockPresenter {
1618 int interval_calls = 0;
1619 UINT last_interval = 0;
1620 int schedule_calls = 0;
1621 UINT last_event = 0;
1622 int wait_calls = 0;
1623 UINT last_flags = 0;
1624 int stats_calls = 0;
1625 int present_calls = 0;
1626 UINT last_planes = 0;
1627 int suspend_calls = 0;
1628 int resume_calls = 0;
1629};
1630
1631int check_presentation_wiring() {
1632 Mock* mock = nullptr;
1633 void* device = make_device(mock, 11, true);
1634 EXPECT(device != nullptr);
1635 void* queue = make_queue(device);
1636 EXPECT(queue != nullptr);
1637
1638 MockPresenter p{};
1639 xs::PresentationHandler h{};
1640 h.context = &p;
1641 h.set_frame_interval = [](void* ctx, IUnknown*, UINT us, UINT, UINT) -> HRESULT {
1642 auto* m = static_cast<MockPresenter*>(ctx);
1643 ++m->interval_calls;
1644 m->last_interval = us;
1645 return S_OK;
1646 };
1647 h.schedule_frame_event = [](void* ctx, UINT ev, UINT, UINT) -> HRESULT {
1648 auto* m = static_cast<MockPresenter*>(ctx);
1649 ++m->schedule_calls;
1650 m->last_event = ev;
1651 return S_OK;
1652 };
1653 h.wait_frame_event = [](void* ctx, UINT, DWORD, UINT flags, std::uint64_t* tok) -> HRESULT {
1654 auto* m = static_cast<MockPresenter*>(ctx);
1655 ++m->wait_calls;
1656 m->last_flags = flags;
1657 if (tok) *tok = 77;
1658 return S_FALSE;
1659 };
1660 h.get_frame_statistics = [](void* ctx, std::uint64_t, UINT, UINT* count, void*) -> HRESULT {
1661 auto* m = static_cast<MockPresenter*>(ctx);
1662 ++m->stats_calls;
1663 if (count) *count = 0;
1664 return S_FALSE;
1665 };
1666 h.present_x = [](void* ctx, UINT plane_count, const void*, const void*) -> HRESULT {
1667 auto* m = static_cast<MockPresenter*>(ctx);
1668 ++m->present_calls;
1669 m->last_planes = plane_count;
1670 return S_OK;
1671 };
1672 h.suspend_x = [](void* ctx, UINT) -> HRESULT {
1673 ++static_cast<MockPresenter*>(ctx)->suspend_calls;
1674 return S_OK;
1675 };
1676 h.resume_x = [](void* ctx) -> HRESULT {
1677 ++static_cast<MockPresenter*>(ctx)->resume_calls;
1678 return S_OK;
1679 };
1680
1681 EXPECT(xs::set_presentation_handler(device, &h));
1682 EXPECT(hr_of(raw(device, 78, 0, 33333, 2, 0)) == S_OK && p.interval_calls == 1 && p.last_interval == 33333);
1683 EXPECT(hr_of(raw(device, 79, 2, 0, 0, 0)) == S_OK && p.schedule_calls == 1 && p.last_event == 2);
1684 std::uint64_t tok = 0;
1685 EXPECT(hr_of(raw(device, 80, 0, 0, 0, 2, word(&tok))) == S_FALSE && tok == 77 && p.wait_calls == 1 &&
1686 p.last_flags == 2);
1687 UINT count = 3;
1688 EXPECT(hr_of(raw(device, 81, 77, 0x1a, word(&count), 0)) == S_FALSE && count == 0 && p.stats_calls == 1);
1689
1690 // Queue slot 30 routes to PresentX while attached. SuspendX and ResumeX have no default route, so 31/32 are refused
1691 // and never reach the presenter (the env mode, run_env_slots, routes them).
1692 EXPECT(hr_of(raw(queue, 30, 1, 0x1000, 0x2000)) == S_OK && p.present_calls == 1 && p.last_planes == 1);
1693 EXPECT(hr_of(raw(queue, 31, 0)) == E_NOTIMPL && p.suspend_calls == 0);
1694 EXPECT(hr_of(raw(queue, 32)) == E_NOTIMPL && p.resume_calls == 0);
1695
1696 // Detaching restores default E_NOTIMPL refusal on beyond-PC queue slots.
1697 EXPECT(xs::set_presentation_handler(device, nullptr));
1698 UINT none = 7; // unattached GetFrameStatisticsX: no statistics yet, never the PC slot 81
1699 EXPECT(hr_of(raw(device, 81, 77, 0x1a, word(&none), 0)) == S_FALSE && none == 0 && p.stats_calls == 1);
1700 EXPECT(hr_of(raw(queue, 30, 1, 0, 0)) == E_NOTIMPL && p.present_calls == 1);
1701
1702 EXPECT(release(queue) == 0);
1703 EXPECT(release(device) == 0 && mock->refs == 0);
1704 std::printf("%s: presentation handler wiring (slots 78-81 and queue PresentX 30) passed\n", g_label);
1705 return 0;
1706}
1707
1537int main(int argc, char** argv) { 1708int main(int argc, char** argv) {
1538 no_dialogs(); 1709 no_dialogs();
1539 std::setvbuf(stdout, nullptr, _IONBF, 0); 1710 std::setvbuf(stdout, nullptr, _IONBF, 0);
@@ -1546,7 +1717,8 @@ int main(int argc, char** argv) {
1546 if (check_tail(true) || check_levels() || check_slot48() || check_fence1() || check_create_failures() || check_open_shared() || 1717 if (check_tail(true) || check_levels() || check_slot48() || check_fence1() || check_create_failures() || check_open_shared() ||
1547 check_alloc_failures() || check_allocators() || check_xbox_slots() || check_console_command_list() || 1718 check_alloc_failures() || check_allocators() || check_xbox_slots() || check_console_command_list() ||
1548 check_custom_heap_properties() || 1719 check_custom_heap_properties() ||
1549 check_resource_allocation_info() || check_slot70() || check_committed_resource3_x()) 1720 check_resource_allocation_info() || check_slot70() || check_committed_resource3_x() ||
1721 check_presentation_wiring())
1550 return 1; 1722 return 1;
1551 std::printf("xs_proxy_mock_test: PASS (%d allocations refused on purpose)\n", g_failed_news); 1723 std::printf("xs_proxy_mock_test: PASS (%d allocations refused on purpose)\n", g_failed_news);
1552 return 0; 1724 return 0;