diff --git a/AGENTS.consumer.md b/AGENTS.consumer.md index 1eef887..8a0dbe5 100644 --- a/AGENTS.consumer.md +++ b/AGENTS.consumer.md @@ -35,6 +35,7 @@ window.StartSync(); // the event loop - A `RenderPass` is `Record(cmd, frameIdx, window)` plus `SwapchainStage()`, which must return the stage that touches the swapchain image (`COMPUTE_SHADER`, `RAY_TRACING_SHADER` or `TRANSFER`): the frame's barriers take their stage and access masks from it. `frameIdx` is the frame slot, `window.currentFrame`, not the image: the frame's image is `window.images[window.currentImage]`. The image stays in `VK_IMAGE_LAYOUT_GENERAL` through the whole pass list, with `STORAGE | TRANSFER_SRC` usage and `TRANSFER_DST` where the surface allows it (`window.swapchainUsage`). Nothing clears it: draw a background quad, or clear from a transfer pass where `TRANSFER_DST` is there. - `window.width` and `height` are physical pixels, as is `currentMousePos`. `CaptureNextFrame(path)` saves the next frame as a PNG. `SetTitle`, `SetAppId`, `SetCursorImage`, `SetDefaultCursor`; `SetTextInput(active, x, y, w, h, purpose, hints)` tells the compositor's input method a text field has focus, which opens an on-screen keyboard on a phone. `purpose` is what the field holds (`TextInputPurpose::Normal`, `Alpha`, `Digits`, `Number`, `Phone`, `Url`, `Email`, `Name`, `Password`, `Pin`, `Date`, `Time`, `Datetime`, `Terminal`), by which the keyboard picks its layout, and `hints` how it treats what is typed (`kTextInputHintCompletion`, `Spellcheck`, `AutoCapitalization`, `Lowercase`, `Uppercase`, `Titlecase`, `HiddenText`, `SensitiveData`, `Latin`, `Multiline`, or-ed together). Without `hints` a field gets `TextInputDefaultHints(purpose)`: completion, spellcheck and capitals for `Normal`, hidden and not learnt for `Password` and `Pin`, none for the rest; `kTextInputHintNone` asks for none. Name the purpose of every field that is not prose. Call it again when the caret moves, with the same purpose and hints. A call that changes either while a field has focus tells the input method the focus moved to another field (it enables anew), which ends the composition under way without an `onPreedit`, as `SetTextInput(false)` does, so commit or drop your composing text first. A move to another field of the same purpose and hints looks to the window like a caret that moved and sends no enable: call `SetTextInput(false)` before the new field's `SetTextInput(true, ...)`. The input method's changes come in batches (text-input-v3's `done`), each fired as `onTextInputDelete`, `onTextInput` and `onPreedit` in that order, and the batches in the order they arrived: one that arrives while a listener of another is running (the listener made a `Window` or called `Clipboard::GetText`, which dispatch the events) waits until that one is through. Only these wait: a key, pointer or touch event the same dispatch brings fires at once, before a batch that waits. - Several windows can exist (on Wayland `Device::windows` lists them; the other backends keep no list), and may share a heap, each writing only its own swapchain slots, but they share one frame clock: one rendering window is the assumption behind the deletion queue, the staging rings and the font atlas's evictions. Without a `Window`, nothing advances `Device::frameCounter`: a program that draws text without one steps it itself after each frame's work, or its full atlas never frees a cell and new glyphs stay blank. +- On Wayland and Win32 a `Window` constructor that throws (a Vulkan error, or a surface that offers no format the swapchain can be written through as a storage image) leaves nothing of the window behind (#169): the destructor has run for what it had made by the time the exception reaches you, so on Wayland the window is not in `Device::windows` and its Wayland objects are destroyed, on Win32 its HWND is, and on both so is its Vulkan surface. The error can be caught and the program go on. ### Device and features diff --git a/AGENTS.template.md b/AGENTS.template.md index 627774f..7b5a7b6 100644 --- a/AGENTS.template.md +++ b/AGENTS.template.md @@ -68,13 +68,13 @@ crafter-build clean ## Testing instructions -Tests are declared in `project.cpp`, not discovered, through the `LibraryTest(name)` lambda: it copies the library's settings field by field (`Configuration` is not copyable) and compiles the library's sources plus `tests//main.cpp` into one executable, so a test reaches non-exported internals the way the library does. A new test is a directory, a `cfg.tests.push_back(LibraryTest("Name"));` and a comment above it saying what it covers and what it needs (a GPU, ray tracing, a compositor, a tool). A test that needs shaders adds them to `test.config.shaders` with the same `ShaderType` lines the examples use; a font or asset goes in `test.config.files`; a tool it runs goes in `requires_` (`{"tool:glslang", "tool:spirv-val"}`), which turns the test into a skip when the tool is missing. The declarations sit in the native branch of `project.cpp`: wasm runs no tests. Wayland-only tests sit in `if (!windows)`; the Win32 tests, `PointerWin32` and `TextWin32`, sit in `if (windows)`, with `requires_ = {"tool:wine"}` when built on Linux. `Win32Link` beside them has no `requires_`, since its link is the test: where there is no Wine it runs as `--runner=cmd:true`, which builds it and runs nothing. A `requires_` would skip the build as well, and a test cannot pick its own runner, as the harness derives every test's from its target. +Tests are declared in `project.cpp`, not discovered, through the `LibraryTest(name)` lambda: it copies the library's settings field by field (`Configuration` is not copyable) and compiles the library's sources plus `tests//main.cpp` into one executable, so a test reaches non-exported internals the way the library does. A new test is a directory, a `cfg.tests.push_back(LibraryTest("Name"));` and a comment above it saying what it covers and what it needs (a GPU, ray tracing, a compositor, a tool). A test that needs shaders adds them to `test.config.shaders` with the same `ShaderType` lines the examples use; a font or asset goes in `test.config.files`; a tool it runs goes in `requires_` (`{"tool:glslang", "tool:spirv-val"}`), which turns the test into a skip when the tool is missing. The declarations sit in the native branch of `project.cpp`: wasm runs no tests. Wayland-only tests sit in `if (!windows)`; the Win32 tests, `PointerWin32`, `TextWin32` and `WindowConstructorThrowWin32`, sit in `if (windows)`, with `requires_ = {"tool:wine"}` when built on Linux. `Win32Link` beside them has no `requires_`, since its link is the test: where there is no Wine it runs as `--runner=cmd:true`, which builds it and runs nothing. A `requires_` would skip the build as well, and a test cannot pick its own runner, as the harness derives every test's from its target. A test is an `int main()`: exit 0 passes, nonzero fails, 77 skips (for a missing capability, never for a failed check). Each runs in its own process, in parallel, with a 60 s default timeout, and the output of a failed, crashed or timed-out test is in `build/test-logs/.log`; a later pass does not delete the log, so check its timestamp. What the tests need, in three groups: - Pure logic, no GPU: they stage `Device`'s statics or feed synthetic data to the decision functions that were factored out for them (`Device::ResolveFeatures`, `ChooseDevice`, `CheckShaderCapabilities`, `GetMemoryType`, `PreferDirectDeviceWrite`, `PipelineCacheDataCompatible`, `AlignMappedFlushRange`, `BuildMipChainFinalBarriers`, `SwapchainStageUnion`, `BuildTlasWriteBarrier`, `UIRenderer::ClipFlags`, `Window::SwapchainMinImageCount`, `WorkaroundNvidiaAS::Patch`, `DescriptorHeapVulkan::ComputeLayout`, `FontAtlas::Packer`, the font and input-field helpers). `PushConstantRewrite` and `UIFusedShader` compile GLSL with glslang and check the SPIR-V with spirv-val at runtime, and `ExampleShaders` compiles every GLSL shader under `examples/` the way crafter-build would, the descriptor-set build included, so a shader contract change that breaks an example fails here without building the example; `FontAtlasDecode` reads `ui-shared.glsl` and `dom-webgpu.js` and holds their copies of the SDF encoding constants to `FontAtlas`'s; `MouseScroll`, `PointerEnterLeave`, `InputTime` and `KeyboardKeymap` drive the Wayland listener callbacks directly (`KeyboardKeymap` with keymaps in memfds, each case in a child process), `TitleWayland` reads the requests a window sends off a `wl_display` connected to a socketpair, `TextInputContent` reads the text input's the same way and feeds its callbacks, and `ToplevelState` does both: it feeds the `xdg_toplevel` and `xdg_surface` configure callbacks of a window whose surfaces are proxies on such a display, and reads the version `xdg_wm_base` is bound at off the wire. `ConfigureResize` does the same for a configure's size: with a made-up swapchain handle it steps the two ends of a frame (`TakeDeferredSize` and `MatchSizesToScale`, `SendFrameSurfaceState`) and reads which commit gets the viewport's destination and the acknowledgement, and what the destination is when the scale changes in between. - A headless device: `Device::Initialize()` and no `Window` (`HeapSlotReuse`, `DeferredDeletion`, `MeshLifetime`, `ImageStagingRelease`, `BLASBuildOptions`, the `TLAS*` tests, ...). Headless still means a Wayland display on Linux. Most of the RT ones check `Device::rayTracingSupported` and return 77 without it; `BLASBuildOptions`, `TLASInstanceDirtyTracking` and `MeshDecompressStagingRelease` do not, and crash on a GPU without ray tracing (`Device::RequireRayTracing` throws out of `main`). `DeviceSelection` skips with one GPU. -- A window and a live compositor: `FrameLoopSync`, `SetupCmdBufferReuse`, `UIFallbackParity`, `SwapchainTransferDst`, `WindowUpdateClock`, `HeapASRead`, `HeapDynamicIndexHit`, `RTPassPushData`, `WindowOptionalGlobals` (hides xdg-decoration, viewporter and fractional scale from the window in turn), `SwapchainImageCount` (every present mode, and swapchains with more images than frames in flight, in child processes on llvmpipe where the host's GPU never makes one), `TextAntialiasing` (text through `DispatchText` and `DispatchFused` against stb_truetype's own antialiased rasterizer, at 14 and 64 px and stretched, plus a glyph mirrored by its UVs and empty texels shrunk below 4 px), `ResizeViewport` (a `Resize` and a configured size, got by maximizing its window for a moment, against the connection itself: it runs with `WAYLAND_DEBUG` set and stderr in a file and replays the log, which has the driver's attach and commit too), and `FeatureRequests` for its retry case. `UIFallbackParity`, `SwapchainTransferDst`, `HeapASRead`, `HeapDynamicIndexHit`, `RTPassPushData` and `TextAntialiasing` read the frame back with `Window::CaptureNextFrame` (a PNG, decoded with a private `STB_IMAGE_STATIC` copy of stb_image), `SwapchainImageCount` with a transfer pass of its own, and check pixels. The others read no frame back: they check what the frame loop, the device and the window report (their counts and members, the validation layer's count, the connection's protocol errors), and `ResizeViewport` the connection's log. +- A window and a live compositor: `FrameLoopSync`, `SetupCmdBufferReuse`, `UIFallbackParity`, `SwapchainTransferDst`, `WindowUpdateClock`, `HeapASRead`, `HeapDynamicIndexHit`, `RTPassPushData`, `WindowOptionalGlobals` (hides xdg-decoration, viewporter and fractional scale from the window in turn), `WindowConstructorThrow` (fails the swapchain's capabilities query inside a window's constructor through `Device::vkGetPhysicalDeviceSurfaceCapabilities2KHR`, and finds the failed window's destroy requests in a `WAYLAND_DEBUG` log, as `ResizeViewport` reads its log), `SwapchainImageCount` (every present mode, and swapchains with more images than frames in flight, in child processes on llvmpipe where the host's GPU never makes one), `TextAntialiasing` (text through `DispatchText` and `DispatchFused` against stb_truetype's own antialiased rasterizer, at 14 and 64 px and stretched, plus a glyph mirrored by its UVs and empty texels shrunk below 4 px), `ResizeViewport` (a `Resize` and a configured size, got by maximizing its window for a moment, against the connection itself: it runs with `WAYLAND_DEBUG` set and stderr in a file and replays the log, which has the driver's attach and commit too), and `FeatureRequests` for its retry case. `UIFallbackParity`, `SwapchainTransferDst`, `HeapASRead`, `HeapDynamicIndexHit`, `RTPassPushData` and `TextAntialiasing` read the frame back with `Window::CaptureNextFrame` (a PNG, decoded with a private `STB_IMAGE_STATIC` copy of stb_image), `SwapchainImageCount` with a transfer pass of its own, and check pixels. The others read no frame back: they check what the frame loop, the device and the window report (their counts and members, the validation layer's count, the connection's protocol errors), and `ResizeViewport` and `WindowConstructorThrow` the connection's log. Conventions the existing tests follow: @@ -87,7 +87,7 @@ Conventions the existing tests follow: A bug fix ships with a test that fails before the fix and passes after it. A change to a UI kernel keeps `UIFallbackParity` green: the heap and descriptor-set builds of one source must stay pixel-identical. A category drawn fused must also match the same category drawn standalone. `TextAntialiasing` compares the two for text, and keeps the text's edge ramp at one screen pixel; for quads, circles and images no test does (`UIFusedShader` only pins the push-constant layout): check those by eye, or add the comparison. -Cross targets: the Win32 tests run under Wine from the native crafter-build on the host, which has `wine` on its `PATH` and finds the host's mingw-w64 itself: `WINEPREFIX= crafter-build test --target=x86_64-w64-mingw32 PointerWin32 TextWin32 Win32Link`. The Flatpak has no `wine`, so there `PointerWin32` and `TextWin32` skip and only `Win32Link`'s link is checked. A Flatpak before crafter-build 5.0.0 links no Win32 executable: it gave clang the host's `/usr` as the MinGW sysroot, which put glibc's headers on the MinGW include path, and libstdc++'s `shared_ptr`, inlined from nlohmann/json in Crafter.Asset's GLB loader, then read glibc's `__libc_single_threaded` (Crafter.Build #43). For an aarch64 device, `crafter-build test --target=...` tries qemu, which has no Vulkan: build with the sysroot, copy the test's whole bin directory (binary, `*.spv`, `*.sets.spv`, fonts) to the device and run it there, unlocked and with the window visible, since a locked phone's compositor sends no frame callbacks and the FIFO present then blocks forever. +Cross targets: the Win32 tests run under Wine from the native crafter-build on the host, which has `wine` on its `PATH` and finds the host's mingw-w64 itself: `WINEPREFIX= crafter-build test --target=x86_64-w64-mingw32 PointerWin32 TextWin32 WindowConstructorThrowWin32 Win32Link`. The Flatpak has no `wine`, so there `PointerWin32`, `TextWin32` and `WindowConstructorThrowWin32` skip and only `Win32Link`'s link is checked. A Flatpak before crafter-build 5.0.0 links no Win32 executable: it gave clang the host's `/usr` as the MinGW sysroot, which put glibc's headers on the MinGW include path, and libstdc++'s `shared_ptr`, inlined from nlohmann/json in Crafter.Asset's GLB loader, then read glibc's `__libc_single_threaded` (Crafter.Build #43). For an aarch64 device, `crafter-build test --target=...` tries qemu, which has no Vulkan: build with the sysroot, copy the test's whole bin directory (binary, `*.spv`, `*.sets.spv`, fonts) to the device and run it there, unlocked and with the window visible, since a locked phone's compositor sends no frame callbacks and the FIFO present then blocks forever. ## Code style diff --git a/README.md b/README.md index ea407ea..c83ce08 100644 --- a/README.md +++ b/README.md @@ -124,6 +124,10 @@ shaded through an intersection shader with an any-hit cut-out. `window.scale` may be a newer one (#165). A window that draws on demand learns of the resize from `onFrameOwed`, which fires at the configure. + On Wayland and Win32 a `Window` constructor that throws (a Vulkan + error, a surface that offers no format the swapchain can be written + through as a storage image) leaves nothing of the window behind, so + the error can be caught (#169). - **Device** *(Vulkan only)* — single-instance bring-up targeting `VK_EXT_descriptor_heap`; pipelines are created with `VK_PIPELINE_CREATE_2_DESCRIPTOR_HEAP_BIT_EXT` so there are no diff --git a/implementations/Crafter.Graphics-Window.cpp b/implementations/Crafter.Graphics-Window.cpp index 02eded2..e3fbf61 100644 --- a/implementations/Crafter.Graphics-Window.cpp +++ b/implementations/Crafter.Graphics-Window.cpp @@ -359,7 +359,21 @@ Window::Window(std::uint32_t width, std::uint32_t height, const std::string_view SetTitle(title); } -Window::Window(std::uint32_t width, std::uint32_t height) : width(width), height(height) { +// Delegates to the default constructor, which makes nothing, so that the +// window is a complete object before the first step below. When a step +// throws (a Vulkan error, a surface that offers no storage-writable format), +// ~Window then runs before the exception leaves the constructor +// ([except.ctor]) and releases what had been made by then, as it does for a +// window made whole: a member not made by then is null or empty, and +// releases nothing. Without that, Device::windows, the HWND's GWLP_USERDATA +// and the proxies' listener data went on pointing at the window after the +// exception (#169). A Vulkan command that fails leaves its outputs without a +// defined value, so each handle goes into its member only once the call that +// makes it has succeeded, the command buffers excepted: an allocation that +// fails sets them to null. +Window::Window(std::uint32_t width, std::uint32_t height) : Window() { + this->width = width; + this->height = height; // Before the platform code below, which may report the pointer. lastMousePos = {0,0}; mouseDelta = {0,0}; @@ -415,6 +429,7 @@ Window::Window(std::uint32_t width, std::uint32_t height) : width(width), height wl_surface_commit(surface); #endif + VkSurfaceKHR madeSurface = VK_NULL_HANDLE; #ifdef CRAFTER_GRAPHICS_WINDOW_WIN32 // A Unicode class, so the text in WndProc's messages is UTF-16: WM_CHAR // brings UTF-16 code units, and SetTitle's WM_SETTEXT reaches @@ -471,7 +486,7 @@ Window::Window(std::uint32_t width, std::uint32_t height) : width(width), height createInfo.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR; createInfo.hinstance = wc.hInstance; createInfo.hwnd = hwnd; - Device::CheckVkResult(vkCreateWin32SurfaceKHR(Device::instance, &createInfo, NULL, &vulkanSurface)); + Device::CheckVkResult(vkCreateWin32SurfaceKHR(Device::instance, &createInfo, NULL, &madeSurface)); #endif #ifdef CRAFTER_GRAPHICS_WINDOW_WAYLAND @@ -479,8 +494,9 @@ Window::Window(std::uint32_t width, std::uint32_t height) : width(width), height createInfo.sType = VK_STRUCTURE_TYPE_WAYLAND_SURFACE_CREATE_INFO_KHR; createInfo.display = Device::display; createInfo.surface = surface; - Device::CheckVkResult(vkCreateWaylandSurfaceKHR(Device::instance, &createInfo, NULL, &vulkanSurface)); + Device::CheckVkResult(vkCreateWaylandSurfaceKHR(Device::instance, &createInfo, NULL, &madeSurface)); #endif + vulkanSurface = madeSurface; // Get list of supported surface formats std::uint32_t formatCount; @@ -558,6 +574,8 @@ Window::Window(std::uint32_t width, std::uint32_t height) : width(width), height cmdBufAllocateInfo.commandPool = Device::commandPool; cmdBufAllocateInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; cmdBufAllocateInfo.commandBufferCount = numFrames; + // Straight into the member: an allocation that fails frees what it had + // made and sets every entry to null. Device::CheckVkResult(vkAllocateCommandBuffers(Device::device, &cmdBufAllocateInfo, drawCmdBuffers)); // Per-frame-in-flight synchronisation objects (issue #40). The fences are @@ -572,8 +590,12 @@ Window::Window(std::uint32_t width, std::uint32_t height) : width(width), height fenceCreateInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; fenceCreateInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT; for (std::uint8_t i = 0; i < numFrames; i++) { - Device::CheckVkResult(vkCreateFence(Device::device, &fenceCreateInfo, nullptr, &waitFences[i])); - Device::CheckVkResult(vkCreateSemaphore(Device::device, &semaphoreCreateInfo, nullptr, &imageAcquiredSemaphores[i])); + VkFence fence = VK_NULL_HANDLE; + Device::CheckVkResult(vkCreateFence(Device::device, &fenceCreateInfo, nullptr, &fence)); + waitFences[i] = fence; + VkSemaphore semaphore = VK_NULL_HANDLE; + Device::CheckVkResult(vkCreateSemaphore(Device::device, &semaphoreCreateInfo, nullptr, &semaphore)); + imageAcquiredSemaphores[i] = semaphore; } // The deferred-deletion queue (issue #101) retires a resource after this @@ -1842,7 +1864,12 @@ void Window::CreateSwapchain() } imageViews.clear(); - Device::CheckVkResult(vkCreateSwapchainKHR(Device::device, &swapchainCI, nullptr, &swapChain)); + // Each handle reaches its member only once it is made, here and for the + // views below: ~Window releases what the members name, also after a + // constructor whose CreateSwapchain threw. + VkSwapchainKHR madeSwapchain = VK_NULL_HANDLE; + Device::CheckVkResult(vkCreateSwapchainKHR(Device::device, &swapchainCI, nullptr, &madeSwapchain)); + swapChain = madeSwapchain; // If an existing swap chain is re-created, destroy the old swap chain and the ressources owned by the application (image views, images are owned by the swap chain) if (oldSwapchain != VK_NULL_HANDLE) { @@ -1864,7 +1891,11 @@ void Window::CreateSwapchain() // A render-finished semaphore per image. The ones the old swapchain's // images used are kept: its last presents may still be waiting on them. + // The vector has room for all of them before the first is made: a + // push_back that grew it, and threw, would leave the semaphore just made + // in no member, where ~Window does not find it. const VkSemaphoreCreateInfo semaphoreCreateInfo { .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO }; + renderFinishedSemaphores.reserve(imageCount); while (renderFinishedSemaphores.size() < imageCount) { VkSemaphore semaphore = VK_NULL_HANDLE; Device::CheckVkResult(vkCreateSemaphore(Device::device, &semaphoreCreateInfo, nullptr, &semaphore)); @@ -1901,7 +1932,9 @@ void Window::CreateSwapchain() // once per frame whose image changed. imageViews.resize(imageCount); for (std::uint32_t i = 0; i < imageCount; i++) { - Device::CheckVkResult(vkCreateImageView(Device::device, &imageViewInfos[i], nullptr, &imageViews[i])); + VkImageView view = VK_NULL_HANDLE; + Device::CheckVkResult(vkCreateImageView(Device::device, &imageViewInfos[i], nullptr, &view)); + imageViews[i] = view; } } diff --git a/interfaces/Crafter.Graphics-Window.cppm b/interfaces/Crafter.Graphics-Window.cppm index 2d263fb..c2a3452 100644 --- a/interfaces/Crafter.Graphics-Window.cppm +++ b/interfaces/Crafter.Graphics-Window.cppm @@ -173,6 +173,12 @@ export namespace Crafter { #endif Window() = default; + // On Wayland and Win32 a constructor that throws (a Vulkan error, a + // surface that offers no format the swapchain can be written through + // as a storage image) leaves nothing of the window behind: ~Window + // has released what it had made by the time the exception reaches + // the caller, so the error can be caught and the program go on + // (#169). Window(std::uint32_t width, std::uint32_t height); Window(std::uint32_t width, std::uint32_t height, const std::string_view title); Window(Window&) = delete; diff --git a/project.cpp b/project.cpp index 164f179..4d0a706 100644 --- a/project.cpp +++ b/project.cpp @@ -420,6 +420,16 @@ extern "C" Configuration CrafterBuildProject(std::span a #endif cfg.tests.push_back(std::move(win32TextTest)); + // Issue #169 on Win32, as WindowConstructorThrow on Wayland: fails + // the swapchain's capabilities query of a window's constructor + // and checks that the HWND it had made and its Vulkan surface + // were destroyed. Needs what PointerWin32 needs. + Test win32ThrowTest = LibraryTest("WindowConstructorThrowWin32"); + #ifndef _WIN32 + win32ThrowTest.requires_ = { "tool:wine" }; + #endif + cfg.tests.push_back(std::move(win32ThrowTest)); + // A Win32 executable that uses the library as an application does // links: the vulkan-1 import library made above and -luuid (#184). // The Win32 library itself is only archived, and the tests above @@ -632,6 +642,17 @@ extern "C" Configuration CrafterBuildProject(std::span a // Needs the Wayland backend and a real compositor. cfg.tests.push_back(LibraryTest("WindowOptionalGlobals")); + // Issue #169: a Window whose constructor throws leaves nothing + // behind. Makes a window beside another and fails its + // swapchain's capabilities query, through + // Device::vkGetPhysicalDeviceSurfaceCapabilities2KHR, then checks + // that Device::windows holds only the other window and that the + // failed one's Vulkan surface and Wayland objects were destroyed + // before the exception reached the caller (the Wayland objects + // read off WAYLAND_DEBUG in a file, as ResizeViewport does). + // Needs the Wayland backend and a real compositor. + cfg.tests.push_back(LibraryTest("WindowConstructorThrow")); + // Issue #199, on a live connection: at every commit of the // window's surface the viewport's destination in effect is the // size of the buffer in effect, and every acknowledgement of a diff --git a/tests/WindowConstructorThrow/main.cpp b/tests/WindowConstructorThrow/main.cpp new file mode 100644 index 0000000..932ad17 --- /dev/null +++ b/tests/WindowConstructorThrow/main.cpp @@ -0,0 +1,274 @@ +//SPDX-License-Identifier: LGPL-3.0-only +//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +// Issue #169, on Wayland: a Window whose constructor throws leaves nothing +// behind. The constructor puts the window in Device::windows, and gives its +// xdg_surface, its xdg_toplevel and its fractional scale the window as +// listener data, before the steps that can throw: the Vulkan surface, the +// surface's formats and capabilities, the swapchain. ~Window, which takes all +// of that back, did not run for a window whose constructor threw, and the +// exception released the window's storage. An application that caught the +// error and carried on had a dangling pointer in Device::windows, which the +// event loop and the seat's enter events walk, and proxies whose events are +// dispatched into the freed window; the Vulkan surface leaked. +// +// The test makes the constructor throw from its CreateSwapchain, once all of +// the above but the swapchain has been made: with +// Device::surfaceMaintenance1Supported set, the swapchain's capabilities are +// asked for through Device::vkGetPhysicalDeviceSurfaceCapabilities2KHR, +// where the test puts a function of its own that fails with +// VK_ERROR_SURFACE_LOST_KHR. Another window stays open throughout. Checked: +// +// - the constructor throws the error Device::CheckVkResult makes of that +// result +// - afterwards Device::windows holds the other window and nothing else +// - before the exception reached the test, the Vulkan surface the window +// had made was destroyed (the test defines vkDestroySurfaceKHR, which +// the library calls by name, and passes each call on to the loader), and +// so was each of its Wayland objects: its wl_surface, xdg_surface and +// xdg_toplevel, and its wp_fractional_scale_v1, +// zxdg_toplevel_decoration_v1 and wp_viewport where the compositor offers +// their globals. The test runs with WAYLAND_DEBUG set and stderr in a +// file, as ResizeViewport does, and finds each object's destroy request +// in that log between the failure and the catch +// - the compositor raises no protocol error over it +// - a window made after it renders and closes, and the other window +// renders throughout +// - the validation layer reports no error (only with +// CRAFTER_GRAPHICS_VALIDATION set) +// +// The checks of the failed window come before the test dispatches the +// connection's events again: without the fix, an enter event can walk the +// freed window in Device::windows from there on, so those checks report +// first. The log is kept when a check fails. Needs a live Wayland compositor +// and a Vulkan device. + +#include +#include +#include +#include +#include +#include +#include "vulkan/vulkan.h" + +import Crafter.Graphics; +import std; +using namespace Crafter; +namespace fs = std::filesystem; + +namespace { + +int failures = 0; + +// Each line flushed as it is printed: without the fix the test can crash +// once it dispatches events again, and stdout into crafter-build's pipe would +// lose the lines of the checks before. +void Check(bool ok, std::string_view what) { + std::println("{} {}", ok ? "PASS" : "FAIL", what); + std::fflush(stdout); + if (!ok) ++failures; +} + +// stderr into `path` while it lives, where libwayland writes WAYLAND_DEBUG. +struct StderrTo { + int saved = -1; + explicit StderrTo(const fs::path& path) { + std::fflush(stderr); + const int file = open(path.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600); + if (file < 0) return; + saved = dup(STDERR_FILENO); + dup2(file, STDERR_FILENO); + close(file); + } + ~StderrTo() { + std::fflush(stderr); + if (saved < 0) return; + dup2(saved, STDERR_FILENO); + close(saved); + } +}; + +// A line the test writes into the log between libwayland's. +void Mark(std::string_view name) { + std::println(stderr, "MARK {}", name); + std::fflush(stderr); +} + +// A roundtrip fails, and the display keeps the error, once the compositor +// has raised a protocol error over anything sent before it. +bool NoProtocolError() { + return wl_display_roundtrip(Device::display) != -1 && wl_display_get_error(Device::display) == 0; +} + +// A Wayland object, as WAYLAND_DEBUG names it. +struct Proxy { + std::string interface; + std::uint32_t id = 0; +}; + +// What the failing capabilities query saw of the window being made. +struct Failed { + int calls = 0; + std::uintptr_t window = 0; + VkSurfaceKHR surface = VK_NULL_HANDLE; + std::vector proxies; +}; +Failed failed; + +// Every surface the library passed to vkDestroySurfaceKHR, in order. +std::vector destroyedSurfaces; + +VkResult FailCapabilities(VkPhysicalDevice, const VkPhysicalDeviceSurfaceInfo2KHR* info, VkSurfaceCapabilities2KHR*) { + ++failed.calls; + // The window being made: its constructor put it in Device::windows + // first thing, behind the other window. + const Window* window = Device::windows.back(); + failed.window = reinterpret_cast(window); + failed.surface = info->surface; + for (void* object : { static_cast(window->surface), static_cast(window->xdgSurface), + static_cast(window->xdgToplevel), static_cast(window->wp_scale), + static_cast(window->decoration), static_cast(window->wpViewport) }) { + if (object == nullptr) continue; + wl_proxy* proxy = static_cast(object); + failed.proxies.push_back({ wl_proxy_get_class(proxy), wl_proxy_get_id(proxy) }); + } + Mark("fail"); + return VK_ERROR_SURFACE_LOST_KHR; +} + +// The log's lines from the mark `from` to the mark `to`. +std::vector LinesBetween(const fs::path& log, std::string_view from, std::string_view to) { + std::vector lines; + std::ifstream file(log); + bool inside = false; + for (std::string line; std::getline(file, line);) { + if (line == std::format("MARK {}", from)) { + inside = true; + } else if (line == std::format("MARK {}", to)) { + break; + } else if (inside) { + lines.push_back(std::move(line)); + } + } + return lines; +} + +// A request line destroys `proxy`: +// [09:41:07.118030] {Default Queue} -> xdg_toplevel#25.destroy() +// Older libwayland writes an `@` for the `#`. +bool DestroyedIn(const std::vector& lines, const Proxy& proxy) { + return std::ranges::any_of(lines, [&](const std::string& line) { + return line.contains(std::format("-> {}#{}.destroy(", proxy.interface, proxy.id)) + || line.contains(std::format("-> {}@{}.destroy(", proxy.interface, proxy.id)); + }); +} + +} // namespace + +// The library calls vkDestroySurfaceKHR by name, so it reaches this +// definition, which notes the surface and passes the call on to the loader's. +extern "C" VKAPI_ATTR void VKAPI_CALL vkDestroySurfaceKHR(VkInstance instance, VkSurfaceKHR surface, const VkAllocationCallbacks* allocator) { + destroyedSurfaces.push_back(surface); + static const auto next = reinterpret_cast(dlsym(RTLD_NEXT, "vkDestroySurfaceKHR")); + if (next != nullptr) next(instance, surface, allocator); +} + +int main() { + const fs::path log = fs::temp_directory_path() / std::format("crafter-window-constructor-throw-{}.log", getpid()); + // Read when the display connects, in Device::Initialize. libwayland + // colours the log when FORCE_COLOR says so, also into a file. + setenv("WAYLAND_DEBUG", "1", 1); + unsetenv("FORCE_COLOR"); + setenv("NO_COLOR", "1", 1); + + std::optional thrown; + std::optional unexpected; + { + StderrTo redirect(log); + try { + Device::Initialize(); + Device::validationErrorCount = 0; + + Window other(160, 120, "WindowConstructorThrow: the other window"); + for (int i = 0; i < Window::numFrames; ++i) other.Render(); + + const bool surfaceMaintenance1 = Device::surfaceMaintenance1Supported; + const PFN_vkGetPhysicalDeviceSurfaceCapabilities2KHR capabilities2 = Device::vkGetPhysicalDeviceSurfaceCapabilities2KHR; + Device::surfaceMaintenance1Supported = true; + Device::vkGetPhysicalDeviceSurfaceCapabilities2KHR = FailCapabilities; + std::size_t destroyedAtCatch = 0; + try { + auto window = std::make_unique(320, 240, "WindowConstructorThrow: the window that fails"); + } catch (const std::runtime_error& error) { + Mark("caught"); + thrown = error.what(); + destroyedAtCatch = destroyedSurfaces.size(); + } + Device::surfaceMaintenance1Supported = surfaceMaintenance1; + Device::vkGetPhysicalDeviceSurfaceCapabilities2KHR = capabilities2; + + Check(thrown == "VK_ERROR_SURFACE_LOST_KHR", + std::format("the constructor throws the error of the failed query (threw: {})", thrown.value_or("nothing"))); + Check(failed.calls == 1 && failed.window != 0 && failed.window != reinterpret_cast(&other), + std::format("the query failed once, inside the window's constructor ({} calls)", failed.calls)); + std::vector listed; + for (const Window* window : Device::windows) listed.push_back(reinterpret_cast(window)); + Check(listed == std::vector{ reinterpret_cast(&other) }, + std::format("Device::windows holds the other window and nothing else ({} entries, the failed window {})", + listed.size(), std::ranges::contains(listed, failed.window) ? "among them" : "not among them")); + Check(failed.surface != VK_NULL_HANDLE + && std::ranges::contains(std::span(destroyedSurfaces).first(destroyedAtCatch), failed.surface), + "the failed window's Vulkan surface was destroyed before the exception reached the caller"); + // The objects the failed window made, each destroyed between the + // moment it failed and the catch: by ~Window, as the exception + // left the constructor. Read before the connection's events are + // dispatched again, as everything above is: where the window is + // still in Device::windows, the seat's enter events walk it there. + const std::vector unwinding = LinesBetween(log, "fail", "caught"); + std::vector names; + for (const Proxy& proxy : failed.proxies) names.push_back(proxy.interface); + Check(std::ranges::contains(names, "wl_surface") && std::ranges::contains(names, "xdg_surface") && std::ranges::contains(names, "xdg_toplevel"), + std::format("the failed window had made its Wayland objects when it failed: {}", names)); + for (const Proxy& proxy : failed.proxies) { + Check(DestroyedIn(unwinding, proxy), + std::format("its {}#{} was destroyed before the exception reached the caller", proxy.interface, proxy.id)); + } + + Check(NoProtocolError(), "no protocol error after the failed constructor"); + + { + Window after(320, 240, "WindowConstructorThrow: the window after"); + for (int i = 0; i < Window::numFrames * 2; ++i) { + after.Render(); + other.Render(); + } + Device::CheckVkResult(vkQueueWaitIdle(Device::queue)); + } + other.Render(); + Device::CheckVkResult(vkQueueWaitIdle(Device::queue)); + Check(NoProtocolError(), "a window made after it renders and closes, beside the other window, with no protocol error"); + wl_display_flush(Device::display); + } catch (const std::exception& error) { + unexpected = error.what(); + } + } + if (unexpected) { + std::println("FAIL the run threw: {}", *unexpected); + std::println(" the log is {}", log.string()); + return EXIT_FAILURE; + } + + if (std::getenv("CRAFTER_GRAPHICS_VALIDATION") != nullptr) { + Check(Device::validationErrorCount == 0, + std::format("no Vulkan validation errors ({} seen)", Device::validationErrorCount)); + } + if (failures != 0) { + std::println("{} check(s) failed", failures); + std::println("the log is {}", log.string()); + return EXIT_FAILURE; + } + std::error_code ignored; + fs::remove(log, ignored); + std::println("all checks passed"); + return EXIT_SUCCESS; +} diff --git a/tests/WindowConstructorThrowWin32/main.cpp b/tests/WindowConstructorThrowWin32/main.cpp new file mode 100644 index 0000000..dc92a62 --- /dev/null +++ b/tests/WindowConstructorThrowWin32/main.cpp @@ -0,0 +1,140 @@ +//SPDX-License-Identifier: LGPL-3.0-only +//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +// Issue #169, on Win32: a Window whose constructor throws leaves nothing +// behind. The constructor makes the HWND, whose WM_NCCREATE puts the window +// in GWLP_USERDATA, and shows it, before the steps that can throw: the +// Vulkan surface, the surface's formats and capabilities, the swapchain. +// ~Window, which detaches the HWND and destroys it and the Vulkan surface, +// did not run for a window whose constructor threw, and the exception +// released the window's storage: the HWND stayed on screen with +// GWLP_USERDATA pointing at the freed window, which WndProc reads and writes +// for the messages it handles, and the Vulkan surface leaked. +// +// As WindowConstructorThrow does on Wayland, the test fails the swapchain's +// capabilities query of the constructor: with +// Device::surfaceMaintenance1Supported set, the query goes through +// Device::vkGetPhysicalDeviceSurfaceCapabilities2KHR, where the test puts a +// function of its own that fails with VK_ERROR_SURFACE_LOST_KHR. Another +// window stays open throughout. Checked: +// +// - the constructor throws the error Device::CheckVkResult makes of that +// result +// - the HWND it had made was destroyed +// - its Vulkan surface was destroyed before the exception reached the +// caller (the test defines vkDestroySurfaceKHR, which the library calls +// by name, and passes each call on to vulkan-1.dll's) +// - a window can be made after it +// +// Built on Linux, it runs under Wine: +// crafter-build test --target=x86_64-w64-mingw32 WindowConstructorThrowWin32 + +#include +#include +#include +#include "vulkan/vulkan.h" + +import Crafter.Graphics; +import std; +using namespace Crafter; + +namespace { + +int failures = 0; + +// Each line flushed as it is printed: without the fix the window that failed +// is still there for the messages pumped after the checks, which can crash +// the test, and a buffered stdout would lose the lines before. +void Check(bool ok, std::string_view what) { + std::println("{} {}", ok ? "PASS" : "FAIL", what); + std::fflush(stdout); + if (!ok) ++failures; +} + +// The other window's HWND, set before the query is made to fail. +HWND otherHwnd = nullptr; + +// What the failing capabilities query saw of the window being made. +struct Failed { + int calls = 0; + HWND hwnd = nullptr; + LONG_PTR userData = 0; + VkSurfaceKHR surface = VK_NULL_HANDLE; +}; +Failed failed; + +// Every surface the library passed to vkDestroySurfaceKHR, in order. +std::vector destroyedSurfaces; + +// The window being made: of the other window's class, on this thread, and +// not the other window. +BOOL CALLBACK FindMade(HWND hwnd, LPARAM) { + if (hwnd != otherHwnd && GetClassLongPtrW(hwnd, GCW_ATOM) == GetClassLongPtrW(otherHwnd, GCW_ATOM)) { + failed.hwnd = hwnd; + failed.userData = GetWindowLongPtrW(hwnd, GWLP_USERDATA); + } + return TRUE; +} + +VkResult VKAPI_CALL FailCapabilities(VkPhysicalDevice, const VkPhysicalDeviceSurfaceInfo2KHR* info, VkSurfaceCapabilities2KHR*) { + ++failed.calls; + failed.surface = info->surface; + EnumThreadWindows(GetCurrentThreadId(), FindMade, 0); + return VK_ERROR_SURFACE_LOST_KHR; +} + +} // namespace + +// The library calls vkDestroySurfaceKHR by name, so it reaches this +// definition, which notes the surface and passes the call on to +// vulkan-1.dll's. +extern "C" VKAPI_ATTR void VKAPI_CALL vkDestroySurfaceKHR(VkInstance instance, VkSurfaceKHR surface, const VkAllocationCallbacks* allocator) { + destroyedSurfaces.push_back(surface); + static const auto next = reinterpret_cast( + reinterpret_cast(GetProcAddress(GetModuleHandleW(L"vulkan-1.dll"), "vkDestroySurfaceKHR"))); + if (next != nullptr) next(instance, surface, allocator); +} + +int main() { + Device::Initialize(); + auto other = std::make_unique(160, 120, "WindowConstructorThrowWin32: the other window"); + otherHwnd = other->hwnd; + + const bool surfaceMaintenance1 = Device::surfaceMaintenance1Supported; + const PFN_vkGetPhysicalDeviceSurfaceCapabilities2KHR capabilities2 = Device::vkGetPhysicalDeviceSurfaceCapabilities2KHR; + Device::surfaceMaintenance1Supported = true; + Device::vkGetPhysicalDeviceSurfaceCapabilities2KHR = FailCapabilities; + std::optional thrown; + std::size_t destroyedAtCatch = 0; + try { + auto window = std::make_unique(320, 240, "WindowConstructorThrowWin32: the window that fails"); + } catch (const std::runtime_error& error) { + thrown = error.what(); + destroyedAtCatch = destroyedSurfaces.size(); + } + Device::surfaceMaintenance1Supported = surfaceMaintenance1; + Device::vkGetPhysicalDeviceSurfaceCapabilities2KHR = capabilities2; + + Check(thrown == "VK_ERROR_SURFACE_LOST_KHR", + std::format("the constructor throws the error of the failed query (threw: {})", thrown.value_or("nothing"))); + Check(failed.calls == 1 && failed.hwnd != nullptr && failed.userData != 0, + std::format("the query failed once, inside the constructor of a window whose HWND names it ({} calls)", failed.calls)); + Check(failed.hwnd != nullptr && !IsWindow(failed.hwnd), "the failed window's HWND was destroyed"); + Check(failed.surface != VK_NULL_HANDLE + && std::ranges::contains(std::span(destroyedSurfaces).first(destroyedAtCatch), failed.surface), + "the failed window's Vulkan surface was destroyed before the exception reached the caller"); + + auto after = std::make_unique(320, 240, "WindowConstructorThrowWin32: the window after"); + const HWND afterHwnd = after->hwnd; + Check(IsWindow(afterHwnd) && IsWindow(otherHwnd), "a window can be made after it, beside the other window"); + after.reset(); + other.reset(); + Check(!IsWindow(afterHwnd) && !IsWindow(otherHwnd), "and both close"); + + if (failures != 0) { + std::println("{} check(s) failed", failures); + return EXIT_FAILURE; + } + std::println("all checks passed"); + return EXIT_SUCCESS; +}