diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 10ee582b12..d0fc1c6054 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -2297,7 +2297,8 @@ if(TARGET Vulkan::Headers) endif() add_test(NAME vk_presenter_sync COMMAND vk_presenter_sync_test) add_test(NAME vk_presenter_sparse_capture COMMAND vk_presenter_sync_test --sparse-capture) - set_tests_properties(vk_presenter_sync vk_presenter_sparse_capture PROPERTIES SKIP_RETURN_CODE 77) + add_test(NAME vk_presenter_probe_timeout COMMAND vk_presenter_sync_test --probe-timeout) + set_tests_properties(vk_presenter_sync vk_presenter_sparse_capture vk_presenter_probe_timeout PROPERTIES SKIP_RETURN_CODE 77) set(conformance_src ${CMAKE_CURRENT_SOURCE_DIR}/../tools/conformance/native/src) add_executable(vk_present_dump_test test/vk_present_dump_test.cpp ${conformance_src}/png_io.cpp ${conformance_src}/diagnostics.cpp) diff --git a/runtime/src/vulkan_present.h b/runtime/src/vulkan_present.h index 81f3b57e1d..e3021c2212 100644 --- a/runtime/src/vulkan_present.h +++ b/runtime/src/vulkan_present.h @@ -228,6 +228,7 @@ class VulkanPresenter { if (frame.done) vkDestroyFence_(device, frame.done, nullptr); if (frame.acquired) vk.vkDestroySemaphore(device, frame.acquired, nullptr); } + probe_reclaim(true); // LOCAL DIAGNOSTIC: the queue wait above has finished a timed-out readback's copy if (probe_fence_) vkDestroyFence_(device, probe_fence_, nullptr); // LOCAL DIAGNOSTIC if (pool_) vk.vkDestroyCommandPool(device, pool_, nullptr); if (surface_ && vkDestroySurfaceKHR_) vkDestroySurfaceKHR_(instance_, surface_, nullptr); @@ -722,6 +723,9 @@ class VulkanPresenter { int probe_written_ = 0; VkCommandBuffer probe_commands_ = VK_NULL_HANDLE; VkFence probe_fence_ = VK_NULL_HANDLE; + // The staging buffer of a readback whose fence wait timed out: the copy may still write it (probe_reclaim). + VkBuffer probe_parked_buffer_ = VK_NULL_HANDLE; + VkDeviceMemory probe_parked_memory_ = VK_NULL_HANDLE; static float probe_half(std::uint16_t h) { const std::uint32_t sign = (h >> 15) & 1, exponent = (h >> 10) & 0x1f, mantissa = h & 0x3ff; @@ -808,6 +812,21 @@ class VulkanPresenter { } } + // Frees the staging buffer a timed-out readback left behind once its fence has signalled (or unconditionally + // when `idle`: the destructor's queue wait has finished the copy). True when nothing is in flight any more, so + // the probe's command buffer and fence may be reset. + bool probe_reclaim(bool idle) { + if (!probe_parked_buffer_ && !probe_parked_memory_) return true; + const VkDevice device = context_.device(); + if (!idle && vkWaitForFences_(device, 1, &probe_fence_, VK_TRUE, 0) != VK_SUCCESS) return false; + auto& vk = context_.vk; + if (probe_parked_memory_) vk.vkFreeMemory(device, probe_parked_memory_, nullptr); + if (probe_parked_buffer_) vk.vkDestroyBuffer(device, probe_parked_buffer_, nullptr); + probe_parked_buffer_ = VK_NULL_HANDLE; + probe_parked_memory_ = VK_NULL_HANDLE; + return true; + } + // Copies mip 0, layer 0 of `id` to host memory on the presenter's queue (waited for), logs and writes it. void probe_read_source(ResourceId id, std::uint64_t number, const char* path, const char* prefix = "source") { const bool is_source = std::strcmp(prefix, "source") == 0; @@ -827,6 +846,11 @@ class VulkanPresenter { return; } } + if (!probe_reclaim(false)) { // an earlier readback timed out and its copy is still running + std::fprintf(stderr, "[rt] present-probe: %s frame %llu skipped: the last readback is still in flight\n", + prefix, static_cast(number)); + return; + } std::shared_lock resource_lock(context_.resource_mutex_); const ResourceBinding* found = context_.resolve(id); if (!found || !found->image) return; @@ -934,13 +958,23 @@ class VulkanPresenter { "vkQueueSubmit (present probe)"); if (submitted == VK_SUCCESS) context_.note_image_work_locked(); } - if (submitted != VK_SUCCESS || - context_.observe_result(vkWaitForFences_(device, 1, &probe_fence_, VK_TRUE, 5'000'000'000ull), - "vkWaitForFences (present probe)") != VK_SUCCESS) { - std::fprintf(stderr, "[rt] present-probe: readback submit/wait failed (%d)\n", int(submitted)); + if (submitted != VK_SUCCESS) { + std::fprintf(stderr, "[rt] present-probe: readback submit failed (%d)\n", int(submitted)); cleanup(); return; } + if (const VkResult waited = context_.observe_result( + vkWaitForFences_(device, 1, &probe_fence_, VK_TRUE, 5'000'000'000ull), "vkWaitForFences (present probe)"); + waited != VK_SUCCESS) { + // The copy was submitted and may still run: the GPU can write the staging buffer and still owns the + // command buffer and the fence. Give up on this readback, but park the buffer and its memory until the + // fence signals (probe_reclaim, or the destructor after its queue wait) instead of freeing them now. + std::fprintf(stderr, "[rt] present-probe: readback wait failed (%d); its buffer is freed once the copy is " + "done\n", int(waited)); + probe_parked_buffer_ = buffer; + probe_parked_memory_ = memory; + return; + } const std::size_t texels = std::size_t(binding.width) * binding.height; const auto* bytes = static_cast(mapped); std::vector rgb(texels * 3); diff --git a/runtime/test/vk_presenter_probe_timeout.h b/runtime/test/vk_presenter_probe_timeout.h new file mode 100644 index 0000000000..bf89453682 --- /dev/null +++ b/runtime/test/vk_presenter_probe_timeout.h @@ -0,0 +1,190 @@ +// vk_presenter_sync_test --probe-timeout (RT-PRESENT-PROBE-TIMEOUT-UAF): the present-source readback probe +// (LEONIDA_CAPTURE_SOURCE) gives up when its fence wait fails, but the copy it submitted may still be running. The +// driver hooks in vk_presenter_sync_test.cpp hold that copy on a timeline semaphore and make the wait time out at +// once. The probe must not free the staging buffer or its memory while the copy is pending, must not reset and +// resubmit its command buffer and fence for a later present while they are in use (that probe is skipped), must take +// readbacks again once the copy is done, and must leave nothing behind at vkDestroyDevice (run it with +// LEONIDA_VK_VALIDATION=1 for the layer's own checks). Included after the driver hooks. No game data. +#pragma once + +namespace probe_timeout_test { +namespace fs = std::filesystem; + +// A fresh owner/SYSTEM-only capture folder; only the files the probe and the capture write in it are removed. +struct Folder { + fs::path path; + bool create() { + auto candidate = fs::temp_directory_path() / ("leonida-probe-timeout-" + std::to_string(GetCurrentProcessId()) + + "-" + std::to_string(GetTickCount64())); + PSECURITY_DESCRIPTOR sd = nullptr; + if (!ConvertStringSecurityDescriptorToSecurityDescriptorW(L"D:P(A;OICI;FA;;;OW)(A;OICI;FA;;;SY)", + SDDL_REVISION_1, &sd, nullptr)) return false; + SECURITY_ATTRIBUTES sa{sizeof(sa), sd, FALSE}; + const bool fresh = CreateDirectoryW(candidate.c_str(), &sa) != FALSE; + LocalFree(sd); + if (fresh) path = std::move(candidate); + return fresh; + } + ~Folder() { + if (path.empty()) return; + std::error_code ec; + for (const auto& e : fs::directory_iterator(path, ec)) { + const std::string name = e.path().filename().string(); + const bool ours = name == "index.txt" || name == "source_index.txt" || + ((name.rfind("frame_", 0) == 0 || name.rfind("source_", 0) == 0) && + e.path().extension() == ".ppm"); + if (ours && fs::is_regular_file(e.symlink_status())) fs::remove(e.path(), ec); + } + fs::remove(path, ec); // leave unknown contents alone + } +}; + +inline int run() { + using namespace leonida; + Folder folder; + if (!folder.create()) { + std::fprintf(stderr, "probe timeout: cannot make a capture folder\n"); + return 1; + } + _putenv_s("LEONIDA_CAPTURE", folder.path.string().c_str()); + _putenv_s("LEONIDA_CAPTURE_SOURCE", "1"); + _putenv_s("LEONIDA_CAPTURE_EVERY", "1"); + + auto d = std::make_unique(); + if (!d->create(true)) { + std::fprintf(stderr, "vk_presenter_sync_test --probe-timeout: no Vulkan device with presentation, skipped\n"); + return 77; + } + WNDCLASSW wc{}; + wc.lpfnWndProc = window_proc; + wc.hInstance = GetModuleHandleW(nullptr); + wc.lpszClassName = L"LeonidaPresenterProbeTimeoutTest"; + EXPECT(RegisterClassW(&wc)); + constexpr std::uint32_t width = 64, height = 48; + RECT fr{0, 0, LONG(width), LONG(height)}; + AdjustWindowRect(&fr, WS_OVERLAPPEDWINDOW, FALSE); + HWND window = CreateWindowExW(WS_EX_NOACTIVATE | WS_EX_TOOLWINDOW, wc.lpszClassName, L"Leonida probe timeout test", + WS_OVERLAPPEDWINDOW, 80, 80, fr.right - fr.left, fr.bottom - fr.top, nullptr, nullptr, + wc.hInstance, nullptr); + EXPECT(window); + ShowWindow(window, SW_SHOWNOACTIVATE); + pump(); + driver::install(d->instance_proc, d->instance, d->device); + + const auto create_semaphore = + reinterpret_cast(driver::real_get_device(d->device, "vkCreateSemaphore")); + const auto destroy_semaphore = + reinterpret_cast(driver::real_get_device(d->device, "vkDestroySemaphore")); + const auto signal_semaphore = + reinterpret_cast(driver::real_get_device(d->device, "vkSignalSemaphore")); + EXPECT(create_semaphore && destroy_semaphore && signal_semaphore); + VkSemaphoreTypeCreateInfo type{VK_STRUCTURE_TYPE_SEMAPHORE_TYPE_CREATE_INFO}; + type.semaphoreType = VK_SEMAPHORE_TYPE_TIMELINE; + VkSemaphoreCreateInfo semaphore_info{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, &type}; + VkSemaphore hold = VK_NULL_HANDLE; + EXPECT(create_semaphore(d->device, &semaphore_info, nullptr, &hold) == VK_SUCCESS); + + bool first_read = false, kept = false, one_submit_while_held = false, read_again = false, idle = false; + VkResult presents[4] = {VK_ERROR_UNKNOWN, VK_ERROR_UNKNOWN, VK_ERROR_UNKNOWN, VK_ERROR_UNKNOWN}; + { + VulkanContext context(driver::get_device, d->device, true); + EXPECT(context.loaded()); + VulkanQueue queue(context, d->queue, d->family); + EXPECT(queue.ok()); + const VkImage image = d->image(VK_FORMAT_R8G8B8A8_UNORM, 32, 32, 1, + VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | + VK_IMAGE_USAGE_TRANSFER_SRC_BIT); + EXPECT(image != VK_NULL_HANDLE); + ResourceBinding rb{}; + rb.image = image; + rb.format = VK_FORMAT_R8G8B8A8_UNORM; + rb.aspects = VK_IMAGE_ASPECT_COLOR_BIT; + rb.width = 32; + rb.height = 32; + rb.mip_levels = 1; + rb.array_layers = 1; + rb.depth = 1; + rb.samples = 1; + rb.color_attachment = true; + context.add_resource(1, rb, VK_IMAGE_LAYOUT_UNDEFINED); + { // a written source: the probe only reads back what a tracked GPU operation wrote + CommandList clear; + EXPECT(clear.transition({1, 0, d3d12_state::common, d3d12_state::render_target})); + EXPECT(clear.clear_render_target({1, 0, 0, 1}, {0.2f, 0.6f, 0.9f, 1.0f})); + EXPECT(clear.transition({1, 0, d3d12_state::render_target, d3d12_state::common})); + EXPECT(clear.close()); + const CommandList* ptr = &clear; + EXPECT(queue.execute({&ptr, 1}) == ReplayResult::success); + EXPECT(queue.idle()); + } + driver::probe_image = image; + + const auto create_surface = reinterpret_cast( + d->instance_proc(d->instance, "vkCreateWin32SurfaceKHR")); + EXPECT(create_surface); + VkWin32SurfaceCreateInfoKHR surface_info{VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR}; + surface_info.hinstance = GetModuleHandleW(nullptr); + surface_info.hwnd = window; + VkSurfaceKHR surface = VK_NULL_HANDLE; + EXPECT(create_surface(d->instance, &surface_info, nullptr, &surface) == VK_SUCCESS); + { + VulkanPresenter presenter(context, driver::get_instance, d->instance, d->physical, d->queue, d->family, + surface); + EXPECT(presenter.ok()); + + // 1. A plain readback: the probe is on and copies the source. + presents[0] = presenter.present(1, true); + first_read = driver::probe_submits.load() == 1; + + // 2. The next readback's copy is held and its wait times out. The frame's own submit is made to fail + // (nothing may be presented behind the held copy), so this present reports that failure. No EXPECT + // may return from here until the semaphore is signalled: the destructor would wait for the queue. + driver::hold = hold; + driver::held.store(true); + presents[1] = presenter.present(1, true); + kept = !driver::freed_in_flight.load() && driver::held_buffer != VK_NULL_HANDLE; + + // 3. A present while the copy is still held: its probe, which runs first, must not reset the busy + // command buffer and fence and submit again. The rest of that present waits for the queue (the image + // the failed present gave back is fenced behind the held copy) until the release thread signals. + VkResult signalled = VK_ERROR_UNKNOWN; + std::thread release([&] { + std::this_thread::sleep_for(std::chrono::milliseconds(500)); + driver::held.store(false); + VkSemaphoreSignalInfo signal{VK_STRUCTURE_TYPE_SEMAPHORE_SIGNAL_INFO}; + signal.semaphore = hold; + signal.value = 1; + signalled = signal_semaphore(d->device, &signal); + }); + presents[2] = presenter.present(1, true); + release.join(); + one_submit_while_held = driver::probe_submits_held.load() == 1 && driver::probe_submits.load() == 2 && + !driver::freed_in_flight.load() && signalled == VK_SUCCESS; + + // 4. With the copy done, the parked buffer is freed and the probe reads back again. + presents[3] = presenter.present(1, true); + read_again = driver::probe_submits.load() == 3; + idle = queue.idle(); + driver::probe_image = VK_NULL_HANDLE; + } + pump(); + context.remove_resource(1); + } + destroy_semaphore(d->device, hold, nullptr); + DestroyWindow(window); + UnregisterClassW(wc.lpszClassName, wc.hInstance); + d.reset(); // vkDestroyDevice: the layer reports any object still alive here + for (int i = 0; i < 4; ++i) std::fprintf(stderr, "probe timeout: present %d returned %d\n", i, int(presents[i])); + EXPECT(presents[0] == VK_SUCCESS && presents[1] == VK_ERROR_OUT_OF_HOST_MEMORY && + presents[2] == VK_SUCCESS && presents[3] == VK_SUCCESS); + EXPECT(first_read); + EXPECT(kept); + EXPECT(one_submit_while_held); + EXPECT(read_again); + EXPECT(idle); + EXPECT(vktest::validation_error_count() == 0); + std::printf("vk_presenter_sync_test --probe-timeout: ok\n"); + return 0; +} + +} // namespace probe_timeout_test diff --git a/runtime/test/vk_presenter_sync_test.cpp b/runtime/test/vk_presenter_sync_test.cpp index ee75ad86f1..f274990480 100644 --- a/runtime/test/vk_presenter_sync_test.cpp +++ b/runtime/test/vk_presenter_sync_test.cpp @@ -101,11 +101,90 @@ VKAPI_ATTR void VKAPI_CALL destroy_swapchain(VkDevice device, VkSwapchainKHR swa real_destroy_swapchain(device, swapchain, alloc); } +// --probe-timeout: the present-source probe's readback copies `probe_image` into a staging buffer. While `hold` is +// set, the submit carrying that copy also waits on the timeline semaphore `hold` (value 1, signalled by the test), +// and the fence wait that follows times out at once, so the copy is still pending when the probe gives up. +PFN_vkDestroyBuffer real_destroy_buffer = nullptr; +PFN_vkFreeMemory real_free_memory = nullptr; +PFN_vkBindBufferMemory real_bind_buffer = nullptr; +VkImage probe_image = VK_NULL_HANDLE; +VkCommandBuffer probe_cb = VK_NULL_HANDLE; +VkBuffer probe_dst = VK_NULL_HANDLE; +VkSemaphore hold = VK_NULL_HANDLE; +std::atomic held{false}; // the semaphore is not signalled yet: the held copy is pending +std::atomic timeout_next_wait{false}; +std::atomic probe_submits{0}; // submits of the probe's copy +std::atomic probe_submits_held{0}; +std::atomic freed_in_flight{false}; // the pending copy's buffer or memory was destroyed or freed +std::mutex bind_mutex; +std::vector> binds; +VkBuffer held_buffer = VK_NULL_HANDLE; +VkDeviceMemory held_memory = VK_NULL_HANDLE; + +VKAPI_ATTR VkResult VKAPI_CALL bind_buffer_memory(VkDevice device, VkBuffer buffer, VkDeviceMemory memory, + VkDeviceSize offset) { + { + std::lock_guard lock(bind_mutex); + binds.emplace_back(buffer, memory); + } + return real_bind_buffer(device, buffer, memory, offset); +} + +// A buffer or memory the held copy still uses is recorded and kept (a real free would let the GPU write freed +// memory once the test signals the semaphore); the test then fails on `freed_in_flight`. +VKAPI_ATTR void VKAPI_CALL destroy_buffer(VkDevice device, VkBuffer buffer, const VkAllocationCallbacks* alloc) { + if (buffer != VK_NULL_HANDLE && held.load() && buffer == held_buffer) { + freed_in_flight.store(true); + return; + } + real_destroy_buffer(device, buffer, alloc); +} + +VKAPI_ATTR void VKAPI_CALL free_memory(VkDevice device, VkDeviceMemory memory, const VkAllocationCallbacks* alloc) { + if (memory != VK_NULL_HANDLE && held.load() && memory == held_memory) { + freed_in_flight.store(true); + return; + } + real_free_memory(device, memory, alloc); +} + VKAPI_ATTR VkResult VKAPI_CALL queue_submit(VkQueue queue, std::uint32_t count, const VkSubmitInfo* submits, VkFence fence) { submit_entered.store(true, std::memory_order_release); + const bool probe = probe_cb != VK_NULL_HANDLE && count == 1 && submits[0].commandBufferCount == 1 && + submits[0].pCommandBuffers[0] == probe_cb; + if (probe) { + probe_cb = VK_NULL_HANDLE; // recorded again by the next readback's copy + probe_submits.fetch_add(1); + if (held.load()) probe_submits_held.fetch_add(1); + } const VkResult armed = fail_next_submit.exchange(VK_SUCCESS); if (armed != VK_SUCCESS) return armed; + if (probe) { + if (hold != VK_NULL_HANDLE && held.load() && !held_buffer) { + { + std::lock_guard lock(bind_mutex); + for (const auto& [b, m] : binds) + if (b == probe_dst) held_memory = m; + } + held_buffer = probe_dst; + const std::uint64_t one = 1; + VkTimelineSemaphoreSubmitInfo timeline{VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO}; + timeline.waitSemaphoreValueCount = 1; + timeline.pWaitSemaphoreValues = &one; + const VkPipelineStageFlags stage = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; + VkSubmitInfo submit = submits[0]; + submit.pNext = &timeline; + submit.waitSemaphoreCount = 1; + submit.pWaitSemaphores = &hold; + submit.pWaitDstStageMask = &stage; + timeout_next_wait.store(true); + // The frame's own submit, next, fails: a present queued behind the held copy would wait on a signal + // that is not submitted yet (VUID-vkQueuePresentKHR-pWaitSemaphores-03268). + fail_next_submit.store(VK_ERROR_OUT_OF_HOST_MEMORY); + return real_submit(queue, 1, &submit, fence); + } + } return real_submit(queue, count, submits, fence); } @@ -122,6 +201,7 @@ VKAPI_ATTR VkResult VKAPI_CALL wait_for_fences(VkDevice device, std::uint32_t co VkBool32 wait_all, std::uint64_t timeout) { const VkResult armed = fail_next_wait.exchange(VK_SUCCESS); if (armed != VK_SUCCESS) return armed; + if (timeout_next_wait.exchange(false)) timeout = 0; // the held probe copy: a real VK_TIMEOUT, at once return real_wait(device, count, fences, wait_all, timeout); } @@ -154,6 +234,10 @@ VKAPI_ATTR void VKAPI_CALL cmd_copy_image_to_buffer(VkCommandBuffer cb, VkImage if (saw_capture_waw.exchange(false, std::memory_order_relaxed)) capture_waw_barriers.fetch_add(1, std::memory_order_relaxed); } + if (probe_image != VK_NULL_HANDLE && src == probe_image) { + probe_cb = cb; + probe_dst = dst; + } real_copy_i2b(cb, src, layout, dst, count, regions); } @@ -165,6 +249,9 @@ VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_device(VkDevice device, const char* if (n == "vkWaitForFences") return reinterpret_cast(wait_for_fences); if (n == "vkCmdPipelineBarrier") return reinterpret_cast(cmd_pipeline_barrier); if (n == "vkCmdCopyImageToBuffer") return reinterpret_cast(cmd_copy_image_to_buffer); + if (n == "vkDestroyBuffer") return reinterpret_cast(destroy_buffer); + if (n == "vkFreeMemory") return reinterpret_cast(free_memory); + if (n == "vkBindBufferMemory") return reinterpret_cast(bind_buffer_memory); return real_get_device(device, name); } @@ -183,16 +270,21 @@ void install(PFN_vkGetInstanceProcAddr instance_proc, VkInstance instance, VkDev real_wait = reinterpret_cast(real_get_device(device, "vkWaitForFences")); real_barrier = reinterpret_cast(real_get_device(device, "vkCmdPipelineBarrier")); real_copy_i2b = reinterpret_cast(real_get_device(device, "vkCmdCopyImageToBuffer")); + real_destroy_buffer = reinterpret_cast(real_get_device(device, "vkDestroyBuffer")); + real_free_memory = reinterpret_cast(real_get_device(device, "vkFreeMemory")); + real_bind_buffer = reinterpret_cast(real_get_device(device, "vkBindBufferMemory")); } } // namespace driver #include "vk_presenter_sparse_capture.h" +#include "vk_presenter_probe_timeout.h" } // namespace int main(int argc, char** argv) { using namespace leonida; const bool sparse = argc==2 && std::string_view(argv[1])=="--sparse-capture"; + if (argc==2 && std::string_view(argv[1])=="--probe-timeout") return probe_timeout_test::run(); if (argc!=1 && !sparse) return 2; vktest::Device d;