upleb.uk

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

summaryrefslogtreecommitdiff
path: root/runtime
diff options
context:
space:
mode:
authorJan Trencansky <jan.trencansky@protonmail.com>2026-11-24 18:48:12 -0500
committerJan Trencansky <jan.trencansky@protonmail.com>2026-11-24 18:48:12 -0500
commitfb2afdccc2314d7b5a59fac10e6d6df7f5df35ab (patch)
tree9e0b7e2e39b42823f148d135ce781e57fab52155 /runtime
parent862890c893eb19eb39eb2fd95e7786e42ff4b18c (diff)
parent864337351bc11a250db77c2fcdd3ba6f1d0f455f (diff)
Merge main into RT-QUEUE18 (#403)
Merged on top of the merge made for #396 (main 507029d1e plus RT-QUEUE35, RT-ALLOC9 and RT-LIST139). No conflicts. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Diffstat (limited to 'runtime')
-rw-r--r--runtime/CMakeLists.txt159
-rw-r--r--runtime/README.md3
-rw-r--r--runtime/cmake/translator_deps.cmake10
-rw-r--r--runtime/shims/acphal.cpp873
-rw-r--r--runtime/shims/d3d12_com.cpp93
-rw-r--r--runtime/shims/d3d12_com.h7
-rw-r--r--runtime/shims/d3d12_vulkan_device.cpp220
-rw-r--r--runtime/shims/d3d12_xs.cpp29
-rw-r--r--runtime/shims/d3d12_xs_device.cpp342
-rw-r--r--runtime/shims/d3d12_xs_device.h40
-rw-r--r--runtime/shims/file_system.cpp15
-rw-r--r--runtime/shims/gameinput.cpp79
-rw-r--r--runtime/shims/library_loader.cpp2
-rw-r--r--runtime/shims/registry.cpp3
-rw-r--r--runtime/shims/ws2_offline.cpp949
-rw-r--r--runtime/shims/xbox_present.cpp57
-rw-r--r--runtime/shims/xbox_present.h13
-rw-r--r--runtime/shims/xgameruntime.cpp23
-rw-r--r--runtime/shims/xgameruntime_gamesave.cpp109
-rw-r--r--runtime/shims/xgameruntime_offline.cpp144
-rw-r--r--runtime/shims/xmem.cpp15
-rw-r--r--runtime/src/active_input.h17
-rw-r--r--runtime/src/arena_size.h5
-rw-r--r--runtime/src/command_list.h15
-rw-r--r--runtime/src/cpu_emulation.h97
-rw-r--r--runtime/src/crt_timed_wait.cpp29
-rw-r--r--runtime/src/frame_pacer.h224
-rw-r--r--runtime/src/gfx10_descriptors.h6
-rw-r--r--runtime/src/mods.h4
-rw-r--r--runtime/src/retire_tickets.h16
-rw-r--r--runtime/src/shader_library.h23
-rw-r--r--runtime/src/statistics_sum.comp10
-rw-r--r--runtime/src/statistics_sum_spirv.h65
-rw-r--r--runtime/src/uav_clear.h4
-rw-r--r--runtime/src/vulkan_backend.h100
-rw-r--r--runtime/src/vulkan_replay.h243
-rw-r--r--runtime/src/vulkan_scratch.h16
-rw-r--r--runtime/src/xdxr_build.h14
-rw-r--r--runtime/src/xdxr_descs.h7
-rw-r--r--runtime/test/acphal_test.cpp628
-rw-r--r--runtime/test/active_input_test.cpp37
-rw-r--r--runtime/test/arena_size_test.cpp3
-rw-r--r--runtime/test/check_sparse_queue_family.py138
-rw-r--r--runtime/test/command_list_test.cpp8
-rw-r--r--runtime/test/cpu_emulation_test.cpp77
-rw-r--r--runtime/test/crt_timed_wait_test.cpp67
-rw-r--r--runtime/test/d3d12_b4g4r4a4_target_test.cpp226
-rw-r--r--runtime/test/d3d12_clear_test.cpp42
-rw-r--r--runtime/test/d3d12_close_parity_test.cpp55
-rw-r--r--runtime/test/d3d12_com_test.cpp93
-rw-r--r--runtime/test/d3d12_dxr_validation_test.cpp26
-rw-r--r--runtime/test/d3d12_execute_indirect_validation_test.cpp56
-rw-r--r--runtime/test/d3d12_heap_properties_test.cpp104
-rw-r--r--runtime/test/d3d12_indirect_dispatch_count_test.cpp56
-rw-r--r--runtime/test/d3d12_indirect_rt_test.cpp6
-rw-r--r--runtime/test/d3d12_mesh_test.cpp31
-rw-r--r--runtime/test/d3d12_multi_viewport_test.cpp484
-rw-r--r--runtime/test/d3d12_noop_copy_test.cpp16
-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_residency_test.cpp82
-rw-r--r--runtime/test/d3d12_state_map_test.cpp8
-rw-r--r--runtime/test/d3d12_state_sweep_test.cpp107
-rw-r--r--runtime/test/d3d12_subresource_copy_test.cpp18
-rw-r--r--runtime/test/d3d12_typeless_depth_test.cpp70
-rw-r--r--runtime/test/d3d12_uav_clear_test.cpp4
-rw-r--r--runtime/test/d3d12_vulkan_device_test.cpp35
-rw-r--r--runtime/test/device_proxy_test.cpp98
-rw-r--r--runtime/test/dxgi_host_parity_test.cpp5
-rw-r--r--runtime/test/dxgi_swapchain_test.cpp20
-rw-r--r--runtime/test/dxgi_waitable_latency_test.cpp6
-rw-r--r--runtime/test/file_system_test.cpp47
-rw-r--r--runtime/test/fixtures/tiny_ga_tls.cpp3
-rw-r--r--runtime/test/fixtures/tiny_game.cpp2
-rw-r--r--runtime/test/frame_pacer_test.cpp149
-rw-r--r--runtime/test/gameinput_test.cpp36
-rw-r--r--runtime/test/gfx10_descriptors_test.cpp13
-rw-r--r--runtime/test/loader_tls_test.cpp164
-rw-r--r--runtime/test/mods_test.cpp5
-rw-r--r--runtime/test/pipeline_cache_seed_test.cpp418
-rw-r--r--runtime/test/replay_copy_offset_test.cpp97
-rw-r--r--runtime/test/replay_cpu_bench.cpp2
-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_readback_stages_test.cpp56
-rw-r--r--runtime/test/replay_texture_barrier_test.cpp136
-rw-r--r--runtime/test/replay_uav_clear_offset_test.cpp108
-rw-r--r--runtime/test/retire_tickets_test.cpp18
-rw-r--r--runtime/test/root_sig_test.cpp41
-rw-r--r--runtime/test/shader_library_test.cpp9
-rw-r--r--runtime/test/shaders/build.py5
-rw-r--r--runtime/test/shaders/check.py362
-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_dpp_cmp.asm22
-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_cmp_f64.asm270
-rw-r--r--runtime/test/shaders/cs_w32_frexp_ldexp.asm44
-rw-r--r--runtime/test/shaders/cs_w32_lds_subdword.asm7
-rw-r--r--runtime/test/shaders/cs_w32_round_f64.asm56
-rw-r--r--runtime/test/shaders/cs_w32_shift64.asm29
-rw-r--r--runtime/test/shaders/mullit_readback.py122
-rw-r--r--runtime/test/shaders/ps_w64_a_wqm_uniform_vote.asm53
-rw-r--r--runtime/test/shaders/w64_graphics.py2
-rw-r--r--runtime/test/vk_command_replay_test.cpp194
-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_host_region_import_test.cpp355
-rw-r--r--runtime/test/vk_pipeline_check.cpp34
-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.h15
-rw-r--r--runtime/test/vk_xdxr_postbuild_readback_test.cpp177
-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_gamesave_test.cpp89
-rw-r--r--runtime/test/xgameruntime_offline_test.cpp83
-rw-r--r--runtime/test/xgameruntime_test.cpp40
-rw-r--r--runtime/test/xmem_test.cpp29
-rw-r--r--runtime/test/xs_proxy_mock_test.cpp390
-rw-r--r--runtime/xma_decoder/README.md15
-rw-r--r--runtime/xma_decoder/leonida_xma2_decoder.h4
-rw-r--r--runtime/xma_decoder/src/lib.rs51
-rw-r--r--runtime/xma_decoder/tests/ffi_contract.rs22
129 files changed, 11425 insertions, 849 deletions
diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt
index e922f067c..de10c26e8 100644
--- a/runtime/CMakeLists.txt
+++ b/runtime/CMakeLists.txt
@@ -106,6 +106,46 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME)
106 MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>" 106 MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>"
107 ) 107 )
108 108
109 # Rust XMA2 decoder (runtime/xma_decoder), built at configure time when cargo is on PATH.
110 # Without it (or if that build fails) the runtime still builds and XMA voices output silence.
111 option(LEONIDA_REQUIRE_XMA2_DECODER "Fail configure if the Rust XMA2 decoder is unavailable" OFF)
112 find_program(LEONIDA_CARGO cargo)
113 if(LEONIDA_CARGO)
114 # Cargo's host (or configured default target) can differ from the runtime's MSVC ABI.
115 set(_xma_target x86_64-pc-windows-msvc)
116 set(_xma_target_dir ${CMAKE_BINARY_DIR}/xma_decoder)
117 set(_xma_lib ${_xma_target_dir}/${_xma_target}/release/leonida_xma2_decoder.lib)
118 set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS
119 ${CMAKE_CURRENT_SOURCE_DIR}/xma_decoder/Cargo.toml
120 ${CMAKE_CURRENT_SOURCE_DIR}/xma_decoder/Cargo.lock
121 ${CMAKE_CURRENT_SOURCE_DIR}/xma_decoder/src/lib.rs)
122 execute_process(
123 COMMAND ${LEONIDA_CARGO} build --release --locked --target ${_xma_target}
124 --manifest-path ${CMAKE_CURRENT_SOURCE_DIR}/xma_decoder/Cargo.toml
125 --target-dir ${_xma_target_dir}
126 TIMEOUT 120
127 RESULT_VARIABLE _xma_result)
128 if(_xma_result STREQUAL "0" AND EXISTS ${_xma_lib})
129 add_library(leonida_xma2_decoder STATIC IMPORTED)
130 # Link Rust's Windows SDK dependencies. CMake's C++ target selects its own CRT
131 # (/MD or /MDd); the C ABI keeps allocation and deallocation on the same side.
132 # synchronization: Rust's std imports WaitOnAddress and WakeByAddress*, which MSVC's
133 # default libraries cover but clang-cl with an xwin SDK does not (lld-link: undefined symbol).
134 set_target_properties(leonida_xma2_decoder PROPERTIES
135 IMPORTED_LOCATION ${_xma_lib}
136 INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_CURRENT_SOURCE_DIR}/xma_decoder
137 INTERFACE_COMPILE_DEFINITIONS LEONIDA_HAVE_XMA2_DECODER=1
138 INTERFACE_LINK_LIBRARIES "kernel32;ntdll;userenv;ws2_32;dbghelp;synchronization")
139 else()
140 message(WARNING "cargo build of runtime/xma_decoder failed: XMA voices will be silent")
141 endif()
142 else()
143 message(STATUS "cargo not found: runtime/xma_decoder not built, XMA voices will be silent")
144 endif()
145 if(LEONIDA_REQUIRE_XMA2_DECODER AND NOT TARGET leonida_xma2_decoder)
146 message(FATAL_ERROR "LEONIDA_REQUIRE_XMA2_DECODER is enabled, but the Rust XMA2 decoder is unavailable")
147 endif()
148
109 add_executable(gta6rt 149 add_executable(gta6rt
110 src/main.cpp 150 src/main.cpp
111 src/host_cpu.cpp 151 src/host_cpu.cpp
@@ -113,6 +153,7 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME)
113 shims/registry.cpp 153 shims/registry.cpp
114 shims/file_system.cpp 154 shims/file_system.cpp
115 shims/winhttp_offline.cpp 155 shims/winhttp_offline.cpp
156 shims/ws2_offline.cpp
116 shims/xmem.cpp 157 shims/xmem.cpp
117 shims/xg_xs.cpp 158 shims/xg_xs.cpp
118 shims/acphal.cpp 159 shims/acphal.cpp
@@ -250,6 +291,11 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME)
250 target_compile_options(acphal_test PRIVATE /W4 /permissive- /utf-8) 291 target_compile_options(acphal_test PRIVATE /W4 /permissive- /utf-8)
251 target_link_options(acphal_test PRIVATE /OPT:NOREF) 292 target_link_options(acphal_test PRIVATE /OPT:NOREF)
252 293
294 if(TARGET leonida_xma2_decoder)
295 target_link_libraries(gta6rt PRIVATE leonida_xma2_decoder)
296 target_link_libraries(acphal_test PRIVATE leonida_xma2_decoder)
297 endif()
298
253 # The Zen 2 instructions a desktop CPU may lack (src/cpu_emulation.h): decoded, emulated on a CONTEXT, and run for 299 # The Zen 2 instructions a desktop CPU may lack (src/cpu_emulation.h): decoded, emulated on a CONTEXT, and run for
254 # real with the #UD handler installed, so an Intel host takes the emulated path and an AMD one the native path. 300 # real with the #UD handler installed, so an Intel host takes the emulated path and an AMD one the native path.
255 add_executable(cpu_emulation_test test/cpu_emulation_test.cpp) 301 add_executable(cpu_emulation_test test/cpu_emulation_test.cpp)
@@ -326,6 +372,18 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME)
326 target_compile_options(winhttp_offline_test PRIVATE /W4 /permissive- /utf-8) 372 target_compile_options(winhttp_offline_test PRIVATE /W4 /permissive- /utf-8)
327 target_link_options(winhttp_offline_test PRIVATE /OPT:NOREF) 373 target_link_options(winhttp_offline_test PRIVATE /OPT:NOREF)
328 374
375 # Offline Winsock2 for mapped images (ws2_32.dll restricted to loopback); no external network is touched.
376 add_executable(ws2_offline_test
377 test/ws2_offline_test.cpp
378 shims/ws2_offline.cpp
379 shims/registry.cpp
380 )
381 target_include_directories(ws2_offline_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims)
382 target_compile_definitions(ws2_offline_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
383 target_compile_options(ws2_offline_test PRIVATE /W4 /permissive- /utf-8)
384 target_link_options(ws2_offline_test PRIVATE /OPT:NOREF)
385 target_link_libraries(ws2_offline_test PRIVATE ws2_32)
386
329 # COM lifecycle and helper shims for api-ms-win-core-com-l1-1-*.dll. 387 # COM lifecycle and helper shims for api-ms-win-core-com-l1-1-*.dll.
330 add_executable(com_shim_test 388 add_executable(com_shim_test
331 test/com_shim_test.cpp 389 test/com_shim_test.cpp
@@ -577,6 +635,10 @@ if(BUILD_TESTING)
577 target_link_options(loader_test PRIVATE /OPT:NOREF ${GTA6RT_HOST_BASE}) 635 target_link_options(loader_test PRIVATE /OPT:NOREF ${GTA6RT_HOST_BASE})
578 add_dependencies(loader_test gta6rt_tls_host) 636 add_dependencies(loader_test gta6rt_tls_host)
579 add_test(NAME loader COMMAND loader_test) 637 add_test(NAME loader COMMAND loader_test)
638 # It takes about 10 s under Wine and under a minute on a desktop with a virus scanner. Before #239 it waited on
639 # a "Bad Image" box on the Windows runner until the job's own timeout cancelled the whole job (every Windows
640 # run from 24 Nov 00:37 to 03:32 UTC); a hang like that now fails this test instead.
641 set_tests_properties(loader PROPERTIES TIMEOUT 180)
580 # PE loader tests use two locally built fixtures: a DLL with exports, imports and relocations, and an EXE that 642 # PE loader tests use two locally built fixtures: a DLL with exports, imports and relocations, and an EXE that
581 # imports it so Loader::load exercises recursive module loading. They contain no game data. 643 # imports it so Loader::load exercises recursive module loading. They contain no game data.
582 set(TINY_FIXTURE_DIR "${CMAKE_CURRENT_BINARY_DIR}/fixtures/$<CONFIG>") 644 set(TINY_FIXTURE_DIR "${CMAKE_CURRENT_BINARY_DIR}/fixtures/$<CONFIG>")
@@ -610,6 +672,8 @@ if(BUILD_TESTING)
610 add_executable(tiny_ga_tls test/fixtures/tiny_ga_tls.cpp) 672 add_executable(tiny_ga_tls test/fixtures/tiny_ga_tls.cpp)
611 target_compile_definitions(tiny_ga_tls PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) 673 target_compile_definitions(tiny_ga_tls PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
612 target_compile_options(tiny_ga_tls PRIVATE /W4 /permissive- /utf-8 /GS- /GA) 674 target_compile_options(tiny_ga_tls PRIVATE /W4 /permissive- /utf-8 /GS- /GA)
675 # /GA can remove the _tls_index reference that pulls in the CRT TLS directory.
676 target_link_options(tiny_ga_tls PRIVATE /INCLUDE:_tls_used)
613 set_target_properties(tiny_ga_tls PROPERTIES 677 set_target_properties(tiny_ga_tls PROPERTIES
614 OUTPUT_NAME tiny_ga_tls 678 OUTPUT_NAME tiny_ga_tls
615 RUNTIME_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}" 679 RUNTIME_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}"
@@ -774,6 +838,17 @@ if(BUILD_TESTING)
774 set_target_properties(tiny_game_fixed PROPERTIES 838 set_target_properties(tiny_game_fixed PROPERTIES
775 RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$<CONFIG>" 839 RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$<CONFIG>"
776 ) 840 )
841 # The same game built with /GA, as a title's executable is: its thread_local reads go to module TLS index 0
842 # without _tls_index, and under gta6rt index 0 is gta6rt.exe's own (docs/boot_leads.md, BL-1).
843 add_executable(tiny_game_ga test/fixtures/tiny_game.cpp)
844 target_link_libraries(tiny_game_ga PRIVATE xgameruntime_stub)
845 target_compile_definitions(tiny_game_ga PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX _CRT_SECURE_NO_WARNINGS)
846 target_compile_options(tiny_game_ga PRIVATE /W4 /permissive- /utf-8 /EHsc /GA)
847 # /GA can remove the _tls_index reference that pulls in the CRT TLS directory.
848 target_link_options(tiny_game_ga PRIVATE /INCLUDE:_tls_used)
849 set_target_properties(tiny_game_ga PROPERTIES
850 RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$<CONFIG>"
851 )
777 add_executable(tiny_game_exit_code_test test/tiny_game_exit_code_test.cpp) 852 add_executable(tiny_game_exit_code_test test/tiny_game_exit_code_test.cpp)
778 target_compile_definitions(tiny_game_exit_code_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) 853 target_compile_definitions(tiny_game_exit_code_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
779 target_compile_options(tiny_game_exit_code_test PRIVATE /W4 /permissive- /utf-8) 854 target_compile_options(tiny_game_exit_code_test PRIVATE /W4 /permissive- /utf-8)
@@ -1163,6 +1238,7 @@ if(BUILD_TESTING)
1163 endif() 1238 endif()
1164 if(WIN32 AND TARGET acphal_test) 1239 if(WIN32 AND TARGET acphal_test)
1165 add_test(NAME acphal COMMAND acphal_test) 1240 add_test(NAME acphal COMMAND acphal_test)
1241 add_test(NAME acphal_noncached_only COMMAND acphal_test --noncached-only)
1166 endif() 1242 endif()
1167 if(WIN32 AND TARGET cpu_emulation_test) 1243 if(WIN32 AND TARGET cpu_emulation_test)
1168 add_test(NAME cpu_emulation COMMAND cpu_emulation_test) 1244 add_test(NAME cpu_emulation COMMAND cpu_emulation_test)
@@ -1182,6 +1258,9 @@ if(BUILD_TESTING)
1182 if(WIN32 AND TARGET winhttp_offline_test) 1258 if(WIN32 AND TARGET winhttp_offline_test)
1183 add_test(NAME winhttp_offline COMMAND winhttp_offline_test) 1259 add_test(NAME winhttp_offline COMMAND winhttp_offline_test)
1184 endif() 1260 endif()
1261 if(WIN32 AND TARGET ws2_offline_test)
1262 add_test(NAME ws2_offline COMMAND ws2_offline_test)
1263 endif()
1185 if(WIN32 AND TARGET com_shim_test) 1264 if(WIN32 AND TARGET com_shim_test)
1186 add_test(NAME com_shim COMMAND com_shim_test) 1265 add_test(NAME com_shim COMMAND com_shim_test)
1187 endif() 1266 endif()
@@ -1261,10 +1340,12 @@ if(BUILD_TESTING)
1261 add_test(NAME active_input COMMAND active_input_test) 1340 add_test(NAME active_input COMMAND active_input_test)
1262 if(WIN32 AND TARGET gameinput_test) 1341 if(WIN32 AND TARGET gameinput_test)
1263 add_test(NAME gameinput COMMAND gameinput_test) 1342 add_test(NAME gameinput COMMAND gameinput_test)
1343 add_test(NAME gameinput_script COMMAND gameinput_test --input-script)
1264 elseif(TARGET gta6rt) 1344 elseif(TARGET gta6rt)
1265 # Built without SDL3: listed as "Not Run (Disabled)" so it is visible that the shim was not tested. 1345 # Built without SDL3: listed as "Not Run (Disabled)" so it is visible that the shim was not tested.
1266 add_test(NAME gameinput COMMAND ${CMAKE_COMMAND} -E echo "built without SDL3") 1346 add_test(NAME gameinput COMMAND ${CMAKE_COMMAND} -E echo "built without SDL3")
1267 set_tests_properties(gameinput PROPERTIES DISABLED TRUE) 1347 add_test(NAME gameinput_script COMMAND ${CMAKE_COMMAND} -E echo "built without SDL3")
1348 set_tests_properties(gameinput gameinput_script PROPERTIES DISABLED TRUE)
1268 endif() 1349 endif()
1269 if(WIN32 AND TARGET gta6rt AND TARGET tiny_game) 1350 if(WIN32 AND TARGET gta6rt AND TARGET tiny_game)
1270 if(TARGET tiny_argv_default_a AND NOT CMAKE_CROSSCOMPILING) 1351 if(TARGET tiny_argv_default_a AND NOT CMAKE_CROSSCOMPILING)
@@ -1319,6 +1400,9 @@ if(BUILD_TESTING)
1319 # The opt-in checks, one test each: thread_local on the game's threads, a C++ exception caught inside the image. 1400 # The opt-in checks, one test each: thread_local on the game's threads, a C++ exception caught inside the image.
1320 add_test(NAME run_tiny_game_tls COMMAND gta6rt --run $<TARGET_FILE:tiny_game> -- hello 42 tls) 1401 add_test(NAME run_tiny_game_tls COMMAND gta6rt --run $<TARGET_FILE:tiny_game> -- hello 42 tls)
1321 add_test(NAME run_tiny_game_eh COMMAND gta6rt --run $<TARGET_FILE:tiny_game> -- hello 42 eh) 1402 add_test(NAME run_tiny_game_eh COMMAND gta6rt --run $<TARGET_FILE:tiny_game> -- hello 42 eh)
1403 # The /GA build of the same game: thread_local on the entry thread and on a thread it starts, through index-0
1404 # reads, while index 0 holds gta6rt.exe's own TLS.
1405 add_test(NAME run_tiny_game_ga_tls COMMAND gta6rt --run $<TARGET_FILE:tiny_game_ga> -- hello 42 tls)
1322 # BUILD-1457: the stack a game thread gets. gta6rt_stack reads SizeOfStackReserve from the built loader (nothing 1406 # BUILD-1457: the stack a game thread gets. gta6rt_stack reads SizeOfStackReserve from the built loader (nothing
1323 # is run); run_tiny_game_stack asks Windows, on the entry thread and on a thread created with dwStackSize 0. 1407 # is run); run_tiny_game_stack asks Windows, on the entry thread and on a thread created with dwStackSize 0.
1324 add_test(NAME gta6rt_stack COMMAND "${CMAKE_COMMAND}" 1408 add_test(NAME gta6rt_stack COMMAND "${CMAKE_COMMAND}"
@@ -1412,6 +1496,11 @@ if(TARGET Vulkan::Headers)
1412 add_executable(vk_shader_fma_test test/vk_shader_fma_test.cpp) 1496 add_executable(vk_shader_fma_test test/vk_shader_fma_test.cpp)
1413 target_link_libraries(vk_shader_fma_test PRIVATE Vulkan::Headers) 1497 target_link_libraries(vk_shader_fma_test PRIVATE Vulkan::Headers)
1414 add_test(NAME vk_shader_fma COMMAND vk_shader_fma_test) 1498 add_test(NAME vk_shader_fma COMMAND vk_shader_fma_test)
1499 add_executable(xdxr_builder_validation_test test/xdxr_builder_validation_test.cpp)
1500 target_link_libraries(xdxr_builder_validation_test PRIVATE Vulkan::Headers)
1501 if(BUILD_TESTING)
1502 add_test(NAME xdxr_builder_validation COMMAND xdxr_builder_validation_test)
1503 endif()
1415 # LEONIDA_VK_DEVICE names the GPU in every harness (docs/testing.md, "Choosing the GPU"): a filter that matches no 1504 # LEONIDA_VK_DEVICE names the GPU in every harness (docs/testing.md, "Choosing the GPU"): a filter that matches no
1416 # device fails the run in vk_descriptor_bench and vk_sandbox too, instead of testing another GPU (TEST-1141). 1505 # device fails the run in vk_descriptor_bench and vk_sandbox too, instead of testing another GPU (TEST-1141).
1417 find_package(Python3 COMPONENTS Interpreter QUIET) 1506 find_package(Python3 COMPONENTS Interpreter QUIET)
@@ -1612,6 +1701,18 @@ if(TARGET Vulkan::Headers)
1612 if(BUILD_TESTING) 1701 if(BUILD_TESTING)
1613 add_test(NAME vk_buffer_registration_oom COMMAND vk_buffer_registration_oom_test) 1702 add_test(NAME vk_buffer_registration_oom COMMAND vk_buffer_registration_oom_test)
1614 endif() 1703 endif()
1704 # VulkanContext::replay_.host_at resolves aliasing placed upload buffers across the full requested byte range.
1705 add_executable(vk_host_at_aliasing_test test/vk_host_at_aliasing_test.cpp)
1706 target_link_libraries(vk_host_at_aliasing_test PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS})
1707 if(WIN32)
1708 target_compile_definitions(vk_host_at_aliasing_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
1709 if(MSVC)
1710 target_compile_options(vk_host_at_aliasing_test PRIVATE /W4 /permissive- /EHsc /utf-8)
1711 endif()
1712 endif()
1713 if(BUILD_TESTING)
1714 add_test(NAME vk_host_at_aliasing COMMAND vk_host_at_aliasing_test)
1715 endif()
1615 # CPU-only: ScratchBuffers chunk alignment, retire/collect/forget, and spare cap (runtime/src/vulkan_scratch.h). 1716 # CPU-only: ScratchBuffers chunk alignment, retire/collect/forget, and spare cap (runtime/src/vulkan_scratch.h).
1616 add_executable(vulkan_scratch_test test/vulkan_scratch_test.cpp) 1717 add_executable(vulkan_scratch_test test/vulkan_scratch_test.cpp)
1617 target_link_libraries(vulkan_scratch_test PRIVATE Vulkan::Headers) 1718 target_link_libraries(vulkan_scratch_test PRIVATE Vulkan::Headers)
@@ -1622,6 +1723,22 @@ if(TARGET Vulkan::Headers)
1622 add_test(NAME vulkan_scratch COMMAND vulkan_scratch_test) 1723 add_test(NAME vulkan_scratch COMMAND vulkan_scratch_test)
1623 endif() 1724 endif()
1624 if(WIN32 AND BUILD_TESTING) 1725 if(WIN32 AND BUILD_TESTING)
1726 # Whole title-region import capability: one host allocation bound as a BDA buffer. The default case uses the
1727 # measured 185 MiB placeholder size. A machine that cannot import (no importable usage/handle, an import-budget
1728 # refusal, no host memory to commit it) exits 77 and is a reported capability result.
1729 add_executable(vk_host_region_import_test test/vk_host_region_import_test.cpp)
1730 target_link_libraries(vk_host_region_import_test PRIVATE Vulkan::Headers)
1731 target_compile_definitions(vk_host_region_import_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
1732 if(MSVC)
1733 target_compile_options(vk_host_region_import_test PRIVATE /W4 /permissive- /utf-8)
1734 endif()
1735 add_test(NAME vk_host_region_import COMMAND vk_host_region_import_test 185)
1736 set_tests_properties(vk_host_region_import PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120)
1737 # The same import under VK_LAYER_KHRONOS_validation with synchronization validation. The binary exits 77 when
1738 # the layer is not installed, so a machine without the SDK skips this variant instead of failing it.
1739 add_test(NAME vk_host_region_import_validation COMMAND vk_host_region_import_test 185)
1740 set_tests_properties(vk_host_region_import_validation PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120
1741 ENVIRONMENT "LEONIDA_VK_VALIDATION=1;VK_VALIDATE_SYNC=1")
1625 # VulkanPresenter tracker lock / failed-submit rollback and capture-buffer WAW synchronization. 1742 # VulkanPresenter tracker lock / failed-submit rollback and capture-buffer WAW synchronization.
1626 add_executable(vk_presenter_sync_test test/vk_presenter_sync_test.cpp) 1743 add_executable(vk_presenter_sync_test test/vk_presenter_sync_test.cpp)
1627 target_link_libraries(vk_presenter_sync_test PRIVATE Vulkan::Headers user32) 1744 target_link_libraries(vk_presenter_sync_test PRIVATE Vulkan::Headers user32)
@@ -1942,6 +2059,13 @@ if(TARGET Vulkan::Headers)
1942 target_compile_options(d3d12_b5g5r5a1_uav_test PRIVATE /W4 /permissive- /utf-8) 2059 target_compile_options(d3d12_b5g5r5a1_uav_test PRIVATE /W4 /permissive- /utf-8)
1943 add_test(NAME d3d12_b5g5r5a1_uav COMMAND d3d12_b5g5r5a1_uav_test) 2060 add_test(NAME d3d12_b5g5r5a1_uav COMMAND d3d12_b5g5r5a1_uav_test)
1944 set_tests_properties(d3d12_b5g5r5a1_uav PROPERTIES SKIP_RETURN_CODE 77) 2061 set_tests_properties(d3d12_b5g5r5a1_uav PROPERTIES SKIP_RETURN_CODE 77)
2062 # B4G4R4A4 render targets as RGBA8 images where no 4444 format is a colour attachment (NVIDIA).
2063 add_executable(d3d12_b4g4r4a4_target_test test/d3d12_b4g4r4a4_target_test.cpp)
2064 target_link_libraries(d3d12_b4g4r4a4_target_test PRIVATE gta6rt_d3d12_com d3d12 dxgi)
2065 target_compile_definitions(d3d12_b4g4r4a4_target_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
2066 target_compile_options(d3d12_b4g4r4a4_target_test PRIVATE /W4 /permissive- /utf-8)
2067 add_test(NAME d3d12_b4g4r4a4_target COMMAND d3d12_b4g4r4a4_target_test)
2068 set_tests_properties(d3d12_b4g4r4a4_target PROPERTIES SKIP_RETURN_CODE 77)
1945 add_executable(d3d12_srgb_uav_test test/d3d12_srgb_uav_test.cpp) 2069 add_executable(d3d12_srgb_uav_test test/d3d12_srgb_uav_test.cpp)
1946 target_link_libraries(d3d12_srgb_uav_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) 2070 target_link_libraries(d3d12_srgb_uav_test PRIVATE gta6rt_d3d12_com d3d12 dxgi)
1947 target_compile_definitions(d3d12_srgb_uav_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) 2071 target_compile_definitions(d3d12_srgb_uav_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
@@ -2135,6 +2259,17 @@ if(TARGET Vulkan::Headers)
2135 set_tests_properties(d3d12_indirect_dispatch_count PROPERTIES SKIP_RETURN_CODE 77) 2259 set_tests_properties(d3d12_indirect_dispatch_count PROPERTIES SKIP_RETURN_CODE 77)
2136 endif() 2260 endif()
2137 2261
2262 # The cache vk_pipeline_check saves has to hit on the runtime's device (docs/pipeline_check.md): the test
2263 # compiles an embedded synthetic compute shader through a same-named copy of the checker, then creates the
2264 # same pipeline on the runtime's device from the saved cache.
2265 add_executable(pipeline_cache_seed_test test/pipeline_cache_seed_test.cpp)
2266 add_dependencies(pipeline_cache_seed_test vk_pipeline_check)
2267 target_link_libraries(pipeline_cache_seed_test PRIVATE gta6rt_d3d12_com)
2268 target_compile_definitions(pipeline_cache_seed_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
2269 target_compile_options(pipeline_cache_seed_test PRIVATE /W4 /permissive- /utf-8)
2270 add_test(NAME pipeline_cache_seed COMMAND pipeline_cache_seed_test $<TARGET_FILE:vk_pipeline_check>)
2271 set_tests_properties(pipeline_cache_seed PROPERTIES SKIP_RETURN_CODE 77)
2272
2138 # What Close returns after one recorded call, against WARP; today's differences are listed in the test. 2273 # What Close returns after one recorded call, against WARP; today's differences are listed in the test.
2139 add_executable(d3d12_close_parity_test test/d3d12_close_parity_test.cpp) 2274 add_executable(d3d12_close_parity_test test/d3d12_close_parity_test.cpp)
2140 target_link_libraries(d3d12_close_parity_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) 2275 target_link_libraries(d3d12_close_parity_test PRIVATE gta6rt_d3d12_com d3d12 dxgi)
@@ -2182,7 +2317,8 @@ if(TARGET Vulkan::Headers)
2182 add_test(NAME d3d12_rgb9e5_rtv COMMAND d3d12_clear_test --rgb9e5) 2317 add_test(NAME d3d12_rgb9e5_rtv COMMAND d3d12_clear_test --rgb9e5)
2183 set_tests_properties(d3d12_rgb9e5_rtv PROPERTIES SKIP_RETURN_CODE 77) 2318 set_tests_properties(d3d12_rgb9e5_rtv PROPERTIES SKIP_RETURN_CODE 77)
2184 add_test(NAME d3d12_clear COMMAND d3d12_clear_test) 2319 add_test(NAME d3d12_clear COMMAND d3d12_clear_test)
2185 set_tests_properties(d3d12_clear PROPERTIES SKIP_RETURN_CODE 77) 2320 add_test(NAME d3d12_clear_restricted_depth COMMAND d3d12_clear_test --restricted-depth)
2321 set_tests_properties(d3d12_clear d3d12_clear_restricted_depth PROPERTIES SKIP_RETURN_CODE 77)
2186 2322
2187 # Synthetic typed-view readbacks against Windows WARP; run explicitly on a Vulkan GPU. 2323 # Synthetic typed-view readbacks against Windows WARP; run explicitly on a Vulkan GPU.
2188 add_executable(d3d12_typeless_rtv_test test/d3d12_typeless_rtv_test.cpp) 2324 add_executable(d3d12_typeless_rtv_test test/d3d12_typeless_rtv_test.cpp)
@@ -2295,6 +2431,15 @@ if(TARGET Vulkan::Headers)
2295 target_compile_definitions(d3d12_resource_desc_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) 2431 target_compile_definitions(d3d12_resource_desc_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
2296 target_compile_options(d3d12_resource_desc_test PRIVATE /W4 /permissive- /utf-8) 2432 target_compile_options(d3d12_resource_desc_test PRIVATE /W4 /permissive- /utf-8)
2297 add_test(NAME d3d12_resource_desc COMMAND d3d12_resource_desc_test) 2433 add_test(NAME d3d12_resource_desc COMMAND d3d12_resource_desc_test)
2434
2435 # Multi-viewport & multi-scissor rendering (RSSetViewports / RSSetScissorRects 1..16) against host D3D12.
2436 add_executable(d3d12_multi_viewport_test test/d3d12_multi_viewport_test.cpp)
2437 target_link_libraries(d3d12_multi_viewport_test PRIVATE gta6rt_d3d12_com d3d12 dxgi dxguid)
2438 target_compile_definitions(d3d12_multi_viewport_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
2439 target_compile_options(d3d12_multi_viewport_test PRIVATE /W4 /permissive- /utf-8)
2440 add_test(NAME d3d12_multi_viewport COMMAND d3d12_multi_viewport_test)
2441 set_tests_properties(d3d12_multi_viewport PROPERTIES SKIP_RETURN_CODE 77
2442 FAIL_REGULAR_EXPRESSION "Validation Error;VUID-")
2298 set_tests_properties(d3d12_resource_desc PROPERTIES SKIP_RETURN_CODE 77) 2443 set_tests_properties(d3d12_resource_desc PROPERTIES SKIP_RETURN_CODE 77)
2299 2444
2300 # Typeless depth-stencil textures without ALLOW_DEPTH_STENCIL, copied from a depth buffer, against WARP. 2445 # Typeless depth-stencil textures without ALLOW_DEPTH_STENCIL, copied from a depth buffer, against WARP.
@@ -3359,6 +3504,16 @@ if(TARGET Vulkan::Headers)
3359 endif() 3504 endif()
3360 endif() 3505 endif()
3361 add_test(NAME vk_queue_constructor_oom COMMAND vk_queue_constructor_oom_test) 3506 add_test(NAME vk_queue_constructor_oom COMMAND vk_queue_constructor_oom_test)
3507 # XDXR AccelerationStructurePostbuild flushes COMPUTE_SHADER_BIT -> HOST_BIT for readback visibility.
3508 add_executable(vk_xdxr_postbuild_readback_test test/vk_xdxr_postbuild_readback_test.cpp)
3509 target_link_libraries(vk_xdxr_postbuild_readback_test PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS})
3510 if(WIN32)
3511 target_compile_definitions(vk_xdxr_postbuild_readback_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
3512 if(MSVC)
3513 target_compile_options(vk_xdxr_postbuild_readback_test PRIVATE /W4 /permissive- /EHsc /utf-8)
3514 endif()
3515 endif()
3516 add_test(NAME vk_xdxr_postbuild_readback COMMAND vk_xdxr_postbuild_readback_test)
3362 endif() 3517 endif()
3363else() 3518else()
3364 include("${CMAKE_CURRENT_SOURCE_DIR}/cmake/vulkan_headers_missing.cmake") 3519 include("${CMAKE_CURRENT_SOURCE_DIR}/cmake/vulkan_headers_missing.cmake")
diff --git a/runtime/README.md b/runtime/README.md
index 61794a2c2..f30515a50 100644
--- a/runtime/README.md
+++ b/runtime/README.md
@@ -239,7 +239,7 @@ Current limits, by design:
239### What `xgameruntime.dll` reports: environment overrides 239### What `xgameruntime.dll` reports: environment overrides
240 240
241The `xgameruntime` shim (`shims/xgameruntime.cpp`) answers the title's questions about the console and its package 241The `xgameruntime` shim (`shims/xgameruntime.cpp`) answers the title's questions about the console and its package
242with fixed values. Five environment variables change an answer, for trying another of the title's code paths. Each 242with fixed values. Six environment variables change an answer, for trying another of the title's code paths. Each
243is read on every call, and a value that is empty or too long for its buffer is ignored. 243is read on every call, and a value that is empty or too long for its buffer is ignored.
244`tests/test_docs_env_vars.py` fails when the runtime or `make_game.py` reads a `LEONIDA_*` variable that no 244`tests/test_docs_env_vars.py` fails when the runtime or `make_game.py` reads a `LEONIDA_*` variable that no
245document names. 245document names.
@@ -251,6 +251,7 @@ document names.
251| `LEONIDA_PACKAGE_ID` | `LeonidaPackageIdentifier00000000` | The identifier `XPackageGetCurrentProcessPackageIdentifier` returns (up to 32 characters). It is also the one identifier `XPackageMount` refuses with `E_ACCESSDENIED`, as the game's own package. | 251| `LEONIDA_PACKAGE_ID` | `LeonidaPackageIdentifier00000000` | The identifier `XPackageGetCurrentProcessPackageIdentifier` returns (up to 32 characters). It is also the one identifier `XPackageMount` refuses with `E_ACCESSDENIED`, as the game's own package. |
252| `LEONIDA_CONTENT_PACKAGES` | unset | The content packages `XPackageMount` can mount: `id1=path1;id2=path2` (up to 1,023 characters). The mount path of a listed identifier is its path, as written; any other identifier is `ERROR_NOT_FOUND`, and a path longer than 259 characters is `ERROR_INSUFFICIENT_BUFFER`. | 252| `LEONIDA_CONTENT_PACKAGES` | unset | The content packages `XPackageMount` can mount: `id1=path1;id2=path2` (up to 1,023 characters). The mount path of a listed identifier is its path, as written; any other identifier is `ERROR_NOT_FOUND`, and a path longer than 259 characters is `ERROR_INSUFFICIENT_BUFFER`. |
253| `LEONIDA_PACKAGED` | `1` | `0`, or text that is not a number, makes `XPackageIsPackagedProcess` return false. Any other number keeps it true. | 253| `LEONIDA_PACKAGED` | `1` | `0`, or text that is not a number, makes `XPackageIsPackagedProcess` return false. Any other number keeps it true. |
254| `LEONIDA_TITLE_MEMORY_MB` | unset | Caps the title memory limit (in MiB, clamped to `2048..65536`) reported by both `XSystemGetAppMemoryUsageLimit` (`xgameruntime.cpp`) and `XMemGetWorkingSetStatistics` (`xmem.cpp`). Useful on 16 GB RAM / low-VRAM hosts to prevent oversized title pools; invalid or non-positive values are ignored and fall back to the host memory report. |
254 255
255The two serializer functions and `D3D12XboxCreateDevice` are the only `d3d12_xs` imports used by the 256The two serializer functions and `D3D12XboxCreateDevice` are the only `d3d12_xs` imports used by the
256shipped DLLs (measured; see `docs/design.md` and `docs/d3d12_vulkan.md`). The game executable's own 257shipped DLLs (measured; see `docs/design.md` and `docs/d3d12_vulkan.md`). The game executable's own
diff --git a/runtime/cmake/translator_deps.cmake b/runtime/cmake/translator_deps.cmake
index 93682b3f8..42be0f0e2 100644
--- a/runtime/cmake/translator_deps.cmake
+++ b/runtime/cmake/translator_deps.cmake
@@ -1,6 +1,6 @@
1# What the SPIR-V that test/shaders/build.py writes comes from, besides the .asm files: build.py and the modules it 1# The shader fixtures use test/shaders/build.py, its local imports and the scripts it runs (tools/rdna2spirv.py
2# imports, the scripts it runs (tools/rdna2spirv.py, and tools/vk_subgroup_info.py, whose answer picks 2# and tools/vk_subgroup_info.py, whose answer picks --bary-fallback). Track the shader-stage dependencies in
3# --bary-fallback), and every module rdna2spirv.py imports or file it reads (make_game.py's TRANSLATION_SOURCES). 3# make_game.py's TRANSLATION_SOURCES here too, including the native PSO catalog writer.
4# Every add_custom_command that runs build.py DEPENDS on this list, so an edit to a helper such as tools/spirv_asm.py 4# Every add_custom_command that runs build.py DEPENDS on this list, so an edit to a helper such as tools/spirv_asm.py
5# rebuilds the test shaders instead of leaving the last build's SPIR-V in place (BUILD-1064). 5# rebuilds the test shaders instead of leaving the last build's SPIR-V in place (BUILD-1064).
6# tests/test_cmake_translator_deps.py fails when an import is missing here or a build.py rule doesn't use the list. 6# tests/test_cmake_translator_deps.py fails when an import is missing here or a build.py rule doesn't use the list.
@@ -10,16 +10,20 @@ set(LEONIDA_TRANSLATOR_DEPS
10 ${_leonida_repo}/runtime/test/shaders/compute_fixture.py 10 ${_leonida_repo}/runtime/test/shaders/compute_fixture.py
11 ${_leonida_repo}/tools/bary_fallback_gs.py 11 ${_leonida_repo}/tools/bary_fallback_gs.py
12 ${_leonida_repo}/tools/cfg_structure.py 12 ${_leonida_repo}/tools/cfg_structure.py
13 ${_leonida_repo}/tools/file_mode.py
13 ${_leonida_repo}/tools/fssm_header.py 14 ${_leonida_repo}/tools/fssm_header.py
14 ${_leonida_repo}/tools/fssm_unpack.py 15 ${_leonida_repo}/tools/fssm_unpack.py
15 ${_leonida_repo}/tools/gfx10_formats.json 16 ${_leonida_repo}/tools/gfx10_formats.json
16 ${_leonida_repo}/tools/lane_masks.py 17 ${_leonida_repo}/tools/lane_masks.py
17 ${_leonida_repo}/tools/mc_command.py 18 ${_leonida_repo}/tools/mc_command.py
19 ${_leonida_repo}/tools/native_pso_hashes.py
18 ${_leonida_repo}/tools/rdna2_decode.py 20 ${_leonida_repo}/tools/rdna2_decode.py
19 ${_leonida_repo}/tools/rdna2_isa_tables.py 21 ${_leonida_repo}/tools/rdna2_isa_tables.py
20 ${_leonida_repo}/tools/rdna2spirv.py 22 ${_leonida_repo}/tools/rdna2spirv.py
21 ${_leonida_repo}/tools/replace_retry.py 23 ${_leonida_repo}/tools/replace_retry.py
22 ${_leonida_repo}/tools/report_paths.py 24 ${_leonida_repo}/tools/report_paths.py
25 ${_leonida_repo}/tools/shader_carve.py
26 ${_leonida_repo}/tools/shader_carve_accel.py
23 ${_leonida_repo}/tools/shader_ir.py 27 ${_leonida_repo}/tools/shader_ir.py
24 ${_leonida_repo}/tools/shader_meta.py 28 ${_leonida_repo}/tools/shader_meta.py
25 ${_leonida_repo}/tools/shader_stage_manifest.py 29 ${_leonida_repo}/tools/shader_stage_manifest.py
diff --git a/runtime/shims/acphal.cpp b/runtime/shims/acphal.cpp
index 5ead016d6..f1c33ddd9 100644
--- a/runtime/shims/acphal.cpp
+++ b/runtime/shims/acphal.cpp
@@ -1,10 +1,12 @@
1// acphal.dll: Audio Control Processor HAL. Scalable Hardware Audio Processing Engine 1// acphal.dll: Audio Control Processor HAL. Scalable Hardware Audio Processing Engine
2// (SHAPE) and APU (Audio Processing Unit) physical memory management for Xbox Series. 2// (SHAPE) and APU (Audio Processing Unit) physical memory management for Xbox Series.
3// 3//
4// On a PC there is no SHAPE/ACP hardware and APU physical memory does not exist. 4// Provides:
5// This shim creates the APU heap from process memory and manages allocations within it. 5// - A VirtualAlloc-backed APU heap (cached + non-cached) with 32-bit device addresses;
6// The SHAPE context arrays are allocated on the process heap; the ACP interface 6// - SHAPE context arrays sized to the documented GDK strides;
7// accepts and acknowledges commands to allow audio bring-up to proceed cleanly. 7// - The IAcpHal command and message queue (registration, completion, disconnect,
8// flowgraph acknowledgement, and APU notification word writes);
9// - A background XMA2 decoder pumping enabled SHAPE_XMA_CONTEXT output rings.
8// 10//
9// Signatures from the public GDK reference (devdocs.xbox.com): 11// Signatures from the public GDK reference (devdocs.xbox.com):
10// AcpHal, APU reference, SHAPE_CONTEXTS, APU_ADDRESS. 12// AcpHal, APU reference, SHAPE_CONTEXTS, APU_ADDRESS.
@@ -14,21 +16,37 @@
14 16
15#include <windows.h> 17#include <windows.h>
16 18
17#include <atomic> 19#include <algorithm>
18#include <array> 20#include <array>
21#include <atomic>
22#include <chrono>
23#include <climits>
24#include <condition_variable>
19#include <cstddef> 25#include <cstddef>
20#include <cstdint> 26#include <cstdint>
21#include <cstdio> 27#include <cstdio>
22#include <cstdlib> 28#include <cstdlib>
23#include <cstring> 29#include <cstring>
30#include <deque>
24#include <map> 31#include <map>
32#include <memory>
25#include <mutex> 33#include <mutex>
34#include <new>
35#include <optional>
26#include <set> 36#include <set>
37#include <shared_mutex>
38#include <stop_token>
27#include <string> 39#include <string>
40#include <string_view>
41#include <system_error>
42#include <thread>
28#include <vector> 43#include <vector>
29 44
30#include "shims.h" 45#include "shims.h"
31#include "startup_trace.h" 46#include "startup_trace.h"
47#if defined(LEONIDA_HAVE_XMA2_DECODER)
48#include "leonida_xma2_decoder.h"
49#endif
32 50
33namespace { 51namespace {
34 52
@@ -124,24 +142,7 @@ struct SHAPE_DMA_CONTEXT {
124static_assert(sizeof(SHAPE_DMA_CONTEXT) == 16, "SHAPE_DMA_CONTEXT is 16 bytes per GDK"); 142static_assert(sizeof(SHAPE_DMA_CONTEXT) == 16, "SHAPE_DMA_CONTEXT is 16 bytes per GDK");
125 143
126struct SHAPE_XMA_CONTEXT { 144struct SHAPE_XMA_CONTEXT {
127 uint32_t sizeRead0 : 12; 145 uint32_t words[16]; // See the shared word layout above the XMA engine.
128 uint32_t numLoops : 8;
129 uint32_t validBuffer : 2;
130 uint32_t sizeWrite : 5;
131 uint32_t offsetWrite : 5;
132 uint32_t sizeRead1 : 12;
133 uint32_t sequenceNumber : 12;
134 uint32_t stopSampleAddress : 8;
135 uint32_t subframeOffset : 4;
136 uint32_t reserved0 : 1;
137 uint32_t isLooping : 1;
138 uint32_t subframeSkip : 2;
139 uint32_t packetMetadata : 16;
140 uint32_t currentByteOffset : 26;
141 uint32_t reserved1 : 6;
142 uint32_t loopStartOffset : 26;
143 uint32_t loopEndOffset : 6;
144 uint32_t reserved[11]; // the GDK's 64-byte context: the published field list leaves one trailing word
145}; 146};
146static_assert(sizeof(SHAPE_XMA_CONTEXT) == 64, "SHAPE_XMA_CONTEXT is 64 bytes per GDK"); 147static_assert(sizeof(SHAPE_XMA_CONTEXT) == 64, "SHAPE_XMA_CONTEXT is 64 bytes per GDK");
147 148
@@ -194,21 +195,28 @@ static_assert(offsetof(SHAPE_CONTEXTS, xmaContextArray) == 0x38,
194 195
195// ---- Startup trace helper ---- 196// ---- Startup trace helper ----
196 197
197void trace_call(const char* api, const std::string& detail) { 198void trace_call(const char* api, std::string_view detail = {}) noexcept try {
198 if (!rt::startup_trace::enabled()) return; 199 if (!rt::startup_trace::enabled()) return;
199 static std::mutex mutex; 200 static std::mutex mutex;
200 static std::set<std::string> seen; 201 static std::set<std::string> seen;
201 { 202 {
202 const std::lock_guard lock(mutex); 203 const std::lock_guard lock(mutex);
203 if (!seen.insert(std::string(api) + detail).second) return; 204 if (!seen.insert(std::string(api).append(detail)).second) return;
204 } 205 }
205 rt::startup_trace::event("acphal", 206 rt::startup_trace::event("acphal",
206 std::string("\"api\":\"") + api + "\"" + detail); 207 (std::string("\"api\":\"") + api + "\"").append(detail));
208} catch (...) {
209 // Tracing cannot change the result of a guest-facing call.
207} 210}
208 211
209// ---- Genuine APU Heap Implementation ---- 212// ---- Genuine APU Heap Implementation ----
210 213
211constexpr uint32_t kApuBaseAddress = 0x40000000u; 214constexpr uint32_t kApuBaseAddress = 0x40000000u;
215constexpr uint64_t kApuRegionAlignment = 0x10000u;
216
217uint64_t align_apu_region(uint64_t size) {
218 return (size + kApuRegionAlignment - 1) & ~(kApuRegionAlignment - 1);
219}
212 220
213struct ApuRegion { 221struct ApuRegion {
214 void* base = nullptr; 222 void* base = nullptr;
@@ -241,6 +249,13 @@ struct ApuRegion {
241 return static_cast<uint8_t*>(base) + offset; 249 return static_cast<uint8_t*>(base) + offset;
242 } 250 }
243 251
252 uint8_t* span_from_offset(uint32_t offset, std::size_t len) const {
253 if (!base || len == 0 || offset >= size) return nullptr;
254 const uint64_t remaining = size - offset;
255 if (len > remaining) return nullptr;
256 return static_cast<uint8_t*>(base) + offset;
257 }
258
244 void* allocate(uint32_t alloc_size, uint32_t alignment, uint32_t* out_offset) { 259 void* allocate(uint32_t alloc_size, uint32_t alignment, uint32_t* out_offset) {
245 if (alloc_size == 0 || alignment == 0) return nullptr; 260 if (alloc_size == 0 || alignment == 0) return nullptr;
246 uint64_t at = 0; 261 uint64_t at = 0;
@@ -281,48 +296,667 @@ ApuRegion g_cached_heap;
281ApuRegion g_noncached_heap; 296ApuRegion g_noncached_heap;
282 297
283// Tracked SHAPE context arrays 298// Tracked SHAPE context arrays
284std::vector<void*> g_active_shape_arrays; 299struct ShapeArrayFree {
300 void operator()(void* array) const noexcept { std::free(array); }
301};
302
303using ShapeAllocation = std::array<std::unique_ptr<void, ShapeArrayFree>, 6>;
304
305std::mutex g_shape_mutex;
306std::vector<ShapeAllocation> g_shape_allocations;
307
308// Resolves a contiguous [apu, apu + len) byte range inside the APU heap.
309uint8_t* apu_span(uint32_t apu, std::size_t len) {
310 if (apu < kApuBaseAddress || len == 0) return nullptr;
311 std::lock_guard lock(g_apu_mutex);
312 const uint32_t offset = apu - kApuBaseAddress;
313 if (g_cached_heap.base && offset < g_cached_heap.size) {
314 return g_cached_heap.span_from_offset(offset, len);
315 }
316 if (g_noncached_heap.base) {
317 const uint64_t cached_span = align_apu_region(g_cached_heap.size);
318 if (offset >= cached_span && offset - cached_span < g_noncached_heap.size) {
319 return g_noncached_heap.span_from_offset(
320 static_cast<uint32_t>(offset - cached_span), len);
321 }
322 }
323 return nullptr;
324}
325
326// ---- ACP Command / Message Protocol Constants ----
327
328constexpr uint32_t kCmdLoadFlowgraph = 1;
329constexpr uint32_t kCmdRegisterMessages = 2;
330constexpr uint32_t kCmdUnregisterMessages = 3;
331constexpr uint32_t kCmdEnableXma = 5;
332constexpr uint32_t kCmdEnableXmas = 6;
333constexpr uint32_t kCmdDisableXma = 7;
334constexpr uint32_t kCmdDisableXmas = 8;
335constexpr uint32_t kCmdAdvanceXmaRead = 18;
336
337constexpr uint32_t kMsgFlowgraphCompleted = 0x02u;
338constexpr uint32_t kMsgCommandCompleted = 0x10u;
339constexpr uint32_t kMsgDisconnected = 0x80u;
340
341// 128 samples per audio frame at 48 kHz = 375 audio frames/second.
342constexpr uint64_t kAudioFramesPerSecond = 375;
343
344// ---- XMA2 Hardware Context Decoder Engine ----
345//
346// Each 64-byte SHAPE_XMA_CONTEXT holds 16 32-bit words shared with the title:
347// Word 0: input 0 packets (0..11), loop count (12..19, 255 = forever),
348// valid input bits (20..21), output ring blocks (22..26), write block (27..31).
349// Word 1: input 1 packets (0..11), loop end subframe (12..13), loop start skip subframes
350// (17..19), initial skip subframes (24..26), rate index (27..28: 24/32/44.1/48 kHz),
351// stereo (29), output writable (31).
352// Word 2: read bit offset (0..25), error status (26..30), error flag (31).
353// Word 3: loop start bit offset (0..25).
354// Word 4: loop end bit offset (0..25), current input buffer index (31).
355// Word 5: input 0 APU address.
356// Word 6: input 1 APU address.
357// Word 7: output ring APU address.
358// Word 8: overlap buffer APU address.
359// Word 9: output read block index (0..4).
360//
361// Packets are decoded by the Rust decoder in runtime/xma_decoder when CMake found cargo (LEONIDA_HAVE_XMA2_DECODER);
362// otherwise each packet becomes silence for its frame count. The read offset (word 2) and the loop points (words 3
363// and 4) are used per 2048-byte packet, so the loop-end subframe (word 1 bits 12..13) is not applied.
364
365constexpr std::size_t kXmaBlockBytes = 256;
366constexpr std::size_t kXmaSamplesPerBlock = kXmaBlockBytes / 2;
367constexpr std::size_t kXmaPacketBytes = 2048;
368constexpr std::size_t kXmaPacketBits = kXmaPacketBytes * 8;
369constexpr std::size_t kXmaSubframeSamples = 128;
370constexpr std::size_t kXmaFrameSamples = 512;
371constexpr uint32_t kXmaErrorInputInvalid = 4;
372
373#if defined(LEONIDA_HAVE_XMA2_DECODER)
374constexpr uint32_t kXmaRates[4] = {24000, 32000, 44100, 48000};
375struct Xma2DecoderFree {
376 void operator()(LeonidaXma2Decoder* d) const noexcept { leonida_xma2_decoder_destroy(d); }
377};
378struct Xma2PcmFree {
379 void operator()(LeonidaXma2PcmBlock* b) const noexcept { leonida_xma2_pcm_destroy(b); }
380};
381#endif
382
383struct XmaContextView {
384 uint32_t* words = nullptr;
385
386 uint32_t get(std::size_t index) const { return std::atomic_ref(words[index]).load(); }
387
388 uint32_t field(std::size_t index, uint32_t shift, uint32_t bits) const {
389 const uint32_t mask = (bits >= 32) ? 0xFFFFFFFFu : ((1u << bits) - 1u);
390 return (get(index) >> shift) & mask;
391 }
392
393 uint32_t set_field(std::size_t index, uint32_t shift, uint32_t bits, uint32_t value) const {
394 const uint32_t raw_mask = (bits >= 32) ? 0xFFFFFFFFu : ((1u << bits) - 1u);
395 const uint32_t mask = raw_mask << shift;
396 const uint32_t field_value = (value << shift) & mask;
397 std::atomic_ref word(words[index]);
398 uint32_t previous = word.load();
399 while (!word.compare_exchange_weak(previous, (previous & ~mask) | field_value)) {}
400 return previous;
401 }
402
403};
404
405struct XmaVoice {
406 explicit XmaVoice(uint32_t format_bits) : pcm(0), format(format_bits) {}
407 std::size_t channels() const { return 1u + (format >> 2); }
408 std::size_t queued_samples() const { return pcm.size() - pcm_read; }
409
410#if defined(LEONIDA_HAVE_XMA2_DECODER)
411 std::unique_ptr<LeonidaXma2Decoder, Xma2DecoderFree> decoder;
412#endif
413 std::vector<int16_t> pcm;
414 std::size_t pcm_read = 0;
415 std::size_t loop_skip = 0; // samples per channel to drop after a rewind
416 uint32_t format; // SHAPE word 1 bits 27..29, rate and channel layout
417 bool ended = false;
418};
419
420struct XmaVoiceSlot {
421 std::mutex mutex;
422 std::optional<XmaVoice> voice;
423};
424
425class XmaEngine {
426public:
427 ~XmaEngine() { unbind(); }
428
429 void bind(SHAPE_XMA_CONTEXT* array, uint32_t count) {
430 // Construct with a size so MSVC's Debug iterator allocations can also fail
431 // through this call instead of the noexcept default constructor.
432 std::vector<std::unique_ptr<XmaVoiceSlot>> slots(count);
433 for (auto& slot : slots) slot = std::make_unique<XmaVoiceSlot>();
434 unbind();
435 std::unique_lock lock(table_mutex_);
436 array_ = array;
437 voices_.swap(slots);
438 }
439
440 void unbind() {
441 {
442 std::unique_lock lock(table_mutex_);
443 array_ = nullptr;
444 voices_.clear();
445 active_count_.store(0, std::memory_order_relaxed);
446 }
447 // Once detached, commands cannot start a worker for this table.
448 stop_worker();
449 }
450
451 bool handle_command(uint32_t command, const void* config) {
452 auto read_word = [config](std::size_t index) -> uint32_t {
453 if (!config) return 0u;
454 uint32_t value = 0;
455 std::memcpy(&value, static_cast<const uint8_t*>(config) + index * sizeof(uint32_t),
456 sizeof(uint32_t));
457 return value;
458 };
459
460 switch (command) {
461 case kCmdEnableXma:
462 if (config) enable(read_word(0));
463 return true;
464 case kCmdDisableXma:
465 if (config) disable(read_word(0));
466 return true;
467 case kCmdEnableXmas:
468 case kCmdDisableXmas: {
469 std::shared_lock lock(table_mutex_);
470 const std::size_t count = voices_.size();
471 lock.unlock();
472 if (!config) return true;
473 for (std::size_t i = 0; i < count; ++i) {
474 const uint32_t bits = read_word(i / 32);
475 if ((bits & (1u << (i % 32))) != 0) {
476 if (command == kCmdEnableXmas) {
477 enable(static_cast<uint32_t>(i));
478 } else {
479 disable(static_cast<uint32_t>(i));
480 }
481 }
482 }
483 return true;
484 }
485 case kCmdAdvanceXmaRead:
486 if (config) advance_read(read_word(0), read_word(1));
487 return true;
488 default:
489 return false;
490 }
491 }
492
493 void enable(uint32_t index) {
494 std::shared_lock table_lock(table_mutex_);
495 XmaContextView ctx = context_locked(index);
496 if (!ctx.words) return;
497
498 {
499 std::lock_guard slot_lock(voices_[index]->mutex);
500 auto& voice = voices_[index]->voice;
501 const uint32_t format = ctx.field(1, 27, 3);
502 // The worker cannot access the voice until the slot is unlocked.
503 ensure_worker_and_wake();
504 if (!voice) {
505 voice.emplace(format);
506 active_count_.fetch_add(1, std::memory_order_relaxed);
507 } else if (voice->format != format) {
508 voice->pcm.clear();
509 voice->pcm_read = 0;
510 voice->loop_skip = 0;
511 voice->format = format;
512#if defined(LEONIDA_HAVE_XMA2_DECODER)
513 voice->decoder.reset();
514#endif
515 }
516 voice->ended = false;
517 ctx.set_field(2, 26, 6, 0);
518 }
519 }
520
521 void disable(uint32_t index) {
522 std::shared_lock table_lock(table_mutex_);
523 if (index >= voices_.size()) return;
524 std::lock_guard slot_lock(voices_[index]->mutex);
525 if (voices_[index]->voice.has_value()) {
526 voices_[index]->voice.reset();
527 active_count_.fetch_sub(1, std::memory_order_relaxed);
528 }
529 }
530
531 void advance_read(uint32_t index, uint32_t blocks) {
532 std::shared_lock table_lock(table_mutex_);
533 XmaContextView ctx = context_locked(index);
534 if (!ctx.words) return;
535
536 bool wake = false;
537 {
538 std::lock_guard slot_lock(voices_[index]->mutex);
539 const uint32_t size = ctx.field(0, 22, 5);
540 if (size == 0) return;
541 const uint32_t read = (ctx.field(9, 0, 5) + blocks % size) % size;
542 ctx.set_field(9, 0, 5, read);
543 if (blocks > 0) {
544 ctx.set_field(1, 31, 1, 1);
545 }
546 wake = voices_[index]->voice.has_value();
547 }
548 if (wake) ensure_worker_and_wake();
549 }
550
551private:
552 XmaContextView context_locked(uint32_t index) const {
553 if (!array_ || index >= voices_.size()) return {};
554 return XmaContextView{array_[index].words};
555 }
556
557 // Appends interleaved s16 for one 2048-byte packet. Without the Rust decoder, or when it
558 // fails, the packet becomes silence for its frame count (header bits 26..31) so timing holds.
559 static void decode_packet(XmaVoice& voice, const uint8_t* bytes) {
560 const std::size_t channels = voice.channels();
561#if defined(LEONIDA_HAVE_XMA2_DECODER)
562 if (!voice.decoder) {
563 LeonidaXma2Decoder* raw = nullptr;
564 if (leonida_xma2_decoder_create_hardware(kXmaRates[voice.format & 3u],
565 static_cast<uint32_t>(channels), &raw) == LEONIDA_XMA2_OK) {
566 voice.decoder.reset(raw);
567 }
568 }
569 if (voice.decoder) {
570 LeonidaXma2PcmBlock* raw = nullptr;
571 if (leonida_xma2_decode_buffer(voice.decoder.get(), bytes, kXmaPacketBytes, &raw) == LEONIDA_XMA2_OK) {
572 const std::unique_ptr<LeonidaXma2PcmBlock, Xma2PcmFree> block(raw);
573 const int16_t* samples = leonida_xma2_pcm_data(block.get());
574 const std::size_t count = leonida_xma2_pcm_sample_count(block.get());
575 if (count != 0) voice.pcm.insert(voice.pcm.end(), samples, samples + count);
576 return;
577 }
578 voice.decoder.reset(); // Resume with a clean state after replacing a packet with silence.
579 }
580#endif
581 voice.pcm.resize(voice.pcm.size() + static_cast<std::size_t>(bytes[0] >> 2) * kXmaFrameSamples * channels);
582 }
583
584 // Decodes the packet at the read offset of the current input buffer and queues its PCM.
585 // Offsets and loop points are used per packet: a loop plays its end packet in full and
586 // restarts at the start of the packet holding the loop start.
587 static bool decode_one_packet(XmaContextView ctx, XmaVoice& voice) {
588 if (voice.ended) return false;
589
590 const std::size_t channels = voice.channels();
591 uint32_t current = ctx.field(4, 31, 1);
592 const uint32_t valid = ctx.field(0, 20, 2);
593
594 if (valid == 0) {
595 voice.ended = true;
596 ctx.set_field(2, 26, 6, kXmaErrorInputInvalid | 32u);
597 return voice.queued_samples() != 0;
598 }
599 if ((valid & (1u << current)) == 0) {
600 current ^= 1u;
601 ctx.set_field(4, 31, 1, current);
602 }
603
604 const uint32_t address = (current == 0) ? ctx.get(5) : ctx.get(6);
605 const std::size_t packets = (current == 0) ? ctx.field(0, 0, 12) : ctx.field(1, 0, 12);
606 const std::size_t packet = ctx.field(2, 0, 26) / kXmaPacketBits;
607 const uint8_t* data = apu_span(address & ~0x7FFu, packets * kXmaPacketBytes);
608 if (!data || packet >= packets) {
609 finish_input(ctx, current, packet >= packets ? packet - packets : 0);
610 return true;
611 }
612
613 const uint8_t* packet_data = data + packet * kXmaPacketBytes;
614 const uint8_t packet_skip = packet_data[3];
615 // Decoding is only requested when less than a ring block remains. Keep that
616 // tail and reuse the packet storage as the voice consumes subsequent packets.
617 voice.pcm.erase(voice.pcm.begin(), voice.pcm.begin() + static_cast<std::ptrdiff_t>(voice.pcm_read));
618 voice.pcm_read = 0;
619 const std::size_t packet_start = voice.pcm.size();
620 decode_packet(voice, packet_data);
621 const std::size_t packet_samples = voice.pcm.size() - packet_start;
622 const std::size_t subframe_samples = kXmaSubframeSamples * channels;
623 const std::size_t initial_skip = ctx.field(1, 24, 3);
624 const std::size_t skipped_subframes = std::min(initial_skip, packet_samples / subframe_samples);
625 const std::size_t initial_samples = skipped_subframes * subframe_samples;
626 const std::size_t loop_samples = std::min(voice.loop_skip * channels, packet_samples - initial_samples);
627 const std::size_t skip_samples = initial_samples + loop_samples;
628 if (skip_samples != 0) {
629 const auto first = voice.pcm.begin() + static_cast<std::ptrdiff_t>(packet_start);
630 voice.pcm.erase(first, first + static_cast<std::ptrdiff_t>(skip_samples));
631 }
632 // Update the context only after the PCM append succeeds.
633 if (skipped_subframes != 0) {
634 ctx.set_field(1, 24, 3, static_cast<uint32_t>(initial_skip - skipped_subframes));
635 }
636 voice.loop_skip -= loop_samples / channels;
637
638 // XMA2 packet headers link packets from the same stream; 0xff ends the chain.
639 std::size_t next = packet_skip == 0xFFu ? packets : packet + 1 + packet_skip;
640 const uint32_t loops = ctx.field(0, 12, 8);
641 const std::size_t loop_end = ctx.field(4, 0, 26);
642 if (loops > 0 && loop_end != 0 && packet == loop_end / kXmaPacketBits) {
643 next = ctx.field(3, 0, 26) / kXmaPacketBits;
644 voice.loop_skip = static_cast<std::size_t>(ctx.field(1, 17, 3)) * kXmaSubframeSamples;
645#if defined(LEONIDA_HAVE_XMA2_DECODER)
646 // A frame spilling out of the loop-end packet does not continue in the loop-start packet:
647 // start a fresh decoder there rather than decode the spliced bits.
648 voice.decoder.reset();
649#endif
650 if (loops != 255u) ctx.set_field(0, 12, 8, loops - 1u);
651 }
652 if (next >= packets) {
653 finish_input(ctx, current, next - packets);
654 } else {
655 ctx.set_field(2, 0, 26, static_cast<uint32_t>(next * kXmaPacketBits));
656 }
657 return true;
658 }
659
660 static void finish_input(XmaContextView ctx, uint32_t current,
661 std::size_t skip_packets) {
662 // Publish the next offset before telling the title it can refill this input.
663 ctx.set_field(2, 0, 26, static_cast<uint32_t>(skip_packets * kXmaPacketBits));
664 const uint32_t other = 1u - current;
665 const uint32_t retired = ctx.set_field(0, 20 + current, 1, 0);
666 // Take the other input if it was queued at retirement. Otherwise a double
667 // refill of the empty pair starts at input 0. A lone input can still run.
668 ctx.set_field(4, 31, 1, (retired & (1u << (20 + other))) != 0 ? other : 0u);
669 }
670
671 static void pump_voice(XmaContextView ctx, XmaVoice& voice) {
672 const uint32_t size = ctx.field(0, 22, 5);
673 if (size == 0 || ctx.field(1, 31, 1) == 0) return;
674 auto* ring = apu_span(ctx.get(7), size * kXmaBlockBytes);
675 if (!ring) return;
676
677 for (uint32_t blocks = 0; blocks < size && ctx.field(1, 31, 1) == 1; ++blocks) {
678 int decode_guard = 0;
679 while (voice.queued_samples() < kXmaSamplesPerBlock && decode_guard++ < 16) {
680 if (!decode_one_packet(ctx, voice)) break;
681 }
682 if (voice.queued_samples() == 0) return;
683
684 const uint32_t write = ctx.field(0, 27, 5) % size;
685 uint8_t* out = ring + write * kXmaBlockBytes;
686
687 for (std::size_t i = 0; i < kXmaSamplesPerBlock; ++i) {
688 int16_t sample = 0;
689 if (voice.pcm_read != voice.pcm.size()) {
690 sample = voice.pcm[voice.pcm_read++];
691 }
692 const uint16_t raw = static_cast<uint16_t>(sample);
693 out[2 * i] = static_cast<uint8_t>(raw & 0xFFu);
694 out[2 * i + 1] = static_cast<uint8_t>((raw >> 8) & 0xFFu);
695 }
696
697 const uint32_t next_write = (write + 1u) % size;
698 ctx.set_field(0, 27, 5, next_write);
699 if (next_write == ctx.field(9, 0, 5) % size) {
700 ctx.set_field(1, 31, 1, 0);
701 }
702 }
703 }
704
705 void pump_all() {
706 std::shared_lock table_lock(table_mutex_);
707 if (!array_) return;
708 for (std::size_t i = 0; i < voices_.size(); ++i) {
709 std::lock_guard slot_lock(voices_[i]->mutex);
710 auto& voice = voices_[i]->voice;
711 if (!voice) continue;
712 auto ctx = context_locked(static_cast<uint32_t>(i));
713 try {
714 pump_voice(ctx, *voice);
715 } catch (const std::bad_alloc&) {
716 // Only this voice failed. Retire it and allow the title to enable it again.
717 voice.reset();
718 active_count_.fetch_sub(1, std::memory_order_relaxed);
719 ctx.set_field(2, 26, 6, kXmaErrorInputInvalid | 32u);
720 }
721 }
722 }
723
724 void ensure_worker_and_wake() {
725 std::lock_guard lock(worker_mutex_);
726 if (!worker_.joinable()) {
727 worker_ = std::jthread([this](std::stop_token stop) { worker_loop(stop); });
728 }
729 wake_requested_ = true;
730 worker_cv_.notify_one();
731 }
732
733 // Each worker owns its stop_token, so a stop only ever reaches the thread it was
734 // sent to; a worker started after this call is unaffected by it.
735 void stop_worker() {
736 std::jthread to_join;
737 {
738 std::lock_guard lock(worker_mutex_);
739 if (!worker_.joinable()) return;
740 worker_.request_stop();
741 worker_cv_.notify_all();
742 to_join = std::move(worker_);
743 }
744 if (to_join.joinable()) to_join.join();
745 }
746
747 void worker_loop(std::stop_token stop) {
748 for (;;) {
749 {
750 std::unique_lock lock(worker_mutex_);
751 if (stop.stop_requested()) return;
752 if (active_count_.load(std::memory_order_relaxed) == 0 && !wake_requested_) {
753 worker_cv_.wait(lock, stop, [this]() { return wake_requested_; });
754 if (stop.stop_requested()) return;
755 }
756 wake_requested_ = false;
757 }
758
759 pump_all();
760
761 std::unique_lock lock(worker_mutex_);
762 if (stop.stop_requested()) return;
763 if (!wake_requested_ && active_count_.load(std::memory_order_relaxed) > 0) {
764 // One 256-byte output block lasts ~2.67 ms at 48 kHz mono.
765 worker_cv_.wait_for(lock, stop, std::chrono::milliseconds(2),
766 [this]() { return wake_requested_; });
767 }
768 }
769 }
770
771 mutable std::shared_mutex table_mutex_;
772 SHAPE_XMA_CONTEXT* array_ = nullptr;
773 std::vector<std::unique_ptr<XmaVoiceSlot>> voices_;
774 std::atomic<uint32_t> active_count_{0};
775
776 std::mutex worker_mutex_;
777 std::condition_variable_any worker_cv_;
778 std::jthread worker_;
779 bool wake_requested_ = false;
780};
781
782XmaEngine g_xma_engine;
285 783
286// ---- IAcpHal Interface Implementation ---- 784// ---- IAcpHal Interface Implementation ----
287 785
288struct AcpHalImpl { 786#pragma pack(push, 1)
787struct AcpMessage {
788 uint32_t kind = 0;
789 uint32_t dropped = 0;
790 uint32_t usec = 0;
791 uint8_t data[16]{};
792};
793#pragma pack(pop)
794static_assert(sizeof(AcpMessage) == 28, "AcpMessage is 28 bytes");
795
796void write_u32_le(uint8_t* dst, uint32_t value) {
797 dst[0] = static_cast<uint8_t>(value & 0xFFu);
798 dst[1] = static_cast<uint8_t>((value >> 8) & 0xFFu);
799 dst[2] = static_cast<uint8_t>((value >> 16) & 0xFFu);
800 dst[3] = static_cast<uint8_t>((value >> 24) & 0xFFu);
801}
802
803void write_u64_le(uint8_t* dst, uint64_t value) {
804 write_u32_le(dst, static_cast<uint32_t>(value & 0xFFFFFFFFu));
805 write_u32_le(dst + 4, static_cast<uint32_t>(value >> 32));
806}
807
808struct IAcpHal {
809 virtual HRESULT __stdcall connect(uint32_t commands, uint32_t messages) = 0;
810 virtual HRESULT __stdcall disconnect() = 0;
811 virtual HRESULT __stdcall submit_command(uint32_t cmd, uint64_t id, uint32_t frame,
812 const void* config, uint32_t notification) = 0;
813 virtual uint32_t __stdcall pop_message(void* out) = 0;
814 virtual uint32_t __stdcall get_num_messages() = 0;
815 virtual HRESULT __stdcall release() = 0;
816};
817
818struct AcpHalImpl final : IAcpHal {
819 std::mutex mutex_;
820 bool connected_ = false;
821 uint32_t mask_ = 0;
822 std::deque<AcpMessage> messages_;
823 std::size_t capacity_ = 0;
824 uint32_t dropped_ = 0;
825 std::chrono::steady_clock::time_point since_ = std::chrono::steady_clock::now();
826
827 uint64_t elapsed_usec_locked() const {
828 const auto dt = std::chrono::steady_clock::now() - since_;
829 return static_cast<uint64_t>(
830 std::chrono::duration_cast<std::chrono::microseconds>(dt).count());
831 }
832
833 uint32_t audio_frame_locked() const {
834 return static_cast<uint32_t>((elapsed_usec_locked() * kAudioFramesPerSecond) / 1000000ull);
835 }
836
837 void post_locked(uint32_t kind, const uint8_t* payload, std::size_t len) {
838 if ((mask_ & kind) == 0) return;
839 if (messages_.size() >= capacity_) {
840 if (dropped_ < UINT32_MAX) ++dropped_;
841 return;
842 }
843 AcpMessage msg{};
844 msg.kind = kind;
845 msg.dropped = dropped_;
846 msg.usec = static_cast<uint32_t>(elapsed_usec_locked());
847 if (payload && len > 0) {
848 std::memcpy(msg.data, payload, std::min(len, sizeof(msg.data)));
849 }
850 try {
851 messages_.push_back(msg);
852 dropped_ = 0;
853 } catch (const std::bad_alloc&) {
854 if (dropped_ < UINT32_MAX) ++dropped_;
855 }
856 }
857
289 // Slot 0: Connect (called at boot with (0x1000, 0x1000), result checked) 858 // Slot 0: Connect (called at boot with (0x1000, 0x1000), result checked)
290 virtual HRESULT __stdcall connect(uint32_t, uint32_t) { 859 HRESULT __stdcall connect(uint32_t commands, uint32_t messages) override {
291 trace_call("AcpHal::Connect", ""); 860 trace_call("AcpHal::Connect", "");
861 if (commands == 0) return E_INVALIDARG;
862 std::lock_guard lock(mutex_);
863 connected_ = true;
864 capacity_ = messages;
292 return S_OK; 865 return S_OK;
293 } 866 }
294 867
295 // Slot 1: Disconnect (called at shutdown) 868 // Slot 1: Disconnect (called at shutdown)
296 virtual HRESULT __stdcall disconnect() { 869 HRESULT __stdcall disconnect() override {
297 trace_call("AcpHal::Disconnect", ""); 870 trace_call("AcpHal::Disconnect", "");
871 std::lock_guard lock(mutex_);
872 if (!connected_) return E_FAIL;
873 post_locked(kMsgDisconnected, nullptr, 0);
874 connected_ = false;
298 return S_OK; 875 return S_OK;
299 } 876 }
300 877
301 // Slot 2: SubmitCommand 878 // Slot 2: SubmitCommand
302 // Critical: The title calls slot 2 as (2, 0xf0f0f0f0, -1, config, 0) and 879 // Acknowledges command completion, updates registered message masks, dispatches
303 // a negative result triggers a fatal int3 kernel panic (+0x43ad94e). 880 // XMA voice commands, and writes any requested APU notification word.
304 virtual HRESULT __stdcall submit_command(uint32_t cmd, uint32_t d1, uint32_t d2, 881 HRESULT __stdcall submit_command(uint32_t cmd, uint64_t id, uint32_t frame,
305 const void* config, uint32_t d3) { 882 const void* config, uint32_t notification) override try {
306 (void)cmd; 883 (void)frame;
307 (void)d1; 884 auto read_word = [config](std::size_t index) -> uint32_t {
308 (void)d2; 885 if (!config) return 0u;
309 (void)config; 886 uint32_t value = 0;
310 (void)d3; 887 std::memcpy(&value, static_cast<const uint8_t*>(config) + index * sizeof(uint32_t),
311 static std::atomic<bool> warned{false}; 888 sizeof(uint32_t));
312 if (!warned.exchange(true, std::memory_order_relaxed)) { 889 return value;
313 std::fprintf(stderr, 890 };
314 "[rt] acphal: command accepted and dropped: no audio DSP hardware on PC\n"); 891
892 const bool handled_xma = g_xma_engine.handle_command(cmd, config);
893 {
894 std::lock_guard lock(mutex_);
895 if (!handled_xma) {
896 switch (cmd) {
897 case kCmdRegisterMessages:
898 mask_ |= read_word(0);
899 break;
900 case kCmdUnregisterMessages:
901 mask_ &= ~read_word(0);
902 break;
903 case kCmdLoadFlowgraph: {
904 uint8_t payload[4];
905 write_u32_le(payload, read_word(1));
906 post_locked(kMsgFlowgraphCompleted, payload, sizeof(payload));
907 break;
908 }
909 default:
910 break;
911 }
912 }
913 if (id != 0) {
914 uint8_t done[16];
915 write_u32_le(done, cmd);
916 write_u64_le(done + 4, id);
917 write_u32_le(done + 12, audio_frame_locked());
918 post_locked(kMsgCommandCompleted, done, sizeof(done));
919 }
920 }
921
922 if (notification != 0) {
923 if (uint8_t* word_bytes = apu_span(notification, sizeof(uint32_t))) {
924 if ((reinterpret_cast<uintptr_t>(word_bytes) & 3u) == 0) {
925 *reinterpret_cast<volatile uint32_t*>(word_bytes) = 1u;
926 } else {
927 static constexpr uint8_t kOneLe[4] = {1, 0, 0, 0};
928 volatile uint8_t* dst = word_bytes;
929 for (std::size_t i = 0; i < 4; ++i) dst[i] = kOneLe[i];
930 }
931 }
315 } 932 }
933
316 trace_call("AcpHal::SubmitCommand", ""); 934 trace_call("AcpHal::SubmitCommand", "");
317 return S_OK; 935 return S_OK;
936 } catch (const std::bad_alloc&) {
937 return E_OUTOFMEMORY;
938 } catch (const std::system_error&) {
939 return E_FAIL;
318 } 940 }
319 941
320 // Slots 3 and 4: PopMessage and GetNumMessages (message polling, not called by title) 942 // Slot 3: PopMessage — returns 0 without touching `out` when the queue is empty.
321 virtual uint32_t __stdcall pop_message() { return 0; } 943 uint32_t __stdcall pop_message(void* out) override {
322 virtual uint32_t __stdcall get_num_messages() { return 0; } 944 std::lock_guard lock(mutex_);
945 if (messages_.empty()) return 0u;
946 const AcpMessage msg = messages_.front();
947 messages_.pop_front();
948 if (out) std::memcpy(out, &msg, sizeof(msg));
949 return 1u;
950 }
951
952 // Slot 4: GetNumMessages
953 uint32_t __stdcall get_num_messages() override {
954 std::lock_guard lock(mutex_);
955 return static_cast<uint32_t>(messages_.size());
956 }
323 957
324 // Slot 5: Release 958 // Slot 5: Release
325 virtual HRESULT __stdcall release() { 959 HRESULT __stdcall release() override {
326 trace_call("AcpHal::Release", ""); 960 trace_call("AcpHal::Release", "");
327 delete this; 961 delete this;
328 return S_OK; 962 return S_OK;
@@ -333,7 +967,12 @@ struct AcpHalImpl {
333 967
334HRESULT __stdcall AcpHalCreate(void** ppAcpHal) { 968HRESULT __stdcall AcpHalCreate(void** ppAcpHal) {
335 if (!ppAcpHal) return E_POINTER; 969 if (!ppAcpHal) return E_POINTER;
336 *ppAcpHal = new AcpHalImpl(); 970 *ppAcpHal = nullptr;
971 try {
972 *ppAcpHal = new AcpHalImpl();
973 } catch (const std::bad_alloc&) {
974 return E_OUTOFMEMORY;
975 }
337 trace_call("AcpHalCreate", ""); 976 trace_call("AcpHalCreate", "");
338 return S_OK; 977 return S_OK;
339} 978}
@@ -343,63 +982,79 @@ HRESULT __stdcall AcpHalCreate(void** ppAcpHal) {
343HRESULT __stdcall AcpHalAllocateShapeContexts(SHAPE_CONTEXTS* ctx) { 982HRESULT __stdcall AcpHalAllocateShapeContexts(SHAPE_CONTEXTS* ctx) {
344 if (!ctx) return E_POINTER; 983 if (!ctx) return E_POINTER;
345 984
346 std::lock_guard lock(g_apu_mutex); 985 std::lock_guard lock(g_shape_mutex);
347 986
348 auto alloc_array = [](uint32_t count, size_t elem_size) -> void* { 987 ShapeAllocation pending{};
988 std::size_t array_index = 0;
989 auto alloc_array = [&](uint32_t count, size_t elem_size) -> void* {
349 if (count == 0) return nullptr; 990 if (count == 0) return nullptr;
350 void* ptr = std::calloc(count, elem_size); 991 void* ptr = std::calloc(count, elem_size);
351 if (ptr) g_active_shape_arrays.push_back(ptr); 992 if (!ptr) throw std::bad_alloc();
993 pending[array_index++].reset(ptr);
352 return ptr; 994 return ptr;
353 }; 995 };
354 996
355 ctx->srcContextArray = static_cast<SHAPE_SRC_CONTEXT*>( 997 SHAPE_CONTEXTS result{};
356 alloc_array(ctx->numSrcContexts, sizeof(SHAPE_SRC_CONTEXT))); 998 result.numSrcContexts = ctx->numSrcContexts;
357 ctx->eqCompContextArray = static_cast<SHAPE_EQCOMP_CONTEXT*>( 999 result.numEqCompContexts = ctx->numEqCompContexts;
358 alloc_array(ctx->numEqCompContexts, sizeof(SHAPE_EQCOMP_CONTEXT))); 1000 result.numFiltVolContexts = ctx->numFiltVolContexts;
359 ctx->filtVolContextArray = static_cast<SHAPE_FILTVOL_CONTEXT*>( 1001 result.numDmaContexts = ctx->numDmaContexts;
360 alloc_array(ctx->numFiltVolContexts, sizeof(SHAPE_FILTVOL_CONTEXT))); 1002 result.numXmaContexts = ctx->numXmaContexts;
361 ctx->dmaContextArray = static_cast<SHAPE_DMA_CONTEXT*>( 1003 result.numPcmContexts = ctx->numPcmContexts;
362 alloc_array(ctx->numDmaContexts, sizeof(SHAPE_DMA_CONTEXT))); 1004 try {
363 ctx->xmaContextArray = static_cast<SHAPE_XMA_CONTEXT*>( 1005 result.srcContextArray = static_cast<SHAPE_SRC_CONTEXT*>(
364 alloc_array(ctx->numXmaContexts, sizeof(SHAPE_XMA_CONTEXT))); 1006 alloc_array(result.numSrcContexts, sizeof(SHAPE_SRC_CONTEXT)));
365 ctx->pcmContextArray = static_cast<SHAPE_PCM_CONTEXT*>( 1007 result.eqCompContextArray = static_cast<SHAPE_EQCOMP_CONTEXT*>(
366 alloc_array(ctx->numPcmContexts, sizeof(SHAPE_PCM_CONTEXT))); 1008 alloc_array(result.numEqCompContexts, sizeof(SHAPE_EQCOMP_CONTEXT)));
367 1009 result.filtVolContextArray = static_cast<SHAPE_FILTVOL_CONTEXT*>(
368 // On PC there is no physical APU address translation for host context arrays; 1010 alloc_array(result.numFiltVolContexts, sizeof(SHAPE_FILTVOL_CONTEXT)));
369 // assign unique synthetic addresses from the APU base. 1011 result.dmaContextArray = static_cast<SHAPE_DMA_CONTEXT*>(
370 ctx->apuSrcContextArray = {ctx->srcContextArray ? kApuBaseAddress : 0}; 1012 alloc_array(result.numDmaContexts, sizeof(SHAPE_DMA_CONTEXT)));
371 ctx->apuEqCompContextArray = {ctx->eqCompContextArray ? kApuBaseAddress + 0x1000 : 0}; 1013 result.xmaContextArray = static_cast<SHAPE_XMA_CONTEXT*>(
372 ctx->apuFiltVolContextArray = {ctx->filtVolContextArray ? kApuBaseAddress + 0x2000 : 0}; 1014 alloc_array(result.numXmaContexts, sizeof(SHAPE_XMA_CONTEXT)));
373 ctx->apuDmaContextArray = {ctx->dmaContextArray ? kApuBaseAddress + 0x3000 : 0}; 1015 result.pcmContextArray = static_cast<SHAPE_PCM_CONTEXT*>(
374 ctx->apuXmaContextArray = {ctx->xmaContextArray ? kApuBaseAddress + 0x4000 : 0}; 1016 alloc_array(result.numPcmContexts, sizeof(SHAPE_PCM_CONTEXT)));
375 ctx->apuPcmContextArray = {ctx->pcmContextArray ? kApuBaseAddress + 0x5000 : 0}; 1017
376 1018 // Assign synthetic APU addresses to the host-side context arrays.
377 trace_call("AcpHalAllocateShapeContexts", 1019 result.apuSrcContextArray = {result.srcContextArray ? kApuBaseAddress : 0};
378 ",\"src\":" + std::to_string(ctx->numSrcContexts) + 1020 result.apuEqCompContextArray = {result.eqCompContextArray ? kApuBaseAddress + 0x1000 : 0};
379 ",\"xma\":" + std::to_string(ctx->numXmaContexts) + 1021 result.apuFiltVolContextArray = {result.filtVolContextArray ? kApuBaseAddress + 0x2000 : 0};
380 ",\"pcm\":" + std::to_string(ctx->numPcmContexts)); 1022 result.apuDmaContextArray = {result.dmaContextArray ? kApuBaseAddress + 0x3000 : 0};
1023 result.apuXmaContextArray = {result.xmaContextArray ? kApuBaseAddress + 0x4000 : 0};
1024 result.apuPcmContextArray = {result.pcmContextArray ? kApuBaseAddress + 0x5000 : 0};
1025
1026 g_shape_allocations.reserve(g_shape_allocations.size() + 1);
1027 if (result.xmaContextArray) g_xma_engine.bind(result.xmaContextArray, result.numXmaContexts);
1028 } catch (const std::bad_alloc&) {
1029 return E_OUTOFMEMORY;
1030 }
1031
1032 // Both the backing arrays and the engine's slots are now fully allocated.
1033 g_shape_allocations.push_back(std::move(pending));
1034 *ctx = result;
1035 if (rt::startup_trace::enabled()) {
1036 try {
1037 trace_call("AcpHalAllocateShapeContexts",
1038 ",\"src\":" + std::to_string(result.numSrcContexts) +
1039 ",\"xma\":" + std::to_string(result.numXmaContexts) +
1040 ",\"pcm\":" + std::to_string(result.numPcmContexts));
1041 } catch (const std::bad_alloc&) {
1042 // The allocation succeeded. A missing diagnostic does not invalidate it.
1043 }
1044 }
381 return S_OK; 1045 return S_OK;
382} 1046}
383 1047
384// ---- AcpHalReleaseShapeContexts ---- 1048// ---- AcpHalReleaseShapeContexts ----
385 1049
386HRESULT __stdcall AcpHalReleaseShapeContexts(SHAPE_CONTEXTS* ctx = nullptr) { 1050HRESULT __stdcall AcpHalReleaseShapeContexts(void* /*hal*/) {
387 std::lock_guard lock(g_apu_mutex); 1051 std::lock_guard lock(g_shape_mutex);
388 1052 // Stop and detach the XMA worker before freeing backing arrays.
389 // Free all recorded context allocations 1053 g_xma_engine.unbind();
390 for (void* p : g_active_shape_arrays) {
391 if (p) std::free(p);
392 }
393 g_active_shape_arrays.clear();
394 1054
395 if (ctx) { 1055 // The export releases the process-wide SHAPE arrays. The argument is an
396 ctx->srcContextArray = nullptr; 1056 // opaque HAL handle, and allocation descriptors are owned by the caller.
397 ctx->eqCompContextArray = nullptr; 1057 g_shape_allocations.clear();
398 ctx->filtVolContextArray = nullptr;
399 ctx->dmaContextArray = nullptr;
400 ctx->xmaContextArray = nullptr;
401 ctx->pcmContextArray = nullptr;
402 }
403 1058
404 trace_call("AcpHalReleaseShapeContexts", ""); 1059 trace_call("AcpHalReleaseShapeContexts", "");
405 return S_OK; 1060 return S_OK;
@@ -411,6 +1066,9 @@ HRESULT __stdcall ApuCreateHeap(uint32_t cachedSizeInBytes,
411 uint32_t nonCachedSizeInBytes) { 1066 uint32_t nonCachedSizeInBytes) {
412 std::lock_guard lock(g_apu_mutex); 1067 std::lock_guard lock(g_apu_mutex);
413 if (g_apu_heap_created) return E_FAIL; 1068 if (g_apu_heap_created) return E_FAIL;
1069 const uint64_t address_bytes = (nonCachedSizeInBytes ? align_apu_region(cachedSizeInBytes)
1070 : cachedSizeInBytes) + nonCachedSizeInBytes;
1071 if (address_bytes > static_cast<uint64_t>(UINT32_MAX) + 1 - kApuBaseAddress) return E_INVALIDARG;
414 1072
415 if (cachedSizeInBytes > 0) { 1073 if (cachedSizeInBytes > 0) {
416 g_cached_heap.base = VirtualAlloc( 1074 g_cached_heap.base = VirtualAlloc(
@@ -430,17 +1088,23 @@ HRESULT __stdcall ApuCreateHeap(uint32_t cachedSizeInBytes,
430 } 1088 }
431 1089
432 g_apu_heap_created = true; 1090 g_apu_heap_created = true;
433 trace_call("ApuCreateHeap", 1091 if (rt::startup_trace::enabled()) {
434 ",\"cachedSize\":" + std::to_string(cachedSizeInBytes) + 1092 try {
435 ",\"nonCachedSize\":" + std::to_string(nonCachedSizeInBytes)); 1093 trace_call("ApuCreateHeap",
1094 ",\"cachedSize\":" + std::to_string(cachedSizeInBytes) +
1095 ",\"nonCachedSize\":" + std::to_string(nonCachedSizeInBytes));
1096 } catch (const std::bad_alloc&) {
1097 // The heap is ready even if its diagnostic cannot be built.
1098 }
1099 }
436 return S_OK; 1100 return S_OK;
437} 1101}
438 1102
439// ---- ApuAlloc ---- 1103// ---- ApuAlloc ----
440 1104
441HRESULT __stdcall ApuAlloc(void** virtualAddress, uint32_t* physicalAddress, 1105HRESULT __stdcall ApuAlloc(void** virtualAddress, uint32_t* physicalAddress,
442 uint32_t sizeInBytes, uint32_t alignmentInBytes, 1106 uint32_t sizeInBytes, uint32_t alignmentInBytes,
443 uint32_t flags) { 1107 uint32_t flags) try {
444 if (!virtualAddress) return E_POINTER; 1108 if (!virtualAddress) return E_POINTER;
445 *virtualAddress = nullptr; 1109 *virtualAddress = nullptr;
446 if (physicalAddress) *physicalAddress = 0; 1110 if (physicalAddress) *physicalAddress = 0;
@@ -459,6 +1123,7 @@ HRESULT __stdcall ApuAlloc(void** virtualAddress, uint32_t* physicalAddress,
459 1123
460 if (!target->base) { 1124 if (!target->base) {
461 if (!prefer_noncached) { 1125 if (!prefer_noncached) {
1126 if (g_apu_heap_created) return E_OUTOFMEMORY;
462 // Lazy default cached heap if ApuCreateHeap wasn't called yet 1127 // Lazy default cached heap if ApuCreateHeap wasn't called yet
463 constexpr uint32_t kDefaultHeapSize = 64 * 1024 * 1024; 1128 constexpr uint32_t kDefaultHeapSize = 64 * 1024 * 1024;
464 target->base = VirtualAlloc(nullptr, kDefaultHeapSize, 1129 target->base = VirtualAlloc(nullptr, kDefaultHeapSize,
@@ -485,17 +1150,17 @@ HRESULT __stdcall ApuAlloc(void** virtualAddress, uint32_t* physicalAddress,
485 1150
486 *virtualAddress = ptr; 1151 *virtualAddress = ptr;
487 if (physicalAddress) { 1152 if (physicalAddress) {
488 // Disjoint APU address ranges: 1153 // Leave alignment padding between the two synthetic address ranges.
489 // cached: 0x40000000 .. 0x40000000 + cached_size - 1
490 // non-cached: 0x40000000 + cached_size .. 0x40000000 + cached_size + noncached_size - 1
491 uint32_t apu = kApuBaseAddress + offset; 1154 uint32_t apu = kApuBaseAddress + offset;
492 if (target == &g_noncached_heap) { 1155 if (target == &g_noncached_heap) {
493 apu += static_cast<uint32_t>(g_cached_heap.size); 1156 apu += static_cast<uint32_t>(align_apu_region(g_cached_heap.size));
494 } 1157 }
495 *physicalAddress = apu; 1158 *physicalAddress = apu;
496 } 1159 }
497 1160
498 return S_OK; 1161 return S_OK;
1162} catch (const std::bad_alloc&) {
1163 return E_OUTOFMEMORY;
499} 1164}
500 1165
501// ---- ApuFree ---- 1166// ---- ApuFree ----
@@ -530,7 +1195,7 @@ void* __stdcall ApuMapApuAddress(uint32_t apu) {
530 return g_cached_heap.from_offset(offset); 1195 return g_cached_heap.from_offset(offset);
531 } 1196 }
532 if (g_noncached_heap.base) { 1197 if (g_noncached_heap.base) {
533 const uint32_t cached_span = static_cast<uint32_t>(g_cached_heap.size); 1198 const uint32_t cached_span = static_cast<uint32_t>(align_apu_region(g_cached_heap.size));
534 if (offset >= cached_span && offset - cached_span < g_noncached_heap.size) { 1199 if (offset >= cached_span && offset - cached_span < g_noncached_heap.size) {
535 return g_noncached_heap.from_offset(offset - cached_span); 1200 return g_noncached_heap.from_offset(offset - cached_span);
536 } 1201 }
@@ -547,7 +1212,7 @@ uint32_t __stdcall ApuMapVirtualAddress(void* virtualAddress) {
547 return kApuBaseAddress + g_cached_heap.to_offset(virtualAddress); 1212 return kApuBaseAddress + g_cached_heap.to_offset(virtualAddress);
548 } 1213 }
549 if (g_noncached_heap.contains(virtualAddress)) { 1214 if (g_noncached_heap.contains(virtualAddress)) {
550 return kApuBaseAddress + static_cast<uint32_t>(g_cached_heap.size) + 1215 return kApuBaseAddress + static_cast<uint32_t>(align_apu_region(g_cached_heap.size)) +
551 g_noncached_heap.to_offset(virtualAddress); 1216 g_noncached_heap.to_offset(virtualAddress);
552 } 1217 }
553 return 0; 1218 return 0;
diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp
index cf02df519..7c5244141 100644
--- a/runtime/shims/d3d12_com.cpp
+++ b/runtime/shims/d3d12_com.cpp
@@ -411,12 +411,20 @@ public:
411 if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false); 411 if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false);
412 if (!count) { 412 if (!count) {
413 viewport_ = {}; 413 viewport_ = {};
414 viewports_.fill({});
415 viewport_count_ = 0;
416 draw_viewports_stale_ = true;
414 return; 417 return;
415 } 418 }
416 if (!viewports || count > D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE) return check(false); 419 if (!viewports || count > D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE) return check(false);
417 if (count > 1) stub("ID3D12GraphicsCommandList::RSSetViewports (more than one viewport; the first is used)"); 420 viewports_.fill({});
418 const D3D12_VIEWPORT& v = viewports[0]; 421 for (UINT i = 0; i < count; ++i) {
419 viewport_ = {v.TopLeftX, v.TopLeftY, v.Width, v.Height, v.MinDepth, v.MaxDepth}; 422 const D3D12_VIEWPORT& v = viewports[i];
423 viewports_[i] = {v.TopLeftX, v.TopLeftY, v.Width, v.Height, v.MinDepth, v.MaxDepth};
424 }
425 viewport_count_ = count;
426 viewport_ = viewports_[0];
427 draw_viewports_stale_ = true;
420 } 428 }
421 429
422 void STDMETHODCALLTYPE RSSetScissorRects(UINT count, const D3D12_RECT* rects) override { 430 void STDMETHODCALLTYPE RSSetScissorRects(UINT count, const D3D12_RECT* rects) override {
@@ -425,11 +433,25 @@ public:
425 // With no scissor bound, the rasterizer clips every fragment, as on native D3D12. 433 // With no scissor bound, the rasterizer clips every fragment, as on native D3D12.
426 if (!count) { 434 if (!count) {
427 scissor_ = {}; 435 scissor_ = {};
436 scissors_.fill({});
437 scissor_count_ = 0;
438 draw_viewports_stale_ = true;
428 return; 439 return;
429 } 440 }
430 if (!rects) return; 441 if (!rects) return;
431 if (count > 1) stub("ID3D12GraphicsCommandList::RSSetScissorRects (more than one rectangle; the first is used)"); 442 // WARP still closes a list after RSSetScissorRects(17) (d3d12_close_parity), so the call is not an error:
432 scissor_ = {rects[0].left, rects[0].top, rects[0].right, rects[0].bottom}; 443 // the rectangles past the 16 a pipeline can have are dropped.
444 if (count > D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE) {
445 stub("ID3D12GraphicsCommandList::RSSetScissorRects(more than 16 rectangles; the first 16 are used)");
446 count = D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE;
447 }
448 scissors_.fill({});
449 for (UINT i = 0; i < count; ++i) {
450 scissors_[i] = {rects[i].left, rects[i].top, rects[i].right, rects[i].bottom};
451 }
452 scissor_count_ = count;
453 scissor_ = scissors_[0];
454 draw_viewports_stale_ = true;
433 } 455 }
434 456
435 // D3D12 reads render-target and depth descriptors here, so their views are copied now. 457 // D3D12 reads render-target and depth descriptors here, so their views are copied now.
@@ -486,10 +508,11 @@ public:
486 d3d12_trace::record("ID3D12GraphicsCommandList6::DispatchMesh"); 508 d3d12_trace::record("ID3D12GraphicsCommandList6::DispatchMesh");
487 if (x > 65535 || y > 65535 || z > 65535 || std::uint64_t(x) * y * z > (1u << 22)) return check(false); 509 if (x > 65535 || y > 65535 || z > 65535 || std::uint64_t(x) * y * z > (1u << 22)) return check(false);
488 if (!graphics_pipeline_ || !graphics_.layout) return check(false); 510 if (!graphics_pipeline_ || !graphics_.layout) return check(false);
489 if (!(viewport_.width > 0) || !(viewport_.height > 0)) return; // as record_draw: nothing is rasterized 511 if (!any_nonempty_viewport()) return; // as record_draw: nothing is rasterized
490 leonida::Draw draw{graphics_pipeline_, graphics_.data, draw_views(), depth_, {}, 0, viewport_, 512 leonida::Draw draw{graphics_pipeline_, graphics_.data, draw_views(), depth_, {}, 0, viewport_,
491 scissor_, blend_factor_, front_stencil_ref_, back_stencil_ref_, false, x, y, z, 0, 0}; 513 scissor_, blend_factor_, front_stencil_ref_, back_stencil_ref_, false, x, y, z, 0, 0};
492 draw.mesh = true; 514 draw.mesh = true;
515 draw.viewports = draw_viewports();
493 check(list_.draw(std::move(draw))); 516 check(list_.draw(std::move(draw)));
494 } 517 }
495 518
@@ -835,9 +858,7 @@ public:
835 return check(false); 858 return check(false);
836 } 859 }
837 // The record size is checked for every call: D3D12 rejects a signature whose stride cannot hold a record 860 // The record size is checked for every call: D3D12 rejects a signature whose stride cannot hold a record
838 // even when no command runs. The argument span is what the signature can walk, max_command_count * stride: 861 // even when no command runs.
839 // the host refuses a range that ends past the buffer (`240` with stride `20` in a `256`-byte buffer), and
840 // it checks the offset itself when max_command_count is 0, where the required bytes are none.
841 const UINT64 record_size = 862 const UINT64 record_size =
842 kind == leonida::IndirectKind::draw ? sizeof(D3D12_DRAW_ARGUMENTS) 863 kind == leonida::IndirectKind::draw ? sizeof(D3D12_DRAW_ARGUMENTS)
843 : kind == leonida::IndirectKind::draw_indexed ? sizeof(D3D12_DRAW_INDEXED_ARGUMENTS) 864 : kind == leonida::IndirectKind::draw_indexed ? sizeof(D3D12_DRAW_INDEXED_ARGUMENTS)
@@ -845,9 +866,18 @@ public:
845 : kind == leonida::IndirectKind::dispatch_mesh ? sizeof(D3D12_DISPATCH_MESH_ARGUMENTS) 866 : kind == leonida::IndirectKind::dispatch_mesh ? sizeof(D3D12_DISPATCH_MESH_ARGUMENTS)
846 : 0; 867 : 0;
847 if (!record_size || stride < record_size || stride % 4 != 0) return check(false); 868 if (!record_size || stride < record_size || stride % 4 != 0) return check(false);
848 if (argument_buffer_offset > arg_desc.Width || 869 // The argument range is the bytes the commands read: (max_command_count - 1) * stride + record_size, and
849 UINT64(max_command_count) > (arg_desc.Width - argument_buffer_offset) / stride) 870 // nothing when max_command_count is 0. PC D3D12 runtimes do not agree here. Some bound max_command_count *
850 return check(false); 871 // stride and check the offset at a zero count; others (D3D12Core 10.0.26100.9818, WARP and NVIDIA alike)
872 // accept a last record that fits while its stride runs past the buffer, and any aligned offset at a zero
873 // count. The layer takes the wider rule: it is the one Vulkan's own indirect draws use, no byte outside the
874 // buffer is read, and refusing here drops the whole command list for a call a real runtime runs.
875 // d3d12_execute_indirect_validation_test lists the five cases the runtimes split on.
876 if (max_command_count) {
877 const UINT64 required = UINT64(max_command_count - 1) * stride + record_size;
878 if (argument_buffer_offset > arg_desc.Width || arg_desc.Width - argument_buffer_offset < required)
879 return check(false);
880 }
851 if (kind == leonida::IndirectKind::dispatch_mesh) { 881 if (kind == leonida::IndirectKind::dispatch_mesh) {
852 // Not replayed yet (#3777 replays it as vkCmdDrawMeshTasksIndirectEXT): nothing is recorded, and the 882 // Not replayed yet (#3777 replays it as vkCmdDrawMeshTasksIndirectEXT): nothing is recorded, and the
853 // first such call says so. The list stays valid. 883 // first such call says so. The list stays valid.
@@ -1276,6 +1306,12 @@ private:
1276 leonida::IndexBufferView index_{}; 1306 leonida::IndexBufferView index_{};
1277 leonida::Viewport viewport_{}; 1307 leonida::Viewport viewport_{};
1278 leonida::Rect scissor_{}; 1308 leonida::Rect scissor_{};
1309 std::array<leonida::Viewport, D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE> viewports_{};
1310 UINT viewport_count_ = 0;
1311 std::array<leonida::Rect, D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE> scissors_{};
1312 UINT scissor_count_ = 0;
1313 std::shared_ptr<const leonida::DrawViewports> draw_viewports_;
1314 bool draw_viewports_stale_ = true;
1279 std::array<leonida::TargetView, D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT> render_targets_{}; 1315 std::array<leonida::TargetView, D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT> render_targets_{};
1280 UINT render_target_count_ = 0; 1316 UINT render_target_count_ = 0;
1281 // One block shared by every draw that keeps the same targets and buffers, rebuilt when either changes, so a 1317 // One block shared by every draw that keeps the same targets and buffers, rebuilt when either changes, so a
@@ -1378,6 +1414,12 @@ private:
1378 index_ = {}; 1414 index_ = {};
1379 viewport_ = {}; 1415 viewport_ = {};
1380 scissor_ = {}; 1416 scissor_ = {};
1417 viewports_.fill({});
1418 viewport_count_ = 0;
1419 scissors_.fill({});
1420 scissor_count_ = 0;
1421 draw_viewports_.reset();
1422 draw_viewports_stale_ = true;
1381 render_targets_.fill({}); 1423 render_targets_.fill({});
1382 render_target_count_ = 0; 1424 render_target_count_ = 0;
1383 draw_views_stale_ = true; 1425 draw_views_stale_ = true;
@@ -1418,16 +1460,37 @@ private:
1418 return draw_views_; 1460 return draw_views_;
1419 } 1461 }
1420 1462
1463 bool any_nonempty_viewport() const {
1464 for (UINT i = 0; i < viewport_count_; ++i)
1465 if (viewports_[i].width > 0.0f && viewports_[i].height > 0.0f) return true;
1466 return false;
1467 }
1468
1469 std::shared_ptr<const leonida::DrawViewports> draw_viewports() {
1470 if (viewport_count_ <= 1 && scissor_count_ <= 1) return nullptr;
1471 if (draw_viewports_stale_) {
1472 auto block = std::make_shared<leonida::DrawViewports>();
1473 block->viewports = viewports_;
1474 block->viewport_count = viewport_count_;
1475 block->scissors = scissors_;
1476 block->scissor_count = scissor_count_;
1477 draw_viewports_ = std::move(block);
1478 draw_viewports_stale_ = false;
1479 }
1480 return draw_viewports_;
1481 }
1482
1421 // A draw needs a graphics pipeline, a graphics root signature and a topology. 1483 // A draw needs a graphics pipeline, a graphics root signature and a topology.
1422 void record_draw(bool indexed, UINT count, UINT instances, UINT first, INT base_vertex, UINT first_instance) { 1484 void record_draw(bool indexed, UINT count, UINT instances, UINT first, INT base_vertex, UINT first_instance) {
1423 if (!graphics_pipeline_ || !graphics_.layout || !topology_) return check(false); 1485 if (!graphics_pipeline_ || !graphics_.layout || !topology_) return check(false);
1424 note_direct_heap_indexing(graphics_.layout); 1486 note_direct_heap_indexing(graphics_.layout);
1425 // No viewport (never set, or unbound with RSSetViewports(0)) or an empty one: D3D12 rasterizes nothing, 1487 // No viewport (never set, or unbound with RSSetViewports(0)) or every bound viewport empty: D3D12 rasterizes
1426 // and Vulkan forbids a 0x0 viewport, so the draw is not recorded. 1488 // nothing, and Vulkan forbids a 0x0 viewport, so the draw is not recorded.
1427 if (!(viewport_.width > 0) || !(viewport_.height > 0)) return; 1489 if (!any_nonempty_viewport()) return;
1428 leonida::Draw draw{graphics_pipeline_, graphics_.data, draw_views(), depth_, index_, topology_, viewport_, 1490 leonida::Draw draw{graphics_pipeline_, graphics_.data, draw_views(), depth_, index_, topology_, viewport_,
1429 scissor_, blend_factor_, front_stencil_ref_, back_stencil_ref_, indexed, count, instances, 1491 scissor_, blend_factor_, front_stencil_ref_, back_stencil_ref_, indexed, count, instances,
1430 first, base_vertex, first_instance}; 1492 first, base_vertex, first_instance};
1493 draw.viewports = draw_viewports();
1431 check(list_.draw(std::move(draw))); 1494 check(list_.draw(std::move(draw)));
1432 } 1495 }
1433}; 1496};
diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h
index d0f3b528a..cf83f1f28 100644
--- a/runtime/shims/d3d12_com.h
+++ b/runtime/shims/d3d12_com.h
@@ -87,6 +87,7 @@ struct VulkanDeviceInfo {
87 std::vector<VkQueue> compute_queues; 87 std::vector<VkQueue> compute_queues;
88 std::vector<VkQueue> copy_queues; 88 std::vector<VkQueue> copy_queues;
89 bool separate_depth_stencil_layouts = true; 89 bool separate_depth_stencil_layouts = true;
90 bool depth_range_unrestricted = false; // VK_EXT_depth_range_unrestricted enabled on this device.
90 std::uint32_t max_push_constants_size = 0; 91 std::uint32_t max_push_constants_size = 0;
91 bool push_constants_need_fallback = false; 92 bool push_constants_need_fallback = false;
92 // maxBufferSize and maxMemoryAllocationSize, which cap the GPU address arena (src/arena_size.h). 0: read from 93 // maxBufferSize and maxMemoryAllocationSize, which cap the GPU address arena (src/arena_size.h). 0: read from
@@ -124,6 +125,9 @@ struct VulkanDeviceInfo {
124 // VK_EXT_host_image_copy and its hostImageCopy feature are enabled on `device`: WriteToSubresource and 125 // VK_EXT_host_image_copy and its hostImageCopy feature are enabled on `device`: WriteToSubresource and
125 // ReadFromSubresource on textures in CPU-visible heaps copy on the CPU instead of through a staging submit. 126 // ReadFromSubresource on textures in CPU-visible heaps copy on the CPU instead of through a staging submit.
126 bool host_image_copy = false; 127 bool host_image_copy = false;
128 // Tests only: every host-transfer texture is treated as one the driver gave no memory type (a GTX 1050 Ti,
129 // NVIDIA 582.78), so it is made again without host-transfer usage and copies on the staging path on any GPU.
130 bool force_host_transfer_retry = false;
127 // VK_KHR_shader_fma and its shaderFmaFloat32 feature are enabled on `device`: translated shaders built with 131 // VK_KHR_shader_fma and its shaderFmaFloat32 feature are enabled on `device`: translated shaders built with
128 // `rdna2spirv.py --fma khr` (OpFmaKHR, capability FMAKHR in the index) can be created. Without it only the 132 // `rdna2spirv.py --fma khr` (OpFmaKHR, capability FMAKHR in the index) can be created. Without it only the
129 // default `--fma glsl` shaders can. 133 // default `--fma glsl` shaders can.
@@ -175,6 +179,9 @@ struct VulkanDeviceInfo {
175 // shaders have no amplification stage). Mesh-shader PSOs and DispatchMesh work, and CheckFeatureSupport reports 179 // shaders have no amplification stage). Mesh-shader PSOs and DispatchMesh work, and CheckFeatureSupport reports
176 // D3D12_MESH_SHADER_TIER_1; without it mesh PSOs are refused and the tier is NOT_SUPPORTED. 180 // D3D12_MESH_SHADER_TIER_1; without it mesh PSOs are refused and the tier is NOT_SUPPORTED.
177 bool mesh_shader = false; 181 bool mesh_shader = false;
182 // VK_EXT_mesh_shader's meshShaderQueries feature is enabled on `device`, so the clipping invocations of a mesh
183 // segment come from a mesh-primitives query (D3D-MESH-CLIPPING-COUNTER). Without it they read 0.
184 bool mesh_shader_queries = false;
178 // The core features enabled on `device`. Graphics PSOs that need independentBlend, fillModeNonSolid, 185 // The core features enabled on `device`. Graphics PSOs that need independentBlend, fillModeNonSolid,
179 // depthBiasClamp or dualSrcBlend are refused unless it is set here. 186 // depthBiasClamp or dualSrcBlend are refused unless it is set here.
180 VkPhysicalDeviceFeatures features{}; 187 VkPhysicalDeviceFeatures features{};
diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp
index 6cc357c87..8ff20b5a4 100644
--- a/runtime/shims/d3d12_vulkan_device.cpp
+++ b/runtime/shims/d3d12_vulkan_device.cpp
@@ -1000,6 +1000,15 @@ struct DeviceState {
1000 backed.uint_backed = VK_FORMAT_A1R5G5B5_UNORM_PACK16; 1000 backed.uint_backed = VK_FORMAT_A1R5G5B5_UNORM_PACK16;
1001 return backed; 1001 return backed;
1002 } 1002 }
1003 // A B4G4R4A4 render target where no 4444 format is a colour attachment (NVIDIA has none, sampled only): an
1004 // RGBA8 image, which holds every 4-bit value exactly. RTVs and PSOs follow the image's format; the 4_4_4_4 T#s
1005 // read it with the 4444 view's channels (bind_image). Not covered: a copy between it and a buffer footprint
1006 // moves 4-byte RGBA8 texels, not packed 16-bit ones (replay's footprint bounds checks still hold).
1007 if (desc.Format == DXGI_FORMAT_B4G4R4A4_UNORM && (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) &&
1008 !color_attachment_usable(VK_FORMAT_A4R4G4B4_UNORM_PACK16) && color_attachment_usable(VK_FORMAT_R8G8B8A8_UNORM)) {
1009 log_once("B4G4R4A4_UNORM render targets unavailable natively, using RGBA8; format", desc.Format);
1010 return Format{VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_ASPECT_COLOR_BIT};
1011 }
1003 // An 8-bit sRGB UAV texture where the sRGB format has no storage support: the host runtime makes it (RTX 4090 1012 // An 8-bit sRGB UAV texture where the sRGB format has no storage support: the host runtime makes it (RTX 4090
1004 // and WARP; a retail title sizes a 2048x2048 R8G8B8A8_UNORM_SRGB render target with unordered access), but no 1013 // and WARP; a retail title sizes a 2048x2048 R8G8B8A8_UNORM_SRGB render target with unordered access), but no
1005 // typed UAV is sRGB in D3D12, so shaders write the raw bytes. A mutable image of the UNORM format of the same 1014 // typed UAV is sRGB in D3D12, so shaders write the raw bytes. A mutable image of the UNORM format of the same
@@ -1176,6 +1185,14 @@ struct DeviceState {
1176 VkFormat view_format = 1185 VkFormat view_format =
1177 stencil ? image_format : g::vulkan_view_format(logical_format, image.format, allow_channel_cast); 1186 stencil ? image_format : g::vulkan_view_format(logical_format, image.format, allow_channel_cast);
1178 VkFormat channels_format = view_format; // whose channels the T#'s swizzle selects from 1187 VkFormat channels_format = view_format; // whose channels the T#'s swizzle selects from
1188 // A B4G4R4A4 render target stored as RGBA8 (no 4444 format renders on this device): a 16-bit view of the
1189 // 32-bit image is not allowed, so its 4_4_4_4 T# reads the RGBA8 image (which holds the logical R, G, B, A)
1190 // with the channels of A4R4G4B4, the format the texture has (DXGI_FORMAT_B4G4R4A4_UNORM).
1191 if (!stencil && image_format == VK_FORMAT_R8G8B8A8_UNORM &&
1192 (view_format == VK_FORMAT_A4B4G4R4_UNORM_PACK16 || view_format == VK_FORMAT_A4R4G4B4_UNORM_PACK16)) {
1193 view_format = VK_FORMAT_R8G8B8A8_UNORM;
1194 channels_format = VK_FORMAT_A4R4G4B4_UNORM_PACK16;
1195 }
1179 if (view_format == VK_FORMAT_UNDEFINED) { // a 96-bit texture's T# names RGB32; its image is RGBA32 1196 if (view_format == VK_FORMAT_UNDEFINED) { // a 96-bit texture's T# names RGB32; its image is RGBA32
1180 view_format = rgb96_view_format(image_format, image.format); 1197 view_format = rgb96_view_format(image_format, image.format);
1181 channels_format = rgb96_named_format(view_format); 1198 channels_format = rgb96_named_format(view_format);
@@ -2226,8 +2243,10 @@ public:
2226 } 2243 }
2227 if (FAILED(support)) return support; 2244 if (FAILED(support)) return support;
2228 device_.share(info); 2245 device_.share(info);
2229 const VkResult created = vk.vkCreateImage(device_.info.device, &info, nullptr, &image_); 2246 const auto create_image = [&]() -> HRESULT {
2230 if (created != VK_SUCCESS) { 2247 const VkResult created = vk.vkCreateImage(device_.info.device, &info, nullptr, &image_);
2248 if (created == VK_SUCCESS) return S_OK;
2249 image_ = VK_NULL_HANDLE; // undefined after a failed create; ~Resource destroys any non-null image_
2231 if (created == VK_ERROR_OUT_OF_HOST_MEMORY || created == VK_ERROR_OUT_OF_DEVICE_MEMORY) 2250 if (created == VK_ERROR_OUT_OF_HOST_MEMORY || created == VK_ERROR_OUT_OF_DEVICE_MEMORY)
2232 return E_OUTOFMEMORY; 2251 return E_OUTOFMEMORY;
2233 if (!view_formats_.empty()) { 2252 if (!view_formats_.empty()) {
@@ -2235,12 +2254,44 @@ public:
2235 return E_INVALIDARG; 2254 return E_INVALIDARG;
2236 } 2255 }
2237 return E_OUTOFMEMORY; 2256 return E_OUTOFMEMORY;
2238 } 2257 };
2258 if (HRESULT hr = create_image(); FAILED(hr)) return hr;
2259 // Some drivers advertise VK_EXT_host_image_copy yet allow no memory type for a HOST_TRANSFER image
2260 // (NVIDIA Pascal / 582.78: memoryTypeBits == 0), or fail to allocate one. Staging copies do not need
2261 // that usage, so recreate the image without it and continue on that path, as for a refused format above.
2239 VkMemoryRequirements requirements{}; 2262 VkMemoryRequirements requirements{};
2240 vk.vkGetImageMemoryRequirements(device_.info.device, image_, &requirements); 2263 for (;;) {
2241 memory_ = device_.allocate(requirements, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, &memory_flags_); 2264 vk.vkGetImageMemoryRequirements(device_.info.device, image_, &requirements);
2242 if (!memory_ || vk.vkBindImageMemory(device_.info.device, image_, memory_, 0) != VK_SUCCESS) 2265 // NVIDIA's Pascal driver (582.78 on a GTX 1050 Ti) reports HOST_IMAGE_TRANSFER for the format and creates
2243 return E_OUTOFMEMORY; 2266 // the image, but then allows it no memory type at all. The image has not been bound or used, so it is
2267 // made again without host-transfer usage and the CPU copies take the staging path. The test forces this
2268 // branch on any GPU with force_host_transfer_retry.
2269 bool retry = host_transfer_ &&
2270 (requirements.memoryTypeBits == 0 || device_.info.force_host_transfer_retry);
2271 if (!retry) {
2272 memory_ = device_.allocate(requirements, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, &memory_flags_);
2273 if (memory_ && vk.vkBindImageMemory(device_.info.device, image_, memory_, 0) == VK_SUCCESS) break;
2274 if (memory_) { vk.vkFreeMemory(device_.info.device, memory_, nullptr); memory_ = VK_NULL_HANDLE; }
2275 retry = host_transfer_; // a failed allocation/bind retries on the staging path too
2276 }
2277 if (!retry) return E_OUTOFMEMORY;
2278 log_once(requirements.memoryTypeBits == 0 || device_.info.force_host_transfer_retry
2279 ? "host-transfer image has no memory type; using staging copies, format"
2280 : "host-transfer image could not be bound; using staging copies, format",
2281 int(info.format));
2282 vk.vkDestroyImage(device_.info.device, image_, nullptr);
2283 image_ = VK_NULL_HANDLE;
2284 host_transfer_ = false;
2285 info.usage &= ~VK_IMAGE_USAGE_HOST_TRANSFER_BIT_EXT;
2286 if (HRESULT hr = device_.check_image_support(info); FAILED(hr)) return hr;
2287 if (HRESULT hr = create_image(); FAILED(hr)) {
2288 log_once("image refused after dropping host-transfer usage; format", int(info.format));
2289 return hr;
2290 }
2291 vk.vkGetImageMemoryRequirements(device_.info.device, image_, &requirements);
2292 if (requirements.memoryTypeBits == 0)
2293 log_once("image has no memory type even without host-transfer usage; format", int(info.format));
2294 }
2244 2295
2245 leonida::ResourceBinding binding{}; 2296 leonida::ResourceBinding binding{};
2246 binding.image = image_; 2297 binding.image = image_;
@@ -3096,16 +3147,23 @@ public:
3096 virtual HRESULT STDMETHODCALLTYPE xbox_slot11(UINT64, UINT64, void** out) = 0; 3147 virtual HRESULT STDMETHODCALLTYPE xbox_slot11(UINT64, UINT64, void** out) = 0;
3097}; 3148};
3098 3149
3099// A pipeline state. Compute only for now: the shader is found by the SHA-256 of its FSSM program in the
3100// translator's index, and the FSSM blob is copied into the arena as the shader's code base.
3101// A D3D12_PIPELINE_STATE_STREAM_DESC (ID3D12Device2::CreatePipelineState) as the descriptions the PSO creators take. 3150// A D3D12_PIPELINE_STATE_STREAM_DESC (ID3D12Device2::CreatePipelineState) as the descriptions the PSO creators take.
3102// The stream is a run of subobjects, each a D3D12_PIPELINE_STATE_SUBOBJECT_TYPE followed by its description at that 3151// The stream is a run of subobjects, each a D3D12_PIPELINE_STATE_SUBOBJECT_TYPE followed by its description at that
3103// description's alignment, each subobject starting at pointer alignment (the d3dx12.h layout, `alignas(void*)`). A 3152// description's alignment, each subobject starting at pointer alignment (the d3dx12.h layout, `alignas(void*)`). A
3104// subobject that is absent takes the runtime's default (the CD3DX12 defaults: depth test on with LESS, back-face 3153// subobject that is absent takes the runtime's default (the CD3DX12 defaults: depth test on with LESS, back-face
3105// culling, no blending, sample mask 0xFFFFFFFF, one sample). A type given twice, a truncated stream or an unknown 3154// culling, no blending, sample mask 0xFFFFFFFF, one sample). A type given twice, a truncated stream or an unknown
3106// type is E_INVALIDARG, as on the PC runtime; state this layer cannot honour yet is E_NOTIMPL with a log. 3155// type is E_INVALIDARG, as on the PC runtime; state this layer cannot honour yet is E_NOTIMPL with a log.
3156// The back face's stencil masks of a DEPTH_STENCIL2 subobject. D3D12_DEPTH_STENCIL_DESC has one read and one write
3157// mask for both faces, so the face masks travel beside the description.
3158struct StencilFaceMasks {
3159 UINT8 read = D3D12_DEFAULT_STENCIL_READ_MASK;
3160 UINT8 write = D3D12_DEFAULT_STENCIL_WRITE_MASK;
3161};
3162
3107struct PipelineStream { 3163struct PipelineStream {
3108 D3D12_GRAPHICS_PIPELINE_STATE_DESC graphics{}; 3164 D3D12_GRAPHICS_PIPELINE_STATE_DESC graphics{};
3165 bool back_masks = false; // DEPTH_STENCIL2: back_stencil holds the back face's masks
3166 StencilFaceMasks back_stencil;
3109 D3D12_COMPUTE_PIPELINE_STATE_DESC compute{}; 3167 D3D12_COMPUTE_PIPELINE_STATE_DESC compute{};
3110 D3D12_SHADER_BYTECODE ms{}; 3168 D3D12_SHADER_BYTECODE ms{};
3111 D3D12_SHADER_BYTECODE as{}; 3169 D3D12_SHADER_BYTECODE as{};
@@ -3236,12 +3294,10 @@ HRESULT parse_pipeline_stream(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, Pipe
3236 log_once("depth-bounds tests are not supported yet; stream subobject", int(type)); 3294 log_once("depth-bounds tests are not supported yet; stream subobject", int(type));
3237 return E_NOTIMPL; 3295 return E_NOTIMPL;
3238 } 3296 }
3239 // Separate front and back stencil masks are not modelled (one read and one write mask per PSO). 3297 // Each face has its own read and write mask (OPTIONS14.IndependentFrontAndBackStencilRefMaskSupported):
3240 if (d.StencilEnable && (d.FrontFace.StencilReadMask != d.BackFace.StencilReadMask || 3298 // the description takes the front face's, back_stencil the back face's.
3241 d.FrontFace.StencilWriteMask != d.BackFace.StencilWriteMask)) { 3299 out.back_masks = true;
3242 log_once("separate front and back stencil masks are not supported yet; stream subobject", int(type)); 3300 out.back_stencil = {UINT8(d.BackFace.StencilReadMask), UINT8(d.BackFace.StencilWriteMask)};
3243 return E_NOTIMPL;
3244 }
3245 const auto face = [](const D3D12_DEPTH_STENCILOP_DESC1& f) { 3301 const auto face = [](const D3D12_DEPTH_STENCILOP_DESC1& f) {
3246 return D3D12_DEPTH_STENCILOP_DESC{f.StencilFailOp, f.StencilDepthFailOp, f.StencilPassOp, f.StencilFunc}; 3302 return D3D12_DEPTH_STENCILOP_DESC{f.StencilFailOp, f.StencilDepthFailOp, f.StencilPassOp, f.StencilFunc};
3247 }; 3303 };
@@ -3293,6 +3349,8 @@ HRESULT parse_pipeline_stream(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, Pipe
3293 return S_OK; 3349 return S_OK;
3294} 3350}
3295 3351
3352// A pipeline state, compute (create_compute) or graphics (create_graphics): each shader is found by the SHA-256 of
3353// its FSSM program in the translator's index, and the FSSM blob is copied into the arena as the shader's code base.
3296class PipelineState final 3354class PipelineState final
3297 : public Child<PipelineState, XboxPipelineStateStubs, ID3D12Object, ID3D12DeviceChild, ID3D12Pageable, 3355 : public Child<PipelineState, XboxPipelineStateStubs, ID3D12Object, ID3D12DeviceChild, ID3D12Pageable,
3298 ID3D12PipelineState> { 3356 ID3D12PipelineState> {
@@ -3388,8 +3446,10 @@ public:
3388 // With `ms` (a pipeline state stream's MS subobject) it is an MS (+ PS) pipeline on VK_EXT_mesh_shader instead: 3446 // With `ms` (a pipeline state stream's MS subobject) it is an MS (+ PS) pipeline on VK_EXT_mesh_shader instead:
3389 // no VS, no vertex input or input assembly (the input layout, topology type and strip cut are ignored, as D3D12 3447 // no VS, no vertex input or input assembly (the input layout, topology type and strip cut are ignored, as D3D12
3390 // does for mesh PSOs), drawn by DispatchMesh. An AS (amplification shader) is refused: the game has none. 3448 // does for mesh PSOs), drawn by DispatchMesh. An AS (amplification shader) is refused: the game has none.
3449 // `back_masks`, from a DEPTH_STENCIL2 subobject, are the back face's stencil masks; without it both faces take
3450 // the description's.
3391 HRESULT create_graphics(const D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc, const D3D12_SHADER_BYTECODE* ms = nullptr, 3451 HRESULT create_graphics(const D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc, const D3D12_SHADER_BYTECODE* ms = nullptr,
3392 const D3D12_SHADER_BYTECODE* as = nullptr) { 3452 const D3D12_SHADER_BYTECODE* as = nullptr, const StencilFaceMasks* back_masks = nullptr) {
3393 auto& vk = device_.context->vk; 3453 auto& vk = device_.context->vk;
3394 const VkDevice dev = device_.info.device; 3454 const VkDevice dev = device_.info.device;
3395 const bool mesh = ms && ms->pShaderBytecode && ms->BytecodeLength; 3455 const bool mesh = ms && ms->pShaderBytecode && ms->BytecodeLength;
@@ -3778,7 +3838,8 @@ public:
3778 depth.depthCompareOp = compare_op(ds.DepthFunc); 3838 depth.depthCompareOp = compare_op(ds.DepthFunc);
3779 depth.stencilTestEnable = ds.StencilEnable; 3839 depth.stencilTestEnable = ds.StencilEnable;
3780 depth.front = stencil_face(ds.FrontFace, ds.StencilReadMask, ds.StencilWriteMask); 3840 depth.front = stencil_face(ds.FrontFace, ds.StencilReadMask, ds.StencilWriteMask);
3781 depth.back = stencil_face(ds.BackFace, ds.StencilReadMask, ds.StencilWriteMask); 3841 depth.back = back_masks ? stencil_face(ds.BackFace, back_masks->read, back_masks->write)
3842 : stencil_face(ds.BackFace, ds.StencilReadMask, ds.StencilWriteMask);
3782 3843
3783 std::vector<VkPipelineColorBlendAttachmentState> blends(desc.NumRenderTargets); 3844 std::vector<VkPipelineColorBlendAttachmentState> blends(desc.NumRenderTargets);
3784 for (UINT i = 0; i < desc.NumRenderTargets; ++i) { 3845 for (UINT i = 0; i < desc.NumRenderTargets; ++i) {
@@ -3850,10 +3911,17 @@ public:
3850 if (raster.depthClampEnable && !features.depthClamp) 3911 if (raster.depthClampEnable && !features.depthClamp)
3851 return refuse("DepthClipEnable = FALSE needs depthClamp, which the device lacks; flag", 0); 3912 return refuse("DepthClipEnable = FALSE needs depthClamp, which the device lacks; flag", 0);
3852 3913
3914 graphics_.viewport_with_count =
3915 features.multiViewport && vk.vkCmdSetViewportWithCount && vk.vkCmdSetScissorWithCount;
3916
3853 graphics_.color_formats.assign(desc.NumRenderTargets, VK_FORMAT_UNDEFINED); 3917 graphics_.color_formats.assign(desc.NumRenderTargets, VK_FORMAT_UNDEFINED);
3854 for (UINT i = 0; i < desc.NumRenderTargets; ++i) { 3918 for (UINT i = 0; i < desc.NumRenderTargets; ++i) {
3855 if (desc.RTVFormats[i] == DXGI_FORMAT_UNKNOWN) continue; 3919 if (desc.RTVFormats[i] == DXGI_FORMAT_UNKNOWN) continue;
3856 graphics_.color_formats[i] = vulkan_format(desc.RTVFormats[i], false).format; 3920 graphics_.color_formats[i] = vulkan_format(desc.RTVFormats[i], false).format;
3921 // B4G4R4A4 targets are RGBA8 images where no 4444 format renders (DeviceState's texture format choice).
3922 if (graphics_.color_formats[i] == VK_FORMAT_A4R4G4B4_UNORM_PACK16 &&
3923 !device_.color_attachment_usable(VK_FORMAT_A4R4G4B4_UNORM_PACK16))
3924 graphics_.color_formats[i] = VK_FORMAT_R8G8B8A8_UNORM;
3857 if (graphics_.color_formats[i] == VK_FORMAT_UNDEFINED) { 3925 if (graphics_.color_formats[i] == VK_FORMAT_UNDEFINED) {
3858 log_once("render-target format not supported yet:", desc.RTVFormats[i]); 3926 log_once("render-target format not supported yet:", desc.RTVFormats[i]);
3859 return E_INVALIDARG; 3927 return E_INVALIDARG;
@@ -4103,14 +4171,6 @@ private:
4103 4171
4104 // The graphics pipeline with the formats of the `unbound` slots (leonida::GraphicsPipeline::variant) undefined. 4172 // The graphics pipeline with the formats of the `unbound` slots (leonida::GraphicsPipeline::variant) undefined.
4105 VkPipeline build(std::uint32_t unbound) const { 4173 VkPipeline build(std::uint32_t unbound) const {
4106 // The stride state is last: a pipeline without vertex bindings (a full-screen pass that builds its vertices
4107 // from SV_VertexID) leaves it out, since no vkCmdBindVertexBuffers2 would ever set it
4108 // (VUID-vkCmdDraw-pStrides-04913).
4109 static constexpr VkDynamicState dynamic_states[] = {
4110 VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR,
4111 VK_DYNAMIC_STATE_PRIMITIVE_TOPOLOGY, VK_DYNAMIC_STATE_PRIMITIVE_RESTART_ENABLE,
4112 VK_DYNAMIC_STATE_STENCIL_REFERENCE, VK_DYNAMIC_STATE_BLEND_CONSTANTS,
4113 VK_DYNAMIC_STATE_VERTEX_INPUT_BINDING_STRIDE};
4114 const Recipe& r = recipe_; 4174 const Recipe& r = recipe_;
4115 std::vector<VkFormat> colors = graphics_.color_formats; 4175 std::vector<VkFormat> colors = graphics_.color_formats;
4116 for (std::size_t slot = 0; slot < colors.size(); ++slot) 4176 for (std::size_t slot = 0; slot < colors.size(); ++slot)
@@ -4137,8 +4197,10 @@ private:
4137 vertex_input.vertexAttributeDescriptionCount = std::uint32_t(r.attributes.size()); 4197 vertex_input.vertexAttributeDescriptionCount = std::uint32_t(r.attributes.size());
4138 vertex_input.pVertexAttributeDescriptions = r.attributes.data(); 4198 vertex_input.pVertexAttributeDescriptions = r.attributes.data();
4139 VkPipelineViewportStateCreateInfo viewport{VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO}; 4199 VkPipelineViewportStateCreateInfo viewport{VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO};
4140 viewport.viewportCount = 1; 4200 if (!graphics_.viewport_with_count) {
4141 viewport.scissorCount = 1; 4201 viewport.viewportCount = 1;
4202 viewport.scissorCount = 1;
4203 }
4142 VkPipelineMultisampleStateCreateInfo multisample = r.multisample; 4204 VkPipelineMultisampleStateCreateInfo multisample = r.multisample;
4143 VkPipelineRasterizationStateCreateInfo raster = r.raster; 4205 VkPipelineRasterizationStateCreateInfo raster = r.raster;
4144 VkPipelineRasterizationConservativeStateCreateInfoEXT conservative{ 4206 VkPipelineRasterizationConservativeStateCreateInfoEXT conservative{
@@ -4155,17 +4217,23 @@ private:
4155 blend.pAttachments = r.blends.data(); 4217 blend.pAttachments = r.blends.data();
4156 // A mesh pipeline takes neither the topology nor the strides as dynamic state 4218 // A mesh pipeline takes neither the topology nor the strides as dynamic state
4157 // (VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-07065 and -07066). 4219 // (VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-07065 and -07066).
4158 static constexpr VkDynamicState mesh_dynamic_states[] = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR, 4220 // With multiViewport enabled, VIEWPORT_WITH_COUNT / SCISSOR_WITH_COUNT allow 1..16 dynamic viewports/scissors.
4159 VK_DYNAMIC_STATE_STENCIL_REFERENCE, 4221 VkDynamicState dyn_list[8]{};
4160 VK_DYNAMIC_STATE_BLEND_CONSTANTS}; 4222 std::uint32_t dyn_count = 0;
4223 dyn_list[dyn_count++] =
4224 graphics_.viewport_with_count ? VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT : VK_DYNAMIC_STATE_VIEWPORT;
4225 dyn_list[dyn_count++] =
4226 graphics_.viewport_with_count ? VK_DYNAMIC_STATE_SCISSOR_WITH_COUNT : VK_DYNAMIC_STATE_SCISSOR;
4227 if (!r.mesh) {
4228 dyn_list[dyn_count++] = VK_DYNAMIC_STATE_PRIMITIVE_TOPOLOGY;
4229 dyn_list[dyn_count++] = VK_DYNAMIC_STATE_PRIMITIVE_RESTART_ENABLE;
4230 }
4231 dyn_list[dyn_count++] = VK_DYNAMIC_STATE_STENCIL_REFERENCE;
4232 dyn_list[dyn_count++] = VK_DYNAMIC_STATE_BLEND_CONSTANTS;
4233 if (!r.mesh && !r.bindings.empty()) dyn_list[dyn_count++] = VK_DYNAMIC_STATE_VERTEX_INPUT_BINDING_STRIDE;
4161 VkPipelineDynamicStateCreateInfo dynamic{VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO}; 4234 VkPipelineDynamicStateCreateInfo dynamic{VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO};
4162 if (r.mesh) { 4235 dynamic.dynamicStateCount = dyn_count;
4163 dynamic.dynamicStateCount = std::uint32_t(std::size(mesh_dynamic_states)); 4236 dynamic.pDynamicStates = dyn_list;
4164 dynamic.pDynamicStates = mesh_dynamic_states;
4165 } else {
4166 dynamic.dynamicStateCount = std::uint32_t(std::size(dynamic_states)) - (r.bindings.empty() ? 1 : 0);
4167 dynamic.pDynamicStates = dynamic_states;
4168 }
4169 4237
4170 VkGraphicsPipelineCreateInfo info{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, &rendering}; 4238 VkGraphicsPipelineCreateInfo info{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, &rendering};
4171 info.stageCount = std::uint32_t(r.stages.size()); 4239 info.stageCount = std::uint32_t(r.stages.size());
@@ -4712,6 +4780,10 @@ bool image_descriptor(const Resource& resource, const TextureView& view, leonida
4712 } 4780 }
4713 const VkFormat resource_format = resource.uint_backed() ? resource.uint_backed() : resource.format(); 4781 const VkFormat resource_format = resource.uint_backed() ? resource.uint_backed() : resource.format();
4714 VkFormat named = resource_format; 4782 VkFormat named = resource_format;
4783 // A B4G4R4A4 render target stored as an RGBA8 image (no 4444 colour attachment on the device): its T# names
4784 // 4_4_4_4 as on the console, and bind_image views the RGBA8 image with the 4444 view's channels.
4785 const bool rgba8_4444 = desc.Format == DXGI_FORMAT_B4G4R4A4_UNORM && resource.format() == VK_FORMAT_R8G8B8A8_UNORM;
4786 if (rgba8_4444) named = VK_FORMAT_A4R4G4B4_UNORM_PACK16;
4715 if (volume) { 4787 if (volume) {
4716 const bool compatible = vulkan_format(desc.Format, false).typeless 4788 const bool compatible = vulkan_format(desc.Format, false).typeless
4717 ? desc.Format == DXGI_FORMAT_R8G8B8A8_TYPELESS && 4789 ? desc.Format == DXGI_FORMAT_R8G8B8A8_TYPELESS &&
@@ -4781,7 +4853,8 @@ bool image_descriptor(const Resource& resource, const TextureView& view, leonida
4781 } 4853 }
4782 if (rgb96) named = rgb96_named_format(named); 4854 if (rgb96) named = rgb96_named_format(named);
4783 } 4855 }
4784 if (named == VK_FORMAT_UNDEFINED || !resource.allows_view_format(named)) { 4856 if (named == VK_FORMAT_UNDEFINED ||
4857 (rgba8_4444 ? named != VK_FORMAT_A4R4G4B4_UNORM_PACK16 : !resource.allows_view_format(named))) {
4785 log_once("view format not in the resource's castable list:", int(view.format)); 4858 log_once("view format not in the resource's castable list:", int(view.format));
4786 return false; 4859 return false;
4787 } 4860 }
@@ -4791,6 +4864,8 @@ bool image_descriptor(const Resource& resource, const TextureView& view, leonida
4791 view_format = resource.format(); 4864 view_format = resource.format();
4792 } else if (code && rgb96) { 4865 } else if (code && rgb96) {
4793 view_format = named; 4866 view_format = named;
4867 } else if (code && rgba8_4444) {
4868 view_format = resource.format();
4794 } else if (code) { 4869 } else if (code) {
4795 view_format = g::vulkan_view_format(resource_format, code, resource.has_view_format_list()); 4870 view_format = g::vulkan_view_format(resource_format, code, resource.has_view_format_list());
4796 } 4871 }
@@ -5120,6 +5195,8 @@ public:
5120 info.conditional_rendering, info.ray_tracing, 5195 info.conditional_rendering, info.ray_tracing,
5121 info.xdxr_acceleration_structures && 5196 info.xdxr_acceleration_structures &&
5122 info.buffer_device_address); 5197 info.buffer_device_address);
5198 state_.context->mesh_queries = info.mesh_shader_queries;
5199 state_.context->set_depth_range_unrestricted(info.depth_range_unrestricted);
5123 if (info.physical && state_.format_properties) { 5200 if (info.physical && state_.format_properties) {
5124 state_.context->set_color_attachment_format( 5201 state_.context->set_color_attachment_format(
5125 [physical = info.physical, get_props = state_.format_properties](VkFormat format) { 5202 [physical = info.physical, get_props = state_.format_properties](VkFormat format) {
@@ -5187,7 +5264,8 @@ public:
5187 if (info.bindless && state_.context->loaded() && !create_bindless(get_device)) 5264 if (info.bindless && state_.context->loaded() && !create_bindless(get_device))
5188 std::fprintf(stderr, "[rt] d3d12: the bindless set 0 could not be created\n"); 5265 std::fprintf(stderr, "[rt] d3d12: the bindless set 0 could not be created\n");
5189 query_luid_and_clock(get_device); 5266 query_luid_and_clock(get_device);
5190 // Timestamps: what the one VkQueue every D3D12 queue submits to can write. 5267 // Timestamps: the device's timestampPeriod, enabled when the graphics family (info.queue_family) has
5268 // timestampValidBits.
5191 VkPhysicalDeviceProperties properties{}; 5269 VkPhysicalDeviceProperties properties{};
5192 device_properties(info.physical, &properties); 5270 device_properties(info.physical, &properties);
5193 state_.max_sampler_lod_bias = properties.limits.maxSamplerLodBias; 5271 state_.max_sampler_lod_bias = properties.limits.maxSamplerLodBias;
@@ -6189,7 +6267,8 @@ public:
6189 auto* pipeline = new PipelineState(state_); 6267 auto* pipeline = new PipelineState(state_);
6190 pipeline->attach_device(identity()); 6268 pipeline->attach_device(identity());
6191 const HRESULT hr = stream.has_cs ? pipeline->create_compute(stream.compute) 6269 const HRESULT hr = stream.has_cs ? pipeline->create_compute(stream.compute)
6192 : pipeline->create_graphics(stream.graphics, &stream.ms, &stream.as); 6270 : pipeline->create_graphics(stream.graphics, &stream.ms, &stream.as,
6271 stream.back_masks ? &stream.back_stencil : nullptr);
6193 if (FAILED(hr)) { 6272 if (FAILED(hr)) {
6194 pipeline->Release(); 6273 pipeline->Release();
6195 return d3d12_trace::result(method, hr); 6274 return d3d12_trace::result(method, hr);
@@ -7594,35 +7673,42 @@ public:
7594 return d3d12_trace::result(method, S_OK); 7673 return d3d12_trace::result(method, S_OK);
7595 } 7674 }
7596 case D3D12_FEATURE_D3D12_OPTIONS: { 7675 case D3D12_FEATURE_D3D12_OPTIONS: {
7597 if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS)) return d3d12_trace::result(method, E_INVALIDARG); 7676 constexpr UINT kConsoleOptionsSize = sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS) + sizeof(UINT);
7598 auto* opts = static_cast<D3D12_FEATURE_DATA_D3D12_OPTIONS*>(data); 7677 if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS) && size != kConsoleOptionsSize)
7599 *opts = {}; 7678 return d3d12_trace::result(method, E_INVALIDARG);
7679 D3D12_FEATURE_DATA_D3D12_OPTIONS pc_opts{};
7600 // Answer what the layer will actually honour, not what the GPU offers: docs/d3d12_vulkan.md 4.1 says a 7680 // Answer what the layer will actually honour, not what the GPU offers: docs/d3d12_vulkan.md 4.1 says a
7601 // false "supported" is worse than a false "unsupported" at boot, and the PSO paths refuse these same 7681 // false "supported" is worse than a false "unsupported" at boot, and the PSO paths refuse these same
7602 // features when they are missing (logic ops, per the mapping vkd3d-proton's 7682 // features when they are missing (logic ops, per the mapping vkd3d-proton's
7603 // d3d12_device_caps_init_feature_options uses). 7683 // d3d12_device_caps_init_feature_options uses).
7604 opts->DoublePrecisionFloatShaderOps = state_.info.features.shaderFloat64; 7684 pc_opts.DoublePrecisionFloatShaderOps = state_.info.features.shaderFloat64;
7605 opts->OutputMergerLogicOp = state_.info.features.logicOp; 7685 pc_opts.OutputMergerLogicOp = state_.info.features.logicOp;
7606 opts->MinPrecisionSupport = D3D12_SHADER_MIN_PRECISION_SUPPORT_NONE; 7686 pc_opts.MinPrecisionSupport = D3D12_SHADER_MIN_PRECISION_SUPPORT_NONE;
7607 opts->TiledResourcesTier = D3D12_TILED_RESOURCES_TIER_NOT_SUPPORTED; 7687 pc_opts.TiledResourcesTier = D3D12_TILED_RESOURCES_TIER_NOT_SUPPORTED;
7608 opts->ResourceBindingTier = D3D12_RESOURCE_BINDING_TIER_3; // Bindless descriptor indexing supported 7688 pc_opts.ResourceBindingTier = D3D12_RESOURCE_BINDING_TIER_3; // Bindless descriptor indexing supported
7609 // No VK_EXT_shader_stencil_export is enabled and the translator emits no stencil-ref write, so a pixel 7689 // No VK_EXT_shader_stencil_export is enabled and the translator emits no stencil-ref write, so a pixel
7610 // shader that writes the stencil ref would be refused: answer unsupported, the direction 4.1 prefers. 7690 // shader that writes the stencil ref would be refused: answer unsupported, the direction 4.1 prefers.
7611 opts->PSSpecifiedStencilRefSupported = FALSE; 7691 pc_opts.PSSpecifiedStencilRefSupported = FALSE;
7612 opts->TypedUAVLoadAdditionalFormats = TRUE; 7692 pc_opts.TypedUAVLoadAdditionalFormats = TRUE;
7613 // POPS: the translator only declares PixelInterlockOrderedEXT, enabled exactly when the GPU offers 7693 // POPS: the translator only declares PixelInterlockOrderedEXT, enabled exactly when the GPU offers
7614 // VK_EXT_fragment_shader_interlock and its fragmentShaderPixelInterlock feature. 7694 // VK_EXT_fragment_shader_interlock and its fragmentShaderPixelInterlock feature.
7615 opts->ROVsSupported = state_.info.fragment_shader_interlock; 7695 pc_opts.ROVsSupported = state_.info.fragment_shader_interlock;
7616 opts->ConservativeRasterizationTier = state_.conservative_raster_tier; 7696 pc_opts.ConservativeRasterizationTier = state_.conservative_raster_tier;
7617 opts->MaxGPUVirtualAddressBitsPerResource = 40; 7697 pc_opts.MaxGPUVirtualAddressBitsPerResource = 40;
7618 opts->StandardSwizzle64KBSupported = FALSE; 7698 pc_opts.StandardSwizzle64KBSupported = FALSE;
7619 opts->CrossNodeSharingTier = D3D12_CROSS_NODE_SHARING_TIER_NOT_SUPPORTED; 7699 pc_opts.CrossNodeSharingTier = D3D12_CROSS_NODE_SHARING_TIER_NOT_SUPPORTED;
7620 opts->CrossAdapterRowMajorTextureSupported = FALSE; 7700 pc_opts.CrossAdapterRowMajorTextureSupported = FALSE;
7621 // A translated vertex shader writing a layer or viewport index needs both Vulkan 1.2 features enabled 7701 // A translated vertex shader writing a layer or viewport index needs both Vulkan 1.2 features enabled
7622 // (vkCreateShaderModule refuses the module without them, VUID-...-pCode-08740). 7702 // (vkCreateShaderModule refuses the module without them, VUID-...-pCode-08740).
7623 opts->VPAndRTArrayIndexFromAnyShaderFeedingRasterizerSupportedWithoutGSEmulation = 7703 pc_opts.VPAndRTArrayIndexFromAnyShaderFeedingRasterizerSupportedWithoutGSEmulation =
7624 state_.info.shader_output_layer && state_.info.shader_output_viewport_index; 7704 state_.info.shader_output_layer && state_.info.shader_output_viewport_index;
7625 opts->ResourceHeapTier = D3D12_RESOURCE_HEAP_TIER_1; 7705 pc_opts.ResourceHeapTier = D3D12_RESOURCE_HEAP_TIER_1;
7706 std::memcpy(data, &pc_opts, sizeof(pc_opts));
7707 if (size == kConsoleOptionsSize) {
7708 // Console titles query D3D12_FEATURE_D3D12_OPTIONS with a 0x40-byte (16-dword) buffer
7709 // (docs/d3d12_xs_surface.md §7.1): fill the 0x3C-byte PC prefix and zero the trailing 4 bytes.
7710 std::memset(static_cast<std::uint8_t*>(data) + sizeof(pc_opts), 0, sizeof(UINT));
7711 }
7626 return d3d12_trace::result(method, S_OK); 7712 return d3d12_trace::result(method, S_OK);
7627 } 7713 }
7628 case D3D12_FEATURE_D3D12_OPTIONS1: { 7714 case D3D12_FEATURE_D3D12_OPTIONS1: {
@@ -7734,7 +7820,9 @@ public:
7734 *opts = {}; 7820 *opts = {};
7735 opts->AdvancedTextureOpsSupported = FALSE; 7821 opts->AdvancedTextureOpsSupported = FALSE;
7736 opts->WriteableMSAATexturesSupported = FALSE; 7822 opts->WriteableMSAATexturesSupported = FALSE;
7737 opts->IndependentFrontAndBackStencilRefMaskSupported = FALSE; 7823 // DEPTH_STENCIL2's per-face masks go to VkStencilOpState, and OMSetFrontAndBackStencilRef sets each
7824 // face's reference (VK_DYNAMIC_STATE_STENCIL_REFERENCE with a face mask).
7825 opts->IndependentFrontAndBackStencilRefMaskSupported = TRUE;
7738 return d3d12_trace::result(method, S_OK); 7826 return d3d12_trace::result(method, S_OK);
7739 } 7827 }
7740 case D3D12_FEATURE_D3D12_OPTIONS15: { 7828 case D3D12_FEATURE_D3D12_OPTIONS15: {
@@ -7956,8 +8044,7 @@ public:
7956 // Vulkan can still advertise buffer features for their backing formats. 8044 // Vulkan can still advertise buffer features for their backing formats.
7957 if (buffer != 0 && vk_fmt != VK_FORMAT_R8G8B8A8_SRGB && vk_fmt != VK_FORMAT_B8G8R8A8_SRGB) 8045 if (buffer != 0 && vk_fmt != VK_FORMAT_R8G8B8A8_SRGB && vk_fmt != VK_FORMAT_B8G8R8A8_SRGB)
7958 s1 |= D3D12_FORMAT_SUPPORT1_BUFFER; 8046 s1 |= D3D12_FORMAT_SUPPORT1_BUFFER;
7959 // Only what CreateGraphicsPipelineState's input layouts accept (vertex_format): R8/R16 SNORM and SINT 8047 // Only what CreateGraphicsPipelineState's input layouts accept (vertex_format).
7960 // have Vulkan vertex support but no input-layout mapping yet.
7961 VkFormat vertex_vk = VK_FORMAT_UNDEFINED; 8048 VkFormat vertex_vk = VK_FORMAT_UNDEFINED;
7962 UINT vertex_bytes = 0; 8049 UINT vertex_bytes = 0;
7963 if ((buffer & VK_FORMAT_FEATURE_VERTEX_BUFFER_BIT) && vertex_format(fs->Format, vertex_vk, vertex_bytes)) 8050 if ((buffer & VK_FORMAT_FEATURE_VERTEX_BUFFER_BIT) && vertex_format(fs->Format, vertex_vk, vertex_bytes))
@@ -8008,8 +8095,9 @@ public:
8008 s1 |= D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW; 8095 s1 |= D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW;
8009 // A typed UAV texture read is not a storage-image read: the translator reads it through the 8096 // A typed UAV texture read is not a storage-image read: the translator reads it through the
8010 // texture's sampled binding with the T#'s numeric type (rdna2spirv.py image_read_typed), so a 8097 // texture's sampled binding with the T#'s numeric type (rdna2spirv.py image_read_typed), so a
8011 // format that can be stored can be read. Typed buffer UAVs share the store side's limits: the layer 8098 // format that can be stored can be read. Typed buffer UAVs share the store side's limits: a buffer
8012 // creates no buffer UAV views yet, and rdna2spirv.py FORMATS decodes only some buffer formats. 8099 // UAV is a typed V# the layer writes itself (write_buffer_uav, no VkBufferView), and rdna2spirv.py
8100 // FORMATS decodes only some buffer formats.
8013 s2 |= D3D12_FORMAT_SUPPORT2_UAV_TYPED_STORE | D3D12_FORMAT_SUPPORT2_UAV_TYPED_LOAD; 8101 s2 |= D3D12_FORMAT_SUPPORT2_UAV_TYPED_STORE | D3D12_FORMAT_SUPPORT2_UAV_TYPED_LOAD;
8014 // Image atomics go through the r32ui storage view, which an R32_UINT UAV view gets 8102 // Image atomics go through the r32ui storage view, which an R32_UINT UAV view gets
8015 // (StorageViews::r32ui). Today that is 2D UAVs only: the translator's image atomics cover 2D and 3D, 8103 // (StorageViews::r32ui). Today that is 2D UAVs only: the translator's image atomics cover 2D and 3D,
@@ -9495,6 +9583,7 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin
9495 VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &mesh_features}; 9583 VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &mesh_features};
9496 vkGetPhysicalDeviceFeatures2(info.physical, &features); 9584 vkGetPhysicalDeviceFeatures2(info.physical, &features);
9497 info.mesh_shader = mesh_features.meshShader == VK_TRUE; 9585 info.mesh_shader = mesh_features.meshShader == VK_TRUE;
9586 info.mesh_shader_queries = mesh_features.meshShaderQueries == VK_TRUE;
9498 } 9587 }
9499 } 9588 }
9500 if (!info.mesh_shader) 9589 if (!info.mesh_shader)
@@ -9531,6 +9620,8 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin
9531 // are not used. 9620 // are not used.
9532 VkPhysicalDeviceMeshShaderFeaturesEXT enable_mesh{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT}; 9621 VkPhysicalDeviceMeshShaderFeaturesEXT enable_mesh{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT};
9533 enable_mesh.meshShader = VK_TRUE; 9622 enable_mesh.meshShader = VK_TRUE;
9623 // The mesh-primitives query, which counts the primitives a mesh shader emits (D3D-MESH-CLIPPING-COUNTER).
9624 enable_mesh.meshShaderQueries = info.mesh_shader_queries ? VK_TRUE : VK_FALSE;
9534 9625
9535 void* ext_chain = nullptr; 9626 void* ext_chain = nullptr;
9536 if (info.mesh_shader) { 9627 if (info.mesh_shader) {
@@ -9728,6 +9819,7 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin
9728 return std::any_of(extensions.begin(), extensions.end(), 9819 return std::any_of(extensions.begin(), extensions.end(),
9729 [&](const auto& e) { return std::strcmp(e.extensionName, name) == 0; }); 9820 [&](const auto& e) { return std::strcmp(e.extensionName, name) == 0; });
9730 }; 9821 };
9822 info.depth_range_unrestricted = has_device_extension(VK_EXT_DEPTH_RANGE_UNRESTRICTED_EXTENSION_NAME);
9731 VkPhysicalDeviceFragmentShaderBarycentricFeaturesKHR barycentric{ 9823 VkPhysicalDeviceFragmentShaderBarycentricFeaturesKHR barycentric{
9732 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_BARYCENTRIC_FEATURES_KHR}; 9824 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_BARYCENTRIC_FEATURES_KHR};
9733 if (has_device_extension(VK_KHR_FRAGMENT_SHADER_BARYCENTRIC_EXTENSION_NAME)) { 9825 if (has_device_extension(VK_KHR_FRAGMENT_SHADER_BARYCENTRIC_EXTENSION_NAME)) {
@@ -9801,6 +9893,7 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin
9801 enable.dualSrcBlend = chosen_features.dualSrcBlend; 9893 enable.dualSrcBlend = chosen_features.dualSrcBlend;
9802 enable.logicOp = chosen_features.logicOp; 9894 enable.logicOp = chosen_features.logicOp;
9803 enable.depthClamp = chosen_features.depthClamp; 9895 enable.depthClamp = chosen_features.depthClamp;
9896 enable.multiViewport = chosen_features.multiViewport;
9804 enable.geometryShader = chosen_features.geometryShader; // translated geometry shaders (195 in the corpus) 9897 enable.geometryShader = chosen_features.geometryShader; // translated geometry shaders (195 in the corpus)
9805 // What translated shaders declare (the index's `features`): 64-bit integers in most of the corpus (25,803 of 9898 // What translated shaders declare (the index's `features`): 64-bit integers in most of the corpus (25,803 of
9806 // 26,503 entries), doubles, 16-bit integers, clip and cull distances in a few vertex shaders, image stores 9899 // 26,503 entries), doubles, 16-bit integers, clip and cull distances in a few vertex shaders, image stores
@@ -9904,6 +9997,7 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin
9904 device_info.pEnabledFeatures = &enable; 9997 device_info.pEnabledFeatures = &enable;
9905 std::vector<const char*> device_extensions; 9998 std::vector<const char*> device_extensions;
9906 v13.add_extensions(device_extensions); 9999 v13.add_extensions(device_extensions);
10000 if (info.depth_range_unrestricted) device_extensions.push_back(VK_EXT_DEPTH_RANGE_UNRESTRICTED_EXTENSION_NAME);
9907 if (info.conservative_rasterization) device_extensions.push_back(VK_EXT_CONSERVATIVE_RASTERIZATION_EXTENSION_NAME); 10001 if (info.conservative_rasterization) device_extensions.push_back(VK_EXT_CONSERVATIVE_RASTERIZATION_EXTENSION_NAME);
9908 if (info.image_view_min_lod) device_extensions.push_back(VK_EXT_IMAGE_VIEW_MIN_LOD_EXTENSION_NAME); 10002 if (info.image_view_min_lod) device_extensions.push_back(VK_EXT_IMAGE_VIEW_MIN_LOD_EXTENSION_NAME);
9909 if (info.vertex_attribute_divisor) device_extensions.push_back(divisor_extension); 10003 if (info.vertex_attribute_divisor) device_extensions.push_back(divisor_extension);
diff --git a/runtime/shims/d3d12_xs.cpp b/runtime/shims/d3d12_xs.cpp
index 173106f1c..dfd16fd6a 100644
--- a/runtime/shims/d3d12_xs.cpp
+++ b/runtime/shims/d3d12_xs.cpp
@@ -34,6 +34,7 @@ FARPROC host(const char* name) {
34 34
35using SerializeFn = decltype(&::D3D12SerializeVersionedRootSignature); 35using SerializeFn = decltype(&::D3D12SerializeVersionedRootSignature);
36using DeserializerFn = decltype(&::D3D12CreateRootSignatureDeserializer); 36using DeserializerFn = decltype(&::D3D12CreateRootSignatureDeserializer);
37using VersionedDeserializerFn = decltype(&::D3D12CreateVersionedRootSignatureDeserializer);
37using LegacySerializeFn = decltype(&::D3D12SerializeRootSignature); 38using LegacySerializeFn = decltype(&::D3D12SerializeRootSignature);
38using CreateDeviceFn = decltype(&::D3D12CreateDevice); 39using CreateDeviceFn = decltype(&::D3D12CreateDevice);
39 40
@@ -117,6 +118,17 @@ HRESULT WINAPI create_root_signature_deserializer(const void* data, SIZE_T size,
117 return fn(data, size, iid, out); 118 return fn(data, size, iid, out);
118} 119}
119 120
121HRESULT WINAPI create_versioned_root_signature_deserializer(const void* data, SIZE_T size, REFIID iid, void** out) {
122 static auto fn = reinterpret_cast<VersionedDeserializerFn>(host("D3D12CreateVersionedRootSignatureDeserializer"));
123 if (!fn) return E_NOTIMPL;
124
125 std::vector<uint8_t> cleared;
126 if (rt::d3d12_xs::copy_rts0_blob_clear_xbox_flags(data, static_cast<size_t>(size), cleared)) {
127 return fn(cleared.data(), cleared.size(), iid, out);
128 }
129 return fn(data, size, iid, out);
130}
131
120void* xmem_descriptor_heap_alloc(std::size_t byte_size, std::uint64_t attributes) { 132void* xmem_descriptor_heap_alloc(std::size_t byte_size, std::uint64_t attributes) {
121 const rt::shims::XMemAllocationHooks* hooks = rt::shims::xmem_allocation_hooks(); 133 const rt::shims::XMemAllocationHooks* hooks = rt::shims::xmem_allocation_hooks();
122 return (hooks && hooks->alloc) ? hooks->alloc(byte_size, attributes) : nullptr; 134 return (hooks && hooks->alloc) ? hooks->alloc(byte_size, attributes) : nullptr;
@@ -129,8 +141,9 @@ void xmem_descriptor_heap_free(void* ptr, std::uint64_t attributes) {
129 141
130// Measured shape: D3D12XboxCreateDevice(adapter, params, riid, out), where params is a 24-word block that is only 142// Measured shape: D3D12XboxCreateDevice(adapter, params, riid, out), where params is a 24-word block that is only
131// logged and not used to create the device. The struct's total size is unknown, so the log reads 24 x 32-bit words 143// logged and not used to create the device. The struct's total size is unknown, so the log reads 24 x 32-bit words
132// (96 bytes) and no more. The PC D3D12CreateDevice needs a minimum feature level instead, so 12_0 is used as the 144// (96 bytes) and no more. The PC D3D12CreateDevice needs a minimum feature level instead: create_host_device asks for
133// least restrictive floor; higher feature levels are still exposed by the created device. 145// 11_0, the least restrictive one (BL-2; 12_0 refused an adapter that tops out at 11_x), and the device still has its
146// highest level.
134HRESULT WINAPI D3D12XboxCreateDevice(IUnknown* adapter, const void* params, const IID* riid, void** out) { 147HRESULT WINAPI D3D12XboxCreateDevice(IUnknown* adapter, const void* params, const IID* riid, void** out) {
135 rt::d3d12_xs::set_default_descriptor_heap_allocator(&xmem_descriptor_heap_alloc, &xmem_descriptor_heap_free); 148 rt::d3d12_xs::set_default_descriptor_heap_allocator(&xmem_descriptor_heap_alloc, &xmem_descriptor_heap_free);
136 constexpr auto method = "D3D12XboxCreateDevice"; 149 constexpr auto method = "D3D12XboxCreateDevice";
@@ -207,13 +220,11 @@ HRESULT WINAPI D3D12XboxCreateDevice(IUnknown* adapter, const void* params, cons
207 if (!create) return result(method, E_NOTIMPL); 220 if (!create) return result(method, E_NOTIMPL);
208 221
209 ID3D12Device* real = nullptr; 222 ID3D12Device* real = nullptr;
210 HRESULT hr = create(adapter, D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), 223 HRESULT hr = rt::d3d12_xs::create_host_device(create, adapter, &real);
211 reinterpret_cast<void**>(&real)); 224 if (FAILED(hr)) {
212 if (FAILED(hr) || !real) {
213 if (real) real->Release();
214 std::fprintf(stderr, "[rt] d3d12_xs: D3D12XboxCreateDevice: PC D3D12CreateDevice failed (hr=0x%08lx)\n", 225 std::fprintf(stderr, "[rt] d3d12_xs: D3D12XboxCreateDevice: PC D3D12CreateDevice failed (hr=0x%08lx)\n",
215 static_cast<unsigned long>(hr)); 226 static_cast<unsigned long>(hr));
216 return result(method, FAILED(hr) ? hr : E_FAIL); 227 return result(method, hr);
217 } 228 }
218 229
219 hr = rt::d3d12_xs::create_device_proxy(real, *riid, out); 230 hr = rt::d3d12_xs::create_device_proxy(real, *riid, out);
@@ -232,6 +243,7 @@ HRESULT WINAPI D3D12XboxCreateDevice(IUnknown* adapter, const void* params, cons
232 243
233static_assert(std::is_same_v<decltype(&serialize_root_signature), SerializeFn>); 244static_assert(std::is_same_v<decltype(&serialize_root_signature), SerializeFn>);
234static_assert(std::is_same_v<decltype(&create_root_signature_deserializer), DeserializerFn>); 245static_assert(std::is_same_v<decltype(&create_root_signature_deserializer), DeserializerFn>);
246static_assert(std::is_same_v<decltype(&create_versioned_root_signature_deserializer), VersionedDeserializerFn>);
235static_assert(std::is_same_v<decltype(&serialize_root_signature_legacy), LegacySerializeFn>); 247static_assert(std::is_same_v<decltype(&serialize_root_signature_legacy), LegacySerializeFn>);
236 248
237// Measured call (RT-5, 1.0.2.1): the title calls it once at startup with one pointer to a zeroed 32-byte block whose 249// Measured call (RT-5, 1.0.2.1): the title calls it once at startup with one pointer to a zeroed 32-byte block whose
@@ -246,6 +258,9 @@ SHIM_TABLE(d3d12_xs,
246 {"d3d12_xs.dll", "D3D12SerializeRootSignature", reinterpret_cast<void*>(&serialize_root_signature_legacy)}, 258 {"d3d12_xs.dll", "D3D12SerializeRootSignature", reinterpret_cast<void*>(&serialize_root_signature_legacy)},
247 {"d3d12_xs.dll", "D3D12CreateRootSignatureDeserializer", 259 {"d3d12_xs.dll", "D3D12CreateRootSignatureDeserializer",
248 reinterpret_cast<void*>(&create_root_signature_deserializer)}, 260 reinterpret_cast<void*>(&create_root_signature_deserializer)},
261 {"d3d12_xs.dll", "D3D12CreateVersionedRootSignatureDeserializer",
262 reinterpret_cast<void*>(&create_versioned_root_signature_deserializer)},
263 {"d3d12_xs.dll", "#7", reinterpret_cast<void*>(&create_versioned_root_signature_deserializer)},
249 {"d3d12_xs.dll", "D3D12XboxCreateDevice", reinterpret_cast<void*>(&D3D12XboxCreateDevice)}, 264 {"d3d12_xs.dll", "D3D12XboxCreateDevice", reinterpret_cast<void*>(&D3D12XboxCreateDevice)},
250 {"d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX", reinterpret_cast<void*>(&configure_virtual_memory)}, 265 {"d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX", reinterpret_cast<void*>(&configure_virtual_memory)},
251); 266);
diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp
index 827b00e77..88593951a 100644
--- a/runtime/shims/d3d12_xs_device.cpp
+++ b/runtime/shims/d3d12_xs_device.cpp
@@ -83,8 +83,25 @@ struct DeviceProxy {
83 std::atomic<std::uint32_t> frame_latency{1}; 83 std::atomic<std::uint32_t> frame_latency{1};
84 std::atomic<bool> frame_event_scheduled{false}; 84 std::atomic<bool> frame_event_scheduled{false};
85 std::atomic<std::uint64_t> frame_next_token{1}; 85 std::atomic<std::uint64_t> frame_next_token{1};
86 // Optional presentation wiring attached via set_presentation_handler (guarded by presentation_lock).
87 SRWLOCK presentation_lock = SRWLOCK_INIT;
88 PresentationHandler presentation{};
86}; 89};
87 90
91// Runs f(handler) with the presentation lock held shared, so a detach cannot destroy the presentation mid-call. f
92// returns false, without calling the presentation, when it has no function for the slot; the result says whether
93// f handled the call.
94// ponytail: a presenter callback must not call set_presentation_handler (exclusive inside shared deadlocks), and a
95// detach waits for a WaitFrameEventX in flight up to its timeout.
96template <typename F>
97bool call_presentation(DeviceProxy* self, F&& f) {
98 if (!self) return false;
99 AcquireSRWLockShared(&self->presentation_lock);
100 const bool handled = f(static_cast<const PresentationHandler&>(self->presentation));
101 ReleaseSRWLockShared(&self->presentation_lock);
102 return handled;
103}
104
88constexpr unsigned kHeapSlots = 11; // IUnknown + ID3D12Object + DeviceChild + Pageable + GetDesc + 2 handles 105constexpr unsigned kHeapSlots = 11; // IUnknown + ID3D12Object + DeviceChild + Pageable + GetDesc + 2 handles
89 106
90struct HeapProxy { 107struct HeapProxy {
@@ -253,6 +270,9 @@ const char* slot_name(unsigned slot) {
253 case 78: return "Xbox SetFrameIntervalX"; 270 case 78: return "Xbox SetFrameIntervalX";
254 case 79: return "Xbox ScheduleFrameEventX"; 271 case 79: return "Xbox ScheduleFrameEventX";
255 case 80: return "Xbox WaitFrameEventX"; 272 case 80: return "Xbox WaitFrameEventX";
273 case 86: return "Xbox CreatePipelineState -> PC CreatePipelineState (slot 47)";
274 case 101: return "Xbox CreateStateObject -> PC CreateStateObject (slot 62)";
275 case 108: return "Xbox GetResourceAllocationInfo2 -> PC GetResourceAllocationInfo2 (slot 68)";
256 case 133: return "Xbox CreatePlacedResourceX (a buffer on the title's pages)"; 276 case 133: return "Xbox CreatePlacedResourceX (a buffer on the title's pages)";
257 default: return "forwarded"; 277 default: return "forwarded";
258 } 278 }
@@ -277,24 +297,27 @@ struct XboxDeviceSlotRoutes {
277 unsigned frame_interval = 78; // SetFrameIntervalX(output, interval_us, latency, flags) 297 unsigned frame_interval = 78; // SetFrameIntervalX(output, interval_us, latency, flags)
278 unsigned schedule_event = 79; // ScheduleFrameEventX(event, offset_us, reserved, flags) 298 unsigned schedule_event = 79; // ScheduleFrameEventX(event, offset_us, reserved, flags)
279 unsigned wait_event = 80; // WaitFrameEventX(event, timeout_ms, reserved, flags, &token) 299 unsigned wait_event = 80; // WaitFrameEventX(event, timeout_ms, reserved, flags, &token)
300 unsigned frame_statistics = 81; // GetFrameStatisticsX(token, type_mask, count, out)
280 unsigned queue_x = 48; // CreateCommandQueueX(desc, riid, out) 301 unsigned queue_x = 48; // CreateCommandQueueX(desc, riid, out)
281 unsigned list_x = 73; // CreateCommandListX(desc, allocator, initial_state, riid, out) 302 unsigned list_x = 73; // CreateCommandListX(desc, allocator, initial_state, riid, out)
282}; 303};
283 304
284unsigned env_device_slot(const char* name, unsigned fallback) { 305// Reads a slot number in lo..hi from `name`: an unset variable gives `fallback`; a bad value is logged (`what` names
306// the kind of slot) and ignored.
307unsigned env_slot(const char* name, unsigned fallback, unsigned lo, unsigned hi, const char* what) {
285 char value[32] = {}; 308 char value[32] = {};
286 const DWORD length = GetEnvironmentVariableA(name, value, sizeof(value)); 309 const DWORD length = GetEnvironmentVariableA(name, value, sizeof(value));
287 if (length == 0) return fallback; 310 if (length == 0) return fallback;
288 if (length >= sizeof(value)) { 311 if (length >= sizeof(value)) {
289 std::fprintf(stderr, "[rt] d3d12_xs: %s is too long for a device slot; the default is kept\n", name); 312 std::fprintf(stderr, "[rt] d3d12_xs: %s is too long for a %s; the default is kept\n", name, what);
290 return fallback; 313 return fallback;
291 } 314 }
292 errno = 0; 315 errno = 0;
293 char* end = nullptr; 316 char* end = nullptr;
294 const unsigned long slot = std::strtoul(value, &end, 0); 317 const unsigned long slot = std::strtoul(value, &end, 0);
295 if (errno != 0 || end == value || *end != '\0' || slot < 3 || slot > 127) { 318 if (errno != 0 || end == value || *end != '\0' || slot < lo || slot > hi) {
296 std::fprintf(stderr, "[rt] d3d12_xs: %s=%s is not a device slot in 3..127; the default is kept\n", name, 319 std::fprintf(stderr, "[rt] d3d12_xs: %s=%s is not a %s in %u..%u; the default is kept\n", name, value, what,
297 value); 320 lo, hi);
298 return fallback; 321 return fallback;
299 } 322 }
300 return static_cast<unsigned>(slot); 323 return static_cast<unsigned>(slot);
@@ -303,23 +326,29 @@ unsigned env_device_slot(const char* name, unsigned fallback) {
303const XboxDeviceSlotRoutes& xbox_device_slot_routes() { 326const XboxDeviceSlotRoutes& xbox_device_slot_routes() {
304 static const XboxDeviceSlotRoutes routes = [] { 327 static const XboxDeviceSlotRoutes routes = [] {
305 XboxDeviceSlotRoutes r; 328 XboxDeviceSlotRoutes r;
306 const unsigned frame_interval = env_device_slot("LEONIDA_XS_FRAME_INTERVAL_SLOT", r.frame_interval); 329 const unsigned frame_interval = env_slot("LEONIDA_XS_FRAME_INTERVAL_SLOT", r.frame_interval, 3, 127,
307 const unsigned schedule_event = env_device_slot("LEONIDA_XS_SCHEDULE_EVENT_SLOT", r.schedule_event); 330 "device slot");
308 const unsigned wait_event = env_device_slot("LEONIDA_XS_WAIT_EVENT_SLOT", r.wait_event); 331 const unsigned schedule_event = env_slot("LEONIDA_XS_SCHEDULE_EVENT_SLOT", r.schedule_event, 3, 127,
309 const unsigned queue_x = env_device_slot("LEONIDA_XS_QUEUE_X_SLOT", r.queue_x); 332 "device slot");
310 const unsigned list_x = env_device_slot("LEONIDA_XS_LIST_X_SLOT", r.list_x); 333 const unsigned wait_event = env_slot("LEONIDA_XS_WAIT_EVENT_SLOT", r.wait_event, 3, 127, "device slot");
334 const unsigned frame_statistics = env_slot("LEONIDA_XS_FRAME_STATISTICS_SLOT", r.frame_statistics, 3, 127,
335 "device slot");
336 const unsigned queue_x = env_slot("LEONIDA_XS_QUEUE_X_SLOT", r.queue_x, 3, 127, "device slot");
337 const unsigned list_x = env_slot("LEONIDA_XS_LIST_X_SLOT", r.list_x, 3, 127, "device slot");
311 const bool moved = frame_interval != r.frame_interval || schedule_event != r.schedule_event || 338 const bool moved = frame_interval != r.frame_interval || schedule_event != r.schedule_event ||
312 wait_event != r.wait_event || queue_x != r.queue_x || list_x != r.list_x; 339 wait_event != r.wait_event || frame_statistics != r.frame_statistics ||
340 queue_x != r.queue_x || list_x != r.list_x;
313 r.frame_interval = frame_interval; 341 r.frame_interval = frame_interval;
314 r.schedule_event = schedule_event; 342 r.schedule_event = schedule_event;
315 r.wait_event = wait_event; 343 r.wait_event = wait_event;
344 r.frame_statistics = frame_statistics;
316 r.queue_x = queue_x; 345 r.queue_x = queue_x;
317 r.list_x = list_x; 346 r.list_x = list_x;
318 if (moved) 347 if (moved)
319 std::fprintf(stderr, 348 std::fprintf(stderr,
320 "[rt] d3d12_xs: Xbox device slots: SetFrameIntervalX=%u ScheduleFrameEventX=%u " 349 "[rt] d3d12_xs: Xbox device slots: SetFrameIntervalX=%u ScheduleFrameEventX=%u "
321 "WaitFrameEventX=%u CreateCommandQueueX=%u CreateCommandListX=%u\n", 350 "WaitFrameEventX=%u GetFrameStatisticsX=%u CreateCommandQueueX=%u CreateCommandListX=%u\n",
322 r.frame_interval, r.schedule_event, r.wait_event, r.queue_x, r.list_x); 351 r.frame_interval, r.schedule_event, r.wait_event, r.frame_statistics, r.queue_x, r.list_x);
323 return r; 352 return r;
324 }(); 353 }();
325 return routes; 354 return routes;
@@ -1112,6 +1141,10 @@ inline void note_list_slot(unsigned slot, std::uint64_t a1 = 0, std::uint64_t a2
1112 static_cast<unsigned long long>(a3), static_cast<unsigned long long>(a4)); 1141 static_cast<unsigned long long>(a3), static_cast<unsigned long long>(a4));
1113} 1142}
1114 1143
1144// Measured Xbox ID3D12GraphicsCommandListX IID passed to device slot 73 (CreateCommandListX).
1145constexpr IID kXboxGraphicsCommandListXIid = {
1146 0xc3827890, 0x4024, 0x474c, {0x98, 0xcf, 0x64, 0x5b, 0x51, 0xdc, 0x48, 0x74}};
1147
1115inline bool is_list_iid(const IID& iid) { 1148inline bool is_list_iid(const IID& iid) {
1116 return IsEqualIID(iid, __uuidof(IUnknown)) || IsEqualIID(iid, __uuidof(ID3D12Object)) || 1149 return IsEqualIID(iid, __uuidof(IUnknown)) || IsEqualIID(iid, __uuidof(ID3D12Object)) ||
1117 IsEqualIID(iid, __uuidof(ID3D12DeviceChild)) || IsEqualIID(iid, __uuidof(ID3D12CommandList)) || 1150 IsEqualIID(iid, __uuidof(ID3D12DeviceChild)) || IsEqualIID(iid, __uuidof(ID3D12CommandList)) ||
@@ -1123,7 +1156,8 @@ inline bool is_list_iid(const IID& iid) {
1123 IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList5)) || 1156 IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList5)) ||
1124 IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList6)) || 1157 IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList6)) ||
1125 IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList7)) || 1158 IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList7)) ||
1126 IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList8)); 1159 IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList8)) ||
1160 IsEqualIID(iid, kXboxGraphicsCommandListXIid);
1127} 1161}
1128 1162
1129inline unsigned long list_add_ref(ListProxy* self) { return self->refs.fetch_add(1, std::memory_order_relaxed) + 1; } 1163inline unsigned long list_add_ref(ListProxy* self) { return self->refs.fetch_add(1, std::memory_order_relaxed) + 1; }
@@ -1151,7 +1185,10 @@ inline HRESULT list_query_interface(ListProxy* self, const IID* riid, void** out
1151 if (supports_iid(self->real, *riid)) log_refused_iid("list", *riid); 1185 if (supports_iid(self->real, *riid)) log_refused_iid("list", *riid);
1152 return E_NOINTERFACE; 1186 return E_NOINTERFACE;
1153 } 1187 }
1154 if (!supports_iid(self->real, *riid)) return E_NOINTERFACE; 1188 const IID real_iid = IsEqualIID(*riid, kXboxGraphicsCommandListXIid)
1189 ? __uuidof(ID3D12GraphicsCommandList)
1190 : *riid;
1191 if (!supports_iid(self->real, real_iid)) return E_NOINTERFACE;
1155 *out = self; 1192 *out = self;
1156 list_add_ref(self); 1193 list_add_ref(self);
1157 return S_OK; 1194 return S_OK;
@@ -1340,6 +1377,40 @@ std::uint64_t queue_execute_command_lists(ChildProxy* self, std::uint64_t count_
1340 return 0; 1377 return 0;
1341} 1378}
1342 1379
1380// PresentX is at queue slot 30 in an older runtime layout and 32 in a newer one (public corroboration, XCL; see
1381// docs/d3d12_vulkan.md). 30 is the default and LEONIDA_XS_PRESENT_X_SLOT sets the other. SuspendX and ResumeX have no
1382// default: 0 means not routed, so they answer only when their variable is set.
1383struct XboxQueueSlotRoutes {
1384 unsigned present_x = 30; // PresentX(plane_count, planes, params)
1385 unsigned suspend_x = 0; // SuspendX(flags)
1386 unsigned resume_x = 0; // ResumeX()
1387};
1388
1389const XboxQueueSlotRoutes& xbox_queue_slot_routes() {
1390 static const XboxQueueSlotRoutes routes = [] {
1391 XboxQueueSlotRoutes r;
1392 r.present_x = env_slot("LEONIDA_XS_PRESENT_X_SLOT", r.present_x, kQueuePublicSlots, kQueueSlots - 1,
1393 "queue slot");
1394 r.suspend_x = env_slot("LEONIDA_XS_SUSPEND_X_SLOT", r.suspend_x, kQueuePublicSlots, kQueueSlots - 1,
1395 "queue slot");
1396 r.resume_x = env_slot("LEONIDA_XS_RESUME_X_SLOT", r.resume_x, kQueuePublicSlots, kQueueSlots - 1,
1397 "queue slot");
1398 // Two routes on one slot cannot both answer: PresentX keeps it, then SuspendX; the later route is unrouted.
1399 if (r.suspend_x && r.suspend_x == r.present_x) {
1400 std::fprintf(stderr, "[rt] d3d12_xs: SuspendX slot %u is PresentX's slot; SuspendX is not routed\n",
1401 r.suspend_x);
1402 r.suspend_x = 0;
1403 }
1404 if (r.resume_x && (r.resume_x == r.present_x || r.resume_x == r.suspend_x)) {
1405 std::fprintf(stderr, "[rt] d3d12_xs: ResumeX slot %u is already routed; ResumeX is not routed\n",
1406 r.resume_x);
1407 r.resume_x = 0;
1408 }
1409 return r;
1410 }();
1411 return routes;
1412}
1413
1343template <ChildKind K, unsigned Slot> 1414template <ChildKind K, unsigned Slot>
1344std::uint64_t WINAPI child_slot(ChildProxy* self, std::uint64_t a1, std::uint64_t a2, std::uint64_t a3, 1415std::uint64_t WINAPI child_slot(ChildProxy* self, std::uint64_t a1, std::uint64_t a2, std::uint64_t a3,
1345 std::uint64_t a4, std::uint64_t a5, std::uint64_t a6, std::uint64_t a7, 1416 std::uint64_t a4, std::uint64_t a5, std::uint64_t a6, std::uint64_t a7,
@@ -1382,6 +1453,27 @@ std::uint64_t WINAPI child_slot(ChildProxy* self, std::uint64_t a1, std::uint64_
1382 return hr_to_u64(S_OK); 1453 return hr_to_u64(S_OK);
1383 } 1454 }
1384 if (Slot >= self->slot_count) { 1455 if (Slot >= self->slot_count) {
1456 if constexpr (K == ChildKind::queue) {
1457 const XboxQueueSlotRoutes& qroutes = xbox_queue_slot_routes();
1458 HRESULT hr = S_OK;
1459 if (call_presentation(self->device, [&](const PresentationHandler& p) {
1460 if (Slot == qroutes.present_x && p.present_x) {
1461 hr = p.present_x(p.context, static_cast<UINT>(a1), reinterpret_cast<const void*>(a2),
1462 reinterpret_cast<const void*>(a3));
1463 return true;
1464 }
1465 if (Slot == qroutes.suspend_x && p.suspend_x) {
1466 hr = p.suspend_x(p.context, static_cast<UINT>(a1));
1467 return true;
1468 }
1469 if (Slot == qroutes.resume_x && p.resume_x) {
1470 hr = p.resume_x(p.context);
1471 return true;
1472 }
1473 return false;
1474 }))
1475 return hr_to_u64(hr);
1476 }
1385 bool expected = false; 1477 bool expected = false;
1386 if (ChildStats<K>::beyond_warned[Slot].compare_exchange_strong(expected, true, 1478 if (ChildStats<K>::beyond_warned[Slot].compare_exchange_strong(expected, true,
1387 std::memory_order_relaxed)) { 1479 std::memory_order_relaxed)) {
@@ -1564,8 +1656,14 @@ HRESULT proxy_create_command_queue(DeviceProxy* self, const D3D12_COMMAND_QUEUE_
1564// 60 Hz), and latency is the allowed frames in flight. S_OK even for 0: a boot must not abort here, and nothing paces. 1656// 60 Hz), and latency is the allowed frames in flight. S_OK even for 0: a boot must not abort here, and nothing paces.
1565HRESULT proxy_set_frame_interval_x(DeviceProxy* self, std::uint64_t output, std::uint64_t interval_us, 1657HRESULT proxy_set_frame_interval_x(DeviceProxy* self, std::uint64_t output, std::uint64_t interval_us,
1566 std::uint64_t latency, std::uint64_t flags) { 1658 std::uint64_t latency, std::uint64_t flags) {
1567 (void)output; 1659 HRESULT hr = S_OK;
1568 (void)flags; 1660 if (call_presentation(self, [&](const PresentationHandler& p) {
1661 if (!p.set_frame_interval) return false;
1662 hr = p.set_frame_interval(p.context, reinterpret_cast<IUnknown*>(output), static_cast<UINT>(interval_us),
1663 static_cast<UINT>(latency), static_cast<UINT>(flags));
1664 return true;
1665 }))
1666 return hr;
1569 self->frame_interval_us.store(static_cast<std::uint32_t>(interval_us), std::memory_order_relaxed); 1667 self->frame_interval_us.store(static_cast<std::uint32_t>(interval_us), std::memory_order_relaxed);
1570 self->frame_latency.store(static_cast<std::uint32_t>(latency ? latency : 1), std::memory_order_relaxed); 1668 self->frame_latency.store(static_cast<std::uint32_t>(latency ? latency : 1), std::memory_order_relaxed);
1571 return S_OK; 1669 return S_OK;
@@ -1574,22 +1672,31 @@ HRESULT proxy_set_frame_interval_x(DeviceProxy* self, std::uint64_t output, std:
1574// Xbox device slot 79 (public HLE): ScheduleFrameEventX(event, offset_us, pEvent, flags); our pacer has only the origin. 1672// Xbox device slot 79 (public HLE): ScheduleFrameEventX(event, offset_us, pEvent, flags); our pacer has only the origin.
1575HRESULT proxy_schedule_frame_event_x(DeviceProxy* self, std::uint64_t event, std::uint64_t offset_us, 1673HRESULT proxy_schedule_frame_event_x(DeviceProxy* self, std::uint64_t event, std::uint64_t offset_us,
1576 std::uint64_t flags) { 1674 std::uint64_t flags) {
1577 (void)event; 1675 HRESULT hr = S_OK;
1578 (void)offset_us; 1676 if (call_presentation(self, [&](const PresentationHandler& p) {
1579 (void)flags; 1677 if (!p.schedule_frame_event) return false;
1678 hr = p.schedule_frame_event(p.context, static_cast<UINT>(event), static_cast<UINT>(offset_us),
1679 static_cast<UINT>(flags));
1680 return true;
1681 }))
1682 return hr;
1580 self->frame_event_scheduled.store(true, std::memory_order_relaxed); 1683 self->frame_event_scheduled.store(true, std::memory_order_relaxed);
1581 return S_OK; 1684 return S_OK;
1582} 1685}
1583 1686
1584// Xbox device slot 80 (public HLE): WaitFrameEventX(event, timeout_ms, pEvent, flags, &token). It returns at once with 1687// Xbox device slot 80 (public HLE): WaitFrameEventX(event, timeout_ms, pEvent, flags, &token). When a presenter is
1585// a fresh non-zero token (the first-frame choice): there is no vblank source behind the device before a presenter, and 1688// attached, forwards directly to it; otherwise returns at once with a fresh non-zero token so boot tests cannot stall.
1586// a zero wait cannot stall the title. A null token pointer is E_POINTER, as a _Out_ parameter.
1587HRESULT proxy_wait_frame_event_x(DeviceProxy* self, std::uint64_t event, std::uint64_t timeout_ms, 1689HRESULT proxy_wait_frame_event_x(DeviceProxy* self, std::uint64_t event, std::uint64_t timeout_ms,
1588 std::uint64_t flags, std::uint64_t token_word) { 1690 std::uint64_t flags, std::uint64_t token_word) {
1589 (void)event;
1590 (void)timeout_ms;
1591 (void)flags;
1592 auto* token = reinterpret_cast<std::uint64_t*>(token_word); 1691 auto* token = reinterpret_cast<std::uint64_t*>(token_word);
1692 HRESULT hr = S_OK;
1693 if (call_presentation(self, [&](const PresentationHandler& p) {
1694 if (!p.wait_frame_event) return false;
1695 hr = p.wait_frame_event(p.context, static_cast<UINT>(event), static_cast<DWORD>(timeout_ms),
1696 static_cast<UINT>(flags), token);
1697 return true;
1698 }))
1699 return hr;
1593 if (!token) return E_POINTER; 1700 if (!token) return E_POINTER;
1594 std::uint64_t value = self->frame_next_token.fetch_add(1, std::memory_order_relaxed); 1701 std::uint64_t value = self->frame_next_token.fetch_add(1, std::memory_order_relaxed);
1595 if (value == 0) value = self->frame_next_token.fetch_add(1, std::memory_order_relaxed); // skip the null token 1702 if (value == 0) value = self->frame_next_token.fetch_add(1, std::memory_order_relaxed); // skip the null token
@@ -1626,8 +1733,11 @@ HRESULT proxy_create_command_list_x(DeviceProxy* self, std::uint64_t desc_word,
1626 if (!allocator) allocator = reinterpret_cast<ID3D12CommandAllocator*>(allocator_word); 1733 if (!allocator) allocator = reinterpret_cast<ID3D12CommandAllocator*>(allocator_word);
1627 auto* initial_state = reinterpret_cast<ID3D12PipelineState*>(initial_state_word); 1734 auto* initial_state = reinterpret_cast<ID3D12PipelineState*>(initial_state_word);
1628 void* created = nullptr; 1735 void* created = nullptr;
1736 const IID& create_iid = IsEqualIID(*riid, kXboxGraphicsCommandListXIid)
1737 ? __uuidof(ID3D12GraphicsCommandList)
1738 : *riid;
1629 const HRESULT hr = self->real->CreateCommandList(0, type, allocator, initial_state, 1739 const HRESULT hr = self->real->CreateCommandList(0, type, allocator, initial_state,
1630 *riid, &created); 1740 create_iid, &created);
1631 if (FAILED(hr)) return hr; 1741 if (FAILED(hr)) return hr;
1632 return wrap_list(static_cast<IUnknown*>(created), self, riid, out); 1742 return wrap_list(static_cast<IUnknown*>(created), self, riid, out);
1633} 1743}
@@ -2460,6 +2570,23 @@ bool route_xbox_device_slot(DeviceProxy* self, unsigned slot, std::uint64_t a1,
2460 } else if (slot == routes.wait_event) { 2570 } else if (slot == routes.wait_event) {
2461 log_xbox_route_once(slot, "WaitFrameEventX", a1, a2, a3, a4, a5); 2571 log_xbox_route_once(slot, "WaitFrameEventX", a1, a2, a3, a4, a5);
2462 result = hr_to_u64(proxy_wait_frame_event_x(self, a1, a2, a4, a5)); 2572 result = hr_to_u64(proxy_wait_frame_event_x(self, a1, a2, a4, a5));
2573 } else if (slot == routes.frame_statistics) {
2574 HRESULT hr = S_OK;
2575 if (call_presentation(self, [&](const PresentationHandler& p) {
2576 if (!p.get_frame_statistics) return false;
2577 log_xbox_route_once(slot, "GetFrameStatisticsX", a1, a2, a3, a4, a5);
2578 hr = p.get_frame_statistics(p.context, a1, static_cast<UINT>(a2), reinterpret_cast<UINT*>(a3),
2579 reinterpret_cast<void*>(a4));
2580 return true;
2581 })) {
2582 result = hr_to_u64(hr);
2583 } else {
2584 // No presenter: no statistics yet (S_FALSE with a zero count, the "not available yet" answer in
2585 // docs/d3d12_vulkan.md), and never the PC slot 81 (ID3D12Device13::OpenExistingHeapFromAddress1).
2586 log_xbox_route_once(slot, "GetFrameStatisticsX", a1, a2, a3, a4, a5);
2587 if (auto* count = reinterpret_cast<UINT*>(a3)) *count = 0;
2588 result = hr_to_u64(S_FALSE);
2589 }
2463 } else if (slot == routes.queue_x) { 2590 } else if (slot == routes.queue_x) {
2464 log_xbox_route_once(slot, "CreateCommandQueueX", a1, a2, a3, a4, a5); 2591 log_xbox_route_once(slot, "CreateCommandQueueX", a1, a2, a3, a4, a5);
2465 result = hr_to_u64(proxy_create_command_queue_xbox(self, reinterpret_cast<const std::uint32_t*>(a1), 2592 result = hr_to_u64(proxy_create_command_queue_xbox(self, reinterpret_cast<const std::uint32_t*>(a1),
@@ -2490,6 +2617,97 @@ std::uint64_t proxy_slot74(std::uint64_t a1, std::uint64_t a2, std::uint64_t a3)
2490 return hr_to_u64(S_OK); 2617 return hr_to_u64(S_OK);
2491} 2618}
2492 2619
2620// Xbox slot 86: CreatePipelineState(desc, riid, out), forwarded to PC ID3D12Device2::CreatePipelineState (PC slot 47).
2621HRESULT proxy_create_pipeline_state(DeviceProxy* self, const D3D12_PIPELINE_STATE_STREAM_DESC* desc, const IID* riid,
2622 void** out) {
2623 if (out) *out = nullptr;
2624 if (self->slot_count <= 47) return refuse_beyond_device(86, self->slot_count); // predates ID3D12Device2
2625 if (!riid) return E_POINTER;
2626 using Fn = HRESULT(WINAPI*)(ID3D12Device*, const D3D12_PIPELINE_STATE_STREAM_DESC*, const IID*, void**);
2627 return reinterpret_cast<Fn>(self->real_vtable[47])(self->real, desc, riid, out);
2628}
2629
2630// Xbox slot 101: CreateStateObject(desc, riid, out), forwarded to PC ID3D12Device5::CreateStateObject (PC slot 62,
2631// displaced on Xbox by compute-PSO slot 62).
2632HRESULT proxy_create_state_object(DeviceProxy* self, const D3D12_STATE_OBJECT_DESC* desc, const IID* riid, void** out) {
2633 if (out) *out = nullptr;
2634 if (self->slot_count <= 62) return refuse_beyond_device(101, self->slot_count); // predates ID3D12Device5
2635 if (!riid) return E_POINTER;
2636 using Fn = HRESULT(WINAPI*)(ID3D12Device*, const D3D12_STATE_OBJECT_DESC*, const IID*, void**);
2637 return reinterpret_cast<Fn>(self->real_vtable[62])(self->real, desc, riid, out);
2638}
2639
2640// Xbox slot 108: GetResourceAllocationInfo2, forwarded to PC ID3D12Device8::GetResourceAllocationInfo2 (PC slot 68).
2641// The retail executable calls struct-returning device methods with the C ABI (return buffer in RCX, device proxy in
2642// RDX); a PC C++ caller passes the proxy in RCX and the return buffer in RDX. Both orders are accepted. The title's
2643// descriptor builder populates 56-byte D3D12_RESOURCE_DESC entries, so the input array is indexed with a 56-byte
2644// stride (sizeof(D3D12_RESOURCE_DESC)), each entry is expanded into a zeroed D3D12_RESOURCE_DESC1 with
2645// SamplerFeedbackMipRegion cleared, and Xbox layout words (e.g. 0x101, 0x105) and console flag bits above the PC
2646// D3D12_RESOURCE_FLAGS are normalized on the copy before the PC call.
2647std::uint64_t proxy_get_resource_allocation_info2(DeviceProxy* self, std::uint64_t a1, std::uint64_t a2,
2648 std::uint64_t a3, std::uint64_t a4, std::uint64_t a5) {
2649 DeviceProxy* proxy = nullptr;
2650 D3D12_RESOURCE_ALLOCATION_INFO* ret = nullptr;
2651 if (is_device_proxy(self)) {
2652 proxy = self;
2653 ret = reinterpret_cast<D3D12_RESOURCE_ALLOCATION_INFO*>(a1);
2654 } else if (is_device_proxy(reinterpret_cast<const void*>(a1))) {
2655 proxy = reinterpret_cast<DeviceProxy*>(a1);
2656 ret = reinterpret_cast<D3D12_RESOURCE_ALLOCATION_INFO*>(self);
2657 }
2658 if (!ret) return 0;
2659 if (!proxy) {
2660 *ret = {UINT64_MAX, 0};
2661 return reinterpret_cast<std::uint64_t>(ret);
2662 }
2663 if (proxy->slot_count <= 68) {
2664 refuse_beyond_device(108, proxy->slot_count);
2665 *ret = {UINT64_MAX, 0};
2666 return reinterpret_cast<std::uint64_t>(ret);
2667 }
2668 const auto visible_mask = static_cast<UINT>(a2);
2669 const auto count = static_cast<UINT>(a3);
2670 const auto* raw_descs = reinterpret_cast<const D3D12_RESOURCE_DESC*>(a4);
2671 auto* info1 = reinterpret_cast<D3D12_RESOURCE_ALLOCATION_INFO1*>(a5);
2672 if (count > 0 && !raw_descs) { // a count with no descriptor array: refuse like the other bad-input paths
2673 *ret = {UINT64_MAX, 0};
2674 return reinterpret_cast<std::uint64_t>(ret);
2675 }
2676
2677 std::vector<D3D12_RESOURCE_DESC1> cleaned;
2678 const D3D12_RESOURCE_DESC1* descs_to_pass = nullptr;
2679 if (raw_descs && count > 0) {
2680 try {
2681 cleaned.resize(count);
2682 } catch (...) {
2683 *ret = {UINT64_MAX, 0};
2684 return reinterpret_cast<std::uint64_t>(ret);
2685 }
2686 for (UINT i = 0; i < count; ++i) {
2687 D3D12_RESOURCE_DESC1 d{};
2688 std::memcpy(&d, &raw_descs[i], sizeof(D3D12_RESOURCE_DESC));
2689 d.SamplerFeedbackMipRegion = {};
2690 if (static_cast<std::uint32_t>(d.Layout) >
2691 static_cast<std::uint32_t>(D3D12_TEXTURE_LAYOUT_64KB_STANDARD_SWIZZLE)) {
2692 d.Layout = d.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER ? D3D12_TEXTURE_LAYOUT_ROW_MAJOR
2693 : D3D12_TEXTURE_LAYOUT_UNKNOWN;
2694 }
2695 // The same PC flag set as slot 133: up to RAYTRACING_ACCELERATION_STRUCTURE (0x100) and
2696 // USE_TIGHT_ALIGNMENT (0x400), with 0x200 dropped.
2697 constexpr std::uint32_t kPcResourceFlagsMask = 0x5FFu;
2698 d.Flags = static_cast<D3D12_RESOURCE_FLAGS>(static_cast<std::uint32_t>(d.Flags) & kPcResourceFlagsMask);
2699 cleaned[i] = d;
2700 }
2701 descs_to_pass = cleaned.data();
2702 }
2703
2704 using Fn = D3D12_RESOURCE_ALLOCATION_INFO*(WINAPI*)(
2705 ID3D12Device*, D3D12_RESOURCE_ALLOCATION_INFO*, UINT, UINT, const D3D12_RESOURCE_DESC1*,
2706 D3D12_RESOURCE_ALLOCATION_INFO1*);
2707 reinterpret_cast<Fn>(proxy->real_vtable[68])(proxy->real, ret, visible_mask, count, descs_to_pass, info1);
2708 return reinterpret_cast<std::uint64_t>(ret);
2709}
2710
2493template <unsigned Slot> 2711template <unsigned Slot>
2494std::uint64_t WINAPI proxy_slot(DeviceProxy* self, std::uint64_t a1, std::uint64_t a2, std::uint64_t a3, 2712std::uint64_t WINAPI proxy_slot(DeviceProxy* self, std::uint64_t a1, std::uint64_t a2, std::uint64_t a3,
2495 std::uint64_t a4, std::uint64_t a5, std::uint64_t a6, std::uint64_t a7, 2713 std::uint64_t a4, std::uint64_t a5, std::uint64_t a6, std::uint64_t a7,
@@ -2649,16 +2867,28 @@ std::uint64_t WINAPI proxy_slot(DeviceProxy* self, std::uint64_t a1, std::uint64
2649 // methods. The check is before the slot-count refusal because slot 80 is outside a PC ID3D12Device11 table. 2867 // methods. The check is before the slot-count refusal because slot 80 is outside a PC ID3D12Device11 table.
2650 std::uint64_t routed = 0; 2868 std::uint64_t routed = 0;
2651 if (route_xbox_device_slot(self, Slot, a1, a2, a3, a4, a5, routed)) return routed; 2869 if (route_xbox_device_slot(self, Slot, a1, a2, a3, a4, a5, routed)) return routed;
2652 if (Slot >= self->slot_count) return hr_to_u64(refuse_beyond_device(Slot, self->slot_count)); 2870 if constexpr (Slot == 86) {
2871 return hr_to_u64(proxy_create_pipeline_state(
2872 self, reinterpret_cast<const D3D12_PIPELINE_STATE_STREAM_DESC*>(a1),
2873 reinterpret_cast<const IID*>(a2), reinterpret_cast<void**>(a3)));
2874 } else if constexpr (Slot == 101) {
2875 return hr_to_u64(proxy_create_state_object(
2876 self, reinterpret_cast<const D3D12_STATE_OBJECT_DESC*>(a1),
2877 reinterpret_cast<const IID*>(a2), reinterpret_cast<void**>(a3)));
2878 } else if constexpr (Slot == 108) {
2879 return proxy_get_resource_allocation_info2(self, a1, a2, a3, a4, a5);
2880 } else {
2881 if (Slot >= self->slot_count) return hr_to_u64(refuse_beyond_device(Slot, self->slot_count));
2653 2882
2654 // The PC vtable entry, called with the PC device as `this`. Integer/pointer arguments, the hidden 2883 // The PC vtable entry, called with the PC device as `this`. Integer/pointer arguments, the hidden
2655 // struct-return pointer and any stack arguments keep their positions; XMM registers are untouched. 2884 // struct-return pointer and any stack arguments keep their positions; XMM registers are untouched.
2656 using ForwardFn = std::uint64_t(WINAPI*)(void*, std::uint64_t, std::uint64_t, std::uint64_t, 2885 using ForwardFn = std::uint64_t(WINAPI*)(void*, std::uint64_t, std::uint64_t, std::uint64_t,
2657 std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, 2886 std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t,
2658 std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, 2887 std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t,
2659 std::uint64_t, std::uint64_t, std::uint64_t); 2888 std::uint64_t, std::uint64_t, std::uint64_t);
2660 auto fn = reinterpret_cast<ForwardFn>(self->real_vtable[Slot]); 2889 auto fn = reinterpret_cast<ForwardFn>(self->real_vtable[Slot]);
2661 return fn(self->real, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14); 2890 return fn(self->real, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14);
2891 }
2662 } 2892 }
2663} 2893}
2664 2894
@@ -2863,6 +3093,33 @@ HRESULT create_device_proxy(ID3D12Device* real, REFIID riid, void** out) {
2863 return S_OK; 3093 return S_OK;
2864} 3094}
2865 3095
3096D3D_FEATURE_LEVEL max_feature_level(ID3D12Device* device) {
3097 if (!device) return D3D_FEATURE_LEVEL(0);
3098 static const D3D_FEATURE_LEVEL kLevels[] = {D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_12_0,
3099 D3D_FEATURE_LEVEL_12_1, D3D_FEATURE_LEVEL_12_2};
3100 D3D12_FEATURE_DATA_FEATURE_LEVELS levels{UINT(std::size(kLevels)), kLevels, D3D_FEATURE_LEVEL(0)};
3101 if (FAILED(device->CheckFeatureSupport(D3D12_FEATURE_FEATURE_LEVELS, &levels, sizeof(levels))))
3102 return D3D_FEATURE_LEVEL(0);
3103 return levels.MaxSupportedFeatureLevel;
3104}
3105
3106HRESULT create_host_device(HostCreateDeviceFn create, IUnknown* adapter, ID3D12Device** out) {
3107 if (!out) return E_POINTER;
3108 *out = nullptr;
3109 if (!create) return E_NOTIMPL;
3110 ID3D12Device* device = nullptr;
3111 const HRESULT hr = create(adapter, kHostDeviceFloor, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
3112 if (FAILED(hr) || !device) {
3113 if (device) device->Release();
3114 return FAILED(hr) ? hr : E_FAIL;
3115 }
3116 const D3D_FEATURE_LEVEL level = max_feature_level(device);
3117 std::fprintf(stderr, "[rt] d3d12_xs: host device created at minimum feature level 11_0; highest level %u_%u\n",
3118 unsigned(level) >> 12, (unsigned(level) >> 8) & 0xf);
3119 *out = device;
3120 return S_OK;
3121}
3122
2866bool is_device_proxy(const void* device) { 3123bool is_device_proxy(const void* device) {
2867 return device && *reinterpret_cast<void* const*>(device) == reinterpret_cast<void*>(get_vtable()); 3124 return device && *reinterpret_cast<void* const*>(device) == reinterpret_cast<void*>(get_vtable());
2868} 3125}
@@ -2934,6 +3191,15 @@ void set_console_descriptor_heap_handler(ConsoleDescriptorHeapHandler handler) {
2934 g_console_descriptor_heap.store(handler, std::memory_order_release); 3191 g_console_descriptor_heap.store(handler, std::memory_order_release);
2935} 3192}
2936 3193
3194bool set_presentation_handler(void* device, const PresentationHandler* handler) {
3195 auto* proxy = static_cast<DeviceProxy*>(device_proxy_primary(device));
3196 if (!proxy) return false;
3197 AcquireSRWLockExclusive(&proxy->presentation_lock);
3198 proxy->presentation = handler ? *handler : PresentationHandler{};
3199 ReleaseSRWLockExclusive(&proxy->presentation_lock);
3200 return true;
3201}
3202
2937ID3D12Device* device_proxy_real_device(const void* device) { 3203ID3D12Device* device_proxy_real_device(const void* device) {
2938 if (!is_device_proxy(device)) return nullptr; 3204 if (!is_device_proxy(device)) return nullptr;
2939 return static_cast<const DeviceProxy*>(device)->real; 3205 return static_cast<const DeviceProxy*>(device)->real;
@@ -2942,11 +3208,11 @@ ID3D12Device* device_proxy_real_device(const void* device) {
2942bool device_slot_overridden(unsigned slot) { 3208bool device_slot_overridden(unsigned slot) {
2943 if (slot <= 2 || slot == 8 || slot == 9 || slot == 14 || (slot >= 17 && slot <= 24) || slot == 25 || slot == 26 || slot == 31 || slot == 32 || slot == 34 || slot == 35 || 3209 if (slot <= 2 || slot == 8 || slot == 9 || slot == 14 || (slot >= 17 && slot <= 24) || slot == 25 || slot == 26 || slot == 31 || slot == 32 || slot == 34 || slot == 35 ||
2944 slot == 36 || slot == 41 || slot == 45 || slot == 46 || slot == 50 || slot == 56 || slot == 61 || slot == 74 || slot == 62 || slot == 67 || 3210 slot == 36 || slot == 41 || slot == 45 || slot == 46 || slot == 50 || slot == 56 || slot == 61 || slot == 74 || slot == 62 || slot == 67 ||
2945 slot == 70 || slot == 75 || slot == 76 || slot == 133 || slot == kCreateCommittedResource3X) 3211 slot == 70 || slot == 75 || slot == 76 || slot == 133 || slot == kCreateCommittedResource3X || slot == 86 || slot == 101 || slot == 108)
2946 return true; 3212 return true;
2947 const XboxDeviceSlotRoutes& routes = xbox_device_slot_routes(); 3213 const XboxDeviceSlotRoutes& routes = xbox_device_slot_routes();
2948 return slot == routes.frame_interval || slot == routes.schedule_event || slot == routes.wait_event || 3214 return slot == routes.frame_interval || slot == routes.schedule_event || slot == routes.wait_event ||
2949 slot == routes.queue_x || slot == routes.list_x; 3215 slot == routes.frame_statistics || slot == routes.queue_x || slot == routes.list_x;
2950} 3216}
2951 3217
2952bool is_queue_proxy(const void* queue) { return is_child_proxy<ChildKind::queue>(queue); } 3218bool is_queue_proxy(const void* queue) { return is_child_proxy<ChildKind::queue>(queue); }
diff --git a/runtime/shims/d3d12_xs_device.h b/runtime/shims/d3d12_xs_device.h
index b9062ff20..c9b62b3a9 100644
--- a/runtime/shims/d3d12_xs_device.h
+++ b/runtime/shims/d3d12_xs_device.h
@@ -33,6 +33,14 @@
33// slots 78/79/80 SetFrameIntervalX, ScheduleFrameEventX, WaitFrameEventX. A per-device token state machine answers 33// slots 78/79/80 SetFrameIntervalX, ScheduleFrameEventX, WaitFrameEventX. A per-device token state machine answers
34// them before the PC vtable is indexed; WaitFrameEventX returns at once with a fresh non-zero token. 34// them before the PC vtable is indexed; WaitFrameEventX returns at once with a fresh non-zero token.
35// Slot 80 is outside a PC ID3D12Device11 table, so it is checked before the beyond-table refusal. 35// Slot 80 is outside a PC ID3D12Device11 table, so it is checked before the beyond-table refusal.
36// slot 86 CreatePipelineState(desc, riid, out) -> PC ID3D12Device2::CreatePipelineState (PC slot 47).
37// slot 101 CreateStateObject(desc, riid, out) -> PC ID3D12Device5::CreateStateObject (PC slot 62, displaced on
38// Xbox by compute-PSO slot 62).
39// slot 108 GetResourceAllocationInfo2(ret, this, visible_mask, count, descs, info1) -> PC
40// ID3D12Device8::GetResourceAllocationInfo2 (PC slot 68), accepting the console C-ABI struct return
41// (return buffer in RCX, device in RDX) as well as the PC C++ order, with each 56-byte
42// D3D12_RESOURCE_DESC expanded to a zero-initialized D3D12_RESOURCE_DESC1 and Xbox layout words and
43// flag bits normalized on the copy.
36// The slots 48/73/78/79/80 are the public HLE Freminet/ScarlettX's observation, not Microsoft documentation, and can 44// The slots 48/73/78/79/80 are the public HLE Freminet/ScarlettX's observation, not Microsoft documentation, and can
37// be moved with LEONIDA_XS_QUEUE_X_SLOT, LEONIDA_XS_LIST_X_SLOT, LEONIDA_XS_FRAME_INTERVAL_SLOT, 45// be moved with LEONIDA_XS_QUEUE_X_SLOT, LEONIDA_XS_LIST_X_SLOT, LEONIDA_XS_FRAME_INTERVAL_SLOT,
38// LEONIDA_XS_SCHEDULE_EVENT_SLOT and LEONIDA_XS_WAIT_EVENT_SLOT (3..127; anything else is logged once and ignored). 46// LEONIDA_XS_SCHEDULE_EVENT_SLOT and LEONIDA_XS_WAIT_EVENT_SLOT (3..127; anything else is logged once and ignored).
@@ -84,6 +92,18 @@ HRESULT create_device_proxy(ID3D12Device* real, REFIID riid, void** out);
84// True when `device` points at a proxy created by create_device_proxy. Used by the tests. 92// True when `device` points at a proxy created by create_device_proxy. Used by the tests.
85bool is_device_proxy(const void* device); 93bool is_device_proxy(const void* device);
86 94
95// The host path of D3D12XboxCreateDevice (BL-2, docs/d3d12_xs_surface.md): the PC D3D12CreateDevice (`create`)
96// asked for kHostDeviceFloor, the lowest feature level D3D12 creates a device at. It is a minimum, so asking for it
97// refuses no adapter the title can run on and still gives the device its highest level, which FEATURE_LEVELS then
98// reports. A null `create`, or S_OK with no device, is E_NOTIMPL / E_FAIL; `*out` is null on failure.
99constexpr D3D_FEATURE_LEVEL kHostDeviceFloor = D3D_FEATURE_LEVEL_11_0;
100using HostCreateDeviceFn = HRESULT(WINAPI*)(IUnknown* adapter, D3D_FEATURE_LEVEL minimum, REFIID riid, void** out);
101HRESULT create_host_device(HostCreateDeviceFn create, IUnknown* adapter, ID3D12Device** out);
102
103// The highest of 11_0, 11_1, 12_0, 12_1 and 12_2 `device` reports through D3D12_FEATURE_FEATURE_LEVELS, or 0 when
104// the query fails.
105D3D_FEATURE_LEVEL max_feature_level(ID3D12Device* device);
106
87// IDXGIDevice1 on the device. A GDKX title asks its device for IDXGIDevice1, then GetAdapter and EnumOutputs(0), 107// IDXGIDevice1 on the device. A GDKX title asks its device for IDXGIDevice1, then GetAdapter and EnumOutputs(0),
88// to find the output it gives SetFrameIntervalX (docs/d3d12_vulkan.md section 4.5). The proxy answers IDXGIObject, 108// to find the output it gives SetFrameIntervalX (docs/d3d12_vulkan.md section 4.5). The proxy answers IDXGIObject,
89// IDXGIDevice and IDXGIDevice1 itself, as one COM object with the device (same reference count, QueryInterface 109// IDXGIDevice and IDXGIDevice1 itself, as one COM object with the device (same reference count, QueryInterface
@@ -153,11 +173,29 @@ using ConsoleDescriptorHeapHandler = HRESULT (*)(ID3D12Device* real, const D3D12
153 REFIID riid, void** out); 173 REFIID riid, void** out);
154void set_console_descriptor_heap_handler(ConsoleDescriptorHeapHandler handler); 174void set_console_descriptor_heap_handler(ConsoleDescriptorHeapHandler handler);
155 175
176// Presentation wiring: connects device frame-event slots (78/79/80/81: SetFrameIntervalX, ScheduleFrameEventX,
177// WaitFrameEventX, GetFrameStatisticsX; 81 is LEONIDA_XS_FRAME_STATISTICS_SLOT) and queue presentation slots (PresentX
178// at 30, or LEONIDA_XS_PRESENT_X_SLOT; SuspendX and ResumeX are routed only when LEONIDA_XS_SUSPEND_X_SLOT /
179// LEONIDA_XS_RESUME_X_SLOT are set) to an external presenter such as rt::d3d12::XboxPresentation without coupling
180// d3d12_xs_device to Vulkan headers. Passing nullptr detaches the handler and restores the default mock/fallback
181// behavior.
182struct PresentationHandler {
183 void* context = nullptr;
184 HRESULT (*set_frame_interval)(void* context, IUnknown* output, UINT interval_us, UINT latency, UINT flags) = nullptr;
185 HRESULT (*schedule_frame_event)(void* context, UINT event, UINT offset_us, UINT flags) = nullptr;
186 HRESULT (*wait_frame_event)(void* context, UINT event, DWORD timeout_ms, UINT flags, std::uint64_t* token) = nullptr;
187 HRESULT (*get_frame_statistics)(void* context, std::uint64_t token, UINT type_mask, UINT* count, void* out) = nullptr;
188 HRESULT (*present_x)(void* context, UINT plane_count, const void* planes, const void* params) = nullptr;
189 HRESULT (*suspend_x)(void* context, UINT flags) = nullptr;
190 HRESULT (*resume_x)(void* context) = nullptr;
191};
192bool set_presentation_handler(void* device, const PresentationHandler* handler);
193
156// True for slots the proxy handles itself rather than forwarding verbatim: IUnknown (0-2), 8 and 75 (queue 194// True for slots the proxy handles itself rather than forwarding verbatim: IUnknown (0-2), 8 and 75 (queue
157// proxies), 9 (allocator proxies), 14 (descriptor heap proxy), 17-24 (CPU descriptor handle translation), 26 (the 195// proxies), 9 (allocator proxies), 14 (descriptor heap proxy), 17-24 (CPU descriptor handle translation), 26 (the
158// console's struct-return form), 196// console's struct-return form),
159// 31/34/35/45/46/50 (proxies unwrapped), 32 and 36 (fence proxies), 48/73 and 197// 31/34/35/45/46/50 (proxies unwrapped), 32 and 36 (fence proxies), 48/73 and
160// 78/79/80 (the Xbox slots above, at their configured indices), 62, 67, 70, 74, 76 and 127. Slot 10 is intentionally false: the 198// 78/79/80 (the Xbox slots above, at their configured indices), 62, 67, 70, 74, 76, 86, 101, 108 and 127. Slot 10 is intentionally false: the
161// measured 9/10 handle conversion is on the heap proxy, and device slot 9 is CreateCommandAllocator, which the proxy 199// measured 9/10 handle conversion is on the heap proxy, and device slot 9 is CreateCommandAllocator, which the proxy
162// handles for the allocator proxy. 200// handles for the allocator proxy.
163bool device_slot_overridden(unsigned slot); 201bool device_slot_overridden(unsigned slot);
diff --git a/runtime/shims/file_system.cpp b/runtime/shims/file_system.cpp
index 75f5e9810..f6934c5ed 100644
--- a/runtime/shims/file_system.cpp
+++ b/runtime/shims/file_system.cpp
@@ -355,6 +355,10 @@ std::vector<std::wstring> parent_of(const std::vector<std::wstring>& parts) {
355 return parts.empty() ? parts : std::vector<std::wstring>(parts.begin(), parts.end() - 1); 355 return parts.empty() ? parts : std::vector<std::wstring>(parts.begin(), parts.end() - 1);
356} 356}
357 357
358DWORD missing_error(const Roots& r, const std::vector<std::wstring>& parts) {
359 return is_folder(r, parent_of(parts)) ? ERROR_FILE_NOT_FOUND : ERROR_PATH_NOT_FOUND;
360}
361
358// Whether a folder has nothing in the title's view: no overlay entry and no package entry that is not deleted. 362// Whether a folder has nothing in the title's view: no overlay entry and no package entry that is not deleted.
359bool empty_in_view(const Roots& r, const std::vector<std::wstring>& parts) { 363bool empty_in_view(const Roots& r, const std::vector<std::wstring>& parts) {
360 std::error_code ec; 364 std::error_code ec;
@@ -1024,10 +1028,7 @@ BOOL WINAPI delete_file_w(LPCWSTR name) {
1024 removed = true; 1028 removed = true;
1025 } 1029 }
1026 } 1030 }
1027 if (!removed) { 1031 if (!removed) return fail_bool(missing_error(r, parts));
1028 SetLastError(ERROR_FILE_NOT_FOUND);
1029 return FALSE;
1030 }
1031 return TRUE; 1032 return TRUE;
1032} 1033}
1033 1034
@@ -1116,7 +1117,7 @@ BOOL WINAPI remove_directory_w(LPCWSTR name) {
1116 if (r.game.empty() || r.overlay.empty()) return fail_bool(ERROR_PATH_NOT_FOUND); 1117 if (r.game.empty() || r.overlay.empty()) return fail_bool(ERROR_PATH_NOT_FOUND);
1117 if (drive_root(name, parts)) return fail_bool(ERROR_ACCESS_DENIED); // "GAME:" and "T:" themselves stay 1118 if (drive_root(name, parts)) return fail_bool(ERROR_ACCESS_DENIED); // "GAME:" and "T:" themselves stay
1118 const View v = view(r, parts); 1119 const View v = view(r, parts);
1119 if (v.kind == Kind::None) return fail_bool(ERROR_FILE_NOT_FOUND); 1120 if (v.kind == Kind::None) return fail_bool(missing_error(r, parts));
1120 if (v.kind == Kind::File) return fail_bool(ERROR_DIRECTORY); 1121 if (v.kind == Kind::File) return fail_bool(ERROR_DIRECTORY);
1121 if (!empty_in_view(r, parts)) return fail_bool(ERROR_DIR_NOT_EMPTY); 1122 if (!empty_in_view(r, parts)) return fail_bool(ERROR_DIR_NOT_EMPTY);
1122 1123
@@ -1153,7 +1154,7 @@ BOOL WINAPI move_file_ex_w(LPCWSTR from, LPCWSTR to, DWORD flags) {
1153 if (r.game.empty() || r.overlay.empty()) return fail_bool(ERROR_PATH_NOT_FOUND); 1154 if (r.game.empty() || r.overlay.empty()) return fail_bool(ERROR_PATH_NOT_FOUND);
1154 if (drive_root(from, src) || drive_root(to, dst)) return fail_bool(ERROR_ACCESS_DENIED); 1155 if (drive_root(from, src) || drive_root(to, dst)) return fail_bool(ERROR_ACCESS_DENIED);
1155 const View from_view = view(r, src); 1156 const View from_view = view(r, src);
1156 if (from_view.kind == Kind::None) return fail_bool(ERROR_FILE_NOT_FOUND); 1157 if (from_view.kind == Kind::None) return fail_bool(missing_error(r, src));
1157 const std::filesystem::path overlay_from = disk_path(r.overlay, src), overlay_to = disk_path(r.overlay, dst); 1158 const std::filesystem::path overlay_from = disk_path(r.overlay, src), overlay_to = disk_path(r.overlay, dst);
1158 if (same_entry(src, dst)) { 1159 if (same_entry(src, dst)) {
1159 // The destination is the source, so it is not "already there". The host succeeds at a move onto the same 1160 // The destination is the source, so it is not "already there". The host succeeds at a move onto the same
@@ -1404,7 +1405,7 @@ BOOL WINAPI set_file_attributes_w(LPCWSTR name, DWORD attributes) {
1404 if (r.game.empty() || r.overlay.empty()) return fail_bool(ERROR_PATH_NOT_FOUND); 1405 if (r.game.empty() || r.overlay.empty()) return fail_bool(ERROR_PATH_NOT_FOUND);
1405 if (parts.empty()) return fail_bool(ERROR_ACCESS_DENIED); 1406 if (parts.empty()) return fail_bool(ERROR_ACCESS_DENIED);
1406 const View v = view(r, parts); 1407 const View v = view(r, parts);
1407 if (v.kind == Kind::None) return fail_bool(ERROR_FILE_NOT_FOUND); 1408 if (v.kind == Kind::None) return fail_bool(missing_error(r, parts));
1408 1409
1409 // The attributes belong to the overlay copy: a package file is copied up and a package folder mirrored first, 1410 // The attributes belong to the overlay copy: a package file is copied up and a package folder mirrored first,
1410 // so the package keeps its own attributes and reads, which prefer the overlay, see the new ones. 1411 // so the package keeps its own attributes and reads, which prefer the overlay, see the new ones.
diff --git a/runtime/shims/gameinput.cpp b/runtime/shims/gameinput.cpp
index 402179cde..7650b361f 100644
--- a/runtime/shims/gameinput.cpp
+++ b/runtime/shims/gameinput.cpp
@@ -47,6 +47,7 @@
47#include <mutex> 47#include <mutex>
48#include <string> 48#include <string>
49#include <thread> 49#include <thread>
50#include <utility>
50#include <vector> 51#include <vector>
51 52
52#include "gameinput.h" 53#include "gameinput.h"
@@ -132,10 +133,14 @@ const rt::gameinput::HapticApi& haptics() { return *g_haptic_api.load(); }
132// ---- configuration ---------------------------------------------------------------------------------------------- 133// ---- configuration ----------------------------------------------------------------------------------------------
133 134
134std::string env(const char* name) { 135std::string env(const char* name) {
135 char buf[64]; 136 // Any length: an input script (LEONIDA_INPUT_SCRIPT) is easily longer than a fixed buffer, and a value that did
136 const DWORD n = GetEnvironmentVariableA(name, buf, sizeof buf); 137 // not fit used to read as unset.
137 if (n == 0 || n >= sizeof buf) return {}; 138 const DWORD need = GetEnvironmentVariableA(name, nullptr, 0); // with the terminator
138 std::string s(buf, n); 139 if (need == 0) return {};
140 std::string s(need, '\0');
141 const DWORD n = GetEnvironmentVariableA(name, s.data(), need);
142 if (n == 0 || n >= need) return {};
143 s.resize(n);
139 for (auto& c : s) c = static_cast<char>(std::tolower(static_cast<unsigned char>(c))); 144 for (auto& c : s) c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
140 return s; 145 return s;
141} 146}
@@ -1861,8 +1866,8 @@ void update_keyboard_pad() {
1861 bool down[SDL_GAMEPAD_BUTTON_COUNT] = {}; 1866 bool down[SDL_GAMEPAD_BUTTON_COUNT] = {};
1862 int lx = 0, ly = 0; 1867 int lx = 0, ly = 0;
1863 bool aim = false, fire = false; 1868 bool aim = false, fire = false;
1864 // Out of focus every button, stick and trigger is released, so a key held while switching windows does not stay 1869 // Focus gates physical keyboard and mouse input. Read the cursor afresh on return to avoid a jump.
1865 // pressed, and the cursor is read afresh on return, so moving it in another window does not swing the stick. 1870 // Scripted presses still run while the window is unfocused.
1866 const bool active = mode == rt::gameinput::KeyboardPadMode::Always || g_has_focus.load()(); 1871 const bool active = mode == rt::gameinput::KeyboardPadMode::Always || g_has_focus.load()();
1867 if (active) { 1872 if (active) {
1868 const rt::gameinput::KeyDownFn key_down = g_key_down.load(); 1873 const rt::gameinput::KeyDownFn key_down = g_key_down.load();
@@ -1890,6 +1895,68 @@ void update_keyboard_pad() {
1890 } 1895 }
1891 clip_cursor(active && g_raw_ready && g_cursor_pos.load() == system_cursor_pos && foreground_is_ours()); 1896 clip_cursor(active && g_raw_ready && g_cursor_pos.load() == system_cursor_pos && foreground_is_ours());
1892 for (const auto& b : kKeyBindings) SDL_SetJoystickVirtualButton(g_keyboard.js, b.sdl_button, down[b.sdl_button]); 1897 for (const auto& b : kKeyBindings) SDL_SetJoystickVirtualButton(g_keyboard.js, b.sdl_button, down[b.sdl_button]);
1898 // Timed presses on the keyboard pad, in seconds since its first update. Each press lasts 300 ms.
1899 struct ScriptedPress {
1900 SDL_GamepadButton button;
1901 double at;
1902 };
1903 static const std::vector<ScriptedPress> script = [] {
1904 std::vector<ScriptedPress> out;
1905 static const std::pair<const char*, SDL_GamepadButton> names[] = {
1906 {"a", SDL_GAMEPAD_BUTTON_SOUTH}, {"b", SDL_GAMEPAD_BUTTON_EAST},
1907 {"x", SDL_GAMEPAD_BUTTON_WEST}, {"y", SDL_GAMEPAD_BUTTON_NORTH},
1908 {"start", SDL_GAMEPAD_BUTTON_START}, {"back", SDL_GAMEPAD_BUTTON_BACK},
1909 {"lb", SDL_GAMEPAD_BUTTON_LEFT_SHOULDER}, {"rb", SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER},
1910 {"up", SDL_GAMEPAD_BUTTON_DPAD_UP}, {"down", SDL_GAMEPAD_BUTTON_DPAD_DOWN},
1911 {"left", SDL_GAMEPAD_BUTTON_DPAD_LEFT}, {"right", SDL_GAMEPAD_BUTTON_DPAD_RIGHT}};
1912 const std::string text = env("LEONIDA_INPUT_SCRIPT");
1913 if (text.empty()) return out;
1914 constexpr char whitespace[] = " \t\r\n\f\v";
1915 size_t items = 0;
1916 for (size_t at = 0, end; at <= text.size(); at = end + 1) {
1917 ++items;
1918 end = std::min(text.find(',', at), text.size());
1919 const std::string item = text.substr(at, end - at);
1920 const size_t first = item.find_first_not_of(whitespace);
1921 const size_t sep = item.find('@');
1922 if (sep == std::string::npos || first >= sep) continue;
1923 const char* time = item.c_str() + sep + 1;
1924 char* tail;
1925 const double seconds = std::strtod(time, &tail);
1926 if (tail == time || !std::isfinite(seconds) || seconds < 0 ||
1927 item.find_first_not_of(whitespace, tail - item.c_str()) != std::string::npos) continue;
1928 for (const auto& [name, button] : names) {
1929 if (item.compare(first, sep - first, name) == 0) {
1930 out.push_back({button, seconds});
1931 break;
1932 }
1933 }
1934 }
1935 std::fprintf(stderr, "[rt] gameinput: LEONIDA_INPUT_SCRIPT: %zu scripted press(es), %zu rejected\n",
1936 out.size(), items - out.size());
1937 return out;
1938 }();
1939 if (!script.empty()) {
1940 static const ULONGLONG origin = GetTickCount64();
1941 const double now = (GetTickCount64() - origin) / 1000.0;
1942 // One decision per button: a later entry for the same button must not release what an earlier entry holds
1943 // (it did: with several entries only the last one ever reached the title).
1944 bool scripted[SDL_GAMEPAD_BUTTON_COUNT] = {};
1945 bool named[SDL_GAMEPAD_BUTTON_COUNT] = {};
1946 for (const auto& press : script) {
1947 named[press.button] = true;
1948 if (now >= press.at && now < press.at + 0.3) scripted[press.button] = true;
1949 }
1950 for (int button = 0; button < SDL_GAMEPAD_BUTTON_COUNT; ++button) {
1951 if (!named[button]) continue;
1952 SDL_SetJoystickVirtualButton(g_keyboard.js, static_cast<SDL_GamepadButton>(button),
1953 scripted[button] || down[button]);
1954 static bool was[SDL_GAMEPAD_BUTTON_COUNT] = {};
1955 if (scripted[button] && !was[button])
1956 std::fprintf(stderr, "[rt] gameinput: scripted press of button %d at %.1f s\n", button, now);
1957 was[button] = scripted[button];
1958 }
1959 }
1893 const int reach = lx && ly ? kStickDiagonal : kStickFull; 1960 const int reach = lx && ly ? kStickDiagonal : kStickFull;
1894 SDL_SetJoystickVirtualAxis(g_keyboard.js, SDL_GAMEPAD_AXIS_LEFTX, static_cast<Sint16>(lx * reach)); 1961 SDL_SetJoystickVirtualAxis(g_keyboard.js, SDL_GAMEPAD_AXIS_LEFTX, static_cast<Sint16>(lx * reach));
1895 SDL_SetJoystickVirtualAxis(g_keyboard.js, SDL_GAMEPAD_AXIS_LEFTY, static_cast<Sint16>(ly * reach)); 1962 SDL_SetJoystickVirtualAxis(g_keyboard.js, SDL_GAMEPAD_AXIS_LEFTY, static_cast<Sint16>(ly * reach));
diff --git a/runtime/shims/library_loader.cpp b/runtime/shims/library_loader.cpp
index 82dd75493..250fe0209 100644
--- a/runtime/shims/library_loader.cpp
+++ b/runtime/shims/library_loader.cpp
@@ -266,7 +266,7 @@ FARPROC WINAPI get_proc_address(HMODULE module, LPCSTR name) {
266 SetLastError(ERROR_PROC_NOT_FOUND); 266 SetLastError(ERROR_PROC_NOT_FOUND);
267 return nullptr; 267 return nullptr;
268 } 268 }
269 if (module && !IS_INTRESOURCE(name)) { 269 if (module) {
270 const DWORD error = GetLastError(); 270 const DWORD error = GetLastError();
271 const std::string dll = host_module_name(module); 271 const std::string dll = host_module_name(module);
272 void* shim = dll.empty() ? nullptr : find(dll, what); 272 void* shim = dll.empty() ? nullptr : find(dll, what);
diff --git a/runtime/shims/registry.cpp b/runtime/shims/registry.cpp
index c0d826e31..d2a78eb6b 100644
--- a/runtime/shims/registry.cpp
+++ b/runtime/shims/registry.cpp
@@ -533,7 +533,8 @@ void* find(const std::string& dll_lower, const std::string& name) {
533 533
534bool owns_dll(const std::string& dll_lower) { 534bool owns_dll(const std::string& dll_lower) {
535 static const char* const host[] = {"kernel32.dll", "kernelbase.dll", "msvcrt.dll", "ucrtbase.dll", "ucrtbased.dll", 535 static const char* const host[] = {"kernel32.dll", "kernelbase.dll", "msvcrt.dll", "ucrtbase.dll", "ucrtbased.dll",
536 "vulkan-1.dll", "ntdll.dll", "user32.dll"}; 536 "vulkan-1.dll", "ntdll.dll", "user32.dll", "ws2_32.dll",
537 "wsock32.dll"};
537 if (starts_with(dll_lower, "api-ms-") || starts_with(dll_lower, "ext-ms-")) return false; 538 if (starts_with(dll_lower, "api-ms-") || starts_with(dll_lower, "ext-ms-")) return false;
538 for (const char* h : host) 539 for (const char* h : host)
539 if (dll_lower == h) return false; 540 if (dll_lower == h) return false;
diff --git a/runtime/shims/ws2_offline.cpp b/runtime/shims/ws2_offline.cpp
new file mode 100644
index 000000000..0a278eb99
--- /dev/null
+++ b/runtime/shims/ws2_offline.cpp
@@ -0,0 +1,949 @@
1// ws2_offline: Winsock2 (ws2_32.dll and its wsock32.dll alias) for a mapped title, restricted to loopback only.
2//
3// Nothing in Leonida goes online. While winhttp_offline.cpp owns winhttp.dll, a title can also import Winsock2
4// functions directly (both by name and by standard Windows ws2_32.dll ordinal) or resolve them through
5// GetProcAddress / WSAIoctl. Bound straight to the host's ws2_32.dll, those calls could open external sockets or
6// trigger DNS queries. wsock32.dll exports forward to ws2_32 natively, so its bind/connect/sendto/gethostby* entries
7// go to the same wrappers.
8//
9// ws2_32.dll stays host-owned in rt::shims::owns_dll (partial override, like kernel32.dll), so socket bookkeeping
10// (WSAStartup, socket, closesocket, select, setsockopt, recv, send, byte-order helpers, freeaddrinfo) continues to
11// run natively on loopback sockets while every outbound, bind, name-resolution, and extension-lookup entry point is
12// vetted here:
13// - connect (#4), WSAConnect, WSAConnectByNameA/W, WSAConnectByList, ConnectEx (from WSAIoctl), sendto (#20),
14// WSASendTo, and WSASendMsg (direct and via WSAIoctl) permit only IPv4 loopback (127.0.0.0/8), IPv6 loopback
15// (::1), and IPv4-mapped IPv6 loopback (::ffff:127.0.0.0/104). Every other destination fails with WSAENETUNREACH.
16// WSAConnectByNameA/W pass "localhost" to the host as the literal 127.0.0.1, so the hosts file is never read.
17// - bind (#2) rewrites wildcard binds (0.0.0.0 or ::) to 127.0.0.1 or ::1 so no external peer can connect in,
18// allows explicit loopback binds, and refuses any other address with WSAEADDRNOTAVAIL.
19// - getaddrinfo, GetAddrInfoW, GetAddrInfoExA/W, gethostbyname (#52), gethostbyaddr (#51), and
20// WSAAsyncGetHostByName/Addr (#103/#102) permit only null/empty nodes, "localhost", and loopback IP literals;
21// everything else fails with WSAHOST_NOT_FOUND without sending DNS packets. A dotted octet with a leading zero
22// (0127.0.0.1) is refused: Windows reads it as octal, so it is not the loopback name it looks like.
23// - WSALookupServiceBeginA/W (name-service queries) always fail with WSASERVICE_NOT_FOUND.
24// - getnameinfo / GetNameInfoW force NI_NUMERICHOST for non-loopback addresses (or return WSAHOST_NOT_FOUND when
25// NI_NAMEREQD is set), avoiding reverse DNS lookups.
26// - WSAIoctl wraps WSAID_CONNECTEX and WSAID_WSASENDMSG and refuses SIO_GET_MULTIPLE_EXTENSION_FUNCTION_POINTER
27// with WSAEINVAL so extension functions cannot bypass the checks. The wrappers ask the host for the native
28// pointer of the socket they are called on, since each Winsock provider has its own.
29//
30// Every host ws2_32.dll call is resolved dynamically from System32 so gta6rt needs no static ws2_32.lib link
31// dependency. Each refused destination is logged once ("[rt] ws2: offline, refused <op> <target>") with no payload.
32#ifndef _WINSOCK_DEPRECATED_NO_WARNINGS
33#define _WINSOCK_DEPRECATED_NO_WARNINGS
34#endif
35#ifndef WIN32_LEAN_AND_MEAN
36#define WIN32_LEAN_AND_MEAN
37#endif
38#ifndef NOMINMAX
39#define NOMINMAX
40#endif
41
42#include <winsock2.h>
43#include <ws2tcpip.h>
44#include <mswsock.h>
45#include <windows.h>
46
47#include <cstdint>
48#include <cstdio>
49#include <cstring>
50#include <mutex>
51#include <set>
52#include <string>
53
54#include "shims.h"
55
56#ifndef SIO_GET_MULTIPLE_EXTENSION_FUNCTION_POINTER
57#define SIO_GET_MULTIPLE_EXTENSION_FUNCTION_POINTER 0xC8000024u
58#endif
59
60namespace rt::ws2 {
61namespace {
62
63HMODULE host_ws2() {
64 static HMODULE mod = LoadLibraryExW(L"ws2_32.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
65 return mod;
66}
67
68template <typename Fn>
69Fn host_proc(const char* name) {
70 HMODULE mod = host_ws2();
71 return mod ? reinterpret_cast<Fn>(GetProcAddress(mod, name)) : nullptr;
72}
73
74void set_wsa_error(int err) {
75 using SetErrFn = void(WSAAPI*)(int);
76 static SetErrFn fn = host_proc<SetErrFn>("WSASetLastError");
77 if (fn) {
78 fn(err);
79 } else {
80 SetLastError(static_cast<DWORD>(err));
81 }
82}
83
84uint16_t read_be16(uint16_t net_val) {
85 const auto* b = reinterpret_cast<const uint8_t*>(&net_val);
86 return static_cast<uint16_t>((static_cast<uint16_t>(b[0]) << 8) | b[1]);
87}
88
89bool is_ipv4_loopback_bytes(const uint8_t b[4]) { return b[0] == 127; }
90
91bool is_ipv4_unspecified_bytes(const uint8_t b[4]) { return b[0] == 0 && b[1] == 0 && b[2] == 0 && b[3] == 0; }
92
93bool is_ipv6_loopback_bytes(const uint8_t b[16]) {
94 // ::1
95 bool exact_loopback = true;
96 for (int i = 0; i < 15; ++i) {
97 if (b[i] != 0) {
98 exact_loopback = false;
99 break;
100 }
101 }
102 if (exact_loopback && b[15] == 1) return true;
103
104 // ::ffff:127.0.0.0/104 (IPv4-mapped loopback)
105 for (int i = 0; i < 10; ++i) {
106 if (b[i] != 0) return false;
107 }
108 return b[10] == 0xff && b[11] == 0xff && b[12] == 127;
109}
110
111bool is_ipv6_unspecified_bytes(const uint8_t b[16]) {
112 for (int i = 0; i < 16; ++i) {
113 if (b[i] != 0) return false;
114 }
115 return true;
116}
117
118bool is_loopback_sockaddr(const sockaddr* sa, int namelen) {
119 if (!sa || namelen < static_cast<int>(sizeof(ADDRESS_FAMILY))) return false;
120 if (sa->sa_family == AF_INET) {
121 if (namelen < static_cast<int>(sizeof(sockaddr_in))) return false;
122 sockaddr_in v4{};
123 std::memcpy(&v4, sa, sizeof(v4));
124 const auto* b = reinterpret_cast<const uint8_t*>(&v4.sin_addr);
125 return is_ipv4_loopback_bytes(b);
126 }
127 if (sa->sa_family == AF_INET6) {
128 if (namelen < static_cast<int>(sizeof(sockaddr_in6))) return false;
129 sockaddr_in6 v6{};
130 std::memcpy(&v6, sa, sizeof(v6));
131 const auto* b = reinterpret_cast<const uint8_t*>(&v6.sin6_addr);
132 return is_ipv6_loopback_bytes(b);
133 }
134 return false;
135}
136
137std::string format_sockaddr(const sockaddr* sa, int namelen) {
138 if (!sa || namelen < static_cast<int>(sizeof(ADDRESS_FAMILY))) return "<invalid>";
139 char buf[96] = {};
140 if (sa->sa_family == AF_INET && namelen >= static_cast<int>(sizeof(sockaddr_in))) {
141 sockaddr_in v4{};
142 std::memcpy(&v4, sa, sizeof(v4));
143 const auto* b = reinterpret_cast<const uint8_t*>(&v4.sin_addr);
144 std::snprintf(buf, sizeof(buf), "%u.%u.%u.%u:%u", b[0], b[1], b[2], b[3],
145 static_cast<unsigned>(read_be16(v4.sin_port)));
146 return buf;
147 }
148 if (sa->sa_family == AF_INET6 && namelen >= static_cast<int>(sizeof(sockaddr_in6))) {
149 sockaddr_in6 v6{};
150 std::memcpy(&v6, sa, sizeof(v6));
151 const auto* b = reinterpret_cast<const uint8_t*>(&v6.sin6_addr);
152 std::snprintf(buf, sizeof(buf), "[%02x%02x:%02x%02x:...:%02x%02x]:%u", b[0], b[1], b[2], b[3], b[14], b[15],
153 static_cast<unsigned>(read_be16(v6.sin6_port)));
154 return buf;
155 }
156 std::snprintf(buf, sizeof(buf), "family=%u", static_cast<unsigned>(sa->sa_family));
157 return buf;
158}
159
160void log_refused(const char* op, const std::string& target) {
161 // Intentionally immortal: mapped-DLL teardown can run after normal statics are destroyed.
162 static auto* mutex = new std::mutex;
163 static auto* seen = new std::set<std::string>;
164 const std::string key = std::string(op) + " " + target;
165 std::lock_guard lock(*mutex);
166 if (seen->insert(key).second) {
167 std::fprintf(stderr, "[rt] ws2: offline, refused %s %s\n", op, target.c_str());
168 }
169}
170
171bool ascii_iequals(const char* a, const char* b) {
172 if (!a || !b) return false;
173 while (*a && *b) {
174 unsigned char ca = static_cast<unsigned char>(*a++);
175 unsigned char cb = static_cast<unsigned char>(*b++);
176 if (ca >= 'A' && ca <= 'Z') ca = static_cast<unsigned char>(ca + 32);
177 if (cb >= 'A' && cb <= 'Z') cb = static_cast<unsigned char>(cb + 32);
178 if (ca != cb) return false;
179 }
180 return *a == '\0' && *b == '\0';
181}
182
183std::string narrow_ascii(const wchar_t* w) {
184 std::string out;
185 if (!w) return out;
186 for (; *w; ++w) out += (*w < 0x80) ? static_cast<char>(*w) : '?';
187 return out;
188}
189
190bool parse_ipv4_literal(const char* s, uint8_t out[4]) {
191 if (!s || !*s) return false;
192 const char* p = s;
193 for (int part = 0; part < 4; ++part) {
194 if (*p < '0' || *p > '9') return false;
195 const char* start = p;
196 unsigned val = 0;
197 int digits = 0;
198 while (*p >= '0' && *p <= '9') {
199 val = val * 10u + static_cast<unsigned>(*p - '0');
200 if (val > 255u) return false;
201 ++p;
202 ++digits;
203 }
204 if (digits == 0) return false;
205 if (digits > 1 && *start == '0') return false; // a leading zero is octal to Windows: 0127 is 87, not 127
206 out[part] = static_cast<uint8_t>(val);
207 if (part < 3) {
208 if (*p != '.') return false;
209 ++p;
210 }
211 }
212 return *p == '\0';
213}
214
215bool is_loopback_node_a(const char* node) {
216 if (!node || !*node) return true;
217 if (ascii_iequals(node, "localhost") || ascii_iequals(node, "localhost.")) return true;
218
219 uint8_t v4[4] = {};
220 if (parse_ipv4_literal(node, v4)) return is_ipv4_loopback_bytes(v4);
221
222 // Strip optional brackets and IPv6 zone suffix (%...) for literal check via host inet_pton.
223 std::string clean(node);
224 if (clean.size() >= 2 && clean.front() == '[' && clean.back() == ']') {
225 clean = clean.substr(1, clean.size() - 2);
226 }
227 if (const size_t pct = clean.find('%'); pct != std::string::npos) {
228 clean.resize(pct);
229 }
230
231 using InetPtonFn = INT(WSAAPI*)(INT, PCSTR, PVOID);
232 static InetPtonFn pton = host_proc<InetPtonFn>("inet_pton");
233 if (pton) {
234 uint8_t v6[16] = {};
235 if (pton(AF_INET6, clean.c_str(), v6) == 1) return is_ipv6_loopback_bytes(v6);
236 } else if (clean == "::1") {
237 return true;
238 }
239 return false;
240}
241
242bool is_loopback_node_w(const wchar_t* node) {
243 if (!node || !*node) return true;
244 for (const wchar_t* p = node; *p; ++p) {
245 if (*p >= 0x80) return false;
246 }
247 const std::string ascii = narrow_ascii(node);
248 return is_loopback_node_a(ascii.c_str());
249}
250
251bool is_localhost_name_a(const char* node) {
252 return ascii_iequals(node, "localhost") || ascii_iequals(node, "localhost.");
253}
254
255// ---- Socket connect / send / bind shims ----
256
257int WSAAPI connect_offline(SOCKET s, const sockaddr* name, int namelen) {
258 if (!is_loopback_sockaddr(name, namelen)) {
259 log_refused("connect", format_sockaddr(name, namelen));
260 set_wsa_error(WSAENETUNREACH);
261 return SOCKET_ERROR;
262 }
263 using Fn = int(WSAAPI*)(SOCKET, const sockaddr*, int);
264 static Fn real_fn = host_proc<Fn>("connect");
265 if (!real_fn) {
266 set_wsa_error(WSAENETUNREACH);
267 return SOCKET_ERROR;
268 }
269 return real_fn(s, name, namelen);
270}
271
272int WSAAPI wsa_connect_offline(SOCKET s, const sockaddr* name, int namelen, LPWSABUF caller_data,
273 LPWSABUF callee_data, LPQOS sqos, LPQOS gqos) {
274 if (!is_loopback_sockaddr(name, namelen)) {
275 log_refused("WSAConnect", format_sockaddr(name, namelen));
276 set_wsa_error(WSAENETUNREACH);
277 return SOCKET_ERROR;
278 }
279 using Fn = int(WSAAPI*)(SOCKET, const sockaddr*, int, LPWSABUF, LPWSABUF, LPQOS, LPQOS);
280 static Fn real_fn = host_proc<Fn>("WSAConnect");
281 if (!real_fn) {
282 set_wsa_error(WSAENETUNREACH);
283 return SOCKET_ERROR;
284 }
285 return real_fn(s, name, namelen, caller_data, callee_data, sqos, gqos);
286}
287
288BOOL WSAAPI wsa_connect_by_name_a_offline(SOCKET s, LPCSTR nodename, LPCSTR servicename,
289 LPDWORD local_addr_len, LPSOCKADDR local_addr,
290 LPDWORD remote_addr_len, LPSOCKADDR remote_addr,
291 const timeval* timeout, LPWSAOVERLAPPED reserved) {
292 if (!nodename || !*nodename || !is_loopback_node_a(nodename)) {
293 log_refused("WSAConnectByNameA", nodename ? nodename : "<null>");
294 set_wsa_error(WSAENETUNREACH);
295 return FALSE;
296 }
297 using Fn = BOOL(WSAAPI*)(SOCKET, LPCSTR, LPCSTR, LPDWORD, LPSOCKADDR, LPDWORD, LPSOCKADDR, const timeval*,
298 LPWSAOVERLAPPED);
299 static Fn real_fn = host_proc<Fn>("WSAConnectByNameA");
300 if (!real_fn) {
301 set_wsa_error(WSAENETUNREACH);
302 return FALSE;
303 }
304 // The host would resolve "localhost" through its hosts file; hand it the literal instead.
305 LPCSTR node = is_localhost_name_a(nodename) ? "127.0.0.1" : nodename;
306 return real_fn(s, node, servicename, local_addr_len, local_addr, remote_addr_len, remote_addr, timeout, reserved);
307}
308
309BOOL WSAAPI wsa_connect_by_name_w_offline(SOCKET s, LPWSTR nodename, LPWSTR servicename,
310 LPDWORD local_addr_len, LPSOCKADDR local_addr,
311 LPDWORD remote_addr_len, LPSOCKADDR remote_addr,
312 const timeval* timeout, LPWSAOVERLAPPED reserved) {
313 if (!nodename || !*nodename || !is_loopback_node_w(nodename)) {
314 log_refused("WSAConnectByNameW", nodename ? narrow_ascii(nodename) : "<null>");
315 set_wsa_error(WSAENETUNREACH);
316 return FALSE;
317 }
318 using Fn = BOOL(WSAAPI*)(SOCKET, LPWSTR, LPWSTR, LPDWORD, LPSOCKADDR, LPDWORD, LPSOCKADDR, const timeval*,
319 LPWSAOVERLAPPED);
320 static Fn real_fn = host_proc<Fn>("WSAConnectByNameW");
321 if (!real_fn) {
322 set_wsa_error(WSAENETUNREACH);
323 return FALSE;
324 }
325 // The host would resolve "localhost" through its hosts file; hand it the literal instead.
326 wchar_t loopback[] = L"127.0.0.1";
327 LPWSTR node = is_localhost_name_a(narrow_ascii(nodename).c_str()) ? loopback : nodename;
328 return real_fn(s, node, servicename, local_addr_len, local_addr, remote_addr_len, remote_addr, timeout, reserved);
329}
330
331BOOL WSAAPI wsa_connect_by_list_offline(SOCKET s, PSOCKET_ADDRESS_LIST addr_list, LPDWORD local_addr_len,
332 LPSOCKADDR local_addr, LPDWORD remote_addr_len, LPSOCKADDR remote_addr,
333 const timeval* timeout, LPWSAOVERLAPPED reserved) {
334 if (!addr_list || addr_list->iAddressCount <= 0) {
335 set_wsa_error(WSAEINVAL);
336 return FALSE;
337 }
338 for (INT i = 0; i < addr_list->iAddressCount; ++i) {
339 const SOCKET_ADDRESS& entry = addr_list->Address[i];
340 if (!is_loopback_sockaddr(entry.lpSockaddr, entry.iSockaddrLength)) {
341 log_refused("WSAConnectByList", format_sockaddr(entry.lpSockaddr, entry.iSockaddrLength));
342 set_wsa_error(WSAENETUNREACH);
343 return FALSE;
344 }
345 }
346 using Fn = BOOL(WSAAPI*)(SOCKET, PSOCKET_ADDRESS_LIST, LPDWORD, LPSOCKADDR, LPDWORD, LPSOCKADDR, const timeval*,
347 LPWSAOVERLAPPED);
348 static Fn real_fn = host_proc<Fn>("WSAConnectByList");
349 if (!real_fn) {
350 set_wsa_error(WSAENETUNREACH);
351 return FALSE;
352 }
353 return real_fn(s, addr_list, local_addr_len, local_addr, remote_addr_len, remote_addr, timeout, reserved);
354}
355
356// sendto, WSASendTo, WSASendMsg and WSAJoinLeaf bind an unbound socket to the wildcard address (Microsoft's remarks
357// for sendto and WSAJoinLeaf: getsockname then reports 0.0.0.0 or ::), so its port would also take datagrams from other
358// hosts. Bind such a socket to the loopback address of the (already checked) loopback destination's family first.
359// Returns false, with WSAEADDRNOTAVAIL set, only if the socket is still unbound afterwards.
360bool bind_loopback_if_unbound(SOCKET s, const sockaddr* dest) {
361 using NameFn = int(WSAAPI*)(SOCKET, sockaddr*, int*);
362 using BindFn = int(WSAAPI*)(SOCKET, const sockaddr*, int);
363 using LastErrFn = int(WSAAPI*)();
364 static NameFn real_getsockname = host_proc<NameFn>("getsockname");
365 static BindFn real_bind = host_proc<BindFn>("bind");
366 static LastErrFn real_last_error = host_proc<LastErrFn>("WSAGetLastError");
367 if (!real_getsockname || !real_bind || !real_last_error) {
368 set_wsa_error(WSAEADDRNOTAVAIL);
369 return false;
370 }
371 // Unbound is WSAEINVAL; any other getsockname error (not a socket, ...) is left for the real call to report.
372 const auto unbound = [&] {
373 sockaddr_storage local{};
374 int local_len = sizeof(local);
375 return real_getsockname(s, reinterpret_cast<sockaddr*>(&local), &local_len) == SOCKET_ERROR &&
376 real_last_error() == WSAEINVAL;
377 };
378 if (!unbound()) return true;
379
380 sockaddr_storage local{};
381 int local_len = 0;
382 if (dest->sa_family == AF_INET) {
383 auto* v4 = reinterpret_cast<sockaddr_in*>(&local);
384 v4->sin_family = AF_INET;
385 auto* b = reinterpret_cast<uint8_t*>(&v4->sin_addr);
386 b[0] = 127;
387 b[3] = 1;
388 local_len = sizeof(sockaddr_in);
389 } else {
390 sockaddr_in6 to6{};
391 std::memcpy(&to6, dest, sizeof(to6));
392 const auto* d = reinterpret_cast<const uint8_t*>(&to6.sin6_addr);
393 auto* v6 = reinterpret_cast<sockaddr_in6*>(&local);
394 v6->sin6_family = AF_INET6;
395 auto* b = reinterpret_cast<uint8_t*>(&v6->sin6_addr);
396 if (d[10] == 0xff && d[11] == 0xff) { // IPv4-mapped loopback destination: ::ffff:127.0.0.1
397 b[10] = 0xff;
398 b[11] = 0xff;
399 b[12] = 127;
400 b[15] = 1;
401 } else { // ::1
402 b[15] = 1;
403 }
404 local_len = sizeof(sockaddr_in6);
405 }
406 // A concurrent send on the same socket may have bound it between the two checks; that bind came through here too.
407 if (real_bind(s, reinterpret_cast<const sockaddr*>(&local), local_len) == 0 || !unbound()) return true;
408 log_refused("implicit wildcard bind", format_sockaddr(reinterpret_cast<const sockaddr*>(&local), local_len));
409 set_wsa_error(WSAEADDRNOTAVAIL);
410 return false;
411}
412
413int WSAAPI sendto_offline(SOCKET s, const char* buf, int len, int flags, const sockaddr* to, int tolen) {
414 if (to && tolen > 0 && !is_loopback_sockaddr(to, tolen)) {
415 log_refused("sendto", format_sockaddr(to, tolen));
416 set_wsa_error(WSAENETUNREACH);
417 return SOCKET_ERROR;
418 }
419 if (to && tolen > 0 && !bind_loopback_if_unbound(s, to)) return SOCKET_ERROR;
420 using Fn = int(WSAAPI*)(SOCKET, const char*, int, int, const sockaddr*, int);
421 static Fn real_fn = host_proc<Fn>("sendto");
422 if (!real_fn) {
423 set_wsa_error(WSAENETUNREACH);
424 return SOCKET_ERROR;
425 }
426 return real_fn(s, buf, len, flags, to, tolen);
427}
428
429int WSAAPI wsa_send_to_offline(SOCKET s, LPWSABUF buffers, DWORD buffer_count, LPDWORD bytes_sent, DWORD flags,
430 const sockaddr* to, int tolen, LPWSAOVERLAPPED overlapped,
431 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion) {
432 if (to && tolen > 0 && !is_loopback_sockaddr(to, tolen)) {
433 log_refused("WSASendTo", format_sockaddr(to, tolen));
434 set_wsa_error(WSAENETUNREACH);
435 return SOCKET_ERROR;
436 }
437 if (to && tolen > 0 && !bind_loopback_if_unbound(s, to)) return SOCKET_ERROR;
438 using Fn = int(WSAAPI*)(SOCKET, LPWSABUF, DWORD, LPDWORD, DWORD, const sockaddr*, int, LPWSAOVERLAPPED,
439 LPWSAOVERLAPPED_COMPLETION_ROUTINE);
440 static Fn real_fn = host_proc<Fn>("WSASendTo");
441 if (!real_fn) {
442 set_wsa_error(WSAENETUNREACH);
443 return SOCKET_ERROR;
444 }
445 return real_fn(s, buffers, buffer_count, bytes_sent, flags, to, tolen, overlapped, completion);
446}
447
448int WSAAPI wsa_send_msg_offline(SOCKET s, LPWSAMSG msg, DWORD flags, LPDWORD bytes_sent,
449 LPWSAOVERLAPPED overlapped, LPWSAOVERLAPPED_COMPLETION_ROUTINE completion) {
450 if (msg && msg->name && msg->namelen > 0 && !is_loopback_sockaddr(msg->name, msg->namelen)) {
451 log_refused("WSASendMsg", format_sockaddr(msg->name, msg->namelen));
452 set_wsa_error(WSAENETUNREACH);
453 return SOCKET_ERROR;
454 }
455 if (msg && msg->name && msg->namelen > 0 && !bind_loopback_if_unbound(s, msg->name)) return SOCKET_ERROR;
456 using Fn = int(WSAAPI*)(SOCKET, LPWSAMSG, DWORD, LPDWORD, LPWSAOVERLAPPED, LPWSAOVERLAPPED_COMPLETION_ROUTINE);
457 static Fn real_fn = host_proc<Fn>("WSASendMsg");
458 if (!real_fn) {
459 set_wsa_error(WSAENETUNREACH);
460 return SOCKET_ERROR;
461 }
462 return real_fn(s, msg, flags, bytes_sent, overlapped, completion);
463}
464
465int WSAAPI bind_offline(SOCKET s, const sockaddr* name, int namelen) {
466 if (!name || namelen < static_cast<int>(sizeof(ADDRESS_FAMILY))) {
467 set_wsa_error(WSAEINVAL);
468 return SOCKET_ERROR;
469 }
470 using Fn = int(WSAAPI*)(SOCKET, const sockaddr*, int);
471 static Fn real_fn = host_proc<Fn>("bind");
472 if (!real_fn) {
473 set_wsa_error(WSAEADDRNOTAVAIL);
474 return SOCKET_ERROR;
475 }
476
477 if (name->sa_family == AF_INET && namelen >= static_cast<int>(sizeof(sockaddr_in))) {
478 sockaddr_in v4{};
479 std::memcpy(&v4, name, sizeof(v4));
480 auto* b = reinterpret_cast<uint8_t*>(&v4.sin_addr);
481 if (is_ipv4_unspecified_bytes(b)) {
482 b[0] = 127;
483 b[1] = 0;
484 b[2] = 0;
485 b[3] = 1;
486 return real_fn(s, reinterpret_cast<const sockaddr*>(&v4), sizeof(v4));
487 }
488 if (is_ipv4_loopback_bytes(b)) {
489 return real_fn(s, name, namelen);
490 }
491 } else if (name->sa_family == AF_INET6 && namelen >= static_cast<int>(sizeof(sockaddr_in6))) {
492 sockaddr_in6 v6{};
493 std::memcpy(&v6, name, sizeof(v6));
494 auto* b = reinterpret_cast<uint8_t*>(&v6.sin6_addr);
495 if (is_ipv6_unspecified_bytes(b)) {
496 b[15] = 1;
497 return real_fn(s, reinterpret_cast<const sockaddr*>(&v6), sizeof(v6));
498 }
499 if (is_ipv6_loopback_bytes(b)) {
500 return real_fn(s, name, namelen);
501 }
502 }
503
504 log_refused("bind", format_sockaddr(name, namelen));
505 set_wsa_error(WSAEADDRNOTAVAIL);
506 return SOCKET_ERROR;
507}
508
509// ---- Multicast ----
510
511// A multicast group join makes the host announce membership on a real interface and receive the group's traffic
512// from other hosts, so every join is refused. Leaving a group and the other options pass through.
513bool is_multicast_join(int level, int optname) {
514 if (level == IPPROTO_IP) {
515 return optname == IP_ADD_MEMBERSHIP || optname == IP_ADD_SOURCE_MEMBERSHIP || optname == MCAST_JOIN_GROUP ||
516 optname == MCAST_JOIN_SOURCE_GROUP;
517 }
518 if (level == IPPROTO_IPV6) {
519 return optname == IPV6_ADD_MEMBERSHIP || optname == MCAST_JOIN_GROUP || optname == MCAST_JOIN_SOURCE_GROUP;
520 }
521 return false;
522}
523
524int refuse_multicast_join(const char* op, int level, int optname) {
525 log_refused(op, "multicast join (level " + std::to_string(level) + ", option " + std::to_string(optname) + ")");
526 set_wsa_error(WSAEADDRNOTAVAIL);
527 return SOCKET_ERROR;
528}
529
530int WSAAPI setsockopt_offline(SOCKET s, int level, int optname, const char* optval, int optlen) {
531 if (is_multicast_join(level, optname)) return refuse_multicast_join("setsockopt", level, optname);
532 using Fn = int(WSAAPI*)(SOCKET, int, int, const char*, int);
533 static Fn real_fn = host_proc<Fn>("setsockopt");
534 if (!real_fn) {
535 set_wsa_error(WSAENETDOWN);
536 return SOCKET_ERROR;
537 }
538 return real_fn(s, level, optname, optval, optlen);
539}
540
541// wsock32.dll's setsockopt is its own export, not a forwarder: it takes the Winsock 1.1 IPPROTO_IP numbers, maps
542// 5 (winsock.h IP_ADD_MEMBERSHIP) to the Winsock 2 value and passes numbers it does not know through unchanged (Wine's
543// dlls/wsock32/socket.c remaps the same table). Refuse both spellings of a join, then let the host wsock32 remap.
544int WSAAPI wsock32_setsockopt_offline(SOCKET s, int level, int optname, const char* optval, int optlen) {
545 constexpr int kWinsock1AddMembership = 5;
546 if (is_multicast_join(level, optname) || (level == IPPROTO_IP && optname == kWinsock1AddMembership)) {
547 return refuse_multicast_join("wsock32 setsockopt", level, optname);
548 }
549 using Fn = int(WSAAPI*)(SOCKET, int, int, const char*, int);
550 static HMODULE host_wsock32 = LoadLibraryExW(L"wsock32.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
551 static Fn real_fn = host_wsock32 ? reinterpret_cast<Fn>(GetProcAddress(host_wsock32, "setsockopt")) : nullptr;
552 if (!real_fn) {
553 set_wsa_error(WSAENETDOWN);
554 return SOCKET_ERROR;
555 }
556 return real_fn(s, level, optname, optval, optlen);
557}
558
559// WSAJoinLeaf joins a multipoint session; a group address is never loopback, so in practice every join is refused.
560SOCKET WSAAPI wsa_join_leaf_offline(SOCKET s, const sockaddr* name, int namelen, LPWSABUF caller_data,
561 LPWSABUF callee_data, LPQOS sqos, LPQOS gqos, DWORD flags) {
562 if (!is_loopback_sockaddr(name, namelen)) {
563 log_refused("WSAJoinLeaf", format_sockaddr(name, namelen));
564 set_wsa_error(WSAENETUNREACH);
565 return INVALID_SOCKET;
566 }
567 if (!bind_loopback_if_unbound(s, name)) return INVALID_SOCKET;
568 using Fn = SOCKET(WSAAPI*)(SOCKET, const sockaddr*, int, LPWSABUF, LPWSABUF, LPQOS, LPQOS, DWORD);
569 static Fn real_fn = host_proc<Fn>("WSAJoinLeaf");
570 if (!real_fn) {
571 set_wsa_error(WSAENETUNREACH);
572 return INVALID_SOCKET;
573 }
574 return real_fn(s, name, namelen, caller_data, callee_data, sqos, gqos, flags);
575}
576
577// ---- Name resolution shims ----
578
579INT WSAAPI getaddrinfo_offline(PCSTR node, PCSTR service, const ADDRINFOA* hints, PADDRINFOA* result) {
580 if (result) *result = nullptr;
581 if (!is_loopback_node_a(node)) {
582 log_refused("getaddrinfo", node ? node : "<null>");
583 set_wsa_error(WSAHOST_NOT_FOUND);
584 return WSAHOST_NOT_FOUND;
585 }
586 using Fn = INT(WSAAPI*)(PCSTR, PCSTR, const ADDRINFOA*, PADDRINFOA*);
587 static Fn real_fn = host_proc<Fn>("getaddrinfo");
588 if (!real_fn) {
589 set_wsa_error(WSAHOST_NOT_FOUND);
590 return WSAHOST_NOT_FOUND;
591 }
592 return real_fn(node, service, hints, result);
593}
594
595INT WSAAPI get_addr_info_w_offline(PCWSTR node, PCWSTR service, const ADDRINFOW* hints, PADDRINFOW* result) {
596 if (result) *result = nullptr;
597 if (!is_loopback_node_w(node)) {
598 log_refused("GetAddrInfoW", node ? narrow_ascii(node) : "<null>");
599 set_wsa_error(WSAHOST_NOT_FOUND);
600 return WSAHOST_NOT_FOUND;
601 }
602 using Fn = INT(WSAAPI*)(PCWSTR, PCWSTR, const ADDRINFOW*, PADDRINFOW*);
603 static Fn real_fn = host_proc<Fn>("GetAddrInfoW");
604 if (!real_fn) {
605 set_wsa_error(WSAHOST_NOT_FOUND);
606 return WSAHOST_NOT_FOUND;
607 }
608 return real_fn(node, service, hints, result);
609}
610
611INT WSAAPI get_addr_info_ex_a_offline(PCSTR name, PCSTR service, DWORD ns, LPGUID nsp_id, const ADDRINFOEXA* hints,
612 PADDRINFOEXA* result, timeval* timeout, LPOVERLAPPED overlapped,
613 LPLOOKUPSERVICE_COMPLETION_ROUTINE completion, LPHANDLE cancel_handle) {
614 if (result) *result = nullptr;
615 if (cancel_handle) *cancel_handle = nullptr;
616 if (!is_loopback_node_a(name)) {
617 log_refused("GetAddrInfoExA", name ? name : "<null>");
618 set_wsa_error(WSAHOST_NOT_FOUND);
619 return WSAHOST_NOT_FOUND;
620 }
621 using Fn = INT(WSAAPI*)(PCSTR, PCSTR, DWORD, LPGUID, const ADDRINFOEXA*, PADDRINFOEXA*, timeval*, LPOVERLAPPED,
622 LPLOOKUPSERVICE_COMPLETION_ROUTINE, LPHANDLE);
623 static Fn real_fn = host_proc<Fn>("GetAddrInfoExA");
624 if (!real_fn) {
625 set_wsa_error(WSAHOST_NOT_FOUND);
626 return WSAHOST_NOT_FOUND;
627 }
628 return real_fn(name, service, ns, nsp_id, hints, result, timeout, overlapped, completion, cancel_handle);
629}
630
631INT WSAAPI get_addr_info_ex_w_offline(PCWSTR name, PCWSTR service, DWORD ns, LPGUID nsp_id, const ADDRINFOEXW* hints,
632 PADDRINFOEXW* result, timeval* timeout, LPOVERLAPPED overlapped,
633 LPLOOKUPSERVICE_COMPLETION_ROUTINE completion, LPHANDLE cancel_handle) {
634 if (result) *result = nullptr;
635 if (cancel_handle) *cancel_handle = nullptr;
636 if (!is_loopback_node_w(name)) {
637 log_refused("GetAddrInfoExW", name ? narrow_ascii(name) : "<null>");
638 set_wsa_error(WSAHOST_NOT_FOUND);
639 return WSAHOST_NOT_FOUND;
640 }
641 using Fn = INT(WSAAPI*)(PCWSTR, PCWSTR, DWORD, LPGUID, const ADDRINFOEXW*, PADDRINFOEXW*, timeval*, LPOVERLAPPED,
642 LPLOOKUPSERVICE_COMPLETION_ROUTINE, LPHANDLE);
643 static Fn real_fn = host_proc<Fn>("GetAddrInfoExW");
644 if (!real_fn) {
645 set_wsa_error(WSAHOST_NOT_FOUND);
646 return WSAHOST_NOT_FOUND;
647 }
648 return real_fn(name, service, ns, nsp_id, hints, result, timeout, overlapped, completion, cancel_handle);
649}
650
651hostent* WSAAPI gethostbyname_offline(const char* name) {
652 if (!is_loopback_node_a(name)) {
653 log_refused("gethostbyname", name ? name : "<null>");
654 set_wsa_error(WSAHOST_NOT_FOUND);
655 return nullptr;
656 }
657 using Fn = hostent*(WSAAPI*)(const char*);
658 static Fn real_fn = host_proc<Fn>("gethostbyname");
659 if (!real_fn) {
660 set_wsa_error(WSAHOST_NOT_FOUND);
661 return nullptr;
662 }
663 return real_fn(name);
664}
665
666bool is_loopback_raw_addr(const char* addr, int len, int type) {
667 if (!addr) return false;
668 if (type == AF_INET && len == 4) {
669 return is_ipv4_loopback_bytes(reinterpret_cast<const uint8_t*>(addr));
670 }
671 if (type == AF_INET6 && len == 16) {
672 return is_ipv6_loopback_bytes(reinterpret_cast<const uint8_t*>(addr));
673 }
674 return false;
675}
676
677hostent* WSAAPI gethostbyaddr_offline(const char* addr, int len, int type) {
678 if (!is_loopback_raw_addr(addr, len, type)) {
679 log_refused("gethostbyaddr", "non-loopback");
680 set_wsa_error(WSAHOST_NOT_FOUND);
681 return nullptr;
682 }
683 using Fn = hostent*(WSAAPI*)(const char*, int, int);
684 static Fn real_fn = host_proc<Fn>("gethostbyaddr");
685 if (!real_fn) {
686 set_wsa_error(WSAHOST_NOT_FOUND);
687 return nullptr;
688 }
689 return real_fn(addr, len, type);
690}
691
692HANDLE WSAAPI wsa_async_get_host_by_name_offline(HWND hWnd, u_int wMsg, const char* name, char* buf, int buflen) {
693 if (!is_loopback_node_a(name)) {
694 log_refused("WSAAsyncGetHostByName", name ? name : "<null>");
695 set_wsa_error(WSAHOST_NOT_FOUND);
696 return nullptr;
697 }
698 using Fn = HANDLE(WSAAPI*)(HWND, u_int, const char*, char*, int);
699 static Fn real_fn = host_proc<Fn>("WSAAsyncGetHostByName");
700 if (!real_fn) {
701 set_wsa_error(WSAHOST_NOT_FOUND);
702 return nullptr;
703 }
704 return real_fn(hWnd, wMsg, name, buf, buflen);
705}
706
707HANDLE WSAAPI wsa_async_get_host_by_addr_offline(HWND hWnd, u_int wMsg, const char* addr, int len, int type,
708 char* buf, int buflen) {
709 if (!is_loopback_raw_addr(addr, len, type)) {
710 log_refused("WSAAsyncGetHostByAddr", "non-loopback");
711 set_wsa_error(WSAHOST_NOT_FOUND);
712 return nullptr;
713 }
714 using Fn = HANDLE(WSAAPI*)(HWND, u_int, const char*, int, int, char*, int);
715 static Fn real_fn = host_proc<Fn>("WSAAsyncGetHostByAddr");
716 if (!real_fn) {
717 set_wsa_error(WSAHOST_NOT_FOUND);
718 return nullptr;
719 }
720 return real_fn(hWnd, wMsg, addr, len, type, buf, buflen);
721}
722
723INT WSAAPI getnameinfo_offline(const sockaddr* sa, socklen_t salen, PCHAR host, DWORD host_size, PCHAR serv,
724 DWORD serv_size, INT flags) {
725 if (!is_loopback_sockaddr(sa, static_cast<int>(salen))) {
726 if ((flags & NI_NAMEREQD) != 0) {
727 log_refused("getnameinfo", format_sockaddr(sa, static_cast<int>(salen)));
728 set_wsa_error(WSAHOST_NOT_FOUND);
729 return WSAHOST_NOT_FOUND;
730 }
731 flags |= NI_NUMERICHOST;
732 }
733 using Fn = INT(WSAAPI*)(const sockaddr*, socklen_t, PCHAR, DWORD, PCHAR, DWORD, INT);
734 static Fn real_fn = host_proc<Fn>("getnameinfo");
735 if (!real_fn) {
736 set_wsa_error(WSAHOST_NOT_FOUND);
737 return WSAHOST_NOT_FOUND;
738 }
739 return real_fn(sa, salen, host, host_size, serv, serv_size, flags);
740}
741
742INT WSAAPI get_name_info_w_offline(const sockaddr* sa, socklen_t salen, PWCHAR host, DWORD host_size, PWCHAR serv,
743 DWORD serv_size, INT flags) {
744 if (!is_loopback_sockaddr(sa, static_cast<int>(salen))) {
745 if ((flags & NI_NAMEREQD) != 0) {
746 log_refused("GetNameInfoW", format_sockaddr(sa, static_cast<int>(salen)));
747 set_wsa_error(WSAHOST_NOT_FOUND);
748 return WSAHOST_NOT_FOUND;
749 }
750 flags |= NI_NUMERICHOST;
751 }
752 using Fn = INT(WSAAPI*)(const sockaddr*, socklen_t, PWCHAR, DWORD, PWCHAR, DWORD, INT);
753 static Fn real_fn = host_proc<Fn>("GetNameInfoW");
754 if (!real_fn) {
755 set_wsa_error(WSAHOST_NOT_FOUND);
756 return WSAHOST_NOT_FOUND;
757 }
758 return real_fn(sa, salen, host, host_size, serv, serv_size, flags);
759}
760
761// ---- Name-service queries (WSALookupServiceBegin) ----
762
763// Name-service (SAP/RNR) queries would reach the host's providers, so every begin call is refused.
764int WSAAPI wsa_lookup_service_begin_a_offline(LPWSAQUERYSETA restrictions, DWORD, LPHANDLE lookup) {
765 if (lookup) *lookup = nullptr;
766 const bool named = restrictions && restrictions->lpszServiceInstanceName;
767 log_refused("WSALookupServiceBeginA", named ? restrictions->lpszServiceInstanceName : "<null>");
768 set_wsa_error(WSASERVICE_NOT_FOUND);
769 return SOCKET_ERROR;
770}
771
772int WSAAPI wsa_lookup_service_begin_w_offline(LPWSAQUERYSETW restrictions, DWORD, LPHANDLE lookup) {
773 if (lookup) *lookup = nullptr;
774 const bool named = restrictions && restrictions->lpszServiceInstanceName;
775 log_refused("WSALookupServiceBeginW", named ? narrow_ascii(restrictions->lpszServiceInstanceName) : "<null>");
776 set_wsa_error(WSASERVICE_NOT_FOUND);
777 return SOCKET_ERROR;
778}
779
780// ---- WSAIoctl extension-function interception (ConnectEx / WSASendMsg) ----
781
782// The provider's own extension function for `s`. Asked per socket: each Winsock provider has its own pointers.
783template <typename Fn>
784Fn host_extension(SOCKET s, const GUID& guid) {
785 using IoctlFn = int(WSAAPI*)(SOCKET, DWORD, LPVOID, DWORD, LPVOID, DWORD, LPDWORD, LPWSAOVERLAPPED,
786 LPWSAOVERLAPPED_COMPLETION_ROUTINE);
787 static IoctlFn ioctl = host_proc<IoctlFn>("WSAIoctl");
788 if (!ioctl) return nullptr;
789 GUID requested = guid;
790 Fn fn = nullptr;
791 DWORD returned = 0;
792 if (ioctl(s, SIO_GET_EXTENSION_FUNCTION_POINTER, &requested, sizeof(requested), &fn, sizeof(fn), &returned, nullptr,
793 nullptr) != 0)
794 return nullptr;
795 return fn;
796}
797
798BOOL PASCAL connect_ex_offline(SOCKET s, const sockaddr* name, int namelen, PVOID send_buf, DWORD send_len,
799 LPDWORD bytes_sent, LPOVERLAPPED overlapped) {
800 if (!is_loopback_sockaddr(name, namelen)) {
801 log_refused("ConnectEx", format_sockaddr(name, namelen));
802 set_wsa_error(WSAENETUNREACH);
803 return FALSE;
804 }
805 static constexpr GUID kConnectExGuid = WSAID_CONNECTEX;
806 LPFN_CONNECTEX real_fn = host_extension<LPFN_CONNECTEX>(s, kConnectExGuid);
807 if (!real_fn) {
808 set_wsa_error(WSAENETUNREACH);
809 return FALSE;
810 }
811 return real_fn(s, name, namelen, send_buf, send_len, bytes_sent, overlapped);
812}
813
814int PASCAL wsa_send_msg_ext_offline(SOCKET s, LPWSAMSG msg, DWORD flags, LPDWORD bytes_sent,
815 LPWSAOVERLAPPED overlapped, LPWSAOVERLAPPED_COMPLETION_ROUTINE completion) {
816 if (msg && msg->name && msg->namelen > 0 && !is_loopback_sockaddr(msg->name, msg->namelen)) {
817 log_refused("WSASendMsg(ext)", format_sockaddr(msg->name, msg->namelen));
818 set_wsa_error(WSAENETUNREACH);
819 return SOCKET_ERROR;
820 }
821 if (msg && msg->name && msg->namelen > 0 && !bind_loopback_if_unbound(s, msg->name)) return SOCKET_ERROR;
822 static constexpr GUID kSendMsgGuid = WSAID_WSASENDMSG;
823 LPFN_WSASENDMSG real_fn = host_extension<LPFN_WSASENDMSG>(s, kSendMsgGuid);
824 if (!real_fn) {
825 set_wsa_error(WSAENETUNREACH);
826 return SOCKET_ERROR;
827 }
828 return real_fn(s, msg, flags, bytes_sent, overlapped, completion);
829}
830
831int WSAAPI wsa_ioctl_offline(SOCKET s, DWORD io_control_code, LPVOID in_buf, DWORD in_len, LPVOID out_buf,
832 DWORD out_len, LPDWORD bytes_returned, LPWSAOVERLAPPED overlapped,
833 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion) {
834 using Fn = int(WSAAPI*)(SOCKET, DWORD, LPVOID, DWORD, LPVOID, DWORD, LPDWORD, LPWSAOVERLAPPED,
835 LPWSAOVERLAPPED_COMPLETION_ROUTINE);
836 static Fn real_fn = host_proc<Fn>("WSAIoctl");
837 if (!real_fn) {
838 set_wsa_error(WSAEINVAL);
839 return SOCKET_ERROR;
840 }
841
842 if (io_control_code == SIO_GET_MULTIPLE_EXTENSION_FUNCTION_POINTER) {
843 set_wsa_error(WSAEINVAL);
844 return SOCKET_ERROR;
845 }
846
847 if (io_control_code == SIO_GET_EXTENSION_FUNCTION_POINTER && in_buf && in_len >= sizeof(GUID)) {
848 static constexpr GUID kConnectExGuid = WSAID_CONNECTEX;
849 static constexpr GUID kSendMsgGuid = WSAID_WSASENDMSG;
850 GUID requested{};
851 std::memcpy(&requested, in_buf, sizeof(requested));
852
853 if (std::memcmp(&requested, &kConnectExGuid, sizeof(GUID)) == 0) {
854 if (!out_buf || out_len < sizeof(void*) || !bytes_returned) {
855 set_wsa_error(WSAEFAULT);
856 return SOCKET_ERROR;
857 }
858 LPFN_CONNECTEX real_ext = nullptr;
859 DWORD returned = 0;
860 const int rc = real_fn(s, io_control_code, in_buf, in_len, &real_ext, sizeof(real_ext), &returned,
861 overlapped, completion);
862 if (rc != 0) return rc;
863 LPFN_CONNECTEX wrapped = &connect_ex_offline;
864 std::memcpy(out_buf, &wrapped, sizeof(wrapped));
865 *bytes_returned = sizeof(wrapped);
866 return 0;
867 }
868 if (std::memcmp(&requested, &kSendMsgGuid, sizeof(GUID)) == 0) {
869 if (!out_buf || out_len < sizeof(void*) || !bytes_returned) {
870 set_wsa_error(WSAEFAULT);
871 return SOCKET_ERROR;
872 }
873 LPFN_WSASENDMSG real_ext = nullptr;
874 DWORD returned = 0;
875 const int rc = real_fn(s, io_control_code, in_buf, in_len, &real_ext, sizeof(real_ext), &returned,
876 overlapped, completion);
877 if (rc != 0) return rc;
878 LPFN_WSASENDMSG wrapped = &wsa_send_msg_ext_offline;
879 std::memcpy(out_buf, &wrapped, sizeof(wrapped));
880 *bytes_returned = sizeof(wrapped);
881 return 0;
882 }
883 }
884
885 return real_fn(s, io_control_code, in_buf, in_len, out_buf, out_len, bytes_returned, overlapped, completion);
886}
887
888} // namespace
889} // namespace rt::ws2
890
891namespace {
892using namespace rt::ws2;
893} // namespace
894
895// Both named exports and the fixed Windows ordinals (#2 bind, #4 connect, #20 sendto, #21 setsockopt,
896// #51 gethostbyaddr, #52 gethostbyname, #102 WSAAsyncGetHostByAddr, #103 WSAAsyncGetHostByName) are registered so
897// static imports by ordinal and dynamic GetProcAddress lookups resolve to the same offline wrappers. wsock32.dll gets
898// the same wrappers for the entries it shares with ws2_32, since those exports forward to ws2_32 natively; its
899// setsockopt is its own export (Winsock 1.1 option numbers), so it gets its own wrapper.
900SHIM_TABLE(ws2_offline,
901 {"ws2_32.dll", "bind", reinterpret_cast<void*>(&bind_offline)},
902 {"ws2_32.dll", "#2", reinterpret_cast<void*>(&bind_offline)},
903 {"ws2_32.dll", "connect", reinterpret_cast<void*>(&connect_offline)},
904 {"ws2_32.dll", "#4", reinterpret_cast<void*>(&connect_offline)},
905 {"ws2_32.dll", "sendto", reinterpret_cast<void*>(&sendto_offline)},
906 {"ws2_32.dll", "#20", reinterpret_cast<void*>(&sendto_offline)},
907 {"ws2_32.dll", "setsockopt", reinterpret_cast<void*>(&setsockopt_offline)},
908 {"ws2_32.dll", "#21", reinterpret_cast<void*>(&setsockopt_offline)},
909 {"ws2_32.dll", "WSAJoinLeaf", reinterpret_cast<void*>(&wsa_join_leaf_offline)},
910 {"ws2_32.dll", "gethostbyaddr", reinterpret_cast<void*>(&gethostbyaddr_offline)},
911 {"ws2_32.dll", "#51", reinterpret_cast<void*>(&gethostbyaddr_offline)},
912 {"ws2_32.dll", "gethostbyname", reinterpret_cast<void*>(&gethostbyname_offline)},
913 {"ws2_32.dll", "#52", reinterpret_cast<void*>(&gethostbyname_offline)},
914 {"ws2_32.dll", "WSAAsyncGetHostByAddr", reinterpret_cast<void*>(&wsa_async_get_host_by_addr_offline)},
915 {"ws2_32.dll", "#102", reinterpret_cast<void*>(&wsa_async_get_host_by_addr_offline)},
916 {"ws2_32.dll", "WSAAsyncGetHostByName", reinterpret_cast<void*>(&wsa_async_get_host_by_name_offline)},
917 {"ws2_32.dll", "#103", reinterpret_cast<void*>(&wsa_async_get_host_by_name_offline)},
918 {"ws2_32.dll", "getaddrinfo", reinterpret_cast<void*>(&getaddrinfo_offline)},
919 {"ws2_32.dll", "GetAddrInfoW", reinterpret_cast<void*>(&get_addr_info_w_offline)},
920 {"ws2_32.dll", "GetAddrInfoExA", reinterpret_cast<void*>(&get_addr_info_ex_a_offline)},
921 {"ws2_32.dll", "GetAddrInfoExW", reinterpret_cast<void*>(&get_addr_info_ex_w_offline)},
922 {"ws2_32.dll", "getnameinfo", reinterpret_cast<void*>(&getnameinfo_offline)},
923 {"ws2_32.dll", "GetNameInfoW", reinterpret_cast<void*>(&get_name_info_w_offline)},
924 {"ws2_32.dll", "WSAConnect", reinterpret_cast<void*>(&wsa_connect_offline)},
925 {"ws2_32.dll", "WSAConnectByNameA", reinterpret_cast<void*>(&wsa_connect_by_name_a_offline)},
926 {"ws2_32.dll", "WSAConnectByNameW", reinterpret_cast<void*>(&wsa_connect_by_name_w_offline)},
927 {"ws2_32.dll", "WSAConnectByList", reinterpret_cast<void*>(&wsa_connect_by_list_offline)},
928 {"ws2_32.dll", "WSASendTo", reinterpret_cast<void*>(&wsa_send_to_offline)},
929 {"ws2_32.dll", "WSASendMsg", reinterpret_cast<void*>(&wsa_send_msg_offline)},
930 {"ws2_32.dll", "WSAIoctl", reinterpret_cast<void*>(&wsa_ioctl_offline)},
931 {"ws2_32.dll", "WSALookupServiceBeginA", reinterpret_cast<void*>(&wsa_lookup_service_begin_a_offline)},
932 {"ws2_32.dll", "WSALookupServiceBeginW", reinterpret_cast<void*>(&wsa_lookup_service_begin_w_offline)},
933 {"wsock32.dll", "bind", reinterpret_cast<void*>(&bind_offline)},
934 {"wsock32.dll", "#2", reinterpret_cast<void*>(&bind_offline)},
935 {"wsock32.dll", "connect", reinterpret_cast<void*>(&connect_offline)},
936 {"wsock32.dll", "#4", reinterpret_cast<void*>(&connect_offline)},
937 {"wsock32.dll", "sendto", reinterpret_cast<void*>(&sendto_offline)},
938 {"wsock32.dll", "#20", reinterpret_cast<void*>(&sendto_offline)},
939 {"wsock32.dll", "setsockopt", reinterpret_cast<void*>(&wsock32_setsockopt_offline)},
940 {"wsock32.dll", "#21", reinterpret_cast<void*>(&wsock32_setsockopt_offline)},
941 {"wsock32.dll", "gethostbyaddr", reinterpret_cast<void*>(&gethostbyaddr_offline)},
942 {"wsock32.dll", "#51", reinterpret_cast<void*>(&gethostbyaddr_offline)},
943 {"wsock32.dll", "gethostbyname", reinterpret_cast<void*>(&gethostbyname_offline)},
944 {"wsock32.dll", "#52", reinterpret_cast<void*>(&gethostbyname_offline)},
945 {"wsock32.dll", "WSAAsyncGetHostByAddr", reinterpret_cast<void*>(&wsa_async_get_host_by_addr_offline)},
946 {"wsock32.dll", "#102", reinterpret_cast<void*>(&wsa_async_get_host_by_addr_offline)},
947 {"wsock32.dll", "WSAAsyncGetHostByName", reinterpret_cast<void*>(&wsa_async_get_host_by_name_offline)},
948 {"wsock32.dll", "#103", reinterpret_cast<void*>(&wsa_async_get_host_by_name_offline)},
949);
diff --git a/runtime/shims/xbox_present.cpp b/runtime/shims/xbox_present.cpp
index dd5f810cf..f8791e1bf 100644
--- a/runtime/shims/xbox_present.cpp
+++ b/runtime/shims/xbox_present.cpp
@@ -1,6 +1,7 @@
1#include "xbox_present.h" 1#include "xbox_present.h"
2 2
3#include "d3d12_trace.h" 3#include "d3d12_trace.h"
4#include "d3d12_xs_device.h"
4 5
5#include "../src/vulkan_present.h" 6#include "../src/vulkan_present.h"
6 7
@@ -66,6 +67,7 @@ XboxPresentation::XboxPresentation(std::unique_ptr<WindowPresenter> presenter, l
66} 67}
67 68
68XboxPresentation::~XboxPresentation() { 69XboxPresentation::~XboxPresentation() {
70 if (presents_.load() > 0) log_pacing_summary();
69 { 71 {
70 std::lock_guard lock(worker_mutex_); 72 std::lock_guard lock(worker_mutex_);
71 worker_stop_ = true; 73 worker_stop_ = true;
@@ -75,6 +77,26 @@ XboxPresentation::~XboxPresentation() {
75 presenter_->set_abort(nullptr); 77 presenter_->set_abort(nullptr);
76} 78}
77 79
80void XboxPresentation::log_pacing_summary() const {
81 const leonida::FramePacingSummary s = pacer_.pacing_summary();
82 std::fprintf(stderr,
83 "[rt] present: pacing summary frames=%llu samples=%llu target_us=%u mean_us=%.1f drift_us=%+.1f "
84 "p50_us=%llu p95_us=%llu p99_us=%llu latency_samples=%llu latency_p50_us=%llu "
85 "latency_p95_us=%llu latency_p99_us=%llu\n",
86 static_cast<unsigned long long>(s.frames),
87 static_cast<unsigned long long>(s.samples),
88 s.target_interval_us,
89 s.mean_us,
90 s.drift_us,
91 static_cast<unsigned long long>(s.p50_us),
92 static_cast<unsigned long long>(s.p95_us),
93 static_cast<unsigned long long>(s.p99_us),
94 static_cast<unsigned long long>(s.latency_samples),
95 static_cast<unsigned long long>(s.latency_p50_us),
96 static_cast<unsigned long long>(s.latency_p95_us),
97 static_cast<unsigned long long>(s.latency_p99_us));
98}
99
78// Windows' SDR white level costs a QueryDisplayConfig and two DisplayConfigGetDeviceInfo calls (measured in 100// Windows' SDR white level costs a QueryDisplayConfig and two DisplayConfigGetDeviceInfo calls (measured in
79// xbox_present_test, docs section 4.5): too much for the present path, which would hitch once a second and feed the pacer. 101// xbox_present_test, docs section 4.5): too much for the present path, which would hitch once a second and feed the pacer.
80// So it is read here, about once a second while an HDR10 swapchain is in use, and PresentX reads the cached value. 102// So it is read here, about once a second while an HDR10 swapchain is in use, and PresentX reads the cached value.
@@ -314,4 +336,39 @@ HRESULT XboxPresentation::ResumeX() {
314 return S_OK; 336 return S_OK;
315} 337}
316 338
339bool attach_xbox_presentation(void* device_proxy, XboxPresentation* presentation) {
340 if (!presentation) return rt::d3d12_xs::set_presentation_handler(device_proxy, nullptr);
341 rt::d3d12_xs::PresentationHandler handler{};
342 handler.context = presentation;
343 handler.set_frame_interval = [](void* ctx, IUnknown* output, UINT interval_us, UINT latency, UINT flags) {
344 return static_cast<XboxPresentation*>(ctx)->SetFrameIntervalX(output, interval_us, latency, flags);
345 };
346 handler.schedule_frame_event = [](void* ctx, UINT event, UINT offset_us, UINT flags) {
347 return static_cast<XboxPresentation*>(ctx)->ScheduleFrameEventX(event, offset_us, flags);
348 };
349 handler.wait_frame_event = [](void* ctx, UINT event, DWORD timeout_ms, UINT flags, std::uint64_t* token) {
350 return static_cast<XboxPresentation*>(ctx)->WaitFrameEventX(event, timeout_ms, flags, token);
351 };
352 handler.get_frame_statistics = [](void* ctx, std::uint64_t token, UINT type_mask, UINT* count, void* out) {
353 return static_cast<XboxPresentation*>(ctx)->GetFrameStatisticsX(
354 token, type_mask, count, static_cast<leonida::FrameStatistic*>(out));
355 };
356 handler.present_x = [](void* ctx, UINT plane_count, const void* planes, const void* params) {
357 return static_cast<XboxPresentation*>(ctx)->PresentX(
358 plane_count, static_cast<const XboxPresentPlaneParameters*>(planes),
359 static_cast<const XboxPresentParameters*>(params));
360 };
361 handler.suspend_x = [](void* ctx, UINT flags) {
362 return static_cast<XboxPresentation*>(ctx)->SuspendX(flags);
363 };
364 handler.resume_x = [](void* ctx) {
365 return static_cast<XboxPresentation*>(ctx)->ResumeX();
366 };
367 return rt::d3d12_xs::set_presentation_handler(device_proxy, &handler);
368}
369
370bool detach_xbox_presentation(void* device_proxy) {
371 return rt::d3d12_xs::set_presentation_handler(device_proxy, nullptr);
372}
373
317} // namespace rt::d3d12 374} // namespace rt::d3d12
diff --git a/runtime/shims/xbox_present.h b/runtime/shims/xbox_present.h
index 60a317bee..6230d82ea 100644
--- a/runtime/shims/xbox_present.h
+++ b/runtime/shims/xbox_present.h
@@ -171,6 +171,9 @@ public:
171 std::uint64_t presents() const { return presents_; } 171 std::uint64_t presents() const { return presents_; }
172 // Frames shown mid-scan because of ImmediateThresholdPercent. 172 // Frames shown mid-scan because of ImmediateThresholdPercent.
173 std::uint64_t immediate_presents() const { return pacer_.immediate_presents(); } 173 std::uint64_t immediate_presents() const { return pacer_.immediate_presents(); }
174 // Frame-time percentiles, mean drift against target interval, and origin-to-present latency (BL-6).
175 leonida::FramePacingSummary pacing_summary() const { return pacer_.pacing_summary(); }
176 void log_pacing_summary() const;
174 177
175private: 178private:
176 // PresentX without its `[d3d12-trace]` line. 179 // PresentX without its `[d3d12-trace]` line.
@@ -199,5 +202,15 @@ private:
199}; 202};
200 203
201inline constexpr UINT xbox_frame_event_origin = leonida::frame_event_origin; 204inline constexpr UINT xbox_frame_event_origin = leonida::frame_event_origin;
205inline constexpr UINT xbox_frame_event_vblank = leonida::frame_event_vblank;
206inline constexpr UINT xbox_frame_event_flip = leonida::frame_event_flip;
207inline constexpr UINT xbox_frame_wait_token_on_timeout = leonida::frame_wait_flag_token_on_timeout;
208
209// Seam for the presenter, not yet called by the runtime: gta6rt creates no XboxPresentation, and only
210// d3d12_boot_movie_test and xbox_present_test construct one. Wires it into a d3d12_xs device proxy's frame-event
211// slots (78–81) and queue PresentX (slot 30, or LEONIDA_XS_PRESENT_X_SLOT); SuspendX and ResumeX are routed only
212// when LEONIDA_XS_SUSPEND_X_SLOT / LEONIDA_XS_RESUME_X_SLOT are set. Passing nullptr detaches the presentation.
213bool attach_xbox_presentation(void* device_proxy, XboxPresentation* presentation);
214bool detach_xbox_presentation(void* device_proxy);
202 215
203} // namespace rt::d3d12 216} // namespace rt::d3d12
diff --git a/runtime/shims/xgameruntime.cpp b/runtime/shims/xgameruntime.cpp
index 2b44229be..07cccc8d7 100644
--- a/runtime/shims/xgameruntime.cpp
+++ b/runtime/shims/xgameruntime.cpp
@@ -15,6 +15,7 @@
15 15
16#include <algorithm> 16#include <algorithm>
17#include <atomic> 17#include <atomic>
18#include <cerrno>
18#include <condition_variable> 19#include <condition_variable>
19#include <cstdio> 20#include <cstdio>
20#include <cstdlib> 21#include <cstdlib>
@@ -522,7 +523,11 @@ HRESULT STDMETHODCALLTYPE pls_get_path(void*, size_t path_size, char* path, size
522 if (!path) return E_POINTER; 523 if (!path) return E_POINTER;
523 const std::string folder = utf8_of(persistent_storage_dir().native()); 524 const std::string folder = utf8_of(persistent_storage_dir().native());
524 if (folder.empty()) return HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND); 525 if (folder.empty()) return HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND);
525 if (path_size < folder.size() + 1) return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); 526 if (path_size < folder.size() + 1) {
527 // A short buffer is left untouched but learns the size it needs: the path with its NUL, as slot 3 reports.
528 if (path_used) *path_used = folder.size() + 1;
529 return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
530 }
526 std::memcpy(path, folder.c_str(), folder.size() + 1); 531 std::memcpy(path, folder.c_str(), folder.size() + 1);
527 if (path_used) *path_used = folder.size() + 1; 532 if (path_used) *path_used = folder.size() + 1;
528 return S_OK; 533 return S_OK;
@@ -699,8 +704,22 @@ HRESULT __stdcall XSystemGetConsoleId(size_t size, char* out, size_t* used) {
699 return S_OK; 704 return S_OK;
700} 705}
701 706
702// uint64_t XSystemGetAppMemoryUsageLimit(). Reports total physical RAM, or 12 GB fallback for Series X. 707// uint64_t XSystemGetAppMemoryUsageLimit(). Reports total physical RAM (or 12 GB fallback for Series X),
708// optionally overridden by LEONIDA_TITLE_MEMORY_MB (clamped to 2048..65536 MiB) so constrained hosts can prevent
709// the title from sizing pools above what the machine can hold.
703uint64_t __stdcall XSystemGetAppMemoryUsageLimit() { 710uint64_t __stdcall XSystemGetAppMemoryUsageLimit() {
711 char env[32]{};
712 const DWORD n = GetEnvironmentVariableA("LEONIDA_TITLE_MEMORY_MB", env, sizeof(env));
713 if (n > 0 && n < sizeof(env) && env[0] != '-' && env[0] != '+') {
714 errno = 0;
715 char* end = nullptr;
716 unsigned long long mib = std::strtoull(env, &end, 10);
717 if (errno == 0 && end != env && *end == '\0' && mib > 0) {
718 if (mib < 2048ULL) mib = 2048ULL;
719 if (mib > 65536ULL) mib = 65536ULL;
720 return static_cast<uint64_t>(mib) * 1024ULL * 1024ULL;
721 }
722 }
704 MEMORYSTATUSEX ms{sizeof(ms)}; 723 MEMORYSTATUSEX ms{sizeof(ms)};
705 if (GlobalMemoryStatusEx(&ms)) return ms.ullTotalPhys; 724 if (GlobalMemoryStatusEx(&ms)) return ms.ullTotalPhys;
706 return 12ULL * 1024 * 1024 * 1024; 725 return 12ULL * 1024 * 1024 * 1024;
diff --git a/runtime/shims/xgameruntime_gamesave.cpp b/runtime/shims/xgameruntime_gamesave.cpp
index fdc5ddec3..7ba8ab645 100644
--- a/runtime/shims/xgameruntime_gamesave.cpp
+++ b/runtime/shims/xgameruntime_gamesave.cpp
@@ -371,6 +371,60 @@ HRESULT read_blobs(const XGameSaveContainer* c, const char* const* names, uint32
371} 371}
372 372
373// ---- Committing an update ---- 373// ---- Committing an update ----
374//
375// Every write goes to "<blob>~" first. Then each op, in name order, applies its change: the blob's file is copied to
376// its backup "<blob>~b~", then a write renames its temporary over the blob or a delete removes the blob. A blob never
377// leaves its name, so a process that dies midway leaves each blob under its name, old or new, as before. When an op
378// fails, the ops already applied are undone newest first (a blob that existed is copied back from its backup, one
379// that did not is removed), the scratch files are deleted and the update fails with E_GS_OUT_OF_LOCAL_STORAGE. A
380// backup whose restore failed is kept, so the old contents survive. Every scratch name ends in '~', which encode_name
381// never produces and decode_name rejects, so enumeration and the quota never count one. A commit first deletes the
382// temporaries of a commit that died midway. It leaves backups alone: one may be the only copy of a blob's old
383// contents. The next successful update of that blob replaces and then removes its backup.
384
385struct CommitStep {
386 fs::path final_path, temp, backup;
387 bool write = false;
388 bool existed = false; // the blob had a file before the update; the backup is a copy of it
389 bool backed_up = false; // this update wrote the backup
390 bool applied = false; // the op took effect
391 bool keep_backup = false; // its undo failed: the backup holds the only copy of the old contents
392};
393
394bool copy_blob(const fs::path& from, const fs::path& to) {
395 std::error_code ec;
396 fs::copy_file(from, to, fs::copy_options::overwrite_existing, ec);
397 return !ec;
398}
399
400// Undoes the applied steps among steps[0, upto), newest first. A step whose restore fails keeps its backup.
401void undo_steps(std::vector<CommitStep>& steps, size_t upto) {
402 for (size_t i = upto; i-- > 0;) {
403 CommitStep& s = steps[i];
404 if (!s.applied) continue;
405 std::error_code ec;
406 if (s.existed) {
407 if (copy_blob(s.backup, s.final_path)) {
408 s.applied = false;
409 } else {
410 s.keep_backup = true;
411 }
412 } else {
413 fs::remove(s.final_path, ec);
414 if (!ec) s.applied = false;
415 }
416 }
417}
418
419// Deletes what the update left behind: the temporaries, and the backups it wrote itself that are not the only copy of
420// a blob's old contents.
421void remove_scratch(const std::vector<CommitStep>& steps) {
422 for (const CommitStep& s : steps) {
423 std::error_code ec;
424 fs::remove(s.temp, ec);
425 if (s.backed_up && !s.keep_backup) fs::remove(s.backup, ec);
426 }
427}
374 428
375HRESULT commit(XGameSaveUpdate* u) { 429HRESULT commit(XGameSaveUpdate* u) {
376 XGameSaveContainer* c = u->container; 430 XGameSaveContainer* c = u->container;
@@ -388,24 +442,53 @@ HRESULT commit(XGameSaveUpdate* u) {
388 std::error_code ec; 442 std::error_code ec;
389 fs::create_directories(dir, ec); 443 fs::create_directories(dir, ec);
390 if (ec) return E_GS_OUT_OF_LOCAL_STORAGE; 444 if (ec) return E_GS_OUT_OF_LOCAL_STORAGE;
391 std::vector<std::pair<fs::path, fs::path>> renames; // temporary -> final 445 // Temporaries of a commit that died midway: never blobs, and nothing else uses these names. Backups are kept.
446 for (const auto& e : fs::directory_iterator(dir, ec)) {
447 std::error_code entry_ec;
448 const std::wstring n = e.path().filename().wstring();
449 if (n.ends_with(L"~") && !n.ends_with(L"~b~") && e.is_regular_file(entry_ec)) fs::remove(e.path(), entry_ec);
450 }
451
452 std::vector<CommitStep> steps;
453 steps.reserve(u->ops.size());
392 for (const auto& [name, op] : u->ops) { 454 for (const auto& [name, op] : u->ops) {
393 if (!op.write) continue; 455 CommitStep s;
394 const fs::path final_path = dir / widen(encode_name(name)); 456 s.final_path = dir / widen(encode_name(name));
395 fs::path temp = final_path; 457 s.temp = s.final_path;
396 temp += L"~"; 458 s.temp += L"~";
397 if (!write_file(temp, op.data.data(), op.data.size())) { 459 s.backup = s.final_path;
398 for (const auto& r : renames) fs::remove(r.first, ec); 460 s.backup += L"~b~";
399 fs::remove(temp, ec); 461 s.write = op.write;
462 std::error_code exists_ec;
463 s.existed = fs::is_regular_file(s.final_path, exists_ec);
464 if (op.write && !write_file(s.temp, op.data.data(), op.data.size())) {
465 std::error_code rm_ec;
466 for (const CommitStep& done : steps) fs::remove(done.temp, rm_ec);
467 fs::remove(s.temp, rm_ec);
400 return E_GS_OUT_OF_LOCAL_STORAGE; 468 return E_GS_OUT_OF_LOCAL_STORAGE;
401 } 469 }
402 renames.emplace_back(temp, final_path); 470 steps.push_back(std::move(s));
403 } 471 }
404 for (const auto& [temp, final_path] : renames) 472
405 if (!MoveFileExW(temp.c_str(), final_path.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) 473 for (size_t i = 0; i < steps.size(); ++i) {
474 CommitStep& s = steps[i];
475 bool ok = true;
476 if (s.existed) ok = s.backed_up = copy_blob(s.final_path, s.backup);
477 if (ok && s.write) {
478 ok = MoveFileExW(s.temp.c_str(), s.final_path.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH) != 0;
479 } else if (ok && s.existed) { // a delete
480 std::error_code rm_ec;
481 fs::remove(s.final_path, rm_ec); // already gone is a delete that has nothing left to do
482 ok = !rm_ec;
483 }
484 if (!ok) {
485 undo_steps(steps, i); // the failed op changed nothing: only the ops before it were applied
486 remove_scratch(steps);
406 return E_GS_OUT_OF_LOCAL_STORAGE; 487 return E_GS_OUT_OF_LOCAL_STORAGE;
407 for (const auto& [name, op] : u->ops) 488 }
408 if (!op.write) fs::remove(dir / widen(encode_name(name)), ec); 489 s.applied = true;
490 }
491 remove_scratch(steps);
409 if (u->has_display_name) write_file(dir / L".display", u->display_name.data(), u->display_name.size()); 492 if (u->has_display_name) write_file(dir / L".display", u->display_name.data(), u->display_name.size());
410 return S_OK; 493 return S_OK;
411} 494}
diff --git a/runtime/shims/xgameruntime_offline.cpp b/runtime/shims/xgameruntime_offline.cpp
index cc7a91d21..23a5e9d81 100644
--- a/runtime/shims/xgameruntime_offline.cpp
+++ b/runtime/shims/xgameruntime_offline.cpp
@@ -1,5 +1,5 @@
1// xgameruntime: XGameEventImpl, XGameUiImpl, XGameStreamingImpl, XDisplayImpl, XUserDeviceImpl, XAccessibilityImpl and 1// xgameruntime: XGameEventImpl, XGameUiImpl, XGameStreamingImpl, XDisplayImpl, XUserDeviceImpl, XAccessibilityImpl
2// XLauncherImpl, offline: small classes a title calls early. 2// and XLauncherImpl, offline: small classes a title calls early.
3// 3//
4// Each XGameEvent*, XGameUi* and XGameStreaming* function in xgameruntime.lib asks QueryApiImpl for its class and 4// Each XGameEvent*, XGameUi* and XGameStreaming* function in xgameruntime.lib asks QueryApiImpl for its class and
5// calls one slot with its own arguments after `this`. The class and interface ids and the method order are 5// calls one slot with its own arguments after `this`. The class and interface ids and the method order are
@@ -18,17 +18,19 @@
18// XUserDeviceImpl every device belongs to the offline user; associations and audio endpoints never change, so 18// XUserDeviceImpl every device belongs to the offline user; associations and audio endpoints never change, so
19// their change registrations are kept until unregistered and never called back; the user has 19// their change registrations are kept until unregistered and never called back; the user has
20// no audio endpoint of its own; finding a controller shows no UI (as on desktop). 20// no audio endpoint of its own; finding a controller shows no UI (as on desktop).
21// XAccessibilityImpl high contrast is Off, closed captions can't be configured, no voice is installed (enumerating 21// XAccessibilityImpl high contrast is Off, closed captions can't be configured, one silent voice is installed
22// calls back zero times), XSpeechSynthesizerCreate fails (E_FAIL) with a null handle, the other 22// (enumerating calls back once), XSpeechSynthesizerCreate hands out a synthesizer whose
23// speech calls refuse the handle they were never given (E_INVALIDARG), speech-to-text display 23// text/SSML streams return a valid 44-byte empty 16 kHz mono 16-bit PCM WAVE header so titles
24// calls fail (E_FAIL). 24// that play narration continue cleanly; speech-to-text display calls fail (E_FAIL).
25// XLauncherImpl XLaunchUri and the display timeout deferral calls fail (E_FAIL); nothing is launched. 25// XLauncherImpl XLaunchUri fails offline (E_FAIL); XDisplayAcquireTimeoutDeferral / Close acquire and clear a
26// real Win32 PowerRequestDisplayRequired handle so the host display stays awake.
26// 27//
27// Slots whose signature the public pages don't give answer with a value that is safe whichever way the caller reads 28// Slots whose signature the public pages don't give answer with a value that is safe whichever way the caller reads
28// it: see `client_not_connected` (XGameStreaming) and `offline_failure`. 29// it: see `client_not_connected` (XGameStreaming) and `offline_failure`.
29#include <windows.h> 30#include <windows.h>
30 31
31#include <atomic> 32#include <atomic>
33#include <cstddef>
32#include <cstdint> 34#include <cstdint>
33#include <cstdio> 35#include <cstdio>
34#include <cstdlib> 36#include <cstdlib>
@@ -604,38 +606,94 @@ HRESULT STDMETHODCALLTYPE accessibility_high_contrast(void*, uint32_t* mode) {
604// 4: HRESULT XClosedCaptionSetEnabled(bool enabled): there are no captions to show; accepted and dropped. 606// 4: HRESULT XClosedCaptionSetEnabled(bool enabled): there are no captions to show; accepted and dropped.
605HRESULT STDMETHODCALLTYPE accessibility_captions_set_enabled(void*, bool) { return S_OK; } 607HRESULT STDMETHODCALLTYPE accessibility_captions_set_enabled(void*, bool) { return S_OK; }
606 608
607// 8: HRESULT XSpeechSynthesizerEnumerateInstalledVoices(callback, void* context): no voice is installed, so the 609// XSpeechSynthesizerVoiceInformation and its callback, in the GDK reference's member order (the gender is
608// callback runs zero times. ASSUMPTION: the argument order (GDK reference), only the count (2) was measured. 610// XSpeechSynthesizerVoiceGender, a uint32_t enum: Female 0, Male 1).
609HRESULT STDMETHODCALLTYPE speech_enumerate_voices(void*, void* callback, void*) { 611struct SpeechVoiceInformation {
610 return callback ? S_OK : E_INVALIDARG; 612 const char* description;
613 const char* display_name;
614 uint32_t gender;
615 const char* voice_id;
616 const char* language;
617};
618static_assert(offsetof(SpeechVoiceInformation, voice_id) == 24 && sizeof(SpeechVoiceInformation) == 40, "x64 layout");
619using InstalledVoicesCallback = bool(CALLBACK*)(const SpeechVoiceInformation* information, void* context);
620constexpr SpeechVoiceInformation kSilentVoice = {"Leonida silent voice - English (United States)",
621 "Leonida silent voice", 0, "leonida-silent", "en-US"};
622
623// 8: HRESULT XSpeechSynthesizerEnumerateInstalledVoices(void* context, callback): one voice, the silent one every
624// synthesizer below speaks with. ASSUMPTION: the argument order (GDK reference), only the count (2) was measured.
625HRESULT STDMETHODCALLTYPE speech_enumerate_voices(void*, void* context, InstalledVoicesCallback callback) {
626 if (!callback) return E_INVALIDARG;
627 callback(&kSilentVoice, context);
628 return S_OK;
629}
630
631// Valid 44-byte RIFF/WAVE header for 16 kHz, 16-bit mono PCM with 0 data bytes (silent speech stream).
632constexpr uint8_t kSilentWave[44] = {
633 'R', 'I', 'F', 'F', 0x24, 0x00, 0x00, 0x00, 'W', 'A', 'V', 'E', 'f', 'm', 't', ' ',
634 0x10, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x80, 0x3e, 0x00, 0x00, 0x00, 0x7d, 0x00, 0x00,
635 0x02, 0x00, 0x10, 0x00, 'd', 'a', 't', 'a', 0x00, 0x00, 0x00, 0x00,
636};
637
638uint8_t g_speech_synth_handle = 0;
639uint8_t g_speech_stream_handle = 0;
640
641// 9: HRESULT XSpeechSynthesizerCreate(XSpeechSynthesizerHandle* handle): silent synthesizer handle.
642HRESULT STDMETHODCALLTYPE speech_create(void*, void** handle) {
643 if (!handle) return E_POINTER;
644 *handle = &g_speech_synth_handle;
645 return S_OK;
646}
647
648// 10: HRESULT XSpeechSynthesizerCloseHandle(XSpeechSynthesizerHandle handle)
649HRESULT STDMETHODCALLTYPE speech_close_synth(void*, void* handle) {
650 return handle == &g_speech_synth_handle ? S_OK : E_INVALIDARG;
611} 651}
612 652
613// 9: HRESULT XSpeechSynthesizerCreate(XSpeechSynthesizerHandle* handle): no synthesizer offline. 653// 11: HRESULT XSpeechSynthesizerSetDefaultVoice(XSpeechSynthesizerHandle handle)
614HRESULT STDMETHODCALLTYPE speech_create(void* self, void** handle) { 654HRESULT STDMETHODCALLTYPE speech_set_default_voice(void*, void* handle) {
615 if (handle) *handle = nullptr; 655 return handle == &g_speech_synth_handle ? S_OK : E_INVALIDARG;
616 return offline_failure<kAccessibilityName, 9>(self);
617} 656}
618 657
619// 10-12, 14: a synthesizer or stream handle is the first argument, and none was ever handed out: E_INVALIDARG. 658// 12: HRESULT XSpeechSynthesizerSetCustomVoice(XSpeechSynthesizerHandle handle, const char* voiceId): only the
620HRESULT STDMETHODCALLTYPE speech_bad_handle(void*) { return E_INVALIDARG; } 659// enumerated voice is installed.
660HRESULT STDMETHODCALLTYPE speech_set_custom_voice(void*, void* handle, const char* voice_id) {
661 if (handle != &g_speech_synth_handle || !voice_id) return E_INVALIDARG;
662 return std::strcmp(voice_id, kSilentVoice.voice_id) == 0 ? S_OK : E_INVALIDARG;
663}
621 664
622// 13, 21: HRESULT XSpeechSynthesizerCreateStreamFromText/Ssml(synthesizer, const char* text, 665// 13, 21: HRESULT XSpeechSynthesizerCreateStreamFromText/Ssml(synthesizer, const char* text,
623// XSpeechSynthesizerStreamHandle* stream) 666// XSpeechSynthesizerStreamHandle* stream)
624HRESULT STDMETHODCALLTYPE speech_create_stream(void*, void*, const char*, void** stream) { 667HRESULT STDMETHODCALLTYPE speech_create_stream(void*, void* synth, const char*, void** stream) {
625 if (stream) *stream = nullptr; 668 if (stream) *stream = nullptr;
626 return E_INVALIDARG; 669 if (synth != &g_speech_synth_handle) return E_INVALIDARG;
670 if (!stream) return E_POINTER;
671 *stream = &g_speech_stream_handle;
672 return S_OK;
673}
674
675// 14: HRESULT XSpeechSynthesizerCloseStreamHandle(XSpeechSynthesizerStreamHandle stream)
676HRESULT STDMETHODCALLTYPE speech_close_stream(void*, void* stream) {
677 return stream == &g_speech_stream_handle ? S_OK : E_INVALIDARG;
627} 678}
628 679
629// 15: HRESULT XSpeechSynthesizerGetStreamDataSize(stream, size_t* size) 680// 15: HRESULT XSpeechSynthesizerGetStreamDataSize(stream, size_t* size)
630HRESULT STDMETHODCALLTYPE speech_stream_size(void*, void*, size_t* size) { 681HRESULT STDMETHODCALLTYPE speech_stream_size(void*, void* stream, size_t* size) {
631 if (size) *size = 0; 682 if (size) *size = 0;
632 return E_INVALIDARG; 683 if (stream != &g_speech_stream_handle) return E_INVALIDARG;
684 if (!size) return E_POINTER;
685 *size = sizeof(kSilentWave);
686 return S_OK;
633} 687}
634 688
635// 16: HRESULT XSpeechSynthesizerGetStreamData(stream, size_t size, void* buffer, size_t* used) 689// 16: HRESULT XSpeechSynthesizerGetStreamData(stream, size_t size, void* buffer, size_t* used)
636HRESULT STDMETHODCALLTYPE speech_stream_data(void*, void*, size_t, void*, size_t* used) { 690HRESULT STDMETHODCALLTYPE speech_stream_data(void*, void* stream, size_t size, void* buffer, size_t* used) {
637 if (used) *used = 0; 691 if (used) *used = 0;
638 return E_INVALIDARG; 692 if (stream != &g_speech_stream_handle) return E_INVALIDARG;
693 if (!buffer || size < sizeof(kSilentWave)) return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
694 std::memcpy(buffer, kSilentWave, sizeof(kSilentWave));
695 if (used) *used = sizeof(kSilentWave);
696 return S_OK;
639} 697}
640 698
641// The slots with no offline counterpart whose arguments the layout doesn't give: the caption properties (3) and 699// The slots with no offline counterpart whose arguments the layout doesn't give: the caption properties (3) and
@@ -654,11 +712,11 @@ const void* const kAccessibilityVtable[] = {
654 FN(accessibility_offline<7>), // 7 XSpeechToTextSendString 712 FN(accessibility_offline<7>), // 7 XSpeechToTextSendString
655 FN(speech_enumerate_voices), // 8 XSpeechSynthesizerEnumerateInstalledVoices 713 FN(speech_enumerate_voices), // 8 XSpeechSynthesizerEnumerateInstalledVoices
656 FN(speech_create), // 9 XSpeechSynthesizerCreate 714 FN(speech_create), // 9 XSpeechSynthesizerCreate
657 FN(speech_bad_handle), // 10 XSpeechSynthesizerCloseHandle 715 FN(speech_close_synth), // 10 XSpeechSynthesizerCloseHandle
658 FN(speech_bad_handle), // 11 XSpeechSynthesizerSetDefaultVoice 716 FN(speech_set_default_voice), // 11 XSpeechSynthesizerSetDefaultVoice
659 FN(speech_bad_handle), // 12 XSpeechSynthesizerSetCustomVoice 717 FN(speech_set_custom_voice), // 12 XSpeechSynthesizerSetCustomVoice
660 FN(speech_create_stream), // 13 XSpeechSynthesizerCreateStreamFromText 718 FN(speech_create_stream), // 13 XSpeechSynthesizerCreateStreamFromText
661 FN(speech_bad_handle), // 14 XSpeechSynthesizerCloseStreamHandle 719 FN(speech_close_stream), // 14 XSpeechSynthesizerCloseStreamHandle
662 FN(speech_stream_size), // 15 XSpeechSynthesizerGetStreamDataSize 720 FN(speech_stream_size), // 15 XSpeechSynthesizerGetStreamDataSize
663 FN(speech_stream_data), // 16 XSpeechSynthesizerGetStreamData 721 FN(speech_stream_data), // 16 XSpeechSynthesizerGetStreamData
664 FN(accessibility_offline<17>), // 17 XSpeechToTextBeginHypothesisString 722 FN(accessibility_offline<17>), // 17 XSpeechToTextBeginHypothesisString
@@ -680,11 +738,31 @@ constexpr char kLauncherName[] = "XLauncherImpl";
680constexpr GUID kLauncherClass = {0x1b339674, 0x328d, 0x4283, {0xa2, 0x00, 0x31, 0x71, 0xf1, 0x8d, 0x36, 0x39}}; 738constexpr GUID kLauncherClass = {0x1b339674, 0x328d, 0x4283, {0xa2, 0x00, 0x31, 0x71, 0xf1, 0x8d, 0x36, 0x39}};
681 739
682// 3: HRESULT XLaunchUri(XUserHandle user, const char* uri): nothing is launched; E_FAIL. 740// 3: HRESULT XLaunchUri(XUserHandle user, const char* uri): nothing is launched; E_FAIL.
683// 4: HRESULT XDisplayAcquireTimeoutDeferral(XDisplayTimeoutDeferralHandle* handle): none is handed out. 741// 4: HRESULT XDisplayAcquireTimeoutDeferral(XDisplayTimeoutDeferralHandle* handle): Win32 display power request.
684// 5: XDisplayCloseTimeoutDeferralHandle(handle): no handle exists; E_FAIL, which a void caller ignores. 742// 5: void XDisplayCloseTimeoutDeferralHandle(XDisplayTimeoutDeferralHandle handle): clears and closes the request.
685HRESULT STDMETHODCALLTYPE launcher_acquire_deferral(void* self, void** handle) { 743HRESULT STDMETHODCALLTYPE launcher_acquire_deferral(void*, void** handle) {
686 if (handle) *handle = nullptr; 744 if (!handle) return E_POINTER;
687 return offline_failure<kLauncherName, 4>(self); 745 *handle = nullptr;
746 wchar_t reason[] = L"Title display timeout deferral";
747 REASON_CONTEXT ctx{};
748 ctx.Version = POWER_REQUEST_CONTEXT_VERSION;
749 ctx.Flags = POWER_REQUEST_CONTEXT_SIMPLE_STRING;
750 ctx.Reason.SimpleReasonString = reason;
751 const HANDLE req = PowerCreateRequest(&ctx);
752 if (req == INVALID_HANDLE_VALUE) return HRESULT_FROM_WIN32(GetLastError());
753 if (!PowerSetRequest(req, PowerRequestDisplayRequired)) {
754 const DWORD err = GetLastError();
755 CloseHandle(req);
756 return HRESULT_FROM_WIN32(err);
757 }
758 *handle = req;
759 return S_OK;
760}
761
762void STDMETHODCALLTYPE launcher_close_deferral(void*, void* handle) {
763 if (!handle) return;
764 PowerClearRequest(handle, PowerRequestDisplayRequired);
765 CloseHandle(handle);
688} 766}
689 767
690HRESULT STDMETHODCALLTYPE launcher_query_interface(void*, REFIID iid, void** out); 768HRESULT STDMETHODCALLTYPE launcher_query_interface(void*, REFIID iid, void** out);
@@ -692,7 +770,7 @@ const void* const kLauncherVtable[] = {
692 FN(launcher_query_interface), FN(object_add_ref), FN(object_release), // 0-2 IUnknown 770 FN(launcher_query_interface), FN(object_add_ref), FN(object_release), // 0-2 IUnknown
693 FN((offline_failure<kLauncherName, 3>)), // 3 XLaunchUri 771 FN((offline_failure<kLauncherName, 3>)), // 3 XLaunchUri
694 FN(launcher_acquire_deferral), // 4 XDisplayAcquireTimeoutDeferral 772 FN(launcher_acquire_deferral), // 4 XDisplayAcquireTimeoutDeferral
695 FN((offline_failure<kLauncherName, 5>)), // 5 XDisplayCloseTimeoutDeferralHandle 773 FN(launcher_close_deferral), // 5 XDisplayCloseTimeoutDeferralHandle
696}; 774};
697static_assert(std::size(kLauncherVtable) == 6, "IUnknown + IXLauncherImpl's 3 methods"); 775static_assert(std::size(kLauncherVtable) == 6, "IUnknown + IXLauncherImpl's 3 methods");
698ClassObject g_launcher_object{kLauncherVtable}; 776ClassObject g_launcher_object{kLauncherVtable};
diff --git a/runtime/shims/xmem.cpp b/runtime/shims/xmem.cpp
index a0335a237..e5c5c4469 100644
--- a/runtime/shims/xmem.cpp
+++ b/runtime/shims/xmem.cpp
@@ -19,8 +19,10 @@
19#include <psapi.h> 19#include <psapi.h>
20 20
21#include <atomic> 21#include <atomic>
22#include <cerrno>
22#include <cstdint> 23#include <cstdint>
23#include <cstdio> 24#include <cstdio>
25#include <cstdlib>
24#include <cstring> 26#include <cstring>
25#include <iterator> 27#include <iterator>
26#include <limits> 28#include <limits>
@@ -159,6 +161,19 @@ BOOL __stdcall XMemGetWorkingSetStatistics(uint32_t /*kind*/, void* stats) {
159 if (GlobalMemoryStatusEx(&ms) && ms.ullTotalPhys != 0) { 161 if (GlobalMemoryStatusEx(&ms) && ms.ullTotalPhys != 0) {
160 total_memory = ms.ullTotalPhys; 162 total_memory = ms.ullTotalPhys;
161 } 163 }
164 // Optional override (matching XSystemGetAppMemoryUsageLimit) so memory-constrained hosts can cap title pools.
165 char env[32]{};
166 const DWORD env_n = GetEnvironmentVariableA("LEONIDA_TITLE_MEMORY_MB", env, sizeof(env));
167 if (env_n > 0 && env_n < sizeof(env) && env[0] != '-' && env[0] != '+') {
168 errno = 0;
169 char* end = nullptr;
170 unsigned long long mib = std::strtoull(env, &end, 10);
171 if (errno == 0 && end != env && *end == '\0' && mib > 0) {
172 if (mib < 2048ULL) mib = 2048ULL;
173 if (mib > 65536ULL) mib = 65536ULL;
174 total_memory = static_cast<uint64_t>(mib) * 1024ULL * 1024ULL;
175 }
176 }
162 177
163 uint8_t* bytes = static_cast<uint8_t*>(stats); 178 uint8_t* bytes = static_cast<uint8_t*>(stats);
164 std::memset(bytes, 0, 16); 179 std::memset(bytes, 0, 16);
diff --git a/runtime/src/active_input.h b/runtime/src/active_input.h
index c0f7451b1..55b67d3bb 100644
--- a/runtime/src/active_input.h
+++ b/runtime/src/active_input.h
@@ -95,7 +95,8 @@ public:
95 const InputEdge edge = edge_between(it->second, now); 95 const InputEdge edge = edge_between(it->second, now);
96 it->second = now; 96 it->second = now;
97 if (edge == InputEdge::None || family == tracked_) return InputEdge::None; 97 if (edge == InputEdge::None || family == tracked_) return InputEdge::None;
98 if (changed_once_ && time_us - changed_at_ < thresholds_.min_switch_us) return InputEdge::None; 98 if (changed_once_ && (time_us < changed_at_ || time_us - changed_at_ < thresholds_.min_switch_us))
99 return InputEdge::None;
99 const InputFamily before = active(); 100 const InputFamily before = active();
100 tracked_ = family; 101 tracked_ = family;
101 changed_at_ = time_us; 102 changed_at_ = time_us;
@@ -125,11 +126,17 @@ private:
125 InputEdge edge_between(const InputSample& was, const InputSample& now) const { 126 InputEdge edge_between(const InputSample& was, const InputSample& now) const {
126 if (now.buttons & ~was.buttons) return InputEdge::Button; 127 if (now.buttons & ~was.buttons) return InputEdge::Button;
127 const float t = thresholds_.trigger; 128 const float t = thresholds_.trigger;
128 if ((was.left_trigger <= t && now.left_trigger > t) || (was.right_trigger <= t && now.right_trigger > t)) 129 const auto trigger_rose = [t](float prev, float cur) {
130 return std::isfinite(prev) && std::isfinite(cur) && prev <= t && cur > t;
131 };
132 if (trigger_rose(was.left_trigger, now.left_trigger) || trigger_rose(was.right_trigger, now.right_trigger))
129 return InputEdge::Trigger; 133 return InputEdge::Trigger;
130 const auto out = [this](float x, float y) { return std::hypot(x, y) > thresholds_.stick; }; 134 const auto stick_left = [this](float px, float py, float cx, float cy) {
131 if ((!out(was.left_x, was.left_y) && out(now.left_x, now.left_y)) || 135 if (!std::isfinite(px) || !std::isfinite(py) || !std::isfinite(cx) || !std::isfinite(cy)) return false;
132 (!out(was.right_x, was.right_y) && out(now.right_x, now.right_y))) 136 return std::hypot(px, py) <= thresholds_.stick && std::hypot(cx, cy) > thresholds_.stick;
137 };
138 if (stick_left(was.left_x, was.left_y, now.left_x, now.left_y) ||
139 stick_left(was.right_x, was.right_y, now.right_x, now.right_y))
133 return InputEdge::Stick; 140 return InputEdge::Stick;
134 return InputEdge::None; 141 return InputEdge::None;
135 } 142 }
diff --git a/runtime/src/arena_size.h b/runtime/src/arena_size.h
index 8f4ca4caf..196b03e3e 100644
--- a/runtime/src/arena_size.h
+++ b/runtime/src/arena_size.h
@@ -60,7 +60,10 @@ struct ArenaSize {
60// invalid Vulkan, while one under 16 MiB is only small (and no conformant device reports under 1 GiB). 60// invalid Vulkan, while one under 16 MiB is only small (and no conformant device reports under 1 GiB).
61inline ArenaSize decide_arena_size(const char* env, const ArenaLimits& limits, VkDeviceSize allocation_overhead = 0) { 61inline ArenaSize decide_arena_size(const char* env, const ArenaLimits& limits, VkDeviceSize allocation_overhead = 0) {
62 VkDeviceSize megabytes = kArenaDefaultMiB; 62 VkDeviceSize megabytes = kArenaDefaultMiB;
63 if (env && *env) megabytes = std::clamp<VkDeviceSize>(std::strtoull(env, nullptr, 10), kArenaMinMiB, kArenaMaxMiB); 63 // Signed, so "-5" clamps to the floor (strtoull wraps it to a huge value, which clamps to the maximum).
64 if (env && *env)
65 megabytes = VkDeviceSize(std::clamp<long long>(std::strtoll(env, nullptr, 10), (long long)kArenaMinMiB,
66 (long long)kArenaMaxMiB));
64 ArenaSize size; 67 ArenaSize size;
65 size.requested = size.bytes = megabytes * kArenaMiB; 68 size.requested = size.bytes = megabytes * kArenaMiB;
66 VkDeviceSize by_buffer = size.requested, by_allocation = size.requested; 69 VkDeviceSize by_buffer = size.requested, by_allocation = size.requested;
diff --git a/runtime/src/command_list.h b/runtime/src/command_list.h
index 595110f36..c28904efe 100644
--- a/runtime/src/command_list.h
+++ b/runtime/src/command_list.h
@@ -414,6 +414,15 @@ struct DrawViews {
414 std::uint32_t render_target_count = 8; 414 std::uint32_t render_target_count = 8;
415}; 415};
416 416
417// Shared across draws that keep the same multi-viewport / multi-scissor state (null for the common 1-viewport case).
418struct DrawViewports {
419 static constexpr std::uint32_t max_count = 16;
420 std::array<Viewport, max_count> viewports{};
421 std::uint32_t viewport_count = 0;
422 std::array<Rect, max_count> scissors{};
423 std::uint32_t scissor_count = 0;
424};
425
417// DrawInstanced / DrawIndexedInstanced / DispatchMesh, with everything they use captured when they are recorded: 426// DrawInstanced / DrawIndexedInstanced / DispatchMesh, with everything they use captured when they are recorded:
418// D3D12 reads render-target and depth descriptors at OMSetRenderTargets, and every other piece of state is the 427// D3D12 reads render-target and depth descriptors at OMSetRenderTargets, and every other piece of state is the
419// list's state at the draw. resource 0 marks an unbound render-target slot or no depth buffer. A mesh draw 428// list's state at the draw. resource 0 marks an unbound render-target slot or no depth buffer. A mesh draw
@@ -440,6 +449,7 @@ struct Draw {
440 std::int32_t base_vertex = 0; 449 std::int32_t base_vertex = 0;
441 std::uint32_t first_instance = 0; 450 std::uint32_t first_instance = 0;
442 bool mesh = false; 451 bool mesh = false;
452 std::shared_ptr<const DrawViewports> viewports; // non-null when >1 viewport or >1 scissor was bound
443}; 453};
444 454
445// D3D12_TEXTURE_DATA_PITCH_ALIGNMENT and D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT. 455// D3D12_TEXTURE_DATA_PITCH_ALIGNMENT and D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT.
@@ -691,10 +701,11 @@ public:
691 return append(barrier); 701 return append(barrier);
692 } 702 }
693 703
704 // LayoutAfter UNDEFINED is legal: the subresources' contents are no longer needed, as before their memory is
705 // aliased (the retail title ends a depth buffer's use this way, #984; WARP closes such a list,
706 // d3d12_close_parity_test). Replay keeps the image's Vulkan layout and orders the accesses only.
694 bool barrier(const TextureBarrier& barrier) { 707 bool barrier(const TextureBarrier& barrier) {
695 if (!barrier.resource || !valid_sync(barrier.sync_before, barrier.sync_after)) return false; 708 if (!barrier.resource || !valid_sync(barrier.sync_before, barrier.sync_after)) return false;
696 if (barrier.layout_after == d3d12_layout::undefined && barrier.layout_before != d3d12_layout::undefined)
697 return false;
698 if (barrier.flags & ~texture_barrier_discard) return false; 709 if (barrier.flags & ~texture_barrier_discard) return false;
699 if (barrier.range.mip_count && (!barrier.range.layer_count || !barrier.range.plane_count)) return false; 710 if (barrier.range.mip_count && (!barrier.range.layer_count || !barrier.range.plane_count)) return false;
700 if (barrier.sync_after == d3d12_sync::split) return !closed_; 711 if (barrier.sync_after == d3d12_sync::split) return !closed_;
diff --git a/runtime/src/cpu_emulation.h b/runtime/src/cpu_emulation.h
index fac13eeee..8df3b55d0 100644
--- a/runtime/src/cpu_emulation.h
+++ b/runtime/src/cpu_emulation.h
@@ -272,6 +272,84 @@ inline bool apply(const Decoded& d, CONTEXT* c, EXCEPTION_RECORD* fault = nullpt
272 return true; 272 return true;
273} 273}
274 274
275inline uint64_t gpr_read(const CONTEXT* c, int r) {
276 switch (r) {
277 case 0: return c->Rax; case 1: return c->Rcx; case 2: return c->Rdx; case 3: return c->Rbx;
278 case 4: return c->Rsp; case 5: return c->Rbp; case 6: return c->Rsi; case 7: return c->Rdi;
279 case 8: return c->R8; case 9: return c->R9; case 10: return c->R10; case 11: return c->R11;
280 case 12: return c->R12; case 13: return c->R13; case 14: return c->R14; case 15: return c->R15;
281 default: return 0;
282 }
283}
284
285enum class ClzeroLoopResult { no_match, ok, faulted };
286
287inline void apply_cmp_flags(CONTEXT* c, uint64_t lhs, uint64_t rhs) {
288 const uint64_t diff = lhs - rhs;
289 uint32_t flags = c->EFlags & ~DWORD(0x8D5u); // clear CF(0), PF(2), AF(4), ZF(6), SF(7), OF(11)
290 if (lhs < rhs) flags |= 0x1u; // CF
291 uint8_t lo8 = static_cast<uint8_t>(diff);
292 lo8 ^= lo8 >> 4;
293 lo8 ^= lo8 >> 2;
294 lo8 ^= lo8 >> 1;
295 if ((lo8 & 1u) == 0) flags |= 0x4u; // PF
296 if ((lhs ^ rhs ^ diff) & 0x10u) flags |= 0x10u; // AF
297 if (diff == 0) flags |= 0x40u; // ZF
298 if (diff >> 63) flags |= 0x80u; // SF
299 if (((lhs ^ rhs) & (lhs ^ diff)) >> 63) flags |= 0x800u; // OF
300 c->EFlags = flags;
301}
302
303// Fast-path for the Zen 2 zeroing loop: `clzero; add rax, 0x40; cmp rax, reg64; jb -12` (12 bytes).
304// Zeroes the entire writable span in one memset instead of raising #UD + VirtualQuery per 64-byte line.
305inline ClzeroLoopResult try_clzero_loop(const uint8_t* code, std::size_t avail, CONTEXT* c, EXCEPTION_RECORD* fault) {
306 if (avail < 12) return ClzeroLoopResult::no_match;
307 if (code[0] != 0x0F || code[1] != 0x01 || code[2] != 0xFC) return ClzeroLoopResult::no_match;
308 if (code[3] != 0x48 || code[4] != 0x83 || code[5] != 0xC0 || code[6] != 0x40) return ClzeroLoopResult::no_match;
309 if ((code[7] != 0x48 && code[7] != 0x4C) || code[8] != 0x39 || (code[9] & 0xC7) != 0xC0)
310 return ClzeroLoopResult::no_match;
311 if (code[10] != 0x72 || code[11] != 0xF4) return ClzeroLoopResult::no_match;
312
313 const int limit_reg = ((code[9] >> 3) & 7) | ((code[7] & 4) << 1);
314 if (limit_reg == 0 || limit_reg == 4) return ClzeroLoopResult::no_match;
315
316 const uint64_t start = c->Rax;
317 const uint64_t limit = gpr_read(c, limit_reg);
318 if ((start & 63) != 0 || limit <= start + 64) return ClzeroLoopResult::no_match;
319
320 uint64_t total = (limit - start + 63) & ~uint64_t(63);
321 constexpr uint64_t kMaxBatch = uint64_t(64) << 20;
322 if (total > kMaxBatch) total = kMaxBatch;
323 const uint64_t end = start + total;
324
325 for (uint64_t cur = start; cur < end;) {
326 const DWORD err = writable(cur);
327 if (err) {
328 if (cur > start) {
329 std::memset(reinterpret_cast<void*>(start), 0, std::size_t(cur - start));
330 c->Rax = cur;
331 apply_cmp_flags(c, cur, limit);
332 }
333 if (fault) {
334 std::memset(fault, 0, sizeof *fault);
335 fault->ExceptionCode = err;
336 fault->NumberParameters = 2;
337 fault->ExceptionInformation[0] = 1;
338 fault->ExceptionInformation[1] = ULONG_PTR(cur);
339 }
340 return ClzeroLoopResult::faulted;
341 }
342 const uint64_t next_page = (cur & ~uint64_t(0xFFF)) + 0x1000;
343 cur = next_page < end ? next_page : end;
344 }
345
346 std::memset(reinterpret_cast<void*>(start), 0, std::size_t(total));
347 c->Rax = end;
348 apply_cmp_flags(c, end, limit);
349 if (end >= limit) c->Rip += 12;
350 return ClzeroLoopResult::ok;
351}
352
275inline LONG CALLBACK handler(EXCEPTION_POINTERS* info) { 353inline LONG CALLBACK handler(EXCEPTION_POINTERS* info) {
276 if (info->ExceptionRecord->ExceptionCode != STATUS_ILLEGAL_INSTRUCTION) return EXCEPTION_CONTINUE_SEARCH; 354 if (info->ExceptionRecord->ExceptionCode != STATUS_ILLEGAL_INSTRUCTION) return EXCEPTION_CONTINUE_SEARCH;
277 CONTEXT* c = info->ContextRecord; 355 CONTEXT* c = info->ContextRecord;
@@ -281,6 +359,25 @@ inline LONG CALLBACK handler(EXCEPTION_POINTERS* info) {
281 const Decoded d = decode(code, avail); 359 const Decoded d = decode(code, avail);
282 if (d.op == Op::none) return EXCEPTION_CONTINUE_SEARCH; 360 if (d.op == Op::none) return EXCEPTION_CONTINUE_SEARCH;
283 EXCEPTION_RECORD fault; 361 EXCEPTION_RECORD fault;
362 if (d.op == Op::clzero && !d.addr32 && d.length == 3) {
363 const uint64_t fault_rip = c->Rip;
364 const ClzeroLoopResult lr = try_clzero_loop(code, avail, c, &fault);
365 if (lr == ClzeroLoopResult::ok) {
366 if (count(d.op).fetch_add(1, std::memory_order_relaxed) == 0)
367 std::fprintf(stderr, "[rt] cpu: this CPU has no %s; emulating it (first at %p)\n", name(d.op),
368 reinterpret_cast<void*>(fault_rip));
369 return EXCEPTION_CONTINUE_EXECUTION;
370 }
371 if (lr == ClzeroLoopResult::faulted) {
372 EXCEPTION_RECORD* r = info->ExceptionRecord;
373 r->ExceptionCode = fault.ExceptionCode;
374 r->ExceptionFlags = 0;
375 r->NumberParameters = fault.NumberParameters;
376 r->ExceptionInformation[0] = fault.ExceptionInformation[0];
377 r->ExceptionInformation[1] = fault.ExceptionInformation[1];
378 return EXCEPTION_CONTINUE_SEARCH;
379 }
380 }
284 if (!apply(d, c, &fault)) { 381 if (!apply(d, c, &fault)) {
285 // CLZERO on a line it cannot write: the CPU would raise that fault at this instruction, so the next handlers 382 // CLZERO on a line it cannot write: the CPU would raise that fault at this instruction, so the next handlers
286 // see it instead of the #UD (RIP still points at the instruction). 383 // see it instead of the #UD (RIP still points at the instruction).
diff --git a/runtime/src/crt_timed_wait.cpp b/runtime/src/crt_timed_wait.cpp
index 6441f2868..cd26e7d3a 100644
--- a/runtime/src/crt_timed_wait.cpp
+++ b/runtime/src/crt_timed_wait.cpp
@@ -25,7 +25,9 @@ extern "C" {
25// absolute, in TIME_UTC seconds and nanoseconds, and the result uses _Thrd_result's values (0, or 2 on timeout). 25// absolute, in TIME_UTC seconds and nanoseconds, and the result uses _Thrd_result's values (0, or 2 on timeout).
26__declspec(dllimport) int __cdecl _Cnd_timedwait(_Cnd_t, _Mtx_t, const _timespec64*) noexcept; 26__declspec(dllimport) int __cdecl _Cnd_timedwait(_Cnd_t, _Mtx_t, const _timespec64*) noexcept;
27 27
28_Thrd_result __stdcall _Cnd_timedwait_for_unchecked(_Cnd_t cond, _Mtx_t mtx, unsigned int ms) noexcept { 28namespace {
29
30_Thrd_result timedwait_for_impl(_Cnd_t cond, _Mtx_t mtx, unsigned int ms, bool unchecked) noexcept {
29 _timespec64 deadline{}; 31 _timespec64 deadline{};
30 if (_timespec64_get(&deadline, TIME_UTC) != TIME_UTC) deadline = {}; 32 if (_timespec64_get(&deadline, TIME_UTC) != TIME_UTC) deadline = {};
31 deadline.tv_sec += ms / 1000; 33 deadline.tv_sec += ms / 1000;
@@ -34,13 +36,32 @@ _Thrd_result __stdcall _Cnd_timedwait_for_unchecked(_Cnd_t cond, _Mtx_t mtx, uns
34 deadline.tv_sec += 1; 36 deadline.tv_sec += 1;
35 deadline.tv_nsec -= 1000000000L; 37 deadline.tv_nsec -= 1000000000L;
36 } 38 }
37 // A spurious or early return is allowed ("unchecked"): the STL's callers check the clock themselves. 39 // Preserve the caller's LastError across the wait while detecting OS timer timeouts cleanly.
38 return static_cast<_Thrd_result>(_Cnd_timedwait(cond, mtx, &deadline)); 40 const DWORD saved_error = GetLastError();
41 SetLastError(ERROR_SUCCESS);
42 const auto res = static_cast<_Thrd_result>(_Cnd_timedwait(cond, mtx, &deadline));
43 const DWORD wait_error = GetLastError();
44 SetLastError(saved_error);
45 // msvcp140's _Cnd_timedwait checks _Xtime_diff_to_millis2(target, &now) == 0 after SleepConditionVariableSRW
46 // returns FALSE/ERROR_TIMEOUT, so an OS timer wake even <1 ms before `deadline` turns into _Thrd_result::_Success.
47 // STL wait_for/wait_until callers treat _Success from _Cnd_timedwait_for_unchecked as a notification/spurious
48 // wake (cv_status::no_timeout) instead of looping until steady_clock reaches the target; report _Timedout here
49 // so the caller checks steady_clock and waits for the remaining time.
50 if (unchecked && res == _Thrd_result::_Success && wait_error == ERROR_TIMEOUT) {
51 return _Thrd_result::_Timedout;
52 }
53 return res;
54}
55
56} // namespace
57
58_Thrd_result __stdcall _Cnd_timedwait_for_unchecked(_Cnd_t cond, _Mtx_t mtx, unsigned int ms) noexcept {
59 return timedwait_for_impl(cond, mtx, ms, true);
39} 60}
40 61
41// Not declared by the 14.4x headers, but defined by the same member: keep a caller of the older name off it too. 62// Not declared by the 14.4x headers, but defined by the same member: keep a caller of the older name off it too.
42_Thrd_result __stdcall _Cnd_timedwait_for(_Cnd_t cond, _Mtx_t mtx, unsigned int ms) noexcept { 63_Thrd_result __stdcall _Cnd_timedwait_for(_Cnd_t cond, _Mtx_t mtx, unsigned int ms) noexcept {
43 return _Cnd_timedwait_for_unchecked(cond, mtx, ms); 64 return timedwait_for_impl(cond, mtx, ms, false);
44} 65}
45 66
46void __cdecl _Smtx_lock_exclusive(_Smtx_t* lock) noexcept { 67void __cdecl _Smtx_lock_exclusive(_Smtx_t* lock) noexcept {
diff --git a/runtime/src/frame_pacer.h b/runtime/src/frame_pacer.h
index fa9c20df1..afeaf191e 100644
--- a/runtime/src/frame_pacer.h
+++ b/runtime/src/frame_pacer.h
@@ -30,14 +30,17 @@
30// suspended) is unchanged. 30// suspended) is unchanged.
31 31
32#include <algorithm> 32#include <algorithm>
33#include <array>
33#include <atomic> 34#include <atomic>
34#include <chrono> 35#include <chrono>
35#include <condition_variable> 36#include <condition_variable>
37#include <cstddef>
36#include <cstdint> 38#include <cstdint>
37#include <deque> 39#include <deque>
38#include <functional> 40#include <functional>
39#include <limits> 41#include <limits>
40#include <mutex> 42#include <mutex>
43#include <vector>
41 44
42namespace leonida { 45namespace leonida {
43 46
@@ -102,8 +105,14 @@ private:
102 std::function<void()> wake_; 105 std::function<void()> wake_;
103}; 106};
104 107
105// Provisional definitions of ours: the real constants and layouts of the console API are unmeasured. 108// Provisional definitions of ours: the real constants and layouts of the console API are unmeasured. Frame event
109// kinds (0: origin, 1: vblank, 2: flip) and wait flags.
106inline constexpr std::uint32_t frame_event_origin = 0; 110inline constexpr std::uint32_t frame_event_origin = 0;
111inline constexpr std::uint32_t frame_event_vblank = 1;
112inline constexpr std::uint32_t frame_event_flip = 2;
113inline constexpr std::uint32_t frame_event_count = 3;
114// Issue a consecutive frame token even when WaitFrameEventX(origin, ...) times out (returns S_FALSE).
115inline constexpr std::uint32_t frame_wait_flag_token_on_timeout = 2;
107// Statistics types (bit mask). Interval and render entries are never produced here. 116// Statistics types (bit mask). Interval and render entries are never produced here.
108inline constexpr std::uint32_t stat_frame_interval = 0x01; 117inline constexpr std::uint32_t stat_frame_interval = 0x01;
109inline constexpr std::uint32_t stat_frame_event = 0x02; 118inline constexpr std::uint32_t stat_frame_event = 0x02;
@@ -143,6 +152,25 @@ struct FrameStatistic {
143 float percent_scanned = 0.0f; // display entries: where the scan was when the frame came up (0 at a vblank) 152 float percent_scanned = 0.0f; // display entries: where the scan was when the frame came up (0 at a vblank)
144}; 153};
145 154
155// Fixed-capacity ring buffer size for recent frame-time and origin-to-present latency samples (BL-6).
156inline constexpr std::size_t frame_pacing_window = 1024;
157
158// Summary over the most recent `frame_pacing_window` presented frames (p50/p95/p99 and mean drift against target).
159struct FramePacingSummary {
160 std::uint64_t frames = 0; // total presented frames recorded
161 std::uint64_t samples = 0; // present-to-present intervals in the ring buffer (<= frame_pacing_window)
162 std::uint32_t target_interval_us = 0; // active target interval in us (0 when unpaced or uncapped)
163 double mean_us = 0.0; // mean present-to-present interval over `samples`
164 double drift_us = 0.0; // mean_us - target_interval_us (0 when unpaced/uncapped or samples == 0)
165 std::uint64_t p50_us = 0; // nearest-rank 50th percentile frame interval in us
166 std::uint64_t p95_us = 0; // nearest-rank 95th percentile frame interval in us
167 std::uint64_t p99_us = 0; // nearest-rank 99th percentile frame interval in us
168 std::uint64_t latency_samples = 0; // origin-to-present latency samples in the ring buffer
169 std::uint64_t latency_p50_us = 0; // nearest-rank 50th percentile origin-to-present latency in us
170 std::uint64_t latency_p95_us = 0; // nearest-rank 95th percentile origin-to-present latency in us
171 std::uint64_t latency_p99_us = 0; // nearest-rank 99th percentile origin-to-present latency in us
172};
173
146class FramePacer { 174class FramePacer {
147public: 175public:
148 explicit FramePacer(FrameClock& clock) : clock_(clock) { 176 explicit FramePacer(FrameClock& clock) : clock_(clock) {
@@ -177,38 +205,42 @@ public:
177 latency_ = std::max(latency, 1u); 205 latency_ = std::max(latency, 1u);
178 epoch_us_ = clock_.now_us(); 206 epoch_us_ = clock_.now_us();
179 interval_set_ = true; 207 interval_set_ = true;
180 offset_us_ = std::min(offset_us_, period_us - 1); 208 for (std::uint32_t k = 0; k < frame_event_count; ++k) {
181 last_origin_ = 0; // origin 0 is the epoch itself, which has passed 209 event_offset_us_[k] = std::min(event_offset_us_[k], period_us - 1);
210 last_event_tick_[k] = 0; // tick 0 is the epoch itself, which has passed
211 }
182 cv_.notify_all(); 212 cv_.notify_all();
183 return pacer_hr::ok; 213 return pacer_hr::ok;
184 } 214 }
185 215
186 // ScheduleFrameEventX(event, offset, ..., flags). Only the origin event exists here. 216 // ScheduleFrameEventX(event, offset, ..., flags). Supports origin (0), vblank (1), and flip (2).
187 std::int32_t schedule_frame_event(std::uint32_t event, std::uint32_t offset_us, std::uint32_t flags) { 217 std::int32_t schedule_frame_event(std::uint32_t event, std::uint32_t offset_us, std::uint32_t flags) {
188 (void)flags; 218 (void)flags;
189 if (event != frame_event_origin) return pacer_hr::invalid_arg; 219 if (event >= frame_event_count) return pacer_hr::invalid_arg;
190 std::lock_guard guard(mutex_); 220 std::lock_guard guard(mutex_);
191 if (suspended_ || !interval_set_) return pacer_hr::invalid_state; 221 if (suspended_ || !interval_set_) return pacer_hr::invalid_state;
192 if (offset_us >= period_us_) return pacer_hr::invalid_arg; 222 if (offset_us >= period_us_) return pacer_hr::invalid_arg;
193 offset_us_ = offset_us; 223 event_offset_us_[event] = offset_us;
194 armed_ = true; 224 event_armed_[event] = true;
195 // The first origin is the next one that has not come yet: origin n is due at epoch + n * period + offset. 225 // The first event is the next one that has not come yet: tick n is due at epoch + n * period + offset.
196 const std::uint64_t now = clock_.now_us(); 226 const std::uint64_t now = clock_.now_us();
197 last_origin_ = now >= epoch_us_ + offset_us_ ? std::int64_t((now - epoch_us_ - offset_us_) / period_us_) : 0; 227 last_event_tick_[event] =
228 now >= epoch_us_ + offset_us ? std::int64_t((now - epoch_us_ - offset_us) / period_us_) : 0;
198 cv_.notify_all(); 229 cv_.notify_all();
199 return pacer_hr::ok; 230 return pacer_hr::ok;
200 } 231 }
201 232
202 // WaitFrameEventX(event, timeout, ..., flags, &token). Blocks until the next origin, and while `latency` frames 233 // WaitFrameEventX(event, timeout, ..., flags, &token). Origin waits block until the next origin tick and while
203 // are in flight. pacer_hr::timeout when `timeout_ms` passes first (infinite_timeout_ms: never); the token is left 234 // `latency` frames are in flight, issuing a consecutive token on success (or on timeout with
204 // alone then. invalid_state when nothing is registered, the pacer is suspended, or one of those happens while waiting. 235 // frame_wait_flag_token_on_timeout, returning S_FALSE). Vblank/flip waits pace independently per event kind and
236 // leave `*token` untouched.
205 std::int32_t wait_frame_event(std::uint32_t event, std::uint32_t timeout_ms, std::uint32_t flags, 237 std::int32_t wait_frame_event(std::uint32_t event, std::uint32_t timeout_ms, std::uint32_t flags,
206 std::uint64_t* token) { 238 std::uint64_t* token) {
207 (void)flags; 239 if (event >= frame_event_count) return pacer_hr::invalid_arg;
208 if (event != frame_event_origin || !token) return pacer_hr::invalid_arg; 240 if (event == frame_event_origin && !token) return pacer_hr::invalid_arg;
209 std::unique_lock lock(mutex_); 241 std::unique_lock lock(mutex_);
210 ++waiters_; 242 ++waiters_;
211 const std::int32_t result = wait_locked(lock, timeout_ms, token); 243 const std::int32_t result = wait_locked(lock, event, timeout_ms, flags, token);
212 if (--waiters_ == 0) cv_.notify_all(); 244 if (--waiters_ == 0) cv_.notify_all();
213 return result; 245 return result;
214 } 246 }
@@ -301,8 +333,9 @@ public:
301 std::lock_guard guard(mutex_); 333 std::lock_guard guard(mutex_);
302 const std::uint64_t now = clock_.now_us(); 334 const std::uint64_t now = clock_.now_us();
303 retire_locked(now); 335 retire_locked(now);
336 record_present_timing_locked(now, token);
304 last_presented_ = std::max(last_presented_, token); 337 last_presented_ = std::max(last_presented_, token);
305 if (!interval_set_ || !armed_ || uncapped_) { // not paced or uncapped: shows at once 338 if (!interval_set_ || !any_armed_locked() || uncapped_) { // not paced or uncapped: shows at once
306 for (Record& r : records_) 339 for (Record& r : records_)
307 if (r.token == token) { r.presented = r.displayed = true; r.present_us = r.display_us = now; } 340 if (r.token == token) { r.presented = r.displayed = true; r.present_us = r.display_us = now; }
308 return; 341 return;
@@ -330,8 +363,9 @@ public:
330 // the origin event not armed or the cap off it is not paced: it shows at once and is not counted. 363 // the origin event not armed or the cap off it is not paced: it shows at once and is not counted.
331 void note_untokened_present() { 364 void note_untokened_present() {
332 std::lock_guard guard(mutex_); 365 std::lock_guard guard(mutex_);
333 if (!interval_set_ || !armed_ || uncapped_) return;
334 const std::uint64_t now = clock_.now_us(); 366 const std::uint64_t now = clock_.now_us();
367 record_present_timing_locked(now, 0);
368 if (!interval_set_ || !any_armed_locked() || uncapped_) return;
335 retire_locked(now); 369 retire_locked(now);
336 const std::uint64_t since = now > epoch_us_ ? now - epoch_us_ : 0; 370 const std::uint64_t since = now > epoch_us_ ? now - epoch_us_ : 0;
337 std::uint64_t flip = epoch_us_ + (since / period_us_ + 1) * period_us_; 371 std::uint64_t flip = epoch_us_ + (since / period_us_ + 1) * period_us_;
@@ -344,7 +378,9 @@ public:
344 void suspend() { 378 void suspend() {
345 std::lock_guard guard(mutex_); 379 std::lock_guard guard(mutex_);
346 suspended_ = true; 380 suspended_ = true;
347 interval_set_ = armed_ = false; 381 interval_set_ = false;
382 has_last_present_ = false; // do not count the suspended pause as a frame interval after resume
383 for (bool& a : event_armed_) a = false;
348 pending_.clear(); 384 pending_.clear();
349 cv_.notify_all(); 385 cv_.notify_all();
350 } 386 }
@@ -352,7 +388,8 @@ public:
352 void resume() { 388 void resume() {
353 std::lock_guard guard(mutex_); 389 std::lock_guard guard(mutex_);
354 suspended_ = false; 390 suspended_ = false;
355 interval_set_ = armed_ = false; 391 interval_set_ = false;
392 for (bool& a : event_armed_) a = false;
356 cv_.notify_all(); 393 cv_.notify_all();
357 } 394 }
358 395
@@ -366,13 +403,54 @@ public:
366 // Frames that were flipped mid-scan because of ImmediateThresholdPercent. 403 // Frames that were flipped mid-scan because of ImmediateThresholdPercent.
367 std::uint64_t immediate_presents() const { std::lock_guard guard(mutex_); return immediate_presents_; } 404 std::uint64_t immediate_presents() const { std::lock_guard guard(mutex_); return immediate_presents_; }
368 std::uint32_t period_us() const { std::lock_guard guard(mutex_); return period_us_; } 405 std::uint32_t period_us() const { std::lock_guard guard(mutex_); return period_us_; }
369 bool registered() const { std::lock_guard guard(mutex_); return interval_set_ && armed_; } 406 bool registered() const { std::lock_guard guard(mutex_); return interval_set_ && any_armed_locked(); }
370 407
371 // The fps cap off (LEONIDA_PRESENT_UNCAP; see the top comment): waits never block and presents count as shown 408 // The fps cap off (LEONIDA_PRESENT_UNCAP; see the top comment): waits never block and presents count as shown
372 // at once. Registration and suspension keep meaning what they did; the flag survives suspend/resume. 409 // at once. Registration and suspension keep meaning what they did; the flag survives suspend/resume.
373 void set_uncapped(bool on) { std::lock_guard guard(mutex_); uncapped_ = on; } 410 void set_uncapped(bool on) { std::lock_guard guard(mutex_); uncapped_ = on; }
374 bool uncapped() const { std::lock_guard guard(mutex_); return uncapped_; } 411 bool uncapped() const { std::lock_guard guard(mutex_); return uncapped_; }
375 412
413 // Frame-time percentiles, mean drift against the active target interval, and origin-to-present latency over
414 // the last `frame_pacing_window` presented frames (BL-6).
415 FramePacingSummary pacing_summary() const {
416 FramePacingSummary out;
417 std::vector<std::uint64_t> intervals;
418 std::vector<std::uint64_t> latencies;
419 {
420 std::lock_guard guard(mutex_);
421 out.frames = presents_recorded_;
422 out.target_interval_us = (interval_set_ && !uncapped_) ? period_us_ : 0u;
423 intervals.reserve(interval_count_);
424 for (std::size_t i = 0; i < interval_count_; ++i) intervals.push_back(interval_ring_[i]);
425 latencies.reserve(latency_count_);
426 for (std::size_t i = 0; i < latency_count_; ++i) latencies.push_back(latency_ring_[i]);
427 }
428 auto percentile = [](const std::vector<std::uint64_t>& sorted, std::size_t pct) -> std::uint64_t {
429 if (sorted.empty()) return 0;
430 const std::size_t idx = (pct * sorted.size() + 99) / 100 - 1;
431 return sorted[std::min(idx, sorted.size() - 1)];
432 };
433 if (!intervals.empty()) {
434 out.samples = intervals.size();
435 double sum = 0.0;
436 for (std::uint64_t v : intervals) sum += double(v);
437 out.mean_us = sum / double(intervals.size());
438 if (out.target_interval_us != 0) out.drift_us = out.mean_us - double(out.target_interval_us);
439 std::sort(intervals.begin(), intervals.end());
440 out.p50_us = percentile(intervals, 50);
441 out.p95_us = percentile(intervals, 95);
442 out.p99_us = percentile(intervals, 99);
443 }
444 if (!latencies.empty()) {
445 out.latency_samples = latencies.size();
446 std::sort(latencies.begin(), latencies.end());
447 out.latency_p50_us = percentile(latencies, 50);
448 out.latency_p95_us = percentile(latencies, 95);
449 out.latency_p99_us = percentile(latencies, 99);
450 }
451 return out;
452 }
453
376private: 454private:
377 struct Pending { 455 struct Pending {
378 std::uint64_t token; 456 std::uint64_t token;
@@ -386,6 +464,29 @@ private:
386 bool presented = false, displayed = false; 464 bool presented = false, displayed = false;
387 }; 465 };
388 466
467 void record_present_timing_locked(std::uint64_t now, std::uint64_t token) {
468 ++presents_recorded_;
469 if (has_last_present_ && now >= last_present_us_) {
470 interval_ring_[interval_head_] = now - last_present_us_;
471 interval_head_ = (interval_head_ + 1) % frame_pacing_window;
472 if (interval_count_ < frame_pacing_window) ++interval_count_;
473 }
474 has_last_present_ = true;
475 last_present_us_ = now;
476 if (token != 0) {
477 for (const Record& r : records_) {
478 if (r.token == token) {
479 if (now >= r.origin_us) {
480 latency_ring_[latency_head_] = now - r.origin_us;
481 latency_head_ = (latency_head_ + 1) % frame_pacing_window;
482 if (latency_count_ < frame_pacing_window) ++latency_count_;
483 }
484 break;
485 }
486 }
487 }
488 }
489
389 // Frames whose vblank has come are shown. 490 // Frames whose vblank has come are shown.
390 void retire_locked(std::uint64_t now) { 491 void retire_locked(std::uint64_t now) {
391 while (!pending_.empty() && pending_.front().flip_us <= now) { 492 while (!pending_.empty() && pending_.front().flip_us <= now) {
@@ -399,45 +500,67 @@ private:
399 } 500 }
400 } 501 }
401 502
402 std::int32_t wait_locked(std::unique_lock<std::mutex>& lock, std::uint32_t timeout_ms, std::uint64_t* token) { 503 bool any_armed_locked() const {
504 return event_armed_[0] || event_armed_[1] || event_armed_[2];
505 }
506
507 std::uint64_t issue_token_locked(std::uint64_t origin_us, std::uint64_t due_us) {
508 const std::uint64_t tok = ++issued_;
509 Record record;
510 record.token = tok;
511 record.origin_us = origin_us;
512 record.due_us = due_us;
513 records_.push_back(record);
514 if (records_.size() > 64) records_.pop_front();
515 return tok;
516 }
517
518 std::int32_t wait_locked(std::unique_lock<std::mutex>& lock, std::uint32_t event, std::uint32_t timeout_ms,
519 std::uint32_t flags, std::uint64_t* token) {
520 const bool is_origin = (event == frame_event_origin);
521 const bool token_on_timeout = (flags & frame_wait_flag_token_on_timeout) != 0;
403 const std::uint64_t start = clock_.now_us(); 522 const std::uint64_t start = clock_.now_us();
404 const std::uint64_t give_up = timeout_ms == infinite_timeout_ms ? no_deadline 523 const std::uint64_t give_up = timeout_ms == infinite_timeout_ms ? no_deadline
405 : start + std::uint64_t(timeout_ms) * 1000; 524 : start + std::uint64_t(timeout_ms) * 1000;
406 for (;;) { 525 for (;;) {
407 if (shutdown_ || suspended_ || !interval_set_ || !armed_) return pacer_hr::invalid_state; 526 if (shutdown_ || suspended_ || !interval_set_) return pacer_hr::invalid_state;
527 if (is_origin ? !event_armed_[frame_event_origin]
528 : (!event_armed_[event] && !event_armed_[frame_event_origin])) {
529 return pacer_hr::invalid_state;
530 }
408 const std::uint64_t now = clock_.now_us(); 531 const std::uint64_t now = clock_.now_us();
409 retire_locked(now); 532 retire_locked(now);
410 if (uncapped_) { // no vblank grid and no latency throttle: a token at once, due now 533 if (uncapped_) { // no vblank grid and no latency throttle
411 *token = ++issued_; 534 if (is_origin) *token = issue_token_locked(now, now);
412 Record record;
413 record.token = *token;
414 record.origin_us = now;
415 record.due_us = now;
416 records_.push_back(record);
417 if (records_.size() > 64) records_.pop_front();
418 return pacer_hr::ok; 535 return pacer_hr::ok;
419 } 536 }
420 const std::uint64_t first = epoch_us_ + offset_us_; // origin 0 537 const std::uint32_t offset = event_offset_us_[event];
421 const std::int64_t next = last_origin_ + 1; 538 const std::uint64_t first = epoch_us_ + offset; // tick 0
539 const std::int64_t next = last_event_tick_[event] + 1;
422 const std::uint64_t next_us = first + std::uint64_t(next) * period_us_; 540 const std::uint64_t next_us = first + std::uint64_t(next) * period_us_;
423 std::uint64_t wake = next_us; 541 std::uint64_t wake = next_us;
424 if (now >= next_us) { 542 if (now >= next_us) {
425 if (pending_.size() < latency_) { 543 if (!is_origin || pending_.size() < latency_) {
426 const std::int64_t newest = std::int64_t((now - first) / period_us_); 544 const std::int64_t newest = std::int64_t((now - first) / period_us_);
427 const std::int64_t origin = std::max(next, newest); 545 const std::int64_t tick = std::max(next, newest);
428 last_origin_ = origin; 546 last_event_tick_[event] = tick;
429 *token = ++issued_; 547 if (is_origin) {
430 Record record; 548 const std::uint64_t origin_us = first + std::uint64_t(tick) * period_us_;
431 record.token = *token; 549 const std::uint64_t due_us = origin_us - offset + period_us_;
432 record.origin_us = first + std::uint64_t(origin) * period_us_; 550 *token = issue_token_locked(origin_us, due_us);
433 record.due_us = record.origin_us - offset_us_ + period_us_; 551 }
434 records_.push_back(record);
435 if (records_.size() > 64) records_.pop_front();
436 return pacer_hr::ok; 552 return pacer_hr::ok;
437 } 553 }
438 wake = pending_.front().flip_us; // blocked by the latency: until the oldest frame is shown 554 wake = pending_.front().flip_us; // blocked by the latency: until the oldest frame is shown
439 } 555 }
440 if (give_up != no_deadline && now >= give_up) return pacer_hr::timeout; 556 if (give_up != no_deadline && now >= give_up) {
557 if (is_origin && token_on_timeout) {
558 // Frame started early on timeout: issue a consecutive token without consuming the tick.
559 *token = issue_token_locked(now, next_us - offset + period_us_);
560 return pacer_hr::false_;
561 }
562 return token_on_timeout ? pacer_hr::false_ : pacer_hr::timeout;
563 }
441 clock_.wait(lock, cv_, give_up == no_deadline ? wake : std::min(wake, give_up)); 564 clock_.wait(lock, cv_, give_up == no_deadline ? wake : std::min(wake, give_up));
442 } 565 }
443 } 566 }
@@ -450,16 +573,25 @@ private:
450 573
451 bool suspended_ = false; 574 bool suspended_ = false;
452 bool interval_set_ = false; 575 bool interval_set_ = false;
453 bool armed_ = false; 576 bool event_armed_[frame_event_count] = {false, false, false};
454 bool uncapped_ = false; 577 bool uncapped_ = false;
455 std::uint32_t period_us_ = 0; 578 std::uint32_t period_us_ = 0;
456 std::uint32_t latency_ = 1; 579 std::uint32_t latency_ = 1;
457 std::uint32_t offset_us_ = 0; 580 std::uint32_t event_offset_us_[frame_event_count] = {0, 0, 0};
458 std::uint64_t epoch_us_ = 0; 581 std::uint64_t epoch_us_ = 0;
459 std::int64_t last_origin_ = 0; // origin 0 is the epoch itself, which has passed 582 std::int64_t last_event_tick_[frame_event_count] = {0, 0, 0}; // tick 0 is the epoch itself, which has passed
460 std::uint64_t issued_ = 0; 583 std::uint64_t issued_ = 0;
461 std::uint64_t last_presented_ = 0; 584 std::uint64_t last_presented_ = 0;
462 std::uint64_t immediate_presents_ = 0; 585 std::uint64_t immediate_presents_ = 0;
586 std::uint64_t presents_recorded_ = 0;
587 bool has_last_present_ = false;
588 std::uint64_t last_present_us_ = 0;
589 std::array<std::uint64_t, frame_pacing_window> interval_ring_{};
590 std::size_t interval_head_ = 0;
591 std::size_t interval_count_ = 0;
592 std::array<std::uint64_t, frame_pacing_window> latency_ring_{};
593 std::size_t latency_head_ = 0;
594 std::size_t latency_count_ = 0;
463 std::deque<Pending> pending_; 595 std::deque<Pending> pending_;
464 std::deque<Record> records_; 596 std::deque<Record> records_;
465}; 597};
diff --git a/runtime/src/gfx10_descriptors.h b/runtime/src/gfx10_descriptors.h
index b225cddef..a4a9b4448 100644
--- a/runtime/src/gfx10_descriptors.h
+++ b/runtime/src/gfx10_descriptors.h
@@ -631,8 +631,9 @@ inline VkSamplerCreateInfo vulkan_sampler(const Sampler& sampler, float max_lod_
631 if (sampler.unnormalized) { 631 if (sampler.unnormalized) {
632 info.unnormalizedCoordinates = VK_TRUE; 632 info.unnormalizedCoordinates = VK_TRUE;
633 // VUID-VkSamplerCreateInfo-unnormalizedCoordinates-01075: U and V clamp to the edge or the border (a 633 // VUID-VkSamplerCreateInfo-unnormalizedCoordinates-01075: U and V clamp to the edge or the border (a
634 // repeating mode would wrap at a texel count the sampler cannot know); -01072: one filter for min and mag. 634 // repeating mode would wrap at a texel count the sampler cannot know); -01072: one filter for min and mag;
635 // The S# allows any address mode with FORCE_UNNORMALIZED, and WRAP is its default (word 0 = 0). 635 // -01074: mipLodBias must be zero. The S# allows any address mode or LOD bias with FORCE_UNNORMALIZED, and
636 // WRAP is its default (word 0 = 0).
636 const auto clamp_or_border = [](VkSamplerAddressMode m) { 637 const auto clamp_or_border = [](VkSamplerAddressMode m) {
637 return m == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ? m : VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; 638 return m == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ? m : VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
638 }; 639 };
@@ -640,6 +641,7 @@ inline VkSamplerCreateInfo vulkan_sampler(const Sampler& sampler, float max_lod_
640 info.addressModeV = clamp_or_border(info.addressModeV); 641 info.addressModeV = clamp_or_border(info.addressModeV);
641 info.minFilter = info.magFilter; 642 info.minFilter = info.magFilter;
642 info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST; 643 info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST;
644 info.mipLodBias = 0.0f;
643 info.minLod = info.maxLod = 0.0f; 645 info.minLod = info.maxLod = 0.0f;
644 info.anisotropyEnable = VK_FALSE; 646 info.anisotropyEnable = VK_FALSE;
645 info.maxAnisotropy = 1.0f; 647 info.maxAnisotropy = 1.0f;
diff --git a/runtime/src/mods.h b/runtime/src/mods.h
index 10155bf19..bd635e9a0 100644
--- a/runtime/src/mods.h
+++ b/runtime/src/mods.h
@@ -78,8 +78,8 @@ struct LoadResult {
78// "0x..." -> that value; anything else -> joaat(name). Returns false for an empty name or a malformed hex value. 78// "0x..." -> that value; anything else -> joaat(name). Returns false for an empty name or a malformed hex value.
79inline bool parse_model_id(const std::string& text, uint32_t& out) { 79inline bool parse_model_id(const std::string& text, uint32_t& out) {
80 if (text.empty()) return false; 80 if (text.empty()) return false;
81 if (text.size() > 2 && text[0] == '0' && (text[1] == 'x' || text[1] == 'X')) { 81 if (text.size() >= 2 && text[0] == '0' && (text[1] == 'x' || text[1] == 'X')) {
82 if (text.size() > 10) return false; 82 if (text.size() == 2 || text.size() > 10) return false;
83 uint32_t v = 0; 83 uint32_t v = 0;
84 for (std::size_t i = 2; i < text.size(); ++i) { 84 for (std::size_t i = 2; i < text.size(); ++i) {
85 const char c = text[i]; 85 const char c = text[i];
diff --git a/runtime/src/retire_tickets.h b/runtime/src/retire_tickets.h
index a48302859..675460cac 100644
--- a/runtime/src/retire_tickets.h
+++ b/runtime/src/retire_tickets.h
@@ -24,7 +24,7 @@ public:
24 while (!pending_.empty()) { 24 while (!pending_.empty()) {
25 const Entry& front = pending_.front(); 25 const Entry& front = pending_.front();
26 if (!front.idle && !query(front.semaphore, front.value)) break; 26 if (!front.idle && !query(front.semaphore, front.value)) break;
27 completed_ = front.ticket; 27 if (front.ticket > completed_) completed_ = front.ticket;
28 pending_.pop_front(); 28 pending_.pop_front();
29 } 29 }
30 return completed_; 30 return completed_;
@@ -34,8 +34,18 @@ public:
34 // that must have them done (and may not hold the lock that guards this object while it waits) waits for. 34 // that must have them done (and may not hold the lock that guards this object while it waits) waits for.
35 std::vector<std::pair<Semaphore, std::uint64_t>> pending_through(std::uint64_t ticket) const { 35 std::vector<std::pair<Semaphore, std::uint64_t>> pending_through(std::uint64_t ticket) const {
36 std::vector<std::pair<Semaphore, std::uint64_t>> out; 36 std::vector<std::pair<Semaphore, std::uint64_t>> out;
37 for (const Entry& entry : pending_) 37 for (const Entry& entry : pending_) {
38 if (entry.ticket <= ticket && !entry.idle) out.emplace_back(entry.semaphore, entry.value); 38 if (entry.ticket > ticket || entry.idle) continue;
39 bool merged = false;
40 for (auto& [sem, val] : out) {
41 if (sem == entry.semaphore) {
42 if (entry.value > val) val = entry.value;
43 merged = true;
44 break;
45 }
46 }
47 if (!merged) out.emplace_back(entry.semaphore, entry.value);
48 }
39 return out; 49 return out;
40 } 50 }
41 51
diff --git a/runtime/src/shader_library.h b/runtime/src/shader_library.h
index 9f752317e..596ad0ae9 100644
--- a/runtime/src/shader_library.h
+++ b/runtime/src/shader_library.h
@@ -246,7 +246,7 @@ inline ZlibError inflate_codes(BitReader& in, std::vector<std::uint8_t>& out, co
246 if (d < 0 || d >= 30) return ZlibError::data; 246 if (d < 0 || d >= 30) return ZlibError::data;
247 const std::size_t distance = std::size_t(distance_base[d]) + in.bits(distance_extra[d]); 247 const std::size_t distance = std::size_t(distance_base[d]) + in.bits(distance_extra[d]);
248 if (in.failed() || distance > out.size()) return ZlibError::data; 248 if (in.failed() || distance > out.size()) return ZlibError::data;
249 if (out.size() + length > limit) return ZlibError::limit; 249 if (out.size() > limit || length > limit - out.size()) return ZlibError::limit;
250 const std::size_t from = out.size() - distance; 250 const std::size_t from = out.size() - distance;
251 for (std::size_t i = 0; i < length; ++i) out.push_back(out[from + i]); 251 for (std::size_t i = 0; i < length; ++i) out.push_back(out[from + i]);
252 } 252 }
@@ -284,7 +284,7 @@ inline bool zlib_inflate(std::span<const std::uint8_t> in, std::vector<std::uint
284 if (!reader.byte(x)) return fail(ZlibError::data); 284 if (!reader.byte(x)) return fail(ZlibError::data);
285 const unsigned length = b[0] | (b[1] << 8), complement = b[2] | (b[3] << 8); 285 const unsigned length = b[0] | (b[1] << 8), complement = b[2] | (b[3] << 8);
286 if (length != (~complement & 0xffff)) return fail(ZlibError::data); 286 if (length != (~complement & 0xffff)) return fail(ZlibError::data);
287 if (out.size() + length > limit) return fail(ZlibError::limit); 287 if (out.size() > limit || length > limit - out.size()) return fail(ZlibError::limit);
288 for (unsigned i = 0; i < length; ++i) { 288 for (unsigned i = 0; i < length; ++i) {
289 std::uint8_t x; 289 std::uint8_t x;
290 if (!reader.byte(x)) return fail(ZlibError::data); 290 if (!reader.byte(x)) return fail(ZlibError::data);
@@ -349,7 +349,7 @@ inline bool zlib_inflate(std::span<const std::uint8_t> in, std::vector<std::uint
349 } 349 }
350 // Adler-32, big-endian, after the deflate data's last whole byte. 350 // Adler-32, big-endian, after the deflate data's last whole byte.
351 const std::size_t at = 2 + reader.position(); 351 const std::size_t at = 2 + reader.position();
352 if (at + 4 > in.size()) return fail(ZlibError::data); 352 if (at > in.size() || in.size() - at < 4) return fail(ZlibError::data);
353 std::uint32_t a = 1, b = 0; 353 std::uint32_t a = 1, b = 0;
354 for (const std::uint8_t x : out) { 354 for (const std::uint8_t x : out) {
355 a = (a + x) % 65521; 355 a = (a + x) % 65521;
@@ -1045,9 +1045,20 @@ private:
1045 if (const Json* fh = meta.find("f16_halves"); fh && fh->kind == Json::Kind::object) { 1045 if (const Json* fh = meta.find("f16_halves"); fh && fh->kind == Json::Kind::object) {
1046 for (const auto& [key, val] : fh->object) { 1046 for (const auto& [key, val] : fh->object) {
1047 if (key.empty() || val.kind != Json::Kind::array || val.array.size() != 2) continue; 1047 if (key.empty() || val.kind != Json::Kind::array || val.array.size() != 2) continue;
1048 char* end = nullptr; 1048 std::uint64_t param = 0;
1049 const unsigned long param = std::strtoul(key.c_str(), &end, 10); 1049 bool ok = true;
1050 if (!end || *end != '\0') continue; 1050 for (const char c : key) {
1051 if (c < '0' || c > '9') {
1052 ok = false;
1053 break;
1054 }
1055 param = param * 10u + std::uint64_t(c - '0');
1056 if (param > UINT32_MAX) {
1057 ok = false;
1058 break;
1059 }
1060 }
1061 if (!ok) continue;
1051 e.f16_halves[std::uint32_t(param)] = {u32(&val.array[0]), u32(&val.array[1])}; 1062 e.f16_halves[std::uint32_t(param)] = {u32(&val.array[0]), u32(&val.array[1])};
1052 } 1063 }
1053 } 1064 }
diff --git a/runtime/src/statistics_sum.comp b/runtime/src/statistics_sum.comp
index c4960347c..c4a02a459 100644
--- a/runtime/src/statistics_sum.comp
+++ b/runtime/src/statistics_sum.comp
@@ -2,9 +2,11 @@
2 2
3// Adds the D3D12_QUERY_DATA_PIPELINE_STATISTICS segments of one split pipeline-statistics query (D3D-162): one 3// Adds the D3D12_QUERY_DATA_PIPELINE_STATISTICS segments of one split pipeline-statistics query (D3D-162): one
4// invocation per counter, in the order of VkQueryPipelineStatisticFlagBits, which is the D3D12 field order. 4// invocation per counter, in the order of VkQueryPipelineStatisticFlagBits, which is the D3D12 field order.
5// `mesh` segments come from the pool a mesh draw can run in (D3D-291), which counts only clipping, fragment and 5// `mesh` segments come from the pool a mesh draw can run in (D3D-291), which counts only the fragment and compute
6// compute: they are copied to counters 5..8 of their record, so CSInvocations sits at 8 and the input-assembly, 6// invocations: they are copied to counters 7 and 8 of their record, so PSInvocations takes the fragment one and
7// vertex, geometry and tessellation counters (0..4, 8 and 9 of the D3D12 order) add nothing. 7// CSInvocations the compute one, and every other counter adds nothing.
8// The clipping invocations of a mesh segment come from the mesh-primitives count of that segment, copied to
9// counter 5 (D3D-MESH-CLIPPING-COUNTER); without that count the field stays 0.
8layout(local_size_x = 11) in; 10layout(local_size_x = 11) in;
9layout(set = 0, binding = 0, std430) buffer QueryResults { 11layout(set = 0, binding = 0, std430) buffer QueryResults {
10 uvec2 total[11]; 12 uvec2 total[11];
@@ -15,7 +17,7 @@ layout(push_constant) uniform ResolveRange { uint count; uint mesh; };
15void main() { 17void main() {
16 const uint counter = gl_LocalInvocationID.x; 18 const uint counter = gl_LocalInvocationID.x;
17 uvec2 sum = total[counter]; 19 uvec2 sum = total[counter];
18 const bool counted = mesh == 0u || (counter >= 5u && counter <= 7u) || counter == 10u; 20 const bool counted = mesh == 0u || counter == 5u || counter == 7u || counter == 10u;
19 const uint source = mesh != 0u && counter == 10u ? 8u : counter; 21 const uint source = mesh != 0u && counter == 10u ? 8u : counter;
20 for (uint i = 0; counted && i < count; ++i) { 22 for (uint i = 0; counted && i < count; ++i) {
21 uvec2 segment = segments[i * 11 + source]; 23 uvec2 segment = segments[i * 11 + source];
diff --git a/runtime/src/statistics_sum_spirv.h b/runtime/src/statistics_sum_spirv.h
index 9c67f0429..a147cd4df 100644
--- a/runtime/src/statistics_sum_spirv.h
+++ b/runtime/src/statistics_sum_spirv.h
@@ -7,7 +7,7 @@ namespace leonida {
7// From statistics_sum.comp. Compile with glslangValidator -V --target-env vulkan1.0 -Os -g0, 7// From statistics_sum.comp. Compile with glslangValidator -V --target-env vulkan1.0 -Os -g0,
8// then encode the little-endian SPIR-V as uint32_t words. No shader compiler is needed at runtime build time. 8// then encode the little-endian SPIR-V as uint32_t words. No shader compiler is needed at runtime build time.
9inline constexpr std::uint32_t statistics_sum_spirv[] = { 9inline constexpr std::uint32_t statistics_sum_spirv[] = {
10 0x07230203, 0x00010000, 0x0008000b, 0x00000080, 0x00000000, 0x00020011, 0x00000001, 0x0006000b, 10 0x07230203, 0x00010000, 0x0008000b, 0x00000084, 0x00000000, 0x00020011, 0x00000001, 0x0006000b,
11 0x00000001, 0x4c534c47, 0x6474732e, 0x3035342e, 0x00000000, 0x0003000e, 0x00000000, 0x00000001, 11 0x00000001, 0x4c534c47, 0x6474732e, 0x3035342e, 0x00000000, 0x0003000e, 0x00000000, 0x00000001,
12 0x0006000f, 0x00000005, 0x00000004, 0x6e69616d, 0x00000000, 0x0000000b, 0x00060010, 0x00000004, 12 0x0006000f, 0x00000005, 0x00000004, 0x6e69616d, 0x00000000, 0x0000000b, 0x00060010, 0x00000004,
13 0x00000011, 0x0000000b, 0x00000001, 0x00000001, 0x00040047, 0x0000000b, 0x0000000b, 0x0000001b, 13 0x00000011, 0x0000000b, 0x00000001, 0x00000001, 0x00040047, 0x0000000b, 0x0000000b, 0x0000001b,
@@ -16,7 +16,7 @@ inline constexpr std::uint32_t statistics_sum_spirv[] = {
16 0x00050048, 0x00000016, 0x00000001, 0x00000023, 0x00000058, 0x00040047, 0x00000018, 0x00000021, 16 0x00050048, 0x00000016, 0x00000001, 0x00000023, 0x00000058, 0x00040047, 0x00000018, 0x00000021,
17 0x00000000, 0x00040047, 0x00000018, 0x00000022, 0x00000000, 0x00030047, 0x00000022, 0x00000002, 17 0x00000000, 0x00040047, 0x00000018, 0x00000022, 0x00000000, 0x00030047, 0x00000022, 0x00000002,
18 0x00050048, 0x00000022, 0x00000000, 0x00000023, 0x00000000, 0x00050048, 0x00000022, 0x00000001, 18 0x00050048, 0x00000022, 0x00000000, 0x00000023, 0x00000000, 0x00050048, 0x00000022, 0x00000001,
19 0x00000023, 0x00000004, 0x00040047, 0x00000072, 0x0000000b, 0x00000019, 0x00020013, 0x00000002, 19 0x00000023, 0x00000004, 0x00040047, 0x0000006f, 0x0000000b, 0x00000019, 0x00020013, 0x00000002,
20 0x00030021, 0x00000003, 0x00000002, 0x00040015, 0x00000006, 0x00000020, 0x00000000, 0x00040017, 20 0x00030021, 0x00000003, 0x00000002, 0x00040015, 0x00000006, 0x00000020, 0x00000000, 0x00040017,
21 0x00000009, 0x00000006, 0x00000003, 0x00040020, 0x0000000a, 0x00000001, 0x00000009, 0x0004003b, 21 0x00000009, 0x00000006, 0x00000003, 0x00040020, 0x0000000a, 0x00000001, 0x00000009, 0x0004003b,
22 0x0000000a, 0x0000000b, 0x00000001, 0x0004002b, 0x00000006, 0x0000000c, 0x00000000, 0x00040020, 22 0x0000000a, 0x0000000b, 0x00000001, 0x0004002b, 0x00000006, 0x0000000c, 0x00000000, 0x00040020,
@@ -28,42 +28,39 @@ inline constexpr std::uint32_t statistics_sum_spirv[] = {
28 0x00000002, 0x00000010, 0x00020014, 0x0000001f, 0x0004001e, 0x00000022, 0x00000006, 0x00000006, 28 0x00000002, 0x00000010, 0x00020014, 0x0000001f, 0x0004001e, 0x00000022, 0x00000006, 0x00000006,
29 0x00040020, 0x00000023, 0x00000009, 0x00000022, 0x0004003b, 0x00000023, 0x00000024, 0x00000009, 29 0x00040020, 0x00000023, 0x00000009, 0x00000022, 0x0004003b, 0x00000023, 0x00000024, 0x00000009,
30 0x0004002b, 0x00000019, 0x00000025, 0x00000001, 0x00040020, 0x00000026, 0x00000009, 0x00000006, 30 0x0004002b, 0x00000019, 0x00000025, 0x00000001, 0x00040020, 0x00000026, 0x00000009, 0x00000006,
31 0x0004002b, 0x00000006, 0x0000002e, 0x00000005, 0x0004002b, 0x00000006, 0x00000031, 0x00000007, 31 0x0004002b, 0x00000006, 0x0000002b, 0x00000005, 0x0004002b, 0x00000006, 0x0000002f, 0x00000007,
32 0x0004002b, 0x00000006, 0x00000036, 0x0000000a, 0x0004002b, 0x00000006, 0x00000040, 0x00000008, 32 0x0004002b, 0x00000006, 0x00000033, 0x0000000a, 0x0004002b, 0x00000006, 0x0000003d, 0x00000008,
33 0x0004002b, 0x00000006, 0x0000005e, 0x00000001, 0x0006002c, 0x00000009, 0x00000072, 0x00000013, 33 0x0004002b, 0x00000006, 0x0000005b, 0x00000001, 0x0006002c, 0x00000009, 0x0000006f, 0x00000013,
34 0x0000005e, 0x0000005e, 0x00050036, 0x00000002, 0x00000004, 0x00000000, 0x00000003, 0x000200f8, 34 0x0000005b, 0x0000005b, 0x00050036, 0x00000002, 0x00000004, 0x00000000, 0x00000003, 0x000200f8,
35 0x00000005, 0x00050041, 0x0000000d, 0x0000000e, 0x0000000b, 0x0000000c, 0x0004003d, 0x00000006, 35 0x00000005, 0x00050041, 0x0000000d, 0x0000000e, 0x0000000b, 0x0000000c, 0x0004003d, 0x00000006,
36 0x0000000f, 0x0000000e, 0x00060041, 0x0000001c, 0x0000001d, 0x00000018, 0x0000001a, 0x0000000f, 36 0x0000000f, 0x0000000e, 0x00060041, 0x0000001c, 0x0000001d, 0x00000018, 0x0000001a, 0x0000000f,
37 0x0004003d, 0x00000010, 0x0000001e, 0x0000001d, 0x00050041, 0x00000026, 0x00000027, 0x00000024, 37 0x0004003d, 0x00000010, 0x0000001e, 0x0000001d, 0x00050041, 0x00000026, 0x00000027, 0x00000024,
38 0x00000025, 0x0004003d, 0x00000006, 0x00000028, 0x00000027, 0x000500aa, 0x0000001f, 0x00000029, 38 0x00000025, 0x0004003d, 0x00000006, 0x00000028, 0x00000027, 0x000500aa, 0x0000001f, 0x00000029,
39 0x00000028, 0x0000000c, 0x000400a8, 0x0000001f, 0x0000002a, 0x00000029, 0x000300f7, 0x0000002c, 39 0x00000028, 0x0000000c, 0x000500aa, 0x0000001f, 0x0000002c, 0x0000000f, 0x0000002b, 0x000500a6,
40 0x00000000, 0x000400fa, 0x0000002a, 0x0000002b, 0x0000002c, 0x000200f8, 0x0000002b, 0x000500ae, 40 0x0000001f, 0x0000002d, 0x00000029, 0x0000002c, 0x000500aa, 0x0000001f, 0x00000030, 0x0000000f,
41 0x0000001f, 0x0000002f, 0x0000000f, 0x0000002e, 0x000500b2, 0x0000001f, 0x00000032, 0x0000000f, 41 0x0000002f, 0x000500a6, 0x0000001f, 0x00000031, 0x0000002d, 0x00000030, 0x000500aa, 0x0000001f,
42 0x00000031, 0x000500a7, 0x0000001f, 0x00000033, 0x0000002f, 0x00000032, 0x000200f9, 0x0000002c, 42 0x00000034, 0x0000000f, 0x00000033, 0x000500a6, 0x0000001f, 0x00000035, 0x00000031, 0x00000034,
43 0x000200f8, 0x0000002c, 0x000700f5, 0x0000001f, 0x00000034, 0x00000029, 0x00000005, 0x00000033, 43 0x000500ab, 0x0000001f, 0x00000039, 0x00000028, 0x0000000c, 0x000500a7, 0x0000001f, 0x0000003c,
44 0x0000002b, 0x000500aa, 0x0000001f, 0x00000037, 0x0000000f, 0x00000036, 0x000500a6, 0x0000001f, 44 0x00000039, 0x00000034, 0x000600a9, 0x00000006, 0x0000003f, 0x0000003c, 0x0000003d, 0x0000000f,
45 0x00000038, 0x00000034, 0x00000037, 0x000500ab, 0x0000001f, 0x0000003c, 0x00000028, 0x0000000c, 45 0x000200f9, 0x00000041, 0x000200f8, 0x00000041, 0x000700f5, 0x00000010, 0x00000082, 0x0000001e,
46 0x000500a7, 0x0000001f, 0x0000003f, 0x0000003c, 0x00000037, 0x000600a9, 0x00000006, 0x00000042, 46 0x00000005, 0x00000083, 0x00000042, 0x000700f5, 0x00000006, 0x00000071, 0x0000000c, 0x00000005,
47 0x0000003f, 0x00000040, 0x0000000f, 0x000200f9, 0x00000044, 0x000200f8, 0x00000044, 0x000700f5, 47 0x0000006b, 0x00000042, 0x000400f6, 0x00000043, 0x00000042, 0x00000000, 0x000200f9, 0x00000045,
48 0x00000010, 0x0000007f, 0x0000001e, 0x0000002c, 0x0000007c, 0x00000045, 0x000700f5, 0x00000006, 48 0x000200f8, 0x00000045, 0x000300f7, 0x00000048, 0x00000000, 0x000400fa, 0x00000035, 0x00000047,
49 0x0000007d, 0x0000000c, 0x0000002c, 0x0000006e, 0x00000045, 0x000400f6, 0x00000046, 0x00000045, 49 0x00000048, 0x000200f8, 0x00000047, 0x00050041, 0x00000026, 0x0000004a, 0x00000024, 0x0000001a,
50 0x00000000, 0x000200f9, 0x00000048, 0x000200f8, 0x00000048, 0x000300f7, 0x0000004b, 0x00000000, 50 0x0004003d, 0x00000006, 0x0000004b, 0x0000004a, 0x000500b0, 0x0000001f, 0x0000004c, 0x00000071,
51 0x000400fa, 0x00000038, 0x0000004a, 0x0000004b, 0x000200f8, 0x0000004a, 0x00050041, 0x00000026, 51 0x0000004b, 0x000200f9, 0x00000048, 0x000200f8, 0x00000048, 0x000700f5, 0x0000001f, 0x0000004d,
52 0x0000004d, 0x00000024, 0x0000001a, 0x0004003d, 0x00000006, 0x0000004e, 0x0000004d, 0x000500b0, 52 0x00000035, 0x00000045, 0x0000004c, 0x00000047, 0x000400fa, 0x0000004d, 0x00000042, 0x00000043,
53 0x0000001f, 0x0000004f, 0x0000007d, 0x0000004e, 0x000200f9, 0x0000004b, 0x000200f8, 0x0000004b, 53 0x000200f8, 0x00000042, 0x00050084, 0x00000006, 0x00000050, 0x00000071, 0x00000013, 0x00050080,
54 0x000700f5, 0x0000001f, 0x00000050, 0x00000038, 0x00000048, 0x0000004f, 0x0000004a, 0x000400fa, 54 0x00000006, 0x00000052, 0x00000050, 0x0000003f, 0x00060041, 0x0000001c, 0x00000053, 0x00000018,
55 0x00000050, 0x00000045, 0x00000046, 0x000200f8, 0x00000045, 0x00050084, 0x00000006, 0x00000053, 55 0x00000025, 0x00000052, 0x0004003d, 0x00000010, 0x00000054, 0x00000053, 0x00050051, 0x00000006,
56 0x0000007d, 0x00000013, 0x00050080, 0x00000006, 0x00000055, 0x00000053, 0x00000042, 0x00060041, 56 0x00000057, 0x00000082, 0x00000000, 0x00050051, 0x00000006, 0x00000059, 0x00000054, 0x00000000,
57 0x0000001c, 0x00000056, 0x00000018, 0x00000025, 0x00000055, 0x0004003d, 0x00000010, 0x00000057, 57 0x00050080, 0x00000006, 0x0000005a, 0x00000057, 0x00000059, 0x00050051, 0x00000006, 0x0000005d,
58 0x00000056, 0x00050051, 0x00000006, 0x0000005a, 0x0000007f, 0x00000000, 0x00050051, 0x00000006, 58 0x00000054, 0x00000001, 0x000500b0, 0x0000001f, 0x00000061, 0x0000005a, 0x00000057, 0x000600a9,
59 0x0000005c, 0x00000057, 0x00000000, 0x00050080, 0x00000006, 0x0000005d, 0x0000005a, 0x0000005c, 59 0x00000006, 0x00000062, 0x00000061, 0x0000005b, 0x0000000c, 0x00050080, 0x00000006, 0x00000063,
60 0x00050051, 0x00000006, 0x00000060, 0x00000057, 0x00000001, 0x000500b0, 0x0000001f, 0x00000064, 60 0x0000005d, 0x00000062, 0x00050051, 0x00000006, 0x00000065, 0x00000082, 0x00000001, 0x00050080,
61 0x0000005d, 0x0000005a, 0x000600a9, 0x00000006, 0x00000065, 0x00000064, 0x0000005e, 0x0000000c, 61 0x00000006, 0x00000066, 0x00000065, 0x00000063, 0x00050050, 0x00000010, 0x00000083, 0x0000005a,
62 0x00050080, 0x00000006, 0x00000066, 0x00000060, 0x00000065, 0x00050051, 0x00000006, 0x00000068, 62 0x00000066, 0x00050080, 0x00000006, 0x0000006b, 0x00000071, 0x00000025, 0x000200f9, 0x00000041,
63 0x0000007f, 0x00000001, 0x00050080, 0x00000006, 0x00000069, 0x00000068, 0x00000066, 0x00050050, 63 0x000200f8, 0x00000043, 0x0003003e, 0x0000001d, 0x00000082, 0x000100fd, 0x00010038,
64 0x00000010, 0x0000007c, 0x0000005d, 0x00000069, 0x00050080, 0x00000006, 0x0000006e, 0x0000007d,
65 0x00000025, 0x000200f9, 0x00000044, 0x000200f8, 0x00000046, 0x0003003e, 0x0000001d, 0x0000007f,
66 0x000100fd, 0x00010038,
67}; 64};
68 65
69} // namespace leonida 66} // namespace leonida
diff --git a/runtime/src/uav_clear.h b/runtime/src/uav_clear.h
index b73ec50e1..385d55950 100644
--- a/runtime/src/uav_clear.h
+++ b/runtime/src/uav_clear.h
@@ -91,6 +91,10 @@ inline constexpr Layout layouts[] = {
91 {VK_FORMAT_R16_UNORM, Kind::unorm, 2, {{{0, 16}, {}, {}, {}}}}, 91 {VK_FORMAT_R16_UNORM, Kind::unorm, 2, {{{0, 16}, {}, {}, {}}}},
92 // A4B4G4R4_UNORM: typed UAVs are the driver's call (WARP has them, AMD's D3D12 driver doesn't). 92 // A4B4G4R4_UNORM: typed UAVs are the driver's call (WARP has them, AMD's D3D12 driver doesn't).
93 {VK_FORMAT_R4G4B4A4_UNORM_PACK16, Kind::unorm, 2, {{{12, 4}, {8, 4}, {4, 4}, {0, 4}}}}, 93 {VK_FORMAT_R4G4B4A4_UNORM_PACK16, Kind::unorm, 2, {{{12, 4}, {8, 4}, {4, 4}, {0, 4}}}},
94 // B5G6R5, B5G5R5A1 and B4G4R4A4_UNORM, likewise (WARP has all three).
95 {VK_FORMAT_R5G6B5_UNORM_PACK16, Kind::unorm, 2, {{{11, 5}, {5, 6}, {0, 5}, {}}}},
96 {VK_FORMAT_A1R5G5B5_UNORM_PACK16, Kind::unorm, 2, {{{10, 5}, {5, 5}, {0, 5}, {15, 1}}}},
97 {VK_FORMAT_A4R4G4B4_UNORM_PACK16, Kind::unorm, 2, {{{8, 4}, {4, 4}, {0, 4}, {12, 4}}}},
94 {VK_FORMAT_R16_SNORM, Kind::snorm, 2, {{{0, 16}, {}, {}, {}}}}, 98 {VK_FORMAT_R16_SNORM, Kind::snorm, 2, {{{0, 16}, {}, {}, {}}}},
95 {VK_FORMAT_R16_UINT, Kind::uint, 2, {{{0, 16}, {}, {}, {}}}}, 99 {VK_FORMAT_R16_UINT, Kind::uint, 2, {{{0, 16}, {}, {}, {}}}},
96 {VK_FORMAT_R16_SINT, Kind::sint, 2, {{{0, 16}, {}, {}, {}}}}, 100 {VK_FORMAT_R16_SINT, Kind::sint, 2, {{{0, 16}, {}, {}, {}}}},
diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h
index e3e4defe8..ab6786a51 100644
--- a/runtime/src/vulkan_backend.h
+++ b/runtime/src/vulkan_backend.h
@@ -101,6 +101,7 @@ struct VulkanDeviceFunctions {
101 X(vkCreateComputePipelines) X(vkDestroyPipeline) X(vkCmdBindPipeline) X(vkCmdBindDescriptorSets) \ 101 X(vkCreateComputePipelines) X(vkDestroyPipeline) X(vkCmdBindPipeline) X(vkCmdBindDescriptorSets) \
102 X(vkCmdPushConstants) X(vkCmdDispatch) \ 102 X(vkCmdPushConstants) X(vkCmdDispatch) \
103 X(vkCmdBindVertexBuffers2) X(vkCmdBindIndexBuffer) X(vkCmdSetViewport) X(vkCmdSetScissor) \ 103 X(vkCmdBindVertexBuffers2) X(vkCmdBindIndexBuffer) X(vkCmdSetViewport) X(vkCmdSetScissor) \
104 X(vkCmdSetViewportWithCount) X(vkCmdSetScissorWithCount) \
104 X(vkCmdSetPrimitiveTopology) X(vkCmdSetPrimitiveRestartEnable) X(vkCmdSetStencilReference) \ 105 X(vkCmdSetPrimitiveTopology) X(vkCmdSetPrimitiveRestartEnable) X(vkCmdSetStencilReference) \
105 X(vkCmdSetBlendConstants) X(vkCmdDraw) \ 106 X(vkCmdSetBlendConstants) X(vkCmdDraw) \
106 X(vkCmdDrawIndexed) X(vkCreateGraphicsPipelines) X(vkQueueBindSparse) X(vkGetImageSparseMemoryRequirements) \ 107 X(vkCmdDrawIndexed) X(vkCreateGraphicsPipelines) X(vkQueueBindSparse) X(vkGetImageSparseMemoryRequirements) \
@@ -244,12 +245,16 @@ public:
244 245
245 // Adds `count` pipeline-statistics results into one D3D12_QUERY_DATA_PIPELINE_STATISTICS at dst + offset: the 246 // Adds `count` pipeline-statistics results into one D3D12_QUERY_DATA_PIPELINE_STATISTICS at dst + offset: the
246 // segments of a statistics query that was split around helper dispatches (D3D-162) or mesh draws (D3D-291). 247 // segments of a statistics query that was split around helper dispatches (D3D-162) or mesh draws (D3D-291).
247 // Segment i is in `mesh_queries` when mesh[i] is set (four counters: clipping, fragment and compute; see 248 // Segment i is in `mesh_queries` when mesh[i] is set (two counters: fragment and compute; see
248 // statistics_sum.comp), otherwise in `queries` (all eleven). 249 // statistics_sum.comp), otherwise in `queries` (all eleven). A mesh segment's clipping invocations come from
249 void sum_statistics(VkCommandBuffer cb, VkQueryPool queries, VkQueryPool mesh_queries, const std::uint8_t* mesh, 250 // `primitives_queries`, the mesh-primitives count of that segment (D3D-MESH-CLIPPING-COUNTER); it is null when
250 std::uint32_t first, std::uint32_t count, VkBuffer dst, VkDeviceSize offset) const { 251 // the device has no meshShaderQueries, and the field then reads 0.
252 void sum_statistics(VkCommandBuffer cb, VkQueryPool queries, VkQueryPool mesh_queries,
253 VkQueryPool primitives_queries, const std::uint8_t* mesh, std::uint32_t first,
254 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) const {
251 constexpr VkDeviceSize result = statistics_counters * word_size; 255 constexpr VkDeviceSize result = statistics_counters * word_size;
252 constexpr VkDeviceSize mesh_slot = 5 * word_size; // CInvocations, where the mesh pool's first counter goes 256 constexpr VkDeviceSize mesh_slot = 7 * word_size; // PSInvocations, where the mesh pool's first counter goes
257 constexpr VkDeviceSize clipping_slot = 5 * word_size; // CInvocations, where the mesh-primitives count goes
253 begin_scratch_write(cb); 258 begin_scratch_write(cb);
254 vk_.vkCmdFillBuffer(cb, scratch_, 0, result, 0); 259 vk_.vkCmdFillBuffer(cb, scratch_, 0, result, 0);
255 bind(cb, statistics_pipeline_); 260 bind(cb, statistics_pipeline_);
@@ -258,9 +263,18 @@ public:
258 std::uint32_t chunk = 1; 263 std::uint32_t chunk = 1;
259 while (chunk < std::min(count, statistics_capacity) && bool(mesh && mesh[first + chunk]) == in_mesh) 264 while (chunk < std::min(count, statistics_capacity) && bool(mesh && mesh[first + chunk]) == in_mesh)
260 ++chunk; 265 ++chunk;
266 if (in_mesh) {
267 // The mesh pool holds only the fragment and compute counters, so the clipping field of a mesh
268 // segment reads 0 unless the mesh-primitives count fills it (D3D-MESH-CLIPPING-COUNTER).
269 vk_.vkCmdFillBuffer(cb, scratch_, result, chunk * result, 0);
270 barrier(cb, transfer, transfer, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT);
271 }
261 vk_.vkCmdCopyQueryPoolResults(cb, in_mesh ? mesh_queries : queries, first, chunk, scratch_, 272 vk_.vkCmdCopyQueryPoolResults(cb, in_mesh ? mesh_queries : queries, first, chunk, scratch_,
262 result + (in_mesh ? mesh_slot : 0), result, 273 result + (in_mesh ? mesh_slot : 0), result,
263 VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT); 274 VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT);
275 if (in_mesh && primitives_queries)
276 vk_.vkCmdCopyQueryPoolResults(cb, primitives_queries, first, chunk, scratch_, result + clipping_slot,
277 result, VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT);
264 barrier(cb, transfer | compute, compute, VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_SHADER_WRITE_BIT, 278 barrier(cb, transfer | compute, compute, VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_SHADER_WRITE_BIT,
265 shader_access); 279 shader_access);
266 dispatch(cb, chunk, 1, in_mesh); 280 dispatch(cb, chunk, 1, in_mesh);
@@ -923,6 +937,10 @@ struct TileRange {
923#endif 937#endif
924class VulkanContext { 938class VulkanContext {
925public: 939public:
940 // mesh_queries: VK_EXT_mesh_shader's meshShaderQueries feature is enabled on `device`, so a mesh segment's
941 // clipping invocations can come from a mesh-primitives query (D3D-MESH-CLIPPING-COUNTER). Set by the device
942 // that created the context.
943 bool mesh_queries = false;
926 // conditional_rendering: VK_EXT_conditional_rendering is enabled on `device` (SetPredication). 944 // conditional_rendering: VK_EXT_conditional_rendering is enabled on `device` (SetPredication).
927 // ray_tracing: VK_KHR_acceleration_structure + VK_KHR_ray_query are enabled on `device`. 945 // ray_tracing: VK_KHR_acceleration_structure + VK_KHR_ray_query are enabled on `device`.
928 // xdxr: acceleration-structure builds write XDXR BVH4 records (xdxr_build.h) instead; needs bufferDeviceAddress. 946 // xdxr: acceleration-structure builds write XDXR BVH4 records (xdxr_build.h) instead; needs bufferDeviceAddress.
@@ -970,6 +988,8 @@ public:
970 replay_.bind_index_buffer = vk.vkCmdBindIndexBuffer; 988 replay_.bind_index_buffer = vk.vkCmdBindIndexBuffer;
971 replay_.set_viewport = vk.vkCmdSetViewport; 989 replay_.set_viewport = vk.vkCmdSetViewport;
972 replay_.set_scissor = vk.vkCmdSetScissor; 990 replay_.set_scissor = vk.vkCmdSetScissor;
991 replay_.set_viewport_with_count = vk.vkCmdSetViewportWithCount;
992 replay_.set_scissor_with_count = vk.vkCmdSetScissorWithCount;
973 replay_.set_primitive_topology = vk.vkCmdSetPrimitiveTopology; 993 replay_.set_primitive_topology = vk.vkCmdSetPrimitiveTopology;
974 replay_.set_primitive_restart_enable = vk.vkCmdSetPrimitiveRestartEnable; 994 replay_.set_primitive_restart_enable = vk.vkCmdSetPrimitiveRestartEnable;
975 replay_.set_stencil_reference = vk.vkCmdSetStencilReference; 995 replay_.set_stencil_reference = vk.vkCmdSetStencilReference;
@@ -1000,7 +1020,7 @@ public:
1000 // binding's host pointer is null on DEFAULT and READBACK heaps, whose mapped bytes the GPU can write. 1020 // binding's host pointer is null on DEFAULT and READBACK heaps, whose mapped bytes the GPU can write.
1001 replay_.host_at = [this](std::uint64_t va, std::uint64_t bytes, const std::uint8_t*& host) { 1021 replay_.host_at = [this](std::uint64_t va, std::uint64_t bytes, const std::uint8_t*& host) {
1002 BufferVaIndex<ResourceId>::Hit hit{}; 1022 BufferVaIndex<ResourceId>::Hit hit{};
1003 if (!buffer_vas_.find(va, hit)) return HostReadStatus::absent; 1023 if (!buffer_vas_.find(va, hit, bytes)) return HostReadStatus::absent;
1004 const ResourceBinding* b = resolve(hit.id); 1024 const ResourceBinding* b = resolve(hit.id);
1005 if (!b) return HostReadStatus::absent; 1025 if (!b) return HostReadStatus::absent;
1006 if (!b->host) return HostReadStatus::not_cpu_written; 1026 if (!b->host) return HostReadStatus::not_cpu_written;
@@ -1268,6 +1288,11 @@ public:
1268 replay_.zero_size = size; 1288 replay_.zero_size = size;
1269 } 1289 }
1270 1290
1291 void set_depth_range_unrestricted(bool enabled) {
1292 std::unique_lock lock(resource_mutex_);
1293 replay_.depth_range_unrestricted = enabled;
1294 }
1295
1271 // Physical-device COLOR_ATTACHMENT format check for reinterpreted UAV clears. 1296 // Physical-device COLOR_ATTACHMENT format check for reinterpreted UAV clears.
1272 void set_color_attachment_format(std::function<bool(VkFormat)> check) { 1297 void set_color_attachment_format(std::function<bool(VkFormat)> check) {
1273 std::unique_lock lock(resource_mutex_); 1298 std::unique_lock lock(resource_mutex_);
@@ -1483,12 +1508,23 @@ public:
1483 void note_bindless_upload() { bindless_upload_pending_ = true; } 1508 void note_bindless_upload() { bindless_upload_pending_ = true; }
1484 1509
1485 std::uint64_t completed_retire_ticket() { 1510 std::uint64_t completed_retire_ticket() {
1486 std::lock_guard lock(submit_mutex_); 1511 bool lost = false;
1487 if (is_device_lost()) return 0; 1512 std::uint64_t ticket = 0;
1488 return retire_tickets_.completed([this](VkSemaphore semaphore, std::uint64_t value) { 1513 {
1489 std::uint64_t done = 0; 1514 std::lock_guard lock(submit_mutex_);
1490 return vk.vkGetSemaphoreCounterValue(device_, semaphore, &done) == VK_SUCCESS && done >= value; 1515 if (is_device_lost()) return 0;
1491 }); 1516 ticket = retire_tickets_.completed([this, &lost](VkSemaphore semaphore, std::uint64_t value) {
1517 std::uint64_t done = 0;
1518 const VkResult result = vk.vkGetSemaphoreCounterValue(device_, semaphore, &done);
1519 if (result == VK_ERROR_DEVICE_LOST) lost = true;
1520 return result == VK_SUCCESS && done >= value;
1521 });
1522 }
1523 // Outside submit_mutex_, as in submit(): notifying the fence dispatcher can run callbacks that submit.
1524 // A DEVICE_LOST seen here is the first Vulkan operation to discover it; it must not be mistaken for
1525 // "this ticket has not completed".
1526 if (lost) mark_device_lost();
1527 return lost ? 0 : ticket;
1492 } 1528 }
1493 1529
1494 void drain_deleted_resources(std::uint64_t current_ticket) { 1530 void drain_deleted_resources(std::uint64_t current_ticket) {
@@ -2394,9 +2430,11 @@ private:
2394 occlusion_resolve_->normalize(cb, pool, first, count, dst, offset); 2430 occlusion_resolve_->normalize(cb, pool, first, count, dst, offset);
2395 }; 2431 };
2396 replay.sum_statistics = [this](VkCommandBuffer cb, VkQueryPool pool, VkQueryPool mesh_pool, 2432 replay.sum_statistics = [this](VkCommandBuffer cb, VkQueryPool pool, VkQueryPool mesh_pool,
2397 const std::uint8_t* mesh, std::uint32_t first, std::uint32_t count, 2433 VkQueryPool primitives_pool, const std::uint8_t* mesh,
2398 VkBuffer dst, VkDeviceSize offset) { 2434 std::uint32_t first, std::uint32_t count, VkBuffer dst,
2399 occlusion_resolve_->sum_statistics(cb, pool, mesh_pool, mesh, first, count, dst, offset); 2435 VkDeviceSize offset) {
2436 occlusion_resolve_->sum_statistics(cb, pool, mesh_pool, primitives_pool, mesh, first, count, dst,
2437 offset);
2400 }; 2438 };
2401 replay.sum_binary_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first, 2439 replay.sum_binary_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first,
2402 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { 2440 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) {
@@ -2443,18 +2481,26 @@ private:
2443 if (std::find(statistics->mesh.begin(), statistics->mesh.end(), 1) == statistics->mesh.end()) { 2481 if (std::find(statistics->mesh.begin(), statistics->mesh.end(), 1) == statistics->mesh.end()) {
2444 statistics->mesh.clear(); 2482 statistics->mesh.clear();
2445 } else { 2483 } else {
2446 // The counters a mesh draw allows (VUID-vkCmdDrawMeshTasksEXT-pipelineStatistics-07076): clipping 2484 // The counters a mesh draw allows (VUID-vkCmdDrawMeshTasksEXT-pipelineStatistics-07076): the
2447 // invocations and primitives, fragment and compute invocations (D3D-291). 2485 // fragment and compute invocations, and no other (D3D-291).
2448 VkQueryPoolCreateInfo info{VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO}; 2486 VkQueryPoolCreateInfo info{VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO};
2449 info.queryType = VK_QUERY_TYPE_PIPELINE_STATISTICS; 2487 info.queryType = VK_QUERY_TYPE_PIPELINE_STATISTICS;
2450 info.queryCount = statistics_segments; 2488 info.queryCount = statistics_segments;
2451 info.pipelineStatistics = VK_QUERY_PIPELINE_STATISTIC_CLIPPING_INVOCATIONS_BIT | 2489 info.pipelineStatistics = kMeshStatisticsFlags;
2452 VK_QUERY_PIPELINE_STATISTIC_CLIPPING_PRIMITIVES_BIT |
2453 VK_QUERY_PIPELINE_STATISTIC_FRAGMENT_SHADER_INVOCATIONS_BIT |
2454 VK_QUERY_PIPELINE_STATISTIC_COMPUTE_SHADER_INVOCATIONS_BIT;
2455 if (context_.vk.vkCreateQueryPool(statistics->device, &info, nullptr, &statistics->mesh_pool) != 2490 if (context_.vk.vkCreateQueryPool(statistics->device, &info, nullptr, &statistics->mesh_pool) !=
2456 VK_SUCCESS) 2491 VK_SUCCESS)
2457 return ReplayResult::unsupported; 2492 return ReplayResult::unsupported;
2493 // The mesh-primitives count of a mesh segment (D3D-MESH-CLIPPING-COUNTER): a query of its own type,
2494 // which the pipeline-statistics pool cannot hold. The device needs the meshShaderQueries feature,
2495 // or the clipping field of a mesh segment stays 0.
2496 if (context_.mesh_queries) {
2497 VkQueryPoolCreateInfo primitives{VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO};
2498 primitives.queryType = VK_QUERY_TYPE_MESH_PRIMITIVES_GENERATED_EXT;
2499 primitives.queryCount = statistics_segments;
2500 if (context_.vk.vkCreateQueryPool(statistics->device, &primitives, nullptr,
2501 &statistics->primitives_pool) != VK_SUCCESS)
2502 return ReplayResult::unsupported;
2503 }
2458 } 2504 }
2459 } 2505 }
2460 // QueryReplay::plan() reads QueryPool::ended / occlusion and QueryReplay::commit() writes them after 2506 // QueryReplay::plan() reads QueryPool::ended / occlusion and QueryReplay::commit() writes them after
@@ -2515,6 +2561,18 @@ private:
2515 discard(); 2561 discard();
2516 return ReplayResult::unsupported; 2562 return ReplayResult::unsupported;
2517 } 2563 }
2564 // D3D12 ends every ExecuteCommandLists with all its work done and its writes visible to the next one on the
2565 // queue (implicit state decay relies on it), and a list may then touch the same memory without a barrier:
2566 // two submissions copying into one buffer, say. Vulkan orders submissions on a queue only by what their
2567 // barriers say, so this one starts with a full memory barrier against everything submitted before it
2568 // (synchronization validation: WRITE_AFTER_WRITE between vk_queue_test's back-to-back copies).
2569 if (context_.vk.vkCmdPipelineBarrier) { // a mocked context may leave it out
2570 VkMemoryBarrier full{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
2571 full.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT;
2572 full.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
2573 context_.vk.vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
2574 VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 1, &full, 0, nullptr, 0, nullptr);
2575 }
2518 if (!tracker_lock.owns_lock()) tracker_lock.lock(); 2576 if (!tracker_lock.owns_lock()) tracker_lock.lock();
2519 if (!transfer_only && context_.bindless_prepare_ && !context_.bindless_prepare_(command_buffer)) { 2577 if (!transfer_only && context_.bindless_prepare_ && !context_.bindless_prepare_(command_buffer)) {
2520 const bool ended = context_.vk.vkEndCommandBuffer(command_buffer) == VK_SUCCESS; 2578 const bool ended = context_.vk.vkEndCommandBuffer(command_buffer) == VK_SUCCESS;
diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h
index 889bb71f7..7dcc7e2c0 100644
--- a/runtime/src/vulkan_replay.h
+++ b/runtime/src/vulkan_replay.h
@@ -216,7 +216,10 @@ inline VkPipelineStageFlags2 vulkan_sync(std::uint32_t sync) {
216 VK_PIPELINE_STAGE_2_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_2_LATE_FRAGMENT_TESTS_BIT}, 216 VK_PIPELINE_STAGE_2_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_2_LATE_FRAGMENT_TESTS_BIT},
217 {y::render_target, VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT}, 217 {y::render_target, VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT},
218 {y::compute_shading, VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT}, 218 {y::compute_shading, VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT},
219 {y::copy, VK_PIPELINE_STAGE_2_COPY_BIT}, 219 // CLEAR as well: two D3D12 copy-scope commands are recorded as Vulkan clear commands, WriteBufferImmediate
220 // as vkCmdUpdateBuffer and ResolveQueryData's never-written queries as vkCmdFillBuffer, and synchronization2
221 // puts both in the CLEAR stage, not COPY.
222 {y::copy, VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_CLEAR_BIT},
220 {y::resolve, VK_PIPELINE_STAGE_2_RESOLVE_BIT}, 223 {y::resolve, VK_PIPELINE_STAGE_2_RESOLVE_BIT},
221 {y::execute_indirect, VK_PIPELINE_STAGE_2_DRAW_INDIRECT_BIT}, 224 {y::execute_indirect, VK_PIPELINE_STAGE_2_DRAW_INDIRECT_BIT},
222 {y::all_shading, pre_raster | VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT}, 225 {y::all_shading, pre_raster | VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT},
@@ -716,6 +719,9 @@ struct OcclusionSegmentPool {
716 // segment index whether it runs there. Empty when no segment of the submission holds a mesh draw. 719 // segment index whether it runs there. Empty when no segment of the submission holds a mesh draw.
717 VkQueryPool mesh_pool = VK_NULL_HANDLE; 720 VkQueryPool mesh_pool = VK_NULL_HANDLE;
718 std::vector<std::uint8_t> mesh; 721 std::vector<std::uint8_t> mesh;
722 // The mesh-primitives pool of the mesh segments (D3D-MESH-CLIPPING-COUNTER): one query per segment, begun and
723 // ended with the mesh segment. Null when the device has no meshShaderQueries.
724 VkQueryPool primitives_pool = VK_NULL_HANDLE;
719 725
720 OcclusionSegmentPool() = default; 726 OcclusionSegmentPool() = default;
721 OcclusionSegmentPool(const OcclusionSegmentPool&) = delete; 727 OcclusionSegmentPool(const OcclusionSegmentPool&) = delete;
@@ -723,6 +729,7 @@ struct OcclusionSegmentPool {
723 ~OcclusionSegmentPool() { 729 ~OcclusionSegmentPool() {
724 if (pool) destroy(device, pool, nullptr); 730 if (pool) destroy(device, pool, nullptr);
725 if (mesh_pool) destroy(device, mesh_pool, nullptr); 731 if (mesh_pool) destroy(device, mesh_pool, nullptr);
732 if (primitives_pool) destroy(device, primitives_pool, nullptr);
726 } 733 }
727}; 734};
728 735
@@ -769,6 +776,7 @@ struct GraphicsPipeline {
769 std::uint32_t zero_step_slots = 0; // per-instance slots with InstanceDataStepRate 0: stride 0 at draw time 776 std::uint32_t zero_step_slots = 0; // per-instance slots with InstanceDataStepRate 0: stride 0 at draw time
770 std::uint32_t strip_cut = 0; // D3D12_INDEX_BUFFER_STRIP_CUT_VALUE (0: off, 1: 0xFFFF, 2: 0xFFFFFFFF) 777 std::uint32_t strip_cut = 0; // D3D12_INDEX_BUFFER_STRIP_CUT_VALUE (0: off, 1: 0xFFFF, 2: 0xFFFFFFFF)
771 bool mesh = false; // a mesh shader instead of a vertex shader: drawn by DispatchMesh only 778 bool mesh = false; // a mesh shader instead of a vertex shader: drawn by DispatchMesh only
779 bool viewport_with_count = false; // pipeline uses VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT / SCISSOR_WITH_COUNT
772 // The same pipeline with some attachment formats VK_FORMAT_UNDEFINED, for a draw that leaves those slots 780 // The same pipeline with some attachment formats VK_FORMAT_UNDEFINED, for a draw that leaves those slots
773 // unbound (D3D12 allows it; dynamic rendering needs the formats to agree). Bit i: colour slot i, bit 8: depth 781 // unbound (D3D12 allows it; dynamic rendering needs the formats to agree). Bit i: colour slot i, bit 8: depth
774 // and stencil. Null when it cannot be built. 782 // and stencil. Null when it cannot be built.
@@ -810,6 +818,7 @@ struct ReplayFunctions {
810 PFN_vkCmdPipelineBarrier pipeline_barrier = nullptr; 818 PFN_vkCmdPipelineBarrier pipeline_barrier = nullptr;
811 PFN_vkCmdClearColorImage clear_color_image = nullptr; 819 PFN_vkCmdClearColorImage clear_color_image = nullptr;
812 PFN_vkCmdClearDepthStencilImage clear_depth_stencil_image = nullptr; 820 PFN_vkCmdClearDepthStencilImage clear_depth_stencil_image = nullptr;
821 bool depth_range_unrestricted = false; // Allows out-of-range float depth clear values.
813 // Optional; a list that needs a missing one is rejected with ReplayResult::unsupported. 822 // Optional; a list that needs a missing one is rejected with ReplayResult::unsupported.
814 PFN_vkCmdPipelineBarrier2 pipeline_barrier2 = nullptr; // enhanced barriers 823 PFN_vkCmdPipelineBarrier2 pipeline_barrier2 = nullptr; // enhanced barriers
815 VkPipelineStageFlags2 queue_stages = 0; 824 VkPipelineStageFlags2 queue_stages = 0;
@@ -850,6 +859,8 @@ struct ReplayFunctions {
850 PFN_vkCmdBindIndexBuffer bind_index_buffer = nullptr; 859 PFN_vkCmdBindIndexBuffer bind_index_buffer = nullptr;
851 PFN_vkCmdSetViewport set_viewport = nullptr; 860 PFN_vkCmdSetViewport set_viewport = nullptr;
852 PFN_vkCmdSetScissor set_scissor = nullptr; 861 PFN_vkCmdSetScissor set_scissor = nullptr;
862 PFN_vkCmdSetViewportWithCount set_viewport_with_count = nullptr;
863 PFN_vkCmdSetScissorWithCount set_scissor_with_count = nullptr;
853 PFN_vkCmdSetPrimitiveTopology set_primitive_topology = nullptr; 864 PFN_vkCmdSetPrimitiveTopology set_primitive_topology = nullptr;
854 PFN_vkCmdSetPrimitiveRestartEnable set_primitive_restart_enable = nullptr; 865 PFN_vkCmdSetPrimitiveRestartEnable set_primitive_restart_enable = nullptr;
855 PFN_vkCmdSetStencilReference set_stencil_reference = nullptr; 866 PFN_vkCmdSetStencilReference set_stencil_reference = nullptr;
@@ -875,9 +886,12 @@ struct ReplayFunctions {
875 VkBuffer dst, VkDeviceSize offset)> resolve_binary_occlusion; 886 VkBuffer dst, VkDeviceSize offset)> resolve_binary_occlusion;
876 // Adds `count` pipeline-statistics results into one D3D12_QUERY_DATA_PIPELINE_STATISTICS, outside conditional 887 // Adds `count` pipeline-statistics results into one D3D12_QUERY_DATA_PIPELINE_STATISTICS, outside conditional
877 // rendering: the segments of a statistics query split around resolves (D3D-162) and mesh draws (D3D-291). 888 // rendering: the segments of a statistics query split around resolves (D3D-162) and mesh draws (D3D-291).
878 // Segment i is in the second pool when mesh[i] is set (mesh may be null: none is). 889 // Segment i is in the second pool when mesh[i] is set (mesh may be null: none is). The third pool holds the
879 std::function<void(VkCommandBuffer, VkQueryPool, VkQueryPool mesh_pool, const std::uint8_t* mesh, 890 // mesh-primitives count of a mesh segment (D3D-MESH-CLIPPING-COUNTER); it is null when the device has no
880 std::uint32_t first, std::uint32_t count, VkBuffer dst, VkDeviceSize offset)> 891 // meshShaderQueries.
892 std::function<void(VkCommandBuffer, VkQueryPool, VkQueryPool mesh_pool, VkQueryPool primitives_pool,
893 const std::uint8_t* mesh, std::uint32_t first, std::uint32_t count, VkBuffer dst,
894 VkDeviceSize offset)>
881 sum_statistics; 895 sum_statistics;
882 // Sums `count` binary-occlusion segments and normalizes the total to a 64-bit 0 or 1, outside conditional 896 // Sums `count` binary-occlusion segments and normalizes the total to a 64-bit 0 or 1, outside conditional
883 // rendering: a binary query split over physical segments because it overlaps other occlusion queries (D3D-252). 897 // rendering: a binary query split over physical segments because it overlaps other occlusion queries (D3D-252).
@@ -958,6 +972,8 @@ struct QueryResolveRun {
958 bool sum = false; 972 bool sum = false;
959 // Statistics segments: the mesh-compatible pool and the kind of each segment (OcclusionSegmentPool::mesh). 973 // Statistics segments: the mesh-compatible pool and the kind of each segment (OcclusionSegmentPool::mesh).
960 VkQueryPool mesh_pool = VK_NULL_HANDLE; 974 VkQueryPool mesh_pool = VK_NULL_HANDLE;
975 // The mesh-primitives pool of the mesh segments (D3D-MESH-CLIPPING-COUNTER); null without meshShaderQueries.
976 VkQueryPool primitives_pool = VK_NULL_HANDLE;
961 const std::uint8_t* mesh = nullptr; 977 const std::uint8_t* mesh = nullptr;
962}; 978};
963 979
@@ -1598,6 +1614,7 @@ inline ReplayResult prepare_buffer_uav_clear(const ClearUnorderedAccess& clear,
1598 if (offset > UINT64_MAX - p.binding.buffer_offset || 1614 if (offset > UINT64_MAX - p.binding.buffer_offset ||
1599 bytes > UINT64_MAX - (p.binding.buffer_offset + offset)) return ReplayResult::invalid_clear; 1615 bytes > UINT64_MAX - (p.binding.buffer_offset + offset)) return ReplayResult::invalid_clear;
1600 offset += p.binding.buffer_offset; // the view is relative to the resource, which starts at buffer_offset 1616 offset += p.binding.buffer_offset; // the view is relative to the resource, which starts at buffer_offset
1617 if (offset % std::min(e, 4u)) return ReplayResult::unsupported;
1601 if (e > 4 && bytes % 4) { 1618 if (e > 4 && bytes % 4) {
1602 return ReplayResult::unsupported; 1619 return ReplayResult::unsupported;
1603 } 1620 }
@@ -1869,27 +1886,48 @@ inline ReplayResult prepare_texture_copy(const CopyTexture& copy, Prepared& p) {
1869 return ReplayResult::success; 1886 return ReplayResult::success;
1870} 1887}
1871 1888
1872// RGBA8 CopyTiles accepts arbitrary byte offsets into its linear buffer, while VkBufferImageCopy requires texel 1889// CopyTiles accepts arbitrary byte offsets into its linear buffer, while VkBufferImageCopy requires texel/block
1873// alignment. Stage only the occupied texels through aligned transfer scratch; leave partial-tile padding alone. 1890// alignment (VUID-vkCmdCopyBufferToImage-dstImage-07975). Stage only the occupied texels/blocks through aligned
1874inline bool stage_unaligned_tile(const ReplayFunctions& vk, Prepared& p, bool upload) { 1891// transfer scratch; leave partial-tile padding alone.
1892inline bool stage_unaligned_tile(const ReplayFunctions& vk, Prepared& p, const ResourceBinding& image,
1893 const BlockFormat& fmt, bool upload) {
1875 auto& region = p.buffer_image_copies.front(); 1894 auto& region = p.buffer_image_copies.front();
1876 const VkDeviceSize row_bytes = VkDeviceSize(region.imageExtent.width) * 4; 1895 if (!fmt.bytes || !fmt.block || image.rgb96 ||
1877 const VkDeviceSize pitch = VkDeviceSize(region.bufferRowLength) * 4; 1896 (image.depth24_as_float && region.imageSubresource.aspectMask == VK_IMAGE_ASPECT_DEPTH_BIT))
1878 const auto rows = region.imageExtent.height; 1897 return false;
1898 const VkDeviceSize blocks_w = (VkDeviceSize(region.imageExtent.width) + fmt.block - 1) / fmt.block;
1899 const VkDeviceSize rows = (VkDeviceSize(region.imageExtent.height) + fmt.block - 1) / fmt.block;
1900 const VkDeviceSize depth = region.imageExtent.depth;
1901 const VkDeviceSize row_bytes = blocks_w * fmt.bytes;
1902 const VkDeviceSize pitch =
1903 region.bufferRowLength ? VkDeviceSize(region.bufferRowLength / fmt.block) * fmt.bytes : row_bytes;
1904 const VkDeviceSize slice_rows =
1905 region.bufferImageHeight ? VkDeviceSize(region.bufferImageHeight / fmt.block) : rows;
1906 const VkDeviceSize slice_pitch = slice_rows * pitch;
1907 const VkDeviceSize slice_bytes = row_bytes * rows;
1908 const VkDeviceSize total_bytes = slice_bytes * depth;
1879 VkDeviceSize scratch_offset = 0; 1909 VkDeviceSize scratch_offset = 0;
1880 if (!vk.copy_scratch || !vk.copy_scratch(row_bytes * rows, p.tile_scratch, scratch_offset)) return false; 1910 if (!total_bytes || !vk.copy_scratch || !vk.copy_scratch(total_bytes, p.tile_scratch, scratch_offset)) return false;
1881 const auto app_offset = region.bufferOffset; 1911 const auto app_offset = region.bufferOffset;
1882 const auto add_copy = [&](VkDeviceSize linear, VkDeviceSize scratch, VkDeviceSize bytes) { 1912 const auto add_copy = [&](VkDeviceSize linear, VkDeviceSize scratch, VkDeviceSize bytes) {
1883 p.tile_rows.push_back(upload ? VkBufferCopy{linear, scratch, bytes} : VkBufferCopy{scratch, linear, bytes}); 1913 p.tile_rows.push_back(upload ? VkBufferCopy{linear, scratch, bytes} : VkBufferCopy{scratch, linear, bytes});
1884 }; 1914 };
1885 if (row_bytes == pitch) { 1915 if (row_bytes == pitch && (depth == 1 || slice_rows == rows)) {
1886 add_copy(app_offset, scratch_offset, row_bytes * rows); 1916 add_copy(app_offset, scratch_offset, total_bytes);
1917 } else if (row_bytes == pitch) {
1918 for (VkDeviceSize z = 0; z < depth; ++z)
1919 add_copy(app_offset + z * slice_pitch, scratch_offset + z * slice_bytes, slice_bytes);
1887 } else { 1920 } else {
1888 for (std::uint32_t row = 0; row < rows; ++row) 1921 for (VkDeviceSize z = 0; z < depth; ++z) {
1889 add_copy(app_offset + row * pitch, scratch_offset + row * row_bytes, row_bytes); 1922 const VkDeviceSize linear_slice = app_offset + z * slice_pitch;
1923 const VkDeviceSize scratch_slice = scratch_offset + z * slice_bytes;
1924 for (VkDeviceSize row = 0; row < rows; ++row)
1925 add_copy(linear_slice + row * pitch, scratch_slice + row * row_bytes, row_bytes);
1926 }
1890 } 1927 }
1891 region.bufferOffset = scratch_offset; 1928 region.bufferOffset = scratch_offset;
1892 region.bufferRowLength = 0; 1929 region.bufferRowLength = 0;
1930 region.bufferImageHeight = 0;
1893 return true; 1931 return true;
1894} 1932}
1895 1933
@@ -2103,6 +2141,8 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct
2103 if (!pipeline || !pipeline->pipeline) return ReplayResult::unresolved_resource; 2141 if (!pipeline || !pipeline->pipeline) return ReplayResult::unresolved_resource;
2104 if (pipeline->mesh != draw.mesh) return ReplayResult::invalid_draw; 2142 if (pipeline->mesh != draw.mesh) return ReplayResult::invalid_draw;
2105 if (draw.mesh && !vk.draw_mesh_tasks) return ReplayResult::unsupported; 2143 if (draw.mesh && !vk.draw_mesh_tasks) return ReplayResult::unsupported;
2144 if (pipeline->viewport_with_count && (!vk.set_viewport_with_count || !vk.set_scissor_with_count))
2145 return ReplayResult::unsupported;
2106 if (pipeline->bindless_set && !vk.bind_descriptor_sets) return ReplayResult::unsupported; 2146 if (pipeline->bindless_set && !vk.bind_descriptor_sets) return ReplayResult::unsupported;
2107 if (pipeline->color_formats.size() > max_render_targets) return ReplayResult::unsupported; 2147 if (pipeline->color_formats.size() > max_render_targets) return ReplayResult::unsupported;
2108 p.graphics = pipeline; 2148 p.graphics = pipeline;
@@ -2151,9 +2191,17 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct
2151 if (!a.view) return ReplayResult::unsupported; 2191 if (!a.view) return ReplayResult::unsupported;
2152 shrink(a.binding, draw.depth, a.range); 2192 shrink(a.binding, draw.depth, a.range);
2153 } 2193 }
2154 if (p.area.width == UINT32_MAX) { // no attachment: the viewport bounds the rendering 2194 if (p.area.width == UINT32_MAX) { // no attachment: the viewports bound the rendering
2155 p.area = {std::uint32_t(std::max(0.0f, draw.viewport.x + draw.viewport.width)), 2195 std::uint32_t max_w = std::uint32_t(std::max(0.0f, draw.viewport.x + draw.viewport.width));
2156 std::uint32_t(std::max(0.0f, draw.viewport.y + draw.viewport.height))}; 2196 std::uint32_t max_h = std::uint32_t(std::max(0.0f, draw.viewport.y + draw.viewport.height));
2197 if (draw.viewports) {
2198 for (std::uint32_t i = 0; i < draw.viewports->viewport_count; ++i) {
2199 const Viewport& v = draw.viewports->viewports[i];
2200 max_w = std::max(max_w, std::uint32_t(std::max(0.0f, v.x + v.width)));
2201 max_h = std::max(max_h, std::uint32_t(std::max(0.0f, v.y + v.height)));
2202 }
2203 }
2204 p.area = {max_w, max_h};
2157 } 2205 }
2158 p.layers = layers == UINT32_MAX ? 1 : std::max(1u, layers); 2206 p.layers = layers == UINT32_MAX ? 1 : std::max(1u, layers);
2159 2207
@@ -2300,6 +2348,8 @@ public:
2300 // For each of those segments, whether it holds mesh draws and so runs in statistics_mesh_pool (D3D-291). 2348 // For each of those segments, whether it holds mesh draws and so runs in statistics_mesh_pool (D3D-291).
2301 std::vector<std::uint8_t> statistics_mesh; 2349 std::vector<std::uint8_t> statistics_mesh;
2302 VkQueryPool statistics_mesh_pool = VK_NULL_HANDLE; 2350 VkQueryPool statistics_mesh_pool = VK_NULL_HANDLE;
2351 // The mesh-primitives pool of the list's mesh segments (D3D-MESH-CLIPPING-COUNTER).
2352 VkQueryPool statistics_primitives_pool = VK_NULL_HANDLE;
2303 // Copies, resolves and UAV clears that run as transfers, recorded while a predicate was set. D3D12 skips them 2353 // Copies, resolves and UAV clears that run as transfers, recorded while a predicate was set. D3D12 skips them
2304 // when the predicate says so, but Vulkan's conditional rendering does not cover transfer commands, so they run 2354 // when the predicate says so, but Vulkan's conditional rendering does not cover transfer commands, so they run
2305 // unconditionally (docs/d3d12_vulkan.md section 4.7). Counted so the caller can report it. 2355 // unconditionally (docs/d3d12_vulkan.md section 4.7). Counted so the caller can report it.
@@ -2344,10 +2394,26 @@ inline ReplayResult plan_occlusion_segments(PreparedList& out) {
2344// Helper dispatches must not contribute to the application's CSInvocations (D3D-162). Query resolves and 2394// Helper dispatches must not contribute to the application's CSInvocations (D3D-162). Query resolves and
2345// ordinary helper commands share one sequence of physical statistics segments. Resolve dispatch requirements 2395// ordinary helper commands share one sequence of physical statistics segments. Resolve dispatch requirements
2346// depend on heap state at planning time, so every non-timestamp resolve splits conservatively. 2396// depend on heap state at planning time, so every non-timestamp resolve splits conservatively.
2347// A mesh draw cannot run while a query with the input-assembly, vertex, geometry or tessellation counters is active 2397// The counters a mesh draw may count: VUID-vkCmdDrawMeshTasksEXT-pipelineStatistics-07076 leaves the input
2348// (VUID-vkCmdDrawMeshTasksEXT-pipelineStatistics-07076), though D3D12 allows it and reads those fields as 0. A query 2398// assembly, vertex, geometry, tessellation and clipping bits out of the pipelineStatistics flags of every pool that
2349// that holds a mesh draw is split as well (D3D-291): a segment's first draw decides whether it runs in the full pool 2399// is active during a mesh draw, so a mesh segment runs in a pool with the fragment and compute counters only
2350// or in the mesh one (statistics_mesh), and a later draw of the other kind ends it and begins one of its own kind. 2400// (D3D-291). D3D12 counts the clipping invocations and primitives of a mesh pipeline, but Vulkan has no counter for
2401// them during a mesh draw, so those two fields read 0.
2402inline constexpr VkQueryPipelineStatisticFlags kMeshStatisticsFlags =
2403 VK_QUERY_PIPELINE_STATISTIC_FRAGMENT_SHADER_INVOCATIONS_BIT | VK_QUERY_PIPELINE_STATISTIC_COMPUTE_SHADER_INVOCATIONS_BIT;
2404// The bits the same VUID forbids in a pool that is active during a mesh draw.
2405inline constexpr VkQueryPipelineStatisticFlags kForbiddenMeshStatisticsFlags =
2406 VK_QUERY_PIPELINE_STATISTIC_INPUT_ASSEMBLY_VERTICES_BIT | VK_QUERY_PIPELINE_STATISTIC_INPUT_ASSEMBLY_PRIMITIVES_BIT |
2407 VK_QUERY_PIPELINE_STATISTIC_VERTEX_SHADER_INVOCATIONS_BIT | VK_QUERY_PIPELINE_STATISTIC_GEOMETRY_SHADER_INVOCATIONS_BIT |
2408 VK_QUERY_PIPELINE_STATISTIC_GEOMETRY_SHADER_PRIMITIVES_BIT | VK_QUERY_PIPELINE_STATISTIC_CLIPPING_INVOCATIONS_BIT |
2409 VK_QUERY_PIPELINE_STATISTIC_CLIPPING_PRIMITIVES_BIT |
2410 VK_QUERY_PIPELINE_STATISTIC_TESSELLATION_CONTROL_SHADER_PATCHES_BIT |
2411 VK_QUERY_PIPELINE_STATISTIC_TESSELLATION_EVALUATION_SHADER_INVOCATIONS_BIT;
2412// A mesh draw cannot run while a query with the input-assembly, vertex, geometry, tessellation or clipping counters
2413// is active (VUID-vkCmdDrawMeshTasksEXT-pipelineStatistics-07076), though D3D12 allows it and reads those fields as
2414// 0. A query that holds a mesh draw is split as well (D3D-291): a segment's first draw decides whether it runs in
2415// the full pool or in the mesh one (statistics_mesh), and a later draw of the other kind ends it and begins one of
2416// its own kind.
2351// Dispatches and segments without draws use the full pool; ExecuteIndirect draws count as vertex draws. Each draw 2417// Dispatches and segments without draws use the full pool; ExecuteIndirect draws count as vertex draws. Each draw
2352// has its own rendering scope, so a split before one stays outside rendering, as a helper's does. 2418// has its own rendering scope, so a split before one stays outside rendering, as a helper's does.
2353inline void plan_statistics_segments(PreparedList& out) { 2419inline void plan_statistics_segments(PreparedList& out) {
@@ -2785,9 +2851,15 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
2785 // A depth plane footprint of a D24 texture stored as D32: words of 24-bit UNORM, floats in the image. 2851 // A depth plane footprint of a D24 texture stored as D32: words of 24-bit UNORM, floats in the image.
2786 const bool upload = texture_copy->src.footprint; 2852 const bool upload = texture_copy->src.footprint;
2787 const ResourceBinding& image = upload ? p.binding : p.source; 2853 const ResourceBinding& image = upload ? p.binding : p.source;
2788 if (result == ReplayResult::success && texture_copy->tile_footprint && !p.buffer_image_copies.empty() && 2854 if (result == ReplayResult::success && texture_copy->tile_footprint && !p.buffer_image_copies.empty()) {
2789 p.buffer_image_copies.front().bufferOffset % 4 && !detail::stage_unaligned_tile(vk, p, upload)) 2855 const auto& region = p.buffer_image_copies.front();
2790 return ReplayResult::unsupported; 2856 const BlockFormat fmt = copy_block_format(image, region.imageSubresource.aspectMask);
2857 const std::uint32_t alignment =
2858 (region.imageSubresource.aspectMask & depth_stencil_aspects) || image.rgb96 ? 4 : fmt.bytes;
2859 if (alignment > 1 && region.bufferOffset % alignment &&
2860 !detail::stage_unaligned_tile(vk, p, image, fmt, upload))
2861 return ReplayResult::unsupported;
2862 }
2791 const bool depth24_footprint = result == ReplayResult::success && image.depth24_as_float && 2863 const bool depth24_footprint = result == ReplayResult::success && image.depth24_as_float &&
2792 !p.buffer_image_copies.empty() && 2864 !p.buffer_image_copies.empty() &&
2793 p.buffer_image_copies[0].imageSubresource.aspectMask == VK_IMAGE_ASPECT_DEPTH_BIT; 2865 p.buffer_image_copies[0].imageSubresource.aspectMask == VK_IMAGE_ASPECT_DEPTH_BIT;
@@ -3016,13 +3088,13 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
3016 const VkDeviceSize record_size = detail::indirect_record_size(ind->kind); 3088 const VkDeviceSize record_size = detail::indirect_record_size(ind->kind);
3017 if (!record_size || ind->stride < record_size || ind->stride % sizeof(std::uint32_t)) 3089 if (!record_size || ind->stride < record_size || ind->stride % sizeof(std::uint32_t))
3018 return ReplayResult::invalid_indirect_arguments; 3090 return ReplayResult::invalid_indirect_arguments;
3019 // The span is max_count * stride, the bytes the signature can walk, as D3D12 measures it: a record that 3091 // The range is the bytes the commands read, (max_count - 1) * stride + record_size: the rule recording
3020 // fits at the end of the buffer while its stride runs past it is refused (`240` with stride `20` in a 3092 // applies (d3d12_com.cpp, ExecuteIndirect) and the one vkCmdDraw*Indirect states. A zero max_count is a
3021 // `256`-byte buffer). A zero max_count still has to name an offset inside the buffer. 3093 // no-op that recording never passes on; if one arrives it reads nothing and needs no range.
3022 if (ind->argument_offset > p.binding.size || 3094 if (ind->max_count
3023 ind->max_count > (p.binding.size - ind->argument_offset) / ind->stride || 3095 ? !detail::indirect_range(p.binding, ind->argument_offset,
3024 !detail::indirect_range(p.binding, ind->argument_offset, 3096 VkDeviceSize(ind->max_count - 1) * ind->stride + record_size)
3025 VkDeviceSize(ind->max_count) * ind->stride)) 3097 : (p.binding.buffer_offset | ind->argument_offset) % sizeof(std::uint32_t) != 0)
3026 return ReplayResult::invalid_indirect_arguments; 3098 return ReplayResult::invalid_indirect_arguments;
3027 if (ind->count_buffer) { 3099 if (ind->count_buffer) {
3028 const ResourceBinding* cnt = resolve(ind->count_buffer); 3100 const ResourceBinding* cnt = resolve(ind->count_buffer);
@@ -3103,6 +3175,11 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
3103 VkDeviceSize offset = 0; 3175 VkDeviceSize offset = 0;
3104 if (!vk.buffer_at(info->dest_va, room, buffer, offset)) return ReplayResult::unresolved_resource; 3176 if (!vk.buffer_at(info->dest_va, room, buffer, offset)) return ReplayResult::unresolved_resource;
3105 if (room < 8 * info->sources.size()) return ReplayResult::invalid_copy; 3177 if (room < 8 * info->sources.size()) return ReplayResult::invalid_copy;
3178 if (!info->sources.empty()) {
3179 // dest_va is resolved by VA and may target a host-readable buffer; XDXR postbuild writes from compute.
3180 out.wrote_readback = true;
3181 out.readback_src_stages |= VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT;
3182 }
3106 } else if (info->type == 0 && vk.write_acceleration_structures_properties && 3183 } else if (info->type == 0 && vk.write_acceleration_structures_properties &&
3107 vk.resolve_acceleration_structure && vk.reset_query_pool && vk.copy_query_pool_results && 3184 vk.resolve_acceleration_structure && vk.reset_query_pool && vk.copy_query_pool_results &&
3108 vk.pipeline_barrier && vk.buffer_at && vk.prepare_khr_postbuild) { 3185 vk.pipeline_barrier && vk.buffer_at && vk.prepare_khr_postbuild) {
@@ -3191,6 +3268,7 @@ public:
3191 retain(statistics_pool); 3268 retain(statistics_pool);
3192 list.statistics_pool = statistics_pool->pool; 3269 list.statistics_pool = statistics_pool->pool;
3193 list.statistics_mesh_pool = statistics_pool->mesh_pool; 3270 list.statistics_mesh_pool = statistics_pool->mesh_pool;
3271 list.statistics_primitives_pool = statistics_pool->primitives_pool;
3194 list.statistics_base = statistics_base; 3272 list.statistics_base = statistics_base;
3195 } else if (mesh) { 3273 } else if (mesh) {
3196 // Unsplit, the query would be active around a mesh draw with counters Vulkan forbids there. 3274 // Unsplit, the query would be active around a mesh draw with counters Vulkan forbids there.
@@ -3247,7 +3325,8 @@ public:
3247 const bool any_mesh = kinds && std::find(kinds + saved.first, kinds + saved.first + saved.count, 3325 const bool any_mesh = kinds && std::find(kinds + saved.first, kinds + saved.first + saved.count,
3248 std::uint8_t(1)) != kinds + saved.first + saved.count; 3326 std::uint8_t(1)) != kinds + saved.first + saved.count;
3249 run = {saved.segments->pool, saved.first, saved.count, run.offset, 3327 run = {saved.segments->pool, saved.first, saved.count, run.offset,
3250 saved.count > 1 || any_mesh, saved.segments->mesh_pool, kinds}; 3328 saved.count > 1 || any_mesh, saved.segments->mesh_pool,
3329 saved.segments->primitives_pool, kinds};
3251 if (any_mesh && !statistics) return ReplayResult::invalid_query; 3330 if (any_mesh && !statistics) return ReplayResult::invalid_query;
3252 if (!can_sum || (run.sum && !uncounted)) return ReplayResult::unsupported; 3331 if (!can_sum || (run.sum && !uncounted)) return ReplayResult::unsupported;
3253 if (statistics) needs_statistics_sum |= run.sum; 3332 if (statistics) needs_statistics_sum |= run.sum;
@@ -3314,6 +3393,9 @@ inline void end_statistics_segment(const PreparedList& list, std::uint32_t segme
3314 const ReplayFunctions& vk) { 3393 const ReplayFunctions& vk) {
3315 if (segment == PreparedQuery::no_segment) return; 3394 if (segment == PreparedQuery::no_segment) return;
3316 vk.end_query(cb, statistics_segment_pool(list, segment), list.statistics_base + segment); 3395 vk.end_query(cb, statistics_segment_pool(list, segment), list.statistics_base + segment);
3396 // The mesh-primitives count of a mesh segment (D3D-MESH-CLIPPING-COUNTER).
3397 if (list.statistics_primitives_pool && list.statistics_mesh[segment])
3398 vk.end_query(cb, list.statistics_primitives_pool, list.statistics_base + segment);
3317} 3399}
3318 3400
3319inline void begin_statistics_segment(const PreparedList& list, std::uint32_t segment, VkCommandBuffer cb, 3401inline void begin_statistics_segment(const PreparedList& list, std::uint32_t segment, VkCommandBuffer cb,
@@ -3322,6 +3404,12 @@ inline void begin_statistics_segment(const PreparedList& list, std::uint32_t seg
3322 const auto pool = statistics_segment_pool(list, segment); 3404 const auto pool = statistics_segment_pool(list, segment);
3323 vk.reset_query_pool(cb, pool, list.statistics_base + segment, 1); 3405 vk.reset_query_pool(cb, pool, list.statistics_base + segment, 1);
3324 vk.begin_query(cb, pool, list.statistics_base + segment, 0); 3406 vk.begin_query(cb, pool, list.statistics_base + segment, 0);
3407 // The mesh-primitives count of a mesh segment (D3D-MESH-CLIPPING-COUNTER): a query of its own type, which the
3408 // mesh statistics pool cannot hold.
3409 if (list.statistics_primitives_pool && list.statistics_mesh[segment]) {
3410 vk.reset_query_pool(cb, list.statistics_primitives_pool, list.statistics_base + segment, 1);
3411 vk.begin_query(cb, list.statistics_primitives_pool, list.statistics_base + segment, 0);
3412 }
3325} 3413}
3326 3414
3327} // namespace detail 3415} // namespace detail
@@ -3382,7 +3470,8 @@ inline void emit_query(const PreparedList& list, const detail::PreparedQuery& qu
3382 if (!run.pool) { 3470 if (!run.pool) {
3383 vk.fill_buffer(cb, dst, run.offset, VkDeviceSize(run.count) * size, 0); 3471 vk.fill_buffer(cb, dst, run.offset, VkDeviceSize(run.count) * size, 0);
3384 } else if (run.sum && resolve.type == d3d12_query::pipeline_statistics) { 3472 } else if (run.sum && resolve.type == d3d12_query::pipeline_statistics) {
3385 vk.sum_statistics(cb, run.pool, run.mesh_pool, run.mesh, run.first, run.count, dst, run.offset); 3473 vk.sum_statistics(cb, run.pool, run.mesh_pool, run.primitives_pool, run.mesh, run.first, run.count,
3474 dst, run.offset);
3386 } else if (run.sum && binary) { 3475 } else if (run.sum && binary) {
3387 vk.sum_binary_occlusion(cb, run.pool, run.first, run.count, dst, run.offset); 3476 vk.sum_binary_occlusion(cb, run.pool, run.first, run.count, dst, run.offset);
3388 } else if (run.sum || binary) { 3477 } else if (run.sum || binary) {
@@ -3535,16 +3624,23 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
3535 const auto range = detail::planes_for_layout(p.binding, p.range, separate); 3624 const auto range = detail::planes_for_layout(p.binding, p.range, separate);
3536 const bool discard = (texture->flags & texture_barrier_discard) || 3625 const bool discard = (texture->flags & texture_barrier_discard) ||
3537 texture->layout_before == d3d12_layout::undefined; 3626 texture->layout_before == d3d12_layout::undefined;
3627 // LayoutAfter UNDEFINED from a defined layout: the contents are no longer needed (the memory is about to
3628 // be aliased, say). Vulkan has no transition into UNDEFINED (VUID-VkImageMemoryBarrier2-newLayout-01198),
3629 // so each piece keeps the layout it is in and the barrier only orders the accesses; the tracker keeps
3630 // that layout too. D3D12 has the next barrier on these subresources start from UNDEFINED, which discards
3631 // from whatever layout they are in.
3632 const bool release = texture->layout_after == d3d12_layout::undefined &&
3633 texture->layout_before != d3d12_layout::undefined;
3538 const VkImageLayout new_layout = 3634 const VkImageLayout new_layout =
3539 image_layout(p.binding, vulkan_layout(texture->layout_after, p.binding.presentable)); 3635 image_layout(p.binding, vulkan_layout(texture->layout_after, p.binding.presentable));
3540 LayoutPieces pieces; 3636 LayoutPieces pieces;
3541 if (discard) 3637 if (discard && !release)
3542 pieces.push_back({range, VK_IMAGE_LAYOUT_UNDEFINED}); 3638 pieces.push_back({range, VK_IMAGE_LAYOUT_UNDEFINED});
3543 else { 3639 else {
3544 const VkImageLayout before = 3640 const VkImageLayout before =
3545 image_layout(p.binding, vulkan_layout(texture->layout_before, p.binding.presentable)); 3641 image_layout(p.binding, vulkan_layout(texture->layout_before, p.binding.presentable));
3546 pieces = detail::current(tracker, id, range, before); 3642 pieces = detail::current(tracker, id, range, before);
3547 detail::initialize(vk, command_buffer, p.binding, id, pieces, before, tracker); 3643 if (!release) detail::initialize(vk, command_buffer, p.binding, id, pieces, before, tracker);
3548 } 3644 }
3549 const BarrierScope src = vulkan_barrier_scope(texture->sync_before, texture->access_before, predicates); 3645 const BarrierScope src = vulkan_barrier_scope(texture->sync_before, texture->access_before, predicates);
3550 const BarrierScope dst = vulkan_barrier_scope(texture->sync_after, texture->access_after, predicates); 3646 const BarrierScope dst = vulkan_barrier_scope(texture->sync_after, texture->access_after, predicates);
@@ -3555,6 +3651,8 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
3555 VkImageMemoryBarrier2* const barriers = many.empty() ? few.data() : many.data(); 3651 VkImageMemoryBarrier2* const barriers = many.empty() ? few.data() : many.data();
3556 std::uint32_t barrier_count = 0; 3652 std::uint32_t barrier_count = 0;
3557 for (const auto& piece : pieces) { 3653 for (const auto& piece : pieces) {
3654 // Released before it was ever used (the tracker still has it in UNDEFINED): nothing to order.
3655 if (release && piece.layout == VK_IMAGE_LAYOUT_UNDEFINED) continue;
3558 VkImageMemoryBarrier2& b = barriers[barrier_count++]; 3656 VkImageMemoryBarrier2& b = barriers[barrier_count++];
3559 b = {VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2}; 3657 b = {VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2};
3560 b.srcStageMask = src.stages; 3658 b.srcStageMask = src.stages;
@@ -3562,7 +3660,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
3562 b.srcAccessMask = src.access; 3660 b.srcAccessMask = src.access;
3563 b.dstAccessMask = dst.access; 3661 b.dstAccessMask = dst.access;
3564 b.oldLayout = piece.layout; 3662 b.oldLayout = piece.layout;
3565 b.newLayout = new_layout; 3663 b.newLayout = release ? piece.layout : new_layout;
3566 b.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; 3664 b.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
3567 b.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; 3665 b.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
3568 b.image = p.binding.image; 3666 b.image = p.binding.image;
@@ -3570,11 +3668,13 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
3570 if (b.srcStageMask) detail::restrict_to_queue(vk, b.srcStageMask, b.srcAccessMask); 3668 if (b.srcStageMask) detail::restrict_to_queue(vk, b.srcStageMask, b.srcAccessMask);
3571 if (b.dstStageMask) detail::restrict_to_queue(vk, b.dstStageMask, b.dstAccessMask); 3669 if (b.dstStageMask) detail::restrict_to_queue(vk, b.dstStageMask, b.dstAccessMask);
3572 } 3670 }
3573 VkDependencyInfo dependency{VK_STRUCTURE_TYPE_DEPENDENCY_INFO}; 3671 if (barrier_count) {
3574 dependency.imageMemoryBarrierCount = barrier_count; 3672 VkDependencyInfo dependency{VK_STRUCTURE_TYPE_DEPENDENCY_INFO};
3575 dependency.pImageMemoryBarriers = barriers; 3673 dependency.imageMemoryBarrierCount = barrier_count;
3576 vk.pipeline_barrier2(command_buffer, &dependency); 3674 dependency.pImageMemoryBarriers = barriers;
3577 if (tracker) tracker->set(id, range, new_layout); 3675 vk.pipeline_barrier2(command_buffer, &dependency);
3676 }
3677 if (tracker && !release) tracker->set(id, range, new_layout);
3578 } else if (const auto* color_clear = std::get_if<ClearRenderTarget>(&command)) { 3678 } else if (const auto* color_clear = std::get_if<ClearRenderTarget>(&command)) {
3579 if (p.skip) continue; 3679 if (p.skip) continue;
3580 const VulkanAccess state = vulkan_access(d3d12_state::render_target, false); 3680 const VulkanAccess state = vulkan_access(d3d12_state::render_target, false);
@@ -3615,10 +3715,13 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
3615 const VulkanAccess state = vulkan_access(d3d12_state::depth_write, false); 3715 const VulkanAccess state = vulkan_access(d3d12_state::depth_write, false);
3616 auto pieces = detail::current(tracker, id, range, image_layout(p.binding, state.layout)); 3716 auto pieces = detail::current(tracker, id, range, image_layout(p.binding, state.layout));
3617 detail::initialize(vk, command_buffer, p.binding, id, pieces, image_layout(p.binding, state.layout), tracker); 3717 detail::initialize(vk, command_buffer, p.binding, id, pieces, image_layout(p.binding, state.layout), tracker);
3618 const float depth = p.binding.depth24 ? depth24_clear_value(depth_clear->depth) // see depth24.h 3718 float depth = p.binding.depth24 ? depth24_clear_value(depth_clear->depth) // see depth24.h
3619 : p.binding.format == VK_FORMAT_D16_UNORM 3719 : p.binding.format == VK_FORMAT_D16_UNORM
3620 ? detail::quantize_unorm(depth_clear->depth, 65535.0) // see quantize_unorm 3720 ? detail::quantize_unorm(depth_clear->depth, 65535.0) // see quantize_unorm
3621 : depth_clear->depth; 3721 : depth_clear->depth;
3722 // Without the extension both clear commands require a depth in [0, 1], including for float images.
3723 if (!vk.depth_range_unrestricted)
3724 depth = std::isnan(depth) ? 0.0f : std::clamp(depth, 0.0f, 1.0f);
3622 const VkClearDepthStencilValue value{depth, depth_clear->stencil}; 3725 const VkClearDepthStencilValue value{depth, depth_clear->stencil};
3623 if (p.rects.empty()) { 3726 if (p.rects.empty()) {
3624 detail::round_trip(vk, command_buffer, p.binding, pieces, image_layout(p.binding, transfer_dst.layout), 3727 detail::round_trip(vk, command_buffer, p.binding, pieces, image_layout(p.binding, transfer_dst.layout),
@@ -4179,14 +4282,46 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
4179 vk.push_constants(command_buffer, graphics.layout, graphics.push_stages, 0, sizeof(data), &data); 4282 vk.push_constants(command_buffer, graphics.layout, graphics.push_stages, 0, sizeof(data), &data);
4180 // Translated vertex shaders write D3D clip coordinates (y up); a negative-height viewport keeps the 4283 // Translated vertex shaders write D3D clip coordinates (y up); a negative-height viewport keeps the
4181 // image upright, and winding as D3D12 sees it. 4284 // image upright, and winding as D3D12 sees it.
4182 const Viewport& v = draw->viewport; 4285 if (graphics.viewport_with_count) {
4183 const VkViewport viewport{v.x, v.y + v.height, v.width, -v.height, v.min_depth, v.max_depth}; 4286 std::array<VkViewport, DrawViewports::max_count> vps{};
4184 vk.set_viewport(command_buffer, 0, 1, &viewport); 4287 std::array<VkRect2D, DrawViewports::max_count> scs{};
4185 const Rect& s = draw->scissor; 4288 const std::uint32_t vp_n = draw->viewports ? draw->viewports->viewport_count : 1u;
4186 const VkRect2D scissor{{std::max(0, s.left), std::max(0, s.top)}, 4289 const std::uint32_t sc_n = draw->viewports ? draw->viewports->scissor_count : 1u;
4187 {std::uint32_t(std::max(0, s.right - std::max(0, s.left))), 4290 const std::uint32_t count = std::clamp(std::max(vp_n, sc_n), 1u, DrawViewports::max_count);
4188 std::uint32_t(std::max(0, s.bottom - std::max(0, s.top)))}}; 4291 for (std::uint32_t k = 0; k < count; ++k) {
4189 vk.set_scissor(command_buffer, 0, 1, &scissor); 4292 const Viewport v = (draw->viewports && k < vp_n) ? draw->viewports->viewports[k]
4293 : (k == 0 ? draw->viewport : Viewport{});
4294 const bool valid_vp = (k < vp_n) && (v.width > 0.0f) && (v.height > 0.0f);
4295 if (valid_vp) {
4296 vps[k] = {v.x, v.y + v.height, v.width, -v.height, v.min_depth, v.max_depth};
4297 } else {
4298 // Vulkan forbids width/height == 0; pair a 1x1 dummy viewport with an empty scissor so nothing
4299 // rasterizes into an unbound/empty D3D12 viewport slot.
4300 vps[k] = {0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f};
4301 }
4302 if (valid_vp && k < sc_n) {
4303 const Rect s = draw->viewports ? draw->viewports->scissors[k] : draw->scissor;
4304 const std::int32_t left = std::max(0, s.left);
4305 const std::int32_t top = std::max(0, s.top);
4306 scs[k] = {{left, top},
4307 {std::uint32_t(std::max(0, s.right - left)),
4308 std::uint32_t(std::max(0, s.bottom - top))}};
4309 } else {
4310 scs[k] = {{0, 0}, {0, 0}};
4311 }
4312 }
4313 vk.set_viewport_with_count(command_buffer, count, vps.data());
4314 vk.set_scissor_with_count(command_buffer, count, scs.data());
4315 } else {
4316 const Viewport& v = draw->viewport;
4317 const VkViewport viewport{v.x, v.y + v.height, v.width, -v.height, v.min_depth, v.max_depth};
4318 vk.set_viewport(command_buffer, 0, 1, &viewport);
4319 const Rect& s = draw->scissor;
4320 const VkRect2D scissor{{std::max(0, s.left), std::max(0, s.top)},
4321 {std::uint32_t(std::max(0, s.right - std::max(0, s.left))),
4322 std::uint32_t(std::max(0, s.bottom - std::max(0, s.top)))}};
4323 vk.set_scissor(command_buffer, 0, 1, &scissor);
4324 }
4190 // A mesh pipeline has no input assembly: its topology comes from the shader, and neither the topology 4325 // A mesh pipeline has no input assembly: its topology comes from the shader, and neither the topology
4191 // nor primitive restart is dynamic state there (VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-07065). 4326 // nor primitive restart is dynamic state there (VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-07065).
4192 if (!draw->mesh) { 4327 if (!draw->mesh) {
diff --git a/runtime/src/vulkan_scratch.h b/runtime/src/vulkan_scratch.h
index 4a8a59ddd..33d84bf72 100644
--- a/runtime/src/vulkan_scratch.h
+++ b/runtime/src/vulkan_scratch.h
@@ -46,12 +46,16 @@ public:
46 constexpr VkDeviceSize alignment = 256, minimum = 4u << 20; 46 constexpr VkDeviceSize alignment = 256, minimum = 4u << 20;
47 if (!loaded_ || !bytes) return false; 47 if (!loaded_ || !bytes) return false;
48 for (auto& chunk : current_.chunks) { 48 for (auto& chunk : current_.chunks) {
49 const VkDeviceSize start = (chunk.used + alignment - 1) / alignment * alignment; 49 const VkDeviceSize rem = chunk.used % alignment;
50 if (start <= chunk.size && bytes <= chunk.size - start) { 50 const VkDeviceSize pad = rem ? alignment - rem : 0;
51 chunk.used = start + bytes; 51 if (pad <= chunk.size - chunk.used) {
52 buffer = chunk.buffer; 52 const VkDeviceSize start = chunk.used + pad;
53 offset = start; 53 if (bytes <= chunk.size - start) {
54 return true; 54 chunk.used = start + bytes;
55 buffer = chunk.buffer;
56 offset = start;
57 return true;
58 }
55 } 59 }
56 } 60 }
57 Chunk chunk; 61 Chunk chunk;
diff --git a/runtime/src/xdxr_build.h b/runtime/src/xdxr_build.h
index e0851098f..e1c1a233e 100644
--- a/runtime/src/xdxr_build.h
+++ b/runtime/src/xdxr_build.h
@@ -133,7 +133,13 @@ public:
133 // update ignores `pair`. 133 // update ignores `pair`.
134 bool record_blas(VkCommandBuffer cb, const XdxrLayout& layout, const std::vector<XdxrTriangles>& geometries, 134 bool record_blas(VkCommandBuffer cb, const XdxrLayout& layout, const std::vector<XdxrTriangles>& geometries,
135 std::uint64_t dst, std::uint64_t scratch, std::uint64_t update_from = 0, bool pair = false) { 135 std::uint64_t dst, std::uint64_t scratch, std::uint64_t update_from = 0, bool pair = false) {
136 if (!loaded_ || layout.tlas) return false; 136 if (!loaded_ || layout.tlas || !layout.size || !dst || !scratch) return false;
137 std::uint64_t total = 0;
138 for (const auto& geo : geometries) {
139 total += geo.triangle_count;
140 if (total > layout.elements) return false;
141 }
142 if (total != layout.elements) return false;
137 Push p = base(layout, dst, scratch); 143 Push p = base(layout, dst, scratch);
138 if (pair && !update_from) p.flags |= flag_pair; 144 if (pair && !update_from) p.flags |= flag_pair;
139 if (update_from) refit_begin(cb, layout, p, update_from); else begin(cb, layout, p); 145 if (update_from) refit_begin(cb, layout, p, update_from); else begin(cb, layout, p);
@@ -155,7 +161,6 @@ public:
155 dispatch(cb, t, t.count); 161 dispatch(cb, t, t.count);
156 first += geo.triangle_count; 162 first += geo.triangle_count;
157 } 163 }
158 if (first != layout.elements) return false;
159 if (update_from) refit_finish(cb, layout, p); else finish(cb, layout, p); 164 if (update_from) refit_finish(cb, layout, p); else finish(cb, layout, p);
160 return true; 165 return true;
161 } 166 }
@@ -164,7 +169,8 @@ public:
164 // `update_from`: as for record_blas; the instances may move, and name other BLASes. 169 // `update_from`: as for record_blas; the instances may move, and name other BLASes.
165 bool record_tlas(VkCommandBuffer cb, const XdxrLayout& layout, std::uint64_t instances, std::uint64_t dst, 170 bool record_tlas(VkCommandBuffer cb, const XdxrLayout& layout, std::uint64_t instances, std::uint64_t dst,
166 std::uint64_t scratch, std::uint64_t bias = 0, std::uint64_t update_from = 0) { 171 std::uint64_t scratch, std::uint64_t bias = 0, std::uint64_t update_from = 0) {
167 if (!loaded_ || !layout.tlas) return false; 172 if (!loaded_ || !layout.tlas || !layout.size || !dst || !scratch || (layout.elements && !instances))
173 return false;
168 Push p = base(layout, dst, scratch); 174 Push p = base(layout, dst, scratch);
169 p.bias = split(bias); 175 p.bias = split(bias);
170 if (update_from) refit_begin(cb, layout, p, update_from); else begin(cb, layout, p); 176 if (update_from) refit_begin(cb, layout, p, update_from); else begin(cb, layout, p);
@@ -341,7 +347,7 @@ private:
341 // dependency on its results to the caller's barrier (the application's UAV or AS barrier). 347 // dependency on its results to the caller's barrier (the application's UAV or AS barrier).
342 void dispatch(VkCommandBuffer cb, const Push& p, std::uint32_t threads, bool barrier = true) { 348 void dispatch(VkCommandBuffer cb, const Push& p, std::uint32_t threads, bool barrier = true) {
343 vk_.vkCmdPushConstants(cb, layout_, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(Push), &p); 349 vk_.vkCmdPushConstants(cb, layout_, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(Push), &p);
344 vk_.vkCmdDispatch(cb, (threads + 63) / 64, 1, 1); 350 vk_.vkCmdDispatch(cb, std::uint32_t((std::uint64_t(threads) + 63u) / 64u), 1, 1);
345 if (!barrier) return; 351 if (!barrier) return;
346 VkMemoryBarrier b{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; 352 VkMemoryBarrier b{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
347 b.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; 353 b.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT;
diff --git a/runtime/src/xdxr_descs.h b/runtime/src/xdxr_descs.h
index b44ce0372..3798b0fe7 100644
--- a/runtime/src/xdxr_descs.h
+++ b/runtime/src/xdxr_descs.h
@@ -99,12 +99,11 @@ constexpr uint32_t kPostbuildInfoOfflineStatistics = 0x10;
99// The record a setting is read from, the way the DLL finds it: the first record of `type` from the start, stepping 99// The record a setting is read from, the way the DLL finds it: the first record of `type` from the start, stepping
100// over types 0, 1 and 2, and stopping at any other type. Null when there is none. 100// over types 0, 1 and 2, and stopping at any other type. Null when there is none.
101inline const StreamRecord* find_stream_record(const StreamDesc& desc, uint32_t type) { 101inline const StreamRecord* find_stream_record(const StreamDesc& desc, uint32_t type) {
102 if (desc.size_in_bytes == 0 || desc.stream == nullptr) 102 if (desc.size_in_bytes < sizeof(StreamRecord) || desc.stream == nullptr)
103 return nullptr; 103 return nullptr;
104 const auto* record = static_cast<const StreamRecord*>(desc.stream); 104 const auto* record = static_cast<const StreamRecord*>(desc.stream);
105 const auto* end = reinterpret_cast<const StreamRecord*>(static_cast<const uint8_t*>(desc.stream) + 105 const uint64_t count = desc.size_in_bytes / sizeof(StreamRecord);
106 desc.size_in_bytes); 106 for (uint64_t i = 0; i < count; ++i, ++record) {
107 for (; record < end; ++record) {
108 if (record->type == type) 107 if (record->type == type)
109 return record; 108 return record;
110 if (record->type > 2) 109 if (record->type > 2)
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/active_input_test.cpp b/runtime/test/active_input_test.cpp
index 11c628320..64b7f1b86 100644
--- a/runtime/test/active_input_test.cpp
+++ b/runtime/test/active_input_test.cpp
@@ -4,6 +4,7 @@
4#include "../src/active_input.h" 4#include "../src/active_input.h"
5 5
6#include <cstdio> 6#include <cstdio>
7#include <limits>
7#include <iterator> 8#include <iterator>
8#include <string_view> 9#include <string_view>
9 10
@@ -201,6 +202,41 @@ int test_forced() {
201 return 0; 202 return 0;
202} 203}
203 204
205int test_out_of_order_timestamp_and_non_finite_axes() {
206 ActiveInputTracker t(InputFamily::Xbox);
207 EXPECT(t.observe(1, InputFamily::PlayStation5, InputSample{}, 1000000) == InputEdge::None);
208 EXPECT(t.observe(2, InputFamily::Keyboard, InputSample{}, 1000000) == InputEdge::None);
209
210 InputSample press;
211 press.buttons = 1;
212 EXPECT(t.observe(1, InputFamily::PlayStation5, press, 2000000) == InputEdge::Button);
213 EXPECT(t.active() == InputFamily::PlayStation5 && t.generation() == 1);
214
215 // An earlier timestamp must not underflow (time_us - changed_at_) and bypass min_switch_us.
216 EXPECT(t.observe(2, InputFamily::Keyboard, press, 1999000) == InputEdge::None);
217 EXPECT(t.active() == InputFamily::PlayStation5 && t.generation() == 1);
218
219 // Non-finite stick/trigger samples (NaN baseline or Inf deflection) must not trigger a family switch.
220 const float nan = std::numeric_limits<float>::quiet_NaN();
221 const float inf = std::numeric_limits<float>::infinity();
222 ActiveInputTracker t2(InputFamily::Xbox);
223 InputSample nan_stick;
224 nan_stick.left_x = nan;
225 EXPECT(t2.observe(3, InputFamily::PlayStation5, nan_stick, 1000000) == InputEdge::None);
226 InputSample deflected;
227 deflected.left_x = 0.9f;
228 EXPECT(t2.observe(3, InputFamily::PlayStation5, deflected, 2000000) == InputEdge::None);
229 EXPECT(t2.active() == InputFamily::Xbox && t2.generation() == 0);
230
231 ActiveInputTracker t3(InputFamily::Xbox);
232 EXPECT(t3.observe(4, InputFamily::PlayStation5, InputSample{}, 1000000) == InputEdge::None);
233 InputSample inf_trig;
234 inf_trig.left_trigger = inf;
235 EXPECT(t3.observe(4, InputFamily::PlayStation5, inf_trig, 2000000) == InputEdge::None);
236 EXPECT(t3.active() == InputFamily::Xbox && t3.generation() == 0);
237 return 0;
238}
239
204int test_names() { 240int test_names() {
205 EXPECT(std::string_view(input_family_name(InputFamily::PlayStation5)) == "PlayStation 5"); 241 EXPECT(std::string_view(input_family_name(InputFamily::PlayStation5)) == "PlayStation 5");
206 EXPECT(std::string_view(input_family_name(InputFamily::Keyboard)) == "keyboard and mouse"); 242 EXPECT(std::string_view(input_family_name(InputFamily::Keyboard)) == "keyboard and mouse");
@@ -222,6 +258,7 @@ int main() {
222 {"one family, held input", test_same_family_and_holds}, 258 {"one family, held input", test_same_family_and_holds},
223 {"reconnect", test_reconnect}, 259 {"reconnect", test_reconnect},
224 {"forced family", test_forced}, 260 {"forced family", test_forced},
261 {"out-of-order timestamp and non-finite axes", test_out_of_order_timestamp_and_non_finite_axes},
225 {"names", test_names}, 262 {"names", test_names},
226 }; 263 };
227 int failures = 0; 264 int failures = 0;
diff --git a/runtime/test/arena_size_test.cpp b/runtime/test/arena_size_test.cpp
index 249af1355..77dcf1f65 100644
--- a/runtime/test/arena_size_test.cpp
+++ b/runtime/test/arena_size_test.cpp
@@ -29,7 +29,10 @@ int request_without_limits() {
29 CHECK(decide_arena_size("1", none).bytes == 16 * MiB); 29 CHECK(decide_arena_size("1", none).bytes == 16 * MiB);
30 CHECK(decide_arena_size("0", none).bytes == 16 * MiB); 30 CHECK(decide_arena_size("0", none).bytes == 16 * MiB);
31 CHECK(decide_arena_size("lots", none).bytes == 16 * MiB); 31 CHECK(decide_arena_size("lots", none).bytes == 16 * MiB);
32 CHECK(decide_arena_size("-5", none).bytes == 16 * MiB);
33 CHECK(decide_arena_size("-99999999999999999999", none).bytes == 16 * MiB);
32 CHECK(decide_arena_size("99999", none).bytes == 4095 * MiB); 34 CHECK(decide_arena_size("99999", none).bytes == 4095 * MiB);
35 CHECK(decide_arena_size("99999999999999999999", none).bytes == 4095 * MiB);
33 const ArenaSize s = decide_arena_size("3000", none); 36 const ArenaSize s = decide_arena_size("3000", none);
34 CHECK(s.bytes == 3000 * MiB && s.requested == 3000 * MiB && s.capped == arena_cap_none); 37 CHECK(s.bytes == 3000 * MiB && s.requested == 3000 * MiB && s.capped == arena_cap_none);
35 return 0; 38 return 0;
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/command_list_test.cpp b/runtime/test/command_list_test.cpp
index 4367df6ec..ea81503e6 100644
--- a/runtime/test/command_list_test.cpp
+++ b/runtime/test/command_list_test.cpp
@@ -99,15 +99,19 @@ int main() {
99 CHECK(!list.barrier(BufferBarrier{y::copy, y::vertex_shading, a::copy_dest, a::vertex_buffer, 0})); 99 CHECK(!list.barrier(BufferBarrier{y::copy, y::vertex_shading, a::copy_dest, a::vertex_buffer, 0}));
100 CHECK(list.barrier(TextureBarrier{y::none, y::render_target, a::no_access, a::render_target, l::undefined, 100 CHECK(list.barrier(TextureBarrier{y::none, y::render_target, a::no_access, a::render_target, l::undefined,
101 l::render_target, 9, all, texture_barrier_discard})); 101 l::render_target, 9, all, texture_barrier_discard}));
102 CHECK(!list.barrier(TextureBarrier{y::all, y::all, a::common, a::common, l::common, l::undefined, 9, all, 0})); 102 // Into UNDEFINED: the contents are no longer needed (WARP closes such a list, d3d12_close_parity_test).
103 CHECK(list.barrier(TextureBarrier{y::depth_stencil, y::none, a::depth_stencil_write, a::no_access,
104 l::depth_stencil_write, l::undefined, 9, all, 0}));
103 CHECK(!list.barrier(TextureBarrier{y::all, y::all, a::common, a::common, l::common, l::common, 9, all, 0x2})); 105 CHECK(!list.barrier(TextureBarrier{y::all, y::all, a::common, a::common, l::common, l::common, 9, all, 0x2}));
104 CHECK(!list.barrier(TextureBarrier{y::all, y::all, a::common, a::common, l::common, l::common, 9, 106 CHECK(!list.barrier(TextureBarrier{y::all, y::all, a::common, a::common, l::common, l::common, 9,
105 {0, 1, 0, 0, 0, 1}, 0})); // zero layers 107 {0, 1, 0, 0, 0, 1}, 0})); // zero layers
106 CHECK(list.close()); 108 CHECK(list.close());
107 CHECK(list.commands().size() == 4); 109 CHECK(list.commands().size() == 5);
108 CHECK(std::get<GlobalBarrier>(list.commands()[1]).sync_before == y::split); 110 CHECK(std::get<GlobalBarrier>(list.commands()[1]).sync_before == y::split);
109 CHECK(std::get<BufferBarrier>(list.commands()[2]).resource == 7); 111 CHECK(std::get<BufferBarrier>(list.commands()[2]).resource == 7);
110 CHECK(std::get<TextureBarrier>(list.commands()[3]).flags == texture_barrier_discard); 112 CHECK(std::get<TextureBarrier>(list.commands()[3]).flags == texture_barrier_discard);
113 CHECK(std::get<TextureBarrier>(list.commands()[4]).layout_before == l::depth_stencil_write &&
114 std::get<TextureBarrier>(list.commands()[4]).layout_after == l::undefined);
111 115
112 // Copies: D3D12's own call rules (aligned footprints; degenerate boxes and DEFAULT-heap 116 // Copies: D3D12's own call rules (aligned footprints; degenerate boxes and DEFAULT-heap
113 // CopyResource self-copies are accepted as no-ops and must not record Vulkan commands). 117 // CopyResource self-copies are accepted as no-ops and must not record Vulkan commands).
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/crt_timed_wait_test.cpp b/runtime/test/crt_timed_wait_test.cpp
index 339a8a215..d88b2811a 100644
--- a/runtime/test/crt_timed_wait_test.cpp
+++ b/runtime/test/crt_timed_wait_test.cpp
@@ -2,6 +2,16 @@
2// statically linked timed wait kept the mutex for the whole timeout, so a thread setting the predicate waited until 2// statically linked timed wait kept the mutex for the whole timeout, so a thread setting the predicate waited until
3// the wait timed out. Also checks the other definitions that file takes over: std::shared_mutex and 3// the wait timed out. Also checks the other definitions that file takes over: std::shared_mutex and
4// this_thread::sleep_for. No game files, no GPU. 4// this_thread::sleep_for. No game files, no GPU.
5#ifdef _WIN32
6#ifndef WIN32_LEAN_AND_MEAN
7#define WIN32_LEAN_AND_MEAN
8#endif
9#ifndef NOMINMAX
10#define NOMINMAX
11#endif
12#include <windows.h>
13#endif
14
5#include <chrono> 15#include <chrono>
6#include <condition_variable> 16#include <condition_variable>
7#include <cstdio> 17#include <cstdio>
@@ -112,6 +122,63 @@ int main() {
112 check(ms_since(start) >= 90, "this_thread::sleep_for sleeps"); 122 check(ms_since(start) >= 90, "this_thread::sleep_for sleeps");
113 } 123 }
114 124
125 {
126 // Repeated short unnotified waits must not return cv_status::no_timeout early before their deadline.
127 bool no_early_no_timeout = true;
128 bool all_reached_target = true;
129 std::unique_lock<std::mutex> lock(mutex);
130 for (int i = 0; i < 25; ++i) {
131 const auto target = Clock::now() + std::chrono::milliseconds(10);
132 const std::cv_status status = cv.wait_for(lock, std::chrono::milliseconds(10));
133 const auto finished = Clock::now();
134 if (finished < target) {
135 all_reached_target = false;
136 if (status == std::cv_status::no_timeout) no_early_no_timeout = false;
137 }
138 }
139 check(no_early_no_timeout, "25 short unnotified wait_for calls never return no_timeout before target");
140 check(all_reached_target, "25 short unnotified wait_for calls reach steady_clock target");
141 }
142
143#ifdef _WIN32
144 {
145 // A pre-existing ERROR_TIMEOUT must not misclassify a real notification as a timeout and must be preserved.
146 bool flag = false;
147 std::thread setter([&] {
148 std::this_thread::sleep_for(std::chrono::milliseconds(20));
149 { std::lock_guard<std::mutex> lock(mutex); flag = true; }
150 cv.notify_one();
151 });
152 SetLastError(ERROR_TIMEOUT);
153 std::cv_status status = std::cv_status::timeout;
154 {
155 std::unique_lock<std::mutex> lock(mutex);
156 while (!flag) {
157 status = cv.wait_for(lock, std::chrono::seconds(5));
158 if (status == std::cv_status::timeout) break;
159 }
160 }
161 const DWORD last_error = GetLastError();
162 setter.join();
163 check(flag && status == std::cv_status::no_timeout, "pre-existing ERROR_TIMEOUT does not mask notification");
164 check(last_error == ERROR_TIMEOUT, "pre-existing ERROR_TIMEOUT is preserved across wait_for");
165 }
166
167 {
168 // Caller LastError is preserved across a timed-out wait_for.
169 SetLastError(ERROR_INVALID_DATA);
170 std::unique_lock<std::mutex> lock(mutex);
171 const auto target = Clock::now() + std::chrono::milliseconds(15);
172 const std::cv_status status = cv.wait_for(lock, std::chrono::milliseconds(15));
173 const auto finished = Clock::now();
174 const DWORD last_error = GetLastError();
175 check(status == std::cv_status::timeout || finished >= target,
176 "unnotified wait_for with preset LastError does not return no_timeout before target");
177 check(finished >= target, "unnotified wait_for with preset LastError reaches steady_clock target");
178 check(last_error == ERROR_INVALID_DATA, "caller LastError is preserved across timed-out wait_for");
179 }
180#endif
181
115 if (failures) { 182 if (failures) {
116 std::printf("RESULT: FAIL (%d failures)\n", failures); 183 std::printf("RESULT: FAIL (%d failures)\n", failures);
117 return 1; 184 return 1;
diff --git a/runtime/test/d3d12_b4g4r4a4_target_test.cpp b/runtime/test/d3d12_b4g4r4a4_target_test.cpp
new file mode 100644
index 000000000..6fce73d9e
--- /dev/null
+++ b/runtime/test/d3d12_b4g4r4a4_target_test.cpp
@@ -0,0 +1,226 @@
1// DXGI_FORMAT_B4G4R4A4_UNORM textures with D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET on Vulkan GPUs where no 4444 format
2// is a colour attachment (NVIDIA: A4R4G4B4, R4G4B4A4 and B4G4R4A4 are sampled only): the texture is an RGBA8 image,
3// which holds every 4-bit value exactly. Its RTVs render in RGBA8 and its T#s keep GFX10's 4_4_4_4 format.
4//
5// Exercises:
6// 1. GetResourceAllocationInfo and CreateCommittedResource for a render-target texture (UINT64_MAX before)
7// 2. ClearRenderTargetView through the RTV, whole view and a rectangle, read back as the RGBA8 image's texels
8// (a buffer footprint gets 4-byte texels; the test reads them as such)
9// 3. The SRV T# names 4_4_4_4, not 8_8_8_8, so shaders see the texture's own format
10// 4. A B4G4R4A4 texture without ALLOW_RENDER_TARGET still gets a size (it samples natively)
11// On a GPU where A4R4G4B4 is a colour attachment nothing is substituted and the test exits 77.
12//
13// Synthetic data only; no game files. Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation.
14#include "vk_test_device.h"
15#include "../shims/d3d12_com.h"
16#include "../src/gfx10_descriptors.h"
17
18#include <cstdint>
19#include <cstdio>
20#include <cstring>
21#include <vector>
22
23#define EXPECT(condition) do { \
24 if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \
25} while (0)
26
27namespace {
28
29namespace g = leonida::gfx10;
30
31template<class T>
32struct Ref {
33 T* p = nullptr;
34 ~Ref() { reset(); }
35 void reset() {
36 if (p) p->Release();
37 p = nullptr;
38 }
39 T* operator->() const { return p; }
40};
41
42D3D12_RESOURCE_DESC tex_desc(UINT64 width, UINT height, D3D12_RESOURCE_FLAGS flags) {
43 D3D12_RESOURCE_DESC d{};
44 d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
45 d.Width = width;
46 d.Height = height;
47 d.DepthOrArraySize = 1;
48 d.MipLevels = 1;
49 d.Format = DXGI_FORMAT_B4G4R4A4_UNORM;
50 d.SampleDesc = {1, 0};
51 d.Flags = flags;
52 return d;
53}
54
55D3D12_RESOURCE_DESC buf_desc(UINT64 bytes) {
56 D3D12_RESOURCE_DESC d{};
57 d.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
58 d.Width = bytes;
59 d.Height = 1;
60 d.DepthOrArraySize = 1;
61 d.MipLevels = 1;
62 d.SampleDesc.Count = 1;
63 d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
64 return d;
65}
66
67D3D12_RESOURCE_BARRIER transition(ID3D12Resource* resource, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) {
68 D3D12_RESOURCE_BARRIER b{};
69 b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
70 b.Transition = {resource, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, before, after};
71 return b;
72}
73
74// GFX10 T# word 1 bits 20..28: the FORMAT field.
75std::uint32_t tsharp_format(const void* descriptor) {
76 std::uint32_t words[8] = {};
77 std::memcpy(words, descriptor, sizeof(words));
78 return (words[1] >> 20) & 0x1ff;
79}
80
81} // namespace
82
83int main() {
84 vktest::Device d;
85 const auto status = d.initialize();
86 if (status == vktest::DeviceStatus::unavailable) return 77;
87 if (status != vktest::DeviceStatus::ready) return 1;
88
89 const auto format_properties =
90 d.instance_fn<PFN_vkGetPhysicalDeviceFormatProperties>("vkGetPhysicalDeviceFormatProperties");
91 VkFormatProperties props{}, rgba8{};
92 format_properties(d.physical, VK_FORMAT_A4R4G4B4_UNORM_PACK16, &props);
93 format_properties(d.physical, VK_FORMAT_R8G8B8A8_UNORM, &rgba8);
94 if (props.optimalTilingFeatures & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT) {
95 std::printf("A4R4G4B4 is a colour attachment on this GPU: nothing is substituted, skipping\n");
96 return 77;
97 }
98 if (!(rgba8.optimalTilingFeatures & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT) ||
99 !(props.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT)) {
100 std::printf("RGBA8 attachment or A4R4G4B4 sampling missing on this GPU, skipping\n");
101 return 77;
102 }
103
104 rt::d3d12::VulkanDeviceInfo info{};
105 info.get_instance_proc = d.instance_proc;
106 info.instance = d.instance;
107 info.physical = d.physical;
108 info.device = d.device;
109 info.queue = d.queue;
110 info.queue_family = d.family;
111 info.bindless = d.bindless;
112 info.bindless_partially_bound = d.partially_bound;
113 info.image_view_min_lod = d.image_view_min_lod;
114 info.host_image_copy = d.host_image_copy;
115 Ref<ID3D12Device> device;
116 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&device.p))));
117 const D3D12_HEAP_PROPERTIES def_heap{D3D12_HEAP_TYPE_DEFAULT};
118
119 // 1. A size and a resource for a render target.
120 const auto big = tex_desc(1920, 1080, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET);
121 const auto big_info = device->GetResourceAllocationInfo(0, 1, &big);
122 EXPECT(big_info.SizeInBytes != UINT64_MAX && big_info.SizeInBytes >= 1920ull * 1080 * 2);
123 Ref<ID3D12Resource> big_tex;
124 EXPECT(SUCCEEDED(device->CreateCommittedResource(&def_heap, D3D12_HEAP_FLAG_NONE, &big, D3D12_RESOURCE_STATE_COMMON,
125 nullptr, IID_PPV_ARGS(&big_tex.p))));
126 EXPECT(big_tex->GetDesc().Format == DXGI_FORMAT_B4G4R4A4_UNORM);
127
128 // 4. Without ALLOW_RENDER_TARGET it is a native 4444 image, as before.
129 const auto sampled = tex_desc(64, 32, D3D12_RESOURCE_FLAG_NONE);
130 EXPECT(device->GetResourceAllocationInfo(0, 1, &sampled).SizeInBytes != UINT64_MAX);
131
132 // 2. Clears through the render-target view.
133 constexpr UINT kW = 64, kH = 32, kPitch = 256;
134 const auto target_desc = tex_desc(kW, kH, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET);
135 Ref<ID3D12Resource> tex, readback;
136 EXPECT(SUCCEEDED(device->CreateCommittedResource(&def_heap, D3D12_HEAP_FLAG_NONE, &target_desc,
137 D3D12_RESOURCE_STATE_RENDER_TARGET, nullptr,
138 IID_PPV_ARGS(&tex.p))));
139 const D3D12_HEAP_PROPERTIES rb_heap{D3D12_HEAP_TYPE_READBACK};
140 const auto rb_desc = buf_desc(UINT64(kPitch) * kH);
141 EXPECT(SUCCEEDED(device->CreateCommittedResource(&rb_heap, D3D12_HEAP_FLAG_NONE, &rb_desc,
142 D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
143 IID_PPV_ARGS(&readback.p))));
144
145 Ref<ID3D12DescriptorHeap> rtv_heap, cpu_heap;
146 const D3D12_DESCRIPTOR_HEAP_DESC rtv_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE};
147 const D3D12_DESCRIPTOR_HEAP_DESC cpu_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE};
148 EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&rtv_desc, IID_PPV_ARGS(&rtv_heap.p))));
149 EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&cpu_desc, IID_PPV_ARGS(&cpu_heap.p))));
150 const auto rtv = rtv_heap->GetCPUDescriptorHandleForHeapStart();
151 device->CreateRenderTargetView(tex.p, nullptr, rtv);
152
153 // 3. The SRV T# names the texture's own GFX10 format.
154 const auto srv_handle = cpu_heap->GetCPUDescriptorHandleForHeapStart();
155 device->CreateShaderResourceView(tex.p, nullptr, srv_handle);
156 const std::uint32_t expected_code = g::format_from_vulkan(VK_FORMAT_A4R4G4B4_UNORM_PACK16);
157 EXPECT(expected_code != 0 && expected_code != g::format_from_vulkan(VK_FORMAT_R8G8B8A8_UNORM));
158 EXPECT(tsharp_format(reinterpret_cast<const void*>(srv_handle.ptr)) == expected_code);
159
160 Ref<ID3D12CommandQueue> queue;
161 const D3D12_COMMAND_QUEUE_DESC qd{D3D12_COMMAND_LIST_TYPE_DIRECT};
162 EXPECT(SUCCEEDED(device->CreateCommandQueue(&qd, IID_PPV_ARGS(&queue.p))));
163 Ref<ID3D12CommandAllocator> alloc;
164 EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&alloc.p))));
165 Ref<ID3D12GraphicsCommandList> list;
166 EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, alloc.p, nullptr,
167 IID_PPV_ARGS(&list.p))));
168 Ref<ID3D12Fence> fence;
169 EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p))));
170
171 // Values a 4-bit channel holds exactly (n / 15), so the RGBA8 bytes are n * 17.
172 const FLOAT outside_color[4] = {1.0f, 0.0f, 5.0f / 15, 1.0f}; // -> FF 00 55 FF
173 const FLOAT inside_color[4] = {0.0f, 10.0f / 15, 0.0f, 0.0f}; // -> 00 AA 00 00
174 const D3D12_RECT rect{8, 4, 24, 12};
175 list->ClearRenderTargetView(rtv, outside_color, 0, nullptr);
176 list->ClearRenderTargetView(rtv, inside_color, 1, &rect);
177 const auto to_src = transition(tex.p, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE);
178 list->ResourceBarrier(1, &to_src);
179 D3D12_TEXTURE_COPY_LOCATION dst{readback.p, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT};
180 dst.PlacedFootprint = {0, {DXGI_FORMAT_B4G4R4A4_UNORM, kW, kH, 1, kPitch}};
181 D3D12_TEXTURE_COPY_LOCATION src{tex.p, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX};
182 src.SubresourceIndex = 0;
183 list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
184 EXPECT(SUCCEEDED(list->Close()));
185 ID3D12CommandList* lists[] = {list.p};
186 queue->ExecuteCommandLists(1, lists);
187 EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success);
188 EXPECT(SUCCEEDED(queue->Signal(fence.p, 1)) && SUCCEEDED(fence->SetEventOnCompletion(1, nullptr)));
189
190 void* mapped = nullptr;
191 EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped)));
192 unsigned wrong = 0;
193 for (UINT y = 0; y < kH; ++y) {
194 for (UINT x = 0; x < kW; ++x) {
195 std::uint8_t texel[4] = {};
196 std::memcpy(texel, static_cast<const std::uint8_t*>(mapped) + y * kPitch + x * 4, sizeof(texel));
197 const bool inside = x >= UINT(rect.left) && x < UINT(rect.right) && y >= UINT(rect.top) &&
198 y < UINT(rect.bottom);
199 const std::uint8_t want[4] = {std::uint8_t(inside ? 0x00 : 0xFF), std::uint8_t(inside ? 0xAA : 0x00),
200 std::uint8_t(inside ? 0x00 : 0x55), std::uint8_t(inside ? 0x00 : 0xFF)};
201 if (std::memcmp(texel, want, 4) != 0 && wrong++ < 4)
202 std::fprintf(stderr, "texel (%u, %u) = %02x %02x %02x %02x, want %02x %02x %02x %02x\n", x, y,
203 texel[0], texel[1], texel[2], texel[3], want[0], want[1], want[2], want[3]);
204 }
205 }
206 readback->Unmap(0, nullptr);
207 EXPECT(wrong == 0);
208
209 readback.reset();
210 tex.reset();
211 big_tex.reset();
212 list.reset();
213 alloc.reset();
214 queue.reset();
215 fence.reset();
216 rtv_heap.reset();
217 cpu_heap.reset();
218 device.reset();
219 if (d.validation_errors()) {
220 std::fprintf(stderr, "%u Vulkan validation errors\n", d.validation_errors());
221 return 1;
222 }
223 std::printf("d3d12_b4g4r4a4_target_test: OK (RGBA8 image, render-target clears %ux%u matched, SRV T# format %u, "
224 "0 validation errors)\n", kW, kH, static_cast<unsigned>(expected_code));
225 return 0;
226}
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_close_parity_test.cpp b/runtime/test/d3d12_close_parity_test.cpp
index 0f01f261d..eaea8a955 100644
--- a/runtime/test/d3d12_close_parity_test.cpp
+++ b/runtime/test/d3d12_close_parity_test.cpp
@@ -48,9 +48,11 @@ struct Env {
48 Ref<ID3D12QueryHeap> occlusion; 48 Ref<ID3D12QueryHeap> occlusion;
49 Ref<ID3D12CommandAllocator> closed_bundle_allocator; 49 Ref<ID3D12CommandAllocator> closed_bundle_allocator;
50 Ref<ID3D12GraphicsCommandList> closed_bundle; 50 Ref<ID3D12GraphicsCommandList> closed_bundle;
51 // The list being recorded, and the same list as ID3D12GraphicsCommandList2 (null when not given). 51 // The list being recorded, and the same list as ID3D12GraphicsCommandList2 and 7 (null when not given; list7
52 // also when the device has no enhanced barriers).
52 ID3D12GraphicsCommandList* list = nullptr; 53 ID3D12GraphicsCommandList* list = nullptr;
53 ID3D12GraphicsCommandList2* list2 = nullptr; 54 ID3D12GraphicsCommandList2* list2 = nullptr;
55 ID3D12GraphicsCommandList7* list7 = nullptr;
54 56
55 bool init(ID3D12Device* d) { 57 bool init(ID3D12Device* d) {
56 device = d; 58 device = d;
@@ -163,6 +165,28 @@ constexpr auto stricter = Known::layer_stricter;
163constexpr auto looser = Known::layer_looser; 165constexpr auto looser = Known::layer_looser;
164constexpr auto match = Known::match; 166constexpr auto match = Known::match;
165 167
168// One enhanced texture barrier over every subresource of `resource`; false when the list has no enhanced barriers.
169bool texture_barrier(Env& e, ID3D12Resource* resource, D3D12_BARRIER_SYNC sync_before, D3D12_BARRIER_SYNC sync_after,
170 D3D12_BARRIER_ACCESS access_before, D3D12_BARRIER_ACCESS access_after,
171 D3D12_BARRIER_LAYOUT layout_before, D3D12_BARRIER_LAYOUT layout_after) {
172 if (!e.list7) return false;
173 D3D12_TEXTURE_BARRIER b{};
174 b.SyncBefore = sync_before;
175 b.SyncAfter = sync_after;
176 b.AccessBefore = access_before;
177 b.AccessAfter = access_after;
178 b.LayoutBefore = layout_before;
179 b.LayoutAfter = layout_after;
180 b.pResource = resource;
181 b.Subresources = {0xffffffff, 0, 0, 0, 0, 0}; // every subresource
182 D3D12_BARRIER_GROUP group{};
183 group.Type = D3D12_BARRIER_TYPE_TEXTURE;
184 group.NumBarriers = 1;
185 group.pTextureBarriers = &b;
186 e.list7->Barrier(1, &group);
187 return true;
188}
189
166std::vector<Case> cases() { 190std::vector<Case> cases() {
167 return { 191 return {
168 {"empty list", true, match, [](Env&) { return true; }}, 192 {"empty list", true, match, [](Env&) { return true; }},
@@ -200,6 +224,28 @@ std::vector<Case> cases() {
200 e.list->ResourceBarrier(1, &b))}, 224 e.list->ResourceBarrier(1, &b))},
201 {"barrier type 7", false, match, 225 {"barrier type 7", false, match,
202 CALLS(D3D12_RESOURCE_BARRIER b{}; b.Type = D3D12_RESOURCE_BARRIER_TYPE(7); e.list->ResourceBarrier(1, &b))}, 226 CALLS(D3D12_RESOURCE_BARRIER b{}; b.Type = D3D12_RESOURCE_BARRIER_TYPE(7); e.list->ResourceBarrier(1, &b))},
227 // Enhanced barriers (ID3D12GraphicsCommandList7::Barrier). LayoutAfter UNDEFINED says the contents are no
228 // longer needed; the retail title ends a depth buffer's use that way (sync DEPTH_STENCIL -> NONE, access
229 // DEPTH_STENCIL_WRITE -> NO_ACCESS), and the layer failed the list's Close for it. The WARP column of these
230 // three rows was measured on Windows 11 26340 (#984), not on the build the header names.
231 {"Barrier: depth DEPTH_STENCIL_WRITE -> COPY_SOURCE", true, match,
232 [](Env& e) {
233 return texture_barrier(e, e.depth.p, D3D12_BARRIER_SYNC_DEPTH_STENCIL, D3D12_BARRIER_SYNC_COPY,
234 D3D12_BARRIER_ACCESS_DEPTH_STENCIL_WRITE, D3D12_BARRIER_ACCESS_COPY_SOURCE,
235 D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_WRITE, D3D12_BARRIER_LAYOUT_COPY_SOURCE);
236 }},
237 {"Barrier: depth DEPTH_STENCIL_WRITE -> UNDEFINED, sync NONE after", true, match,
238 [](Env& e) {
239 return texture_barrier(e, e.depth.p, D3D12_BARRIER_SYNC_DEPTH_STENCIL, D3D12_BARRIER_SYNC_NONE,
240 D3D12_BARRIER_ACCESS_DEPTH_STENCIL_WRITE, D3D12_BARRIER_ACCESS_NO_ACCESS,
241 D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_WRITE, D3D12_BARRIER_LAYOUT_UNDEFINED);
242 }},
243 {"Barrier: texture COMMON -> UNDEFINED", true, match,
244 [](Env& e) {
245 return texture_barrier(e, e.tex.p, D3D12_BARRIER_SYNC_ALL, D3D12_BARRIER_SYNC_NONE,
246 D3D12_BARRIER_ACCESS_COMMON, D3D12_BARRIER_ACCESS_NO_ACCESS,
247 D3D12_BARRIER_LAYOUT_COMMON, D3D12_BARRIER_LAYOUT_UNDEFINED);
248 }},
203 // CopyBufferRegion 249 // CopyBufferRegion
204 {"CopyBufferRegion of 0 bytes", true, match, CALLS(e.list->CopyBufferRegion(e.buffer.p, 0, e.upload.p, 0, 0))}, 250 {"CopyBufferRegion of 0 bytes", true, match, CALLS(e.list->CopyBufferRegion(e.buffer.p, 0, e.upload.p, 0, 0))},
205 {"CopyBufferRegion past the end of the destination", false, looser, 251 {"CopyBufferRegion past the end of the destination", false, looser,
@@ -434,17 +480,24 @@ bool run_case(Env& env, const Case& c, HRESULT& close) {
434 Ref<ID3D12CommandAllocator> allocator; 480 Ref<ID3D12CommandAllocator> allocator;
435 Ref<ID3D12GraphicsCommandList> list; 481 Ref<ID3D12GraphicsCommandList> list;
436 Ref<ID3D12GraphicsCommandList2> list2; 482 Ref<ID3D12GraphicsCommandList2> list2;
483 Ref<ID3D12GraphicsCommandList7> list7;
437 CHECK(SUCCEEDED(env.device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); 484 CHECK(SUCCEEDED(env.device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p))));
438 CHECK(SUCCEEDED(env.device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, 485 CHECK(SUCCEEDED(env.device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr,
439 IID_PPV_ARGS(&list.p)))); 486 IID_PPV_ARGS(&list.p))));
440 if (FAILED(list->QueryInterface(IID_PPV_ARGS(&list2.p)))) list2.p = nullptr; 487 if (FAILED(list->QueryInterface(IID_PPV_ARGS(&list2.p)))) list2.p = nullptr;
488 D3D12_FEATURE_DATA_D3D12_OPTIONS12 options12{};
489 if (FAILED(env.device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS12, &options12, sizeof(options12))) ||
490 !options12.EnhancedBarriersSupported || FAILED(list->QueryInterface(IID_PPV_ARGS(&list7.p))))
491 list7.p = nullptr;
441 env.list = list.p; 492 env.list = list.p;
442 env.list2 = list2.p; 493 env.list2 = list2.p;
494 env.list7 = list7.p;
443 const bool recorded = c.record(env); 495 const bool recorded = c.record(env);
444 close = recorded ? list->Close() : not_run; 496 close = recorded ? list->Close() : not_run;
445 if (!recorded) list->Close(); 497 if (!recorded) list->Close();
446 env.list = nullptr; 498 env.list = nullptr;
447 env.list2 = nullptr; 499 env.list2 = nullptr;
500 env.list7 = nullptr;
448 return true; 501 return true;
449} 502}
450 503
diff --git a/runtime/test/d3d12_com_test.cpp b/runtime/test/d3d12_com_test.cpp
index d1d4bf3a6..7f07e8bdf 100644
--- a/runtime/test/d3d12_com_test.cpp
+++ b/runtime/test/d3d12_com_test.cpp
@@ -54,9 +54,18 @@ int main(int argc, char** argv) {
54 constexpr VkDeviceSize depth_offset = texels * 4, stencil_offset = depth_offset + texels * 4; 54 constexpr VkDeviceSize depth_offset = texels * 4, stencil_offset = depth_offset + texels * 4;
55 const VkBuffer buffer = d.buffer(stencil_offset + texels, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &mapped); 55 const VkBuffer buffer = d.buffer(stencil_offset + texels, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &mapped);
56 EXPECT(rt && ds && buffer && d.depth_format_usable(VK_FORMAT_D32_SFLOAT_S8_UINT)); 56 EXPECT(rt && ds && buffer && d.depth_format_usable(VK_FORMAT_D32_SFLOAT_S8_UINT));
57 // A second depth buffer, for a barrier into LAYOUT_UNDEFINED (a release) and the use that follows it.
58 const VkImage released =
59 d.image(VK_FORMAT_D32_SFLOAT_S8_UINT, size, size, 1, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT);
60 void* released_mapped = nullptr;
61 constexpr VkDeviceSize released_stencil_offset = texels * 4;
62 const VkBuffer released_buffer =
63 d.buffer(released_stencil_offset + texels, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &released_mapped);
64 EXPECT(released && released_buffer);
57 EXPECT(d.run([&](VkCommandBuffer cb) { 65 EXPECT(d.run([&](VkCommandBuffer cb) {
58 d.initial_layout(cb, rt, VK_IMAGE_ASPECT_COLOR_BIT, 1, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); 66 d.initial_layout(cb, rt, VK_IMAGE_ASPECT_COLOR_BIT, 1, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
59 d.initial_layout(cb, ds, depth_stencil_aspects, 1, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL); 67 d.initial_layout(cb, ds, depth_stencil_aspects, 1, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL);
68 d.initial_layout(cb, released, depth_stencil_aspects, 1, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL);
60 return true; 69 return true;
61 })); 70 }));
62 71
@@ -79,6 +88,13 @@ int main(int argc, char** argv) {
79 const TargetView dsv{rt::d3d12::resource_id(ds_resource), 0, 0, 1}; 88 const TargetView dsv{rt::d3d12::resource_id(ds_resource), 0, 0, 1};
80 const D3D12_CPU_DESCRIPTOR_HANDLE rtv_handle{reinterpret_cast<SIZE_T>(&rtv)}; 89 const D3D12_CPU_DESCRIPTOR_HANDLE rtv_handle{reinterpret_cast<SIZE_T>(&rtv)};
81 const D3D12_CPU_DESCRIPTOR_HANDLE dsv_handle{reinterpret_cast<SIZE_T>(&dsv)}; 90 const D3D12_CPU_DESCRIPTOR_HANDLE dsv_handle{reinterpret_cast<SIZE_T>(&dsv)};
91 auto* released_resource = reinterpret_cast<ID3D12Resource*>(std::uintptr_t{0x3000});
92 ResourceBinding released_binding = ds_binding;
93 released_binding.image = released;
94 context.add_resource(rt::d3d12::resource_id(released_resource), released_binding,
95 VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL);
96 const TargetView released_dsv{rt::d3d12::resource_id(released_resource), 0, 0, 1};
97 const D3D12_CPU_DESCRIPTOR_HANDLE released_dsv_handle{reinterpret_cast<SIZE_T>(&released_dsv)};
82 98
83 { 99 {
84 D3D12_COMMAND_QUEUE_DESC queue_desc{}; 100 D3D12_COMMAND_QUEUE_DESC queue_desc{};
@@ -338,6 +354,66 @@ int main(int argc, char** argv) {
338 EXPECT(context.layout(rt::d3d12::resource_id(ds_resource), 0) == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); 354 EXPECT(context.layout(rt::d3d12::resource_id(ds_resource), 0) == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
339 EXPECT(context.layout(rt::d3d12::resource_id(ds_resource), 1) == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); 355 EXPECT(context.layout(rt::d3d12::resource_id(ds_resource), 1) == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
340 356
357 // A barrier into LAYOUT_UNDEFINED releases a texture: its contents are no longer needed (the retail title
358 // ends a depth buffer's use this way, #984). The list closes and runs. Vulkan has no transition into
359 // UNDEFINED, so both planes stay in the layout they were in.
360 const auto released_barrier = [&](D3D12_BARRIER_SYNC sync_before, D3D12_BARRIER_SYNC sync_after,
361 D3D12_BARRIER_ACCESS access_before, D3D12_BARRIER_ACCESS access_after,
362 D3D12_BARRIER_LAYOUT layout_before, D3D12_BARRIER_LAYOUT layout_after) {
363 D3D12_TEXTURE_BARRIER b{};
364 b.SyncBefore = sync_before;
365 b.SyncAfter = sync_after;
366 b.AccessBefore = access_before;
367 b.AccessAfter = access_after;
368 b.LayoutBefore = layout_before;
369 b.LayoutAfter = layout_after;
370 b.pResource = released_resource;
371 b.Subresources = {0xffffffff, 0, 0, 0, 0, 0};
372 D3D12_BARRIER_GROUP g{};
373 g.Type = D3D12_BARRIER_TYPE_TEXTURE;
374 g.NumBarriers = 1;
375 g.pTextureBarriers = &b;
376 list->Barrier(1, &g);
377 };
378 // Executes the closed list and waits until the queue has signalled `value` on `done`.
379 const auto run_list = [&](UINT64 value) {
380 queue->ExecuteCommandLists(1, lists);
381 if (rt::d3d12::last_execute_result(queue.p) != ReplayResult::success) return false;
382 if (FAILED(queue->Signal(done.p, value))) return false;
383 const HANDLE finished = CreateEventW(nullptr, FALSE, FALSE, nullptr);
384 const bool ok = finished && SUCCEEDED(done->SetEventOnCompletion(value, finished)) &&
385 WaitForSingleObject(finished, 5000) == WAIT_OBJECT_0;
386 if (finished) CloseHandle(finished);
387 return ok;
388 };
389 const auto released_id = rt::d3d12::resource_id(released_resource);
390 const auto depth_and_stencil = D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL;
391 EXPECT(SUCCEEDED(allocator->Reset()));
392 EXPECT(SUCCEEDED(list->Reset(allocator.p, nullptr)));
393 list->ClearDepthStencilView(released_dsv_handle, depth_and_stencil, 0.25f, 0x07, 0, nullptr);
394 released_barrier(D3D12_BARRIER_SYNC_DEPTH_STENCIL, D3D12_BARRIER_SYNC_NONE,
395 D3D12_BARRIER_ACCESS_DEPTH_STENCIL_WRITE, D3D12_BARRIER_ACCESS_NO_ACCESS,
396 D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_WRITE, D3D12_BARRIER_LAYOUT_UNDEFINED);
397 EXPECT(list->Close() == S_OK);
398 EXPECT(run_list(2));
399 EXPECT(context.layout(released_id, 0) == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL);
400 EXPECT(context.layout(released_id, 1) == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL);
401
402 // Its next use starts from UNDEFINED, which discards; what is written after that is what is read back.
403 EXPECT(SUCCEEDED(allocator->Reset()));
404 EXPECT(SUCCEEDED(list->Reset(allocator.p, nullptr)));
405 released_barrier(D3D12_BARRIER_SYNC_NONE, D3D12_BARRIER_SYNC_DEPTH_STENCIL, D3D12_BARRIER_ACCESS_NO_ACCESS,
406 D3D12_BARRIER_ACCESS_DEPTH_STENCIL_WRITE, D3D12_BARRIER_LAYOUT_UNDEFINED,
407 D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_WRITE);
408 list->ClearDepthStencilView(released_dsv_handle, depth_and_stencil, 0.75f, 0x09, 0, nullptr);
409 released_barrier(D3D12_BARRIER_SYNC_DEPTH_STENCIL, D3D12_BARRIER_SYNC_COPY,
410 D3D12_BARRIER_ACCESS_DEPTH_STENCIL_WRITE, D3D12_BARRIER_ACCESS_COPY_SOURCE,
411 D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_WRITE, D3D12_BARRIER_LAYOUT_COPY_SOURCE);
412 EXPECT(list->Close() == S_OK);
413 EXPECT(run_list(3));
414 EXPECT(context.layout(released_id, 0) == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
415 EXPECT(context.layout(released_id, 1) == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
416
341 // A depth outside [0, 1] is recorded as given and the list closes, as on WARP (3ce953ae8; 417 // A depth outside [0, 1] is recorded as given and the list closes, as on WARP (3ce953ae8;
342 // d3d12_close_parity_test "ClearDepthStencilView depth 1.5", d3d12_clear_test reads the texels back). 418 // d3d12_close_parity_test "ClearDepthStencilView depth 1.5", d3d12_clear_test reads the texels back).
343 EXPECT(SUCCEEDED(allocator->Reset())); 419 EXPECT(SUCCEEDED(allocator->Reset()));
@@ -383,6 +459,10 @@ int main(int argc, char** argv) {
383 depth_offset); 459 depth_offset);
384 d.read_back(cb, ds, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_ASPECT_STENCIL_BIT, size, size, 1, buffer, 460 d.read_back(cb, ds, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_ASPECT_STENCIL_BIT, size, size, 1, buffer,
385 stencil_offset); 461 stencil_offset);
462 d.read_back(cb, released, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_ASPECT_DEPTH_BIT, size, size, 1,
463 released_buffer, 0);
464 d.read_back(cb, released, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_ASPECT_STENCIL_BIT, size, size, 1,
465 released_buffer, released_stencil_offset);
386 return true; 466 return true;
387 })); 467 }));
388 const auto* data = static_cast<const std::uint8_t*>(mapped); 468 const auto* data = static_cast<const std::uint8_t*>(mapped);
@@ -404,6 +484,19 @@ int main(int argc, char** argv) {
404 } 484 }
405 } 485 }
406 EXPECT(!mismatches); 486 EXPECT(!mismatches);
487 // The depth buffer that was released and used again holds what was written after the release.
488 const auto* released_data = static_cast<const std::uint8_t*>(released_mapped);
489 unsigned released_mismatches = 0;
490 for (std::uint32_t i = 0; i < texels; ++i) {
491 float depth;
492 std::memcpy(&depth, released_data + i * 4, 4);
493 if (depth != 0.75f || released_data[released_stencil_offset + i] != 0x09) {
494 if (released_mismatches++ < 4)
495 std::fprintf(stderr, "released texel %u: depth %f stencil 0x%02x\n", i, depth,
496 unsigned(released_data[released_stencil_offset + i]));
497 }
498 }
499 EXPECT(!released_mismatches);
407 if (d.validation_errors()) { 500 if (d.validation_errors()) {
408 std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); 501 std::fprintf(stderr, "%u validation errors\n", d.validation_errors());
409 return 1; 502 return 1;
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_execute_indirect_validation_test.cpp b/runtime/test/d3d12_execute_indirect_validation_test.cpp
index a2fb98a41..39a4961f8 100644
--- a/runtime/test/d3d12_execute_indirect_validation_test.cpp
+++ b/runtime/test/d3d12_execute_indirect_validation_test.cpp
@@ -125,8 +125,12 @@ struct Env {
125 125
126struct Case { 126struct Case {
127 const char* name; 127 const char* name;
128 bool expected_ok; // Measured on Windows 11 WARP and RTX 5090 HW D3D12 128 bool expected_ok; // What the layer answers. Outside host_varies it is also what every measured host answers.
129 std::function<void(Env&)> record; 129 std::function<void(Env&)> record;
130 // PC D3D12 runtimes disagree on this case, so a live host may answer either way and only the layer is judged.
131 // Measured: WARP and an RTX 5060 refuse all five such cases (e1ec785b2); WARP and an RTX 3080 Ti on D3D12Core
132 // 10.0.26100.9818 accept all five. The layer accepts them (d3d12_com.cpp, ExecuteIndirect, says why).
133 bool host_varies = false;
130}; 134};
131 135
132bool run_case(Env& env, const Case& c, HRESULT& out_hr) { 136bool run_case(Env& env, const Case& c, HRESULT& out_hr) {
@@ -212,12 +216,12 @@ std::vector<Case> parity_cases() {
212 [](Env& e) { e.list->ExecuteIndirect(e.draw16.p, 1, e.buf256.p, 260, nullptr, 0); }}, 216 [](Env& e) { e.list->ExecuteIndirect(e.draw16.p, 1, e.buf256.p, 260, nullptr, 0); }},
213 {"arg_offset=256 ==width (max=0 no-op)", true, 217 {"arg_offset=256 ==width (max=0 no-op)", true,
214 [](Env& e) { e.list->ExecuteIndirect(e.draw16.p, 0, e.buf256.p, 256, nullptr, 0); }}, 218 [](Env& e) { e.list->ExecuteIndirect(e.draw16.p, 0, e.buf256.p, 256, nullptr, 0); }},
215 {"arg_offset=260 >width (max=0 no-op)", false, 219 {"arg_offset=260 >width (max=0 no-op)", true,
216 [](Env& e) { e.list->ExecuteIndirect(e.draw16.p, 0, e.buf256.p, 260, nullptr, 0); }}, 220 [](Env& e) { e.list->ExecuteIndirect(e.draw16.p, 0, e.buf256.p, 260, nullptr, 0); }, true},
217 {"arg_offset=U64MAX-3 wrap (max=1)", false, 221 {"arg_offset=U64MAX-3 wrap (max=1)", false,
218 [=](Env& e) { e.list->ExecuteIndirect(e.draw16.p, 1, e.buf256.p, kU64Max - 3, nullptr, 0); }}, 222 [=](Env& e) { e.list->ExecuteIndirect(e.draw16.p, 1, e.buf256.p, kU64Max - 3, nullptr, 0); }},
219 {"arg_offset=U64MAX-3 aligned (max=0 no-op)", false, 223 {"arg_offset=U64MAX-3 aligned (max=0 no-op)", true,
220 [=](Env& e) { e.list->ExecuteIndirect(e.draw16.p, 0, e.buf256.p, kU64Max - 3, nullptr, 0); }}, 224 [=](Env& e) { e.list->ExecuteIndirect(e.draw16.p, 0, e.buf256.p, kU64Max - 3, nullptr, 0); }, true},
221 {"arg_offset=U64MAX unaligned+wrap (max=1)", false, 225 {"arg_offset=U64MAX unaligned+wrap (max=1)", false,
222 [=](Env& e) { e.list->ExecuteIndirect(e.draw16.p, 1, e.buf256.p, kU64Max, nullptr, 0); }}, 226 [=](Env& e) { e.list->ExecuteIndirect(e.draw16.p, 1, e.buf256.p, kU64Max, nullptr, 0); }},
223 {"arg_offset=240 max=2 cnt=null (OOB)", false, 227 {"arg_offset=240 max=2 cnt=null (OOB)", false,
@@ -233,17 +237,23 @@ std::vector<Case> parity_cases() {
233 {"arg_buf width=3 (max=1 OOB)", false, 237 {"arg_buf width=3 (max=1 OOB)", false,
234 [](Env& e) { e.list->ExecuteIndirect(e.draw16.p, 1, e.buf3.p, 0, nullptr, 0); }}, 238 [](Env& e) { e.list->ExecuteIndirect(e.draw16.p, 1, e.buf3.p, 0, nullptr, 0); }},
235 239
236 // Padded stride: the host bounds max_count * stride, not (max_count - 1) * stride + record_size, so a 240 // Padded stride: the last record fits at the end of the buffer while its stride runs past it. A runtime
237 // record that fits at the end of the buffer while its stride runs past it is refused 241 // that bounds max_count * stride refuses these; one that bounds (max_count - 1) * stride + record_size
238 {"draw stride=20 off=240 max=1 (240+20>256)", false, 242 // accepts them, and so does the layer.
239 [](Env& e) { e.list->ExecuteIndirect(e.draw20.p, 1, e.buf256.p, 240, nullptr, 0); }}, 243 {"draw stride=20 off=240 max=1 (240+16==256)", true,
240 {"draw stride=20 off=220 max=2 (220+40>256)", false, 244 [](Env& e) { e.list->ExecuteIndirect(e.draw20.p, 1, e.buf256.p, 240, nullptr, 0); }, true},
241 [](Env& e) { e.list->ExecuteIndirect(e.draw20.p, 2, e.buf256.p, 220, nullptr, 0); }}, 245 {"draw stride=20 off=220 max=2 (220+20+16==256)", true,
242 {"dispatch stride=20 off=244 max=1 (244+20>256)", false, 246 [](Env& e) { e.list->ExecuteIndirect(e.draw20.p, 2, e.buf256.p, 220, nullptr, 0); }, true},
247 {"dispatch stride=20 off=244 max=1 (244+12==256)", true,
243 [](Env& e) { 248 [](Env& e) {
244 e.bind_compute_if_available(); 249 e.bind_compute_if_available();
245 e.list->ExecuteIndirect(e.dispatch20.p, 1, e.buf256.p, 244, nullptr, 0); 250 e.list->ExecuteIndirect(e.dispatch20.p, 1, e.buf256.p, 244, nullptr, 0);
246 }}, 251 }, true},
252 // One byte group further and the record itself no longer fits: refused under either rule.
253 {"draw stride=20 off=244 max=1 (244+16>256)", false,
254 [](Env& e) { e.list->ExecuteIndirect(e.draw20.p, 1, e.buf256.p, 244, nullptr, 0); }},
255 {"draw stride=20 off=224 max=2 (224+20+16>256)", false,
256 [](Env& e) { e.list->ExecuteIndirect(e.draw20.p, 2, e.buf256.p, 224, nullptr, 0); }},
247 {"draw_indexed stride=24 off=240 max=1 (OOB)", false, 257 {"draw_indexed stride=24 off=240 max=1 (OOB)", false,
248 [](Env& e) { e.list->ExecuteIndirect(e.draw_indexed24.p, 1, e.buf256.p, 240, nullptr, 0); }}, 258 [](Env& e) { e.list->ExecuteIndirect(e.draw_indexed24.p, 1, e.buf256.p, 240, nullptr, 0); }},
249 259
@@ -304,6 +314,11 @@ bool run_positive_gpu_dispatch(Env& env) {
304 // Exact-fit indirect dispatch (244 + 12 == 256) plus max_command_count == 0 no-op at the buffer's end. 314 // Exact-fit indirect dispatch (244 + 12 == 256) plus max_command_count == 0 no-op at the buffer's end.
305 list->ExecuteIndirect(env.dispatch12.p, 1, args.p, 244, nullptr, 0); 315 list->ExecuteIndirect(env.dispatch12.p, 1, args.p, 244, nullptr, 0);
306 list->ExecuteIndirect(env.dispatch12.p, 0, args.p, 256, nullptr, 0); 316 list->ExecuteIndirect(env.dispatch12.p, 0, args.p, 256, nullptr, 0);
317 // The two shapes PC runtimes split on, which the layer accepts: the same record read through a padded stride
318 // that runs past the buffer, and a zero count at an offset outside it. Replayed with validation on, so a rule
319 // that let Vulkan read past the buffer would show up as a validation error below.
320 list->ExecuteIndirect(env.dispatch20.p, 1, args.p, 244, nullptr, 0);
321 list->ExecuteIndirect(env.dispatch12.p, 0, args.p, 260, nullptr, 0);
307 CHECK(SUCCEEDED(list->Close())); 322 CHECK(SUCCEEDED(list->Close()));
308 323
309 ID3D12CommandList* lists[] = {list.p}; 324 ID3D12CommandList* lists[] = {list.p};
@@ -430,6 +445,7 @@ int main() {
430 std::filesystem::remove_all(fixture, ec); 445 std::filesystem::remove_all(fixture, ec);
431 446
432 unsigned failures = 0; 447 unsigned failures = 0;
448 unsigned varied_accepted = 0, varied_refused = 0; // live host answers on the host_varies cases
433 std::printf("%-48s | %-10s | %-10s | %-10s\n", "case", "layer", "WARP", hw_ran ? hw_name.c_str() : "HW"); 449 std::printf("%-48s | %-10s | %-10s | %-10s\n", "case", "layer", "WARP", hw_ran ? hw_name.c_str() : "HW");
434 for (std::size_t i = 0; i < table.size(); ++i) { 450 for (std::size_t i = 0; i < table.size(); ++i) {
435 const bool layer_ok = SUCCEEDED(layer_hr[i]); 451 const bool layer_ok = SUCCEEDED(layer_hr[i]);
@@ -440,12 +456,26 @@ int main() {
440 static_cast<unsigned long>(layer_hr[i]), 456 static_cast<unsigned long>(layer_hr[i]),
441 warp_ran ? (SUCCEEDED(warp_hr[i]) ? "S_OK" : "FAIL") : (warp_ok ? "(S_OK)" : "(FAIL)"), 457 warp_ran ? (SUCCEEDED(warp_hr[i]) ? "S_OK" : "FAIL") : (warp_ok ? "(S_OK)" : "(FAIL)"),
442 hw_ran ? (SUCCEEDED(hw_hr[i]) ? "S_OK" : "FAIL") : (hw_ok ? "(S_OK)" : "(FAIL)")); 458 hw_ran ? (SUCCEEDED(hw_hr[i]) ? "S_OK" : "FAIL") : (hw_ok ? "(S_OK)" : "(FAIL)"));
459 if (table[i].host_varies) {
460 // Runtimes split on this case: the hosts are reported, the layer alone has to answer as expected.
461 if (warp_ran) ++(warp_ok ? varied_accepted : varied_refused);
462 if (hw_ran) ++(hw_ok ? varied_accepted : varied_refused);
463 if (layer_ok != table[i].expected_ok) {
464 std::fprintf(stderr, "FAIL %s: layer=%d expected=%d (hosts differ by D3D12 runtime: warp=%d hw=%d)\n",
465 table[i].name, int(layer_ok), int(table[i].expected_ok), int(warp_ok), int(hw_ok));
466 ++failures;
467 }
468 continue;
469 }
443 if (layer_ok != warp_ok || layer_ok != hw_ok || layer_ok != table[i].expected_ok) { 470 if (layer_ok != warp_ok || layer_ok != hw_ok || layer_ok != table[i].expected_ok) {
444 std::fprintf(stderr, "FAIL %s: layer=%d warp=%d hw=%d expected=%d\n", 471 std::fprintf(stderr, "FAIL %s: layer=%d warp=%d hw=%d expected=%d\n",
445 table[i].name, int(layer_ok), int(warp_ok), int(hw_ok), int(table[i].expected_ok)); 472 table[i].name, int(layer_ok), int(warp_ok), int(hw_ok), int(table[i].expected_ok));
446 ++failures; 473 ++failures;
447 } 474 }
448 } 475 }
476 if (varied_accepted || varied_refused)
477 std::printf("runtime-dependent cases: the live hosts accepted %u and refused %u answers; the layer accepts "
478 "all of them\n", varied_accepted, varied_refused);
449 479
450 const unsigned validation_errors = vk.validation_errors() - errors_before; 480 const unsigned validation_errors = vk.validation_errors() - errors_before;
451 if (validation_errors) { 481 if (validation_errors) {
diff --git a/runtime/test/d3d12_heap_properties_test.cpp b/runtime/test/d3d12_heap_properties_test.cpp
index 39ab881af..1033e01e7 100644
--- a/runtime/test/d3d12_heap_properties_test.cpp
+++ b/runtime/test/d3d12_heap_properties_test.cpp
@@ -5,11 +5,14 @@
5// the node masks and DENY bits of a few committed resources; this test covers the rest. Every value is recorded, 5// the node masks and DENY bits of a few committed resources; this test covers the rest. Every value is recorded,
6// with whether the call wrote its outputs (they start as a sentinel), and the two records must be the same. A 6// with whether the call wrote its outputs (they start as a sentinel), and the two records must be the same. A
7// resource one device refuses to create is reported and its steps aren't compared. No shaders or game data. Skips 7// resource one device refuses to create is reported and its steps aren't compared. No shaders or game data. Skips
8// (77) without a Vulkan GPU or the standalone device; without a host D3D12 device only the layer's own record is 8// (77) without a Vulkan GPU or the standalone device. The layer's record is first checked on its own (layer_wrong:
9// printed. The host runs on the layer's adapter (host_adapter.h; LEONIDA_HOST_ADAPTER picks another, "warp" WARP). 9// what D3D12 documents for the call), on every host; without a host D3D12 device that is all that is checked, and so
10// it is under Wine, whose host is vkd3d and reports other heap flags (host_wine.h). The host runs on
11// the layer's adapter (host_adapter.h; LEONIDA_HOST_ADAPTER picks another, "warp" WARP).
10// Set LEONIDA_D3D49_VERBOSE=1 to print every value. 12// Set LEONIDA_D3D49_VERBOSE=1 to print every value.
11#include "../shims/d3d12_com.h" 13#include "../shims/d3d12_com.h"
12#include "host_adapter.h" 14#include "host_adapter.h"
15#include "host_wine.h"
13 16
14#include <cstdint> 17#include <cstdint>
15#include <cstdio> 18#include <cstdio>
@@ -227,6 +230,85 @@ void run(ID3D12Device* device, Record& out) {
227 } 230 }
228} 231}
229 232
233// What the layer has to answer whatever the host is, checked on its record alone so that a run with no host to
234// compare with (no host device, or Wine's) still fails on a wrong answer. D3D12 documents GetHeapProperties for
235// committed and placed resources, with either output optional, and not for reserved ones. So for every committed or
236// placed resource the layer created: the call succeeds with both outputs, with the properties alone and with the
237// flags alone; Type is the heap type it was created with and, for a custom heap, so are the CPU page property and the
238// memory pool; and a call asking for one output reports what the call asking for both does, and every output asked
239// for is written. For a reserved resource the call fails. The values D3D12 derives itself (the flags a committed
240// resource reports, the node masks) are the host comparison's. Returns the number of wrong answers; `checked` counts
241// the resources looked at.
242int layer_wrong(const Record& ours, int* checked) {
243 int wrong = 0;
244 const auto find = [&](const std::string& name, std::uint64_t* value) {
245 for (std::size_t i = 0; i < ours.names.size(); ++i)
246 if (ours.names[i] == name) {
247 *value = ours.values[i];
248 return true;
249 }
250 return false;
251 };
252 const auto expect = [&](const std::string& name, std::uint64_t want, const char* why) {
253 std::uint64_t got = 0;
254 const bool found = find(name, &got);
255 if (found && got == want) return;
256 if (found)
257 std::printf("heap properties %s: the layer answers 0x%llx, 0x%llx expected (%s)\n", name.c_str(),
258 static_cast<unsigned long long>(got), static_cast<unsigned long long>(want), why);
259 else
260 std::printf("heap properties %s: missing from the layer's record (%s)\n", name.c_str(), why);
261 ++wrong;
262 };
263 // A value from a call asking for one output: it has to be what the call asking for both gave, and the call has
264 // to have written it (the outputs start as the sentinel), which holds the other call to having written it too.
265 const auto same = [&](const std::string& one, const std::string& both) {
266 std::uint64_t a = 0, b = 0;
267 const bool found = find(one, &a) && find(both, &b);
268 if (found && a == b && std::uint32_t(a) != kSentinel) return;
269 if (found && a == b)
270 std::printf("heap properties %s: the layer did not write it, with both outputs asked for either\n",
271 one.c_str());
272 else
273 std::printf("heap properties %s: the layer answers 0x%llx where the call with both outputs gave "
274 "0x%llx\n", one.c_str(), static_cast<unsigned long long>(a),
275 static_cast<unsigned long long>(b));
276 ++wrong;
277 };
278 static const char* const kPropertyFields[] = {"Type", "CPUPageProperty", "MemoryPoolPreference",
279 "CreationNodeMask", "VisibleNodeMask"};
280 for (const Case& c : cases()) {
281 const std::string name = c.name;
282 std::uint64_t created = 0;
283 if (!find(name + ": created", &created) || FAILED(HRESULT(std::uint32_t(created)))) continue;
284 if (c.kind == Kind::reserved) {
285 for (const char* shape : {"", ", properties only", ", flags only"}) {
286 std::uint64_t hr = 0;
287 if (find(name + shape + ": hr", &hr) && FAILED(HRESULT(std::uint32_t(hr)))) continue;
288 std::printf("heap properties %s%s: the layer answers 0x%llx for a reserved resource, a failure "
289 "expected\n", name.c_str(), shape, static_cast<unsigned long long>(hr));
290 ++wrong;
291 }
292 continue;
293 }
294 ++*checked;
295 for (const char* shape : {"", ", properties only", ", flags only"})
296 expect(name + shape + ": hr", std::uint32_t(S_OK), "a committed or placed resource has heap properties");
297 for (const char* shape : {"", ", properties only"}) {
298 expect(name + shape + ": Type", std::uint32_t(c.props.Type), "the heap type it was created with");
299 if (c.props.Type != D3D12_HEAP_TYPE_CUSTOM) continue;
300 expect(name + shape + ": CPUPageProperty", std::uint32_t(c.props.CPUPageProperty),
301 "the custom heap's CPU page property");
302 expect(name + shape + ": MemoryPoolPreference", std::uint32_t(c.props.MemoryPoolPreference),
303 "the custom heap's memory pool");
304 }
305 for (const char* field : kPropertyFields)
306 same(name + ", properties only: " + field, name + ": " + field);
307 same(name + ", flags only: flags", name + ": flags");
308 }
309 return wrong;
310}
311
230} // namespace 312} // namespace
231 313
232int main() { 314int main() {
@@ -238,6 +320,20 @@ int main() {
238 const bool verbose = GetEnvironmentVariableA("LEONIDA_D3D49_VERBOSE", nullptr, 0) > 0; 320 const bool verbose = GetEnvironmentVariableA("LEONIDA_D3D49_VERBOSE", nullptr, 0) > 0;
239 Record ours; 321 Record ours;
240 run(device.p, ours); 322 run(device.p, ours);
323 // The layer's own answers first, on every host: the comparison below needs a host, and Wine's is not one.
324 int layer_checked = 0;
325 const int layer_wrong_answers = layer_wrong(ours, &layer_checked);
326 std::printf("heap properties: the layer's answers for %d committed and placed resources checked on their own, "
327 "%d wrong\n", layer_checked, layer_wrong_answers);
328 EXPECT(layer_checked > 0);
329 EXPECT(layer_wrong_answers == 0);
330 // With no host to compare with, LEONIDA_D3D49_VERBOSE still prints what the layer recorded.
331 const auto print_ours = [&] {
332 if (!verbose) return;
333 for (std::size_t i = 0; i < ours.names.size(); ++i)
334 std::printf("heap properties %s: ours 0x%llx\n", ours.names[i].c_str(),
335 static_cast<unsigned long long>(ours.values[i]));
336 };
241 337
242 const HMODULE d3d12 = LoadLibraryExA("d3d12.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); 338 const HMODULE d3d12 = LoadLibraryExA("d3d12.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
243 const auto create_host = d3d12 ? reinterpret_cast<PFN_D3D12_CREATE_DEVICE>( 339 const auto create_host = d3d12 ? reinterpret_cast<PFN_D3D12_CREATE_DEVICE>(
@@ -251,15 +347,17 @@ int main() {
251 // No factory, or no adapter for the pass (LEONIDA_HOST_ADAPTER=warp without WARP): don't compare, rather than 347 // No factory, or no adapter for the pass (LEONIDA_HOST_ADAPTER=warp without WARP): don't compare, rather than
252 // fall back to the default adapter and compare with a GPU the layer doesn't run on. 348 // fall back to the default adapter and compare with a GPU the layer doesn't run on.
253 const bool have_adapter = 349 const bool have_adapter =
254 SUCCEEDED(CreateDXGIFactory1(IID_PPV_ARGS(&factory.p))) && 350 !hostwine::host_is_wine() && SUCCEEDED(CreateDXGIFactory1(IID_PPV_ARGS(&factory.p))) &&
255 hostadapter::reference(factory.p, &luid, hostadapter::wanted() == "warp", &adapter.p, host_name); 351 hostadapter::reference(factory.p, &luid, hostadapter::wanted() == "warp", &adapter.p, host_name);
256 Ref<ID3D12Device> host; 352 Ref<ID3D12Device> host;
257 if (!have_adapter) { 353 if (!have_adapter) {
258 std::printf("heap properties: no host adapter to compare with; %zu values recorded, not compared\n", 354 std::printf("heap properties: no host adapter to compare with; %zu values recorded, not compared\n",
259 ours.values.size()); 355 ours.values.size());
356 print_ours();
260 } else if (!create_host || FAILED(create_host(adapter.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)))) { 357 } else if (!create_host || FAILED(create_host(adapter.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)))) {
261 std::printf("heap properties: no host D3D12 device to compare with; %zu values recorded, not compared\n", 358 std::printf("heap properties: no host D3D12 device to compare with; %zu values recorded, not compared\n",
262 ours.values.size()); 359 ours.values.size());
360 print_ours();
263 } else { 361 } else {
264 Record theirs; 362 Record theirs;
265 run(host.p, theirs); 363 run(host.p, theirs);
diff --git a/runtime/test/d3d12_indirect_dispatch_count_test.cpp b/runtime/test/d3d12_indirect_dispatch_count_test.cpp
index 62b5f4988..9a97032e8 100644
--- a/runtime/test/d3d12_indirect_dispatch_count_test.cpp
+++ b/runtime/test/d3d12_indirect_dispatch_count_test.cpp
@@ -1,7 +1,9 @@
1// D3D12 ExecuteIndirect with a GPU count buffer and one DISPATCH argument per record. 1// D3D12 ExecuteIndirect with a GPU count buffer and one DISPATCH argument per record.
2// The same synthetic workload runs on native WARP and on the Vulkan layer, with actual GPU readback. 2// The same synthetic workload runs on native WARP and on the Vulkan layer, with actual GPU readback.
3// Under Wine the WARP runs are skipped (host_wine.h) and the layer is checked against the expected result alone.
3// Set LEONIDA_VK_VALIDATION=1 to enable Vulkan core and synchronization validation. 4// Set LEONIDA_VK_VALIDATION=1 to enable Vulkan core and synchronization validation.
4#include "vk_test_device.h" 5#include "vk_test_device.h"
6#include "host_wine.h"
5#include "shader_fixture_path.h" 7#include "shader_fixture_path.h"
6#include "d3d12_test_shaders.h" 8#include "d3d12_test_shaders.h"
7#include "../shims/d3d12_com.h" 9#include "../shims/d3d12_com.h"
@@ -177,24 +179,35 @@ std::string module_version(const wchar_t* name) {
177} // namespace 179} // namespace
178 180
179int main() { 181int main() {
180 using Compile = decltype(&D3DCompile); 182 // Wine has no WARP (its host is vkd3d on the GPU), and its D3DCompile has no RWByteAddressBuffer::InterlockedAdd
181 const HMODULE compiler = LoadLibraryExW(L"d3dcompiler_47.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); 183 // (E5005 on wine-staging 11.21), so the reference shader did not build and the test ended before the layer ran.
182 if (!compiler) return 77; 184 // The host runs are skipped there; the layer is still checked against expected().
183 const auto compile = reinterpret_cast<Compile>(GetProcAddress(compiler, "D3DCompile")); 185 const bool compare_host = !hostwine::host_is_wine();
184 if (!compile) return 77; 186 std::vector<std::uint8_t> native_code;
185 Ref<ID3DBlob> native, errors;
186 if (FAILED(compile(native_shader, std::strlen(native_shader), nullptr, nullptr, nullptr,
187 "main", "cs_5_0", 0, 0, &native.p, &errors.p)) || !native.p)
188 return 1;
189 const auto* native_bytes = static_cast<const std::uint8_t*>(native->GetBufferPointer());
190 const std::vector<std::uint8_t> native_code(native_bytes, native_bytes + native->GetBufferSize());
191 Ref<IDXGIFactory4> factory; 187 Ref<IDXGIFactory4> factory;
192 Ref<IDXGIAdapter> warp; 188 Ref<IDXGIAdapter> warp;
193 Ref<ID3D12Device> host; 189 Ref<ID3D12Device> host;
194 if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory.p))) || 190 if (compare_host) {
195 FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&warp.p))) || 191 using Compile = decltype(&D3DCompile);
196 FAILED(D3D12CreateDevice(warp.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)))) 192 const HMODULE compiler = LoadLibraryExW(L"d3dcompiler_47.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
197 return 77; 193 if (!compiler) return 77;
194 const auto compile = reinterpret_cast<Compile>(GetProcAddress(compiler, "D3DCompile"));
195 if (!compile) return 77;
196 Ref<ID3DBlob> native, errors;
197 if (FAILED(compile(native_shader, std::strlen(native_shader), nullptr, nullptr, nullptr,
198 "main", "cs_5_0", 0, 0, &native.p, &errors.p)) || !native.p) {
199 std::fprintf(stderr, "D3DCompile of the reference shader failed%s%.*s\n", errors.p ? ": " : "",
200 errors.p ? int(errors->GetBufferSize()) : 0,
201 errors.p ? static_cast<const char*>(errors->GetBufferPointer()) : "");
202 return 1;
203 }
204 const auto* native_bytes = static_cast<const std::uint8_t*>(native->GetBufferPointer());
205 native_code.assign(native_bytes, native_bytes + native->GetBufferSize());
206 if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory.p))) ||
207 FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&warp.p))) ||
208 FAILED(D3D12CreateDevice(warp.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p))))
209 return 77;
210 }
198 211
199 vktest::Device vk; 212 vktest::Device vk;
200 vk.request_buffer_device_address = true; 213 vk.request_buffer_device_address = true;
@@ -237,12 +250,13 @@ int main() {
237 for (bool update : {false, true}) { 250 for (bool update : {false, true}) {
238 std::array<UINT, 2> native_result{}, layer_result{}; 251 std::array<UINT, 2> native_result{}, layer_result{};
239 const auto want = expected(count, update); 252 const auto want = expected(count, update);
240 if (!run(host.p, native_code, count, update, native_result, false) || 253 if (!compare_host) native_result = want; // no host run: the layer alone is held to `want`
254 if ((compare_host && !run(host.p, native_code, count, update, native_result, false)) ||
241 !run(layer.p, container, count, update, layer_result, true) || layer_result != want || 255 !run(layer.p, container, count, update, layer_result, true) || layer_result != want ||
242 (native_result != want && !(update && native_result == expected(count, update, count)))) { 256 (native_result != want && !(update && native_result == expected(count, update, count)))) {
243 std::fprintf(stderr, "count %u update %d: host %u/%u, layer %u/%u, expected %u/%u\n", 257 std::fprintf(stderr, "count %u update %d: host %u/%u%s, layer %u/%u, expected %u/%u\n",
244 count, int(update), native_result[0], native_result[1], 258 count, int(update), native_result[0], native_result[1],
245 layer_result[0], layer_result[1], want[0], want[1]); 259 compare_host ? "" : " (not run)", layer_result[0], layer_result[1], want[0], want[1]);
246 return 1; 260 return 1;
247 } 261 }
248 if (native_result != want) { 262 if (native_result != want) {
@@ -262,7 +276,9 @@ int main() {
262 std::fprintf(stderr, "validation errors: %u\n", vk.validation_errors()); 276 std::fprintf(stderr, "validation errors: %u\n", vk.validation_errors());
263 return 1; 277 return 1;
264 } 278 }
265 std::printf("counted ExecuteIndirect(DISPATCH): %u native WARP / Vulkan GPU comparisons passed; " 279 std::printf("counted ExecuteIndirect(DISPATCH): %u %s passed; "
266 "count=0,1,max,>max, nonzero offsets and GPU count overwrite, no validation errors\n", cases); 280 "count=0,1,max,>max, nonzero offsets and GPU count overwrite, no validation errors\n", cases,
281 compare_host ? "native WARP / Vulkan GPU comparisons"
282 : "Vulkan GPU results against the expected values (no WARP runs under Wine)");
267 return 0; 283 return 0;
268} 284}
diff --git a/runtime/test/d3d12_indirect_rt_test.cpp b/runtime/test/d3d12_indirect_rt_test.cpp
index 6a921d820..f7ecfa2f5 100644
--- a/runtime/test/d3d12_indirect_rt_test.cpp
+++ b/runtime/test/d3d12_indirect_rt_test.cpp
@@ -10,6 +10,7 @@
10#include "vulkan_loader.h" 10#include "vulkan_loader.h"
11#include "../src/vulkan_device_filter.h" 11#include "../src/vulkan_device_filter.h"
12 12
13#include <algorithm>
13#include <cmath> 14#include <cmath>
14#include <cstdint> 15#include <cstdint>
15#include <cstdio> 16#include <cstdio>
@@ -818,9 +819,10 @@ int main() {
818 } 819 }
819 const UINT64 compact_blas_bytes = 820 const UINT64 compact_blas_bytes =
820 std::max<UINT64>(blas_compact_info.ResultDataMaxSizeInBytes, compact_vk_sizes.accelerationStructureSize); 821 std::max<UINT64>(blas_compact_info.ResultDataMaxSizeInBytes, compact_vk_sizes.accelerationStructureSize);
822 // Not nested std::max: MSVC 19.52 at /O2 reads the inner call's result from a stack slot it never wrote.
821 const UINT64 compact_scratch_bytes = std::max<UINT64>( 823 const UINT64 compact_scratch_bytes = std::max<UINT64>(
822 tlas_info.ScratchDataSizeInBytes, 824 {tlas_info.ScratchDataSizeInBytes, blas_compact_info.ScratchDataSizeInBytes,
823 std::max<UINT64>(blas_compact_info.ScratchDataSizeInBytes, compact_vk_sizes.buildScratchSize)); 825 compact_vk_sizes.buildScratchSize});
824 826
825 auto compact_scratch_desc = make_buf_desc(align256(compact_scratch_bytes) + 256u, 827 auto compact_scratch_desc = make_buf_desc(align256(compact_scratch_bytes) + 256u,
826 D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); 828 D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS);
diff --git a/runtime/test/d3d12_mesh_test.cpp b/runtime/test/d3d12_mesh_test.cpp
index 590d3507b..aae2fb162 100644
--- a/runtime/test/d3d12_mesh_test.cpp
+++ b/runtime/test/d3d12_mesh_test.cpp
@@ -140,6 +140,7 @@ int main() {
140 info.buffer_device_address = true; 140 info.buffer_device_address = true;
141 info.shader_dir = library.string(); 141 info.shader_dir = library.string();
142 info.mesh_shader = mesh; 142 info.mesh_shader = mesh;
143 info.mesh_shader_queries = mesh && d.mesh_shader_queries;
143 info.pipeline_statistics_query = d.pipeline_statistics_query; 144 info.pipeline_statistics_query = d.pipeline_statistics_query;
144 return info; 145 return info;
145 }; 146 };
@@ -427,8 +428,15 @@ int main() {
427 // query 2 the two vertex draws alone. A mesh draw has no input assembly or vertex shader, so those fields 428 // query 2 the two vertex draws alone. A mesh draw has no input assembly or vertex shader, so those fields
428 // count only the two full-screen triangles (3 vertices, 1 primitive each). How many clipping and pixel 429 // count only the two full-screen triangles (3 vertices, 1 primitive each). How many clipping and pixel
429 // shader invocations a draw makes is the driver's (RADV's PSInvocations is not the pixel count), so query 430 // shader invocations a draw makes is the driver's (RADV's PSInvocations is not the pixel count), so query
430 // 0 is checked against query 2: more of both is the mesh segment's share. Under LEONIDA_VK_VALIDATION=1 the 431 // 0 is checked against query 2: more pixel shader invocations is the mesh segment's share. A mesh segment
431 // run must stay free of VUID-vkCmdDrawMeshTasksEXT-pipelineStatistics-07076. 432 // runs in a pool that counts the fragment and compute invocations only, because
433 // VUID-vkCmdDrawMeshTasksEXT-pipelineStatistics-07076 leaves the clipping counters out of a pool that is
434 // active during a mesh draw; D3D12 counts the clipping invocations and primitives of a mesh pipeline, so
435 // those two fields read 0 here. Under LEONIDA_VK_VALIDATION=1 the run must stay free of the VUID.
436 // Where the device has the meshShaderQueries feature, the clipping invocations of a mesh segment come
437 // from a mesh-primitives query instead (D3D-MESH-CLIPPING-COUNTER): the number of primitives the mesh
438 // shader emitted that reached the fragment shader. How many that is depends on the driver, so the counts
439 // are compared with each other and not written down.
432 if (d.pipeline_statistics_query) { 440 if (d.pipeline_statistics_query) {
433 const D3D12_QUERY_HEAP_DESC statistics_desc{D3D12_QUERY_HEAP_TYPE_PIPELINE_STATISTICS, 3, 0}; 441 const D3D12_QUERY_HEAP_DESC statistics_desc{D3D12_QUERY_HEAP_TYPE_PIPELINE_STATISTICS, 3, 0};
434 Ref<ID3D12QueryHeap> statistics; 442 Ref<ID3D12QueryHeap> statistics;
@@ -494,11 +502,26 @@ int main() {
494 EXPECT(vertex_only.IAVertices == 6 && vertex_only.IAPrimitives == 2); 502 EXPECT(vertex_only.IAVertices == 6 && vertex_only.IAPrimitives == 2);
495 EXPECT(mixed.GSInvocations == 0 && mixed.GSPrimitives == 0 && mixed.HSInvocations == 0 && 503 EXPECT(mixed.GSInvocations == 0 && mixed.GSPrimitives == 0 && mixed.HSInvocations == 0 &&
496 mixed.DSInvocations == 0 && mixed.CSInvocations == 0); 504 mixed.DSInvocations == 0 && mixed.CSInvocations == 0);
497 EXPECT(mixed.CInvocations > vertex_only.CInvocations && mixed.PSInvocations > vertex_only.PSInvocations); 505 // The clipping invocations of the mesh segments (D3D-MESH-CLIPPING-COUNTER). Without the feature they
506 // read 0; with it they are the mesh-primitives count of those segments.
507 const auto mesh_clipping = mixed.CInvocations - vertex_only.CInvocations;
508 if (d.mesh_shader_queries) {
509 // The count has to be wired up, not merely self-consistent. A layer that reported the feature but
510 // never created the third pool would leave both counts at 0, and 0 >= 0 would still hold. How many
511 // primitives the mesh shader emits is the driver's, so ask for a positive count and not for a
512 // number: the mesh draw above fills the top-left quadrant, so it emits at least one.
513 EXPECT(mesh_clipping >= mesh_only.CInvocations);
514 EXPECT(mesh_only.CInvocations > 0);
515 } else {
516 EXPECT(mesh_clipping == 0);
517 }
518 EXPECT(mixed.PSInvocations > vertex_only.PSInvocations);
498 EXPECT(mesh_only.IAVertices == 0 && mesh_only.IAPrimitives == 0 && mesh_only.VSInvocations == 0 && 519 EXPECT(mesh_only.IAVertices == 0 && mesh_only.IAPrimitives == 0 && mesh_only.VSInvocations == 0 &&
499 mesh_only.GSInvocations == 0 && mesh_only.GSPrimitives == 0 && mesh_only.HSInvocations == 0 && 520 mesh_only.GSInvocations == 0 && mesh_only.GSPrimitives == 0 && mesh_only.HSInvocations == 0 &&
500 mesh_only.DSInvocations == 0 && mesh_only.CSInvocations == 0); 521 mesh_only.DSInvocations == 0 && mesh_only.CSInvocations == 0);
501 EXPECT(mesh_only.CInvocations > 0 && mesh_only.PSInvocations > 0); 522 // Vulkan has no clipped-primitive counter, so the clipping primitives of a mesh segment stay 0.
523 EXPECT(mesh_only.CPrimitives == 0 && mesh_only.PSInvocations > 0);
524 if (!d.mesh_shader_queries) EXPECT(mesh_only.CInvocations == 0);
502 } else { 525 } else {
503 std::printf("pipelineStatisticsQuery not available: the D3D-291 statistics check is skipped\n"); 526 std::printf("pipelineStatisticsQuery not available: the D3D-291 statistics check is skipped\n");
504 } 527 }
diff --git a/runtime/test/d3d12_multi_viewport_test.cpp b/runtime/test/d3d12_multi_viewport_test.cpp
new file mode 100644
index 000000000..a05b713af
--- /dev/null
+++ b/runtime/test/d3d12_multi_viewport_test.cpp
@@ -0,0 +1,484 @@
1// Live GPU host-parity test for multi-viewport and multi-scissor rendering (D3D-MULTI-VIEWPORT):
2// - RSSetViewports(1..16) and RSSetScissorRects(1..16) -> vkCmdSetViewportWithCount / vkCmdSetScissorWithCount
3// - Single DrawInstanced routing 4 fullscreen quads via SV_ViewportArrayIndex to 4 quadrants (TL/TR/BL/BR)
4// - Independent per-viewport scissor clipping (each quadrant half-clipped by its own scissor rect)
5// - Mismatched counts (4 viewports, 2 scissors -> slots 2 and 3 clipped as on D3D12)
6// - Empty viewport 0 with active viewports 1..3 (draw still rasterizes slots 1..3)
7// Compares all 64/64 pixels of the 8x8 RGBA8_UNORM render target byte-for-byte against the host Windows D3D12
8// runtime on the same adapter (matched by LUID). Self-contained: builds minimal SPIR-V 1.5 shaders in memory.
9#include "vk_test_device.h"
10#include "host_wine.h"
11#include "d3d12_test_shaders.h"
12#include "../shims/d3d12_com.h"
13#include "../src/shader_library.h"
14
15#include <d3dcompiler.h>
16#include <dxgi1_4.h>
17
18#include <bit>
19#include <cstdint>
20#include <cstdio>
21#include <cstring>
22#include <filesystem>
23#include <fstream>
24#include <string>
25#include <vector>
26
27namespace {
28
29using d3d12test::Ref;
30
31#define CHECK(expr) \
32 do { \
33 if (!(expr)) { \
34 std::fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #expr); \
35 return 1; \
36 } \
37 } while (0)
38
39struct Vertex {
40 float x, y;
41 float r, g, b, a;
42 std::uint32_t vp;
43};
44
45void emit_op(std::vector<std::uint32_t>& out, std::uint16_t opcode, std::initializer_list<std::uint32_t> ops) {
46 out.push_back((std::uint32_t(ops.size() + 1) << 16) | opcode);
47 out.insert(out.end(), ops.begin(), ops.end());
48}
49
50// Minimal valid SPIR-V 1.5 vertex shader: reads vec2 POSITION (loc 0), vec4 COLOR (loc 1), uint TEXCOORD0 (loc 2),
51// writes gl_Position and gl_ViewportIndex (BuiltIn 4440), and passes COLOR to fragment loc 0.
52std::vector<std::uint32_t> make_multi_vp_vs_spv() {
53 std::vector<std::uint32_t> w = {0x07230203u, 0x00010500u, 0u, 38u, 0u};
54 emit_op(w, 17, {1}); // OpCapability Shader
55 emit_op(w, 17, {57}); // OpCapability MultiViewport
56 emit_op(w, 17, {70}); // OpCapability ShaderViewportIndex
57 emit_op(w, 14, {0, 1}); // OpMemoryModel Logical GLSL450
58 // Entry point: Vertex %main(4) "main" %per_vertex(10) %out_col(11) %in_pos(12) %in_col(13) %in_vp(14).
59 emit_op(w, 15, {0, 4, 0x6e69616du, 0u, 10, 11, 12, 13, 14});
60 // Decorations.
61 emit_op(w, 71, {20, 2}); // OpDecorate %20 Block
62 emit_op(w, 72, {20, 0, 11, 0}); // OpMemberDecorate %20 0 BuiltIn Position
63 emit_op(w, 72, {20, 1, 11, 10}); // OpMemberDecorate %20 1 BuiltIn ViewportIndex
64 emit_op(w, 71, {11, 30, 0}); // OpDecorate %out_col Location 0
65 emit_op(w, 71, {12, 30, 0}); // OpDecorate %in_pos Location 0
66 emit_op(w, 71, {13, 30, 1}); // OpDecorate %in_col Location 1
67 emit_op(w, 71, {14, 30, 2}); // OpDecorate %in_vp Location 2
68 // Types & variables.
69 emit_op(w, 19, {1}); // %1 = OpTypeVoid
70 emit_op(w, 33, {2, 1}); // %2 = OpTypeFunction %1
71 emit_op(w, 22, {3, 32}); // %3 = OpTypeFloat 32
72 emit_op(w, 23, {5, 3, 2}); // %5 = OpTypeVector %3 2
73 emit_op(w, 23, {6, 3, 4}); // %6 = OpTypeVector %3 4
74 emit_op(w, 21, {15, 32, 1}); // %15 = OpTypeInt 32 1 (signed int)
75 emit_op(w, 21, {16, 32, 0}); // %16 = OpTypeInt 32 0 (uint)
76 emit_op(w, 30, {20, 6, 15}); // %20 = OpTypeStruct %vec4 %int
77 emit_op(w, 32, {21, 3, 20}); // %21 = OpTypePointer Output %20
78 emit_op(w, 32, {7, 3, 6}); // %7 = OpTypePointer Output %vec4
79 emit_op(w, 32, {22, 3, 15}); // %22 = OpTypePointer Output %int
80 emit_op(w, 32, {8, 1, 5}); // %8 = OpTypePointer Input %vec2
81 emit_op(w, 32, {9, 1, 6}); // %9 = OpTypePointer Input %vec4
82 emit_op(w, 32, {23, 1, 16}); // %23 = OpTypePointer Input %uint
83 emit_op(w, 59, {21, 10, 3}); // %10 = OpVariable %21 Output (PerVertex)
84 emit_op(w, 59, {7, 11, 3}); // %11 = OpVariable %7 Output (out_col)
85 emit_op(w, 59, {8, 12, 1}); // %12 = OpVariable %8 Input (in_pos)
86 emit_op(w, 59, {9, 13, 1}); // %13 = OpVariable %9 Input (in_col)
87 emit_op(w, 59, {23, 14, 1}); // %14 = OpVariable %23 Input (in_vp)
88 emit_op(w, 43, {15, 24, 0}); // %24 = OpConstant %int 0
89 emit_op(w, 43, {15, 25, 1}); // %25 = OpConstant %int 1
90 emit_op(w, 43, {3, 26, std::bit_cast<std::uint32_t>(0.0f)});
91 emit_op(w, 43, {3, 27, std::bit_cast<std::uint32_t>(1.0f)});
92 // Function %main(4).
93 emit_op(w, 54, {1, 4, 0, 2});
94 emit_op(w, 248, {28}); // OpLabel
95 emit_op(w, 61, {5, 29, 12}); // %29 = OpLoad pos2
96 emit_op(w, 81, {3, 30, 29, 0}); // %30 = x
97 emit_op(w, 81, {3, 31, 29, 1}); // %31 = y
98 emit_op(w, 80, {6, 32, 30, 31, 26, 27}); // %32 = vec4(x, y, 0.0, 1.0)
99 emit_op(w, 65, {7, 33, 10, 24}); // %33 = &PerVertex.Position
100 emit_op(w, 62, {33, 32}); // store Position
101 emit_op(w, 61, {16, 34, 14}); // %34 = OpLoad uint in_vp
102 emit_op(w, 124, {15, 35, 34}); // %35 = OpBitcast %int %34
103 emit_op(w, 65, {22, 36, 10, 25}); // %36 = &PerVertex.ViewportIndex
104 emit_op(w, 62, {36, 35}); // store ViewportIndex
105 emit_op(w, 61, {6, 37, 13}); // %37 = OpLoad col
106 emit_op(w, 62, {11, 37}); // store out_col
107 emit_op(w, 253, {});
108 emit_op(w, 56, {});
109 return w;
110}
111
112std::vector<std::uint32_t> make_col_ps_spv() {
113 std::vector<std::uint32_t> w = {0x07230203u, 0x00010500u, 0u, 16u, 0u};
114 emit_op(w, 17, {1}); // OpCapability Shader
115 emit_op(w, 14, {0, 1}); // OpMemoryModel Logical GLSL450
116 emit_op(w, 15, {4, 4, 0x6e69616du, 0u, 8, 9});
117 emit_op(w, 16, {4, 7}); // OriginUpperLeft
118 emit_op(w, 71, {8, 30, 0}); // Location 0
119 emit_op(w, 71, {9, 30, 0}); // Location 0
120 emit_op(w, 19, {1});
121 emit_op(w, 33, {2, 1});
122 emit_op(w, 22, {3, 32});
123 emit_op(w, 23, {5, 3, 4});
124 emit_op(w, 32, {6, 1, 5});
125 emit_op(w, 32, {7, 3, 5});
126 emit_op(w, 59, {6, 8, 1});
127 emit_op(w, 59, {7, 9, 3});
128 emit_op(w, 54, {1, 4, 0, 2});
129 emit_op(w, 248, {10});
130 emit_op(w, 61, {5, 11, 8});
131 emit_op(w, 62, {9, 11});
132 emit_op(w, 253, {});
133 emit_op(w, 56, {});
134 return w;
135}
136
137bool write_spv(const std::filesystem::path& path, const std::vector<std::uint32_t>& words) {
138 std::ofstream f(path, std::ios::binary | std::ios::trunc);
139 if (!f) return false;
140 f.write(reinterpret_cast<const char*>(words.data()), static_cast<std::streamsize>(words.size() * 4));
141 return bool(f);
142}
143
144constexpr char kHostVs[] =
145 "struct VsIn { float2 pos : POSITION; float4 col : COLOR; uint vp : TEXCOORD0; };\n"
146 "struct VsOut { float4 pos : SV_Position; float4 col : COLOR; uint vp : SV_ViewportArrayIndex; };\n"
147 "VsOut main(VsIn i) { VsOut o; o.pos = float4(i.pos, 0.0, 1.0); o.col = i.col; o.vp = i.vp; return o; }\n";
148constexpr char kHostPs[] = "float4 main(float4 pos : SV_Position, float4 col : COLOR) : SV_Target { return col; }\n";
149
150bool compile_hlsl(pD3DCompile compile, const char* source, std::vector<std::uint8_t>& out, bool vertex) {
151 ID3DBlob* code = nullptr;
152 ID3DBlob* errors = nullptr;
153 const HRESULT hr = compile(source, std::strlen(source), nullptr, nullptr, nullptr, "main", vertex ? "vs_5_0" : "ps_5_0",
154 0, 0, &code, &errors);
155 if (errors) {
156 std::fprintf(stderr, "%s\n", static_cast<const char*>(errors->GetBufferPointer()));
157 errors->Release();
158 }
159 if (FAILED(hr) || !code) return false;
160 const auto* bytes = static_cast<const std::uint8_t*>(code->GetBufferPointer());
161 out.assign(bytes, bytes + code->GetBufferSize());
162 code->Release();
163 return true;
164}
165
166bool host_device_for_vk(const vktest::Device& vk, Ref<ID3D12Device>& out, std::string& name) {
167 VkPhysicalDeviceIDProperties id{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES};
168 VkPhysicalDeviceProperties2 props{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &id};
169 vk.instance_fn<PFN_vkGetPhysicalDeviceProperties2>("vkGetPhysicalDeviceProperties2")(vk.physical, &props);
170 Ref<IDXGIFactory4> factory;
171 if (!id.deviceLUIDValid || FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory.p)))) return false;
172 LUID luid{};
173 std::memcpy(&luid, id.deviceLUID, sizeof(luid));
174 Ref<IDXGIAdapter1> adapter;
175 if (FAILED(factory->EnumAdapterByLuid(luid, IID_PPV_ARGS(&adapter.p)))) return false;
176 DXGI_ADAPTER_DESC1 desc{};
177 adapter->GetDesc1(&desc);
178 char utf8[256]{};
179 WideCharToMultiByte(CP_UTF8, 0, desc.Description, -1, utf8, sizeof(utf8), nullptr, nullptr);
180 name = utf8;
181 return SUCCEEDED(D3D12CreateDevice(adapter.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&out.p)));
182}
183
184struct Programs {
185 std::vector<std::uint8_t> root, vs, ps;
186};
187
188struct ViewportCase {
189 const char* name;
190 std::vector<D3D12_VIEWPORT> viewports;
191 std::vector<D3D12_RECT> scissors;
192};
193
194// 4 fullscreen quads routed to viewports 0, 1, 2, 3 with distinct solid colors:
195// vp 0 = Red, vp 1 = Green, vp 2 = Blue, vp 3 = Yellow.
196std::vector<Vertex> make_quads() {
197 const float cols[4][4] = {
198 {1.0f, 0.0f, 0.0f, 1.0f}, // vp 0: red
199 {0.0f, 1.0f, 0.0f, 1.0f}, // vp 1: green
200 {0.0f, 0.0f, 1.0f, 1.0f}, // vp 2: blue
201 {1.0f, 1.0f, 0.0f, 1.0f}, // vp 3: yellow
202 };
203 const float xy[6][2] = {{-1, -1}, {1, -1}, {1, 1}, {-1, -1}, {1, 1}, {-1, 1}};
204 std::vector<Vertex> out;
205 for (std::uint32_t vp = 0; vp < 4; ++vp) {
206 for (int i = 0; i < 6; ++i)
207 out.push_back({xy[i][0], xy[i][1], cols[vp][0], cols[vp][1], cols[vp][2], cols[vp][3], vp});
208 }
209 return out;
210}
211
212bool run_case(ID3D12Device* dev, const Programs& p, const ViewportCase& c, std::vector<std::uint8_t>& pixels_out) {
213 Ref<ID3D12RootSignature> root;
214 if (FAILED(dev->CreateRootSignature(0, p.root.data(), p.root.size(), IID_PPV_ARGS(&root.p)))) return false;
215
216 const D3D12_INPUT_ELEMENT_DESC layout[3] = {
217 {"POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0},
218 {"COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 8, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0},
219 {"TEXCOORD", 0, DXGI_FORMAT_R32_UINT, 0, 24, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0},
220 };
221 D3D12_GRAPHICS_PIPELINE_STATE_DESC pd{};
222 pd.pRootSignature = root.p;
223 pd.VS = {p.vs.data(), p.vs.size()};
224 pd.PS = {p.ps.data(), p.ps.size()};
225 for (auto& rt : pd.BlendState.RenderTarget) {
226 rt.SrcBlend = rt.SrcBlendAlpha = D3D12_BLEND_ONE;
227 rt.DestBlend = rt.DestBlendAlpha = D3D12_BLEND_ZERO;
228 rt.BlendOp = rt.BlendOpAlpha = D3D12_BLEND_OP_ADD;
229 rt.LogicOp = D3D12_LOGIC_OP_NOOP;
230 rt.RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL;
231 }
232 pd.SampleMask = UINT_MAX;
233 pd.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID;
234 pd.RasterizerState.CullMode = D3D12_CULL_MODE_NONE;
235 pd.RasterizerState.DepthClipEnable = TRUE;
236 pd.DepthStencilState.DepthEnable = FALSE;
237 pd.DepthStencilState.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ZERO;
238 pd.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_ALWAYS;
239 pd.InputLayout = {layout, 3};
240 pd.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
241 pd.NumRenderTargets = 1;
242 pd.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
243 pd.SampleDesc = {1, 0};
244
245 Ref<ID3D12PipelineState> pso;
246 if (FAILED(dev->CreateGraphicsPipelineState(&pd, IID_PPV_ARGS(&pso.p)))) return false;
247
248 const D3D12_HEAP_PROPERTIES def_heap{D3D12_HEAP_TYPE_DEFAULT};
249 const D3D12_HEAP_PROPERTIES up_heap{D3D12_HEAP_TYPE_UPLOAD};
250 const D3D12_HEAP_PROPERTIES rb_heap{D3D12_HEAP_TYPE_READBACK};
251
252 D3D12_RESOURCE_DESC td{};
253 td.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
254 td.Width = td.Height = 8;
255 td.DepthOrArraySize = td.MipLevels = 1;
256 td.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
257 td.SampleDesc = {1, 0};
258 td.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
259 Ref<ID3D12Resource> target;
260 if (FAILED(dev->CreateCommittedResource(&def_heap, D3D12_HEAP_FLAG_NONE, &td, D3D12_RESOURCE_STATE_RENDER_TARGET,
261 nullptr, IID_PPV_ARGS(&target.p))))
262 return false;
263
264 D3D12_PLACED_SUBRESOURCE_FOOTPRINT foot{};
265 UINT rows = 0;
266 UINT64 row_bytes = 0, total = 0;
267 dev->GetCopyableFootprints(&td, 0, 1, 0, &foot, &rows, &row_bytes, &total);
268 Ref<ID3D12Resource> readback;
269 const auto rb_desc = d3d12test::buffer_desc(total);
270 if (FAILED(dev->CreateCommittedResource(&rb_heap, D3D12_HEAP_FLAG_NONE, &rb_desc, D3D12_RESOURCE_STATE_COPY_DEST,
271 nullptr, IID_PPV_ARGS(&readback.p))))
272 return false;
273
274 const auto verts = make_quads();
275 const auto vb_desc = d3d12test::buffer_desc(verts.size() * sizeof(Vertex));
276 Ref<ID3D12Resource> vb_up, vb_def;
277 if (FAILED(dev->CreateCommittedResource(&up_heap, D3D12_HEAP_FLAG_NONE, &vb_desc, D3D12_RESOURCE_STATE_GENERIC_READ,
278 nullptr, IID_PPV_ARGS(&vb_up.p))) ||
279 FAILED(dev->CreateCommittedResource(&def_heap, D3D12_HEAP_FLAG_NONE, &vb_desc, D3D12_RESOURCE_STATE_COPY_DEST,
280 nullptr, IID_PPV_ARGS(&vb_def.p))))
281 return false;
282 {
283 void* mapped = nullptr;
284 const D3D12_RANGE empty{0, 0};
285 if (FAILED(vb_up->Map(0, &empty, &mapped)) || !mapped) return false;
286 std::memcpy(mapped, verts.data(), verts.size() * sizeof(Vertex));
287 vb_up->Unmap(0, nullptr);
288 }
289
290 Ref<ID3D12DescriptorHeap> rtv_heap;
291 const D3D12_DESCRIPTOR_HEAP_DESC rh{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1};
292 if (FAILED(dev->CreateDescriptorHeap(&rh, IID_PPV_ARGS(&rtv_heap.p)))) return false;
293 const auto rtv = rtv_heap->GetCPUDescriptorHandleForHeapStart();
294 dev->CreateRenderTargetView(target.p, nullptr, rtv);
295
296 Ref<ID3D12CommandQueue> queue;
297 Ref<ID3D12CommandAllocator> alloc;
298 Ref<ID3D12GraphicsCommandList> list;
299 Ref<ID3D12Fence> fence;
300 const D3D12_COMMAND_QUEUE_DESC qd{D3D12_COMMAND_LIST_TYPE_DIRECT};
301 if (FAILED(dev->CreateCommandQueue(&qd, IID_PPV_ARGS(&queue.p))) ||
302 FAILED(dev->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&alloc.p))) ||
303 FAILED(dev->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, alloc.p, pso.p, IID_PPV_ARGS(&list.p))) ||
304 FAILED(dev->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p))))
305 return false;
306
307 list->CopyResource(vb_def.p, vb_up.p);
308 const auto vb_ready =
309 d3d12test::transition(vb_def.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER);
310 list->ResourceBarrier(1, &vb_ready);
311
312 const FLOAT clear_gray[4] = {0.25f, 0.25f, 0.25f, 1.0f};
313 list->ClearRenderTargetView(rtv, clear_gray, 0, nullptr);
314 list->OMSetRenderTargets(1, &rtv, FALSE, nullptr);
315 list->RSSetViewports(UINT(c.viewports.size()), c.viewports.empty() ? nullptr : c.viewports.data());
316 list->RSSetScissorRects(UINT(c.scissors.size()), c.scissors.empty() ? nullptr : c.scissors.data());
317 list->SetGraphicsRootSignature(root.p);
318 list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
319 const D3D12_VERTEX_BUFFER_VIEW vbv{vb_def->GetGPUVirtualAddress(), UINT(verts.size() * sizeof(Vertex)),
320 sizeof(Vertex)};
321 list->IASetVertexBuffers(0, 1, &vbv);
322 list->DrawInstanced(UINT(verts.size()), 1, 0, 0);
323
324 const auto to_src = d3d12test::transition(target.p, D3D12_RESOURCE_STATE_RENDER_TARGET,
325 D3D12_RESOURCE_STATE_COPY_SOURCE);
326 list->ResourceBarrier(1, &to_src);
327 D3D12_TEXTURE_COPY_LOCATION src_loc{target.p, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX};
328 src_loc.SubresourceIndex = 0;
329 D3D12_TEXTURE_COPY_LOCATION dst_loc{readback.p, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT};
330 dst_loc.PlacedFootprint = foot;
331 list->CopyTextureRegion(&dst_loc, 0, 0, 0, &src_loc, nullptr);
332 if (FAILED(list->Close())) return false;
333
334 ID3D12CommandList* lists[] = {list.p};
335 queue->ExecuteCommandLists(1, lists);
336 if (FAILED(queue->Signal(fence.p, 1)) || FAILED(fence->SetEventOnCompletion(1, nullptr))) return false;
337
338 void* mapped = nullptr;
339 const D3D12_RANGE range{0, static_cast<SIZE_T>(total)};
340 if (FAILED(readback->Map(0, &range, &mapped)) || !mapped) return false;
341 pixels_out.resize(8 * 8 * 4);
342 for (UINT y = 0; y < 8; ++y) {
343 std::memcpy(pixels_out.data() + y * 32,
344 static_cast<const std::uint8_t*>(mapped) + foot.Offset + y * foot.Footprint.RowPitch, 32);
345 }
346 const D3D12_RANGE empty{0, 0};
347 readback->Unmap(0, &empty);
348 return true;
349}
350
351} // namespace
352
353int main() {
354 vktest::Device vk;
355 vk.request_buffer_device_address = true;
356 const auto status = vk.initialize();
357 if (status == vktest::DeviceStatus::unavailable) return 77;
358 if (status != vktest::DeviceStatus::ready) return 1;
359 if (!vk.enabled.multiViewport || !vk.shader_output_viewport_index) {
360 std::printf("GPU lacks multiViewport or shaderOutputViewportIndex; skipping\n");
361 return 77;
362 }
363
364 const auto vs_program = d3d12test::fssm_program({0x56534d56u, 0xbf810000u});
365 const auto ps_program = d3d12test::fssm_program({0x50534d56u, 0xbf810000u});
366 const auto library = std::filesystem::temp_directory_path() /
367 ("leonida_multi_viewport_test_" + std::to_string(GetCurrentProcessId()));
368 std::filesystem::create_directories(library);
369 CHECK(write_spv(library / "vs.spv", make_multi_vp_vs_spv()));
370 CHECK(write_spv(library / "ps.spv", make_col_ps_spv()));
371 {
372 std::ofstream index(library / "index.json", std::ios::binary | std::ios::trunc);
373 index << "{\"vs\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(vs_program)
374 << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"input_signature\": ["
375 "{\"semantic\": \"POSITION\", \"semantic_index\": 0, \"register\": 0, \"system_value\": 0},"
376 "{\"semantic\": \"COLOR\", \"semantic_index\": 0, \"register\": 1, \"system_value\": 0},"
377 "{\"semantic\": \"TEXCOORD\", \"semantic_index\": 0, \"register\": 2, \"system_value\": 0}]},"
378 " \"ps\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << leonida::sha256_hex(ps_program)
379 << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"inputs\": [0], \"outputs\": [0]}}";
380 }
381
382 rt::d3d12::VulkanDeviceInfo info{};
383 info.get_instance_proc = vk.instance_proc;
384 info.instance = vk.instance;
385 info.physical = vk.physical;
386 info.device = vk.device;
387 info.queue = vk.queue;
388 info.queue_family = vk.family;
389 info.bindless = vk.bindless;
390 info.bindless_partially_bound = vk.partially_bound;
391 info.host_image_copy = vk.host_image_copy;
392 info.buffer_device_address = vk.buffer_device_address;
393 info.features = vk.enabled;
394 info.shader_output_viewport_index = vk.shader_output_viewport_index;
395 info.shader_dir = library.string();
396
397 Ref<ID3D12Device> ours;
398 CHECK(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&ours.p))));
399
400 D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{};
401 root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0;
402 root_desc.Desc_1_0.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT;
403 Programs our_programs;
404 our_programs.root = d3d12test::serialize_root_signature(root_desc);
405 CHECK(!our_programs.root.empty());
406 our_programs.vs = d3d12test::shader_container(vs_program);
407 our_programs.ps = d3d12test::shader_container(ps_program);
408
409 Ref<ID3D12Device> host;
410 std::string adapter;
411 Programs host_programs;
412 bool have_host = false;
413 if (!hostwine::host_is_wine() && host_device_for_vk(vk, host, adapter)) {
414 D3D12_FEATURE_DATA_D3D12_OPTIONS host_o{};
415 if (SUCCEEDED(host->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &host_o, sizeof(host_o))) &&
416 host_o.VPAndRTArrayIndexFromAnyShaderFeedingRasterizerSupportedWithoutGSEmulation) {
417 const HMODULE compiler = LoadLibraryExA("d3dcompiler_47.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
418 const auto compile = compiler ? reinterpret_cast<pD3DCompile>(reinterpret_cast<void*>(
419 GetProcAddress(compiler, "D3DCompile")))
420 : nullptr;
421 host_programs.root = our_programs.root;
422 if (compile && compile_hlsl(compile, kHostVs, host_programs.vs, true) &&
423 compile_hlsl(compile, kHostPs, host_programs.ps, false)) {
424 have_host = true;
425 std::printf("host reference: %s\n", adapter.c_str());
426 }
427 }
428 }
429
430 const D3D12_VIEWPORT q0{0, 0, 4, 4, 0, 1};
431 const D3D12_VIEWPORT q1{4, 0, 4, 4, 0, 1};
432 const D3D12_VIEWPORT q2{0, 4, 4, 4, 0, 1};
433 const D3D12_VIEWPORT q3{4, 4, 4, 4, 0, 1};
434 const D3D12_VIEWPORT empty_vp{0, 0, 0, 0, 0, 1};
435 const D3D12_RECT full{0, 0, 8, 8};
436
437 const ViewportCase cases[] = {
438 {"4 quadrant viewports + 4 full scissors", {q0, q1, q2, q3}, {full, full, full, full}},
439 {"4 viewports + 4 independent half-clipping scissors",
440 {q0, q1, q2, q3},
441 {{0, 0, 2, 4}, {6, 0, 8, 4}, {0, 4, 4, 6}, {4, 6, 8, 8}}},
442 {"4 viewports + 2 scissors (slots 2,3 clipped)", {q0, q1, q2, q3}, {full, full}},
443 {"empty vp0 + active vp1..3", {empty_vp, q1, q2, q3}, {full, full, full, full}},
444 };
445
446 auto px_at = [](const std::vector<std::uint8_t>& buf, int x, int y) {
447 return buf.data() + (y * 8 + x) * 4;
448 };
449
450 for (std::size_t ci = 0; ci < std::size(cases); ++ci) {
451 const auto& c = cases[ci];
452 std::vector<std::uint8_t> ours_px;
453 CHECK(run_case(ours.p, our_programs, c, ours_px));
454 const auto* tl = px_at(ours_px, 1, 1);
455 const auto* tr = px_at(ours_px, 6, 1);
456 const auto* bl = px_at(ours_px, 1, 6);
457 const auto* br = px_at(ours_px, 6, 6);
458 std::printf(" %-52s TL=(%3u,%3u,%3u) TR=(%3u,%3u,%3u) BL=(%3u,%3u,%3u) BR=(%3u,%3u,%3u)", c.name, tl[0],
459 tl[1], tl[2], tr[0], tr[1], tr[2], bl[0], bl[1], bl[2], br[0], br[1], br[2]);
460 if (ci == 0) {
461 CHECK(tl[0] == 255 && tl[1] == 0 && tl[2] == 0);
462 CHECK(tr[0] == 0 && tr[1] == 255 && tr[2] == 0);
463 CHECK(bl[0] == 0 && bl[1] == 0 && bl[2] == 255);
464 CHECK(br[0] == 255 && br[1] == 255 && br[2] == 0);
465 } else if (ci == 2) {
466 CHECK(tl[0] == 255 && tr[1] == 255 && bl[0] == 64 && br[0] == 64);
467 } else if (ci == 3) {
468 CHECK(tl[0] == 64 && tr[1] == 255 && bl[2] == 255 && br[0] == 255 && br[1] == 255);
469 }
470 if (have_host) {
471 std::vector<std::uint8_t> host_px;
472 CHECK(run_case(host.p, host_programs, c, host_px));
473 CHECK(ours_px == host_px);
474 std::printf(" [64/64 px EXACT vs host]");
475 }
476 std::printf(" OK\n");
477 }
478
479 std::filesystem::remove_all(library);
480 CHECK(vk.validation_errors() == 0);
481 std::printf("d3d12_multi_viewport_test: ALL %zu CASES PASSED%s\n", std::size(cases),
482 have_host ? " (EXACT MATCH vs host D3D12)" : "");
483 return 0;
484}
diff --git a/runtime/test/d3d12_noop_copy_test.cpp b/runtime/test/d3d12_noop_copy_test.cpp
index 66bcdbc0f..cc651cd85 100644
--- a/runtime/test/d3d12_noop_copy_test.cpp
+++ b/runtime/test/d3d12_noop_copy_test.cpp
@@ -1,6 +1,8 @@
1// Legal D3D12 no-op copies must not poison Close or emit invalid Vulkan copy commands. 1// Legal D3D12 no-op copies must not poison Close or emit invalid Vulkan copy commands.
2// Synthetic resources and native host WARP comparator; no game content. 2// Synthetic resources and native host WARP comparator; no game content. Under Wine the comparator is skipped
3// (host_wine.h) and the layer is still checked.
3#include "../shims/d3d12_com.h" 4#include "../shims/d3d12_com.h"
5#include "host_wine.h"
4#include <dxgi1_4.h> 6#include <dxgi1_4.h>
5#include <cstdio> 7#include <cstdio>
6#include <cstring> 8#include <cstring>
@@ -118,10 +120,14 @@ int main() {
118 Ref<IDXGIFactory4> factory; 120 Ref<IDXGIFactory4> factory;
119 Ref<IDXGIAdapter> warp; 121 Ref<IDXGIAdapter> warp;
120 Ref<ID3D12Device> host; 122 Ref<ID3D12Device> host;
121 if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory.p))) || 123 // Wine's host is vkd3d, which accepts the upload-heap self-copy Microsoft's runtime refuses: check() would stop
122 FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&warp.p))) || 124 // there, before the layer is looked at.
123 FAILED(D3D12CreateDevice(warp.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)))) return 77; 125 if (!hostwine::host_is_wine()) {
124 if (check(host.p, "native WARP")) return 1; 126 if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory.p))) ||
127 FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&warp.p))) ||
128 FAILED(D3D12CreateDevice(warp.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)))) return 77;
129 if (check(host.p, "native WARP")) return 1;
130 }
125 Ref<ID3D12Device> layer; 131 Ref<ID3D12Device> layer;
126 if (FAILED(rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(&layer.p)))) return 77; 132 if (FAILED(rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(&layer.p)))) return 77;
127 return check(layer.p, "Leonida Vulkan"); 133 return check(layer.p, "Leonida Vulkan");
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_residency_test.cpp b/runtime/test/d3d12_residency_test.cpp
index d0f90d5fc..b033f6689 100644
--- a/runtime/test/d3d12_residency_test.cpp
+++ b/runtime/test/d3d12_residency_test.cpp
@@ -4,10 +4,13 @@
4// fence): counts of 0, null arrays, null entries, the same object twice, evicting twice, every named priority and a 4// fence): counts of 0, null arrays, null entries, the same object twice, evicting twice, every named priority and a
5// few others, residency flags, a null fence, and the fence values EnqueueMakeResident signals (the value the fence 5// few others, residency flags, a null fence, and the fence values EnqueueMakeResident signals (the value the fence
6// reaches is recorded too). Every HRESULT is recorded and the two records must be the same, step by step. A step the 6// reaches is recorded too). Every HRESULT is recorded and the two records must be the same, step by step. A step the
7// host runtime faults on is reported and not compared. No shaders or game data. Skips (77) without a Vulkan GPU; 7// host runtime faults on is reported and not compared. No shaders or game data. Skips (77) without a Vulkan GPU.
8// without a host D3D12 device only the layer's own record is printed. Set LEONIDA_D3D49_VERBOSE=1 to print every 8// The layer's record is first checked on its own (layer_wrong: the valid calls succeed, the fence reaches the values
9// step. 9// asked for), on every host; without a host D3D12 device that is all that is checked, and so it is under Wine, whose
10// host is vkd3d (host_wine.h: it answers S_OK to calls Microsoft's runtime refuses). Set LEONIDA_D3D49_VERBOSE=1 to
11// print every step.
10#include "vk_test_device.h" 12#include "vk_test_device.h"
13#include "host_wine.h"
11#include "../shims/d3d12_com.h" 14#include "../shims/d3d12_com.h"
12 15
13#include <cstdint> 16#include <cstdint>
@@ -337,6 +340,68 @@ bool run(ID3D12Device* device, bool host, Record& out) {
337 return true; 340 return true;
338} 341}
339 342
343// Steps that are plain, valid use of the API on a committed buffer, a heap and a fence: they have to succeed.
344bool must_succeed(const char* name) {
345 static const char* const kValid[] = {
346 "MakeResident a resident buffer", "Evict the buffer", "MakeResident the evicted buffer",
347 "SetResidencyPriority the buffer", "SetResidencyPriority the heap", "SetResidencyPriority MINIMUM",
348 "SetResidencyPriority LOW", "SetResidencyPriority HIGH", "SetResidencyPriority MAXIMUM",
349 "EnqueueMakeResident NONE, two objects, value 7", "EnqueueMakeResident all six, value 10",
350 };
351 for (const char* valid : kValid)
352 if (std::strcmp(name, valid) == 0) return true;
353 return false;
354}
355
356// What the layer has to answer whatever the host is, checked on its record alone (the one run() makes with `host`
357// false) so that a run with no host to compare with (no host device, or Wine's) still fails on a wrong answer: no
358// call raises an exception; the valid calls above succeed; the device is never removed (the host removes its own on
359// some steps, the layer has no reason to); and after an EnqueueMakeResident that succeeded the fence holds the value
360// asked for, or stays where it was when that value is below it (a Vulkan timeline only goes up, docs/d3d12_vulkan.md),
361// and after one that failed it has not moved. The HRESULTs of the invalid calls are the host comparison's.
362// Returns the number of wrong answers.
363int layer_wrong(const Record& ours) {
364 int wrong = 0;
365 const auto bad = [&](const std::string& name, std::uint64_t got, const char* why) {
366 std::printf("residency %s: the layer answers 0x%llx: %s\n", name.c_str(),
367 static_cast<unsigned long long>(got), why);
368 ++wrong;
369 };
370 std::size_t i = 0;
371 const auto next = [&](const std::string& name, std::uint64_t* value) {
372 if (i >= ours.values.size() || ours.names[i] != name) {
373 bad(name, 0, "missing from the layer's record");
374 return false;
375 }
376 *value = ours.values[i++];
377 return true;
378 };
379 UINT64 fence = 0; // make() creates it at 0
380 for (const Step& s : kSteps) {
381 std::uint64_t hr = 0;
382 if (!next(s.name, &hr)) return wrong;
383 if (hr == kFaulted) bad(s.name, hr, "the call raised an exception");
384 else if (must_succeed(s.name) && hr != std::uint32_t(S_OK)) bad(s.name, hr, "a valid call has to succeed");
385 if (s.isolated) continue;
386 std::uint64_t removed = 0;
387 if (!next(std::string(s.name) + " (removed reason)", &removed)) return wrong;
388 if (removed != std::uint32_t(S_OK))
389 bad(std::string(s.name) + " (removed reason)", removed, "the device was removed");
390 if (!s.fence_value) continue;
391 std::uint64_t reached = 0;
392 if (!next(std::string(s.name) + " (fence)", &reached)) return wrong;
393 const bool succeeded = hr != kFaulted && SUCCEEDED(HRESULT(std::uint32_t(hr)));
394 const UINT64 want = succeeded && s.fence_value > fence ? s.fence_value : fence;
395 if (reached != want)
396 bad(std::string(s.name) + " (fence)", reached,
397 succeeded ? "the fence has to hold the value asked for, or stay where it was for a lower one"
398 : "a call that failed must not move the fence");
399 else
400 fence = reached;
401 }
402 return wrong;
403}
404
340// --host-step N: one isolated step on a fresh host device; the exit code is its HRESULT. 405// --host-step N: one isolated step on a fresh host device; the exit code is its HRESULT.
341int host_step(std::size_t index) { 406int host_step(std::size_t index) {
342 if (index >= sizeof(kSteps) / sizeof(kSteps[0])) return int(kNoChild); 407 if (index >= sizeof(kSteps) / sizeof(kSteps[0])) return int(kNoChild);
@@ -369,12 +434,21 @@ int main(int argc, char** argv) {
369 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&device.p)))); 434 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&device.p))));
370 Record ours; 435 Record ours;
371 EXPECT(run(device.p, false, ours)); 436 EXPECT(run(device.p, false, ours));
437 // The layer's own answers first, on every host: the comparison below needs a host, and Wine's is not one.
438 const int layer_wrong_answers = layer_wrong(ours);
439 std::printf("residency: the layer's %zu values checked on their own, %d wrong\n", ours.values.size(),
440 layer_wrong_answers);
441 EXPECT(layer_wrong_answers == 0);
372 442
373 Ref<ID3D12Device> host; 443 Ref<ID3D12Device> host;
374 host.p = create_host(); 444 host.p = hostwine::host_is_wine() ? nullptr : create_host();
375 if (!host.p) { 445 if (!host.p) {
376 std::printf("residency: no host D3D12 device to compare with; %zu steps recorded, not compared\n", 446 std::printf("residency: no host D3D12 device to compare with; %zu steps recorded, not compared\n",
377 ours.values.size()); 447 ours.values.size());
448 if (verbose)
449 for (std::size_t i = 0; i < ours.values.size(); ++i)
450 std::printf("residency %s: ours 0x%llx\n", ours.names[i].c_str(),
451 static_cast<unsigned long long>(ours.values[i]));
378 } else { 452 } else {
379 Record theirs; 453 Record theirs;
380 EXPECT(run(host.p, true, theirs)); 454 EXPECT(run(host.p, true, theirs));
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_state_sweep_test.cpp b/runtime/test/d3d12_state_sweep_test.cpp
index 0ce033e99..2c237910b 100644
--- a/runtime/test/d3d12_state_sweep_test.cpp
+++ b/runtime/test/d3d12_state_sweep_test.cpp
@@ -51,8 +51,74 @@ struct Case {
51 UINT8 clear_stencil = 0; 51 UINT8 clear_stencil = 0;
52 UINT8 stencil_ref = 0; 52 UINT8 stencil_ref = 0;
53 float blend_factor[4] = {0.3f, 0.6f, 0.9f, 0.1f}; 53 float blend_factor[4] = {0.3f, 0.6f, 0.9f, 0.1f};
54 // A pipeline state stream with a DEPTH_STENCIL2 subobject (ID3D12Device2::CreatePipelineState) instead of
55 // CreateGraphicsPipelineState: `face_masks` gives each face its own read and write mask. With `back_ref` set
56 // the draw takes ID3D12GraphicsCommandList8::OMSetFrontAndBackStencilRef(stencil_ref, back_ref).
57 bool stream = false;
58 UINT8 front_read = 0xff, front_write = 0xff, back_read = 0xff, back_write = 0xff;
59 int back_ref = -1;
54}; 60};
55 61
62// One pipeline state stream subobject as d3dx12.h declares it (CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT). The
63// alignment pads some of them, which is the point (C4324).
64#pragma warning(push)
65#pragma warning(disable : 4324)
66template <D3D12_PIPELINE_STATE_SUBOBJECT_TYPE Type, typename Inner>
67struct alignas(void*) Subobject {
68 D3D12_PIPELINE_STATE_SUBOBJECT_TYPE type = Type;
69 Inner inner;
70};
71#pragma warning(pop)
72
73// The graphics description `pd` as a stream, its depth-stencil state as DEPTH_STENCIL2 with per-face masks.
74HRESULT create_stream_pso(ID3D12Device* device, const D3D12_GRAPHICS_PIPELINE_STATE_DESC& pd, const Case& c,
75 ID3D12PipelineState** out) {
76 ID3D12Device2* device2 = nullptr;
77 if (FAILED(device->QueryInterface(IID_PPV_ARGS(&device2)))) return E_NOINTERFACE;
78 const D3D12_DEPTH_STENCIL_DESC& ds = pd.DepthStencilState;
79 const auto face = [](const D3D12_DEPTH_STENCILOP_DESC& f, UINT8 read, UINT8 write) {
80 return D3D12_DEPTH_STENCILOP_DESC1{f.StencilFailOp, f.StencilDepthFailOp, f.StencilPassOp, f.StencilFunc, read,
81 write};
82 };
83 D3D12_DEPTH_STENCIL_DESC2 ds2{};
84 ds2.DepthEnable = ds.DepthEnable;
85 ds2.DepthWriteMask = ds.DepthWriteMask;
86 ds2.DepthFunc = ds.DepthFunc;
87 ds2.StencilEnable = ds.StencilEnable;
88 ds2.FrontFace = face(ds.FrontFace, c.front_read, c.front_write);
89 ds2.BackFace = face(ds.BackFace, c.back_read, c.back_write);
90 D3D12_RT_FORMAT_ARRAY formats{};
91 formats.NumRenderTargets = pd.NumRenderTargets;
92 std::memcpy(formats.RTFormats, pd.RTVFormats, sizeof(formats.RTFormats));
93 struct {
94 Subobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, ID3D12RootSignature*> root;
95 Subobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, D3D12_SHADER_BYTECODE> vs;
96 Subobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, D3D12_SHADER_BYTECODE> ps;
97 Subobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, D3D12_BLEND_DESC> blend;
98 Subobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, UINT> sample_mask;
99 Subobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, D3D12_RASTERIZER_DESC> raster;
100 Subobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL2, D3D12_DEPTH_STENCIL_DESC2> depth;
101 Subobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY, D3D12_PRIMITIVE_TOPOLOGY_TYPE> topology;
102 Subobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, D3D12_RT_FORMAT_ARRAY> rtvs;
103 Subobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, DXGI_FORMAT> dsv;
104 Subobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, DXGI_SAMPLE_DESC> samples;
105 } stream{{D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, pd.pRootSignature},
106 {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, pd.VS},
107 {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, pd.PS},
108 {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, pd.BlendState},
109 {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, pd.SampleMask},
110 {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, pd.RasterizerState},
111 {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL2, ds2},
112 {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY, pd.PrimitiveTopologyType},
113 {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, formats},
114 {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, pd.DSVFormat},
115 {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, pd.SampleDesc}};
116 const D3D12_PIPELINE_STATE_STREAM_DESC desc{sizeof(stream), &stream};
117 const HRESULT hr = device2->CreatePipelineState(&desc, IID_PPV_ARGS(out));
118 device2->Release();
119 return hr;
120}
121
56constexpr DXGI_FORMAT kDepthFormat = DXGI_FORMAT_D32_FLOAT_S8X24_UINT; 122constexpr DXGI_FORMAT kDepthFormat = DXGI_FORMAT_D32_FLOAT_S8X24_UINT;
57 123
58void base_state(D3D12_GRAPHICS_PIPELINE_STATE_DESC& pd, const Case& c, ID3D12RootSignature* root, const Programs& p) { 124void base_state(D3D12_GRAPHICS_PIPELINE_STATE_DESC& pd, const Case& c, ID3D12RootSignature* root, const Programs& p) {
@@ -100,7 +166,8 @@ Result run(ID3D12Device* device, const Case& c, const Programs& p) {
100 D3D12_GRAPHICS_PIPELINE_STATE_DESC pd; 166 D3D12_GRAPHICS_PIPELINE_STATE_DESC pd;
101 base_state(pd, c, root.p, p); 167 base_state(pd, c, root.p, p);
102 Ref<ID3D12PipelineState> pso; 168 Ref<ID3D12PipelineState> pso;
103 r.pso = device->CreateGraphicsPipelineState(&pd, IID_PPV_ARGS(&pso.p)); 169 r.pso = c.stream ? create_stream_pso(device, pd, c, &pso.p)
170 : device->CreateGraphicsPipelineState(&pd, IID_PPV_ARGS(&pso.p));
104 if (FAILED(r.pso)) return r; 171 if (FAILED(r.pso)) return r;
105 172
106 D3D12_RESOURCE_DESC cd{}; 173 D3D12_RESOURCE_DESC cd{};
@@ -172,7 +239,13 @@ Result run(ID3D12Device* device, const Case& c, const Programs& p) {
172 list->SetGraphicsRootSignature(root.p); 239 list->SetGraphicsRootSignature(root.p);
173 list->SetPipelineState(pso.p); 240 list->SetPipelineState(pso.p);
174 list->OMSetRenderTargets(1, &rtv, FALSE, &dsv); 241 list->OMSetRenderTargets(1, &rtv, FALSE, &dsv);
175 list->OMSetStencilRef(c.stencil_ref); 242 if (c.back_ref >= 0) {
243 Ref<ID3D12GraphicsCommandList8> list8;
244 if (FAILED(list->QueryInterface(IID_PPV_ARGS(&list8.p)))) return r;
245 list8->OMSetFrontAndBackStencilRef(c.stencil_ref, UINT(c.back_ref));
246 } else {
247 list->OMSetStencilRef(c.stencil_ref);
248 }
176 list->OMSetBlendFactor(c.blend_factor); 249 list->OMSetBlendFactor(c.blend_factor);
177 list->RSSetViewports(1, &viewport); 250 list->RSSetViewports(1, &viewport);
178 list->RSSetScissorRects(1, &scissor); 251 list->RSSetScissorRects(1, &scissor);
@@ -429,6 +502,36 @@ std::vector<Case> build_cases() {
429 }; 502 };
430 cases.push_back(std::move(c)); 503 cases.push_back(std::move(c));
431 } 504 }
505 // DEPTH_STENCIL2: each face compares with its own read mask and writes through its own write mask, and with
506 // OMSetFrontAndBackStencilRef against its own reference. Stored 0xa5; a pass replaces, a fail inverts.
507 struct Masks {
508 const char* name;
509 UINT8 front_read, front_write, back_read, back_write;
510 };
511 for (const Masks& m : {Masks{"same", 0x0f, 0x3c, 0x0f, 0x3c}, Masks{"split", 0x0f, 0x3c, 0xf0, 0xc3},
512 Masks{"front only", 0xff, 0x00, 0x0f, 0xff}, Masks{"back only", 0x0f, 0xff, 0xff, 0x00}})
513 for (int back_ref : {-1, 0xa3})
514 for (bool flipped : {false, true}) {
515 Case c;
516 c.name = std::string("stencil per-face masks ") + m.name + (back_ref < 0 ? ", one ref" : ", two refs") +
517 (flipped ? ", back-facing" : ", front-facing");
518 c.clear_stencil = 0xa5;
519 c.stencil_ref = 0x35;
520 c.back_ref = back_ref;
521 c.stream = true;
522 c.front_read = m.front_read;
523 c.front_write = m.front_write;
524 c.back_read = m.back_read;
525 c.back_write = m.back_write;
526 c.state = [=](D3D12_GRAPHICS_PIPELINE_STATE_DESC& pd) {
527 pd.RasterizerState.FrontCounterClockwise = flipped;
528 pd.DepthStencilState.StencilEnable = TRUE;
529 pd.DepthStencilState.FrontFace = pd.DepthStencilState.BackFace = {
530 D3D12_STENCIL_OP_INVERT, D3D12_STENCIL_OP_INVERT, D3D12_STENCIL_OP_REPLACE,
531 D3D12_COMPARISON_FUNC_EQUAL};
532 };
533 cases.push_back(std::move(c));
534 }
432 return cases; 535 return cases;
433} 536}
434 537
diff --git a/runtime/test/d3d12_subresource_copy_test.cpp b/runtime/test/d3d12_subresource_copy_test.cpp
index 1039d7d36..646a51b02 100644
--- a/runtime/test/d3d12_subresource_copy_test.cpp
+++ b/runtime/test/d3d12_subresource_copy_test.cpp
@@ -356,10 +356,19 @@ int main() {
356 else if (name.rfind("bc1:", 0) == 0) recorded.add(name, kMissing); 356 else if (name.rfind("bc1:", 0) == 0) recorded.add(name, kMissing);
357 } 357 }
358 358
359 // Once per copy path: on the host with VK_EXT_host_image_copy where the GPU has it, and through a staging submit 359 // Once per copy path: on the host with VK_EXT_host_image_copy where the GPU has it, through a staging submit
360 // (a second D3D12 device on the same Vulkan device, told the extension is off). 360 // (a second D3D12 device on the same Vulkan device, told the extension is off), and with host-transfer textures
361 for (const bool host_copy : {true, false}) { 361 // the driver gives no memory type (force_host_transfer_retry: made again without host-transfer usage, so they
362 const char* path = host_copy ? "host image copy" : "staging copy"; 362 // take the staging path, as on NVIDIA's Pascal driver).
363 struct CopyPath {
364 const char* name;
365 bool host_copy;
366 bool force_retry;
367 };
368 for (const CopyPath copy_path : {CopyPath{"host image copy", true, false}, CopyPath{"staging copy", false, false},
369 CopyPath{"host image copy refused by the driver", true, true}}) {
370 const char* path = copy_path.name;
371 const bool host_copy = copy_path.host_copy;
363 if (host_copy && !d.host_image_copy) { 372 if (host_copy && !d.host_image_copy) {
364 std::printf("CPU copies (%s): no VK_EXT_host_image_copy, skipped\n", path); 373 std::printf("CPU copies (%s): no VK_EXT_host_image_copy, skipped\n", path);
365 continue; 374 continue;
@@ -373,6 +382,7 @@ int main() {
373 info.queue_family = d.family; 382 info.queue_family = d.family;
374 info.texture_compression_bc = d.bc; 383 info.texture_compression_bc = d.bc;
375 info.host_image_copy = host_copy; 384 info.host_image_copy = host_copy;
385 info.force_host_transfer_retry = copy_path.force_retry;
376 Ref<ID3D12Device> device; 386 Ref<ID3D12Device> device;
377 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&device.p)))); 387 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&device.p))));
378 Record ours; 388 Record ours;
diff --git a/runtime/test/d3d12_typeless_depth_test.cpp b/runtime/test/d3d12_typeless_depth_test.cpp
index 42eb1d2f9..9f99ca75d 100644
--- a/runtime/test/d3d12_typeless_depth_test.cpp
+++ b/runtime/test/d3d12_typeless_depth_test.cpp
@@ -1,11 +1,17 @@
1// Typeless depth-stencil textures without ALLOW_DEPTH_STENCIL (R24G8_TYPELESS, R32G8X24_TYPELESS), as an application 1// Typeless depth-stencil textures without ALLOW_DEPTH_STENCIL (R24G8_TYPELESS, R32G8X24_TYPELESS), as an application
2// makes to keep a copy of its depth buffer for sampling: clear a depth buffer of the family, CopyResource it into 2// makes to keep a copy of its depth buffer for sampling: clear a depth buffer of the family, CopyResource it into
3// the plain texture, read both planes back and compare with Windows D3D12/WARP. No game data or shaders. 3// the plain texture, read both planes back, check that they hold the cleared values and compare with Windows
4// D3D12/WARP. No game data or shaders. Under Wine the reference would be vkd3d (host_wine.h), which reads both planes
5// back as zeros: there the comparison is left out, and the layer's readback is checked against the cleared values
6// alone.
4// LEONIDA_VK_VALIDATION=1 checks Vulkan usage. 7// LEONIDA_VK_VALIDATION=1 checks Vulkan usage.
5#include "vk_test_device.h" 8#include "vk_test_device.h"
9#include "host_wine.h"
6#include "../shims/d3d12_com.h" 10#include "../shims/d3d12_com.h"
7#include <dxgi1_4.h> 11#include <dxgi1_4.h>
8#include <algorithm> 12#include <algorithm>
13#include <cstdint>
14#include <cstring>
9#include <vector> 15#include <vector>
10 16
11#define CHECK(condition) do { \ 17#define CHECK(condition) do { \
@@ -155,6 +161,46 @@ bool copy_and_read(ID3D12Device* device, const Family& family, std::vector<unsig
155 return true; 161 return true;
156} 162}
157 163
164// Whether a readback of copy_and_read holds what clear() wrote, texel by texel: depth 0.25 and stencil 0x5a, and
165// depth 0.75 and stencil 0x3c inside the rectangle (1,1)-(5,3). This needs no reference device, so it is checked on
166// every host and is the whole check where there is none to compare with (Wine). The depth plane is four bytes a
167// texel: a float for R32G8X24, and for R24G8 a 24-bit UNORM in the low three bytes (the fourth is not depth, and a
168// device that keeps D24 as a float may round by one step either way). The stencil plane is one byte a texel.
169bool holds_cleared_values(const Family& family, const std::vector<unsigned char>& data) {
170 const size_t texels = size_t(width) * height;
171 if (data.size() != texels * 5) {
172 std::fprintf(stderr, "%s: the readback is %zu bytes, %zu expected (4 of depth and 1 of stencil a texel)\n",
173 family.name, data.size(), texels * 5);
174 return false;
175 }
176 for (UINT y = 0; y < height; ++y) {
177 for (UINT x = 0; x < width; ++x) {
178 const bool inside = x >= 1 && x < 5 && y >= 1 && y < 3;
179 const float depth = inside ? 0.75f : 0.25f;
180 const unsigned char stencil = inside ? 0x3c : 0x5a;
181 const size_t texel = size_t(y) * width + x;
182 std::uint32_t word = 0;
183 std::memcpy(&word, data.data() + texel * 4, sizeof(word));
184 bool depth_ok = false;
185 if (family.typeless == DXGI_FORMAT_R24G8_TYPELESS) {
186 const auto want = static_cast<std::int64_t>(double(depth) * 16777215.0 + 0.5);
187 const auto got = static_cast<std::int64_t>(word & 0x00ffffffu);
188 depth_ok = got >= want - 1 && got <= want + 1;
189 } else {
190 std::uint32_t want = 0;
191 std::memcpy(&want, &depth, sizeof(want));
192 depth_ok = word == want;
193 }
194 const unsigned char got_stencil = data[texels * 4 + texel];
195 if (depth_ok && got_stencil == stencil) continue;
196 std::fprintf(stderr, "%s: texel (%u,%u) holds depth word 0x%08x and stencil 0x%02x, cleared to depth %g "
197 "and stencil 0x%02x\n", family.name, x, y, word, got_stencil, double(depth), stencil);
198 return false;
199 }
200 }
201 return true;
202}
203
158// The first byte where the two readbacks differ, or -1. 204// The first byte where the two readbacks differ, or -1.
159long first_difference(const std::vector<unsigned char>& a, const std::vector<unsigned char>& b) { 205long first_difference(const std::vector<unsigned char>& a, const std::vector<unsigned char>& b) {
160 if (a.size() != b.size()) return long(std::min(a.size(), b.size())); 206 if (a.size() != b.size()) return long(std::min(a.size(), b.size()));
@@ -169,6 +215,9 @@ int main() {
169 const auto device_status = vk.initialize(); 215 const auto device_status = vk.initialize();
170 if (device_status == vktest::DeviceStatus::unavailable) return 77; 216 if (device_status == vktest::DeviceStatus::unavailable) return 77;
171 if (device_status != vktest::DeviceStatus::ready) return 1; 217 if (device_status != vktest::DeviceStatus::ready) return 1;
218 // Under Wine the reference would be vkd3d, which reads both planes back as zeros: no comparison there, and the
219 // layer's readback is still checked against the values it was cleared to.
220 const bool compare_with_host = !hostwine::host_is_wine();
172 unsigned failures = 0; 221 unsigned failures = 0;
173 { 222 {
174 Ref<ID3D12Device> ours; 223 Ref<ID3D12Device> ours;
@@ -184,15 +233,16 @@ int main() {
184 Ref<IDXGIFactory4> factory; 233 Ref<IDXGIFactory4> factory;
185 Ref<IDXGIAdapter> adapter; 234 Ref<IDXGIAdapter> adapter;
186 Ref<ID3D12Device> warp; 235 Ref<ID3D12Device> warp;
187 if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory.p))) || 236 if (compare_with_host &&
188 FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter.p))) || 237 (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory.p))) ||
189 FAILED(D3D12CreateDevice(adapter.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&warp.p)))) { 238 FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter.p))) ||
239 FAILED(D3D12CreateDevice(adapter.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&warp.p))))) {
190 std::fprintf(stderr, "no WARP device, skipped\n"); 240 std::fprintf(stderr, "no WARP device, skipped\n");
191 return 77; 241 return 77;
192 } 242 }
193 for (const Family& family : families) { 243 for (const Family& family : families) {
194 std::vector<unsigned char> expected, actual; 244 std::vector<unsigned char> expected, actual;
195 if (!copy_and_read(warp.p, family, expected)) { 245 if (compare_with_host && !copy_and_read(warp.p, family, expected)) {
196 std::fprintf(stderr, "%s: WARP could not run the copy\n", family.name); 246 std::fprintf(stderr, "%s: WARP could not run the copy\n", family.name);
197 ++failures; 247 ++failures;
198 continue; 248 continue;
@@ -202,6 +252,16 @@ int main() {
202 ++failures; 252 ++failures;
203 continue; 253 continue;
204 } 254 }
255 if (!holds_cleared_values(family, actual)) {
256 ++failures;
257 continue;
258 }
259 if (!compare_with_host) {
260 std::printf("%s without ALLOW_DEPTH_STENCIL: copy of a cleared depth buffer holds the cleared depth "
261 "and stencil at every texel (%zu bytes; not compared with the host)\n",
262 family.name, actual.size());
263 continue;
264 }
205 const long at = first_difference(actual, expected); 265 const long at = first_difference(actual, expected);
206 if (at >= 0) { 266 if (at >= 0) {
207 std::fprintf(stderr, "%s: readback differs from WARP at byte %ld of %zu\n", family.name, at, 267 std::fprintf(stderr, "%s: readback differs from WARP at byte %ld of %zu\n", family.name, at,
diff --git a/runtime/test/d3d12_uav_clear_test.cpp b/runtime/test/d3d12_uav_clear_test.cpp
index 6bba27044..2d13ba59b 100644
--- a/runtime/test/d3d12_uav_clear_test.cpp
+++ b/runtime/test/d3d12_uav_clear_test.cpp
@@ -74,6 +74,10 @@ int conversion_checks() {
74 EXPECT((element(VK_FORMAT_R4G4B4A4_UNORM_PACK16, true, floats(1.0f, 0, 0, 0)) == V{0x00, 0xf0})); 74 EXPECT((element(VK_FORMAT_R4G4B4A4_UNORM_PACK16, true, floats(1.0f, 0, 0, 0)) == V{0x00, 0xf0}));
75 EXPECT((element(VK_FORMAT_R4G4B4A4_UNORM_PACK16, true, floats(0, 0, 0, 1.0f)) == V{0x0f, 0x00})); 75 EXPECT((element(VK_FORMAT_R4G4B4A4_UNORM_PACK16, true, floats(0, 0, 0, 1.0f)) == V{0x0f, 0x00}));
76 EXPECT((element(VK_FORMAT_R4G4B4A4_UNORM_PACK16, true, floats(0, 1.0f, 0.2f, 0)) == V{0x30, 0x0f})); 76 EXPECT((element(VK_FORMAT_R4G4B4A4_UNORM_PACK16, true, floats(0, 1.0f, 0.2f, 0)) == V{0x30, 0x0f}));
77 // B5G6R5, B5G5R5A1 and B4G4R4A4 as ClearUnorderedAccessViewFloat leaves them on WARP.
78 EXPECT((element(VK_FORMAT_R5G6B5_UNORM_PACK16, true, floats(0.25f, 0.75f, 0.4f, 0.6f)) == V{0xec, 0x45}));
79 EXPECT((element(VK_FORMAT_A1R5G5B5_UNORM_PACK16, true, floats(0.25f, 0.75f, 0.4f, 0.6f)) == V{0xec, 0xa2}));
80 EXPECT((element(VK_FORMAT_A4R4G4B4_UNORM_PACK16, true, floats(0.25f, 0.75f, 0.4f, 0.6f)) == V{0xb6, 0x94}));
77 // Half floats round to nearest even; too large is infinity; tiny values become subnormals. 81 // Half floats round to nearest even; too large is infinity; tiny values become subnormals.
78 EXPECT((element(VK_FORMAT_R16_SFLOAT, true, floats(1.0f, 0, 0, 0)) == V{0x00, 0x3c})); 82 EXPECT((element(VK_FORMAT_R16_SFLOAT, true, floats(1.0f, 0, 0, 0)) == V{0x00, 0x3c}));
79 EXPECT((element(VK_FORMAT_R16_SFLOAT, true, floats(-2.0f, 0, 0, 0)) == V{0x00, 0xc0})); 83 EXPECT((element(VK_FORMAT_R16_SFLOAT, true, floats(-2.0f, 0, 0, 0)) == V{0x00, 0xc0}));
diff --git a/runtime/test/d3d12_vulkan_device_test.cpp b/runtime/test/d3d12_vulkan_device_test.cpp
index 056e82561..f51ce2191 100644
--- a/runtime/test/d3d12_vulkan_device_test.cpp
+++ b/runtime/test/d3d12_vulkan_device_test.cpp
@@ -143,7 +143,8 @@ D3D12_RESOURCE_BARRIER transition(ID3D12Resource* resource, D3D12_RESOURCE_STATE
143std::uint8_t texel_byte(UINT x, UINT y, UINT z, UINT i) { return std::uint8_t(x * 31 + y * 7 + z * 61 + i * 3 + 1); } 143std::uint8_t texel_byte(UINT x, UINT y, UINT z, UINT i) { return std::uint8_t(x * 31 + y * 7 + z * 61 + i * 3 + 1); }
144 144
145// WriteToSubresource/ReadFromSubresource on `device`. Textures in a CPU-visible custom heap copy on the host when the 145// WriteToSubresource/ReadFromSubresource on `device`. Textures in a CPU-visible custom heap copy on the host when the
146// device has VK_EXT_host_image_copy, through a staging submit when it doesn't; main runs this once per path. Covers 146// device has VK_EXT_host_image_copy, through a staging submit when it doesn't or when the driver gave the
147// host-transfer image no memory type; main runs this once per path, three paths. Covers
147// zero-filled first reads, boxes with pitches unlike the texture's, a mip, a volume, BC1 blocks, a default-heap 148// zero-filled first reads, boxes with pitches unlike the texture's, a mip, a volume, BC1 blocks, a default-heap
148// texture (always staged), the rejected calls, and both directions between the CPU copies and GPU copies. 149// texture (always staged), the rejected calls, and both directions between the CPU copies and GPU copies.
149int cpu_copies(ID3D12Device* device, bool bc, const char* path) { 150int cpu_copies(ID3D12Device* device, bool bc, const char* path) {
@@ -2449,9 +2450,11 @@ int compare_feature_options(ID3D12Device* ours, const rt::d3d12::VulkanDeviceInf
2449 o13.InvertedViewportHeightFlipsYSupported || o13.InvertedViewportDepthFlipsZSupported || 2450 o13.InvertedViewportHeightFlipsYSupported || o13.InvertedViewportDepthFlipsZSupported ||
2450 o13.TextureCopyBetweenDimensionsSupported || o13.AlphaBlendFactorSupported) 2451 o13.TextureCopyBetweenDimensionsSupported || o13.AlphaBlendFactorSupported)
2451 fail("OPTIONS13 unexpected support"); 2452 fail("OPTIONS13 unexpected support");
2452 if (o14.AdvancedTextureOpsSupported || o14.WriteableMSAATexturesSupported || 2453 if (o14.AdvancedTextureOpsSupported || o14.WriteableMSAATexturesSupported)
2453 o14.IndependentFrontAndBackStencilRefMaskSupported)
2454 fail("OPTIONS14 unexpected support"); 2454 fail("OPTIONS14 unexpected support");
2455 // DEPTH_STENCIL2's per-face masks and OMSetFrontAndBackStencilRef (d3d12_state_sweep_test draws them).
2456 if (!o14.IndependentFrontAndBackStencilRefMaskSupported)
2457 fail("OPTIONS14.IndependentFrontAndBackStencilRefMaskSupported should be TRUE");
2455 if (o15.TriangleFanSupported || o15.DynamicIndexBufferStripCutSupported) fail("OPTIONS15 unexpected support"); 2458 if (o15.TriangleFanSupported || o15.DynamicIndexBufferStripCutSupported) fail("OPTIONS15 unexpected support");
2456 if (o16.DynamicDepthBiasSupported || o16.GPUUploadHeapSupported) fail("OPTIONS16 unexpected support"); 2459 if (o16.DynamicDepthBiasSupported || o16.GPUUploadHeapSupported) fail("OPTIONS16 unexpected support");
2457 if (o18.RenderPassesValid) fail("OPTIONS18 unexpected support"); 2460 if (o18.RenderPassesValid) fail("OPTIONS18 unexpected support");
@@ -5168,6 +5171,12 @@ int main() {
5168 EXPECT(SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof(options)))); 5171 EXPECT(SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof(options))));
5169 EXPECT(options.ResourceBindingTier == D3D12_RESOURCE_BINDING_TIER_3); 5172 EXPECT(options.ResourceBindingTier == D3D12_RESOURCE_BINDING_TIER_3);
5170 EXPECT(options.MaxGPUVirtualAddressBitsPerResource == 40); 5173 EXPECT(options.MaxGPUVirtualAddressBitsPerResource == 40);
5174 // Console 0x40-byte (16-dword) D3D12_OPTIONS query (docs/d3d12_xs_surface.md §7.1): 0x3C PC prefix + zero tail.
5175 UINT console_opts[16]{};
5176 console_opts[15] = 0xdeadbeefu;
5177 EXPECT(SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, console_opts, sizeof(console_opts))));
5178 EXPECT(std::memcmp(console_opts, &options, sizeof(options)) == 0);
5179 EXPECT(console_opts[15] == 0);
5171 5180
5172 D3D12_FEATURE_DATA_GPU_VIRTUAL_ADDRESS_SUPPORT va_support{}; 5181 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)))); 5182 EXPECT(SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_GPU_VIRTUAL_ADDRESS_SUPPORT, &va_support, sizeof(va_support))));
@@ -7018,11 +7027,20 @@ int main() {
7018 EXPECT(!mismatches); 7027 EXPECT(!mismatches);
7019 7028
7020 // CPU texture copies, once per path. A second D3D12 device on the same Vulkan device, told the extension is 7029 // CPU texture copies, once per path. A second D3D12 device on the same Vulkan device, told the extension is
7021 // off, takes the staging path even on a GPU that has host image copy. 7030 // off, takes the staging path even on a GPU that has host image copy. The third path has the extension but
7022 for (const bool host : {true, false}) { 7031 // treats every host-transfer image as one the driver gave no memory type (a GTX 1050 Ti, NVIDIA 582.78): the
7032 // image is made again without host-transfer usage and copies on the staging path.
7033 struct CopyPath {
7034 const char* name;
7035 bool host;
7036 bool force_retry;
7037 };
7038 for (const CopyPath path : {CopyPath{"host image copy", true, false}, CopyPath{"staging copy", false, false},
7039 CopyPath{"host image copy refused by the driver", true, true}}) {
7040 const bool host = path.host;
7023 if (host && !d.host_image_copy) { 7041 if (host && !d.host_image_copy) {
7024 std::printf("WriteToSubresource/ReadFromSubresource (host image copy): no VK_EXT_host_image_copy, " 7042 std::printf("WriteToSubresource/ReadFromSubresource (%s): no VK_EXT_host_image_copy, skipped\n",
7025 "skipped\n"); 7043 path.name);
7026 continue; 7044 continue;
7027 } 7045 }
7028 rt::d3d12::VulkanDeviceInfo info{}; 7046 rt::d3d12::VulkanDeviceInfo info{};
@@ -7033,9 +7051,10 @@ int main() {
7033 info.queue = d.queue; 7051 info.queue = d.queue;
7034 info.queue_family = d.family; 7052 info.queue_family = d.family;
7035 info.host_image_copy = host; 7053 info.host_image_copy = host;
7054 info.force_host_transfer_retry = path.force_retry;
7036 Ref<ID3D12Device> device; 7055 Ref<ID3D12Device> device;
7037 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&device.p)))); 7056 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&device.p))));
7038 EXPECT(cpu_copies(device.p, d.bc, host ? "host image copy" : "staging copy") == 0); 7057 EXPECT(cpu_copies(device.p, d.bc, path.name) == 0);
7039 } 7058 }
7040 7059
7041 { 7060 {
diff --git a/runtime/test/device_proxy_test.cpp b/runtime/test/device_proxy_test.cpp
index 6242d1b52..1c1707243 100644
--- a/runtime/test/device_proxy_test.cpp
+++ b/runtime/test/device_proxy_test.cpp
@@ -161,6 +161,9 @@ int main(int argc, char** argv) {
161 check(rt::d3d12_xs::device_slot_overridden(14), "device slot 14 is the descriptor-heap override"); 161 check(rt::d3d12_xs::device_slot_overridden(14), "device slot 14 is the descriptor-heap override");
162 check(rt::d3d12_xs::device_slot_overridden(62), "device slot 62 is the compute-PSO override"); 162 check(rt::d3d12_xs::device_slot_overridden(62), "device slot 62 is the compute-PSO override");
163 check(rt::d3d12_xs::device_slot_overridden(76), "device slot 76 is the resource override"); 163 check(rt::d3d12_xs::device_slot_overridden(76), "device slot 76 is the resource override");
164 check(rt::d3d12_xs::device_slot_overridden(86), "device slot 86 is the CreatePipelineState override");
165 check(rt::d3d12_xs::device_slot_overridden(101), "device slot 101 is the CreateStateObject override");
166 check(rt::d3d12_xs::device_slot_overridden(108), "device slot 108 is the GetResourceAllocationInfo2 override");
164 check(rt::d3d12_xs::device_slot_overridden(67), 167 check(rt::d3d12_xs::device_slot_overridden(67),
165 "device slot 67 is the DeserializeComputePipelineStateX override (console native-code compute pipeline, not PC CreateProtectedResourceSession1)"); 168 "device slot 67 is the DeserializeComputePipelineStateX override (console native-code compute pipeline, not PC CreateProtectedResourceSession1)");
166 169
@@ -521,6 +524,101 @@ int main(int argc, char** argv) {
521 check(SUCCEEDED(hr) && pso67 != nullptr, "slot 67 creates a compute PSO via CreateComputePipelineState"); 524 check(SUCCEEDED(hr) && pso67 != nullptr, "slot 67 creates a compute PSO via CreateComputePipelineState");
522 check(rt::d3d12_xs::device_slot_hits(67) == 1, "slot 67 hit counter is 1"); 525 check(rt::d3d12_xs::device_slot_hits(67) == 1, "slot 67 hit counter is 1");
523 check(rt::d3d12_xs::device_slot_first_call_seen(67), "slot 67 first-call flag is set"); 526 check(rt::d3d12_xs::device_slot_first_call_seen(67), "slot 67 first-call flag is set");
527
528 // Slot 86: CreatePipelineState(const D3D12_PIPELINE_STATE_STREAM_DESC*, REFIID, void**), forwarded to PC
529 // ID3D12Device2::CreatePipelineState (PC slot 47).
530 if (slots > 47) {
531 struct alignas(void*) ComputeStream {
532 alignas(void*) D3D12_PIPELINE_STATE_SUBOBJECT_TYPE root_type =
533 D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE;
534 ID3D12RootSignature* root_sig = nullptr;
535 alignas(void*) D3D12_PIPELINE_STATE_SUBOBJECT_TYPE cs_type = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS;
536 D3D12_SHADER_BYTECODE cs{};
537 } stream;
538 stream.root_sig = root_signature.Get();
539 stream.cs.pShaderBytecode = bytecode->GetBufferPointer();
540 stream.cs.BytecodeLength = bytecode->GetBufferSize();
541 D3D12_PIPELINE_STATE_STREAM_DESC stream_desc{sizeof(stream), &stream};
542 using XboxCreatePipelineStateFn =
543 HRESULT(WINAPI*)(void*, const D3D12_PIPELINE_STATE_STREAM_DESC*, const IID*, void**);
544 auto create_stream_pso = reinterpret_cast<XboxCreatePipelineStateFn>(proxy_vtbl[86]);
545 ComPtr<ID3D12PipelineState> pso86;
546 hr = create_stream_pso(device.Get(), &stream_desc, &iid_pso,
547 reinterpret_cast<void**>(pso86.GetAddressOf()));
548 check(SUCCEEDED(hr) && pso86 != nullptr,
549 "slot 86 creates a PSO via PC ID3D12Device2::CreatePipelineState (slot 47)");
550 check(rt::d3d12_xs::device_slot_hits(86) == 1, "slot 86 hit counter is 1");
551 check(rt::d3d12_xs::device_slot_first_call_seen(86), "slot 86 first-call flag is set");
552 }
553 }
554
555 // Slot 101: CreateStateObject(const D3D12_STATE_OBJECT_DESC*, REFIID, void**), forwarded to PC
556 // ID3D12Device5::CreateStateObject (PC slot 62).
557 if (slots > 62) {
558 using XboxCreateStateObjectFn = HRESULT(WINAPI*)(void*, const D3D12_STATE_OBJECT_DESC*, const IID*, void**);
559 auto create_state_object = reinterpret_cast<XboxCreateStateObjectFn>(proxy_vtbl[101]);
560 D3D12_STATE_OBJECT_DESC empty_so{};
561 empty_so.Type = D3D12_STATE_OBJECT_TYPE_RAYTRACING_PIPELINE;
562 void* so_out = reinterpret_cast<void*>(0x1111);
563 hr = create_state_object(device.Get(), &empty_so, nullptr, &so_out);
564 check(hr == E_POINTER && so_out == nullptr, "slot 101 nulls its output for a null IID");
565 check(rt::d3d12_xs::device_slot_hits(101) == 1, "slot 101 hit counter is 1");
566 }
567
568 // Slot 108: GetResourceAllocationInfo2(ret, this, visible_mask, count, descs, info1) with C-ABI struct return,
569 // 56-byte D3D12_RESOURCE_DESC entries, and Xbox layout/flag words, compared against direct PC
570 // ID3D12Device8::GetResourceAllocationInfo2 (PC slot 68).
571 if (slots > 68) {
572 ComPtr<ID3D12Device8> real_device8;
573 if (real && SUCCEEDED(real->QueryInterface(IID_PPV_ARGS(real_device8.GetAddressOf()))) && real_device8) {
574 D3D12_RESOURCE_DESC xbox_descs[2]{};
575 xbox_descs[0].Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
576 xbox_descs[0].Width = 64;
577 xbox_descs[0].Height = 64;
578 xbox_descs[0].DepthOrArraySize = 1;
579 xbox_descs[0].MipLevels = 1;
580 xbox_descs[0].Format = DXGI_FORMAT_R8G8B8A8_UNORM;
581 xbox_descs[0].SampleDesc.Count = 1;
582 xbox_descs[0].Layout = static_cast<D3D12_TEXTURE_LAYOUT>(0x105);
583 xbox_descs[0].Flags = static_cast<D3D12_RESOURCE_FLAGS>(
584 D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | 0x300000u);
585 xbox_descs[1].Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
586 xbox_descs[1].Width = 4096;
587 xbox_descs[1].Height = 1;
588 xbox_descs[1].DepthOrArraySize = 1;
589 xbox_descs[1].MipLevels = 1;
590 xbox_descs[1].SampleDesc.Count = 1;
591 xbox_descs[1].Layout = static_cast<D3D12_TEXTURE_LAYOUT>(0x101);
592 xbox_descs[1].Flags = static_cast<D3D12_RESOURCE_FLAGS>(0x200000u);
593
594 D3D12_RESOURCE_DESC1 pc_descs[2]{};
595 std::memcpy(&pc_descs[0], &xbox_descs[0], sizeof(D3D12_RESOURCE_DESC));
596 pc_descs[0].SamplerFeedbackMipRegion = {};
597 pc_descs[0].Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
598 pc_descs[0].Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
599 std::memcpy(&pc_descs[1], &xbox_descs[1], sizeof(D3D12_RESOURCE_DESC));
600 pc_descs[1].SamplerFeedbackMipRegion = {};
601 pc_descs[1].Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
602 pc_descs[1].Flags = D3D12_RESOURCE_FLAG_NONE;
603
604 D3D12_RESOURCE_ALLOCATION_INFO1 pc_info1[2]{};
605 const D3D12_RESOURCE_ALLOCATION_INFO pc_info =
606 real_device8->GetResourceAllocationInfo2(1, 2, pc_descs, pc_info1);
607
608 using XboxGetAllocInfo2CAbiFn = D3D12_RESOURCE_ALLOCATION_INFO*(WINAPI*)(
609 D3D12_RESOURCE_ALLOCATION_INFO*, void*, UINT, UINT, const D3D12_RESOURCE_DESC*,
610 D3D12_RESOURCE_ALLOCATION_INFO1*);
611 auto get_alloc_info2 = reinterpret_cast<XboxGetAllocInfo2CAbiFn>(proxy_vtbl[108]);
612 D3D12_RESOURCE_ALLOCATION_INFO xbox_info{};
613 D3D12_RESOURCE_ALLOCATION_INFO1 xbox_info1[2]{};
614 D3D12_RESOURCE_ALLOCATION_INFO* ret_ptr =
615 get_alloc_info2(&xbox_info, device.Get(), 1, 2, xbox_descs, xbox_info1);
616 check(ret_ptr == &xbox_info && xbox_info.SizeInBytes == pc_info.SizeInBytes &&
617 xbox_info.Alignment == pc_info.Alignment && xbox_info1[0].SizeInBytes == pc_info1[0].SizeInBytes &&
618 xbox_info1[1].SizeInBytes == pc_info1[1].SizeInBytes,
619 "slot 108 C-ABI GetResourceAllocationInfo2 with 56-byte Xbox descs matches PC Device8");
620 check(rt::d3d12_xs::device_slot_hits(108) == 1, "slot 108 hit counter is 1");
621 }
524 } 622 }
525 623
526 // _COM_Outptr_ (d3d12.h): a failed create leaves NULL in the output. WARP accepts invalid heap descriptions, 624 // _COM_Outptr_ (d3d12.h): a failed create leaves NULL in the output. WARP accepts invalid heap descriptions,
diff --git a/runtime/test/dxgi_host_parity_test.cpp b/runtime/test/dxgi_host_parity_test.cpp
index 1492244c5..3c0809a6e 100644
--- a/runtime/test/dxgi_host_parity_test.cpp
+++ b/runtime/test/dxgi_host_parity_test.cpp
@@ -7,9 +7,11 @@
7// output is S_OK with a null output; on ResizeBuffers NONPREROTATED, FULLSCREEN_VIDEO and every bit from 0x4000 up are 7// output is S_OK with a null output; on ResizeBuffers NONPREROTATED, FULLSCREEN_VIDEO and every bit from 0x4000 up are
8// DXGI_ERROR_INVALID_CALL, and FOREGROUND_LAYER, YUV_VIDEO and 0x2000 on a chain created without them E_INVALIDARG; 8// DXGI_ERROR_INVALID_CALL, and FOREGROUND_LAYER, YUV_VIDEO and 0x2000 on a chain created without them E_INVALIDARG;
9// a null out-pointer is DXGI_ERROR_INVALID_CALL on GetBuffer, GetHwnd, GetLastPresentCount and GetRestrictToOutput. 9// a null out-pointer is DXGI_ERROR_INVALID_CALL on GetBuffer, GetHwnd, GetLastPresentCount and GetRestrictToOutput.
10// Exits 77 without an interactive window station, a Vulkan device or a host D3D12 device. 10// Exits 77 without an interactive window station, a Vulkan device or a host D3D12 device, and under Wine, whose DXGI
11// is not that reference (host_wine.h; its wined3d faults on the null GetBuffer out-pointer).
11#include "vk_test_device.h" 12#include "vk_test_device.h"
12#include "host_adapter.h" 13#include "host_adapter.h"
14#include "host_wine.h"
13#include "window_station.h" 15#include "window_station.h"
14#include "../shims/d3d12_com.h" 16#include "../shims/d3d12_com.h"
15 17
@@ -226,6 +228,7 @@ int main() {
226 std::printf("SKIP: the process has no interactive window station\n"); 228 std::printf("SKIP: the process has no interactive window station\n");
227 return 77; 229 return 77;
228 } 230 }
231 if (hostwine::host_is_wine()) return 77; // every row is compared with the host
229 vktest::Device vk; 232 vktest::Device vk;
230 if (!vk.create(true)) { 233 if (!vk.create(true)) {
231 std::printf("SKIP: no Vulkan device\n"); 234 std::printf("SKIP: no Vulkan device\n");
diff --git a/runtime/test/dxgi_swapchain_test.cpp b/runtime/test/dxgi_swapchain_test.cpp
index d47a9ada3..f862e9fd2 100644
--- a/runtime/test/dxgi_swapchain_test.cpp
+++ b/runtime/test/dxgi_swapchain_test.cpp
@@ -8,6 +8,7 @@
8 8
9#include "../shims/d3d12_com.h" 9#include "../shims/d3d12_com.h"
10#include "../shims/dxgi_com.h" 10#include "../shims/dxgi_com.h"
11#include "host_wine.h"
11#include "vulkan_loader.h" 12#include "vulkan_loader.h"
12#include "window_station.h" 13#include "window_station.h"
13#include "../src/vulkan_device_filter.h" 14#include "../src/vulkan_device_filter.h"
@@ -156,8 +157,9 @@ HRESULT create_guarded(IDXGIFactory4* factory, IUnknown* queue, HWND hwnd, const
156 157
157// CreateSwapChainForHwnd with descriptions D3D12 refuses (and the valid ones next to them), against the host runtime's 158// CreateSwapChainForHwnd with descriptions D3D12 refuses (and the valid ones next to them), against the host runtime's
158// DXGI: each case gets its own window on each side, and the HRESULTs must match. Returns the number of mismatches, 159// DXGI: each case gets its own window on each side, and the HRESULTs must match. Returns the number of mismatches,
159// or -1 without a host D3D12 device. 160// or -1 without a host D3D12 device, or under Wine, whose DXGI is not that reference (host_wine.h).
160int compare_swap_chain_arguments(IDXGIFactory4* ours, ID3D12Device* our_device, ID3D12CommandQueue* our_queue) { 161int compare_swap_chain_arguments(IDXGIFactory4* ours, ID3D12Device* our_device, ID3D12CommandQueue* our_queue) {
162 if (hostwine::host_is_wine()) return -1;
161 using CreateDevice = HRESULT(WINAPI*)(IUnknown*, D3D_FEATURE_LEVEL, REFIID, void**); 163 using CreateDevice = HRESULT(WINAPI*)(IUnknown*, D3D_FEATURE_LEVEL, REFIID, void**);
162 using CreateFactory2 = HRESULT(WINAPI*)(UINT, REFIID, void**); 164 using CreateFactory2 = HRESULT(WINAPI*)(UINT, REFIID, void**);
163 const HMODULE d3d12 = LoadLibraryExA("d3d12.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); 165 const HMODULE d3d12 = LoadLibraryExA("d3d12.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
@@ -312,8 +314,9 @@ int compare_swap_chain_arguments(IDXGIFactory4* ours, ID3D12Device* our_device,
312// GetBuffer and Present are DXGI_ERROR_INVALID_CALL, and the next ResizeBuffers to a valid size brings it all back. 314// GetBuffer and Present are DXGI_ERROR_INVALID_CALL, and the next ResizeBuffers to a valid size brings it all back.
313// A refused call (a back buffer still held) changes nothing. WARP differs (it takes 16385 and fails at 32768 with 315// A refused call (a back buffer still held) changes nothing. WARP differs (it takes 16385 and fails at 32768 with
314// E_OUTOFMEMORY), so this compares with the host's default adapter. Returns the number of mismatches, or -1 without 316// E_OUTOFMEMORY), so this compares with the host's default adapter. Returns the number of mismatches, or -1 without
315// a host D3D12 device. 317// a host D3D12 device or under Wine (host_wine.h).
316int compare_failed_resize(IDXGIFactory4* ours, ID3D12CommandQueue* our_queue) { 318int compare_failed_resize(IDXGIFactory4* ours, ID3D12CommandQueue* our_queue) {
319 if (hostwine::host_is_wine()) return -1;
317 using CreateDevice = HRESULT(WINAPI*)(IUnknown*, D3D_FEATURE_LEVEL, REFIID, void**); 320 using CreateDevice = HRESULT(WINAPI*)(IUnknown*, D3D_FEATURE_LEVEL, REFIID, void**);
318 using CreateFactory2 = HRESULT(WINAPI*)(UINT, REFIID, void**); 321 using CreateFactory2 = HRESULT(WINAPI*)(UINT, REFIID, void**);
319 const HMODULE d3d12 = LoadLibraryExA("d3d12.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); 322 const HMODULE d3d12 = LoadLibraryExA("d3d12.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
@@ -638,11 +641,15 @@ int main() {
638 cl->Close(); 641 cl->Close();
639 642
640 // Before the test's own swap chain: the host comparison creates and releases its own windows and chains. 643 // Before the test's own swap chain: the host comparison creates and releases its own windows and chains.
644 // Why a comparison was left out: under Wine there is a host device, and it is not the reference (host_wine.h).
645 const char* const not_compared = hostwine::host_is_wine()
646 ? "the host's DXGI is Wine's, not compared with it"
647 : "no host D3D12 device to compare with, skipped";
641 const int argument_mismatches = compare_swap_chain_arguments(factory, dev, queue); 648 const int argument_mismatches = compare_swap_chain_arguments(factory, dev, queue);
642 if (argument_mismatches < 0) std::printf("CreateSwapChainForHwnd: no host D3D12 device to compare with, skipped\n"); 649 if (argument_mismatches < 0) std::printf("CreateSwapChainForHwnd: %s\n", not_compared);
643 if (argument_mismatches > 0) return fail("CreateSwapChainForHwnd answers differ from the host runtime"); 650 if (argument_mismatches > 0) return fail("CreateSwapChainForHwnd answers differ from the host runtime");
644 const int resize_mismatches = compare_failed_resize(factory, queue); 651 const int resize_mismatches = compare_failed_resize(factory, queue);
645 if (resize_mismatches < 0) std::printf("failed ResizeBuffers: no host D3D12 device to compare with, skipped\n"); 652 if (resize_mismatches < 0) std::printf("failed ResizeBuffers: %s\n", not_compared);
646 if (resize_mismatches > 0) return fail("a failed ResizeBuffers differs from the host runtime"); 653 if (resize_mismatches > 0) return fail("a failed ResizeBuffers differs from the host runtime");
647 654
648 DXGI_SWAP_CHAIN_DESC1 scd{}; 655 DXGI_SWAP_CHAIN_DESC1 scd{};
@@ -1256,8 +1263,9 @@ int main() {
1256 return fail("Adapter CheckInterfaceSupport(IDXGIDevice) failed"); 1263 return fail("Adapter CheckInterfaceSupport(IDXGIDevice) failed");
1257 IDXGIFactory4* host_factory = nullptr; 1264 IDXGIFactory4* host_factory = nullptr;
1258 IDXGIAdapter1* host_adapter = nullptr; 1265 IDXGIAdapter1* host_adapter = nullptr;
1259 // The host dxgi.dll, loaded at run time: this test doesn't link it, and a Wine run without it skips. 1266 // The host dxgi.dll, loaded at run time: this test doesn't link it. Not under Wine, whose DXGI makes up a
1260 HMODULE host_dxgi = LoadLibraryW(L"dxgi.dll"); 1267 // version of its own for the adapter (host_wine.h).
1268 HMODULE host_dxgi = hostwine::host_is_wine() ? nullptr : LoadLibraryW(L"dxgi.dll");
1261 const auto create_factory = host_dxgi ? reinterpret_cast<decltype(&CreateDXGIFactory1)>( 1269 const auto create_factory = host_dxgi ? reinterpret_cast<decltype(&CreateDXGIFactory1)>(
1262 GetProcAddress(host_dxgi, "CreateDXGIFactory1")) : nullptr; 1270 GetProcAddress(host_dxgi, "CreateDXGIFactory1")) : nullptr;
1263 if (create_factory && SUCCEEDED(create_factory(IID_PPV_ARGS(&host_factory))) && host_factory && 1271 if (create_factory && SUCCEEDED(create_factory(IID_PPV_ARGS(&host_factory))) && host_factory &&
diff --git a/runtime/test/dxgi_waitable_latency_test.cpp b/runtime/test/dxgi_waitable_latency_test.cpp
index 96e597d5e..d870c53e1 100644
--- a/runtime/test/dxgi_waitable_latency_test.cpp
+++ b/runtime/test/dxgi_waitable_latency_test.cpp
@@ -2,7 +2,8 @@
2// (IDXGISwapChain2::SetMaximumFrameLatency, GetMaximumFrameLatency, GetFrameLatencyWaitableObject, 2// (IDXGISwapChain2::SetMaximumFrameLatency, GetMaximumFrameLatency, GetFrameLatencyWaitableObject,
3// Present, Present(DXGI_PRESENT_TEST), ResizeBuffers). 3// Present, Present(DXGI_PRESENT_TEST), ResizeBuffers).
4// Compares Leonida's Vulkan-backed DXGI shim directly against live Windows host d3d12.dll / dxgi.dll 4// Compares Leonida's Vulkan-backed DXGI shim directly against live Windows host d3d12.dll / dxgi.dll
5// when available, and validates all contracts independently. 5// when available, and validates all contracts independently. Under Wine the host suite is skipped (host_wine.h: its
6// dxgi faults on GetMaximumFrameLatency(null)) and the layer's own contracts are still checked.
6// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation (Core + Synchronization Validation). 7// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation (Core + Synchronization Validation).
7#ifndef VK_USE_PLATFORM_WIN32_KHR 8#ifndef VK_USE_PLATFORM_WIN32_KHR
8#define VK_USE_PLATFORM_WIN32_KHR 9#define VK_USE_PLATFORM_WIN32_KHR
@@ -11,6 +12,7 @@
11#include "../shims/d3d12_com.h" 12#include "../shims/d3d12_com.h"
12#include "../shims/dxgi_com.h" 13#include "../shims/dxgi_com.h"
13#include "../src/vulkan_device_filter.h" 14#include "../src/vulkan_device_filter.h"
15#include "host_wine.h"
14#include "vulkan_loader.h" 16#include "vulkan_loader.h"
15#include "window_station.h" 17#include "window_station.h"
16 18
@@ -795,7 +797,7 @@ int main() {
795 reinterpret_cast<void*>(GetProcAddress(host_dxgi, "CreateDXGIFactory2"))) 797 reinterpret_cast<void*>(GetProcAddress(host_dxgi, "CreateDXGIFactory2")))
796 : nullptr; 798 : nullptr;
797 bool compared_host = false; 799 bool compared_host = false;
798 if (create_host_dev && create_host_fac) { 800 if (create_host_dev && create_host_fac && !hostwine::host_is_wine()) {
799 IDXGIFactory4* hfac = nullptr; 801 IDXGIFactory4* hfac = nullptr;
800 ID3D12Device* hdev = nullptr; 802 ID3D12Device* hdev = nullptr;
801 ID3D12CommandQueue* hq = nullptr; 803 ID3D12CommandQueue* hq = nullptr;
diff --git a/runtime/test/file_system_test.cpp b/runtime/test/file_system_test.cpp
index 299ceda3b..493ffd6bf 100644
--- a/runtime/test/file_system_test.cpp
+++ b/runtime/test/file_system_test.cpp
@@ -551,8 +551,8 @@ void run_checks(const std::filesystem::path& root) {
551 check(delete_w(L"GAME:\\data\\bye.txt") == FALSE && GetLastError() == ERROR_FILE_NOT_FOUND, 551 check(delete_w(L"GAME:\\data\\bye.txt") == FALSE && GetLastError() == ERROR_FILE_NOT_FOUND,
552 "deleting an already hidden file reports ERROR_FILE_NOT_FOUND"); 552 "deleting an already hidden file reports ERROR_FILE_NOT_FOUND");
553 SetLastError(0); 553 SetLastError(0);
554 check(delete_w(L"GAME:\\nope\\missing.txt") == FALSE && GetLastError() == ERROR_FILE_NOT_FOUND, 554 check(delete_w(L"GAME:\\nope\\missing.txt") == FALSE && GetLastError() == ERROR_PATH_NOT_FOUND,
555 "deleting a file that never existed reports ERROR_FILE_NOT_FOUND"); 555 "deleting a file in a folder that never existed reports ERROR_PATH_NOT_FOUND");
556 556
557 // Deleting a nested package file creates parent directories inside .gta6rt-deleted/; those marker parent 557 // Deleting a nested package file creates parent directories inside .gta6rt-deleted/; those marker parent
558 // directories must not hide the corresponding ancestor directories in the package. 558 // directories must not hide the corresponding ancestor directories in the package.
@@ -768,6 +768,49 @@ void run_checks(const std::filesystem::path& root) {
768 "and the new folder is empty: only . and .."); 768 "and the new folder is empty: only . and ..");
769 } 769 }
770 770
771 {
772 const std::filesystem::path host = root / "host_missing";
773 write_path(host / "file.txt", "file");
774 const std::wstring host_dest = (host / "dest.txt").wstring();
775 auto error_of = [](BOOL ok) { return ok ? DWORD{0} : GetLastError(); };
776 struct Name {
777 const wchar_t* game;
778 std::filesystem::path host;
779 DWORD expected;
780 const char* what;
781 };
782 const Name names[] = {
783 {L"GAME:\\nowhere\\x.txt", host / "nowhere" / "x.txt", ERROR_PATH_NOT_FOUND, "inside a missing folder"},
784 {L"GAME:\\misc\\keep.txt\\x.txt", host / "file.txt" / "x.txt", ERROR_PATH_NOT_FOUND, "below a file"},
785 {L"GAME:\\misc\\absent.txt", host / "absent.txt", ERROR_FILE_NOT_FOUND, "missing from a folder that exists"},
786 };
787 for (const Name& n : names) {
788 const std::wstring native = n.host.wstring();
789 const std::string suffix = std::string(" of a name ") + n.what + " fails as on the host";
790 SetLastError(0);
791 const DWORD host_delete = error_of(::DeleteFileW(native.c_str()));
792 SetLastError(0);
793 check(error_of(delete_w(n.game)) == n.expected && host_delete == n.expected, ("DeleteFileW" + suffix).c_str());
794 SetLastError(0);
795 const DWORD host_rmdir = error_of(::RemoveDirectoryW(native.c_str()));
796 SetLastError(0);
797 check(error_of(rmdir_w(n.game)) == n.expected && host_rmdir == n.expected,
798 ("RemoveDirectoryW" + suffix).c_str());
799 SetLastError(0);
800 const DWORD host_setattr = error_of(::SetFileAttributesW(native.c_str(), FILE_ATTRIBUTE_NORMAL));
801 SetLastError(0);
802 check(error_of(setattr_w(n.game, FILE_ATTRIBUTE_NORMAL)) == n.expected && host_setattr == n.expected,
803 ("SetFileAttributesW" + suffix).c_str());
804 SetLastError(0);
805 const DWORD host_move = error_of(::MoveFileExW(native.c_str(), host_dest.c_str(), MOVEFILE_REPLACE_EXISTING));
806 SetLastError(0);
807 check(error_of(move_ex_w(n.game, L"GAME:\\misc\\dest.txt", MOVEFILE_REPLACE_EXISTING)) == n.expected &&
808 host_move == n.expected,
809 ("MoveFileExW" + suffix).c_str());
810 }
811 check(!std::filesystem::exists(overlay / "nowhere") && !std::filesystem::exists(overlay / "misc" / "dest.txt"),
812 "and none of them leaves anything in the overlay");
813 }
771 // Recreating a removed package directory clears its own marker, but not nested deletion markers. 814 // Recreating a removed package directory clears its own marker, but not nested deletion markers.
772 { 815 {
773 std::filesystem::create_directories(package / "recreate_dir"); 816 std::filesystem::create_directories(package / "recreate_dir");
diff --git a/runtime/test/fixtures/tiny_ga_tls.cpp b/runtime/test/fixtures/tiny_ga_tls.cpp
index 493ec8b97..01dd03ea6 100644
--- a/runtime/test/fixtures/tiny_ga_tls.cpp
+++ b/runtime/test/fixtures/tiny_ga_tls.cpp
@@ -7,6 +7,9 @@ __declspec(thread) int g_ga_tls_value = 7;
7 7
8extern "C" __declspec(dllexport) int ga_tls_get() { return g_ga_tls_value; } 8extern "C" __declspec(dllexport) int ga_tls_get() { return g_ga_tls_value; }
9extern "C" __declspec(dllexport) void ga_tls_set(int value) { g_ga_tls_value = value; } 9extern "C" __declspec(dllexport) void ga_tls_set(int value) { g_ga_tls_value = value; }
10// Where this code looks for the variable on the calling thread: ThreadLocalStoragePointer[0] plus the variable's
11// offset, with no read of the variable itself. The test uses it to tell whose block index 0 resolved to.
12extern "C" __declspec(dllexport) void* ga_tls_address() { return &g_ga_tls_value; }
10 13
11int main() { 14int main() {
12 return 0; 15 return 0;
diff --git a/runtime/test/fixtures/tiny_game.cpp b/runtime/test/fixtures/tiny_game.cpp
index c0088eea4..cd456f497 100644
--- a/runtime/test/fixtures/tiny_game.cpp
+++ b/runtime/test/fixtures/tiny_game.cpp
@@ -6,6 +6,8 @@
6// calls exit() with 0 (42 with `exit-code`) when everything held. Two checks are opt-in, by argument (CTest's 6// calls exit() with 0 (42 with `exit-code`) when everything held. Two checks are opt-in, by argument (CTest's
7// run_tiny_game_tls and run_tiny_game_eh): `tls`, thread_local on the game's own threads, which needs the loader's 7// run_tiny_game_tls and run_tiny_game_eh): `tls`, thread_local on the game's own threads, which needs the loader's
8// per-thread TLS (gta6rt starts main on a separate thread); and `eh`, a C++ exception caught inside the image. 8// per-thread TLS (gta6rt starts main on a separate thread); and `eh`, a C++ exception caught inside the image.
9// run_tiny_game_ga_tls runs `tls` on tiny_game_ga, this file built with /GA: its thread_local reads then take module
10// TLS index 0 without _tls_index, as a title's executable does, and under gta6rt that index is gta6rt.exe's own.
9// A third, `game-file` (run_tiny_game_dir), reads GAME:\tiny_game_probe.txt after moving the current directory. 11// A third, `game-file` (run_tiny_game_dir), reads GAME:\tiny_game_probe.txt after moving the current directory.
10// A fourth, `stack` (run_tiny_game_stack), checks that the entry thread and a thread created with dwStackSize 0 12// A fourth, `stack` (run_tiny_game_stack), checks that the entry thread and a thread created with dwStackSize 0
11// both have 8 MB of stack: a driver compiles shaders on the game's threads (BUILD-1457). Only under gta6rt: run 13// both have 8 MB of stack: a driver compiles shaders on the game's threads (BUILD-1457). Only under gta6rt: run
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/gameinput_test.cpp b/runtime/test/gameinput_test.cpp
index 93c48518b..b6658f51c 100644
--- a/runtime/test/gameinput_test.cpp
+++ b/runtime/test/gameinput_test.cpp
@@ -1693,12 +1693,14 @@ void test_haptic_motors(IGameInput* input) {
1693 1693
1694} // namespace 1694} // namespace
1695 1695
1696int main() { 1696int main(int argc, char** argv) {
1697 // Only virtual pads: no real controller on the test machine may show up. 1697 // Only virtual pads: no real controller on the test machine may show up.
1698 for (const char* hint : {SDL_HINT_JOYSTICK_HIDAPI, SDL_HINT_JOYSTICK_RAWINPUT, SDL_HINT_JOYSTICK_WGI, 1698 for (const char* hint : {SDL_HINT_JOYSTICK_HIDAPI, SDL_HINT_JOYSTICK_RAWINPUT, SDL_HINT_JOYSTICK_WGI,
1699 SDL_HINT_JOYSTICK_GAMEINPUT, SDL_HINT_XINPUT_ENABLED, SDL_HINT_JOYSTICK_DIRECTINPUT}) 1699 SDL_HINT_JOYSTICK_GAMEINPUT, SDL_HINT_XINPUT_ENABLED, SDL_HINT_JOYSTICK_DIRECTINPUT})
1700 SDL_SetHintWithPriority(hint, "0", SDL_HINT_OVERRIDE); 1700 SDL_SetHintWithPriority(hint, "0", SDL_HINT_OVERRIDE);
1701 set_env("LEONIDA_GAMEINPUT_THREAD", "0"); 1701 set_env("LEONIDA_GAMEINPUT_THREAD", "0");
1702 set_env("LEONIDA_KEYBOARD_PAD", nullptr);
1703 set_env("LEONIDA_INPUT_SCRIPT", nullptr);
1702 set_env("LEONIDA_DS_TRIGGERS", nullptr); 1704 set_env("LEONIDA_DS_TRIGGERS", nullptr);
1703 set_env("LEONIDA_DS_LIGHTBAR", nullptr); 1705 set_env("LEONIDA_DS_LIGHTBAR", nullptr);
1704 set_env("LEONIDA_RUMBLE", nullptr); 1706 set_env("LEONIDA_RUMBLE", nullptr);
@@ -1714,6 +1716,38 @@ int main() {
1714 1716
1715 IGameInput* input = nullptr; 1717 IGameInput* input = nullptr;
1716 check(create(&input) == S_OK && input, "GameInputCreate returns an instance"); 1718 check(create(&input) == S_OK && input, "GameInputCreate returns an instance");
1719 if (argc == 2 && std::strcmp(argv[1], "--input-script") == 0) {
1720 if (!input) return 1;
1721 // Only the X after byte 63 is due now. Its later entry must not cancel it.
1722 set_env("LEONIDA_INPUT_SCRIPT",
1723 "start@3600,start@3600,start@3600,start@3600,start@3600,start@3600, X@0 \t,x@3600,"
1724 "unknown@0,a@,a@x,,a@-0.1,a@nan,a@inf,a@1e999,a@0tail, ,");
1725 set_env("LEONIDA_KEYBOARD_PAD", "1");
1726 rt::gameinput::set_keyboard_source(fake_key_down, fake_focus);
1727 rt::gameinput::set_cursor_source(fake_cursor);
1728 g_focus = true;
1729 g_keys[VK_BACK] = true;
1730 rt::gameinput::reload_config();
1731 rt::gameinput::poll();
1732 const auto buttons = pad_state(input, nullptr).buttons;
1733 const auto expected = GameInputGamepadX | GameInputGamepadB;
1734 check((buttons & expected) == expected, "long script: the spaced X after byte 63 and the physical B are held");
1735 check((buttons & ~expected) == 0, "malformed script entries hold no extra buttons");
1736 g_focus = false;
1737 set_env("LEONIDA_INPUT_SCRIPT", "y@0");
1738 rt::gameinput::reload_config();
1739 rt::gameinput::poll();
1740 check(pad_state(input, nullptr).buttons == GameInputGamepadX,
1741 "scripted X survives focus loss; reload does not replace it with Y");
1742 Sleep(350);
1743 g_focus = true;
1744 rt::gameinput::poll();
1745 check(pad_state(input, nullptr).buttons == GameInputGamepadB,
1746 "long script: the timed press ends while the physical key stays held");
1747 input->Release();
1748 std::printf("%d checks, %d failures\n", g_checks, g_failures);
1749 return g_failures ? 1 : 0;
1750 }
1717 check(create(nullptr) == E_POINTER, "GameInputCreate(nullptr) is E_POINTER"); 1751 check(create(nullptr) == E_POINTER, "GameInputCreate(nullptr) is E_POINTER");
1718 IUnknown* unk = nullptr; 1752 IUnknown* unk = nullptr;
1719 check(input->QueryInterface(IID_IGameInput, reinterpret_cast<void**>(&unk)) == S_OK && unk == input, 1753 check(input->QueryInterface(IID_IGameInput, reinterpret_cast<void**>(&unk)) == S_OK && unk == input,
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..26d846147 100644
--- a/runtime/test/loader_tls_test.cpp
+++ b/runtime/test/loader_tls_test.cpp
@@ -24,6 +24,9 @@
24 24
25#include "pe_loader.h" 25#include "pe_loader.h"
26 26
27// The CRT's record of the module TLS index Windows gave this EXE.
28extern "C" unsigned long _tls_index;
29
27namespace { 30namespace {
28 31
29namespace fs = std::filesystem; 32namespace fs = std::filesystem;
@@ -790,7 +793,8 @@ void test_ga_tls_existing_thread(const fs::path& exe) {
790 { 793 {
791 rt::Loader loader(exe.parent_path()); 794 rt::Loader loader(exe.parent_path());
792 rt::Module& m = loader.load(exe); 795 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"); 796 check(m.tls_index != rt::kNoTlsIndex && m.tls_index != 0,
797 "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"); 798 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"); 799 get = find_export<int(__cdecl*)()>(m, "ga_tls_get");
796 set = find_export<void(__cdecl*)(int)>(m, "ga_tls_set"); 800 set = find_export<void(__cdecl*)(int)>(m, "ga_tls_set");
@@ -818,6 +822,163 @@ void test_ga_tls_existing_thread(const fs::path& exe) {
818 for (HANDLE h : {first.go, first.done, second.go, second.done, started}) CloseHandle(h); 822 for (HANDLE h : {first.go, first.done, second.go, second.done, started}) CloseHandle(h);
819} 823}
820 824
825// This EXE's TLS template size, from its own TLS directory: the size of the block Windows puts at its index.
826uint64_t own_tls_template_size() {
827 const auto* base = reinterpret_cast<const uint8_t*>(GetModuleHandleW(nullptr));
828 const auto* dos = reinterpret_cast<const IMAGE_DOS_HEADER*>(base);
829 const auto* nt = reinterpret_cast<const IMAGE_NT_HEADERS64*>(base + dos->e_lfanew);
830 const auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_TLS];
831 if (!dir.Size || !dir.VirtualAddress) return 0;
832 const auto* tls = reinterpret_cast<const IMAGE_TLS_DIRECTORY64*>(base + dir.VirtualAddress);
833 return tls->EndAddressOfRawData - tls->StartAddressOfRawData;
834}
835
836// Sets an environment variable for one scope. An empty value removes it.
837struct ScopedEnv {
838 std::string name, previous;
839 bool had = false;
840 ScopedEnv(const char* variable, const char* value) : name(variable) {
841 char buffer[64] = {};
842 size_t size = 0;
843 had = getenv_s(&size, buffer, name.c_str()) == 0 && size > 0;
844 if (had) previous = buffer;
845 _putenv_s(name.c_str(), value);
846 }
847 ~ScopedEnv() { _putenv_s(name.c_str(), had ? previous.c_str() : ""); }
848 ScopedEnv(const ScopedEnv&) = delete;
849 ScopedEnv& operator=(const ScopedEnv&) = delete;
850};
851
852// BL-1 (docs/boot_leads.md): code built with /GA reads ThreadLocalStoragePointer[0] and takes the block there for
853// its own executable's, while a second mapped module has static TLS of its own. Index 0 of the process belongs to
854// the EXE Windows started: this test here, gta6rt.exe in a real run. ga_tls_address() says where the fixture's code
855// looks for its variable, so the checks name whose block index 0 resolved to. With the rewrite off it is this EXE's
856// block, which is stop 4 of docs/retail_boot_chain.md. As load() leaves the image by default, it is the fixture's
857// own block, on the loading thread and on a thread started later, with tiny_tls.dll's block at its own index
858// beside it and this EXE's block still at index 0 of the thread's TLS array.
859void test_ga_exe_beside_tls_module(const fs::path& exe, const fs::path& dll) {
860 std::printf("\n-- /GA EXE reading index 0 beside a second TLS module --\n");
861 const auto offset_in = [](const void* address, const void* block) {
862 return static_cast<const uint8_t*>(address) - static_cast<const uint8_t*>(block);
863 };
864 void* const host_block = module_tls_slots()[0];
865 const ptrdiff_t sentinel_offset = offset_in(&g_host_tls_sentinel, host_block);
866 check(_tls_index == 0, "this EXE has module TLS index 0, as the process EXE does");
867 check(sentinel_offset >= 0 && static_cast<uint64_t>(sentinel_offset) + sizeof(int) <= own_tls_template_size(),
868 "its own thread-local variable is in the block at index 0");
869
870 // The fixture as built. Only the address is taken: reading or writing there would use this EXE's TLS.
871 ptrdiff_t offset = -1; // of the fixture's variable in a TLS block
872 {
873 ScopedEnv rewrite_off("LEONIDA_TLS_GA_PATCH", "0");
874 rt::Loader loader(exe.parent_path());
875 rt::Module& game = loader.load(exe);
876 check(game.tls_ga_slot == rt::kNoTlsIndex && game.tls_index != rt::kNoTlsIndex && game.tls_index != 0,
877 "with LEONIDA_TLS_GA_PATCH=0 the fixture is left as built, at a module TLS index that is not 0");
878 const auto address = find_export<void*(__cdecl*)()>(game, "ga_tls_address");
879 offset = offset_in(address(), host_block);
880 check(offset >= 0 && static_cast<uint64_t>(offset) + sizeof(int) <= game.tls_block_size,
881 "as built, its code looks for its variable in the block at index 0, which is this EXE's (stop 4)");
882 check(module_tls_slots()[game.tls_index] == game.tls_block && game.tls_block != host_block,
883 "while its own block sits at its module index, where that code never looks");
884 }
885
886 struct Seen {
887 int host = -1, host_after = -1;
888 int game = -1, lib = -1, game_after = -1, lib_after = -1;
889 void* address = nullptr; // where the fixture's code looks for its variable
890 void* view0 = nullptr; // [0] of the array that code reads
891 void* at_index0 = nullptr; // the thread's real TLS array: index 0, the fixture's index, the DLL's index
892 void* at_game = nullptr;
893 void* at_lib = nullptr;
894 ptrdiff_t sentinel_offset = -1;
895 };
896 uint32_t ga_slot = rt::kNoTlsIndex;
897 {
898 rt::Loader loader(exe.parent_path());
899 rt::Module& game = loader.load(exe);
900 rt::Module& lib = loader.load(dll);
901 loader.initialise(); // from here on thread events run both images' TLS callbacks
902 ga_slot = game.tls_ga_slot;
903 check(game.tls_index != rt::kNoTlsIndex && lib.tls_index != rt::kNoTlsIndex && game.tls_index != 0 &&
904 lib.tls_index != 0 && game.tls_index != lib.tls_index,
905 "the EXE and the DLL each get a module TLS index of their own, neither of them 0");
906 check(ga_slot != rt::kNoTlsIndex, "by default load() rewrites the EXE's index-0 TLS reads");
907 if (ga_slot == rt::kNoTlsIndex) return; // nothing below can hold, and this EXE's TLS must not be written
908
909 const auto game_get = find_export<int(__cdecl*)()>(game, "ga_tls_get");
910 const auto game_set = find_export<void(__cdecl*)(int)>(game, "ga_tls_set");
911 const auto game_address = find_export<void*(__cdecl*)()>(game, "ga_tls_address");
912 const auto lib_get = find_export<int(__cdecl*)()>(lib, "tiny_tls_get");
913 const auto lib_set = find_export<void(__cdecl*)(int)>(lib, "tiny_tls_set");
914 const auto lib_watch = find_export<void(__cdecl*)(DWORD)>(lib, "tiny_tls_watch_thread");
915 const auto lib_thread_attach = find_export<int(__cdecl*)()>(lib, "tiny_tls_thread_attach_count");
916 const auto lib_thread_detach = find_export<int(__cdecl*)()>(lib, "tiny_tls_thread_detach_count");
917 const auto lib_value_at_attach = find_export<int(__cdecl*)()>(lib, "tiny_tls_value_at_thread_attach");
918
919 const auto look = [&](Seen& seen, int game_value, int lib_value) {
920 seen.host = g_host_tls_sentinel;
921 seen.game = game_get();
922 seen.lib = lib_get();
923 game_set(game_value);
924 lib_set(lib_value);
925 seen.game_after = game_get();
926 seen.lib_after = lib_get();
927 seen.address = game_address();
928 auto* view = static_cast<void**>(TlsGetValue(ga_slot));
929 seen.view0 = view ? view[0] : nullptr;
930 void** slots = module_tls_slots();
931 seen.at_index0 = slots[0];
932 seen.at_game = slots[game.tls_index];
933 seen.at_lib = slots[lib.tls_index];
934 seen.sentinel_offset = offset_in(&g_host_tls_sentinel, slots[0]);
935 seen.host_after = g_host_tls_sentinel;
936 };
937
938 Seen here;
939 look(here, 11, 22);
940 check(here.game == 7 && here.lib == 7, "the loading thread reads both templates' value 7");
941 check(here.game_after == 11 && here.lib_after == 22, "and its writes to the two modules stay apart");
942 check(here.address == static_cast<uint8_t*>(game.tls_block) + offset,
943 "the EXE's index-0 read resolves to its own block on the loading thread");
944 check(here.view0 == game.tls_block && here.at_game == game.tls_block,
945 "that block is at [0] of the array its code reads and at its module index");
946 check(here.at_lib == lib.tls_block && lib.tls_block != game.tls_block,
947 "the DLL's block is at the DLL's own index");
948 check(here.at_index0 == host_block && here.sentinel_offset == sentinel_offset && here.host == 2 &&
949 here.host_after == 2,
950 "this EXE's block is still at index 0 of the thread's TLS array, its value unchanged");
951
952 Seen there;
953 int attach_inside = -1;
954 auto body = [&] {
955 attach_inside = lib_thread_attach();
956 look(there, 33, 44);
957 };
958 WatchedThread thread(lib_watch, &body);
959 thread.join();
960 check(there.game == 7 && there.lib == 7,
961 "a thread started after load() reads both templates' value 7, not 11 and 22");
962 check(there.game_after == 33 && there.lib_after == 44, "and its writes to the two modules stay apart");
963 check(there.view0 != nullptr && there.view0 != game.tls_block &&
964 there.address == static_cast<uint8_t*>(there.view0) + offset,
965 "on that thread the EXE's index-0 read resolves to the thread's own copy");
966 check(there.at_game == there.view0, "which is also at the EXE's module index there");
967 check(there.at_lib != nullptr && there.at_lib != lib.tls_block && there.at_lib != there.view0,
968 "the DLL has a copy of its own at its own index there");
969 check(there.at_index0 != host_block && there.at_index0 != there.view0 &&
970 there.sentinel_offset == sentinel_offset && there.host == 1 && there.host_after == 1,
971 "index 0 of that thread's TLS array is its copy of this EXE's TLS, its value unchanged");
972 check(attach_inside == 1 && lib_thread_detach() == 1 && lib_value_at_attach() == 7,
973 "the DLL's TLS callback got that thread's attach and detach, with its copy in place");
974 check(game_get() == 11 && lib_get() == 22 && g_host_tls_sentinel == 2,
975 "the loading thread's three values are unchanged by the other thread");
976 }
977 check(module_tls_slots()[0] == host_block && g_host_tls_sentinel == 2,
978 "~Loader leaves this EXE's block at index 0");
979 check(TlsGetValue(ga_slot) == nullptr, "and takes the EXE's view out of the loading thread");
980}
981
821void print_result() { 982void print_result() {
822 if (g_failures == 0) 983 if (g_failures == 0)
823 std::printf("\nloader_tls_test: OK (%d checks)\n", g_checks); 984 std::printf("\nloader_tls_test: OK (%d checks)\n", g_checks);
@@ -857,6 +1018,7 @@ int main(int argc, char** argv) {
857 const fs::path ga_exe = tls_dll.parent_path() / "tiny_ga_tls.exe"; 1018 const fs::path ga_exe = tls_dll.parent_path() / "tiny_ga_tls.exe";
858 check(fs::exists(ga_exe), "tiny_ga_tls fixture exists"); 1019 check(fs::exists(ga_exe), "tiny_ga_tls fixture exists");
859 if (fs::exists(ga_exe)) test_ga_tls_existing_thread(ga_exe); 1020 if (fs::exists(ga_exe)) test_ga_tls_existing_thread(ga_exe);
1021 if (fs::exists(ga_exe)) test_ga_exe_beside_tls_module(ga_exe, tls_dll);
860 check(g_host_tls_sentinel == 2, "this EXE's own TLS at module index 0 is untouched"); 1022 check(g_host_tls_sentinel == 2, "this EXE's own TLS at module index 0 is untouched");
861 1023
862 // The --run path calls cleanup_tls_clones() before ExitProcess because atexit never runs there. 1024 // The --run path calls cleanup_tls_clones() before ExitProcess because atexit never runs there.
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/pipeline_cache_seed_test.cpp b/runtime/test/pipeline_cache_seed_test.cpp
new file mode 100644
index 000000000..782a0707c
--- /dev/null
+++ b/runtime/test/pipeline_cache_seed_test.cpp
@@ -0,0 +1,418 @@
1// The cache vk_pipeline_check saves has to hit on the runtime's device:
2// pipeline_cache_seed_test <vk_pipeline_check.exe>
3//
4// Writes a synthetic minimal compute SPIR-V module and index.json to a temporary directory, runs a copy of
5// vk_pipeline_check named after this test executable (a driver can make the executable file name part of the pipeline
6// cache key, see docs/pipeline_check.md), and then creates the exact same pipeline on the runtime's own device
7// (create_vulkan_device_standalone) from the saved cache. Passes when Vulkan creation feedback reports an
8// application pipeline cache hit.
9//
10// Exit 77 (skipped): no Vulkan device for the runtime, pre-Vulkan 1.3 device without core pipeline creation feedback,
11// vk_pipeline_check built no pipeline, cache written for another GPU/driver, or a driver that reports no hit even for
12// a cache this device wrote itself a moment before.
13#include "../shims/d3d12_com.h"
14#include "../src/shader_library.h"
15
16#include <wrl/client.h>
17
18#include <array>
19#include <cstdint>
20#include <cstdio>
21#include <cstring>
22#include <filesystem>
23#include <fstream>
24#include <iterator>
25#include <string>
26#include <system_error>
27#include <vector>
28
29namespace {
30
31// Minimal valid SPIR-V 1.0 compute shader: `void main() {}` with LocalSize(1, 1, 1).
32constexpr std::array<std::uint32_t, 35> kMinimalComputeSpv = {
33 0x07230203u, 0x00010000u, 0u, 6u, 0u,
34 (2u << 16) | 17u, 1u, // OpCapability Shader
35 (3u << 16) | 14u, 0u, 1u, // OpMemoryModel Logical GLSL450
36 (5u << 16) | 15u, 5u, 4u, 0x6e69616du, 0x00000000u, // OpEntryPoint GLCompute %4 "main"
37 (6u << 16) | 16u, 4u, 17u, 1u, 1u, 1u, // OpExecutionMode %4 LocalSize 1 1 1
38 (2u << 16) | 19u, 2u, // %2 = OpTypeVoid
39 (3u << 16) | 33u, 3u, 2u, // %3 = OpTypeFunction %2
40 (5u << 16) | 54u, 2u, 4u, 0u, 3u, // %4 = OpFunction %2 None %3
41 (2u << 16) | 248u, 5u, // %5 = OpLabel
42 (1u << 16) | 253u, // OpReturn
43 (1u << 16) | 56u, // OpFunctionEnd
44};
45
46struct TempDirGuard {
47 std::filesystem::path path;
48 ~TempDirGuard() {
49 if (!path.empty()) {
50 std::error_code ec;
51 std::filesystem::remove_all(path, ec);
52 }
53 }
54};
55
56struct UniqueHandle {
57 HANDLE h = nullptr;
58 UniqueHandle() = default;
59 explicit UniqueHandle(HANDLE handle) : h(handle) {}
60 ~UniqueHandle() { reset(); }
61 UniqueHandle(const UniqueHandle&) = delete;
62 UniqueHandle& operator=(const UniqueHandle&) = delete;
63 void reset(HANDLE next = nullptr) {
64 if (h && h != INVALID_HANDLE_VALUE) CloseHandle(h);
65 h = next;
66 }
67 HANDLE get() const { return h; }
68};
69
70struct VulkanObjects {
71 VkDevice device = VK_NULL_HANDLE;
72 PFN_vkDestroyShaderModule destroy_module = nullptr;
73 PFN_vkDestroyPipelineLayout destroy_layout = nullptr;
74 PFN_vkDestroyPipelineCache destroy_cache = nullptr;
75 VkShaderModule shader = VK_NULL_HANDLE;
76 VkPipelineLayout layout = VK_NULL_HANDLE;
77 VkPipelineCache seeded = VK_NULL_HANDLE;
78 VkPipelineCache first = VK_NULL_HANDLE;
79 VkPipelineCache second = VK_NULL_HANDLE;
80 ~VulkanObjects() {
81 if (!device) return;
82 if (second && destroy_cache) destroy_cache(device, second, nullptr);
83 if (first && destroy_cache) destroy_cache(device, first, nullptr);
84 if (seeded && destroy_cache) destroy_cache(device, seeded, nullptr);
85 if (layout && destroy_layout) destroy_layout(device, layout, nullptr);
86 if (shader && destroy_module) destroy_module(device, shader, nullptr);
87 }
88};
89
90struct Created {
91 bool ok = false;
92 bool hit = false;
93};
94
95std::vector<char> read_file(const std::filesystem::path& path) {
96 std::ifstream file(path, std::ios::binary);
97 return {std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>()};
98}
99
100bool write_bytes(const std::filesystem::path& path, const void* data, std::size_t size) {
101 std::ofstream file(path, std::ios::binary | std::ios::trunc);
102 if (!file) return false;
103 file.write(static_cast<const char*>(data), static_cast<std::streamsize>(size));
104 file.flush();
105 return file.good();
106}
107
108std::filesystem::path create_temp_dir() {
109 std::wstring base(MAX_PATH, L'\0');
110 const DWORD len = GetTempPathW(static_cast<DWORD>(base.size()), base.data());
111 std::filesystem::path root;
112 if (len > 0 && len < base.size()) {
113 base.resize(len);
114 root = base;
115 } else {
116 std::error_code ec;
117 root = std::filesystem::temp_directory_path(ec);
118 if (ec) return {};
119 }
120 const std::wstring name =
121 L"leonida_pipeline_cache_seed_" + std::to_wstring(GetCurrentProcessId()) + L"_" +
122 std::to_wstring(GetTickCount64());
123 const std::filesystem::path dir = root / name;
124 std::error_code ec;
125 std::filesystem::remove_all(dir, ec);
126 if (!std::filesystem::create_directories(dir, ec) && !std::filesystem::is_directory(dir, ec)) return {};
127 return dir;
128}
129
130std::wstring self_filename() {
131 std::wstring path(MAX_PATH, L'\0');
132 for (;;) {
133 const DWORD len = GetModuleFileNameW(nullptr, path.data(), static_cast<DWORD>(path.size()));
134 if (len == 0) return {};
135 if (len < path.size()) {
136 path.resize(len);
137 return std::filesystem::path(path).filename().native();
138 }
139 if (path.size() >= 32768) return {};
140 path.resize(path.size() * 2);
141 }
142}
143
144void append_quoted_arg(std::wstring& out, const std::wstring& arg) {
145 if (!out.empty()) out.push_back(L' ');
146 out.push_back(L'"');
147 std::size_t backslashes = 0;
148 for (wchar_t ch : arg) {
149 if (ch == L'\\') {
150 ++backslashes;
151 } else if (ch == L'"') {
152 out.append(backslashes * 2 + 1, L'\\');
153 out.push_back(L'"');
154 backslashes = 0;
155 } else {
156 out.append(backslashes, L'\\');
157 backslashes = 0;
158 out.push_back(ch);
159 }
160 }
161 out.append(backslashes * 2, L'\\');
162 out.push_back(L'"');
163}
164
165bool run_checker_process(const std::filesystem::path& exe, const std::filesystem::path& spirv_dir,
166 const std::filesystem::path& cache_path, const std::filesystem::path& log_path,
167 DWORD& exit_code) {
168 SECURITY_ATTRIBUTES sa{};
169 sa.nLength = sizeof(sa);
170 sa.bInheritHandle = TRUE;
171 UniqueHandle log_file(CreateFileW(log_path.c_str(), GENERIC_WRITE, FILE_SHARE_READ, &sa, CREATE_ALWAYS,
172 FILE_ATTRIBUTE_NORMAL, nullptr));
173 if (log_file.get() == INVALID_HANDLE_VALUE) return false;
174
175 std::wstring cmd_line;
176 append_quoted_arg(cmd_line, exe.native());
177 append_quoted_arg(cmd_line, spirv_dir.native());
178 append_quoted_arg(cmd_line, cache_path.native());
179 append_quoted_arg(cmd_line, L"--jobs");
180 append_quoted_arg(cmd_line, L"1");
181
182 STARTUPINFOW si{};
183 si.cb = sizeof(si);
184 si.dwFlags = STARTF_USESTDHANDLES;
185 si.hStdOutput = log_file.get();
186 si.hStdError = log_file.get();
187
188 PROCESS_INFORMATION pi{};
189 const BOOL started =
190 CreateProcessW(exe.c_str(), cmd_line.data(), nullptr, nullptr, TRUE, 0, nullptr, nullptr, &si, &pi);
191 log_file.reset();
192 if (!started) return false;
193
194 UniqueHandle proc(pi.hProcess);
195 UniqueHandle thread(pi.hThread);
196 const DWORD wait = WaitForSingleObject(proc.get(), 120000);
197 if (wait != WAIT_OBJECT_0) {
198 TerminateProcess(proc.get(), 1);
199 WaitForSingleObject(proc.get(), 5000);
200 return false;
201 }
202 return GetExitCodeProcess(proc.get(), &exit_code) != FALSE;
203}
204
205} // namespace
206
207int wmain(int argc, wchar_t** argv) {
208 if (argc != 2 || !argv[1] || !*argv[1]) {
209 std::fprintf(stderr, "usage: pipeline_cache_seed_test <vk_pipeline_check.exe>\n");
210 return 2;
211 }
212 const std::filesystem::path checker_src(argv[1]);
213 std::error_code ec;
214 if (!std::filesystem::is_regular_file(checker_src, ec)) {
215 std::fprintf(stderr, "checker executable not found\n");
216 return 1;
217 }
218
219 TempDirGuard temp;
220 temp.path = create_temp_dir();
221 if (temp.path.empty()) {
222 std::fprintf(stderr, "failed to create temporary directory\n");
223 return 1;
224 }
225
226 Microsoft::WRL::ComPtr<ID3D12Device> d3d;
227 if (FAILED(rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(&d3d))) || !d3d) {
228 std::printf("SKIP: no Vulkan device for the runtime\n");
229 return 77;
230 }
231 const rt::d3d12::VulkanDeviceInfo* info = rt::d3d12::vulkan_device_info(d3d.Get());
232 if (!info || !info->get_instance_proc) return 1;
233 const VkDevice device = info->device;
234 const auto device_proc = reinterpret_cast<PFN_vkGetDeviceProcAddr>(
235 info->get_instance_proc(info->instance, "vkGetDeviceProcAddr"));
236 const auto physical_properties = reinterpret_cast<PFN_vkGetPhysicalDeviceProperties>(
237 info->get_instance_proc(info->instance, "vkGetPhysicalDeviceProperties"));
238 if (!device_proc || !physical_properties) return 1;
239
240#define LOAD(name) const auto name = reinterpret_cast<PFN_##name>(device_proc(device, #name))
241 LOAD(vkCreateShaderModule);
242 LOAD(vkDestroyShaderModule);
243 LOAD(vkCreatePipelineLayout);
244 LOAD(vkDestroyPipelineLayout);
245 LOAD(vkCreatePipelineCache);
246 LOAD(vkDestroyPipelineCache);
247 LOAD(vkGetPipelineCacheData);
248 LOAD(vkCreateComputePipelines);
249 LOAD(vkDestroyPipeline);
250#undef LOAD
251 if (!vkCreateShaderModule || !vkDestroyShaderModule || !vkCreatePipelineLayout || !vkDestroyPipelineLayout ||
252 !vkCreatePipelineCache || !vkDestroyPipelineCache || !vkGetPipelineCacheData || !vkCreateComputePipelines ||
253 !vkDestroyPipeline) {
254 return 1;
255 }
256
257 VkPhysicalDeviceProperties properties{};
258 physical_properties(info->physical, &properties);
259 if (properties.apiVersion < VK_API_VERSION_1_3) {
260 std::printf("SKIP: %s is pre-Vulkan 1.3 (no core pipeline creation feedback)\n", properties.deviceName);
261 return 77;
262 }
263
264 const std::filesystem::path spv_path = temp.path / L"seed.spv";
265 const std::filesystem::path index_path = temp.path / L"index.json";
266 const std::filesystem::path cache_path = temp.path / L"pipeline_cache.bin";
267 const std::filesystem::path log_path = temp.path / L"checker.log";
268 const std::filesystem::path checker_dir = temp.path / L"checker";
269 const std::wstring self_name = self_filename();
270 if (self_name.empty()) {
271 std::fprintf(stderr, "GetModuleFileNameW failed\n");
272 return 1;
273 }
274 if (!std::filesystem::create_directories(checker_dir, ec) && !std::filesystem::is_directory(checker_dir, ec)) {
275 std::fprintf(stderr, "failed to create checker staging directory\n");
276 return 1;
277 }
278 const std::filesystem::path checker_copy = checker_dir / self_name;
279 // CopyFileW rather than std::filesystem::copy_file: Wine 9 lacks CopyFile2.
280 if (!CopyFileW(checker_src.c_str(), checker_copy.c_str(), FALSE)) {
281 std::fprintf(stderr, "CopyFileW failed (%lu)\n", static_cast<unsigned long>(GetLastError()));
282 return 1;
283 }
284 if (!write_bytes(spv_path, kMinimalComputeSpv.data(), kMinimalComputeSpv.size() * sizeof(std::uint32_t))) {
285 std::fprintf(stderr, "failed to write synthetic compute shader\n");
286 return 1;
287 }
288 static_assert(sizeof(leonida::ShaderUserData) == 144,
289 "synthetic index.json push_constant_bytes must match ShaderUserData");
290 const char index_json[] =
291 "{\"seed\":{\"stage\":\"cs\",\"bindings\":[],\"push_constant_bytes\":144,"
292 "\"local_size\":[1,1,1],\"wave64\":false}}\n";
293 if (!write_bytes(index_path, index_json, sizeof(index_json) - 1)) {
294 std::fprintf(stderr, "failed to write synthetic index.json\n");
295 return 1;
296 }
297
298 DWORD checker_exit = 1;
299 if (!run_checker_process(checker_copy, temp.path, cache_path, log_path, checker_exit)) {
300 std::fprintf(stderr, "failed to run copied vk_pipeline_check process\n");
301 return 1;
302 }
303 const std::vector<char> log_bytes = read_file(log_path);
304 const std::string log_text(log_bytes.begin(), log_bytes.end());
305 const bool built_ok = log_text.find("cs pipelines: 1 ok, 0 failed, 0 skipped") != std::string::npos;
306 const bool has_cache = std::filesystem::is_regular_file(cache_path, ec);
307 if (!built_ok || !has_cache) {
308 if (log_text.find("no Vulkan physical device") != std::string::npos ||
309 log_text.find("vulkan-1") != std::string::npos ||
310 log_text.find("libvulkan") != std::string::npos ||
311 log_text.find("cs pipelines: 0 ok, 0 failed, 1 skipped") != std::string::npos) {
312 std::printf("SKIP: vk_pipeline_check built no pipeline here\n");
313 return 77;
314 }
315 std::fprintf(stderr, "vk_pipeline_check did not build the pipeline (exit %lu)\n%s\n",
316 static_cast<unsigned long>(checker_exit), log_text.c_str());
317 return 1;
318 }
319
320 const std::vector<char> seed = read_file(cache_path);
321 if (seed.size() < sizeof(VkPipelineCacheHeaderVersionOne)) {
322 std::fprintf(stderr, "pipeline_cache.bin is too small (%zu bytes)\n", seed.size());
323 return 1;
324 }
325 VkPipelineCacheHeaderVersionOne header{};
326 std::memcpy(&header, seed.data(), sizeof(header));
327 if (header.vendorID != properties.vendorID || header.deviceID != properties.deviceID ||
328 std::memcmp(header.pipelineCacheUUID, properties.pipelineCacheUUID, VK_UUID_SIZE) != 0) {
329 std::printf("SKIP: pipeline_cache.bin was written for another GPU or driver than the runtime's %s\n",
330 properties.deviceName);
331 return 77;
332 }
333
334 VulkanObjects vk;
335 vk.device = device;
336 vk.destroy_module = vkDestroyShaderModule;
337 vk.destroy_layout = vkDestroyPipelineLayout;
338 vk.destroy_cache = vkDestroyPipelineCache;
339
340 VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO};
341 module_info.codeSize = kMinimalComputeSpv.size() * sizeof(std::uint32_t);
342 module_info.pCode = kMinimalComputeSpv.data();
343 if (vkCreateShaderModule(device, &module_info, nullptr, &vk.shader) != VK_SUCCESS) return 1;
344
345 const VkPushConstantRange push{VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(leonida::ShaderUserData)};
346 VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO};
347 layout_info.pushConstantRangeCount = 1;
348 layout_info.pPushConstantRanges = &push;
349 if (vkCreatePipelineLayout(device, &layout_info, nullptr, &vk.layout) != VK_SUCCESS) return 1;
350
351 const auto make_cache = [&](const void* data, std::size_t size) {
352 VkPipelineCacheCreateInfo cache_info{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO};
353 cache_info.initialDataSize = size;
354 cache_info.pInitialData = data;
355 VkPipelineCache cache = VK_NULL_HANDLE;
356 if (vkCreatePipelineCache(device, &cache_info, nullptr, &cache) != VK_SUCCESS) return VkPipelineCache{};
357 return cache;
358 };
359
360 leonida::ShaderEntry entry;
361 entry.stage = "cs";
362 entry.local_size = {1, 1, 1};
363 const auto create = [&](VkPipelineCache cache) {
364 VkPipelineCreationFeedback feedback{};
365 const VkPipelineCreationFeedbackCreateInfo feedback_info{
366 VK_STRUCTURE_TYPE_PIPELINE_CREATION_FEEDBACK_CREATE_INFO, nullptr, &feedback, 0, nullptr};
367 VkComputePipelineCreateInfo pipeline_info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO, &feedback_info};
368 pipeline_info.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO};
369 pipeline_info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT;
370 pipeline_info.stage.module = vk.shader;
371 pipeline_info.stage.pName = "main";
372 VkPipelineShaderStageRequiredSubgroupSizeCreateInfo required_size{};
373 leonida::apply_subgroup_request(leonida::decide_subgroup_size(entry, info->subgroup), required_size,
374 pipeline_info.stage);
375 pipeline_info.layout = vk.layout;
376 VkPipeline pipeline = VK_NULL_HANDLE;
377 Created result;
378 if (vkCreateComputePipelines(device, cache, 1, &pipeline_info, nullptr, &pipeline) != VK_SUCCESS) return result;
379 vkDestroyPipeline(device, pipeline, nullptr);
380 result.ok = true;
381 result.hit = (feedback.flags & VK_PIPELINE_CREATION_FEEDBACK_VALID_BIT) != 0 &&
382 (feedback.flags & VK_PIPELINE_CREATION_FEEDBACK_APPLICATION_PIPELINE_CACHE_HIT_BIT) != 0;
383 return result;
384 };
385
386 vk.seeded = make_cache(seed.data(), seed.size());
387 const Created from_seed = vk.seeded ? create(vk.seeded) : Created{};
388 if (!from_seed.ok) {
389 std::fprintf(stderr, "FAIL: the pipeline was not created from the seeded cache\n");
390 return 1;
391 }
392 if (from_seed.hit) {
393 std::printf("ok: vk_pipeline_check cache hits on the runtime's device (%s)\n", properties.deviceName);
394 return 0;
395 }
396
397 // Does this driver report a hit at all? Write a cache on this device and read it back.
398 vk.first = make_cache(nullptr, 0);
399 std::vector<char> own;
400 std::size_t own_size = 0;
401 if (vk.first && create(vk.first).ok && vkGetPipelineCacheData(device, vk.first, &own_size, nullptr) == VK_SUCCESS) {
402 own.resize(own_size);
403 if (vkGetPipelineCacheData(device, vk.first, &own_size, own.data()) != VK_SUCCESS) own.clear();
404 own.resize(own.empty() ? 0 : own_size);
405 }
406 vk.second = own.empty() ? VkPipelineCache{} : make_cache(own.data(), own.size());
407 const bool reports_hits = vk.second && create(vk.second).hit;
408 if (reports_hits) {
409 std::fprintf(stderr,
410 "FAIL: vk_pipeline_check cache does not hit on the runtime's device (%s), which does hit a "
411 "cache it wrote itself: vk_pipeline_check's device differs from the runtime's in something the "
412 "driver makes part of a pipeline's cache key\n",
413 properties.deviceName);
414 return 1;
415 }
416 std::printf("SKIP: %s reports no cache hit even for a cache it wrote itself\n", properties.deviceName);
417 return 77;
418}
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_cpu_bench.cpp b/runtime/test/replay_cpu_bench.cpp
index a3957d166..0da65357b 100644
--- a/runtime/test/replay_cpu_bench.cpp
+++ b/runtime/test/replay_cpu_bench.cpp
@@ -226,6 +226,8 @@ struct Scene {
226 vk.bind_index_buffer = nop<PFN_vkCmdBindIndexBuffer>(); 226 vk.bind_index_buffer = nop<PFN_vkCmdBindIndexBuffer>();
227 vk.set_viewport = nop<PFN_vkCmdSetViewport>(); 227 vk.set_viewport = nop<PFN_vkCmdSetViewport>();
228 vk.set_scissor = nop<PFN_vkCmdSetScissor>(); 228 vk.set_scissor = nop<PFN_vkCmdSetScissor>();
229 vk.set_viewport_with_count = nop<PFN_vkCmdSetViewportWithCount>();
230 vk.set_scissor_with_count = nop<PFN_vkCmdSetScissorWithCount>();
229 vk.set_primitive_topology = nop<PFN_vkCmdSetPrimitiveTopology>(); 231 vk.set_primitive_topology = nop<PFN_vkCmdSetPrimitiveTopology>();
230 vk.set_primitive_restart_enable = nop<PFN_vkCmdSetPrimitiveRestartEnable>(); 232 vk.set_primitive_restart_enable = nop<PFN_vkCmdSetPrimitiveRestartEnable>();
231 vk.set_stencil_reference = nop<PFN_vkCmdSetStencilReference>(); 233 vk.set_stencil_reference = nop<PFN_vkCmdSetStencilReference>();
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_readback_stages_test.cpp b/runtime/test/replay_readback_stages_test.cpp
index d09f1ebfe..f081c3c1f 100644
--- a/runtime/test/replay_readback_stages_test.cpp
+++ b/runtime/test/replay_readback_stages_test.cpp
@@ -239,7 +239,61 @@ int main() {
239 "non-host_readable buffer UAV clear leaves wrote_readback false"); 239 "non-host_readable buffer UAV clear leaves wrote_readback false");
240 } 240 }
241 241
242 // 9. XDXR AccelerationStructurePostbuild writes compacted/current size via compute shader to dest_va,
243 // which may target a host-readable buffer, so prepare() must request a COMPUTE_SHADER_BIT -> HOST flush.
244 {
245 ReplayFunctions xdxr_vk = vk;
246 xdxr_vk.xdxr_postbuild = [](VkCommandBuffer, std::uint64_t, std::uint64_t) {};
247 xdxr_vk.buffer_at = [&](std::uint64_t va, std::uint64_t& size, VkBuffer& buf, VkDeviceSize& off) {
248 if (va == 0x10000 && size <= 64) {
249 buf = readback_buf.buffer;
250 off = 0;
251 size = 64;
252 return true;
253 }
254 if (va == 0x20000) {
255 buf = readback_buf.buffer;
256 off = 0;
257 size = 4; // too small for 8 bytes
258 return true;
259 }
260 return false;
261 };
262
263 CommandList compacted;
264 expect(compacted.acceleration_structure_postbuild({0x10000, 0, {0x40000}}) && compacted.close(),
265 "record XDXR postbuild compacted size");
266 expect(prepare(compacted, resolve, xdxr_vk, out) == ReplayResult::success,
267 "prepare XDXR postbuild compacted size");
268 expect(out.wrote_readback && out.readback_src_stages == VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT,
269 "XDXR postbuild compacted size reports COMPUTE_SHADER_BIT");
270
271 CommandList current;
272 expect(current.acceleration_structure_postbuild({0x10000, 3, {0x40000, 0x40100}}) && current.close(),
273 "record XDXR postbuild current size");
274 expect(prepare(current, resolve, xdxr_vk, out) == ReplayResult::success,
275 "prepare XDXR postbuild current size");
276 expect(out.wrote_readback && out.readback_src_stages == VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT,
277 "XDXR postbuild current size reports COMPUTE_SHADER_BIT");
278
279 CommandList bad_type;
280 expect(bad_type.acceleration_structure_postbuild({0x10000, 1, {0x40000}}) && bad_type.close(),
281 "record XDXR postbuild unsupported type");
282 expect(prepare(bad_type, resolve, xdxr_vk, out) == ReplayResult::unsupported,
283 "XDXR postbuild unsupported type returns unsupported");
284 expect(!out.wrote_readback && out.readback_src_stages == 0,
285 "failed XDXR postbuild leaves wrote_readback false");
286
287 CommandList bad_room;
288 expect(bad_room.acceleration_structure_postbuild({0x20000, 0, {0x40000}}) && bad_room.close(),
289 "record XDXR postbuild too-small dest");
290 expect(prepare(bad_room, resolve, xdxr_vk, out) == ReplayResult::invalid_copy,
291 "XDXR postbuild too-small dest returns invalid_copy");
292 expect(!out.wrote_readback && out.readback_src_stages == 0,
293 "too-small XDXR postbuild leaves wrote_readback false");
294 }
295
242 if (failures) return 1; 296 if (failures) return 1;
243 std::printf("replay_readback_stages: depth24, rgb96, copy and UAV-clear readback stages exact\n"); 297 std::printf("replay_readback_stages: depth24, rgb96, copy, UAV-clear and XDXR postbuild readback stages exact\n");
244 return 0; 298 return 0;
245} 299}
diff --git a/runtime/test/replay_texture_barrier_test.cpp b/runtime/test/replay_texture_barrier_test.cpp
index 66c594779..43ee9dcb7 100644
--- a/runtime/test/replay_texture_barrier_test.cpp
+++ b/runtime/test/replay_texture_barrier_test.cpp
@@ -3,6 +3,9 @@
3// - A range in one layout is one piece: emit makes no heap allocation for it. 3// - A range in one layout is one piece: emit makes no heap allocation for it.
4// - A range whose mips are in different layouts is one piece for each mip: all of them are in the same call, 4// - A range whose mips are in different layouts is one piece for each mip: all of them are in the same call,
5// each with its own old layout. 5// each with its own old layout.
6// - A barrier into UNDEFINED from a defined layout keeps each piece's layout (Vulkan has no transition into
7// UNDEFINED) and the tracker's; a piece that was never used records nothing, and the next barrier, from
8// UNDEFINED, discards as before.
6// vkCmdPipelineBarrier2 is a function that records its barriers. No Vulkan loader, GPU or game data. 9// vkCmdPipelineBarrier2 is a function that records its barriers. No Vulkan loader, GPU or game data.
7#ifndef VK_NO_PROTOTYPES 10#ifndef VK_NO_PROTOTYPES
8#define VK_NO_PROTOTYPES 11#define VK_NO_PROTOTYPES
@@ -68,6 +71,20 @@ void VKAPI_CALL record_barrier2(VkCommandBuffer, const VkDependencyInfo* info) {
68 g_barriers.push_back(info->pImageMemoryBarriers[i]); 71 g_barriers.push_back(info->pImageMemoryBarriers[i]);
69} 72}
70 73
74// What zero-filling an image that was never used calls: its own layout changes and the clear. Counted, not recorded.
75std::uint32_t g_fill_calls = 0;
76
77void VKAPI_CALL count_barrier(VkCommandBuffer, VkPipelineStageFlags, VkPipelineStageFlags, VkDependencyFlags,
78 std::uint32_t, const VkMemoryBarrier*, std::uint32_t, const VkBufferMemoryBarrier*,
79 std::uint32_t, const VkImageMemoryBarrier*) {
80 ++g_fill_calls;
81}
82
83void VKAPI_CALL count_clear(VkCommandBuffer, VkImage, VkImageLayout, const VkClearColorValue*, std::uint32_t,
84 const VkImageSubresourceRange*) {
85 ++g_fill_calls;
86}
87
71int failures = 0; 88int failures = 0;
72void expect(bool ok, const char* what) { 89void expect(bool ok, const char* what) {
73 if (!ok) { 90 if (!ok) {
@@ -95,7 +112,11 @@ int main() {
95 image.aspects = VK_IMAGE_ASPECT_COLOR_BIT; 112 image.aspects = VK_IMAGE_ASPECT_COLOR_BIT;
96 image.width = image.height = 64; 113 image.width = image.height = 64;
97 image.mip_levels = mips; 114 image.mip_levels = mips;
98 const auto resolve = [&](ResourceId r) { return r == id ? &image : nullptr; }; 115 // A second image that nothing has used yet: the tracker has it in UNDEFINED.
116 constexpr ResourceId unused_id = 2;
117 ResourceBinding unused = image;
118 unused.image = reinterpret_cast<VkImage>(std::uintptr_t(0x2000));
119 const auto resolve = [&](ResourceId r) { return r == id ? &image : r == unused_id ? &unused : nullptr; };
99 120
100 ReplayFunctions vk{}; 121 ReplayFunctions vk{};
101 vk.pipeline_barrier2 = record_barrier2; 122 vk.pipeline_barrier2 = record_barrier2;
@@ -170,6 +191,119 @@ int main() {
170 } 191 }
171 } 192 }
172 193
194 // 3. Into UNDEFINED from a defined layout (the retail title ends a depth buffer's use this way before its memory
195 // is aliased, #984): Vulkan has no transition into UNDEFINED, so each mip keeps the layout it is in and the
196 // barrier only orders the accesses. The tracker keeps those layouts.
197 const auto kept = [&](std::uint32_t mip) { return mip == 1 ? transfer_src : attachment; };
198 {
199 for (std::uint32_t mip = 0; mip < mips; ++mip)
200 tracker.set(id, {VK_IMAGE_ASPECT_COLOR_BIT, mip, 1, 0, 1}, kept(mip));
201 g_barriers.clear();
202 g_calls = 0;
203 CommandList list;
204 expect(list.barrier(TextureBarrier{y::render_target, y::none, a::render_target, a::no_access,
205 l::render_target, l::undefined, id, all, 0}) &&
206 list.close(),
207 "record a barrier into UNDEFINED");
208 PreparedList prepared;
209 expect(prepare(list, resolve, vk, prepared) == ReplayResult::success, "prepare a barrier into UNDEFINED");
210 emit(prepared, cb, vk, &tracker);
211 expect(g_calls == 1 && g_barriers.size() == mips, "into UNDEFINED: one call with a barrier for each mip");
212 for (const VkImageMemoryBarrier2& b : g_barriers) {
213 expect(b.newLayout != VK_IMAGE_LAYOUT_UNDEFINED, "no transition into VK_IMAGE_LAYOUT_UNDEFINED");
214 expect(b.oldLayout == b.newLayout && b.oldLayout == kept(b.subresourceRange.baseMipLevel),
215 "into UNDEFINED: each mip keeps its own layout");
216 expect(b.srcStageMask != 0 && b.srcAccessMask != 0, "into UNDEFINED: the earlier accesses are ordered");
217 }
218 for (std::uint32_t mip = 0; mip < mips; ++mip)
219 expect(tracker.layout(id, mip) == kept(mip), "into UNDEFINED: the tracker keeps the layout");
220 }
221
222 // 4. The discard flag changes nothing there: a release has nothing to discard into.
223 {
224 g_barriers.clear();
225 g_calls = 0;
226 CommandList list;
227 expect(list.barrier(TextureBarrier{y::render_target, y::none, a::render_target, a::no_access,
228 l::render_target, l::undefined, id, all, texture_barrier_discard}) &&
229 list.close(),
230 "record a barrier into UNDEFINED with the discard flag");
231 PreparedList prepared;
232 expect(prepare(list, resolve, vk, prepared) == ReplayResult::success,
233 "prepare a barrier into UNDEFINED with the discard flag");
234 emit(prepared, cb, vk, &tracker);
235 expect(g_calls == 1 && g_barriers.size() == mips, "into UNDEFINED with discard: a barrier for each mip");
236 for (const VkImageMemoryBarrier2& b : g_barriers)
237 expect(b.oldLayout == b.newLayout && b.oldLayout == kept(b.subresourceRange.baseMipLevel),
238 "into UNDEFINED with discard: each mip keeps its own layout");
239 for (std::uint32_t mip = 0; mip < mips; ++mip)
240 expect(tracker.layout(id, mip) == kept(mip), "into UNDEFINED with discard: the tracker keeps the layout");
241 }
242
243 // 5. Without a tracker the layout kept is the one the barrier names.
244 {
245 g_barriers.clear();
246 g_calls = 0;
247 CommandList list;
248 expect(list.barrier(TextureBarrier{y::render_target, y::none, a::render_target, a::no_access,
249 l::render_target, l::undefined, id, all, 0}) &&
250 list.close(),
251 "record a barrier into UNDEFINED for an untracked replay");
252 PreparedList prepared;
253 expect(prepare(list, resolve, vk, prepared) == ReplayResult::success,
254 "prepare a barrier into UNDEFINED for an untracked replay");
255 emit(prepared, cb, vk, nullptr);
256 expect(g_calls == 1 && g_barriers.size() == 1 && g_barriers[0].oldLayout == attachment &&
257 g_barriers[0].newLayout == attachment,
258 "into UNDEFINED without a tracker: the named layout is kept");
259 }
260
261 // 6. An image nothing has used is released without a Vulkan call: there is no access to order, and it is not
262 // zero-filled first, as it would be on its way into any other layout. It stays in UNDEFINED.
263 {
264 tracker.track(unused_id, unused, VK_IMAGE_LAYOUT_UNDEFINED);
265 vk.pipeline_barrier = count_barrier;
266 vk.clear_color_image = count_clear;
267 g_barriers.clear();
268 g_calls = 0;
269 CommandList list;
270 expect(list.barrier(TextureBarrier{y::render_target, y::none, a::render_target, a::no_access,
271 l::render_target, l::undefined, unused_id, all, 0}) &&
272 list.close(),
273 "record a barrier into UNDEFINED for an unused image");
274 PreparedList prepared;
275 expect(prepare(list, resolve, vk, prepared) == ReplayResult::success,
276 "prepare a barrier into UNDEFINED for an unused image");
277 emit(prepared, cb, vk, &tracker);
278 expect(g_calls == 0 && g_barriers.empty(), "an unused image is released without a barrier");
279 expect(g_fill_calls == 0, "an unused image is not zero-filled to be released");
280 for (std::uint32_t mip = 0; mip < mips; ++mip)
281 expect(tracker.layout(unused_id, mip) == VK_IMAGE_LAYOUT_UNDEFINED, "an unused image stays in UNDEFINED");
282 vk.pipeline_barrier = nullptr;
283 vk.clear_color_image = nullptr;
284 }
285
286 // 7. After a release D3D12 has the next barrier start from UNDEFINED: one barrier that discards from whatever
287 // layouts the mips are in (case 3 left them in two), and the tracker has the new layout.
288 {
289 g_barriers.clear();
290 g_calls = 0;
291 CommandList list;
292 expect(list.barrier(TextureBarrier{y::none, y::render_target, a::no_access, a::render_target, l::undefined,
293 l::render_target, id, all, 0}) &&
294 list.close(),
295 "record the barrier that follows a release");
296 PreparedList prepared;
297 expect(prepare(list, resolve, vk, prepared) == ReplayResult::success,
298 "prepare the barrier that follows a release");
299 emit(prepared, cb, vk, &tracker);
300 expect(g_calls == 1 && g_barriers.size() == 1 && g_barriers[0].oldLayout == VK_IMAGE_LAYOUT_UNDEFINED &&
301 g_barriers[0].newLayout == attachment,
302 "after a release: one barrier from UNDEFINED into the new layout");
303 for (std::uint32_t mip = 0; mip < mips; ++mip)
304 expect(tracker.layout(id, mip) == attachment, "after a release: the tracker has the new layout");
305 }
306
173 if (failures) return 1; 307 if (failures) return 1;
174 std::printf("replay_texture_barrier_test: OK\n"); 308 std::printf("replay_texture_barrier_test: OK\n");
175 return 0; 309 return 0;
diff --git a/runtime/test/replay_uav_clear_offset_test.cpp b/runtime/test/replay_uav_clear_offset_test.cpp
index 35818fe8e..3aa37f8b2 100644
--- a/runtime/test/replay_uav_clear_offset_test.cpp
+++ b/runtime/test/replay_uav_clear_offset_test.cpp
@@ -83,10 +83,106 @@ bool inside(VkDeviceSize begin, VkDeviceSize end) {
83 } 83 }
84 return true; 84 return true;
85} 85}
86
87// UAV clears of B5G6R5, B5G5R5A1 and B4G4R4A4 textures. The packed words are what ClearUnorderedAccessViewFloat/Uint
88// leave on WARP for the same values (no channel sits at a rounding midpoint).
89void packed_16bit_texture_clears() {
90 using namespace leonida;
91 struct Case {
92 const char* name;
93 VkFormat format;
94 std::array<std::uint32_t, 4> max; // of R, G, B, A; 0: no such channel
95 std::uint32_t red, green, blue, alpha, mixed, uint_word;
96 };
97 constexpr Case cases[] = {
98 {"B5G6R5", VK_FORMAT_R5G6B5_UNORM_PACK16, {31, 63, 31, 0}, 0xf800, 0x07e0, 0x001f, 0x0000, 0x45ec, 0x0843},
99 {"B5G5R5A1", VK_FORMAT_A1R5G5B5_UNORM_PACK16, {31, 31, 31, 1}, 0x7c00, 0x03e0, 0x001f, 0x8000, 0xa2ec, 0x8443},
100 {"B4G4R4A4", VK_FORMAT_A4R4G4B4_UNORM_PACK16, {15, 15, 15, 15}, 0x0f00, 0x00f0, 0x000f, 0xf000, 0x94b6, 0xf123}};
101 ReplayFunctions vk{};
102 vk.pipeline_barrier = barrier;
103 vk.clear_color_image = clear_image;
104 vk.begin_rendering = begin_rendering;
105 vk.end_rendering = end_rendering;
106 vk.clear_attachments = clear_attachments;
107 vk.image_view = [](const ResourceBinding& b, const VkImageSubresourceRange&) {
108 requested_view_format = b.format;
109 return reinterpret_cast<VkImageView>(std::uintptr_t{0x2000});
110 };
111 const auto run = [&](VkFormat backing, bool attachment, VkFormat view, bool is_float,
112 const std::array<std::uint32_t, 4>& values) {
113 reset_texture_capture();
114 ResourceBinding tex{};
115 tex.image = reinterpret_cast<VkImage>(std::uintptr_t{0x3000});
116 tex.format = backing;
117 tex.aspects = VK_IMAGE_ASPECT_COLOR_BIT;
118 tex.width = tex.height = 8;
119 tex.mip_levels = tex.array_layers = 1;
120 tex.color_attachment = attachment;
121 CommandList list;
122 list.clear_unordered_access({2, false, std::uint32_t(view), 0, 0, 0, 0, 0, 1}, is_float, values, {});
123 list.close();
124 return replay(list, VK_NULL_HANDLE, [&](ResourceId id) { return id == 2 ? &tex : nullptr; }, vk) ==
125 ReplayResult::success;
126 };
127 const auto check = [](bool ok, const Case& c, const char* what) {
128 char text[128];
129 std::snprintf(text, sizeof text, "%s UAV clear: %s", c.name, what);
130 expect(ok, text);
131 };
132 const auto floats = [](float r, float g, float b, float a) {
133 return std::array<std::uint32_t, 4>{std::bit_cast<std::uint32_t>(r), std::bit_cast<std::uint32_t>(g),
134 std::bit_cast<std::uint32_t>(b), std::bit_cast<std::uint32_t>(a)};
135 };
136 for (const Case& c : cases) {
137 const struct {
138 const char* what;
139 bool is_float;
140 std::array<std::uint32_t, 4> values;
141 std::uint32_t word;
142 } clears[] = {{"Float red", true, floats(1, 0, 0, 0), c.red},
143 {"Float green", true, floats(0, 1, 0, 0), c.green},
144 {"Float blue", true, floats(0, 0, 1, 0), c.blue},
145 {"Float alpha", true, floats(0, 0, 0, 1), c.alpha},
146 {"Float mixed", true, floats(0.25f, 0.75f, 0.4f, 0.6f), c.mixed},
147 {"Uint", false, {1, 2, 3, 0xffffffffu}, c.uint_word}};
148 for (const auto& clear : clears) // an R16_UINT image takes the packed word itself
149 check(run(VK_FORMAT_R16_UINT, false, c.format, clear.is_float, clear.values) && image_clears == 1 &&
150 attachment_clears == 0 && captured_color.uint32[0] == clear.word,
151 c, clear.what);
152
153 // An image of the format itself takes the channels the word holds.
154 const std::array<std::uint32_t, 4> raw{1, 2, 3, 0xffffffffu};
155 bool channels = run(c.format, true, c.format, false, raw) && image_clears == 1 && attachment_clears == 0;
156 for (unsigned i = 0; i < 4; ++i)
157 channels &= c.max[i] == 0 || captured_color.float32[i] == float(raw[i] & c.max[i]) / float(c.max[i]);
158 check(channels, c, "image of the same format");
159
160 // Every packed word survives decode() and encode().
161 bool round_trip = true;
162 for (std::uint32_t word = 0; word < 0x10000 && round_trip; ++word) {
163 uav_clear::Element element{}, again{};
164 element.size = 2;
165 element.bytes[0] = std::uint8_t(word);
166 element.bytes[1] = std::uint8_t(word >> 8);
167 VkClearColorValue color{};
168 round_trip = uav_clear::decode(c.format, element, color) &&
169 uav_clear::encode(c.format, true, std::bit_cast<std::array<std::uint32_t, 4>>(color.float32), again) &&
170 again.size == 2 && again.bytes == element.bytes;
171 }
172 check(round_trip, c, "decode/encode round trip");
173 }
174 // The render-target + UAV B5G5R5A1 texture the device backs with R16_UINT clears through its A1R5G5B5 view.
175 check(run(VK_FORMAT_R16_UINT, true, VK_FORMAT_A1R5G5B5_UNORM_PACK16, true, floats(1, 0, 0, 1)) &&
176 attachment_clears == 1 && image_clears == 0 &&
177 requested_view_format == VK_FORMAT_A1R5G5B5_UNORM_PACK16 && captured_color.float32[0] == 1.0f &&
178 captured_color.float32[1] == 0.0f && captured_color.float32[2] == 0.0f && captured_color.float32[3] == 1.0f,
179 cases[1], "R16_UINT-backed render target");
180}
86} // namespace 181} // namespace
87 182
88int main() { 183int main() {
89 using namespace leonida; 184 using namespace leonida;
185 packed_16bit_texture_clears();
90 constexpr VkDeviceSize at = 65536, bytes = 256; 186 constexpr VkDeviceSize at = 65536, bytes = 256;
91 ResourceBinding range{}; 187 ResourceBinding range{};
92 range.buffer = reinterpret_cast<VkBuffer>(std::uintptr_t{0x1000}); 188 range.buffer = reinterpret_cast<VkBuffer>(std::uintptr_t{0x1000});
@@ -173,6 +269,18 @@ int main() {
173 range.buffer_offset = UINT64_MAX - 2; 269 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(), 270 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"); 271 "backing range overflow is rejected before scratch allocation or emission");
272 // Misaligned backing buffer_offset must be rejected for multi-byte elements (e.g., e > 4 violates
273 // VUID-vkCmdUpdateBuffer-dstOffset-00032; e == 2/4 would byte-swap/rotate elements in vkCmdFillBuffer).
274 range.buffer_offset = at + 2;
275 expect(run({1, true, VK_FORMAT_R32G32B32A32_UINT, 0, 32, 16, 0, 0, 1}) == ReplayResult::unsupported && writes.empty(),
276 "misaligned backing buffer_offset for 16-byte element clear is rejected before vkCmdUpdateBuffer");
277 expect(run({1, true, VK_FORMAT_R32_UINT, 0, 16, 4, 0, 0, 1}) == ReplayResult::unsupported && writes.empty(),
278 "misaligned backing buffer_offset for 4-byte element clear is rejected before vkCmdFillBuffer");
279 range.buffer_offset = at + 1;
280 expect(run({1, true, VK_FORMAT_R16_UINT, 0, 16, 2, 0, 0, 1}) == ReplayResult::unsupported && writes.empty(),
281 "odd backing buffer_offset for 2-byte element clear is rejected before vkCmdFillBuffer");
282 expect(run({1, true, VK_FORMAT_R8_UINT, 0, 16, 1, 0, 0, 1}) == ReplayResult::success,
283 "odd backing buffer_offset for 1-byte R8 element clear still replays");
176 range.buffer_offset = at; 284 range.buffer_offset = at;
177 vk.copy_scratch = {}; 285 vk.copy_scratch = {};
178 286
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/root_sig_test.cpp b/runtime/test/root_sig_test.cpp
index ac65075ee..cc828b36c 100644
--- a/runtime/test/root_sig_test.cpp
+++ b/runtime/test/root_sig_test.cpp
@@ -479,6 +479,37 @@ void test_deserializer() {
479 auto deserialize = reinterpret_cast<DeserializeFn>( 479 auto deserialize = reinterpret_cast<DeserializeFn>(
480 rt::shims::find("d3d12_xs.dll", "D3D12CreateRootSignatureDeserializer")); 480 rt::shims::find("d3d12_xs.dll", "D3D12CreateRootSignatureDeserializer"));
481 check(deserialize != nullptr, "shim registry exposes d3d12_xs!D3D12CreateRootSignatureDeserializer"); 481 check(deserialize != nullptr, "shim registry exposes d3d12_xs!D3D12CreateRootSignatureDeserializer");
482 auto versioned = reinterpret_cast<decltype(&D3D12CreateVersionedRootSignatureDeserializer)>(
483 rt::shims::find("d3d12_xs.dll", "D3D12CreateVersionedRootSignatureDeserializer"));
484 check(versioned != nullptr, "shim registry exposes the versioned deserializer");
485 check(versioned && rt::shims::find("d3d12_xs.dll", "#7") == reinterpret_cast<void*>(versioned),
486 "ordinal 7 resolves to the versioned deserializer");
487 if (versioned) {
488 ID3D12VersionedRootSignatureDeserializer* de = nullptr;
489 auto bad_checksum = tampered;
490 bad_checksum[4] ^= 1;
491 HRESULT bad_hr = versioned(bad_checksum.data(), bad_checksum.size(), IID_PPV_ARGS(&de));
492 check(FAILED(bad_hr) && !de, "versioned shim rejects Xbox flags with corrupt checksum");
493 if (de) de->Release();
494 de = nullptr;
495 HRESULT versioned_hr = versioned(tampered.data(), tampered.size(), IID_PPV_ARGS(&de));
496 check(SUCCEEDED(versioned_hr) && de, "versioned shim accepts Xbox flags");
497 if (de) {
498 const auto* desc = de->GetUnconvertedRootSignatureDesc();
499 check(desc && desc->Version == D3D_ROOT_SIGNATURE_VERSION_1_0 && desc->Desc_1_0.Flags == 0,
500 "versioned shim clears Xbox flags");
501 de->Release();
502 }
503 de = nullptr;
504 versioned_hr = versioned(bytes, size, IID_PPV_ARGS(&de));
505 check(SUCCEEDED(versioned_hr) && de, "versioned shim accepts clean blob");
506 if (de) de->Release();
507 const uint8_t garbage[] = {1, 2, 3, 4};
508 de = nullptr;
509 versioned_hr = versioned(garbage, sizeof(garbage), IID_PPV_ARGS(&de));
510 check(FAILED(versioned_hr), "versioned shim rejects garbage");
511 if (de) de->Release();
512 }
482 if (!deserialize) return; 513 if (!deserialize) return;
483 514
484 ID3D12RootSignatureDeserializer* shim_de = nullptr; 515 ID3D12RootSignatureDeserializer* shim_de = nullptr;
@@ -564,6 +595,16 @@ void test_deserializer() {
564 check(SUCCEEDED(hr_zero) && shim_zero && shim_zero->GetRootSignatureDesc()->Flags == 0, 595 check(SUCCEEDED(hr_zero) && shim_zero && shim_zero->GetRootSignatureDesc()->Flags == 0,
565 "shim deserializer accepts an all-zero-checksum Xbox blob with the high byte cleared"); 596 "shim deserializer accepts an all-zero-checksum Xbox blob with the high byte cleared");
566 if (shim_zero) shim_zero->Release(); 597 if (shim_zero) shim_zero->Release();
598
599 if (versioned) {
600 ID3D12VersionedRootSignatureDeserializer* v_zero = nullptr;
601 const HRESULT v_hr_zero = versioned(zero_hash.data(), zero_hash.size(), IID_PPV_ARGS(&v_zero));
602 const auto* desc = v_zero ? v_zero->GetUnconvertedRootSignatureDesc() : nullptr;
603 check(SUCCEEDED(v_hr_zero) && v_zero && desc &&
604 desc->Version == D3D_ROOT_SIGNATURE_VERSION_1_0 && desc->Desc_1_0.Flags == 0,
605 "versioned shim accepts an all-zero-checksum Xbox blob with the high byte cleared");
606 if (v_zero) v_zero->Release();
607 }
567 } 608 }
568} 609}
569 610
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..3b73d736f 100644
--- a/runtime/test/shaders/check.py
+++ b/runtime/test/shaders/check.py
@@ -125,7 +125,9 @@ CS_DPP = [("cs_dpp", [1, 0, 3, 2, 5, 4, 7, 6]),
125 ("cs_dpp_ops", [100, 10, 11, 12, 13, 14, 15, 16]), 125 ("cs_dpp_ops", [100, 10, 11, 12, 13, 14, 15, 16]),
126 ("cs_dpp_bound", [10, 10, 11, 12, 13, 14, 15, 16]), 126 ("cs_dpp_bound", [10, 10, 11, 12, 13, 14, 15, 16]),
127 ("cs_dpp_bank", [0xffffffff, 0xfffffffe, 0xfffffffd, 0xfffffffc, 7, 7, 7, 7]), 127 ("cs_dpp_bank", [0xffffffff, 0xfffffffe, 0xfffffffd, 0xfffffffc, 7, 7, 7, 7]),
128 ("cs_dpp_fi", [1, 2, 3, 0x7777, 5, 6, 7, 0x7777])] 128 ("cs_dpp_fi", [1, 2, 3, 0x7777, 5, 6, 7, 0x7777]),
129 # a VOPC compare with a DPP src0: 1 for the pair compare, 2 for the dpp8 one (cs_dpp_cmp.asm header)
130 ("cs_dpp_cmp", [3, 2, 3, 2, 1, 0, 1, 0])]
129WAVE32_DUMPS += tuple(n for n, _ in CS_DPP) 131WAVE32_DUMPS += tuple(n for n, _ in CS_DPP)
130WAVE32_LANE_DUMPS += tuple(n for n, _ in CS_DPP) 132WAVE32_LANE_DUMPS += tuple(n for n, _ in CS_DPP)
131CS_DUMPS = [*CS_DPP, ("cs_store", CS_STORE), ("cs_smem_soffset_imm", CS_SMEM), 133CS_DUMPS = [*CS_DPP, ("cs_store", CS_STORE), ("cs_smem_soffset_imm", CS_SMEM),
@@ -358,6 +360,337 @@ def heap_init_env():
358 return {"VKC_HEAP_INIT": path, "VKC_OUT_WORDS": str(len(HEAP_INIT_FILE) // 4)} 360 return {"VKC_HEAP_INIT": path, "VKC_OUT_WORDS": str(len(HEAP_INIT_FILE) // 4)}
359 361
360 362
363def shift64_words():
364 """cs_w32_shift64: input heap and full expected readback, using Python integers as the oracle."""
365 values = (0, 1, 0xFFFFFFFF, 0x100000000, 0x7FFFFFFFFFFFFFFF,
366 0x8000000000000000, 0xFFFFFFFFFFFFFFFF, 0x8123456789ABCDEF)
367 counts = (0, 1, 31, 32, 33, 63, 64, 65)
368 inputs, results = [], []
369 for value in values:
370 for count in counts:
371 inputs.extend((value & 0xFFFFFFFF, value >> 32, count, 0xA5A5A5A5))
372 signed = value if value < (1 << 63) else value - (1 << 64)
373 shift = count & 63
374 for result in (value << shift, value >> shift, signed >> shift):
375 results.extend((result & 0xFFFFFFFF, (result >> 32) & 0xFFFFFFFF))
376 return [0xEEEEEEEE] * len(results) + inputs, results + inputs
377
378
379def shift64_test(tools, spirv, env=None):
380 """Verify all three 64-bit shifts for 64 memory-fed cases, including the untouched input records."""
381 initial, expected = shift64_words()
382 with tempfile.TemporaryDirectory(prefix="leonida-shift64-") as tmp:
383 path = Path(tmp) / "input.bin"
384 path.write_bytes(struct.pack(f"<{len(initial)}I", *initial))
385 child = dict(os.environ if env is None else env, VKC_HEAP_INIT=str(path))
386 child.setdefault("VKC_SUBGROUP_SIZE", str(subgroup_size(spirv, "cs_w32_shift64") or 32))
387 return dump_test(tools, spirv, "cs_w32_shift64", expected, len(expected), child)
388
389
390# cs_w32_cmp_f64.asm: the 16 binary64 compare predicates in opcode order (bit n of a result word is predicate n), and
391# the operand values every pair is drawn from, in ascending order and then two NaNs.
392CMP_F64_PREDICATES = ("f", "lt", "eq", "le", "gt", "lg", "ge", "o",
393 "u", "nge", "nlg", "ngt", "nle", "neq", "nlt", "tru")
394CMP_F64_VALUES = (
395 0xFFF0000000000000, # -inf
396 0xFFEFFFFFFFFFFFFF, # -max
397 0xBFF0000000000001, # -1 - 1 ulp
398 0xBFF0000000000000, # -1
399 0xBFEFFFFFFFFFFFFF, # the value above -1: its high dword is the smaller one, its low dword all ones
400 0x8000000000000001, # the negative smallest subnormal
401 0x8000000000000000, # -0
402 0x0000000000000000, # +0
403 0x0000000000000001, # the smallest subnormal
404 0x0010000000000000, # the smallest normal
405 0x3FF0000000000000, # 1
406 0x3FF0000000000001, # 1 + 1 ulp
407 0x7FEFFFFFFFFFFFFF, # +max
408 0x7FF0000000000000, # +inf
409 0x7FF0000000000001, # a NaN whose payload is only in the low dword: its high dword is +inf's
410 0xFFF8000000000000) # a negative quiet NaN
411CMP_F64_SIGN = 1 << 63
412
413
414def cmp_f64_predicates(a_bits, b_bits):
415 """The 16 results of comparing two binary64 bit patterns, as a mask with bit n for CMP_F64_PREDICATES[n].
416 IEEE-754 through Python floats: a pair with a NaN is unordered, so lt, eq and gt are all false for it and every
417 negated predicate is true; -0 equals +0 and a subnormal is not zero."""
418 a, b = (struct.unpack("<d", struct.pack("<Q", bits))[0] for bits in (a_bits, b_bits))
419 unordered = a != a or b != b
420 lt, eq, gt = a < b, a == b, a > b
421 results = (False, lt, eq, lt or eq, gt, lt or gt, gt or eq, not unordered,
422 unordered, not (gt or eq), not (lt or gt), not gt, not (lt or eq), not eq, not lt, True)
423 return sum(1 << bit for bit, result in enumerate(results) if result)
424
425
426def cmp_f64_words():
427 """cs_w32_cmp_f64: the input heap and the full expected readback, with Python floats as the oracle. Record
428 16 * ia + ib compares value ia with value ib. Thread i handles records i and i + 128, so a record's thread has
429 the record's parity."""
430 inputs, results = [], []
431 for record, (a, b) in enumerate((a, b) for a in CMP_F64_VALUES for b in CMP_F64_VALUES):
432 inputs.extend((a & 0xFFFFFFFF, a >> 32, b & 0xFFFFFFFF, b >> 32))
433 word = cmp_f64_predicates(a, b)
434 word |= (record % 2 == 0) << 16 # tru with the odd threads turned off first
435 word |= (cmp_f64_predicates(a & ~CMP_F64_SIGN, b ^ CMP_F64_SIGN) >> 1 & 1) << 17 # lt of |a| and -b
436 word |= (cmp_f64_predicates(a ^ CMP_F64_SIGN, b & ~CMP_F64_SIGN) >> 9 & 1) << 18 # nge of -a and |b|
437 results.extend((word, word)) # the v_cmp_ word (VCC), then the v_cmpx_ word (EXEC)
438 return [0xEEEEEEEE] * len(results) + inputs, results + inputs
439
440
441def cmp_f64_test(tools, spirv, env=None):
442 """Verify the 32 binary64 compares on 256 memory-fed operand pairs, including the untouched input records."""
443 initial, expected = cmp_f64_words()
444 with tempfile.TemporaryDirectory(prefix="leonida-cmp-f64-") as tmp:
445 path = Path(tmp) / "input.bin"
446 path.write_bytes(struct.pack(f"<{len(initial)}I", *initial))
447 child = dict(os.environ if env is None else env, VKC_HEAP_INIT=str(path))
448 child.setdefault("VKC_SUBGROUP_SIZE", str(subgroup_size(spirv, "cs_w32_cmp_f64") or 32))
449 return dump_test(tools, spirv, "cs_w32_cmp_f64", expected, len(expected), child)
450
451
452# cs_w32_round_f64.asm: the binary64 input of each thread, a value and its negative side by side.
453ROUND_F64_VALUES = (
454 0x0000000000000000, 0x8000000000000000, # +0, -0
455 0x0000000000000001, 0x8000000000000001, # the smallest subnormal and its negative
456 0x3FD0000000000000, 0xBFD0000000000000, # +-0.25
457 0x3FDFFFFFFFFFFFFF, 0xBFDFFFFFFFFFFFFF, # +-the largest value below 0.5: x + 0.5 already rounds to 1
458 0x3FE0000000000000, 0xBFE0000000000000, # +-0.5, a tie that goes to 0
459 0x3FE0000000000001, 0xBFE0000000000001, # +-the value just above 0.5
460 0x3FE8000000000000, 0xBFE8000000000000, # +-0.75
461 0x3FEFFFFFFFFFFFFF, 0xBFEFFFFFFFFFFFFF, # +-the value just below 1
462 0x3FF0000000000000, 0xBFF0000000000000, # +-1
463 0x3FF0000000000001, 0xBFF0000000000001, # +-the value just above 1
464 0x3FF8000000000000, 0xBFF8000000000000, # +-1.5, a tie that goes to 2
465 0x4004000000000000, 0xC004000000000000, # +-2.5, a tie that goes to 2
466 0x400C000000000000, 0xC00C000000000000, # +-3.5, a tie that goes to 4
467 0x4003FFFFFFFFFFFF, 0xC004000000000001, # just below 2.5, and just beyond -2.5
468 0x4320000000000001, 0xC320000000000001, # +-(2^51 + 0.5), a tie that goes to 2^51
469 0x4320000000000003, 0xC320000000000003, # +-(2^51 + 1.5), a tie that goes to 2^51 + 2
470 0x432FFFFFFFFFFFFF, 0xC32FFFFFFFFFFFFF, # +-(2^52 - 0.5), the largest value with a fraction; a tie to 2^52
471 0x4330000000000000, 0x4330000000000001, # 2^52, and the odd integer 2^52 + 1
472 0xC330000000000001, 0x433FFFFFFFFFFFFF, # -(2^52 + 1), and 2^53 - 1
473 0x4340000000000000, 0x43E0000000000000, # 2^53, and 2^63
474 0xC3E0000000000000, 0x7E37E43C8800759C, # -2^63, and 1e300
475 0xFE37E43C8800759C, 0x7FEFFFFFFFFFFFFF, # -1e300, and the largest finite value
476 0xFFEFFFFFFFFFFFFF, 0x7FF0000000000000, # its negative, and +inf
477 0xFFF0000000000000, 0x7FF8000000000000, # -inf, and a quiet NaN
478 0xFFF8000000000000, 0x7FF0000000000001, # a negative quiet NaN, and a signalling NaN (payload in the low dword)
479 0xFFF0000080000000, 0x7FF8DEADBEEF1234, # a negative signalling NaN, and a quiet NaN with a payload
480 0x419D6F3454400000, 0xC19D6F3457000000, # 123456789.0625, and -123456789.75
481 0x3FB999999999999A, 0xBFB999999999999A, # +-0.1
482 0x4012000000000000, 0xC012000000000000, # +-4.5, a tie that goes to 4
483 0x4016000000000000, 0xC016000000000000, # +-5.5, a tie that goes to 6
484 0x0010000000000000, 0x8010000000000000, # +-the smallest normal
485 0x41E0000000100000, 0xC1E0000000100000) # +-(2^31 + 0.5), a tie that goes to 2^31
486ROUND_F64_SIGN = 1 << 63
487ROUND_F64_KEPT = 0xCAFEF00DDEADBEEF # the pair an inactive lane keeps: 0xdeadbeef low, 0xcafef00d high
488
489
490def round_f64(op, bits):
491 """The binary64 pattern RDNA2 gives for `bits` rounded to an integral value by "trunc", "ceil", "rndne" or
492 "floor" (docs/design.md): exact IEEE-754, a tie of rndne going to the even integer, the result keeping the
493 sign of the source even when it is zero, and an infinity or a NaN coming back unchanged."""
494 x = struct.unpack("<d", struct.pack("<Q", bits))[0]
495 if x != x or x in (math.inf, -math.inf):
496 return bits
497 whole = {"trunc": math.trunc, "ceil": math.ceil, "rndne": round, "floor": math.floor}[op](x)
498 return struct.unpack("<Q", struct.pack("<d", math.copysign(float(whole), x)))[0]
499
500
501def round_f64_results():
502 """cs_w32_round_f64: for each thread its eight results in store order, as (op, source bits). The source has the
503 VOP3 modifier applied. The last result of an odd thread is (None, the pair it keeps): the lane was off."""
504 threads = []
505 for thread, x in enumerate(ROUND_F64_VALUES):
506 threads.append([("trunc", x), ("ceil", x), ("rndne", x), ("floor", x), ("trunc", x ^ ROUND_F64_SIGN),
507 ("ceil", x & ~ROUND_F64_SIGN), ("floor", x),
508 ("rndne", x) if thread % 2 == 0 else (None, ROUND_F64_KEPT)])
509 return threads
510
511
512def round_f64_words():
513 """cs_w32_round_f64: the input heap and the readback RDNA2's rules give, low dword first, with Python floats as
514 the oracle."""
515 results, inputs = [], []
516 for thread in round_f64_results():
517 for op, source in thread:
518 value = source if op is None else round_f64(op, source)
519 results.extend((value & 0xFFFFFFFF, value >> 32))
520 for x in ROUND_F64_VALUES:
521 inputs.extend((x & 0xFFFFFFFF, x >> 32))
522 return [0xEEEEEEEE] * len(results) + inputs, results + inputs
523
524
525# Drivers that round a binary64 with code written for a binary32, by the first word of the device name on
526# vk_compute_test's "device: ..." line (as UNJUDGED_WORDS is keyed), and the ops they do it for.
527# - Mesa llvmpipe: Trunc and RoundEven of a double take its float fallback whenever the CPU has no vector extension
528# as wide as its double vectors, which are twice its native width: 512 bits at the usual 256, so every CPU without
529# AVX-512. There a magnitude above 2^24 comes back unchanged (trunc of 123456789.0625 is 123456789.0625), and
530# RoundEven of a smaller one can be the other neighbouring integer (1 for 1.5, 0 for the value just above 0.5).
531# Floor and Ceil are exact on that path. Measured with Mesa 25.2.8 (LLVM 20.1.2) on the CI's runners, where the
532# CPU decides from run to run, and with Mesa 26.2.6 (LLVM 23.1.4) under GALLIUM_OVERRIDE_CPU_CAPS=avx: 48 of the
533# 512 results. With AVX-512, or with AVX at LP_NATIVE_VECTOR_WIDTH=128, all four ops are exact.
534ROUND_F64_FLOAT_PATH = {"llvmpipe": ("trunc", "rndne")}
535
536
537def round_f64_float_path(op, source, value):
538 """Whether `value` is what a driver in ROUND_F64_FLOAT_PATH may give for the rounding of the finite `source`
539 instead of round_f64's word: the source itself when its magnitude is above 2^24, else one of its two
540 neighbouring integers, with the source's sign. Nothing below 0.5, a subnormal included: Trunc and RoundEven
541 give the zero of the source's sign there on either path."""
542 x = struct.unpack("<d", struct.pack("<Q", source))[0]
543 if x != x or x in (math.inf, -math.inf) or abs(x) < 0.5:
544 return False
545 if abs(x) > 1 << 24:
546 return value == source
547 return value in (round_f64("floor", source), round_f64("ceil", source))
548
549
550def round_f64_problem(got, out=""):
551 """Judge a readback of cs_w32_round_f64: "" or the first word that is wrong, named by its op and source. `out` is
552 vk_compute_test's output, for its "device: ..." line. Every word is exact, the results of a NaN and of a
553 subnormal included: the translated code rounds those two itself and does not leave them to the driver's
554 double-precision functions (docs/design.md). On a device in ROUND_F64_FLOAT_PATH the ops named there are held
555 to round_f64_float_path instead."""
556 _, expected = round_f64_words()
557 results = [result for thread in round_f64_results() for result in thread]
558 device = re.search(r"^device: (\S+)", out, re.MULTILINE)
559 float_path = ROUND_F64_FLOAT_PATH.get(device.group(1), ()) if device else ()
560 for index, (op, source) in enumerate(results):
561 value = got[2 * index] | got[2 * index + 1] << 32
562 want = expected[2 * index] | expected[2 * index + 1] << 32
563 if value == want or op in float_path and round_f64_float_path(op, source, value):
564 continue
565 what = "the pair an inactive lane keeps" if op is None else f"{op} of {source:#018x}"
566 return f"word {2 * index} (thread {index // 8}): {what} gave {value:#018x}, expected {want:#018x}"
567 for index in range(2 * len(results), len(expected)):
568 if got[index] != expected[index]:
569 return f"word {index}: an input changed, expected {expected[index]:#010x}, got {got[index]:#010x}"
570 return ""
571
572
573def round_f64_test(tools, spirv, env=None):
574 """Verify the four binary64 roundings on 64 memory-fed inputs, including the untouched input records."""
575 initial, expected = round_f64_words()
576 with tempfile.TemporaryDirectory(prefix="leonida-round-f64-") as tmp:
577 path = Path(tmp) / "input.bin"
578 path.write_bytes(struct.pack(f"<{len(initial)}I", *initial))
579 child = dict(os.environ if env is None else env, VKC_HEAP_INIT=str(path))
580 child.setdefault("VKC_SUBGROUP_SIZE", str(subgroup_size(spirv, "cs_w32_round_f64") or 32))
581 return dump_test(tools, spirv, "cs_w32_round_f64", expected, len(expected), child, judge=round_f64_problem)
582
583
584# cs_w32_frexp_ldexp.asm: per thread a binary32 word with the exponent v_ldexp_f32 adds to it (a 32-bit word, signed),
585# and a binary64 pattern.
586FREXP_LDEXP_F32 = (
587 (0x3F800000, 0), (0x3F800000, 1), (0x3F800000, 0xFFFFFFFF), (0x3FC00000, 10), # 1 and 1.5
588 (0xBFC00000, 0xFFFFFFF6), (0x3F7FFFFF, 127), (0x3EAAAAAB, 3), (0xBF400000, 4), # -1.5 by 2^-10, ...
589 (0x47F12065, 0xFFFFFFEC), (0xC0490FDB, 100), (0x42F6E979, 0xFFFFFF7E), (0x3F000000, 0), # 123456.79 by 2^-20
590 (0x3F800000, 127), (0x3F800000, 128), (0x3F800000, 0xFFFFFF82), (0x3F800000, 0xFFFFFF81), # 1 by 2^127 .. 2^-127
591 (0x00800000, 0xFFFFFFFF), (0x00800000, 1), (0x00800000, 253), (0x00800000, 254), # the smallest normal
592 (0x00800001, 0xFFFFFFFF), (0x7F7FFFFF, 1), (0x7F7FFFFF, 0xFFFFFFFF), (0x7F7FFFFF, 0), # the largest finite
593 (0x7F7FFFFF, 0xFFFFFF03), (0x7F7FFFFF, 0xFFFFFF02), (0xFF7FFFFF, 2), (0x7F000000, 1), # ... by 2^-253, 2^-254
594 (0x40000000, 512), (0x40000000, 0xFFFFFE00), (0x40000000, 513), (0x40000000, 0xFFFFFDFF), # the clamp at +-512
595 (0x3F800000, 0x7FFFFFFF), (0xBF800000, 0x80000000), (0x00800000, 0x7FFFFFFF), (0x7F7FFFFF, 0x80000000),
596 (0x3F000000, 0xFFFFFF83), (0x3F000000, 0xFFFFFF82), (0x7F000000, 0), (0x00FFFFFF, 0xFFFFFFFF),
597 (0x00000000, 5), (0x80000000, 0xFFFFFFFB), (0x00000000, 0x7FFFFFFF), (0x80000000, 0x80000000), # zeros
598 (0x00000001, 10), (0x807FFFFF, 300), (0x007FFFFF, 0), (0x00400000, 1), # denormals
599 (0x7F800000, 0xFFFFFFFB), (0xFF800000, 500), (0x7F800000, 0x80000000), (0xFF800000, 0), # infinities
600 (0x7FC00000, 3), (0x7F800001, 0xFFFFFFFD), (0xFFC12345, 1000), (0xFF800001, 0xFFFFFC18), # NaNs
601 (0x3F800001, 23), (0xBF7FFFFF, 0xFFFFFFE9), (0x41200000, 0xFFFFFF80), (0x3DCCCCCD, 130),
602 (0x4B800000, 0xFFFFFF6A), (0x33800000, 150), (0x7EFFFFFF, 1), (0x01000000, 0xFFFFFFFE))
603FREXP_F64 = (
604 0x3FF0000000000000, 0xBFF0000000000000, 0x3FE8000000000000, 0x4008000000000000, # 1, -1, 0.75, 3
605 0x7E37E43C8800759C, 0x01A56E1FC2F8F359, 0x7FEFFFFFFFFFFFFF, 0xFFEFFFFFFFFFFFFF, # 1e300, 1e-300, +-max
606 0x0010000000000000, 0x8010000000000000, 0x3FF0000000000001, 0x400921FB54442D18, # +-min normal, 1 + ulp, pi
607 0x3FB999999999999A, 0xBFB999999999999A, 0x4330000000000000, 0x0170000000000000, # +-0.1, 2^52, 2^-1000
608 0x0000000000000001, 0x8000000000000001, 0x000FFFFFFFFFFFFF, 0x800FFFFFFFFFFFFF, # subnormals: the smallest, largest
609 0x0000000080000000, 0x0000000100000000, 0x0008000000000000, 0x00000001FFFFFFFF, # bit 31, bit 32, bit 51, 33 bits
610 0x0000000180000000, 0x000000000000FFFF, 0x8000000100000001, 0x0004000000000001, # bits on both sides of the dwords
611 0x0000000000000002, 0x0000000000008000, 0x0000000000010000, 0x0000000040000000, # single bits 1, 15, 16, 30
612 0x0000000200000000, 0x0000800000000000, 0x0001000000000000, 0x0004000000000000, # single bits 33, 47, 48, 50
613 0x800000000000ABCD, 0x80000000FFFFFFFF, 0x8000FFFF00000000, 0x000ABCDEF0123456,
614 0x0000000000000000, 0x8000000000000000, 0x7FF0000000000000, 0xFFF0000000000000, # zeros and infinities
615 0x7FF8000000000000, 0x7FF0000000000001, 0xFFF8000012345678, 0xFFF0000080000000, # NaNs
616 0x3FE0000000000000, 0xBFE0000000000000, 0x7FE0000000000000, 0x0020000000000000, # +-0.5, 2^1023, 2^-1021
617 0x4059000000000000, 0xC08F400000000000, 0x3F50624DD2F1A9FC, 0x41DFFFFFFFC00000, # 100, -1000, 0.001, 2^31 - 1
618 0x3FEFFFFFFFFFFFFF, 0xBFEFFFFFFFFFFFFF, 0x001FFFFFFFFFFFFF, 0x801FFFFFFFFFFFFF,
619 0x43E0000000000000, 0xC3E0000000000000, 0x3CA0000000000000, 0x7FD0000000000001)
620FREXP_LDEXP_KEPT = 0xDEADBEEF # the word an inactive lane keeps
621
622
623def frexp_mant_f32(x):
624 """v_frexp_mant_f32 on a binary32 word (docs/design.md): a normal keeps its sign and fraction and gets the
625 exponent field 126; a zero or a denormal, read as zero, gives a zero of its sign; an infinity or a NaN comes
626 back unchanged."""
627 exponent = x >> 23 & 0xFF
628 if exponent == 0:
629 return x & 0x80000000
630 return x if exponent == 255 else x & 0x807FFFFF | 126 << 23
631
632
633def frexp_exp_i32_f32(x):
634 """v_frexp_exp_i32_f32: the exponent field minus 126 for a normal, as a 32-bit word; 0 for everything else."""
635 exponent = x >> 23 & 0xFF
636 return (exponent - 126) & 0xFFFFFFFF if 0 < exponent < 255 else 0
637
638
639def ldexp_f32(x, n):
640 """v_ldexp_f32: the 32-bit word n, read as signed and clamped to [-512, 512], is added to the exponent field of
641 a normal x. A field above 254 gives an infinity of x's sign and one of 0 or below a zero of its sign (there are
642 no denormal results). A zero or a denormal gives a zero of its sign, and an infinity or a NaN comes back."""
643 exponent, sign = x >> 23 & 0xFF, x & 0x80000000
644 if exponent == 0:
645 return sign
646 if exponent == 255:
647 return x
648 exponent += max(-512, min(512, n - (1 << 32) if n & 0x80000000 else n))
649 if exponent > 254:
650 return sign | 0x7F800000
651 return sign if exponent <= 0 else x & 0x807FFFFF | exponent << 23
652
653
654def frexp_f64(bits):
655 """(v_frexp_mant_f64, v_frexp_exp_i32_f64) of a binary64 pattern, the exponent as a 32-bit word. A normal gets
656 the exponent field 1022 and gives its field minus 1022. A subnormal is normalized: its top fraction bit, at
657 position p, becomes the implicit one, and the exponent is p - 1073. A zero keeps its sign and an infinity or a
658 NaN comes back unchanged, all three with exponent 0."""
659 exponent, fraction, sign = bits >> 52 & 0x7FF, bits & ((1 << 52) - 1), bits & (1 << 63)
660 if exponent == 0x7FF:
661 return bits, 0
662 if exponent:
663 return sign | 1022 << 52 | fraction, (exponent - 1022) & 0xFFFFFFFF
664 if not fraction:
665 return sign, 0
666 top = fraction.bit_length() - 1
667 return sign | 1022 << 52 | (fraction << (52 - top)) & ((1 << 52) - 1), (top - 1073) & 0xFFFFFFFF
668
669
670def frexp_ldexp_words():
671 """cs_w32_frexp_ldexp: the input heap and the full expected readback, eight result words per thread and then
672 the records {x, n, d.lo, d.hi}."""
673 results, inputs = [], []
674 for thread, ((x, n), d) in enumerate(zip(FREXP_LDEXP_F32, FREXP_F64)):
675 mantissa, exponent = frexp_f64(d)
676 results.extend((frexp_mant_f32(x), frexp_exp_i32_f32(x), ldexp_f32(x, n), frexp_mant_f32(x ^ 0x80000000),
677 mantissa & 0xFFFFFFFF, mantissa >> 32, exponent,
678 ldexp_f32(x & 0x7FFFFFFF, n) if thread % 2 == 0 else FREXP_LDEXP_KEPT))
679 inputs.extend((x, n, d & 0xFFFFFFFF, d >> 32))
680 return [0xEEEEEEEE] * len(results) + inputs, results + inputs
681
682
683def frexp_ldexp_test(tools, spirv, env=None):
684 """Verify the five frexp and ldexp ops on 64 memory-fed records, including the untouched input records."""
685 initial, expected = frexp_ldexp_words()
686 with tempfile.TemporaryDirectory(prefix="leonida-frexp-ldexp-") as tmp:
687 path = Path(tmp) / "input.bin"
688 path.write_bytes(struct.pack(f"<{len(initial)}I", *initial))
689 child = dict(os.environ if env is None else env, VKC_HEAP_INIT=str(path))
690 child.setdefault("VKC_SUBGROUP_SIZE", str(subgroup_size(spirv, "cs_w32_frexp_ldexp") or 32))
691 return dump_test(tools, spirv, "cs_w32_frexp_ldexp", expected, len(expected), child)
692
693
361# cs_user_sgprs.asm: vk_compute_test puts these words in s4..s7 and the shader stores them back. 694# 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] 695USER_SGPRS = [0x4F000000, 0xDEADBEEF, 7, 0xFFFFFFFF]
363USER_SGPRS_ENV = {"VKC_SGPRS": ",".join(hex(w) for w in USER_SGPRS)} 696USER_SGPRS_ENV = {"VKC_SGPRS": ",".join(hex(w) for w in USER_SGPRS)}
@@ -597,6 +930,17 @@ STORE_WORDS = {
597 # 3D image atomics: the data register afterwards (sint image) and the six texels afterwards (volume) 930 # 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])), 931 "cs_imgatomic3d": ({}, dict(enumerate([0x101, 0xDB, 0xF4, 0xCE, 0xE6, 0xFF])),
599 {57: 0x111, 19: 3, 44: 0xF4, 6: 0xD00D, 30: 0xE6, 39: 0x10}), 932 {57: 0x111, 19: 3, 44: 0xF4, 6: 0xD00D, 30: 0xE6, 39: 0x10}),
933 # GPU-IMG-ATOMIC-EXT: swap, inc, dec, fmin, fmax and fcmpswap. The 2D cases' texels afterwards (uint image, with the
934 # four that all 64 threads hit at 40..43), the data registers afterwards (sint image: 2D cases at 0..20, 3D cases
935 # at 32..37) and the 3D cases' texels afterwards (volume)
936 "cs_imgatomic_ext": ({0: 0x12345678, 1: 0xABCDEF01, 2: 0, 3: 0x68, 4: 0, 5: 0x68, 6: 0x32, 7: 9, 8: 0x6D,
937 9: 0x3FC00000, 10: 0xC0400000, 11: 0x40200000, 12: 0x3FC00000, 13: 0x3FC00000,
938 14: 0x3FC00000, 15: 0x40490FDB, 16: 0x3FC00000, 17: 0x3F800000, 18: 0x7FC00000,
939 19: 0x78, 20: 0x77, 40: 0xCC, 41: 0x4D, 42: 0x427C0000, 43: 0xC27C0000},
940 {0: 0x64, 1: 0xABCDEF01, 2: 0x66, 3: 0x67, 4: 0x68, 5: 0x69, 6: 0x6A, 7: 0, 8: 0x1F4,
941 **dict.fromkeys(range(9, 17), 0x3FC00000), 17: 0, 18: 0x7FC00000, 19: 0x77, 20: 0x78,
942 32: 0x101, 33: 0xDB, 34: 0xF4, 35: 0x3FC00000, 36: 0x3FC00000, 37: 0x3FC00000},
943 {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 944 # 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 945 # 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) 946 # level 5, past the last (2D depth 0 and the past-the-end zeros measured on RDNA2, SHADER-388)
@@ -701,9 +1045,10 @@ def failure(code, output, lines):
701 return f"exit {code}: {details or 'no test output'}" 1045 return f"exit {code}: {details or 'no test output'}"
702 1046
703 1047
704def dump_test(tools, spirv, name, want, words, env=None): 1048def dump_test(tools, spirv, name, want, words, env=None, judge=None):
705 """Run one group with a heap of `words` words and compare the first len(want) words of the whole dump. The 1049 """Run one group with a heap of `words` words and compare the first len(want) words of the whole dump. The
706 console dump stops at word 7.""" 1050 console dump stops at word 7. With `judge`, the whole dump goes to it instead, as a tuple of words, with the
1051 test program's output (it names the device), and its answer ("" for a pass) is returned."""
707 with tempfile.TemporaryDirectory(prefix="leonida-fmt-") as tmp: 1052 with tempfile.TemporaryDirectory(prefix="leonida-fmt-") as tmp:
708 dump = Path(tmp) / "out.bin" 1053 dump = Path(tmp) / "out.bin"
709 # VKC_OUT_WORDS sets a minimum. Pin this dispatch to exactly `words` words. 1054 # VKC_OUT_WORDS sets a minimum. Pin this dispatch to exactly `words` words.
@@ -719,6 +1064,8 @@ def dump_test(tools, spirv, name, want, words, env=None):
719 data = dump.read_bytes() 1064 data = dump.read_bytes()
720 if len(data) != 4 * words: 1065 if len(data) != 4 * words:
721 return f"expected {4 * words} dump bytes, got {len(data)}" 1066 return f"expected {4 * words} dump bytes, got {len(data)}"
1067 if judge:
1068 return judge(struct.unpack(f"<{words}I", data), out)
722 for i, (expected, got) in enumerate(zip(want, struct.unpack(f"<{words}I", data))): 1069 for i, (expected, got) in enumerate(zip(want, struct.unpack(f"<{words}I", data))):
723 if got != expected: 1070 if got != expected:
724 return f"word {i}: expected {expected:#010x}, got {got:#010x}" 1071 return f"word {i}: expected {expected:#010x}, got {got:#010x}"
@@ -965,7 +1312,7 @@ def compute_test(tools, spirv, name, groups, mode, *, require_wave64=False, expe
965 return Skip(f"SKIP ({out.strip() or 'unsupported device'})") 1312 return Skip(f"SKIP ({out.strip() or 'unsupported device'})")
966 if code == 0 and (skip := wave32_lane_skip(out)): 1313 if code == 0 and (skip := wave32_lane_skip(out)):
967 return skip 1314 return skip
968 if sg and (skip := unpinned_subgroup_skip(out)): 1315 if code == 0 and sg and (skip := unpinned_subgroup_skip(out)):
969 return skip 1316 return skip
970 if code != 0: 1317 if code != 0:
971 return failure(code, out, 2) 1318 return failure(code, out, 2)
@@ -1842,6 +2189,10 @@ def main():
1842 expected_words=USER_SGPRS_WORDS, env=USER_SGPRS_ENV))) 2189 expected_words=USER_SGPRS_WORDS, env=USER_SGPRS_ENV)))
1843 results.append(("cs_heap_init", compute_test(tools, spirv, "cs_heap_init", "1", "dump", 2190 results.append(("cs_heap_init", compute_test(tools, spirv, "cs_heap_init", "1", "dump",
1844 expected_words=HEAP_INIT_EXPECTED, env=heap_init_env()))) 2191 expected_words=HEAP_INIT_EXPECTED, env=heap_init_env())))
2192 results.append(("cs_w32_shift64", shift64_test(tools, spirv)))
2193 results.append(("cs_w32_cmp_f64", cmp_f64_test(tools, spirv)))
2194 results.append(("cs_w32_round_f64", round_f64_test(tools, spirv)))
2195 results.append(("cs_w32_frexp_ldexp", frexp_ldexp_test(tools, spirv)))
1845 results.append(("cs_cvt_f32_sat", cvt_f32_sat_test(tools, spirv))) 2196 results.append(("cs_cvt_f32_sat", cvt_f32_sat_test(tools, spirv)))
1846 results.append(("cs_fma_fused", fma_fused_test(tools, spirv))) 2197 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", 2198 results.append(("cs_cvt_pk_u8", compute_test(tools, spirv, "cs_cvt_pk_u8", "1", "dump",
@@ -1857,7 +2208,8 @@ def main():
1857 results.append(("ms_wave_info_s3", mesh_w64x_test(tools, spirv, "ms_wave_info_s3"))) 2208 results.append(("ms_wave_info_s3", mesh_w64x_test(tools, spirv, "ms_wave_info_s3")))
1858 with tempfile.TemporaryDirectory(prefix="leonida-mesh-") as tmp: 2209 with tempfile.TemporaryDirectory(prefix="leonida-mesh-") as tmp:
1859 results.append(("ms_v5_workgroup", mesh_v5_test(tools, spirv, Path(tmp) / "groups.raw"))) 2210 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"]), 2211 for name, args in (("cs_imgstore", []), ("cs_imgstore_cube", ["cube"]), ("cs_imgload", ["load"]),
2212 ("cs_imgload_tfe", ["load"]),
1861 ("cs_imgload_d16", ["load-d16"]), ("cs_imgload_d16_tfe", ["load-d16"]), 2213 ("cs_imgload_d16", ["load-d16"]), ("cs_imgload_d16_tfe", ["load-d16"]),
1862 ("cs_sample_lz_int_d16", ["load-d16"])): 2214 ("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) 2215 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_dpp_cmp.asm b/runtime/test/shaders/cs_dpp_cmp.asm
new file mode 100644
index 000000000..867c6a81a
--- /dev/null
+++ b/runtime/test/shaders/cs_dpp_cmp.asm
@@ -0,0 +1,22 @@
1; DPP on a VOPC compare: src0 is read from the permuted lane, src1 from the lane itself, and the result goes to VCC.
2; v1 = float(lane). The first compare takes src0 from the other lane of each pair (quad_perm [1,0,3,2]), so
3; "neighbour > self" is true on even lanes. The second takes it from the other half of each 8 lanes (dpp8), so it
4; is true on lanes 0-3. out = (first ? 1 : 0) + (second ? 2 : 0).
5; Run: vk_compute_test cs_dpp_cmp.spv 1 dump -> out[0..7] = 3 2 3 2 1 0 1 0
6; llvm-mc assembles neither compare for gfx1013 ("dpp variant of this instruction is not supported"), so the GPU
7; test takes this file's text as its listing; tools/shader_disasm.py prints the same lines for the encoded words.
8; run_gpu_tests: text only, llvm-mc has no gfx1013 encoding for an instruction here
9; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm
10v_mbcnt_lo_u32_b32 v0, -1, 0
11v_cvt_f32_u32 v1, v0
12v_mov_b32 v3, 0
13v_mov_b32 v4, 1
14v_mov_b32 v5, 2
15v_cmp_gt_f32_dpp vcc_lo, v1, v1 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf bound_ctrl:1
16v_cndmask_b32 v6, v3, v4, vcc_lo
17v_cmp_gt_f32_dpp vcc_lo, v1, v1 dpp8:[4,5,6,7,0,1,2,3]
18v_cndmask_b32 v7, v3, v5, vcc_lo
19v_add_nc_u32 v6, v6, v7
20v_lshlrev_b32 v2, 2, v0
21buffer_store_dword v6, v2, s[0:3], 0 offen
22s_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_cmp_f64.asm b/runtime/test/shaders/cs_w32_cmp_f64.asm
new file mode 100644
index 000000000..99ddb94dd
--- /dev/null
+++ b/runtime/test/shaders/cs_w32_cmp_f64.asm
@@ -0,0 +1,270 @@
1; GPU-CMP-F64: the 16 binary64 vector compares, v_cmp_*_f64 into VCC and v_cmpx_*_f64 on EXEC.
2; group: 128,1,1
3; mattr: +wavefrontsize32,-wavefrontsize64
4; check.py seeds 256 records at byte 0x800: {a.lo, a.hi, b.lo, b.hi}, the Cartesian product of 16 binary64 values
5; (record 16 * ia + ib holds values ia and ib), in ascending order and then two NaNs: -inf, -max, -1 - 1 ulp, -1,
6; the value above -1 (high dword smaller, low dword all ones), the negative smallest subnormal, -0, +0, the smallest
7; subnormal, the smallest normal, 1, 1 + 1 ulp, +max, +inf, a NaN whose payload is only in the low dword (its high
8; dword is +inf's) and a negative quiet NaN.
9; Thread i reads records i and i + 128 from memory, so neither the translator nor the driver can fold a compare,
10; and writes two words per record at byte 8 * record: the v_cmp_ word, then the v_cmpx_ word.
11; Bits 0..15 of both words are the 16 predicates in opcode order (RDNA2 ISA, VOPC compare operations):
12; f lt eq le gt lg ge o u nge nlg ngt nle neq nlt tru
13; lt, eq and gt are IEEE-754 (false when either operand is a NaN, -0 == +0, no denormal flush), o is "neither is a
14; NaN", u its negation, and le/lg/ge/nge/nlg/ngt/nle/neq/nlt are the unions and negations their names say, so every
15; n* predicate is true for a NaN. v_cmp_ sets the lane's VCC bit; v_cmpx_ leaves the lane active only when true.
16; bit 16: v_cmp_tru / v_cmpx_tru with the odd threads turned off first: set on even threads only. A lane EXEC has
17; off gets VCC 0 from v_cmp_ and stays off through v_cmpx_.
18; bit 17: lt with VOP3 modifiers, |a| < -b. bit 18: nge with VOP3 modifiers, !(-a >= |b|).
19; Bits 19..31 are 0. EXEC is put back with a constant after each v_cmpx_, so no step needs a particular subgroup
20; width. The input records must come back unchanged.
21; Run with the heap initialized by check.py's cmp_f64_test; compare all 1536 words.
22v_lshlrev_b32_e32 v1, 4, v0
23v_add_nc_u32_e32 v11, 0x800, v1
24v_lshlrev_b32_e32 v10, 3, v0
25v_and_b32_e32 v9, 1, v0
26buffer_load_dwordx4 v[2:5], v1, s[0:3], 0 offen offset:2048
27s_waitcnt vmcnt(0)
28v_mov_b32_e32 v6, 0
29v_mov_b32_e32 v7, 0
30v_cmp_f_f64_e32 vcc_lo, v[2:3], v[4:5]
31v_or_b32_e32 v8, 0x1, v6
32v_cndmask_b32_e32 v6, v6, v8, vcc_lo
33v_cmp_lt_f64_e32 vcc_lo, v[2:3], v[4:5]
34v_or_b32_e32 v8, 0x2, v6
35v_cndmask_b32_e32 v6, v6, v8, vcc_lo
36v_cmp_eq_f64_e32 vcc_lo, v[2:3], v[4:5]
37v_or_b32_e32 v8, 0x4, v6
38v_cndmask_b32_e32 v6, v6, v8, vcc_lo
39v_cmp_le_f64_e32 vcc_lo, v[2:3], v[4:5]
40v_or_b32_e32 v8, 0x8, v6
41v_cndmask_b32_e32 v6, v6, v8, vcc_lo
42v_cmp_gt_f64_e32 vcc_lo, v[2:3], v[4:5]
43v_or_b32_e32 v8, 0x10, v6
44v_cndmask_b32_e32 v6, v6, v8, vcc_lo
45v_cmp_lg_f64_e32 vcc_lo, v[2:3], v[4:5]
46v_or_b32_e32 v8, 0x20, v6
47v_cndmask_b32_e32 v6, v6, v8, vcc_lo
48v_cmp_ge_f64_e32 vcc_lo, v[2:3], v[4:5]
49v_or_b32_e32 v8, 0x40, v6
50v_cndmask_b32_e32 v6, v6, v8, vcc_lo
51v_cmp_o_f64_e32 vcc_lo, v[2:3], v[4:5]
52v_or_b32_e32 v8, 0x80, v6
53v_cndmask_b32_e32 v6, v6, v8, vcc_lo
54v_cmp_u_f64_e32 vcc_lo, v[2:3], v[4:5]
55v_or_b32_e32 v8, 0x100, v6
56v_cndmask_b32_e32 v6, v6, v8, vcc_lo
57v_cmp_nge_f64_e32 vcc_lo, v[2:3], v[4:5]
58v_or_b32_e32 v8, 0x200, v6
59v_cndmask_b32_e32 v6, v6, v8, vcc_lo
60v_cmp_nlg_f64_e32 vcc_lo, v[2:3], v[4:5]
61v_or_b32_e32 v8, 0x400, v6
62v_cndmask_b32_e32 v6, v6, v8, vcc_lo
63v_cmp_ngt_f64_e32 vcc_lo, v[2:3], v[4:5]
64v_or_b32_e32 v8, 0x800, v6
65v_cndmask_b32_e32 v6, v6, v8, vcc_lo
66v_cmp_nle_f64_e32 vcc_lo, v[2:3], v[4:5]
67v_or_b32_e32 v8, 0x1000, v6
68v_cndmask_b32_e32 v6, v6, v8, vcc_lo
69v_cmp_neq_f64_e32 vcc_lo, v[2:3], v[4:5]
70v_or_b32_e32 v8, 0x2000, v6
71v_cndmask_b32_e32 v6, v6, v8, vcc_lo
72v_cmp_nlt_f64_e32 vcc_lo, v[2:3], v[4:5]
73v_or_b32_e32 v8, 0x4000, v6
74v_cndmask_b32_e32 v6, v6, v8, vcc_lo
75v_cmp_tru_f64_e32 vcc_lo, v[2:3], v[4:5]
76v_or_b32_e32 v8, 0x8000, v6
77v_cndmask_b32_e32 v6, v6, v8, vcc_lo
78v_cmpx_eq_u32_e32 0, v9
79v_cmp_tru_f64_e32 vcc_lo, v[2:3], v[4:5]
80s_mov_b32 exec_lo, -1
81v_or_b32_e32 v8, 0x10000, v6
82v_cndmask_b32_e32 v6, v6, v8, vcc_lo
83v_cmp_lt_f64_e64 vcc_lo, |v[2:3]|, -v[4:5]
84v_or_b32_e32 v8, 0x20000, v6
85v_cndmask_b32_e32 v6, v6, v8, vcc_lo
86v_cmp_nge_f64_e64 vcc_lo, -v[2:3], |v[4:5]|
87v_or_b32_e32 v8, 0x40000, v6
88v_cndmask_b32_e32 v6, v6, v8, vcc_lo
89v_cmpx_f_f64_e32 v[2:3], v[4:5]
90v_or_b32_e32 v7, 0x1, v7
91s_mov_b32 exec_lo, -1
92v_cmpx_lt_f64_e32 v[2:3], v[4:5]
93v_or_b32_e32 v7, 0x2, v7
94s_mov_b32 exec_lo, -1
95v_cmpx_eq_f64_e32 v[2:3], v[4:5]
96v_or_b32_e32 v7, 0x4, v7
97s_mov_b32 exec_lo, -1
98v_cmpx_le_f64_e32 v[2:3], v[4:5]
99v_or_b32_e32 v7, 0x8, v7
100s_mov_b32 exec_lo, -1
101v_cmpx_gt_f64_e32 v[2:3], v[4:5]
102v_or_b32_e32 v7, 0x10, v7
103s_mov_b32 exec_lo, -1
104v_cmpx_lg_f64_e32 v[2:3], v[4:5]
105v_or_b32_e32 v7, 0x20, v7
106s_mov_b32 exec_lo, -1
107v_cmpx_ge_f64_e32 v[2:3], v[4:5]
108v_or_b32_e32 v7, 0x40, v7
109s_mov_b32 exec_lo, -1
110v_cmpx_o_f64_e32 v[2:3], v[4:5]
111v_or_b32_e32 v7, 0x80, v7
112s_mov_b32 exec_lo, -1
113v_cmpx_u_f64_e32 v[2:3], v[4:5]
114v_or_b32_e32 v7, 0x100, v7
115s_mov_b32 exec_lo, -1
116v_cmpx_nge_f64_e32 v[2:3], v[4:5]
117v_or_b32_e32 v7, 0x200, v7
118s_mov_b32 exec_lo, -1
119v_cmpx_nlg_f64_e32 v[2:3], v[4:5]
120v_or_b32_e32 v7, 0x400, v7
121s_mov_b32 exec_lo, -1
122v_cmpx_ngt_f64_e32 v[2:3], v[4:5]
123v_or_b32_e32 v7, 0x800, v7
124s_mov_b32 exec_lo, -1
125v_cmpx_nle_f64_e32 v[2:3], v[4:5]
126v_or_b32_e32 v7, 0x1000, v7
127s_mov_b32 exec_lo, -1
128v_cmpx_neq_f64_e32 v[2:3], v[4:5]
129v_or_b32_e32 v7, 0x2000, v7
130s_mov_b32 exec_lo, -1
131v_cmpx_nlt_f64_e32 v[2:3], v[4:5]
132v_or_b32_e32 v7, 0x4000, v7
133s_mov_b32 exec_lo, -1
134v_cmpx_tru_f64_e32 v[2:3], v[4:5]
135v_or_b32_e32 v7, 0x8000, v7
136s_mov_b32 exec_lo, -1
137v_cmpx_eq_u32_e32 0, v9
138v_cmpx_tru_f64_e32 v[2:3], v[4:5]
139v_or_b32_e32 v7, 0x10000, v7
140s_mov_b32 exec_lo, -1
141v_cmpx_lt_f64_e64 |v[2:3]|, -v[4:5]
142v_or_b32_e32 v7, 0x20000, v7
143s_mov_b32 exec_lo, -1
144v_cmpx_nge_f64_e64 -v[2:3], |v[4:5]|
145v_or_b32_e32 v7, 0x40000, v7
146s_mov_b32 exec_lo, -1
147buffer_store_dwordx2 v[6:7], v10, s[0:3], 0 offen
148buffer_load_dwordx4 v[2:5], v11, s[0:3], 0 offen offset:2048
149s_waitcnt vmcnt(0)
150v_mov_b32_e32 v6, 0
151v_mov_b32_e32 v7, 0
152v_cmp_f_f64_e32 vcc_lo, v[2:3], v[4:5]
153v_or_b32_e32 v8, 0x1, v6
154v_cndmask_b32_e32 v6, v6, v8, vcc_lo
155v_cmp_lt_f64_e32 vcc_lo, v[2:3], v[4:5]
156v_or_b32_e32 v8, 0x2, v6
157v_cndmask_b32_e32 v6, v6, v8, vcc_lo
158v_cmp_eq_f64_e32 vcc_lo, v[2:3], v[4:5]
159v_or_b32_e32 v8, 0x4, v6
160v_cndmask_b32_e32 v6, v6, v8, vcc_lo
161v_cmp_le_f64_e32 vcc_lo, v[2:3], v[4:5]
162v_or_b32_e32 v8, 0x8, v6
163v_cndmask_b32_e32 v6, v6, v8, vcc_lo
164v_cmp_gt_f64_e32 vcc_lo, v[2:3], v[4:5]
165v_or_b32_e32 v8, 0x10, v6
166v_cndmask_b32_e32 v6, v6, v8, vcc_lo
167v_cmp_lg_f64_e32 vcc_lo, v[2:3], v[4:5]
168v_or_b32_e32 v8, 0x20, v6
169v_cndmask_b32_e32 v6, v6, v8, vcc_lo
170v_cmp_ge_f64_e32 vcc_lo, v[2:3], v[4:5]
171v_or_b32_e32 v8, 0x40, v6
172v_cndmask_b32_e32 v6, v6, v8, vcc_lo
173v_cmp_o_f64_e32 vcc_lo, v[2:3], v[4:5]
174v_or_b32_e32 v8, 0x80, v6
175v_cndmask_b32_e32 v6, v6, v8, vcc_lo
176v_cmp_u_f64_e32 vcc_lo, v[2:3], v[4:5]
177v_or_b32_e32 v8, 0x100, v6
178v_cndmask_b32_e32 v6, v6, v8, vcc_lo
179v_cmp_nge_f64_e32 vcc_lo, v[2:3], v[4:5]
180v_or_b32_e32 v8, 0x200, v6
181v_cndmask_b32_e32 v6, v6, v8, vcc_lo
182v_cmp_nlg_f64_e32 vcc_lo, v[2:3], v[4:5]
183v_or_b32_e32 v8, 0x400, v6
184v_cndmask_b32_e32 v6, v6, v8, vcc_lo
185v_cmp_ngt_f64_e32 vcc_lo, v[2:3], v[4:5]
186v_or_b32_e32 v8, 0x800, v6
187v_cndmask_b32_e32 v6, v6, v8, vcc_lo
188v_cmp_nle_f64_e32 vcc_lo, v[2:3], v[4:5]
189v_or_b32_e32 v8, 0x1000, v6
190v_cndmask_b32_e32 v6, v6, v8, vcc_lo
191v_cmp_neq_f64_e32 vcc_lo, v[2:3], v[4:5]
192v_or_b32_e32 v8, 0x2000, v6
193v_cndmask_b32_e32 v6, v6, v8, vcc_lo
194v_cmp_nlt_f64_e32 vcc_lo, v[2:3], v[4:5]
195v_or_b32_e32 v8, 0x4000, v6
196v_cndmask_b32_e32 v6, v6, v8, vcc_lo
197v_cmp_tru_f64_e32 vcc_lo, v[2:3], v[4:5]
198v_or_b32_e32 v8, 0x8000, v6
199v_cndmask_b32_e32 v6, v6, v8, vcc_lo
200v_cmpx_eq_u32_e32 0, v9
201v_cmp_tru_f64_e32 vcc_lo, v[2:3], v[4:5]
202s_mov_b32 exec_lo, -1
203v_or_b32_e32 v8, 0x10000, v6
204v_cndmask_b32_e32 v6, v6, v8, vcc_lo
205v_cmp_lt_f64_e64 vcc_lo, |v[2:3]|, -v[4:5]
206v_or_b32_e32 v8, 0x20000, v6
207v_cndmask_b32_e32 v6, v6, v8, vcc_lo
208v_cmp_nge_f64_e64 vcc_lo, -v[2:3], |v[4:5]|
209v_or_b32_e32 v8, 0x40000, v6
210v_cndmask_b32_e32 v6, v6, v8, vcc_lo
211v_cmpx_f_f64_e32 v[2:3], v[4:5]
212v_or_b32_e32 v7, 0x1, v7
213s_mov_b32 exec_lo, -1
214v_cmpx_lt_f64_e32 v[2:3], v[4:5]
215v_or_b32_e32 v7, 0x2, v7
216s_mov_b32 exec_lo, -1
217v_cmpx_eq_f64_e32 v[2:3], v[4:5]
218v_or_b32_e32 v7, 0x4, v7
219s_mov_b32 exec_lo, -1
220v_cmpx_le_f64_e32 v[2:3], v[4:5]
221v_or_b32_e32 v7, 0x8, v7
222s_mov_b32 exec_lo, -1
223v_cmpx_gt_f64_e32 v[2:3], v[4:5]
224v_or_b32_e32 v7, 0x10, v7
225s_mov_b32 exec_lo, -1
226v_cmpx_lg_f64_e32 v[2:3], v[4:5]
227v_or_b32_e32 v7, 0x20, v7
228s_mov_b32 exec_lo, -1
229v_cmpx_ge_f64_e32 v[2:3], v[4:5]
230v_or_b32_e32 v7, 0x40, v7
231s_mov_b32 exec_lo, -1
232v_cmpx_o_f64_e32 v[2:3], v[4:5]
233v_or_b32_e32 v7, 0x80, v7
234s_mov_b32 exec_lo, -1
235v_cmpx_u_f64_e32 v[2:3], v[4:5]
236v_or_b32_e32 v7, 0x100, v7
237s_mov_b32 exec_lo, -1
238v_cmpx_nge_f64_e32 v[2:3], v[4:5]
239v_or_b32_e32 v7, 0x200, v7
240s_mov_b32 exec_lo, -1
241v_cmpx_nlg_f64_e32 v[2:3], v[4:5]
242v_or_b32_e32 v7, 0x400, v7
243s_mov_b32 exec_lo, -1
244v_cmpx_ngt_f64_e32 v[2:3], v[4:5]
245v_or_b32_e32 v7, 0x800, v7
246s_mov_b32 exec_lo, -1
247v_cmpx_nle_f64_e32 v[2:3], v[4:5]
248v_or_b32_e32 v7, 0x1000, v7
249s_mov_b32 exec_lo, -1
250v_cmpx_neq_f64_e32 v[2:3], v[4:5]
251v_or_b32_e32 v7, 0x2000, v7
252s_mov_b32 exec_lo, -1
253v_cmpx_nlt_f64_e32 v[2:3], v[4:5]
254v_or_b32_e32 v7, 0x4000, v7
255s_mov_b32 exec_lo, -1
256v_cmpx_tru_f64_e32 v[2:3], v[4:5]
257v_or_b32_e32 v7, 0x8000, v7
258s_mov_b32 exec_lo, -1
259v_cmpx_eq_u32_e32 0, v9
260v_cmpx_tru_f64_e32 v[2:3], v[4:5]
261v_or_b32_e32 v7, 0x10000, v7
262s_mov_b32 exec_lo, -1
263v_cmpx_lt_f64_e64 |v[2:3]|, -v[4:5]
264v_or_b32_e32 v7, 0x20000, v7
265s_mov_b32 exec_lo, -1
266v_cmpx_nge_f64_e64 -v[2:3], |v[4:5]|
267v_or_b32_e32 v7, 0x40000, v7
268s_mov_b32 exec_lo, -1
269buffer_store_dwordx2 v[6:7], v10, s[0:3], 0 offen offset:1024
270s_endpgm
diff --git a/runtime/test/shaders/cs_w32_frexp_ldexp.asm b/runtime/test/shaders/cs_w32_frexp_ldexp.asm
new file mode 100644
index 000000000..330549eb1
--- /dev/null
+++ b/runtime/test/shaders/cs_w32_frexp_ldexp.asm
@@ -0,0 +1,44 @@
1; GPU-FREXP-LDEXP: v_frexp_mant_f32, v_frexp_exp_i32_f32, v_ldexp_f32, v_frexp_mant_f64 and v_frexp_exp_i32_f64.
2; group: 64,1,1
3; mattr: +wavefrontsize32,-wavefrontsize64
4; check.py seeds 64 records at byte 0x800: {x, n, d.lo, d.hi}, a binary32 value, an ldexp exponent and a binary64
5; value. Thread i reads record i from memory, so neither the translator nor the driver can fold an op, and writes
6; eight words at byte 32 * i:
7; +0 v_frexp_mant_f32 x a normal keeps sign and fraction and gets the exponent field 126 (a mantissa
8; in [0.5, 1)); a zero or a denormal, read as zero, gives a zero of its sign;
9; an infinity or a NaN comes back unchanged
10; +4 v_frexp_exp_i32_f32 x the exponent field minus 126 for a normal, 0 for everything else
11; +8 v_ldexp_f32 x, n n is clamped to [-512, 512] and added to the exponent field: above 254 the
12; result is an infinity of x's sign, at 0 or below a zero of its sign (there
13; are no denormal results); a zero, a denormal, an infinity and a NaN ignore n
14; +12 v_frexp_mant_f32 -x VOP3 neg: the sign bit is flipped first
15; +16 v_frexp_mant_f64 d two words, low first: a normal gets the exponent field 1022; a subnormal is
16; normalized into [0.5, 1) too; a zero keeps its sign; an infinity or a NaN
17; comes back unchanged
18; +24 v_frexp_exp_i32_f64 d the exponent field minus 1022 for a normal, the position of the top fraction
19; bit minus 1073 for a subnormal (-1073..-1022), 0 for everything else
20; +28 v_ldexp_f32 |x|, n VOP3 abs, with the odd threads turned off first: they keep the 0xdeadbeef
21; that was in the destination
22; The records cover normals, the clamp of n at +-512 and beyond, results that overflow and that fall below the
23; smallest normal, binary32 denormals, binary64 subnormals with single bits on both sides of the dword boundary and
24; with several bits, zeros, infinities and NaNs. The rules are the rows of docs/design.md for these five ops.
25; The input records must come back unchanged.
26; Run with the heap initialized by check.py's frexp_ldexp_test; compare all 768 words.
27v_lshlrev_b32_e32 v1, 4, v0
28v_lshlrev_b32_e32 v10, 5, v0
29v_and_b32_e32 v9, 1, v0
30buffer_load_dwordx4 v[2:5], v1, s[0:3], 0 offen offset:2048
31s_waitcnt vmcnt(0)
32v_frexp_mant_f32_e32 v12, v2
33v_frexp_exp_i32_f32_e32 v13, v2
34v_ldexp_f32 v14, v2, v3
35v_frexp_mant_f32_e64 v15, -v2
36v_frexp_mant_f64_e32 v[16:17], v[4:5]
37v_frexp_exp_i32_f64_e32 v18, v[4:5]
38v_mov_b32_e32 v19, 0xdeadbeef
39v_cmpx_eq_u32_e32 0, v9
40v_ldexp_f32 v19, |v2|, v3
41s_mov_b32 exec_lo, -1
42buffer_store_dwordx4 v[12:15], v10, s[0:3], 0 offen
43buffer_store_dwordx4 v[16:19], v10, s[0:3], 0 offen offset:16
44s_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_round_f64.asm b/runtime/test/shaders/cs_w32_round_f64.asm
new file mode 100644
index 000000000..79358129f
--- /dev/null
+++ b/runtime/test/shaders/cs_w32_round_f64.asm
@@ -0,0 +1,56 @@
1; GPU-ROUND-F64: round binary64 to an integral value, v_trunc_f64, v_ceil_f64, v_rndne_f64 and v_floor_f64.
2; group: 64,1,1
3; mattr: +wavefrontsize32,-wavefrontsize64
4; check.py seeds 64 binary64 inputs at byte 0x1000, {lo, hi} each: signed zeros, the smallest subnormals and
5; normals, values around 0.5 and 1 (the largest value below 0.5 among them), ties at 0.5, 1.5, 2.5, 3.5, 4.5 and 5.5,
6; ties at 2^31 + 0.5, 2^51 + 0.5 and 2^52 - 0.5, the integers 2^52, 2^52 + 1, 2^53 - 1, 2^53 and 2^63, 1e300, the
7; largest finite value, the infinities, quiet NaNs with and without a payload and two signalling NaNs. Thread i
8; reads input i from memory, so neither the translator nor the driver can fold a rounding, and writes eight results
9; of two words (low first) at byte 64 * i:
10; +0 v_trunc_f64 x toward zero
11; +8 v_ceil_f64 x toward +infinity
12; +16 v_rndne_f64 x to nearest, a tie to the even integer
13; +24 v_floor_f64 x toward -infinity
14; +32 v_trunc_f64 -x VOP3 neg: the sign bit is flipped first
15; +40 v_ceil_f64 |x| VOP3 abs: the sign bit is cleared first
16; +48 v_floor_f64 x the destination pair v[21:22] overlaps the source pair v[20:21]
17; +56 v_rndne_f64 x with the odd threads turned off first: they keep the pair 0xdeadbeef,
18; 0xcafef00d that was in the destination
19; RDNA2 ISA VOP1 opcodes 23..26. A result that is zero keeps the sign of its source (ceil of -0.25 is -0), a value
20; of magnitude 2^52 or more is already integral, an infinity stays, and a NaN and a subnormal are rounded like any
21; other value: a NaN comes back unchanged, signalling ones included, ceil of the smallest subnormal is 1 and floor
22; of its negative is -1 (docs/design.md). The translator gives the four ops to the driver's double-precision Trunc,
23; Ceil, RoundEven and Floor, except for a NaN and a subnormal, which it rounds with integer ops: Vulkan lets a driver
24; return any NaN for a NaN (a signalling one came back quiet on an RTX 4070 Ti and on llvmpipe) and, with no
25; DenormPreserve for 64 bits, read a subnormal as zero (llvmpipe did).
26; Run with the heap initialized by check.py's round_f64_test; all 1152 words are compared, and the input records
27; must come back unchanged.
28v_lshlrev_b32_e32 v1, 3, v0
29v_add_nc_u32_e32 v1, 0x1000, v1
30v_lshlrev_b32_e32 v10, 6, v0
31v_and_b32_e32 v9, 1, v0
32buffer_load_dwordx2 v[2:3], v1, s[0:3], 0 offen
33s_waitcnt vmcnt(0)
34v_trunc_f64_e32 v[4:5], v[2:3]
35v_ceil_f64_e32 v[6:7], v[2:3]
36v_rndne_f64_e32 v[12:13], v[2:3]
37v_floor_f64_e32 v[14:15], v[2:3]
38v_trunc_f64_e64 v[16:17], -v[2:3]
39v_ceil_f64_e64 v[18:19], |v[2:3]|
40v_mov_b32_e32 v20, v2
41v_mov_b32_e32 v21, v3
42v_floor_f64_e32 v[21:22], v[20:21]
43v_mov_b32_e32 v24, 0xdeadbeef
44v_mov_b32_e32 v25, 0xcafef00d
45v_cmpx_eq_u32_e32 0, v9
46v_rndne_f64_e32 v[24:25], v[2:3]
47s_mov_b32 exec_lo, -1
48buffer_store_dwordx2 v[4:5], v10, s[0:3], 0 offen
49buffer_store_dwordx2 v[6:7], v10, s[0:3], 0 offen offset:8
50buffer_store_dwordx2 v[12:13], v10, s[0:3], 0 offen offset:16
51buffer_store_dwordx2 v[14:15], v10, s[0:3], 0 offen offset:24
52buffer_store_dwordx2 v[16:17], v10, s[0:3], 0 offen offset:32
53buffer_store_dwordx2 v[18:19], v10, s[0:3], 0 offen offset:40
54buffer_store_dwordx2 v[21:22], v10, s[0:3], 0 offen offset:48
55buffer_store_dwordx2 v[24:25], v10, s[0:3], 0 offen offset:56
56s_endpgm
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/shaders/ps_w64_a_wqm_uniform_vote.asm b/runtime/test/shaders/ps_w64_a_wqm_uniform_vote.asm
new file mode 100644
index 000000000..51f320e8e
--- /dev/null
+++ b/runtime/test/shaders/ps_w64_a_wqm_uniform_vote.asm
@@ -0,0 +1,53 @@
1; SHADER-W64-WQM-UVOTE tier A: votes on a compare of scalars while EXEC is the whole quads of the launch mask
2; (docs/design.md, "Wave64 graphics: a uniform vote under whole-quad EXEC"). A pixel shader that needs derivatives
3; starts with s_wqm_b64 exec, exec: the helper lanes of every quad that has a covered pixel come on. A v_cmp of
4; scalars and constants there is the same in every lane, so its mask is every lane of EXEC or none, and EXEC has a
5; lane in every 32-lane half that runs (a quad never straddles the halves): each half votes as the whole wave does,
6; and both sides of the branch may have code of their own, scalars included. s4 is a user SGPR (the test sets it to
7; 9 with VKH_SGPRS=0,0,0,0,9). x = floor(u * 64) on the 64x64 target of vs_ids.
8; (1) s_cbranch_vccz if/else on 5 < s4 (yes), the compare written straight to VCC: the yes side sets v6 = 7 and
9; s20 = 11, the no side v6 = 5 and s20 = 22; both are read after the join. r0 = x + 7, r1 = 11.
10; (2) the LLVM form v_cmp_e64 s[14:15] + s_and_b64 vcc, exec, s[14:15] + s_cbranch_vccnz on 50 < s4 (no): the no
11; side sets v8 = 3 and s21 = 33, the yes side v8 = 4 and s21 = 44. r2 = s21 + v8 = 36.
12; (3) a loop whose back edge is s_cbranch_vccnz on s22 < s4 (s22 the trip count, an SGPR carried across the back
13; edge): s4 = 9 iterations of v9 += 2, then v9 += s22. r3 = 2 * 9 + 9 = 27.
14; EXEC goes back to the launch mask before the export. The words are those of ps_w64_a_uniform_vote, whose compares
15; read a VGPR under the launch mask; here no VGPR is compared, because one written under the launch mask is not
16; uniform over the helper lanes.
17; Run: VKH_SGPRS=0,0,0,0,9 vk_harness vs_ids.spv ps_w64_a_wqm_uniform_vote.spv out.raw with VKH_SUBGROUP_SIZE=64
18; and 32: equal, and equal to the expected words (x + 7, 11, 36, 27).
19; mattr: +wavefrontsize64,-wavefrontsize32
20v_interp_p1_f32_e32 v2, v0, attr0.x
21v_interp_p2_f32_e32 v2, v1, attr0.x
22v_mul_f32_e32 v2, 0x42800000, v2
23v_cvt_u32_f32_e32 v2, v2
24s_mov_b64 s[10:11], exec
25s_wqm_b64 exec, exec
26v_cmp_lt_u32_e64 vcc, 5, s4
27s_cbranch_vccz 3
28v_mov_b32_e32 v6, 7
29s_mov_b32 s20, 11
30s_branch 2
31v_mov_b32_e32 v6, 5
32s_mov_b32 s20, 22
33v_add_nc_u32_e32 v6, v6, v2
34v_mov_b32_e32 v7, s20
35v_cmp_lt_u32_e64 s[14:15], 50, s4
36s_and_b64 vcc, exec, s[14:15]
37s_cbranch_vccnz 3
38v_mov_b32_e32 v8, 3
39s_mov_b32 s21, 33
40s_branch 2
41v_mov_b32_e32 v8, 4
42s_mov_b32 s21, 44
43v_add_nc_u32_e32 v8, s21, v8
44s_mov_b32 s22, 0
45v_mov_b32_e32 v9, 0
46s_add_u32 s22, s22, 1
47v_add_nc_u32_e32 v9, 2, v9
48v_cmp_gt_u32_e64 vcc, s4, s22
49s_cbranch_vccnz -5
50v_add_nc_u32_e32 v9, s22, v9
51s_and_b64 exec, exec, s[10:11]
52exp mrt0 v6, v7, v8, v9 done vm
53s_endpgm
diff --git a/runtime/test/shaders/w64_graphics.py b/runtime/test/shaders/w64_graphics.py
index 649fc4630..e28d03d2f 100644
--- a/runtime/test/shaders/w64_graphics.py
+++ b/runtime/test/shaders/w64_graphics.py
@@ -187,6 +187,8 @@ FIXTURES = {
187 "ps_w64_a_swizzle": ("A", _a_swizzle, {}), 187 "ps_w64_a_swizzle": ("A", _a_swizzle, {}),
188 "ps_w64_a_bpermute": ("A", _a_bpermute, {}), 188 "ps_w64_a_bpermute": ("A", _a_bpermute, {}),
189 "ps_w64_a_uniform_vote": ("A", _a_uniform_vote, {"VKH_SGPRS": "0,0,0,0,9"}), 189 "ps_w64_a_uniform_vote": ("A", _a_uniform_vote, {"VKH_SGPRS": "0,0,0,0,9"}),
190 # SHADER-W64-WQM-UVOTE: the same votes on compares of scalars under s_wqm_b64 exec, exec (the same words)
191 "ps_w64_a_wqm_uniform_vote": ("A", _a_uniform_vote, {"VKH_SGPRS": "0,0,0,0,9"}),
190 192
191 "ps_w64_a_discard": ("A", _a_discard, {}), 193 "ps_w64_a_discard": ("A", _a_discard, {}),
192 "ps_w64_b_waterfall": ("B", _b_waterfall, {}), 194 "ps_w64_b_waterfall": ("B", _b_waterfall, {}),
diff --git a/runtime/test/vk_command_replay_test.cpp b/runtime/test/vk_command_replay_test.cpp
index 9769e70be..703821e3c 100644
--- a/runtime/test/vk_command_replay_test.cpp
+++ b/runtime/test/vk_command_replay_test.cpp
@@ -8,7 +8,7 @@
8// list, which D3D12 orders on the queue and needs an explicit dependency for on Vulkan. Part H copies depth to colour 8// list, which D3D12 orders on the queue and needs an explicit dependency for on Vulkan. Part H copies depth to colour
9// and back (D32_FLOAT <-> R32_FLOAT), which the replay stages through a scratch buffer. Part I resolves a depth 9// and back (D32_FLOAT <-> R32_FLOAT), which the replay stages through a scratch buffer. Part I resolves a depth
10// rectangle (MIN) and checks that the texels around it keep their values. Part J copies between disjoint regions 10// rectangle (MIN) and checks that the texels around it keep their values. Part J copies between disjoint regions
11// of one texture subresource. 11// of one texture subresource. Part L releases textures with a barrier into LAYOUT_UNDEFINED and uses one again.
12// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation; any validation error fails the test. 12// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation; any validation error fails the test.
13#include "vk_test_device.h" 13#include "vk_test_device.h"
14#include "../src/vulkan_replay.h" 14#include "../src/vulkan_replay.h"
@@ -1265,6 +1265,196 @@ 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
1343// Part L: an enhanced barrier into LAYOUT_UNDEFINED releases a texture (D3D-BARRIER-INTO-UNDEFINED). Vulkan has no
1344// transition into UNDEFINED, so the replay keeps the layout of every plane and only orders the accesses. Released
1345// here: a colour target after a clear, a depth buffer whose two planes are in different layouts, and an image nothing
1346// has used. The colour target is then taken from UNDEFINED again, cleared and read back. Under
1347// LEONIDA_VK_VALIDATION=1 these barriers must pass the validation layer.
1348int part_l(vktest::Device& d) {
1349 if (!d.depth_format_usable(VK_FORMAT_D32_SFLOAT_S8_UINT)) {
1350 std::printf("L: skipped, no D32_SFLOAT_S8_UINT\n");
1351 return 0;
1352 }
1353 constexpr std::uint32_t size = 4, texels = size * size;
1354 const VkImage rt = d.image(VK_FORMAT_R8G8B8A8_UNORM, size, size, 1, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT);
1355 const VkImage ds = d.image(VK_FORMAT_D32_SFLOAT_S8_UINT, size, size, 1, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT);
1356 const VkImage unused = d.image(VK_FORMAT_R8G8B8A8_UNORM, size, size, 1, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT);
1357 void* mapped = nullptr;
1358 const VkBuffer buffer = d.buffer(texels * 4, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &mapped);
1359 EXPECT(rt && ds && unused && buffer);
1360
1361 const auto binding = [&](VkImage image, VkFormat format, VkImageAspectFlags aspects) {
1362 ResourceBinding b{};
1363 b.image = image;
1364 b.format = format;
1365 b.aspects = aspects;
1366 b.width = b.height = size;
1367 return b;
1368 };
1369 constexpr ResourceId rt_id = 50, ds_id = 51, unused_id = 52;
1370 const std::map<ResourceId, ResourceBinding> bindings{
1371 {rt_id, binding(rt, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_ASPECT_COLOR_BIT)},
1372 {ds_id, binding(ds, VK_FORMAT_D32_SFLOAT_S8_UINT, depth_stencil_aspects)},
1373 {unused_id, binding(unused, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_ASPECT_COLOR_BIT)},
1374 };
1375 const auto resolve = [&](ResourceId id) -> const ResourceBinding* {
1376 const auto it = bindings.find(id);
1377 return it == bindings.end() ? nullptr : &it->second;
1378 };
1379
1380 Views views{d, {}};
1381 ReplayFunctions vk{};
1382 vk.pipeline_barrier = d.fn<PFN_vkCmdPipelineBarrier>("vkCmdPipelineBarrier");
1383 vk.clear_color_image = d.fn<PFN_vkCmdClearColorImage>("vkCmdClearColorImage");
1384 vk.clear_depth_stencil_image = d.fn<PFN_vkCmdClearDepthStencilImage>("vkCmdClearDepthStencilImage");
1385 vk.pipeline_barrier2 = d.fn<PFN_vkCmdPipelineBarrier2>("vkCmdPipelineBarrier2");
1386 vk.begin_rendering = d.fn<PFN_vkCmdBeginRendering>("vkCmdBeginRendering");
1387 vk.end_rendering = d.fn<PFN_vkCmdEndRendering>("vkCmdEndRendering");
1388 vk.clear_attachments = d.fn<PFN_vkCmdClearAttachments>("vkCmdClearAttachments");
1389 vk.image_view = [&](const ResourceBinding& r, const VkImageSubresourceRange& range) { return views(r, range); };
1390 vk.separate_depth_stencil_layouts = true;
1391
1392 LayoutTracker tracker(true);
1393 tracker.track(rt_id, bindings.at(rt_id), VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); // render_target
1394 tracker.track(ds_id, bindings.at(ds_id), VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL); // depth_write
1395 tracker.track(unused_id, bindings.at(unused_id), VK_IMAGE_LAYOUT_UNDEFINED); // never used
1396
1397 namespace y = d3d12_sync;
1398 namespace a = d3d12_access;
1399 namespace l = d3d12_layout;
1400 const BarrierSubresourceRange all{all_subresources, 0, 0, 0, 0, 0};
1401 // What the releases give up: a red target, and a depth buffer with its stencil plane moved to a read-only state.
1402 CommandList written;
1403 EXPECT(written.clear_render_target({rt_id, 0, 0, 1}, {1, 0, 0, 1}));
1404 EXPECT(written.clear_depth_stencil({ds_id, 0, 0, 1}, clear_depth | clear_stencil, 1.0f, 0x11));
1405 EXPECT(written.transition({ds_id, 1, s::depth_write, s::depth_read | s::pixel_shader_resource}));
1406 EXPECT(written.close());
1407 CommandList release;
1408 EXPECT(release.barrier(TextureBarrier{y::render_target, y::none, a::render_target, a::no_access, l::render_target,
1409 l::undefined, rt_id, all, 0}));
1410 EXPECT(release.barrier(TextureBarrier{y::depth_stencil, y::none, a::depth_stencil_write, a::no_access,
1411 l::depth_stencil_write, l::undefined, ds_id, all, 0}));
1412 EXPECT(release.barrier(TextureBarrier{y::render_target, y::none, a::render_target, a::no_access, l::render_target,
1413 l::undefined, unused_id, all, 0}));
1414 EXPECT(release.close());
1415 // D3D12 has the next barrier start from UNDEFINED, which discards; green is written after it.
1416 CommandList reuse;
1417 EXPECT(reuse.barrier(TextureBarrier{y::none, y::render_target, a::no_access, a::render_target, l::undefined,
1418 l::render_target, rt_id, all, 0}));
1419 EXPECT(reuse.clear_render_target({rt_id, 0, 0, 1}, {0, 1, 0, 1}));
1420 EXPECT(reuse.barrier(TextureBarrier{y::render_target, y::copy, a::render_target, a::copy_source, l::render_target,
1421 l::copy_source, rt_id, all, 0}));
1422 EXPECT(reuse.close());
1423
1424 const unsigned errors_before = d.validation_errors();
1425 VkImageLayout before[3]{}, after[3]{};
1426 const auto layouts = [&](VkImageLayout* out) {
1427 out[0] = tracker.layout(rt_id, 0);
1428 out[1] = tracker.layout(ds_id, 0);
1429 out[2] = tracker.layout(ds_id, 1);
1430 };
1431 const bool ok = d.run([&](VkCommandBuffer cb) {
1432 d.initial_layout(cb, rt, VK_IMAGE_ASPECT_COLOR_BIT, 1, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
1433 d.initial_layout(cb, ds, depth_stencil_aspects, 1, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL);
1434 if (replay(written, cb, resolve, vk, &tracker) != ReplayResult::success) return false;
1435 layouts(before);
1436 if (replay(release, cb, resolve, vk, &tracker) != ReplayResult::success) return false;
1437 layouts(after);
1438 if (tracker.layout(unused_id, 0) != VK_IMAGE_LAYOUT_UNDEFINED) return false; // released without a fill
1439 if (replay(reuse, cb, resolve, vk, &tracker) != ReplayResult::success) return false;
1440 d.read_back(cb, rt, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_ASPECT_COLOR_BIT, size, size, 1, buffer, 0);
1441 return true;
1442 });
1443 EXPECT(ok);
1444 // The release changed no layout, and the two depth planes were in different ones.
1445 EXPECT(before[0] == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL && after[0] == before[0]);
1446 EXPECT(before[1] == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL && after[1] == before[1]);
1447 EXPECT(before[2] != before[1] && before[2] != VK_IMAGE_LAYOUT_UNDEFINED && after[2] == before[2]);
1448 EXPECT(tracker.layout(rt_id, 0) == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
1449 const auto* data = static_cast<const std::uint8_t*>(mapped);
1450 for (std::uint32_t i = 0; i < texels; ++i) expect_rgba("L reuse", data, i, green);
1451 const unsigned errors = d.validation_errors() - errors_before;
1452 std::printf("L: a target, a depth buffer in two plane layouts and an unused image released into UNDEFINED; "
1453 "%u texels of the reused target%s\n", texels,
1454 d.validation ? (errors ? ": validation errors" : ", no validation errors") : " (validation off)");
1455 return 0;
1456}
1457
1268} // namespace 1458} // namespace
1269 1459
1270int main() { 1460int main() {
@@ -1276,7 +1466,7 @@ int main() {
1276 } 1466 }
1277 EXPECT(status == vktest::DeviceStatus::ready); 1467 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) || 1468 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)) 1469 part_g(device) || part_h(device) || part_i(device) || part_j(device) || part_k(device) || part_l(device))
1280 return 1; 1470 return 1;
1281 if (g_mismatches) return 1; 1471 if (g_mismatches) return 1;
1282 if (device.validation_errors()) { 1472 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_host_region_import_test.cpp b/runtime/test/vk_host_region_import_test.cpp
new file mode 100644
index 000000000..11239fa9c
--- /dev/null
+++ b/runtime/test/vk_host_region_import_test.cpp
@@ -0,0 +1,355 @@
1// Capability probe for RT-TITLE-HOST-REGION: import one committed host region as a buffer-device-addressable
2// Vulkan buffer with VK_EXT_external_memory_host. The optional argument is the region size in MiB (default 185).
3// A successful import is checked in both directions: GPU reads CPU writes, and GPU writes are visible to the CPU.
4//
5// Exit codes: 0 when the region imported and both directions matched; 77 (the ctest SKIP_RETURN_CODE) when this
6// machine cannot import - the driver reports the usage or the handle type as not importable, refuses the host
7// pointer, has no memory left to commit it, or has no Vulkan device - and 1 when the probe contradicts itself
8// (a coherence mismatch, VK_ERROR_DEVICE_LOST, a driver answer that breaks its own contract, or a validation
9// error). Every 77 prints one "SKIP vk_host_region_import: ..." line that says why. No shaders or game data.
10#include "vk_test_device.h"
11
12#include <windows.h>
13
14#include <cstdint>
15#include <cstdio>
16#include <cstdlib>
17#include <cstring>
18#include <limits>
19#include <vector>
20
21#ifndef VK_EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME
22#define VK_EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME "VK_EXT_external_memory_host"
23#endif
24
25namespace {
26
27constexpr std::uint64_t kMiB = 1ull << 20;
28constexpr VkDeviceSize kSampleBytes = 4096;
29constexpr int kSkip = 77; // the SKIP_RETURN_CODE of runtime/CMakeLists.txt
30// What the title's one arena buffer is used for: the translated draws and dispatches bind it as vertex, index,
31// indirect, uniform and storage memory, and the title computes its GPU pointers from its device address.
32constexpr VkBufferUsageFlags kImportUsage =
33 VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT |
34 VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT |
35 VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT;
36
37struct Region {
38 void* address = nullptr;
39 ~Region() {
40 if (address) VirtualFree(address, 0, MEM_RELEASE);
41 }
42};
43
44struct Imported {
45 vktest::Device& vk;
46 VkBuffer buffer = VK_NULL_HANDLE;
47 VkDeviceMemory memory = VK_NULL_HANDLE;
48 ~Imported() {
49 if (buffer) vk.fn<PFN_vkDestroyBuffer>("vkDestroyBuffer")(vk.device, buffer, nullptr);
50 if (memory) vk.fn<PFN_vkFreeMemory>("vkFreeMemory")(vk.device, memory, nullptr);
51 }
52};
53
54// A VkResult that says this machine cannot do the import, rather than that the import is wrong: the driver has no
55// memory to commit it, or will not import this handle. VK_ERROR_DEVICE_LOST is deliberately not one of them: a
56// lost device is a failure, and a skip would hide it.
57bool capability_refusal(VkResult result) {
58 return result == VK_ERROR_OUT_OF_DEVICE_MEMORY || result == VK_ERROR_OUT_OF_HOST_MEMORY ||
59 result == VK_ERROR_INVALID_EXTERNAL_HANDLE;
60}
61
62// VirtualAlloc refusing the commit because the machine has no room for it, as opposed to failing for any reason.
63bool host_capacity_error(DWORD error) {
64 return error == ERROR_NOT_ENOUGH_MEMORY || error == ERROR_COMMITMENT_LIMIT || error == ERROR_WORKING_SET_QUOTA;
65}
66
67void* allocate_region(std::size_t size, std::size_t alignment, DWORD* error) {
68 *error = 0;
69 SYSTEM_INFO info{};
70 GetSystemInfo(&info);
71 if (alignment <= info.dwAllocationGranularity) {
72 if (void* address = VirtualAlloc(nullptr, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)) return address;
73 *error = GetLastError();
74 return nullptr;
75 }
76
77 MEM_ADDRESS_REQUIREMENTS requirements{};
78 requirements.Alignment = alignment;
79 MEM_EXTENDED_PARAMETER parameter{};
80 parameter.Type = MemExtendedParameterAddressRequirements;
81 parameter.Pointer = &requirements;
82 const auto alloc2 = reinterpret_cast<decltype(&VirtualAlloc2)>(
83 GetProcAddress(GetModuleHandleW(L"kernelbase.dll"), "VirtualAlloc2"));
84 if (!alloc2) return nullptr;
85 void* address =
86 alloc2(GetCurrentProcess(), nullptr, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE, &parameter, 1);
87 if (!address) *error = GetLastError();
88 return address;
89}
90
91int fail(const char* message) {
92 std::fprintf(stderr, "host-region import: %s\n", message);
93 return 1;
94}
95
96// A driver call that failed: 77 with a SKIP line when the machine cannot import, 1 when the probe is at fault.
97// `detail` is printed after the result, and may be empty.
98int result_outcome(std::uint64_t mib, const char* what, VkResult result, const char* detail) {
99 if (!capability_refusal(result)) {
100 std::fprintf(stderr, "host-region import: %s failed (VkResult %d)%s%s\n", what, static_cast<int>(result),
101 *detail ? " " : "", detail);
102 return 1;
103 }
104 std::printf("SKIP vk_host_region_import: size=%llu MiB result=%s vkResult=%d%s%s\n",
105 static_cast<unsigned long long>(mib), what, static_cast<int>(result), *detail ? " " : "", detail);
106 return kSkip;
107}
108
109int run(vktest::Device& vk, std::uint64_t mib) {
110 if (!mib || mib > (std::numeric_limits<std::size_t>::max)() / kMiB) return fail("invalid region size");
111 const auto size = static_cast<VkDeviceSize>(mib * kMiB);
112 const auto alignment = static_cast<std::size_t>(vk.host_pointer_alignment);
113 if (!alignment || (alignment & (alignment - 1))) return fail("invalid imported-host-pointer alignment");
114
115 // What the driver says about this exact usage and handle type before anything is allocated: a buffer it will
116 // not import is a capability result, and the answer also says whether the memory must be dedicated.
117 VkPhysicalDeviceExternalBufferInfo external_info{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_BUFFER_INFO};
118 external_info.usage = kImportUsage;
119 external_info.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT;
120 VkExternalBufferProperties external_properties{VK_STRUCTURE_TYPE_EXTERNAL_BUFFER_PROPERTIES};
121 vk.instance_fn<PFN_vkGetPhysicalDeviceExternalBufferProperties>("vkGetPhysicalDeviceExternalBufferProperties")(
122 vk.physical, &external_info, &external_properties);
123 const VkExternalMemoryProperties& external = external_properties.externalMemoryProperties;
124 if (!(external.compatibleHandleTypes & VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT) ||
125 !(external.externalMemoryFeatures & VK_EXTERNAL_MEMORY_FEATURE_IMPORTABLE_BIT)) {
126 std::printf("SKIP vk_host_region_import: size=%llu MiB result=not-importable handleTypes=0x%x features=0x%x\n",
127 static_cast<unsigned long long>(mib), external.compatibleHandleTypes,
128 external.externalMemoryFeatures);
129 return kSkip;
130 }
131 const bool dedicated_only = (external.externalMemoryFeatures & VK_EXTERNAL_MEMORY_FEATURE_DEDICATED_ONLY_BIT) != 0;
132
133 DWORD allocation_error = 0;
134 Region region;
135 region.address = allocate_region(static_cast<std::size_t>(size), alignment, &allocation_error);
136 if (!region.address) {
137 if (host_capacity_error(allocation_error)) {
138 std::printf("SKIP vk_host_region_import: size=%llu MiB result=host-allocation-refused win32=%lu\n",
139 static_cast<unsigned long long>(mib), static_cast<unsigned long>(allocation_error));
140 return kSkip;
141 }
142 std::fprintf(stderr, "host-region import: VirtualAlloc of %llu bytes at %llu-byte alignment failed (Win32 %lu)\n",
143 static_cast<unsigned long long>(size), static_cast<unsigned long long>(alignment),
144 static_cast<unsigned long>(allocation_error));
145 return 1;
146 }
147 if (reinterpret_cast<std::uintptr_t>(region.address) & (alignment - 1))
148 return fail("host region is not aligned to minImportedHostPointerAlignment");
149
150 Imported imported{vk};
151 VkExternalMemoryBufferCreateInfo external_buffer{VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO};
152 external_buffer.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT;
153 VkBufferCreateInfo buffer_info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, &external_buffer};
154 buffer_info.size = size;
155 buffer_info.usage = kImportUsage;
156 buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
157 VkResult result =
158 vk.fn<PFN_vkCreateBuffer>("vkCreateBuffer")(vk.device, &buffer_info, nullptr, &imported.buffer);
159 if (result != VK_SUCCESS) return result_outcome(mib, "buffer-refused", result, "");
160
161 VkMemoryRequirements requirements{};
162 vk.fn<PFN_vkGetBufferMemoryRequirements>("vkGetBufferMemoryRequirements")(vk.device, imported.buffer,
163 &requirements);
164 if (requirements.size > size) {
165 std::printf("SKIP vk_host_region_import: size=%llu MiB result=requirements-beyond-region requirements=%llu "
166 "bytes\n",
167 static_cast<unsigned long long>(mib), static_cast<unsigned long long>(requirements.size));
168 return kSkip;
169 }
170
171 const auto host_properties = vk.fn<PFN_vkGetMemoryHostPointerPropertiesEXT>("vkGetMemoryHostPointerPropertiesEXT");
172 if (!host_properties) return fail("vkGetMemoryHostPointerPropertiesEXT is not available");
173 VkMemoryHostPointerPropertiesEXT host{VK_STRUCTURE_TYPE_MEMORY_HOST_POINTER_PROPERTIES_EXT};
174 result = host_properties(vk.device, VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT, region.address,
175 &host);
176 if (result != VK_SUCCESS) return result_outcome(mib, "host-pointer-refused", result, "");
177 if (!host.memoryTypeBits) {
178 std::printf("SKIP vk_host_region_import: size=%llu MiB result=no-memory-type memoryTypeBits=0\n",
179 static_cast<unsigned long long>(mib));
180 return kSkip;
181 }
182
183 VkPhysicalDeviceMemoryProperties memory_properties{};
184 vk.instance_fn<PFN_vkGetPhysicalDeviceMemoryProperties>("vkGetPhysicalDeviceMemoryProperties")(vk.physical,
185 &memory_properties);
186 std::uint32_t memory_type = std::numeric_limits<std::uint32_t>::max();
187 for (std::uint32_t i = 0; i < memory_properties.memoryTypeCount; ++i) {
188 if (!(host.memoryTypeBits & requirements.memoryTypeBits & (1u << i))) continue;
189 const auto flags = memory_properties.memoryTypes[i].propertyFlags;
190 if ((flags & (VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) ==
191 (VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) {
192 memory_type = i;
193 break;
194 }
195 }
196 if (memory_type == std::numeric_limits<std::uint32_t>::max()) {
197 std::printf("SKIP vk_host_region_import: size=%llu MiB result=unsupported no host-visible coherent type\n",
198 static_cast<unsigned long long>(mib));
199 return kSkip;
200 }
201
202 // Dedicated only where the driver said so for this handle type (Vulkan requires the binding then).
203 VkMemoryDedicatedAllocateInfo dedicated{VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO};
204 dedicated.buffer = imported.buffer;
205 VkImportMemoryHostPointerInfoEXT host_import{VK_STRUCTURE_TYPE_IMPORT_MEMORY_HOST_POINTER_INFO_EXT};
206 host_import.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT;
207 host_import.pHostPointer = region.address;
208 host_import.pNext = dedicated_only ? &dedicated : nullptr;
209 VkMemoryAllocateFlagsInfo flags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO, &host_import};
210 flags.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT;
211 VkMemoryAllocateInfo allocate{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, &flags};
212 allocate.allocationSize = requirements.size;
213 allocate.memoryTypeIndex = memory_type;
214 result = vk.fn<PFN_vkAllocateMemory>("vkAllocateMemory")(vk.device, &allocate, nullptr, &imported.memory);
215 if (result != VK_SUCCESS) {
216 char detail[192] = {};
217 std::snprintf(detail, sizeof detail,
218 "alignment=%llu requirements=%llu memoryTypeBits=0x%x type=%u dedicated=%s",
219 static_cast<unsigned long long>(requirements.alignment),
220 static_cast<unsigned long long>(requirements.size), host.memoryTypeBits, memory_type,
221 dedicated_only ? "yes" : "no");
222 return result_outcome(mib, "import-refused", result, detail);
223 }
224 result = vk.fn<PFN_vkBindBufferMemory>("vkBindBufferMemory")(vk.device, imported.buffer, imported.memory, 0);
225 if (result != VK_SUCCESS) return result_outcome(mib, "bind-refused", result, "");
226
227 VkBufferDeviceAddressInfo address_info{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO};
228 address_info.buffer = imported.buffer;
229 const auto address = vk.fn<PFN_vkGetBufferDeviceAddress>("vkGetBufferDeviceAddress")(vk.device, &address_info);
230 if (!address) return fail("imported buffer has no device address");
231
232 auto* bytes = static_cast<std::uint8_t*>(region.address);
233 for (VkDeviceSize i = 0; i < kSampleBytes; ++i) {
234 bytes[i] = static_cast<std::uint8_t>(i * 131u + 7u);
235 bytes[size - kSampleBytes + i] = static_cast<std::uint8_t>(i * 197u + 11u);
236 }
237
238 void* readback_map = nullptr;
239 const VkBuffer readback = vk.buffer(2 * kSampleBytes, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &readback_map);
240 if (!readback || !readback_map) return fail("readback buffer creation failed");
241 const auto copy = vk.fn<PFN_vkCmdCopyBuffer>("vkCmdCopyBuffer");
242 const auto pipeline_barrier = vk.fn<PFN_vkCmdPipelineBarrier>("vkCmdPipelineBarrier");
243 const bool copied = vk.run([&](VkCommandBuffer command) {
244 VkBufferCopy regions[2]{};
245 regions[0].srcOffset = 0;
246 regions[0].dstOffset = 0;
247 regions[0].size = kSampleBytes;
248 regions[1].srcOffset = size - kSampleBytes;
249 regions[1].dstOffset = kSampleBytes;
250 regions[1].size = kSampleBytes;
251 copy(command, imported.buffer, readback, 2, regions);
252 // The CPU reads the copy's destination next: its writes are only available to the host after a
253 // transfer -> host barrier (without it, synchronization validation reports the read as a hazard).
254 VkMemoryBarrier to_host{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
255 to_host.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
256 to_host.dstAccessMask = VK_ACCESS_HOST_READ_BIT;
257 pipeline_barrier(command, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0, 1, &to_host, 0,
258 nullptr, 0, nullptr);
259 return true;
260 });
261 if (!copied) return fail("GPU copy from imported memory failed");
262 const auto* readback_bytes = static_cast<const std::uint8_t*>(readback_map);
263 if (std::memcmp(readback_bytes, bytes, kSampleBytes) != 0 ||
264 std::memcmp(readback_bytes + kSampleBytes, bytes + size - kSampleBytes, kSampleBytes) != 0)
265 return fail("GPU did not read the CPU's writes");
266
267 const auto fill = vk.fn<PFN_vkCmdFillBuffer>("vkCmdFillBuffer");
268 const bool filled = vk.run([&](VkCommandBuffer command) {
269 fill(command, imported.buffer, 0, kSampleBytes, 0xa5a5a5a5u);
270 fill(command, imported.buffer, size - kSampleBytes, kSampleBytes, 0x5a5a5a5au);
271 VkMemoryBarrier barrier{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
272 barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
273 barrier.dstAccessMask = VK_ACCESS_HOST_READ_BIT;
274 pipeline_barrier(command, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0, 1, &barrier, 0,
275 nullptr, 0, nullptr);
276 return true;
277 });
278 if (!filled) return fail("GPU fill of imported memory failed");
279 for (VkDeviceSize i = 0; i < kSampleBytes; ++i) {
280 if (bytes[i] != 0xa5 || bytes[size - kSampleBytes + i] != 0x5a)
281 return fail("CPU did not see the GPU's writes");
282 }
283
284 std::printf("host-region import: size=%llu MiB result=imported alignment=%llu requirements=%llu "
285 "memoryTypeBits=0x%x type=%u dedicated=%s bda=0x%llx handleTypes=0x%x import-features=0x%x "
286 "cpu-gpu-coherence=ok\n",
287 static_cast<unsigned long long>(mib), static_cast<unsigned long long>(requirements.alignment),
288 static_cast<unsigned long long>(requirements.size), host.memoryTypeBits, memory_type,
289 dedicated_only ? "yes" : "no", static_cast<unsigned long long>(address),
290 external.compatibleHandleTypes, external.externalMemoryFeatures);
291 return 0;
292}
293
294// True when LEONIDA_VK_VALIDATION asks for the Khronos layer and it is not installed. vk_test_device.h then fails
295// the device, which is right for a test that asked for validation by hand; this probe's CTest variant runs on
296// every machine, so it reports a missing layer as a skip instead of a failure.
297bool validation_layer_missing() {
298#ifdef _MSC_VER
299#pragma warning(push)
300#pragma warning(disable : 4996) // getenv: read once, as vk_test_device.h does
301#endif
302 const char* env = std::getenv("LEONIDA_VK_VALIDATION");
303#ifdef _MSC_VER
304#pragma warning(pop)
305#endif
306 if (!env || std::strcmp(env, "0") == 0) return false;
307 const auto instance_proc = load_vulkan();
308 if (!instance_proc) return false; // initialize() reports the missing loader as unavailable
309 const auto enumerate = reinterpret_cast<PFN_vkEnumerateInstanceLayerProperties>(
310 instance_proc(nullptr, "vkEnumerateInstanceLayerProperties"));
311 if (!enumerate) return false;
312 std::vector<VkLayerProperties> layers;
313 if (vktest::enumerate_all(layers, enumerate) != VK_SUCCESS) return false;
314 for (const auto& layer : layers)
315 if (std::strcmp(layer.layerName, "VK_LAYER_KHRONOS_validation") == 0) return false;
316 return true;
317}
318
319} // namespace
320
321int main(int argc, char** argv) {
322 if (validation_layer_missing()) {
323 std::printf("SKIP vk_host_region_import: LEONIDA_VK_VALIDATION is set but VK_LAYER_KHRONOS_validation is not "
324 "installed\n");
325 return kSkip;
326 }
327 std::uint64_t mib = 185;
328 if (argc > 1) {
329 char* end = nullptr;
330 mib = std::strtoull(argv[1], &end, 10);
331 if (!end || *end) {
332 std::fprintf(stderr, "usage: vk_host_region_import_test [MiB]\n");
333 return 1;
334 }
335 }
336 vktest::Device vk;
337 vk.request_buffer_device_address = true;
338 const auto status = vk.initialize();
339 if (status == vktest::DeviceStatus::unavailable) {
340 std::printf("SKIP vk_host_region_import: no Vulkan 1.3 device\n");
341 return kSkip;
342 }
343 if (status != vktest::DeviceStatus::ready) return 1;
344 if (!vk.host_pointer_alignment || !vk.buffer_device_address) {
345 std::printf("SKIP vk_host_region_import: VK_EXT_external_memory_host or bufferDeviceAddress is not "
346 "available\n");
347 return kSkip;
348 }
349 const int result = run(vk, mib);
350 if (vk.validation_errors()) {
351 std::fprintf(stderr, "%u validation errors\n", vk.validation_errors());
352 return 1;
353 }
354 return result;
355}
diff --git a/runtime/test/vk_pipeline_check.cpp b/runtime/test/vk_pipeline_check.cpp
index 7b4f8d533..a237f60ff 100644
--- a/runtime/test/vk_pipeline_check.cpp
+++ b/runtime/test/vk_pipeline_check.cpp
@@ -7,8 +7,10 @@
7// descriptor-free shaders with the standard push-constant range 7// descriptor-free shaders with the standard push-constant range
8// - ps/vs/ms/gs: graphics pipeline via vkCreateGraphicsPipelines (Vulkan 1.3 dynamic rendering, no render pass) 8// - ps/vs/ms/gs: graphics pipeline via vkCreateGraphicsPipelines (Vulkan 1.3 dynamic rendering, no render pass)
9// paired with minimal partner stubs from <spirv dir>/stubs/ (generated by tools/spirv_stubs.py) 9// paired with minimal partner stubs from <spirv dir>/stubs/ (generated by tools/spirv_stubs.py)
10// Only optional device extensions needed by the selected shaders (and supported by the GPU) are enabled. Shaders 10// VK_EXT_mesh_shader (with meshShaderQueries) and VK_KHR_maintenance8 are always enabled when supported so the
11// whose required features or partner stubs are unavailable are reported as skipped rather than failed. 11// saved pipeline cache matches the runtime's device key; other optional device extensions are enabled only when
12// needed by the selected shaders. Shaders whose required features or partner stubs are unavailable are reported as
13// skipped rather than failed.
12// [cache.bin] loaded first if it exists (a stopped run resumes: cached pipelines are instant), saved every 14// [cache.bin] loaded first if it exists (a stopped run resumes: cached pipelines are instant), saved every
13// 10 minutes and at the end 15// 10 minutes and at the end
14// --jobs N compile on up to N worker threads (default: half the hardware threads) 16// --jobs N compile on up to N worker threads (default: half the hardware threads)
@@ -1058,14 +1060,13 @@ int main(int argc, char** argv) {
1058 return failed ? 1 : 0; 1060 return failed ? 1 : 0;
1059 } 1061 }
1060 1062
1061 // Scan selected shaders to request only the optional extensions they actually use. 1063 // Scan selected shaders to request the optional shader extensions they use. VK_EXT_mesh_shader and
1062 bool want_mesh = false, want_bary = false, want_lock = false, want_m8 = false, want_fma = false, want_clock = false; 1064 // VK_KHR_maintenance8 are always enabled when supported (even for compute-only runs), because
1065 // create_vulkan_device_standalone enables both unconditionally and NVIDIA includes them in its cache key.
1066 bool want_bary = false, want_lock = false, want_fma = false, want_clock = false;
1063 for (auto& [_, meta] : work) { 1067 for (auto& [_, meta] : work) {
1064 if (meta->stage == "ms") want_mesh = true;
1065 if (meta->needs_maintenance8) want_m8 = true;
1066 for (const auto& feat : meta->features) { 1068 for (const auto& feat : meta->features) {
1067 if (feat == "meshShader") want_mesh = true; 1069 if (feat == "fragmentShaderBarycentric") want_bary = true;
1068 else if (feat == "fragmentShaderBarycentric") want_bary = true;
1069 else if (feat == "fragmentShaderPixelInterlock") want_lock = true; 1070 else if (feat == "fragmentShaderPixelInterlock") want_lock = true;
1070 else if (feat == "shaderFmaFloat32" || feat == "shaderFmaFloat64") want_fma = true; // OpFmaKHR (--fma khr) 1071 else if (feat == "shaderFmaFloat32" || feat == "shaderFmaFloat64") want_fma = true; // OpFmaKHR (--fma khr)
1071 else if (feat == "shaderSubgroupClock" || feat == "shaderDeviceClock") want_clock = true; 1072 else if (feat == "shaderSubgroupClock" || feat == "shaderDeviceClock") want_clock = true;
@@ -1137,13 +1138,11 @@ int main(int argc, char** argv) {
1137 link(&f11, reinterpret_cast<VkBaseOutStructure*>(&f11), nullptr, true); // shaderDrawParameters (VS v0/v3) 1138 link(&f11, reinterpret_cast<VkBaseOutStructure*>(&f11), nullptr, true); // shaderDrawParameters (VS v0/v3)
1138 link(&f12, reinterpret_cast<VkBaseOutStructure*>(&f12), nullptr, true); 1139 link(&f12, reinterpret_cast<VkBaseOutStructure*>(&f12), nullptr, true);
1139 link(&f13, reinterpret_cast<VkBaseOutStructure*>(&f13), nullptr, true); 1140 link(&f13, reinterpret_cast<VkBaseOutStructure*>(&f13), nullptr, true);
1140 const bool ext_mesh = link(&mesh, reinterpret_cast<VkBaseOutStructure*>(&mesh), VK_EXT_MESH_SHADER_EXTENSION_NAME, want_mesh); 1141 const bool ext_mesh = link(&mesh, reinterpret_cast<VkBaseOutStructure*>(&mesh), VK_EXT_MESH_SHADER_EXTENSION_NAME, true);
1141 const bool ext_bary = link(&bary, reinterpret_cast<VkBaseOutStructure*>(&bary), VK_KHR_FRAGMENT_SHADER_BARYCENTRIC_EXTENSION_NAME, want_bary); 1142 const bool ext_bary = link(&bary, reinterpret_cast<VkBaseOutStructure*>(&bary), VK_KHR_FRAGMENT_SHADER_BARYCENTRIC_EXTENSION_NAME, want_bary);
1142 const bool ext_lock = link(&lock, reinterpret_cast<VkBaseOutStructure*>(&lock), VK_EXT_FRAGMENT_SHADER_INTERLOCK_EXTENSION_NAME, want_lock); 1143 const bool ext_lock = link(&lock, reinterpret_cast<VkBaseOutStructure*>(&lock), VK_EXT_FRAGMENT_SHADER_INTERLOCK_EXTENSION_NAME, want_lock);
1143#ifdef VK_KHR_MAINTENANCE_8_EXTENSION_NAME 1144#ifdef VK_KHR_MAINTENANCE_8_EXTENSION_NAME
1144 const bool ext_m8 = link(&m8, reinterpret_cast<VkBaseOutStructure*>(&m8), VK_KHR_MAINTENANCE_8_EXTENSION_NAME, want_m8); 1145 const bool ext_m8 = link(&m8, reinterpret_cast<VkBaseOutStructure*>(&m8), VK_KHR_MAINTENANCE_8_EXTENSION_NAME, true);
1145#else
1146 (void)want_m8;
1147#endif 1146#endif
1148#ifdef VK_KHR_SHADER_FMA_EXTENSION_NAME 1147#ifdef VK_KHR_SHADER_FMA_EXTENSION_NAME
1149 VkPhysicalDeviceShaderFmaFeaturesKHR fma{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_FMA_FEATURES_KHR}; 1148 VkPhysicalDeviceShaderFmaFeaturesKHR fma{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_FMA_FEATURES_KHR};
@@ -1172,6 +1171,12 @@ int main(int argc, char** argv) {
1172 VkPhysicalDeviceFeatures2 f2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2}; 1171 VkPhysicalDeviceFeatures2 f2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2};
1173 f2.pNext = chain; 1172 f2.pNext = chain;
1174 vkGetPhysicalDeviceFeatures2(pd, &f2); // fills every linked struct with what's supported 1173 vkGetPhysicalDeviceFeatures2(pd, &f2); // fills every linked struct with what's supported
1174 // The runtime's device (create_vulkan_device_standalone) never enables these three, and a driver makes them part
1175 // of a pipeline's cache key: with any of them on here, the cache this tool saves does not hit in gta6rt
1176 // (pipeline_cache_seed_test; docs/pipeline_check.md, "The cache and the runtime's device").
1177 f2.features.robustBufferAccess = VK_FALSE;
1178 f12.scalarBlockLayout = VK_FALSE;
1179 f13.robustImageAccess = VK_FALSE;
1175 VkPhysicalDeviceMeshShaderPropertiesEXT mesh_props{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_PROPERTIES_EXT}; 1180 VkPhysicalDeviceMeshShaderPropertiesEXT mesh_props{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_PROPERTIES_EXT};
1176 if (ext_mesh && mesh.meshShader) { 1181 if (ext_mesh && mesh.meshShader) {
1177 VkPhysicalDeviceProperties2 mesh_device_props{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2}; 1182 VkPhysicalDeviceProperties2 mesh_device_props{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2};
@@ -1179,7 +1184,10 @@ int main(int argc, char** argv) {
1179 vkGetPhysicalDeviceProperties2(pd, &mesh_device_props); 1184 vkGetPhysicalDeviceProperties2(pd, &mesh_device_props);
1180 } 1185 }
1181 if (ext_mesh) { 1186 if (ext_mesh) {
1182 mesh.multiviewMeshShader = mesh.primitiveFragmentShadingRateMeshShader = mesh.meshShaderQueries = VK_FALSE; 1187 // Keep meshShaderQueries as supported: create_vulkan_device_standalone enables it when present (#577),
1188 // and NVIDIA hashes it into the pipeline cache key even for compute pipelines.
1189 if (!f2.features.pipelineStatisticsQuery) mesh.meshShaderQueries = VK_FALSE;
1190 mesh.multiviewMeshShader = mesh.primitiveFragmentShadingRateMeshShader = VK_FALSE;
1183 mesh.taskShader = VK_FALSE; 1191 mesh.taskShader = VK_FALSE;
1184 } 1192 }
1185 float prio = 1; 1193 float prio = 1;
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..0e5befcdc 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,11 +120,13 @@ 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;
124 bool custom_border_color = false; // VK_EXT_custom_border_color and customBorderColors enabled 127 bool custom_border_color = false; // VK_EXT_custom_border_color and customBorderColors enabled
125 bool custom_border_color_without_format = false; 128 bool custom_border_color_without_format = false;
129 bool shader_output_viewport_index = false; // Vulkan 1.2 shaderOutputViewportIndex enabled
126 // VK_EXT_external_memory_host is enabled when non-zero: its minImportedHostPointerAlignment. 130 // VK_EXT_external_memory_host is enabled when non-zero: its minImportedHostPointerAlignment.
127 VkDeviceSize host_pointer_alignment = 0; 131 VkDeviceSize host_pointer_alignment = 0;
128 132
@@ -398,6 +402,8 @@ public:
398 enable12.descriptorBindingPartiallyBound = partially_bound; 402 enable12.descriptorBindingPartiallyBound = partially_bound;
399 sampler_filter_minmax = features12.samplerFilterMinmax == VK_TRUE; 403 sampler_filter_minmax = features12.samplerFilterMinmax == VK_TRUE;
400 enable12.samplerFilterMinmax = sampler_filter_minmax; 404 enable12.samplerFilterMinmax = sampler_filter_minmax;
405 shader_output_viewport_index = features12.shaderOutputViewportIndex == VK_TRUE;
406 enable12.shaderOutputViewportIndex = shader_output_viewport_index;
401 enable12.bufferDeviceAddress = VK_TRUE; 407 enable12.bufferDeviceAddress = VK_TRUE;
402 408
403 const std::uint32_t graphics_count = std::max(1u, std::min(queue_count_wanted, family_queue_count)); 409 const std::uint32_t graphics_count = std::max(1u, std::min(queue_count_wanted, family_queue_count));
@@ -433,6 +439,7 @@ public:
433 enable.shaderSampledImageArrayDynamicIndexing = bindless; 439 enable.shaderSampledImageArrayDynamicIndexing = bindless;
434 enable.shaderStorageImageArrayDynamicIndexing = bindless; 440 enable.shaderStorageImageArrayDynamicIndexing = bindless;
435 enable.logicOp = features.features.logicOp; // d3d12_draw_test's logic-op draw, where available 441 enable.logicOp = features.features.logicOp; // d3d12_draw_test's logic-op draw, where available
442 enable.multiViewport = features.features.multiViewport; // d3d12_multi_viewport_test, where available
436 enable.geometryShader = features.features.geometryShader; // d3d12_geometry_test, where available 443 enable.geometryShader = features.features.geometryShader; // d3d12_geometry_test, where available
437 enable.shaderInt64 = features.features.shaderInt64; // translated shaders declare Int64 for their addresses 444 enable.shaderInt64 = features.features.shaderInt64; // translated shaders declare Int64 for their addresses
438 const char* conditional_extension = VK_EXT_CONDITIONAL_RENDERING_EXTENSION_NAME; 445 const char* conditional_extension = VK_EXT_CONDITIONAL_RENDERING_EXTENSION_NAME;
@@ -523,10 +530,13 @@ public:
523 VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &mesh_features}; 530 VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &mesh_features};
524 instance_fn<PFN_vkGetPhysicalDeviceFeatures2>("vkGetPhysicalDeviceFeatures2")(physical, &query); 531 instance_fn<PFN_vkGetPhysicalDeviceFeatures2>("vkGetPhysicalDeviceFeatures2")(physical, &query);
525 mesh_shader = mesh_features.meshShader == VK_TRUE; 532 mesh_shader = mesh_features.meshShader == VK_TRUE;
533 mesh_shader_queries = mesh_features.meshShaderQueries == VK_TRUE;
526 } 534 }
527 if (mesh_shader) { 535 if (mesh_shader) {
528 mesh_features = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT, *v13_.next()}; 536 mesh_features = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT, *v13_.next()};
529 mesh_features.meshShader = VK_TRUE; 537 mesh_features.meshShader = VK_TRUE;
538 // The mesh-primitives query, which counts the primitives a mesh shader emits (D3D-MESH-CLIPPING-COUNTER).
539 mesh_features.meshShaderQueries = mesh_shader_queries ? VK_TRUE : VK_FALSE;
530 *v13_.next() = &mesh_features; 540 *v13_.next() = &mesh_features;
531 } 541 }
532 enable.occlusionQueryPrecise = features.features.occlusionQueryPrecise; // query heaps, where available 542 enable.occlusionQueryPrecise = features.features.occlusionQueryPrecise; // query heaps, where available
@@ -567,6 +577,11 @@ public:
567 enabled = enable; 577 enabled = enable;
568 std::vector<const char*> device_extensions; 578 std::vector<const char*> device_extensions;
569 v13_.add_extensions(device_extensions); 579 v13_.add_extensions(device_extensions);
580 depth_range_unrestricted = request_depth_range_unrestricted &&
581 std::any_of(extensions.begin(), extensions.end(), [](const auto& e) {
582 return std::strcmp(e.extensionName, VK_EXT_DEPTH_RANGE_UNRESTRICTED_EXTENSION_NAME) == 0;
583 });
584 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) { 585 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; 586 return std::strcmp(e.extensionName, VK_EXT_CONSERVATIVE_RASTERIZATION_EXTENSION_NAME) == 0;
572 }); 587 });
diff --git a/runtime/test/vk_xdxr_postbuild_readback_test.cpp b/runtime/test/vk_xdxr_postbuild_readback_test.cpp
new file mode 100644
index 000000000..0ab5893a6
--- /dev/null
+++ b/runtime/test/vk_xdxr_postbuild_readback_test.cpp
@@ -0,0 +1,177 @@
1// Real Vulkan GPU regression test: XDXR AccelerationStructurePostbuild writes compacted/current
2// acceleration-structure sizes from a compute shader into dest_va (commonly a host-readable READBACK buffer).
3// VulkanQueue::execute_now() must emit a COMPUTE_SHADER_BIT -> HOST_BIT visibility barrier for the batch,
4// and the host readback must observe the exact GPU-computed BLAS size.
5// Exit 77 when there is no Vulkan device with bufferDeviceAddress.
6#include "vk_test_device.h"
7#include "../src/vulkan_backend.h"
8
9#include <atomic>
10#include <cstdint>
11#include <cstdio>
12#include <cstring>
13
14#define EXPECT(condition) do { \
15 if (!(condition)) { std::fprintf(stderr, "FAIL line %d: %s\n", __LINE__, #condition); return 1; } \
16} while (0)
17
18namespace {
19
20PFN_vkGetDeviceProcAddr g_real_get_device_proc_addr = nullptr;
21PFN_vkCmdPipelineBarrier2 g_real_barrier2 = nullptr;
22PFN_vkCmdPipelineBarrier g_real_barrier = nullptr;
23std::atomic<std::uint32_t> g_compute_to_host_barriers{0};
24
25void VKAPI_PTR hooked_barrier2(VkCommandBuffer cb, const VkDependencyInfo* dep) {
26 if (dep) {
27 for (std::uint32_t i = 0; i < dep->memoryBarrierCount; ++i) {
28 const VkMemoryBarrier2& mb = dep->pMemoryBarriers[i];
29 const bool src_compute = (mb.srcStageMask & VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT) != 0;
30 const bool src_write =
31 (mb.srcAccessMask & (VK_ACCESS_2_MEMORY_WRITE_BIT | VK_ACCESS_2_SHADER_WRITE_BIT)) != 0;
32 const bool dst_host = (mb.dstStageMask & VK_PIPELINE_STAGE_2_HOST_BIT) != 0 &&
33 (mb.dstAccessMask & VK_ACCESS_2_HOST_READ_BIT) != 0;
34 if (src_compute && src_write && dst_host) ++g_compute_to_host_barriers;
35 }
36 }
37 g_real_barrier2(cb, dep);
38}
39
40void VKAPI_PTR hooked_barrier(VkCommandBuffer cb, VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
41 VkDependencyFlags dependencyFlags, std::uint32_t memoryBarrierCount,
42 const VkMemoryBarrier* pMemoryBarriers, std::uint32_t bufferMemoryBarrierCount,
43 const VkBufferMemoryBarrier* pBufferMemoryBarriers, std::uint32_t imageMemoryBarrierCount,
44 const VkImageMemoryBarrier* pImageMemoryBarriers) {
45 const bool src_ok =
46 (srcStageMask & (VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | VK_PIPELINE_STAGE_ALL_COMMANDS_BIT)) != 0;
47 const bool dst_ok = (dstStageMask & VK_PIPELINE_STAGE_HOST_BIT) != 0;
48 if (src_ok && dst_ok) {
49 for (std::uint32_t i = 0; i < memoryBarrierCount; ++i) {
50 const VkMemoryBarrier& mb = pMemoryBarriers[i];
51 const bool src_write = (mb.srcAccessMask & (VK_ACCESS_MEMORY_WRITE_BIT | VK_ACCESS_SHADER_WRITE_BIT)) != 0;
52 const bool dst_read = (mb.dstAccessMask & VK_ACCESS_HOST_READ_BIT) != 0;
53 if (src_write && dst_read) ++g_compute_to_host_barriers;
54 }
55 }
56 g_real_barrier(cb, srcStageMask, dstStageMask, dependencyFlags, memoryBarrierCount, pMemoryBarriers,
57 bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers);
58}
59
60PFN_vkVoidFunction VKAPI_PTR wrapped_get_device_proc_addr(VkDevice device, const char* name) {
61 PFN_vkVoidFunction fn = g_real_get_device_proc_addr(device, name);
62 if (!fn || !name) return fn;
63 if (std::strcmp(name, "vkCmdPipelineBarrier2") == 0) {
64 g_real_barrier2 = reinterpret_cast<PFN_vkCmdPipelineBarrier2>(fn);
65 return reinterpret_cast<PFN_vkVoidFunction>(hooked_barrier2);
66 }
67 if (std::strcmp(name, "vkCmdPipelineBarrier") == 0) {
68 g_real_barrier = reinterpret_cast<PFN_vkCmdPipelineBarrier>(fn);
69 return reinterpret_cast<PFN_vkVoidFunction>(hooked_barrier);
70 }
71 return fn;
72}
73
74} // namespace
75
76int main() {
77 using namespace leonida;
78
79 vktest::Device gpu;
80 gpu.request_buffer_device_address = true;
81 if (!gpu.create() || !gpu.buffer_device_address) {
82 std::printf("vk_xdxr_postbuild_readback: skipped (no Vulkan device with bufferDeviceAddress)\n");
83 return 77;
84 }
85
86 g_real_get_device_proc_addr = gpu.device_proc;
87 VulkanContext ctx(wrapped_get_device_proc_addr, gpu.device, /*separate_depth_stencil_layouts=*/false,
88 /*conditional_rendering=*/false, /*ray_tracing=*/false, /*xdxr=*/true);
89 EXPECT(ctx.loaded());
90
91 VulkanQueue queue(ctx, gpu.queue, gpu.family);
92 EXPECT(queue.ok());
93
94 // Build a minimal 1-triangle XDXR BLAS on the real GPU.
95 void* vtx_map = nullptr;
96 const VkBuffer vtx_buf = gpu.buffer(256, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, &vtx_map);
97 EXPECT(vtx_buf && vtx_map);
98 const float tri[9] = {0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f};
99 std::memcpy(vtx_map, tri, sizeof(tri));
100 const std::uint64_t vtx_va = gpu.device_address(vtx_buf);
101
102 XdxrLayout layout;
103 EXPECT(layout.compute(1, /*is_tlas=*/false, /*box16=*/false));
104 void* blas_map = nullptr;
105 const VkBuffer blas_buf = gpu.buffer(layout.size + 512, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, &blas_map);
106 void* scratch_map = nullptr;
107 const VkBuffer scratch_buf =
108 gpu.buffer(std::size_t(layout.scratch) + 512, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, &scratch_map);
109 void* postbuild_map = nullptr;
110 const VkBuffer postbuild_buf = gpu.buffer(256, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, &postbuild_map);
111 EXPECT(blas_buf && blas_map && scratch_buf && scratch_map && postbuild_buf && postbuild_map);
112
113 const std::uint64_t blas_raw_va = gpu.device_address(blas_buf);
114 const std::uint64_t blas_va = (blas_raw_va + 255ull) & ~255ull;
115 const std::uint64_t scratch_va = (gpu.device_address(scratch_buf) + 255ull) & ~255ull;
116 const std::uint64_t postbuild_va = (gpu.device_address(postbuild_buf) + 7ull) & ~7ull;
117 const std::size_t postbuild_off = std::size_t(postbuild_va - gpu.device_address(postbuild_buf));
118
119 // Poison the postbuild readback buffer so we verify real GPU writeback.
120 constexpr std::uint64_t poison = 0xDEADBEEFCAFEBABEull;
121 std::memcpy(static_cast<char*>(postbuild_map) + postbuild_off, &poison, sizeof(poison));
122
123 // Register the host-readable postbuild buffer in VulkanContext so prepare() resolves dest_va via buffer_at.
124 ResourceBinding rb{};
125 rb.buffer = postbuild_buf;
126 rb.size = 256;
127 rb.va = gpu.device_address(postbuild_buf);
128 rb.host_readable = true;
129 ctx.add_resource(1, rb);
130
131 // Step 1: Build the BLAS on the real GPU.
132 BuildAccelerationStructure build{};
133 build.is_tlas = false;
134 build.dst_va = blas_va;
135 build.scratch_va = scratch_va;
136 RtTriangleGeometry geom{};
137 geom.vertex_va = vtx_va;
138 geom.vertex_count = 3;
139 geom.vertex_stride = 12;
140 geom.vertex_format = VK_FORMAT_R32G32B32_SFLOAT;
141 geom.opaque = true;
142 geom.flags = 1;
143 build.triangles.push_back(geom);
144
145 CommandList build_list;
146 EXPECT(build_list.build_acceleration_structure(build) && build_list.close());
147 const CommandList* build_ptrs[1] = {&build_list};
148 EXPECT(queue.execute(build_ptrs) == ReplayResult::success);
149 EXPECT(queue.idle());
150
151 // Step 2: Execute a command list containing ONLY XDXR AccelerationStructurePostbuild into the READBACK buffer.
152 g_compute_to_host_barriers.store(0);
153 CommandList postbuild_list;
154 EXPECT(postbuild_list.acceleration_structure_postbuild({postbuild_va, /*type=*/0, {blas_va}}) &&
155 postbuild_list.close());
156 const CommandList* postbuild_ptrs[1] = {&postbuild_list};
157 EXPECT(queue.execute(postbuild_ptrs) == ReplayResult::success);
158 EXPECT(queue.idle());
159
160 const std::uint32_t barriers = g_compute_to_host_barriers.load();
161 std::uint64_t reported_size = 0;
162 std::memcpy(&reported_size, static_cast<const char*>(postbuild_map) + postbuild_off, sizeof(reported_size));
163
164 std::uint32_t header_units = 0;
165 std::memcpy(&header_units, static_cast<const char*>(blas_map) + (blas_va - blas_raw_va) + 4, sizeof(header_units));
166 const std::uint64_t expected_size = (std::uint64_t(header_units) + 1ull) * 64ull;
167
168 EXPECT(barriers >= 1);
169 EXPECT(reported_size != poison);
170 EXPECT(reported_size > 0 && reported_size <= layout.size);
171 EXPECT(reported_size == expected_size);
172
173 std::printf("vk_xdxr_postbuild_readback: PASS (compute_to_host_barriers=%u, reported_size=%llu, expected=%llu)\n",
174 barriers, static_cast<unsigned long long>(reported_size),
175 static_cast<unsigned long long>(expected_size));
176 return 0;
177}
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_gamesave_test.cpp b/runtime/test/xgameruntime_gamesave_test.cpp
index d2d7f45eb..b53461944 100644
--- a/runtime/test/xgameruntime_gamesave_test.cpp
+++ b/runtime/test/xgameruntime_gamesave_test.cpp
@@ -10,6 +10,7 @@
10#include <ctime> 10#include <ctime>
11#include <filesystem> 11#include <filesystem>
12#include <fstream> 12#include <fstream>
13#include <iterator>
13#include <string> 14#include <string>
14#include <vector> 15#include <vector>
15 16
@@ -362,6 +363,94 @@ int main() {
362 std::filesystem::remove_all(root / L"local-user" / L"second", ec); 363 std::filesystem::remove_all(root / L"local-user" / L"second", ec);
363 } 364 }
364 365
366 // ---- a failed commit leaves the container as it was ----
367 // Another process holds blob "b" open without FILE_SHARE_DELETE, so replacing it fails in the middle of the
368 // update, after "a" was already replaced. The update must fail, undo what it already did, and leave no temporary
369 // or backup files. Closing the handle makes the same update succeed.
370 {
371 const HRESULT out_of_local = static_cast<HRESULT>(0x80830003); // E_GS_OUT_OF_LOCAL_STORAGE
372 struct Edit {
373 const char* name;
374 const char* data; // nullptr: delete
375 };
376 auto submit = [&](Handle container, std::vector<Edit> edits) -> HRESULT {
377 Handle u = nullptr;
378 HRESULT hr = at<Create>(save, 23)(save, container, nullptr, &u);
379 for (const Edit& e : edits) {
380 if (FAILED(hr)) break;
381 hr = e.data ? at<Write>(save, 25)(save, u, e.name, reinterpret_cast<const uint8_t*>(e.data),
382 std::strlen(e.data))
383 : at<ByName>(save, 26)(save, u, e.name);
384 }
385 if (SUCCEEDED(hr)) hr = at<Submit>(save, 27)(save, u);
386 at<Close>(save, 24)(save, u);
387 return hr;
388 };
389 auto read_blob = [&](const std::filesystem::path& dir, const wchar_t* file) {
390 std::ifstream f(dir / file, std::ios::binary);
391 return std::string((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
392 };
393 auto file_count = [](const std::filesystem::path& dir) {
394 std::error_code count_ec;
395 int n = 0;
396 for (const auto& e : std::filesystem::directory_iterator(dir, count_ec)) {
397 (void)e;
398 ++n;
399 }
400 return n;
401 };
402
403 Handle rc = nullptr;
404 check(at<Create>(save, 16)(save, provider, "rollback", &rc) == S_OK && rc, "CreateContainer for the rollback checks");
405 const std::filesystem::path rollback_dir = root / L"local-user" / L"rollback";
406
407 // Case A: a write whose rename is blocked after an earlier write was applied.
408 check(submit(rc, {{"a", "OLD_A"}, {"b", "OLD_B"}}) == S_OK, "seed blobs a and b");
409 HANDLE hold = CreateFileW((rollback_dir / L"b").c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
410 OPEN_EXISTING, 0, nullptr);
411 check(hold != INVALID_HANDLE_VALUE, "another handle holds blob b open");
412 check(submit(rc, {{"a", "NEW_A"}, {"b", "NEW_B"}}) == out_of_local, "an update whose rename of b is blocked fails");
413 check(read_blob(rollback_dir, L"a") == "OLD_A" && read_blob(rollback_dir, L"b") == "OLD_B",
414 "a failed update leaves a and b with their old contents");
415 check(file_count(rollback_dir) == 2, "a failed update leaves no temporary or backup files");
416 CloseHandle(hold);
417 check(submit(rc, {{"a", "NEW_A"}, {"b", "NEW_B"}}) == S_OK, "the same update succeeds once b is free");
418 check(read_blob(rollback_dir, L"a") == "NEW_A" && read_blob(rollback_dir, L"b") == "NEW_B" && file_count(rollback_dir) == 2,
419 "the successful update leaves only the new contents");
420
421 // Case B: a delete that sorts before a blocked write must not be applied.
422 check(submit(rc, {{"a", "OLD_A"}, {"b", "OLD_B"}}) == S_OK, "reseed blobs a and b");
423 hold = CreateFileW((rollback_dir / L"b").c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING,
424 0, nullptr);
425 check(hold != INVALID_HANDLE_VALUE, "another handle holds blob b open again");
426 check(submit(rc, {{"a", nullptr}, {"b", "NEW_B"}}) == out_of_local, "a mixed update with a blocked write fails");
427 check(std::filesystem::exists(rollback_dir / L"a") && read_blob(rollback_dir, L"a") == "OLD_A" && read_blob(rollback_dir, L"b") == "OLD_B",
428 "the delete of a is not applied when the write of b fails");
429 check(file_count(rollback_dir) == 2, "the mixed failed update leaves no temporary or backup files");
430 CloseHandle(hold);
431
432 // Case C: the plain success path, a write and a delete.
433 check(submit(rc, {{"a", "FINAL_A"}, {"b", nullptr}}) == S_OK, "a write and a delete succeed together");
434 check(read_blob(rollback_dir, L"a") == "FINAL_A" && !std::filesystem::exists(rollback_dir / L"b") && file_count(rollback_dir) == 1,
435 "the successful write and delete leave only the written blob");
436
437 // Case D: scratch files of a commit that died midway. A temporary is dropped; a backup may be the only copy of
438 // a blob's old contents, so neither an update of another blob nor a failed update of two rollback_dir removes it.
439 std::ofstream(rollback_dir / L"b~", std::ios::binary) << "HALF_B";
440 std::ofstream(rollback_dir / L"b~b~", std::ios::binary) << "KEPT_B";
441 check(submit(rc, {{"a", "NEXT_A"}}) == S_OK, "an update of a with scratch files of b present");
442 check(!std::filesystem::exists(rollback_dir / L"b~") && read_blob(rollback_dir, L"b~b~") == "KEPT_B",
443 "a stale temporary is removed and a kept backup is not");
444 hold = CreateFileW((rollback_dir / L"a").c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING,
445 0, nullptr);
446 check(hold != INVALID_HANDLE_VALUE, "another handle holds blob a open");
447 check(submit(rc, {{"a", "X"}, {"b", "Y"}}) == out_of_local, "an update that fails at a, before b is reached");
448 CloseHandle(hold);
449 check(read_blob(rollback_dir, L"b~b~") == "KEPT_B", "the failed update keeps the backup it did not write");
450
451 at<Close>(save, 17)(save, rc);
452 }
453
365 at<Close>(save, 6)(save, provider); 454 at<Close>(save, 6)(save, provider);
366 at<Close>(save, 6)(save, provider2); 455 at<Close>(save, 6)(save, provider2);
367 at<Close>(save, 6)(save, provider); // twice: ignored 456 at<Close>(save, 6)(save, provider); // twice: ignored
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/xgameruntime_test.cpp b/runtime/test/xgameruntime_test.cpp
index af67045d4..8c1fb456e 100644
--- a/runtime/test/xgameruntime_test.cpp
+++ b/runtime/test/xgameruntime_test.cpp
@@ -579,8 +579,13 @@ void check_run_time_load() {
579 char tiny[2] = {'x', 'x'}; 579 char tiny[2] = {'x', 'x'};
580 used = 99; 580 used = 99;
581 check(reinterpret_cast<GetPath>(slot(pls, 4))(pls, 2, tiny, &used) == HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER) && 581 check(reinterpret_cast<GetPath>(slot(pls, 4))(pls, 2, tiny, &used) == HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER) &&
582 used == 0, 582 used == size && tiny[0] == 'x' && tiny[1] == 'x',
583 "slot 4 refuses a buffer that is too small"); 583 "slot 4 refuses a buffer that is too small, reports the size it needs and leaves the buffer alone");
584 check(reinterpret_cast<GetPath>(slot(pls, 4))(pls, size - 1, path.data(), &used) ==
585 HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER) && used == size,
586 "slot 4 reports the size for a buffer one byte short");
587 check(reinterpret_cast<GetPath>(slot(pls, 4))(pls, 2, tiny, nullptr) == HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER),
588 "slot 4 tolerates a null used pointer on a short buffer");
584 589
585 { 590 {
586 std::ofstream cache_file(folder / L"cache.bin", std::ios::binary); 591 std::ofstream cache_file(folder / L"cache.bin", std::ios::binary);
@@ -1090,6 +1095,37 @@ int main() {
1090 check(is_packaged() == false, "XPackageIsPackagedProcess respects LEONIDA_PACKAGED=0 override"); 1095 check(is_packaged() == false, "XPackageIsPackagedProcess respects LEONIDA_PACKAGED=0 override");
1091 SetEnvironmentVariableA("LEONIDA_PACKAGED", nullptr); 1096 SetEnvironmentVariableA("LEONIDA_PACKAGED", nullptr);
1092 1097
1098 using AppMemoryLimitFn = uint64_t(__stdcall*)();
1099 auto app_mem_limit = get<AppMemoryLimitFn>("XSystemGetAppMemoryUsageLimit");
1100 check(app_mem_limit != nullptr, "XSystemGetAppMemoryUsageLimit is registered");
1101 if (app_mem_limit) {
1102 char saved_env[64]{};
1103 const DWORD saved_n = GetEnvironmentVariableA("LEONIDA_TITLE_MEMORY_MB", saved_env, sizeof(saved_env));
1104 SetEnvironmentVariableA("LEONIDA_TITLE_MEMORY_MB", nullptr);
1105 MEMORYSTATUSEX ms{sizeof(ms)};
1106 const uint64_t expected_default = GlobalMemoryStatusEx(&ms) ? ms.ullTotalPhys : (12ULL << 30);
1107 check(app_mem_limit() == expected_default, "XSystemGetAppMemoryUsageLimit reports host RAM by default");
1108 SetEnvironmentVariableA("LEONIDA_TITLE_MEMORY_MB", "6144");
1109 check(app_mem_limit() == 6144ULL * 1024ULL * 1024ULL,
1110 "XSystemGetAppMemoryUsageLimit honors LEONIDA_TITLE_MEMORY_MB=6144");
1111 SetEnvironmentVariableA("LEONIDA_TITLE_MEMORY_MB", "512");
1112 check(app_mem_limit() == 2048ULL * 1024ULL * 1024ULL,
1113 "XSystemGetAppMemoryUsageLimit clamps LEONIDA_TITLE_MEMORY_MB below 2048 MiB");
1114 SetEnvironmentVariableA("LEONIDA_TITLE_MEMORY_MB", "131072");
1115 check(app_mem_limit() == 65536ULL * 1024ULL * 1024ULL,
1116 "XSystemGetAppMemoryUsageLimit clamps LEONIDA_TITLE_MEMORY_MB above 65536 MiB");
1117 SetEnvironmentVariableA("LEONIDA_TITLE_MEMORY_MB", "notanumber");
1118 check(app_mem_limit() == expected_default,
1119 "XSystemGetAppMemoryUsageLimit ignores invalid LEONIDA_TITLE_MEMORY_MB");
1120 SetEnvironmentVariableA("LEONIDA_TITLE_MEMORY_MB", "6144mb");
1121 check(app_mem_limit() == expected_default,
1122 "XSystemGetAppMemoryUsageLimit ignores LEONIDA_TITLE_MEMORY_MB with trailing text");
1123 SetEnvironmentVariableA("LEONIDA_TITLE_MEMORY_MB", "-4096");
1124 check(app_mem_limit() == expected_default,
1125 "XSystemGetAppMemoryUsageLimit ignores negative LEONIDA_TITLE_MEMORY_MB");
1126 SetEnvironmentVariableA("LEONIDA_TITLE_MEMORY_MB", (saved_n > 0 && saved_n < sizeof(saved_env)) ? saved_env : nullptr);
1127 }
1128
1093 // Work on the thread pool, completions dispatched by the "game loop" on this thread. 1129 // Work on the thread pool, completions dispatched by the "game loop" on this thread.
1094 auto create = get<QueueCreateFn>("XTaskQueueCreate"); 1130 auto create = get<QueueCreateFn>("XTaskQueueCreate");
1095 auto close = get<QueueCloseFn>("XTaskQueueCloseHandle"); 1131 auto close = get<QueueCloseFn>("XTaskQueueCloseHandle");
diff --git a/runtime/test/xmem_test.cpp b/runtime/test/xmem_test.cpp
index bf5bd3638..0c151bb9c 100644
--- a/runtime/test/xmem_test.cpp
+++ b/runtime/test/xmem_test.cpp
@@ -98,6 +98,10 @@ void test_alloc(XMemAllocFn alloc, XMemFreeFn free_mem) {
98} 98}
99 99
100void test_working_set(XMemGetWorkingSetStatisticsFn get_stats) { 100void test_working_set(XMemGetWorkingSetStatisticsFn get_stats) {
101 char saved_env[64]{};
102 const DWORD saved_n = GetEnvironmentVariableA("LEONIDA_TITLE_MEMORY_MB", saved_env, sizeof(saved_env));
103 SetEnvironmentVariableA("LEONIDA_TITLE_MEMORY_MB", nullptr);
104
101 alignas(64) uint8_t stats[64]; 105 alignas(64) uint8_t stats[64];
102 std::memset(stats, 0xa5, sizeof(stats)); 106 std::memset(stats, 0xa5, sizeof(stats));
103 // The pointer is the second argument: the first (0x20000001 here, as the FSR DLL passes it) must never be written 107 // The pointer is the second argument: the first (0x20000001 here, as the FSR DLL passes it) must never be written
@@ -134,6 +138,31 @@ void test_working_set(XMemGetWorkingSetStatisticsFn get_stats) {
134 } 138 }
135 check(ok != FALSE && tail_untouched, "XMemGetWorkingSetStatistics leaves bytes 16..63 untouched"); 139 check(ok != FALSE && tail_untouched, "XMemGetWorkingSetStatistics leaves bytes 16..63 untouched");
136 140
141 // LEONIDA_TITLE_MEMORY_MB override and clamping (matches XSystemGetAppMemoryUsageLimit).
142 auto query_total = [&]() -> uint64_t {
143 alignas(64) uint8_t buf[64]{};
144 if (!get_stats(kMeasuredKind, buf)) return 0;
145 uint64_t out = 0;
146 std::memcpy(&out, buf, sizeof(out));
147 return out;
148 };
149 SetEnvironmentVariableA("LEONIDA_TITLE_MEMORY_MB", "6144");
150 check(query_total() == 6144ULL * 1024ULL * 1024ULL,
151 "XMemGetWorkingSetStatistics honors LEONIDA_TITLE_MEMORY_MB=6144");
152 SetEnvironmentVariableA("LEONIDA_TITLE_MEMORY_MB", "512");
153 check(query_total() == 2048ULL * 1024ULL * 1024ULL,
154 "XMemGetWorkingSetStatistics clamps LEONIDA_TITLE_MEMORY_MB below 2048 MiB");
155 SetEnvironmentVariableA("LEONIDA_TITLE_MEMORY_MB", "131072");
156 check(query_total() == 65536ULL * 1024ULL * 1024ULL,
157 "XMemGetWorkingSetStatistics clamps LEONIDA_TITLE_MEMORY_MB above 65536 MiB");
158 SetEnvironmentVariableA("LEONIDA_TITLE_MEMORY_MB", "invalid");
159 check(query_total() == total_memory,
160 "XMemGetWorkingSetStatistics ignores invalid LEONIDA_TITLE_MEMORY_MB");
161 SetEnvironmentVariableA("LEONIDA_TITLE_MEMORY_MB", "-4096");
162 check(query_total() == total_memory,
163 "XMemGetWorkingSetStatistics ignores negative LEONIDA_TITLE_MEMORY_MB");
164 SetEnvironmentVariableA("LEONIDA_TITLE_MEMORY_MB", (saved_n > 0 && saved_n < sizeof(saved_env)) ? saved_env : nullptr);
165
137 check(get_stats(kMeasuredKind, nullptr) == FALSE, 166 check(get_stats(kMeasuredKind, nullptr) == FALSE,
138 "XMemGetWorkingSetStatistics(kind, nullptr) returns FALSE without crashing"); 167 "XMemGetWorkingSetStatistics(kind, nullptr) returns FALSE without crashing");
139} 168}
diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp
index 4e0b509e8..1062d02ff 100644
--- a/runtime/test/xs_proxy_mock_test.cpp
+++ b/runtime/test/xs_proxy_mock_test.cpp
@@ -20,6 +20,7 @@
20 20
21#include <crtdbg.h> 21#include <crtdbg.h>
22 22
23#include <algorithm>
23#include <atomic> 24#include <atomic>
24#include <cstdint> 25#include <cstdint>
25#include <cstdio> 26#include <cstdio>
@@ -95,12 +96,15 @@ struct Mock {
95 bool allocator_tag; // allocator: answers kLeonidaCommandAllocatorTag; device: the allocators it makes do 96 bool allocator_tag; // allocator: answers kLeonidaCommandAllocatorTag; device: the allocators it makes do
96 bool create_null; // device: creation returns create_result with no object 97 bool create_null; // device: creation returns create_result with no object
97 HRESULT create_result; // device: what creation returns (S_OK makes the object) 98 HRESULT create_result; // device: what creation returns (S_OK makes the object)
99 bool list_refuse; // device: CreateCommandList refuses every riid with E_NOINTERFACE
100 IID create_riid; // device: copy of the riid its last CreateCommandList got (the caller's may be a local)
98 Mock* last_child; // device: the object its last creation or open made 101 Mock* last_child; // device: the object its last creation or open made
99 unsigned calls[kMockSlots]; 102 unsigned calls[kMockSlots];
100 std::uint64_t args[kMockSlots][5]; 103 std::uint64_t args[kMockSlots][5];
101 std::uint64_t array[kMockSlots][4]; // device: the first entries of the array argument, as received 104 std::uint64_t array[kMockSlots][4]; // device: the first entries of the array argument, as received
102 D3D12_COMMAND_QUEUE_DESC queue_desc; // device: the description of its last CreateCommandQueue (slot 8) 105 D3D12_COMMAND_QUEUE_DESC queue_desc; // device: the description of its last CreateCommandQueue (slot 8)
103 IUnknown* held; // ID3D12Object::SetPrivateDataInterface (slot 5): one reference, until destroyed 106 IUnknown* held; // ID3D12Object::SetPrivateDataInterface (slot 5): one reference, until destroyed
107 D3D_FEATURE_LEVEL max_level; // device: the highest level FEATURE_LEVELS reports (0: the query is refused)
104}; 108};
105 109
106Mock g_pool[256]; 110Mock g_pool[256];
@@ -301,6 +305,39 @@ std::uint64_t mock_call(Mock* m, unsigned slot, const std::uint64_t* words) {
301 } 305 }
302 break; 306 break;
303 case 50: copy_array(m, slot, a3, a2); break; // (flags, count, objects, fence, value) 307 case 50: copy_array(m, slot, a3, a2); break; // (flags, count, objects, fence, value)
308 case 68: { // GetResourceAllocationInfo2
309 auto* ret = reinterpret_cast<D3D12_RESOURCE_ALLOCATION_INFO*>(a1);
310 const auto count = static_cast<std::uint32_t>(a3);
311 const auto* descs = reinterpret_cast<const D3D12_RESOURCE_DESC1*>(a4);
312 auto* info1 = reinterpret_cast<D3D12_RESOURCE_ALLOCATION_INFO1*>(words[4]);
313 if (descs && count > 0) {
314 m->array[68][0] = static_cast<std::uint64_t>(descs[0].Layout);
315 m->array[68][1] = static_cast<std::uint64_t>(descs[0].Flags);
316 m->array[68][2] = descs[0].SamplerFeedbackMipRegion.Width |
317 descs[0].SamplerFeedbackMipRegion.Height |
318 descs[0].SamplerFeedbackMipRegion.Depth;
319 if (count > 1) {
320 const auto& last = descs[count - 1];
321 m->array[68][3] = (static_cast<std::uint64_t>(last.Layout) << 32) |
322 static_cast<std::uint32_t>(last.Flags);
323 }
324 }
325 if (ret) *ret = {0x40000, 0x10000};
326 if (info1 && count > 0) info1[0] = {0, 0x10000, 0x40000};
327 return a1;
328 }
329 case 13: { // CheckFeatureSupport(feature, data, size): FEATURE_LEVELS only, as the host answers it
330 auto* levels = reinterpret_cast<D3D12_FEATURE_DATA_FEATURE_LEVELS*>(a2);
331 if (static_cast<std::uint32_t>(a1) != D3D12_FEATURE_FEATURE_LEVELS || !levels || !m->max_level ||
332 static_cast<std::uint32_t>(a3) != sizeof(*levels) || !levels->pFeatureLevelsRequested)
333 return static_cast<std::uint32_t>(E_INVALIDARG);
334 D3D_FEATURE_LEVEL best = D3D_FEATURE_LEVEL(0);
335 for (UINT i = 0; i < levels->NumFeatureLevels; ++i)
336 if (levels->pFeatureLevelsRequested[i] <= m->max_level)
337 best = std::max(best, levels->pFeatureLevelsRequested[i]);
338 levels->MaxSupportedFeatureLevel = best;
339 return static_cast<std::uint32_t>(best ? S_OK : DXGI_ERROR_UNSUPPORTED);
340 }
304 default: break; 341 default: break;
305 } 342 }
306 return S_OK; 343 return S_OK;
@@ -365,8 +402,10 @@ HRESULT WINAPI mock_create_command_list(Mock* self, std::uint64_t node_mask, std
365 self->args[12][2] = allocator; 402 self->args[12][2] = allocator;
366 self->args[12][3] = initial_state; 403 self->args[12][3] = initial_state;
367 self->args[12][4] = reinterpret_cast<std::uint64_t>(riid); 404 self->args[12][4] = reinterpret_cast<std::uint64_t>(riid);
405 if (riid) self->create_riid = *riid;
368 if (!out) return S_FALSE; 406 if (!out) return S_FALSE;
369 *out = nullptr; 407 *out = nullptr;
408 if (self->list_refuse) return E_NOINTERFACE;
370 if (self->create_null || FAILED(self->create_result)) return self->create_result; 409 if (self->create_null || FAILED(self->create_result)) return self->create_result;
371 Mock* child = new_mock(Kind::command_list); 410 Mock* child = new_mock(Kind::command_list);
372 child->list_level = self->list_level; 411 child->list_level = self->list_level;
@@ -500,6 +539,67 @@ unsigned long release(void* object) {
500 return static_cast<unsigned long>(raw(object, 2)); 539 return static_cast<unsigned long>(raw(object, 2));
501} 540}
502 541
542// ---- 0. The host device's feature-level floor (BL-2) ----
543
544// A host D3D12CreateDevice whose adapter tops out at g_host_max: a minimum above it is refused with E_INVALIDARG,
545// as on a host that tops out at 11_x, and g_host_mode makes it fail outright or succeed with no object.
546D3D_FEATURE_LEVEL g_host_max = D3D_FEATURE_LEVEL_12_1;
547D3D_FEATURE_LEVEL g_host_minimum = D3D_FEATURE_LEVEL(0); // the minimum the last call asked for
548enum class HostMode { normal, fail, no_object } g_host_mode = HostMode::normal;
549
550HRESULT WINAPI fake_create_device(IUnknown*, D3D_FEATURE_LEVEL minimum, REFIID riid, void** out) {
551 g_host_minimum = minimum;
552 if (!out) return S_FALSE;
553 *out = nullptr;
554 if (g_host_mode == HostMode::fail) return DXGI_ERROR_UNSUPPORTED;
555 if (g_host_mode == HostMode::no_object) return S_OK;
556 if (minimum > g_host_max) return E_INVALIDARG;
557 Mock* m = new_mock(Kind::device);
558 m->max_level = g_host_max;
559 return mock_query(m, &riid, out);
560}
561
562int check_host_device_floor() {
563 g_label = "xs_proxy_mock host feature level";
564 EXPECT(xs::kHostDeviceFloor == D3D_FEATURE_LEVEL_11_0);
565 const D3D_FEATURE_LEVEL tops[] = {D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_12_0,
566 D3D_FEATURE_LEVEL_12_1, D3D_FEATURE_LEVEL_12_2};
567 for (const D3D_FEATURE_LEVEL top : tops) {
568 g_host_max = top;
569 // The floor 12_0 the host path used to ask for refuses the adapters that top out at 11_x.
570 void* old = nullptr;
571 const HRESULT old_hr = fake_create_device(nullptr, D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), &old);
572 EXPECT(FAILED(old_hr) == (top < D3D_FEATURE_LEVEL_12_0));
573 if (old) release(old);
574
575 ID3D12Device* real = nullptr;
576 EXPECT(xs::create_host_device(&fake_create_device, nullptr, &real) == S_OK && real);
577 EXPECT(g_host_minimum == D3D_FEATURE_LEVEL_11_0);
578 EXPECT(xs::max_feature_level(real) == top); // the device keeps its highest level
579 // The title asks the device it gets (the Xbox-ABI proxy) through slot 13, CheckFeatureSupport.
580 void* device = nullptr;
581 EXPECT(SUCCEEDED(xs::create_device_proxy(real, __uuidof(ID3D12Device), &device)) && device);
582 D3D12_FEATURE_DATA_FEATURE_LEVELS levels{UINT(std::size(tops)), tops, D3D_FEATURE_LEVEL(0)};
583 EXPECT(hr_of(raw(device, 13, D3D12_FEATURE_FEATURE_LEVELS, word(&levels), sizeof(levels))) == S_OK);
584 EXPECT(levels.MaxSupportedFeatureLevel == top);
585 release(device);
586 }
587 g_host_max = D3D_FEATURE_LEVEL_12_1;
588 ID3D12Device* real = reinterpret_cast<ID3D12Device*>(&g_host_max); // must be cleared on every failure
589 EXPECT(xs::create_host_device(nullptr, nullptr, &real) == E_NOTIMPL && !real);
590 EXPECT(xs::create_host_device(&fake_create_device, nullptr, nullptr) == E_POINTER);
591 g_host_mode = HostMode::fail;
592 real = reinterpret_cast<ID3D12Device*>(&g_host_max);
593 EXPECT(xs::create_host_device(&fake_create_device, nullptr, &real) == DXGI_ERROR_UNSUPPORTED && !real);
594 g_host_mode = HostMode::no_object;
595 real = reinterpret_cast<ID3D12Device*>(&g_host_max);
596 EXPECT(xs::create_host_device(&fake_create_device, nullptr, &real) == E_FAIL && !real);
597 g_host_mode = HostMode::normal;
598 EXPECT(xs::max_feature_level(nullptr) == D3D_FEATURE_LEVEL(0));
599 g_label = "xs_proxy_mock";
600 return 0;
601}
602
503// ---- 1. Device interface levels ---- 603// ---- 1. Device interface levels ----
504 604
505int check_levels() { 605int check_levels() {
@@ -667,6 +767,35 @@ int check_levels() {
667 xs::set_placed_at_va_handler(nullptr); 767 xs::set_placed_at_va_handler(nullptr);
668 } 768 }
669 769
770 // 86: Xbox CreatePipelineState -> PC slot 47 (ID3D12Device2)
771 void* pso_out = reinterpret_cast<void*>(1);
772 const HRESULT r86 = hr_of(raw(device, 86, 0, word(&kUnknownIid), word(&pso_out)));
773 if (l.level >= 2) {
774 EXPECT(r86 == S_OK && mock->calls[47] == 1 && mock->calls[86] == 0);
775 } else {
776 EXPECT(r86 == E_NOTIMPL && !pso_out && mock->calls[47] == 0 && mock->calls[86] == 0);
777 }
778
779 // 101: Xbox CreateStateObject -> PC slot 62 (ID3D12Device5)
780 void* so_out = reinterpret_cast<void*>(1);
781 const HRESULT r101 = hr_of(raw(device, 101, 0, word(&kUnknownIid), word(&so_out)));
782 if (l.level >= 5) {
783 EXPECT(r101 == S_OK && mock->calls[62] == 1 && mock->calls[101] == 0);
784 } else {
785 EXPECT(r101 == E_NOTIMPL && !so_out && mock->calls[62] == 0 && mock->calls[101] == 0);
786 }
787
788 // 108: Xbox GetResourceAllocationInfo2 -> PC slot 68 (ID3D12Device8)
789 D3D12_RESOURCE_ALLOCATION_INFO alloc_info{1, 1};
790 const std::uint64_t r108 = raw(device, 108, word(&alloc_info), 1, 0, 0, 0);
791 if (l.level >= 8) {
792 EXPECT(r108 == word(&alloc_info) && alloc_info.SizeInBytes == 0x40000 && alloc_info.Alignment == 0x10000 &&
793 mock->calls[68] == 1 && mock->calls[108] == 0);
794 } else {
795 EXPECT(r108 == word(&alloc_info) && alloc_info.SizeInBytes == UINT64_MAX && alloc_info.Alignment == 0 &&
796 mock->calls[68] == 0 && mock->calls[108] == 0);
797 }
798
670 Mock* const queue_mock = reinterpret_cast<Mock*>(real_queue); 799 Mock* const queue_mock = reinterpret_cast<Mock*>(real_queue);
671 Mock* const fence_mock = reinterpret_cast<Mock*>(real_fence); 800 Mock* const fence_mock = reinterpret_cast<Mock*>(real_fence);
672 EXPECT(release(queue) == 0 && release(fence) == 0); 801 EXPECT(release(queue) == 0 && release(fence) == 0);
@@ -1132,7 +1261,94 @@ int check_xbox_slots() {
1132 1261
1133 EXPECT(xs::device_slot_overridden(41) && xs::device_slot_overridden(48) && xs::device_slot_overridden(61) && 1262 EXPECT(xs::device_slot_overridden(41) && xs::device_slot_overridden(48) && xs::device_slot_overridden(61) &&
1134 xs::device_slot_overridden(73) && 1263 xs::device_slot_overridden(73) &&
1135 xs::device_slot_overridden(78) && xs::device_slot_overridden(79) && xs::device_slot_overridden(80)); 1264 xs::device_slot_overridden(78) && xs::device_slot_overridden(79) && xs::device_slot_overridden(80) &&
1265 xs::device_slot_overridden(86) && xs::device_slot_overridden(101) && xs::device_slot_overridden(108));
1266
1267 // 86 CreatePipelineState(desc, riid, out) -> PC slot 47 (ID3D12Device2::CreatePipelineState).
1268 D3D12_PIPELINE_STATE_STREAM_DESC stream_desc{};
1269 const IID pso_iid = __uuidof(ID3D12PipelineState);
1270 void* pso_stream_out = nullptr;
1271 EXPECT(hr_of(raw(device, 86, word(&stream_desc), word(&pso_iid), word(&pso_stream_out))) == S_OK);
1272 EXPECT(mock->calls[86] == 0 && mock->calls[47] == 1 && xs::device_slot_hits(86) == 1);
1273 EXPECT(mock->args[47][0] == word(&stream_desc) && mock->args[47][1] == word(&pso_iid) &&
1274 mock->args[47][2] == word(&pso_stream_out));
1275 pso_stream_out = reinterpret_cast<void*>(1);
1276 EXPECT(hr_of(raw(device, 86, word(&stream_desc), 0, word(&pso_stream_out))) == E_POINTER && !pso_stream_out);
1277
1278 // 101 CreateStateObject(desc, riid, out) -> PC slot 62 (ID3D12Device5::CreateStateObject).
1279 D3D12_STATE_OBJECT_DESC state_obj_desc{};
1280 const IID so_iid = __uuidof(ID3D12StateObject);
1281 void* so_out = nullptr;
1282 EXPECT(hr_of(raw(device, 101, word(&state_obj_desc), word(&so_iid), word(&so_out))) == S_OK);
1283 EXPECT(mock->calls[101] == 0 && mock->calls[62] == 1 && xs::device_slot_hits(101) == 1);
1284 EXPECT(mock->args[62][0] == word(&state_obj_desc) && mock->args[62][1] == word(&so_iid) &&
1285 mock->args[62][2] == word(&so_out));
1286 so_out = reinterpret_cast<void*>(1);
1287 EXPECT(hr_of(raw(device, 101, word(&state_obj_desc), 0, word(&so_out))) == E_POINTER && !so_out);
1288
1289 // 108 GetResourceAllocationInfo2 -> PC slot 68 (ID3D12Device8::GetResourceAllocationInfo2), called with the
1290 // retail executable's C-ABI struct return (return buffer in RCX, device proxy in RDX), 56-byte D3D12_RESOURCE_DESC
1291 // entries, and an Xbox layout/flag word, as well as the PC C++ argument order.
1292 void* const* proxy_vtable = *reinterpret_cast<void* const* const*>(device);
1293 using CAbiSlot108Fn = D3D12_RESOURCE_ALLOCATION_INFO*(WINAPI*)(
1294 D3D12_RESOURCE_ALLOCATION_INFO*, void*, UINT, UINT, const D3D12_RESOURCE_DESC*,
1295 D3D12_RESOURCE_ALLOCATION_INFO1*);
1296 const auto call_slot108_c_abi = reinterpret_cast<CAbiSlot108Fn>(proxy_vtable[108]);
1297 D3D12_RESOURCE_DESC xbox_descs[2]{};
1298 xbox_descs[0].Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
1299 xbox_descs[0].Width = 3840;
1300 xbox_descs[0].Height = 2160;
1301 xbox_descs[0].DepthOrArraySize = 1;
1302 xbox_descs[0].MipLevels = 1;
1303 xbox_descs[0].Format = DXGI_FORMAT_R8G8B8A8_UNORM;
1304 xbox_descs[0].SampleDesc.Count = 1;
1305 xbox_descs[0].Layout = static_cast<D3D12_TEXTURE_LAYOUT>(0x105);
1306 xbox_descs[0].Flags = static_cast<D3D12_RESOURCE_FLAGS>(
1307 D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | 0x300000u);
1308 xbox_descs[1].Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
1309 xbox_descs[1].Width = 4096;
1310 xbox_descs[1].Height = 1;
1311 xbox_descs[1].DepthOrArraySize = 1;
1312 xbox_descs[1].MipLevels = 1;
1313 xbox_descs[1].SampleDesc.Count = 1;
1314 xbox_descs[1].Layout = static_cast<D3D12_TEXTURE_LAYOUT>(0x101);
1315 xbox_descs[1].Flags = static_cast<D3D12_RESOURCE_FLAGS>(D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | 0x200000u);
1316 D3D12_RESOURCE_ALLOCATION_INFO ret_info{};
1317 D3D12_RESOURCE_ALLOCATION_INFO1 detail_info[2]{};
1318 EXPECT(call_slot108_c_abi(&ret_info, device, 1, 2, xbox_descs, detail_info) == &ret_info);
1319 EXPECT(ret_info.SizeInBytes == 0x40000 && ret_info.Alignment == 0x10000);
1320 EXPECT(detail_info[0].SizeInBytes == 0x40000 && detail_info[0].Alignment == 0x10000);
1321 EXPECT(mock->calls[108] == 0 && mock->calls[68] == 1 && xs::device_slot_hits(108) == 1);
1322 EXPECT(mock->array[68][0] == static_cast<std::uint64_t>(D3D12_TEXTURE_LAYOUT_UNKNOWN));
1323 EXPECT(mock->array[68][1] == static_cast<std::uint64_t>(
1324 D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS));
1325 EXPECT(mock->array[68][2] == 0);
1326 EXPECT(mock->array[68][3] == ((static_cast<std::uint64_t>(D3D12_TEXTURE_LAYOUT_ROW_MAJOR) << 32) |
1327 static_cast<std::uint32_t>(D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)));
1328
1329 D3D12_RESOURCE_DESC xbox_buf_desc = xbox_descs[1];
1330 xbox_buf_desc.Flags = static_cast<D3D12_RESOURCE_FLAGS>(0x200000u);
1331 D3D12_RESOURCE_ALLOCATION_INFO buf_ret{};
1332 EXPECT(raw(device, 108, word(&buf_ret), 1, 1, word(&xbox_buf_desc), 0) == word(&buf_ret));
1333 EXPECT(buf_ret.SizeInBytes == 0x40000 && mock->calls[68] == 2 && xs::device_slot_hits(108) == 2);
1334 EXPECT(mock->array[68][0] == static_cast<std::uint64_t>(D3D12_TEXTURE_LAYOUT_ROW_MAJOR));
1335 EXPECT(mock->array[68][1] == static_cast<std::uint64_t>(D3D12_RESOURCE_FLAG_NONE));
1336
1337 D3D12_RESOURCE_DESC batch1025[1025]{};
1338 for (int i = 0; i < 1024; ++i) batch1025[i] = xbox_descs[0];
1339 batch1025[1024] = xbox_descs[1];
1340 D3D12_RESOURCE_ALLOCATION_INFO batch_ret{};
1341 EXPECT(call_slot108_c_abi(&batch_ret, device, 1, 1025, batch1025, nullptr) == &batch_ret);
1342 EXPECT(batch_ret.SizeInBytes == 0x40000 && mock->calls[68] == 3 && xs::device_slot_hits(108) == 3);
1343 EXPECT(mock->array[68][0] == static_cast<std::uint64_t>(D3D12_TEXTURE_LAYOUT_UNKNOWN));
1344 EXPECT(mock->array[68][3] == ((static_cast<std::uint64_t>(D3D12_TEXTURE_LAYOUT_ROW_MAJOR) << 32) |
1345 static_cast<std::uint32_t>(D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)));
1346
1347 // A count with a null descriptor array is refused with {UINT64_MAX, 0} and never reaches PC slot 68.
1348 D3D12_RESOURCE_ALLOCATION_INFO null_ret{};
1349 EXPECT(call_slot108_c_abi(&null_ret, device, 1, 2, nullptr, nullptr) == &null_ret);
1350 EXPECT(null_ret.SizeInBytes == UINT64_MAX && null_ret.Alignment == 0);
1351 EXPECT(mock->calls[68] == 3 && xs::device_slot_hits(108) == 4);
1136 1352
1137 EXPECT(release(allocator) == 0 && real_allocator->refs == 0); 1353 EXPECT(release(allocator) == 0 && real_allocator->refs == 0);
1138 EXPECT(release(queue) == 0); 1354 EXPECT(release(queue) == 0);
@@ -1201,17 +1417,27 @@ int check_xbox_queue_slots() {
1201 1417
1202// ---- 8. Environment overrides for the Xbox device slots (one process each, read once) ---- 1418// ---- 8. Environment overrides for the Xbox device slots (one process each, read once) ----
1203 1419
1420struct EnvPresenter {
1421 int stats = 0, present = 0, suspend = 0, resume = 0;
1422};
1423
1204int run_env_slots(bool valid, bool on_slot74 = false) { 1424int run_env_slots(bool valid, bool on_slot74 = false) {
1205 const char* frame_interval = on_slot74 ? "74" : valid ? "96" : "2"; 1425 const char* frame_interval = on_slot74 ? "74" : valid ? "96" : "2";
1206 const char* schedule_event = valid ? "97" : "2"; 1426 const char* schedule_event = valid ? "97" : "2";
1207 const char* wait_event = valid ? "98" : "2"; 1427 const char* wait_event = valid ? "98" : "2";
1208 const char* queue_x = valid ? "99" : "2"; 1428 const char* queue_x = valid ? "99" : "2";
1209 const char* list_x = valid ? "100" : "2"; 1429 const char* list_x = valid ? "100" : "2";
1430 const char* frame_statistics = valid ? "101" : "2";
1431 const char* suspend_x = valid ? "33" : "2"; // a queue slot beyond the PC table, as SuspendX would be
1432 const char* resume_x = valid ? "30" : "2"; // equal to PresentX's default: ResumeX is unrouted (logged)
1210 EXPECT(SetEnvironmentVariableA("LEONIDA_XS_FRAME_INTERVAL_SLOT", frame_interval) != FALSE); 1433 EXPECT(SetEnvironmentVariableA("LEONIDA_XS_FRAME_INTERVAL_SLOT", frame_interval) != FALSE);
1211 EXPECT(SetEnvironmentVariableA("LEONIDA_XS_SCHEDULE_EVENT_SLOT", schedule_event) != FALSE); 1434 EXPECT(SetEnvironmentVariableA("LEONIDA_XS_SCHEDULE_EVENT_SLOT", schedule_event) != FALSE);
1212 EXPECT(SetEnvironmentVariableA("LEONIDA_XS_WAIT_EVENT_SLOT", wait_event) != FALSE); 1435 EXPECT(SetEnvironmentVariableA("LEONIDA_XS_WAIT_EVENT_SLOT", wait_event) != FALSE);
1436 EXPECT(SetEnvironmentVariableA("LEONIDA_XS_FRAME_STATISTICS_SLOT", frame_statistics) != FALSE);
1213 EXPECT(SetEnvironmentVariableA("LEONIDA_XS_QUEUE_X_SLOT", queue_x) != FALSE); 1437 EXPECT(SetEnvironmentVariableA("LEONIDA_XS_QUEUE_X_SLOT", queue_x) != FALSE);
1214 EXPECT(SetEnvironmentVariableA("LEONIDA_XS_LIST_X_SLOT", list_x) != FALSE); 1438 EXPECT(SetEnvironmentVariableA("LEONIDA_XS_LIST_X_SLOT", list_x) != FALSE);
1439 EXPECT(SetEnvironmentVariableA("LEONIDA_XS_SUSPEND_X_SLOT", suspend_x) != FALSE);
1440 EXPECT(SetEnvironmentVariableA("LEONIDA_XS_RESUME_X_SLOT", resume_x) != FALSE);
1215 1441
1216 Mock* mock = nullptr; 1442 Mock* mock = nullptr;
1217 void* device = make_device(mock, 11, true); 1443 void* device = make_device(mock, 11, true);
@@ -1243,6 +1469,36 @@ int run_env_slots(bool valid, bool on_slot74 = false) {
1243 EXPECT(hr_of(raw(device, 78, 0, 16667, 1, 0)) == S_OK && mock->calls[78] == 1); 1469 EXPECT(hr_of(raw(device, 78, 0, 16667, 1, 0)) == S_OK && mock->calls[78] == 1);
1244 EXPECT(release(list) == 0); 1470 EXPECT(release(list) == 0);
1245 EXPECT(release(allocator) == 0); 1471 EXPECT(release(allocator) == 0);
1472
1473 // The presenter answers frame statistics at 101 only (81 is not routed, so the mock refuses it); PresentX
1474 // stays at 30, SuspendX answers at 33, and ResumeX, asked for 30, is unrouted, so 32 is refused.
1475 EnvPresenter env{};
1476 xs::PresentationHandler h{};
1477 h.context = &env;
1478 h.get_frame_statistics = [](void* ctx, std::uint64_t, UINT, UINT*, void*) -> HRESULT {
1479 ++static_cast<EnvPresenter*>(ctx)->stats;
1480 return S_FALSE;
1481 };
1482 h.present_x = [](void* ctx, UINT, const void*, const void*) -> HRESULT {
1483 ++static_cast<EnvPresenter*>(ctx)->present;
1484 return S_OK;
1485 };
1486 h.suspend_x = [](void* ctx, UINT) -> HRESULT {
1487 ++static_cast<EnvPresenter*>(ctx)->suspend;
1488 return S_OK;
1489 };
1490 h.resume_x = [](void* ctx) -> HRESULT {
1491 ++static_cast<EnvPresenter*>(ctx)->resume;
1492 return S_OK;
1493 };
1494 EXPECT(xs::set_presentation_handler(device, &h));
1495 UINT count = 0;
1496 EXPECT(hr_of(raw(device, 101, 77, 0x1a, word(&count), 0)) == S_FALSE && env.stats == 1);
1497 EXPECT(hr_of(raw(device, 81, 77, 0x1a, word(&count), 0)) == E_NOTIMPL && env.stats == 1);
1498 EXPECT(hr_of(raw(queue, 30, 1, 0, 0)) == S_OK && env.present == 1);
1499 EXPECT(hr_of(raw(queue, 33)) == S_OK && env.suspend == 1);
1500 EXPECT(hr_of(raw(queue, 32)) == E_NOTIMPL && env.resume == 0);
1501 EXPECT(xs::set_presentation_handler(device, nullptr));
1246 EXPECT(release(queue) == 0); 1502 EXPECT(release(queue) == 0);
1247 } else { 1503 } else {
1248 // Values outside 3..127 are ignored: the five defaults still answer, and a PC slot that is not a default is 1504 // Values outside 3..127 are ignored: the five defaults still answer, and a PC slot that is not a default is
@@ -1250,6 +1506,7 @@ int run_env_slots(bool valid, bool on_slot74 = false) {
1250 EXPECT(hr_of(raw(device, 78, 0, 16667, 1, 0)) == S_OK && mock->calls[78] == 0); 1506 EXPECT(hr_of(raw(device, 78, 0, 16667, 1, 0)) == S_OK && mock->calls[78] == 0);
1251 EXPECT(hr_of(raw(device, 79, 0, 0, 0, 0)) == S_OK && mock->calls[79] == 0); 1507 EXPECT(hr_of(raw(device, 79, 0, 0, 0, 0)) == S_OK && mock->calls[79] == 0);
1252 EXPECT(hr_of(raw(device, 80, 0, 0, 0, 0, word(&token))) == S_OK && token && mock->calls[80] == 0); 1508 EXPECT(hr_of(raw(device, 80, 0, 0, 0, 0, word(&token))) == S_OK && token && mock->calls[80] == 0);
1509 EXPECT(hr_of(raw(device, 81, 0, 0, 0, 0)) == S_FALSE); // the default GetFrameStatisticsX slot, unattached
1253 EXPECT(hr_of(raw(device, 71)) == S_OK && mock->calls[71] == 1); // not an Xbox slot: forwarded 1510 EXPECT(hr_of(raw(device, 71)) == S_OK && mock->calls[71] == 1); // not an Xbox slot: forwarded
1254 } 1511 }
1255 EXPECT(release(device) == 0 && mock->refs == 0); 1512 EXPECT(release(device) == 0 && mock->refs == 0);
@@ -2243,6 +2500,39 @@ int check_console_command_list() {
2243 EXPECT(real_queue->array[10][0] == word(unwrapped_list)); 2500 EXPECT(real_queue->array[10][0] == word(unwrapped_list));
2244 EXPECT(real_queue->array[10][1] == word(real_list)); 2501 EXPECT(real_queue->array[10][1] == word(real_list));
2245 2502
2503 // 5b. Public list revisions the proxy does not model and unknown private IIDs must not trigger a retry.
2504 // Spell out the Windows SDK's ID3D12GraphicsCommandList9 IID so this also builds with older headers.
2505 const IID list9_iid = {0x34ed2808, 0xffe6, 0x4c2b, {0xb1, 0x1a, 0xca, 0xbd, 0x2b, 0x0c, 0x59, 0xe1}};
2506 const IID unknown_iid = {0x12345678, 0x1234, 0x1234, {1, 2, 3, 4, 5, 6, 7, 8}};
2507 for (const IID* iid : {&list9_iid, &unknown_iid}) {
2508 const unsigned calls_before = mock_device->calls[12];
2509 void* unsupported_list = list_proxy;
2510 EXPECT(hr_of(raw(device, 73, word(&desc), word(allocator), 0, word(iid), word(&unsupported_list))) ==
2511 E_NOINTERFACE);
2512 EXPECT(!unsupported_list && mock_device->calls[12] == calls_before + 1);
2513 }
2514
2515 // The measured Xbox list IID is created as ID3D12GraphicsCommandList in one call and stays queryable on the proxy.
2516 const IID console_iid = {0xc3827890, 0x4024, 0x474c, {0x98, 0xcf, 0x64, 0x5b, 0x51, 0xdc, 0x48, 0x74}};
2517 const unsigned calls12_before = mock_device->calls[12];
2518 void* console_list = nullptr;
2519 EXPECT(hr_of(raw(device, 73, word(&desc), word(allocator), 0, word(&console_iid), word(&console_list))) == S_OK);
2520 EXPECT(xs::is_command_list_proxy(console_list) && mock_device->calls[12] == calls12_before + 1);
2521 EXPECT(IsEqualIID(mock_device->create_riid, __uuidof(ID3D12GraphicsCommandList)));
2522 void* console_list_qi = nullptr;
2523 EXPECT(hr_of(raw(console_list, 0, word(&console_iid), word(&console_list_qi))) == S_OK);
2524 EXPECT(console_list_qi == console_list && release(console_list_qi) == 1);
2525 EXPECT(release(console_list) == 0);
2526
2527 // The PC device refuses even ID3D12GraphicsCommandList for a PC IID: E_NOINTERFACE comes back as is, no retry.
2528 mock_device->list_refuse = true;
2529 const unsigned calls12_refused = mock_device->calls[12];
2530 console_list = nullptr;
2531 EXPECT(hr_of(raw(device, 73, word(&desc), word(allocator), 0, word(&list_iid), word(&console_list))) ==
2532 E_NOINTERFACE);
2533 EXPECT(!console_list && mock_device->calls[12] == calls12_refused + 1);
2534 mock_device->list_refuse = false;
2535
2246 // 6. Test with list_level = 7 (supporting ID3D12GraphicsCommandList7, 81 slots) 2536 // 6. Test with list_level = 7 (supporting ID3D12GraphicsCommandList7, 81 slots)
2247 mock_device->list_level = 7; 2537 mock_device->list_level = 7;
2248 void* list7_proxy = nullptr; 2538 void* list7_proxy = nullptr;
@@ -2273,6 +2563,99 @@ int check_console_command_list() {
2273 return 0; 2563 return 0;
2274} 2564}
2275 2565
2566// ---- 11. Presentation handler wiring (device slots 78–81 + queue PresentX/SuspendX/ResumeX) ----
2567
2568struct MockPresenter {
2569 int interval_calls = 0;
2570 UINT last_interval = 0;
2571 int schedule_calls = 0;
2572 UINT last_event = 0;
2573 int wait_calls = 0;
2574 UINT last_flags = 0;
2575 int stats_calls = 0;
2576 int present_calls = 0;
2577 UINT last_planes = 0;
2578 int suspend_calls = 0;
2579 int resume_calls = 0;
2580};
2581
2582int check_presentation_wiring() {
2583 Mock* mock = nullptr;
2584 void* device = make_device(mock, 11, true);
2585 EXPECT(device != nullptr);
2586 void* queue = make_queue(device);
2587 EXPECT(queue != nullptr);
2588
2589 MockPresenter p{};
2590 xs::PresentationHandler h{};
2591 h.context = &p;
2592 h.set_frame_interval = [](void* ctx, IUnknown*, UINT us, UINT, UINT) -> HRESULT {
2593 auto* m = static_cast<MockPresenter*>(ctx);
2594 ++m->interval_calls;
2595 m->last_interval = us;
2596 return S_OK;
2597 };
2598 h.schedule_frame_event = [](void* ctx, UINT ev, UINT, UINT) -> HRESULT {
2599 auto* m = static_cast<MockPresenter*>(ctx);
2600 ++m->schedule_calls;
2601 m->last_event = ev;
2602 return S_OK;
2603 };
2604 h.wait_frame_event = [](void* ctx, UINT, DWORD, UINT flags, std::uint64_t* tok) -> HRESULT {
2605 auto* m = static_cast<MockPresenter*>(ctx);
2606 ++m->wait_calls;
2607 m->last_flags = flags;
2608 if (tok) *tok = 77;
2609 return S_FALSE;
2610 };
2611 h.get_frame_statistics = [](void* ctx, std::uint64_t, UINT, UINT* count, void*) -> HRESULT {
2612 auto* m = static_cast<MockPresenter*>(ctx);
2613 ++m->stats_calls;
2614 if (count) *count = 0;
2615 return S_FALSE;
2616 };
2617 h.present_x = [](void* ctx, UINT plane_count, const void*, const void*) -> HRESULT {
2618 auto* m = static_cast<MockPresenter*>(ctx);
2619 ++m->present_calls;
2620 m->last_planes = plane_count;
2621 return S_OK;
2622 };
2623 h.suspend_x = [](void* ctx, UINT) -> HRESULT {
2624 ++static_cast<MockPresenter*>(ctx)->suspend_calls;
2625 return S_OK;
2626 };
2627 h.resume_x = [](void* ctx) -> HRESULT {
2628 ++static_cast<MockPresenter*>(ctx)->resume_calls;
2629 return S_OK;
2630 };
2631
2632 EXPECT(xs::set_presentation_handler(device, &h));
2633 EXPECT(hr_of(raw(device, 78, 0, 33333, 2, 0)) == S_OK && p.interval_calls == 1 && p.last_interval == 33333);
2634 EXPECT(hr_of(raw(device, 79, 2, 0, 0, 0)) == S_OK && p.schedule_calls == 1 && p.last_event == 2);
2635 std::uint64_t tok = 0;
2636 EXPECT(hr_of(raw(device, 80, 0, 0, 0, 2, word(&tok))) == S_FALSE && tok == 77 && p.wait_calls == 1 &&
2637 p.last_flags == 2);
2638 UINT count = 3;
2639 EXPECT(hr_of(raw(device, 81, 77, 0x1a, word(&count), 0)) == S_FALSE && count == 0 && p.stats_calls == 1);
2640
2641 // Queue slot 30 routes to PresentX while attached. SuspendX and ResumeX have no default route, so 31/32 are refused
2642 // and never reach the presenter (the env mode, run_env_slots, routes them).
2643 EXPECT(hr_of(raw(queue, 30, 1, 0x1000, 0x2000)) == S_OK && p.present_calls == 1 && p.last_planes == 1);
2644 EXPECT(hr_of(raw(queue, 31, 0)) == E_NOTIMPL && p.suspend_calls == 0);
2645 EXPECT(hr_of(raw(queue, 32)) == E_NOTIMPL && p.resume_calls == 0);
2646
2647 // Detaching restores default E_NOTIMPL refusal on beyond-PC queue slots.
2648 EXPECT(xs::set_presentation_handler(device, nullptr));
2649 UINT none = 7; // unattached GetFrameStatisticsX: no statistics yet, never the PC slot 81
2650 EXPECT(hr_of(raw(device, 81, 77, 0x1a, word(&none), 0)) == S_FALSE && none == 0 && p.stats_calls == 1);
2651 EXPECT(hr_of(raw(queue, 30, 1, 0, 0)) == E_NOTIMPL && p.present_calls == 1);
2652
2653 EXPECT(release(queue) == 0);
2654 EXPECT(release(device) == 0 && mock->refs == 0);
2655 std::printf("%s: presentation handler wiring (slots 78-81 and queue PresentX 30) passed\n", g_label);
2656 return 0;
2657}
2658
2276int main(int argc, char** argv) { 2659int main(int argc, char** argv) {
2277 no_dialogs(); 2660 no_dialogs();
2278 std::setvbuf(stdout, nullptr, _IONBF, 0); 2661 std::setvbuf(stdout, nullptr, _IONBF, 0);
@@ -2283,7 +2666,7 @@ int main(int argc, char** argv) {
2283 return run_fault_mode(argv[1]); 2666 return run_fault_mode(argv[1]);
2284 } 2667 }
2285 if (argc != 1) return 2; 2668 if (argc != 1) return 2;
2286 if (check_tail(true) || check_levels() || check_slot48() || check_fence1() || check_create_failures() || check_open_shared() || 2669 if (check_tail(true) || check_host_device_floor() || check_levels() || check_slot48() || check_fence1() || check_create_failures() || check_open_shared() ||
2287 check_alloc_failures() || check_allocators() || check_xbox_slots() || check_console_command_list() || 2670 check_alloc_failures() || check_allocators() || check_xbox_slots() || check_console_command_list() ||
2288 check_custom_heap_properties() || 2671 check_custom_heap_properties() ||
2289 check_resource_allocation_info() || check_slot70() || check_committed_resource3_x() || 2672 check_resource_allocation_info() || check_slot70() || check_committed_resource3_x() ||
@@ -2293,7 +2676,8 @@ int main(int argc, char** argv) {
2293 check_render_target_layout() || 2676 check_render_target_layout() ||
2294 check_committed_resource_leases() || 2677 check_committed_resource_leases() ||
2295 check_slot74() || 2678 check_slot74() ||
2296 check_xbox_queue_slots()) 2679 check_xbox_queue_slots() ||
2680 check_presentation_wiring())
2297 return 1; 2681 return 1;
2298 std::printf("xs_proxy_mock_test: PASS (%d allocations refused on purpose)\n", g_failed_news); 2682 std::printf("xs_proxy_mock_test: PASS (%d allocations refused on purpose)\n", g_failed_news);
2299 return 0; 2683 return 0;
diff --git a/runtime/xma_decoder/README.md b/runtime/xma_decoder/README.md
index 4a6d5fb10..67341e60a 100644
--- a/runtime/xma_decoder/README.md
+++ b/runtime/xma_decoder/README.md
@@ -6,8 +6,6 @@ Each decoder handle serializes decode calls. The returned PCM block owns its sam
6 6
7The tests build packets in memory; they do not open or contain audio fixtures. The synthetic C++ smoke test verifies the exported ABI and ownership boundary. 7The tests build packets in memory; they do not open or contain audio fixtures. The synthetic C++ smoke test verifies the exported ABI and ownership boundary.
8 8
9This PR adds the decoder boundary only; the Windows XAudio2 engine/source-voice adapter is a follow-up stage.
10
11Run: 9Run:
12 10
13```powershell 11```powershell
@@ -16,4 +14,15 @@ cargo test --manifest-path runtime/xma_decoder/Cargo.toml --locked
16cargo build --manifest-path runtime/xma_decoder/Cargo.toml --locked 14cargo build --manifest-path runtime/xma_decoder/Cargo.toml --locked
17``` 15```
18 16
19The C++ smoke test is run by the xma2-decoder workflow with MSVC. It links ws2_32, userenv, and ntdll for Rust's Windows standard library. 17The `xma2-decoder` workflow builds and runs the C++ smoke test with MSVC. It links `ws2_32.lib`, `userenv.lib`,
18`ntdll.lib`, and `synchronization.lib` for Rust's Windows standard library. `synchronization.lib` resolves the
19`WaitOnAddress` and `WakeByAddress*` imports in the Rust static library.
20
21## Use in the runtime
22
23`runtime/CMakeLists.txt` builds this crate for `x86_64-pc-windows-msvc` at configure time when `cargo` is on `PATH` and links it into `gta6rt` and `acphal_test` with `LEONIDA_HAVE_XMA2_DECODER` defined. The first build fetches the pinned `xma` git dependency. Set `CARGO_NET_OFFLINE=true` for a configure that uses only the local Cargo cache.
24
25`runtime/shims/acphal.cpp` uses `leonida_xma2_decoder_create_hardware` and decodes whole 2048-byte packets, so loop points are rounded to packets. The shim creates a fresh decoder after a loop rewind or a decoder error.
26
27Without `cargo`, when that build fails, or with the cl.exe fallback of `scripts/build_runtime.ps1`, XMA voices output silence.
28Use `-DLEONIDA_REQUIRE_XMA2_DECODER=ON` to require the decoder in a CMake build, as the Windows runtime CI does.
diff --git a/runtime/xma_decoder/leonida_xma2_decoder.h b/runtime/xma_decoder/leonida_xma2_decoder.h
index 98dd5c49c..a4c5b4534 100644
--- a/runtime/xma_decoder/leonida_xma2_decoder.h
+++ b/runtime/xma_decoder/leonida_xma2_decoder.h
@@ -25,6 +25,10 @@ enum LeonidaXma2Status {
25 25
26int32_t leonida_xma2_decoder_create(uint32_t sample_rate, uint32_t channels, 26int32_t leonida_xma2_decoder_create(uint32_t sample_rate, uint32_t channels,
27 LeonidaXma2Decoder **out_decoder); 27 LeonidaXma2Decoder **out_decoder);
28/* Like leonida_xma2_decoder_create, but decodes like the console's XMA hardware: the first
29 frame is kept and there is no 64-sample start skip; the caller applies the context's skip. */
30int32_t leonida_xma2_decoder_create_hardware(uint32_t sample_rate, uint32_t channels,
31 LeonidaXma2Decoder **out_decoder);
28int32_t leonida_xma2_decode_buffer(LeonidaXma2Decoder *decoder, 32int32_t leonida_xma2_decode_buffer(LeonidaXma2Decoder *decoder,
29 const uint8_t *input, size_t input_len, 33 const uint8_t *input, size_t input_len,
30 LeonidaXma2PcmBlock **out_block); 34 LeonidaXma2PcmBlock **out_block);
diff --git a/runtime/xma_decoder/src/lib.rs b/runtime/xma_decoder/src/lib.rs
index 1b435a0ce..69fedf49e 100644
--- a/runtime/xma_decoder/src/lib.rs
+++ b/runtime/xma_decoder/src/lib.rs
@@ -59,6 +59,28 @@ pub unsafe extern "C" fn leonida_xma2_decoder_create(
59 channels: u32, 59 channels: u32,
60 out_decoder: *mut *mut LeonidaXma2Decoder, 60 out_decoder: *mut *mut LeonidaXma2Decoder,
61) -> i32 { 61) -> i32 {
62 unsafe { create_with(sample_rate, channels, out_decoder, Xma2Stream::new) }
63}
64
65/// Like `leonida_xma2_decoder_create`, but decodes like the console's XMA hardware: the first
66/// frame is kept and there is no 64-sample start skip; the caller applies the context's skip.
67/// # Safety
68/// Same as `leonida_xma2_decoder_create`.
69#[no_mangle]
70pub unsafe extern "C" fn leonida_xma2_decoder_create_hardware(
71 sample_rate: u32,
72 channels: u32,
73 out_decoder: *mut *mut LeonidaXma2Decoder,
74) -> i32 {
75 unsafe { create_with(sample_rate, channels, out_decoder, Xma2Stream::new_hardware) }
76}
77
78unsafe fn create_with<E>(
79 sample_rate: u32,
80 channels: u32,
81 out_decoder: *mut *mut LeonidaXma2Decoder,
82 make: impl FnOnce(u32, usize) -> Result<Xma2Stream, E>,
83) -> i32 {
62 if out_decoder.is_null() { 84 if out_decoder.is_null() {
63 return LEONIDA_XMA2_INVALID_ARGUMENT; 85 return LEONIDA_XMA2_INVALID_ARGUMENT;
64 } 86 }
@@ -68,8 +90,8 @@ pub unsafe extern "C" fn leonida_xma2_decoder_create(
68 } 90 }
69 91
70 match catch_unwind(AssertUnwindSafe(|| { 92 match catch_unwind(AssertUnwindSafe(|| {
71 let stream = Xma2Stream::new(sample_rate, channels as usize) 93 let stream =
72 .map_err(|_| LEONIDA_XMA2_INVALID_FORMAT)?; 94 make(sample_rate, channels as usize).map_err(|_| LEONIDA_XMA2_INVALID_FORMAT)?;
73 try_new_handle(LeonidaXma2Decoder { 95 try_new_handle(LeonidaXma2Decoder {
74 stream: Mutex::new(stream), 96 stream: Mutex::new(stream),
75 channels: channels as usize, 97 channels: channels as usize,
@@ -87,7 +109,8 @@ pub unsafe extern "C" fn leonida_xma2_decoder_create(
87/// Decodes a buffer containing one or more complete 2048-byte XMA2 packets. 109/// Decodes a buffer containing one or more complete 2048-byte XMA2 packets.
88/// 110///
89/// # Safety 111/// # Safety
90/// `decoder` must be a live handle returned by `leonida_xma2_decoder_create`. 112/// `decoder` must be a live handle returned by `leonida_xma2_decoder_create`
113/// or `leonida_xma2_decoder_create_hardware`.
91/// `input` must reference `input_len` readable bytes and `out_block` must be writable. 114/// `input` must reference `input_len` readable bytes and `out_block` must be writable.
92/// Do not destroy a decoder concurrently with this call. The returned PCM block remains valid 115/// Do not destroy a decoder concurrently with this call. The returned PCM block remains valid
93/// until `leonida_xma2_pcm_destroy` is called. 116/// until `leonida_xma2_pcm_destroy` is called.
@@ -160,8 +183,8 @@ pub unsafe extern "C" fn leonida_xma2_decode_buffer(
160/// Destroys a decoder. Passing null is a no-op. 183/// Destroys a decoder. Passing null is a no-op.
161/// 184///
162/// # Safety 185/// # Safety
163/// A non-null pointer must be a live handle returned by `leonida_xma2_decoder_create`, 186/// A non-null pointer must be a live handle returned by `leonida_xma2_decoder_create`
164/// and no calls may be using it concurrently. 187/// or `leonida_xma2_decoder_create_hardware`. No calls may be using it concurrently.
165#[no_mangle] 188#[no_mangle]
166pub unsafe extern "C" fn leonida_xma2_decoder_destroy(decoder: *mut LeonidaXma2Decoder) { 189pub unsafe extern "C" fn leonida_xma2_decoder_destroy(decoder: *mut LeonidaXma2Decoder) {
167 if !decoder.is_null() { 190 if !decoder.is_null() {
@@ -233,6 +256,24 @@ mod tests {
233 } 256 }
234 257
235 #[test] 258 #[test]
259 fn create_hardware_accepts_stereo_and_rejects_three_channels() {
260 let mut decoder = ptr::null_mut();
261 assert_eq!(
262 unsafe { leonida_xma2_decoder_create_hardware(48_000, 2, &mut decoder) },
263 LEONIDA_XMA2_OK
264 );
265 assert!(!decoder.is_null());
266 unsafe { leonida_xma2_decoder_destroy(decoder) };
267
268 let mut decoder = ptr::dangling_mut();
269 assert_eq!(
270 unsafe { leonida_xma2_decoder_create_hardware(48_000, 3, &mut decoder) },
271 LEONIDA_XMA2_INVALID_FORMAT
272 );
273 assert!(decoder.is_null());
274 }
275
276 #[test]
236 fn pcm_handle_allocation_failure_clears_output_and_allows_retry() { 277 fn pcm_handle_allocation_failure_clears_output_and_allows_retry() {
237 let mut decoder = ptr::null_mut(); 278 let mut decoder = ptr::null_mut();
238 assert_eq!( 279 assert_eq!(
diff --git a/runtime/xma_decoder/tests/ffi_contract.rs b/runtime/xma_decoder/tests/ffi_contract.rs
index 0eb8e5cf4..6e6185c39 100644
--- a/runtime/xma_decoder/tests/ffi_contract.rs
+++ b/runtime/xma_decoder/tests/ffi_contract.rs
@@ -52,6 +52,28 @@ fn make_decoder(rate: u32, channels: u32) -> *mut LeonidaXma2Decoder {
52} 52}
53 53
54#[test] 54#[test]
55fn hardware_mode_keeps_all_samples_of_the_first_stereo_frame() {
56 let mut packet = synthetic_silent_packet(2);
57 packet[..4].copy_from_slice(&[4, 0, 1, 0]); // One frame, no continuation from a previous packet.
58 let mut decoder = ptr::null_mut();
59 let mut block = ptr::null_mut();
60 unsafe {
61 assert_eq!(
62 leonida_xma2_decoder_create_hardware(48_000, 2, &mut decoder),
63 LEONIDA_XMA2_OK
64 );
65 assert_eq!(
66 leonida_xma2_decode_buffer(decoder, packet.as_ptr(), packet.len(), &mut block),
67 LEONIDA_XMA2_OK
68 );
69 let count = leonida_xma2_pcm_sample_count(block);
70 leonida_xma2_pcm_destroy(block);
71 leonida_xma2_decoder_destroy(decoder);
72 assert_eq!(count, 512 * 2);
73 }
74}
75
76#[test]
55fn creation_rejects_invalid_outputs_and_formats() { 77fn creation_rejects_invalid_outputs_and_formats() {
56 assert_eq!( 78 assert_eq!(
57 unsafe { leonida_xma2_decoder_create(48_000, 2, ptr::null_mut()) }, 79 unsafe { leonida_xma2_decoder_create(48_000, 2, ptr::null_mut()) },