mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-21 05:46:03 +00:00
feat: non-Adreno graphics stack (Venus, open driver pairs, gamescope patches) (#2029)
* Retain compositor resources when GPU completion is unconfirmed * Stop quarantined GPU callers before retries and mapped writes * Support Android hardware-buffer presentation over Wayland * Support PowerVR swapchains and linear image imports in Gamescope * Bundle verified PowerVR graphics components through existing build preparation * Detect and select the system Vulkan backend on PowerVR * Apply PowerVR Steam and game compatibility during normal launches * Show PowerVR support through existing driver and component controls * Update existing hardware guidance for system Vulkan support * Import the shared system Vulkan readiness check * Discover and propagate the actual PowerVR render node * Prune obsolete PowerVR runtimes after guest processes exit * Retain external DMA-BUF ownership after GPU quarantine * Name the PowerVR HAL selection explicitly * Isolate component UI tests from application startup * Cover the inherited FEX preset in PowerVR profile tests * Log test worker failures for CI diagnosis * Remove temporary test logging after diagnostic CI * Prefer system dependencies for the Android Vulkan loader * Capture raw stderr before test worker termination * Remove the temporary test worker crash probe * Import pinned DXVK recipe prerequisite from PowerVR PR570 Copy only the standalone build recipe, source pin, BC-format prerequisite and presentation-sync patch/check from wallentx/DroidDeck atd0f7264ea8. Source: https://github.com/Droid-Deck/DroidDeck/pull/570 Preserve that proposal attribution; no Android app, compositor, managed pack, private data or fork development history is imported. * Add opt-in low32 GPU mapping adapter and integrity probes * Add opt-in D3D9 single-sample workaround and fix HUD texel format * Document verified production game workaround and publication scope * Restrict reset diagnostics and create private output atomically * Target official runtime review and document PR570 prerequisite provenance * Fix runtime tool output isolation, mmap64 chaining and DST ambiguity * Normalize swapchain backbuffers for the opt-in D3D9 single-sample path * Experimental Samsung Xclipse support on the system Vulkan path Detect Samsung's Vulkan HAL (vulkan.samsung.so) and its sgpu render node alongside PowerVR, and run Xclipse through the same libhybris bridge: - VK_LAYER_DROIDDECK_xclipse (tools/linuxfs/xclipse-layer), built with the glibc preloads and enabled only on Xclipse: sets bionic's environ for the driver's shader compiler, avoids immutable YCbCr samplers in compute layouts, forwards the KHR calibrated-timestamp entry points to the EXT ones, and reports textureCompressionBC and BC4/BC5 filtering over the compat layer's BC emulation. - Upstream DXVK 2.6.2, pinned as a tar.gz component and selected on Xclipse: the driver has 128 bytes of push constants, DXVK 3 needs 256. - android_wlegl accepts a zero stride and passes it through unchanged: Samsung's gralloc records none for GPU-only buffers. Tested on a Galaxy A56 (Xclipse 540, driver 24.0.560): Steam Big Picture and PICO PARK (D3D9). * Xclipse layer: copy the device chain and track samplers per device - Clear textureCompressionBC in a copy of the device-create chain (every structure up to the VkPhysicalDeviceFeatures2 that enables it) instead of writing the caller's structure; a chain led by a structure of unknown size is passed on unchanged. - Track YCbCr samplers per device in a growable list, drop them on vkDestroySampler and device teardown, and fail sampler creation rather than leave one untracked when the list cannot grow. - Fail descriptor set layout creation with VK_ERROR_OUT_OF_HOST_MEMORY when a replacement sampler array cannot be allocated, instead of passing the original YCbCr samplers to the driver. * Xclipse layer: copy any device-chain structure the headers define The chain copy that clears the emulated textureCompressionBC only knew a handful of structure sizes, so a valid chain such as VkPhysicalDeviceTimelineSemaphoreFeatures -> VkPhysicalDeviceFeatures2 was passed on unchanged and the compat layer refused the bit. Size every structure that may extend VkDeviceCreateInfo from a table generated from the Vulkan registry (gen_device_chain.py, Vulkan-Headers 1.3.275, the headers the build compiles with), and copy onto the heap instead of a fixed buffer. Only a structure newer than those headers still passes the chain unchanged. Add a regression test that runs the layer between a simulated loader and a mock driver: the timeline-semaphore chain, pEnabledFeatures, an unknown structure, the caller's structures left untouched, per-device YCbCr sampler tracking with handle reuse, and the KHR calibrated-timestamp forwarding. CI installs libvulkan-dev for it. * Mali bridge (#517, by ASEbrahim) on the non-Adreno test branch Squash of Droid-Deck/DroidDeck#517 (ASEbrahim/DroidDeck mali-bridge @6b823341): the Vulkan bridge (tools/vkbridge) that runs the guest's Vulkan on the phone's own driver, with BC1-BC7, clip/cull distance, vertex-divisor and depth-clip emulation and dma-heap memory sharing for Mali. All of the bridge is ASEbrahim's work; squashed only to carry it on this test branch. Combined with #570 on this branch, a device draws through exactly one path: - Adreno: Turnip, unchanged (checked first; the bridge setting is ignored there). - PowerVR / Xclipse with the system HAL and a render node: the system-Vulkan path (#570). - Anything else with the Setup toggle on (Mali): the bridge. * Test branch: keep #570's DXVK build recipe so its pinned PowerVR components verify #602 adds output checks to tools/dxvk/build.sh; tools/powervr/fetch.py pins the exact recipe the published PowerVR DXVK was built from, so the branch carries #570's copy. * Test branch: make #570, #602 and #560/#561 pass each other's tests - tools/dxvk/build.sh: #602's copy (its output checks) and the PowerVR pin in tools/powervr/release.json moved to that file's hash; the recipe's outputs are unchanged. - droiddeck-session: the presentation block sets _bl_cef for #570's PowerVR path, and the UI block keeps main's order, defaulting to -cef-use-angle=vulkan when the block has not run. - Compositor test harnesses: AHardwareBuffer stubs for #570's AHB import, and a stub for vkp_effects_forget_image (main #597) that #561's caller harness predates. * Auto drivers for Mali and Xclipse on the non-Adreno test branch Auto now picks an open driver pair for the GPU, the way it does for Adreno: - Mali (no KGSL, /dev/mali0): the GPU's name ("Mali-G720-Immortalis MC12", from the vendor Vulkan driver or kbase's gpuinfo) picks the PanVK build: G52-G78 (Job Manager), G610/G710, G615 or G720. A Mali none of them covers (G925...), or one whose pair is not published yet, draws through the Mali bridge, switched on by Auto. - Xclipse keeps the system-driver path as Auto; the RADV pair is offered as a manual choice. - The pairs come from The412Banner/droiddeck-nonadreno-drivers (one pre-release per driver, each a DriverBundle zip). Only a device without an Adreno reads that repo. - The importers accept PanVK and RADV libraries (libvulkan_panfrost / libvulkan_radeon). - An open driver pair and the Mali bridge are alternatives: a selected pair turns the bridge off. - TU_DEBUG is only set for Turnip, on an Adreno. Every new branch is reached only when the device has no Adreno; an Adreno's detection, release sources, Auto choice and session environment are unchanged. * Auto: the one-binary PanVK kbase build for Mali v9-v13 on Android 15+ The412Banner/droiddeck-nonadreno-drivers adds panvk-mali-kbase: one PanVK build for G57/G68/G77/G78, G610/G710, G615/G715, G720/G725 and G925, whose display half needs Android 15. On Android 15+ Auto prefers it for every Mali it covers; below 15, and whenever its release is not listed, Auto falls back to the GPU generation's own pair. G52/G76 keep the Job Manager build; a G715/G725/G925 below Android 15, or any Mali no pair covers, draws through the bridge. Every pair stays selectable by hand. * Test: the G925 is in the kbase build's family now * Offer faux123's device PanVK builds (RP4 Pro, Ace, RG556) as manual pairs for their Mali * Detailed graphics logs for non-Adreno test reports - graphics-report.txt in every session folder: the graphics path the session draws with and why (Turnip, system Vulkan #570, Mali bridge #517, or an open driver pair with its release), the driver mode and choices, what Auto would pick, the GPU (family, Vulkan device name, kbase gpuinfo, Android, SoC, kernel), the GPU nodes the app can see (access, device numbers, SELinux label; nothing is opened) and the guest's graphics environment. At the end it adds the compositor's driver lines from app.log and the game launches that were logged. - vulkan-summary.txt: the session's own vulkaninfo --summary with the driver as exported, in the background with a 10 s timeout. - Per-game logs under games/<time>-<appid>/: Proton's log, DXVK's and vkd3d-proton's, Mesa's and PanVK's startup messages and the launch environment, from droiddeck-game-env. Each file is cut to 20 MB and the folder to 120 MB at the session's end. - The per-game logs and the Vulkan summary are on for a GPU that is not an Adreno, and on an Adreno only with Setup's new "Detailed graphics logs" switch. Share logs already takes the whole session folder, so all of it is in the zip, scrubbed as before. * Mali pairs: a stand-in render node, the driver's real library name, and a Mali known by its chip - Auto on Jim's Dimensity 9300+ chose the bridge: the GPU had no name (the app had not asked Vulkan yet and kbase's gpuinfo is unreadable under SELinux), so a Mali-G720 counted as a Mali no build covers. The name now falls back to the GPU the chip is known to carry (Dimensity, Helio, Kompanio, Tensor); and when nothing names it, Auto asks the vendor Vulkan driver off the main thread before it settles for the bridge. Auto logs what it decided and why. - An open Mali driver pair gets /dev/mali0 as the guest's render node, as the bridge does (bindGpuNode, BL_DRM_STANDIN): gamescope needs the node the driver reports. The session shim only answers libdrm's PRIME and GEM-close calls on it, which PanVK on kbase never makes. - A PanVK or RADV runtime half is installed as libvulkan_panfrost.so / libvulkan_radeon.so rather than under Turnip's name; Turnip keeps libvulkan_freedreno.so. - graphics-report.txt names the render node the guest got, adds the session script's driver lines and flags a failed Mali-bridge self-test at the top. * Auto takes the RADV pair on a Samsung Xclipse, with the system route as its fallback A tester's Galaxy S24 FE (Xclipse 940) boots to Steam with the RADV-Xclipse pair, where the system-driver route fails at Steam's OpenGL (glamor and GLX cannot load a driver). Auto now downloads and selects RADV on an Xclipse like the Mali pairs, and falls back to the system route only when RADV is not published. #570's reset of both drivers at each start no longer undoes an open driver pair. PowerVR (vulkan.powervr.so) keeps the system driver as before. * An Exynos with a Mali is a Mali, not an Xclipse The system route took vulkan.samsung.so as Samsung's Xclipse, but an Exynos 1280/1380 (Galaxy Tab S9 FE: Mali-G68) may name its HAL the same; with /dev/mali0 present that HAL is not the system route's, and the device is detected as the Mali it is. The chip table adds the Exynos 1380 and 1280 (s5e8835, s5e8825: Mali-G68). * Auto fetches the open drivers itself; Xclipse named as such; sound and frame-gen in the logs - Auto looks online again when its saved release list predates this device's open drivers, so a Samsung or Mali phone gets its pair without pressing refresh first. - A Samsung Xclipse is labelled "Samsung Xclipse" (not PowerVR), with its own support line. - Per-game logs add audio-streams.txt: PulseAudio's sink inputs 20 s and 60 s into the launch, so a silent game shows whether its stream reached Pulse. - graphics-report.txt states the frame-generation setting and keeps the LSFG gate, FrameGen and audio lines from app.log. * Client sound retries a briefly disconnected AAudio; kbase ioctl refusals explained in the report A Galaxy S24 FE's session had no sound at all: the DirectAudio sink's AAudio stream opened with AAUDIO_ERROR_DISCONNECTED while the output route was still changing at session start, and the plain AAudio fallback failed the same moment. The sink guard now retries DirectAudio, then the plain sink, five times over ten seconds and says which one it got. graphics-report.txt keeps the client-sink and kbase lines, and explains a KBASE_IOCTL_MEM_EXEC_INIT EPERM as the kbase driver's own answer rather than the session's sandbox. * Mali pairs draw the display on the phone's own Mali driver; Xwayland falls back without glamor - Testers' Mali pairs got the guest drawing (gamescope on the stand-in node, Zink on PanVK) but the compositor's PanVK Android half failed on Mali gralloc: it probes AHB formats 0x38/0x3b that mali_gralloc does not have, and "vkCreateImage w/ native buffer failed". Under Auto a Mali pair now leaves the display on the phone's own Vulkan driver (dma-buf, modifiers and AHB all pass the testers' checks) and runs the pair's PanVK in the guest; the Android half stays installed for a manual pick. "Pair in use" now follows the runtime half. - A session after one whose Xwayland crashed (segfault, then gamescope's X11 I/O error) starts Xwayland with XWAYLAND_NO_GLAMOR=1 on a non-Adreno device, and says so in app.log. - graphics-report.txt names the display driver the compositor used, and keeps gralloc, dma-buf, modifier and import lines from app.log and Xwayland's own lines from the session log. * Non-Adreno sound: the daemon falls back on its own; the build's commit in device.txt and the report The S24 FE's session still had no sound: its AAudio refuses DirectAudio's low-latency stream with AAUDIO_ERROR_DISCONNECTED, and the sink guard never got to retry because pactl did not reach the daemon in time ("the daemon did not answer in 15 s"). On a GPU that is not an Adreno the daemon's own start-up script now asks DirectAudio again without low latency and loads the plain AAudio sink underneath it, so a default sink exists whatever pactl does. device.txt and graphics-report.txt name the build label and source commit, so a log says which build it came from. * Non-Adreno sound: no second DirectAudio load (it hung the daemon); the plain AAudio sink underneath On the S24 FE the daemon stopped after DirectAudio's failed low-latency load: the second DirectAudio load in the same daemon never returned, so nothing after it ran and pactl never connected. The daemon now loads only the plain AAudio sink (no low latency) after DirectAudio, inside .nofail, and sets whichever exists as the default. * gamescope: explicit sync off where the kernel or the stand-in node cannot signal its timelines Adds tools/gamescope/patches/0126 (GAMESCOPE_DISABLE_EXPLICIT_SYNC=1 for the nested backends) and sets it on a GPU that is not an Adreno when the kernel is older than 6.6 (no DRM_IOCTL_SYNCOBJ_EVENTFD) or the guest's render node is Mali's stand-in. The graphics report lists it with the rest of the guest's graphics environment. * Test branch: gamescope with the explicit-sync switch (0126), pinned by sha Built by build-gamescope.yml run 38335744351 from0136fb61and published as a component release of The412Banner/droiddeck-nonadreno-drivers; the apk build fetches it by tag and checks the sha. * Sound: nothing that can block in the daemon's start-up; Steam's web compositing in software on open pairs - The S24 FE (US) daemon hung loading the plain AAudio sink from default.pa (its AAudio open blocks rather than fails), so it never finished starting. default.pa is back to DirectAudio alone inside .nofail; the fallbacks are loaded from the app once the daemon answers, each pactl bounded by its timeout (DirectAudio, then the plain sink with and without low latency). The guard waits 30 s and logs, with timestamps, how long the daemon took, whether its socket and pactl exist, and what it finally got. - With an open driver pair on a GPU that is not an Adreno, Steam's CEF composites in software (-cef-disable-gpu-compositing) with GPU raster kept: RADV on Xclipse showed stale, half-written tiles, as #570 saw on PowerVR. The session log says so. * Mali under Auto: the display always on Android's own Vulkan loader; a reboot hint for refused audio Axel's Tab S9 FE still drew its display with the PanVK Android half, set by an earlier build, and stalled at "Waiting for Steam's first frame" on Mali gralloc's format probes. Under Auto a Mali's display now goes to Android's own loader whatever was set before (DriverMenus resets it, and the compositor's driver choice ignores a pair's Android half), with no HAL path to find first. A pair counts as in use when its runtime half is. A manual pick of the PanVK display is kept. When audio.log shows AAUDIO_ERROR_DISCONNECTED, the report and the client-sink line say Android refused the output and that rebooting the phone usually fixes it. * Fix: call SessionPrefs.gpuDriverMode through its instance from Java * Compositor: log each new dma-buf format/modifier/size it imports (for colour and swizzle reports) Steam's software web compositing already covers every open driver pair, Mali included. * Open driver pairs: vkd3d-proton reports the driver's caps; buffer attach/release tracing; Mesa log - With a PanVK or RADV pair (BL_OPEN_DRIVER=1), droiddeck-game-env drops the app-wide VKD3D_FEATURE_LEVEL=12_2 and VKD3D_SHADER_MODEL=6_9 so vkd3d-proton reports what the driver has (an Unreal DX12 game crashed at start on PanVK with the overrides); a game's own setting still wins, and launch.txt records DROIDDECK_VKD3D_CAPS=driver. - The compositor traces, on a GPU that is not an Adreno, the first 400 dma-buf attaches and buffer releases by wl_buffer id and sending line, and logs any release of a buffer already released and not attached again (gamescope's "Compositor released us but we were not acquired" on G925). - Per-game logs no longer set MESA_DEBUG=silent, which kept mesa.log empty. * Tests: the dma-buf quarantine harness follows send_buffer_release's tracing macro * Mali (Venus): David Cimo's Venus route sources and recipes From DavidCimo/droiddeck-mali, branch mali-venus @ 4f838891 (prototype 13; his 12 commits on top of DroidDeck 0.3.1, GPL-3.0), by David Cimo: - tools/venus: Mesa Venus vtest patch (incl. the per-queue submit_mutex fix and the cached-memory frame readback), virglrenderer Android patch, the Mali compatibility layer (the six features DXVK needs: fill modes, multi-viewport, robustness2, clip/cull distance, BC1-BC7) and his tools. - tools/linuxfs/preload/venus.c: keeps Zink's kopper under Venus. - tools/gamescope/patches/0127 (his 0114): shm buffers uploaded on every commit. - docs/development/mali-venus.md: his design notes. - tools/venus/ci-build.sh and build-venus.yml: his build recipes as one CI job that packs the component (vtest server, ICD, layer) as venus.tzst for the apk. Co-authored-by: Dersim Abbas <derabb0620@gmail.com> * Mali (Venus) as a selectable route, by David Cimo Ports David Cimo's Venus route (DavidCimo/droiddeck-mali, mali-venus @ 4f838891) onto this branch as "Mali (Venus)", one tap in Setup next to the Mali bridge: - VenusComponent (his): stages the Venus ICD and runs virglrenderer's vtest server over the phone's own Vulkan driver; the guest gets VK_ICD_FILENAMES, VN_DEBUG=vtest, VTEST_SOCKET_NAME and MESA_VK_WSI_DEBUG=sw. - Selection rule: Venus when Setup's "Mali (Venus)" is on, on a GPU that is neither an Adreno nor a system-driver one (PowerVR, Xclipse), and the apk carries it. It then replaces the Mali bridge and any open driver pair for the session, and the display stays on the phone's own driver. Auto is unchanged (the PanVK pair). Adreno never takes any of it. - The compositor enables only the dma-buf extensions the driver has, logs a vendor driver's extension list, and gives a zero row pitch a packed row (his vk_present.c changes). - The Mali compatibility layer is staged into the runtime on non-Adreno devices only. - The component (vtest server, ICD, layer) comes from build-venus.yml as venus.tzst, published on The412Banner/droiddeck-nonadreno-drivers and pinned by sha in tools/venus/release.env. - gamescope 3.16.29-p15 adds his shm upload patch (0127) next to 0126; pinned by sha. - device.txt and graphics-report.txt name the route. Co-authored-by: Dersim Abbas <derabb0620@gmail.com> * Mali: Venus gamescope without robustness2, the bridge switch honoured and kept, clean driver switches - gamescope 0128: VK_EXT_robustness2 is optional. A Mali driver through Venus has none, and gamescope stopped at "Missing required extension: VK_EXT_robustness2" (the wayland_surface error after it was only the knock-on). Without it, unused descriptor slots point at a 1x1 texture instead of VK_NULL_HANDLE. (David Cimo's Pixel 9 driver has robustness2, so his build never needed this.) gamescope component rebuilt and pinned by sha. - Open-files limit: on a GPU that is not an Adreno the session script raises the soft limit to the hard limit for the whole session tree (a PanVK-kbase session froze on "Too many open files" after ten minutes) and graphics-report.txt shows before and after. A stopgap; the driver leak is fixed separately. - The Mali bridge switch is honoured: when on and usable it wins over a PanVK pair for the session (Venus still wins over it). Selecting a pair no longer switches the bridge off, which is why the switch did not survive an app restart (Auto re-selected the pair at start). Setup says when this phone cannot use the bridge at all. - Driver switching: picking a Mali pair by hand keeps the display on the phone's own driver, as Auto does (a PanVK Android display stalls on Mali gralloc at "Waiting for Steam's first frame", and stayed set after switching back); installing a bundle again replaces it instead of adding a "-2" copy beside the old one. - graphics-report.txt names the runtime driver's folder and libraries, and the previous session's drivers, flagged when they changed. * gamescope p16 (0128 robustness2 optional), pinned by sha; graphics-report says who chose the display driver * Bundle replace only for open non-Adreno pairs; Adreno bundles keep their numbered copies * Rebuilt open drivers reach phones: re-downloaded when their digest changes, release list hourly on non-Adreno The non-Adreno driver releases replace their assets in place (the PanVK kbase sync-file fd leak fix). A download is now remembered with its GitHub sha256, and an asset whose digest changed counts as not installed, so Auto fetches it again and the bundle replaces the old one; the release list is re-read after an hour instead of a day on a GPU that is not an Adreno. * Mali compatibility layer: multiDrawIndirect, depthClipEnable and robustness2 for DXVK on Venus A Galaxy A15 (Mali-G57) on Venus got gamescope and Steam up, but DXVK refused the GPU: "Device does not support required feature 'multiDrawIndirect'". DXVK 3.1 stops at the first missing feature, so the rest of its required list (dxvk_device_info.cpp) was checked against what the testers' Mali drivers cannot have, and covered in the same pass, on top of David Cimo's six: - multiDrawIndirect: reported, taken off the device, and an indirect draw with drawCount > 1 is recorded as single draws at offset + i * stride; maxDrawIndirectCount reported as 2^30. (drawIndirectCount is optional for DXVK and stays as the driver says.) - VK_EXT_depth_clip_enable (required): offered when the driver lacks it; depthClipEnable off in a pipeline becomes depthClampEnable, and the extension's structures never reach the driver. - VK_EXT_robustness2 missing entirely (gamescope saw the same on these phones): offered with robustBufferAccess2 (as robustBufferAccess, as before) and nullDescriptor, emulated by small stand-ins (a zeroed buffer, a 1x1 image) for VK_NULL_HANDLE buffers, image views and vertex buffers in plain, template and push descriptor writes and vertex-buffer binds. A null texel-buffer view stays null (its format is not known). The layer logs every feature it emulates per device. * Venus component22694a38(layer: multiDrawIndirect, depthClipEnable, robustness2), pinned by sha * Non-Adreno round 3: bridge images, Venus GL, shared buffers, Steam GPU drawing - vkbridge: the memory model skips lazily allocated types. Mali-G615 lists DEVICE_LOCAL|LAZILY_ALLOCATED first; taken as the device-local type it left images with no memory type (self-test "image clear/draw: setup" FAIL, gamescope "No compatible image memory type"). - Session: a bridge self-test that fails images or draws falls back to the runtime's driver pair for that session (BL_VKBRIDGE_FALLBACK_ICD); Setup and the graphics report say so. - Venus: the Mali compatibility layer runs in every process but gamescope (DROIDDECK_MALI_COMPAT=1), so Zink in Steam and Xwayland gets nullDescriptor; null texel-buffer views get stand-ins too. Without nullDescriptor the session's GL goes to llvmpipe. - gamescope 0129: a refused compute pipeline is named with its SPIR-V capabilities. - Compositor: a buffer on two surfaces at once (gamescope's planes while a notification is up) is released only when the last one lets go. - Open driver pairs: processes.txt timeline for the first three minutes; Setup "Steam interface: GPU drawing" turns off software web compositing. * Pin gamescope p17 (0129) and Venus55b30fbf* Non-Adreno round 4: Mali GPU-drawing block, gamescope YCbCr retry, GL probe, bridge draw sync - Setup's "Steam interface: GPU drawing" is hidden on Mali and a saved "on" is cleared: with PanVK it rebooted an Edge 60 (G615) as steamwebhelper started. Kept for Xclipse. - gamescope 0130: a composite pipeline refused at start-up is retried with a layout without immutable YCbCr samplers (G615 through Venus refused every composite shader; their SPIR-V has no Float16, so fp16 was not the cause). - Venus: droiddeck-glprobe opens GL through GLX the way the Steam client does, with the loader's reasons logged; when it fails the client's GL goes to llvmpipe. - vkbridge self-test: the draw check waits for the render pass's stores before copying out (a tiler read zeros without the dependency). * Pin gamescope p18 (0130) * Non-Adreno round 5: gamescope memory fallback, Venus destroy guard, OpenAL depot - gamescope 0131: DEVICE_LOCAL|HOST_VISIBLE requests fall back to host-visible memory (the bridge's unified-memory model lists none with both), with the request, type bits and memory types logged on failure; 0130's probe pipeline is kept and skipped when forced. - Venus: GAMESCOPE_NO_YCBCR_SAMPLERS=1 from the start; virglrenderer ignores the destroy of a pipeline it never created instead of marking the context fatal (vtest server exit 137 on a Mali-G615). - Steam's OpenAL depot (229020) maps to oalinst_dll, so games that list it (Hotline Miami) get OpenAL in their prefix. * Pin gamescope p19 (0131) and Venus6199a93f* Non-Adreno round 6: PowerVR PRIME on old kernels, thermal, hang-up names, bridge flippable images, Venus Zink variants - drm.c: PR #570's current PRIME ownership check (F_DUPFD_QUERY, then kcmp, then the F_SETOWN_EX owner marker): on a kernel before 6.10 with kcmp blocked, drmPrimeFDToHandle answered EOPNOTSUPP for every PowerVR import (Pixel 10, Android 17: Zink "failed drmPrimeFDToHandle", Xwayland error 7, gamescope X11 I/O error). The Mali stand-in node is kept. - A /sys/class/thermal the kernel will not list gets an empty directory, so mangoapp no longer aborts on it. - gamescope 0132: a hung-up waitable is named before the abort; 0133: the bridge's flippable images use supported-but-unexportable modifiers instead of asserting. - Venus: when Zink does not start, the loader's view is logged and Zink is retried without ZINK_DEBUG=compact, with ZINK_DESCRIPTORS=auto and without kopper before falling back to llvmpipe. * Pin gamescope p20 (0132, 0133) * Non-Adreno round 7: bridge command-buffer guard, Venus Zink trace, PowerVR mangoapp, Xclipse label - vkbridge server: every command buffer a device hands out is tracked; Begin, End (stream replay) and QueueSubmit refuse one it never allocated or has freed (VK_ERROR_DEVICE_LOST, logged) instead of passing it to the driver, where Mali's vkBeginCommandBuffer crashed the app (SIGSEGV 0x10, Steam's Zink on an Edge 60 and a Tab S11). - vkbridge server: a fault inside the driver while serving a request cuts that client off (SIGSEGV/SIGBUS guard per request) and leaves its objects alone; the app and the other clients carry on. Other faults go to the previous handler. - vkbridge server: the pipeline cache directory is copied; the JNI string it pointed at was freed (garbage in the cache path). - Venus: DROIDDECK_MALI_COMPAT_TRACE=1 makes the Mali compatibility layer log what an application queries before vkCreateDevice; a failed glprobe adds a traced run and vulkaninfo --summary under the same environment. - PowerVR: mangoapp draws with llvmpipe (Zink could not make it a swapchain and it crashed at every start). - Setup: an Xclipse GPU reads "Experimental: RADV or the system Xclipse driver", not the PowerVR line. * Pin Venuse40cd361(layer trace) * Non-Adreno round 8: bridge sharing fallback and crash detail, Venus diagnostics and 1.2 gate, compositor disconnect reasons, RADV upstream - Mali bridge: the self-test fails "memory sharing" when the server offers no host-visible memory type (no sharing method passed, RP4 Pro G77); the session then falls back to the PanVK pair like a failed draw, and Setup says the bridge cannot share memory with that driver. Without a pair to fall back on, the log says so. - Mali bridge: a guarded driver crash now logs the sub-command it was in, the fault address and pc (library + offset via dladdr), the command buffer's level, begin flags, pool flags and state, and the last 32 replayed commands. Begin on an executable buffer from a pool without RESET_COMMAND_BUFFER_BIT is logged once (implicit reset). - Venus: vulkan-summary.txt gets the device extension list and key features (full vulkaninfo in vulkan-full.txt); a failed GL probe runs once with VN_DEBUG=init,result, ZINK_DEBUG=mem, MESA_LOG_LEVEL=debug and the layer trace into glprobe-trace.txt. The Mali compatibility layer's trace covers every pre-device query (devices, memory, queue families, formats, image formats, external handles) and names the extensions. - Venus: off when the phone's driver reports Vulkan below 1.2 (gamescope skips such a device); Setup and the graphics report say why and the session uses the PanVK pair. - Compositor: libwayland's own disconnect reasons go to wayland.log, and a client's buffer may grow to 1 MB before a slow reader is dropped. A session that ended without teardown records Android's exit reasons. - Drivers: RADV-Xclipse upstream (radv-xclipse-upstream) is a manual choice for Xclipse; Auto keeps radv-xclipse. * Tests: the terminal-callers harness stubs the Quest layer and Cardboard modules and Android's system properties * Pin gamescope p21 (main's patches + 0120-0133) and Venusa4d47cf3(layer trace) * Display driver Auto: Quest's patched Turnip first; the system driver only for a Mali, other GPUs keep the generic fallback * Open driver pairs: the installed build's version, its upload date, and an Update when the release is rebuilt in place - The release check records each asset's GitHub id and updated_at; a download records them (with the digest) for an open non-Adreno pair. - Components > GPU drivers: an installed open pair shows its manifest version ("android <tag> + linux <commit>"), one not yet installed shows "built YYYY-MM-DD". A different digest, asset id or upload time on the same tag marks the installed pair "Update available" with an Update action: the pair is downloaded again and replaced in place, and stays selected only if it was. Adreno and DD-Turnip pairs are unchanged. - graphics-report.txt: the pair release line gives the installed and the listed upload dates and flags a newer build; an exact bundle id match is preferred (RADV-Xclipse-upstream is not RADV-Xclipse). * Session preload: drop oom_score_adj raises so lmkd does not treat games as cached apps steam-launch-wrapper starts every game with --oom-score-adjust 900; on Android 900 is CACHED_APP_MIN_ADJ, so lmkd kills the running game first when memory runs short (and on Linux 6.1 the raise becomes the process's permanent minimum). A process in the app cannot go below the score it inherits, so the writes that succeed from inside are raises: every write-open of /proc/<pid|self|thread-self>[/task/<tid>]/oom_score_adj (or oom_adj), through open/openat or fopen, goes to /dev/null, logged once. Based on the oom_score_adj redirect in the preload's opens.c by jdmg28 (https://github.com/jdmg28/DroidDeck-Mali/commit/6be00e00) * Display: why presenting failed on the session-ended screen, and the display driver that really loaded - The compositor records why it cannot present (no Vulkan driver loaded, vkCreateInstance/vkCreateDevice failed, no GPU or graphics queue, no swapchain on the screen with the driver's reason, device lost, GPU work unconfirmed). Each is a DD_PRESENT_FAULT line in wayland.log, read back over JNI or from wayland.log; the session-ended screen shows it instead of a black screen, and graphics-report.txt gets "!! DISPLAY FAILED". A first frame or a working swapchain clears it. - After the display device is created, the driver that answered is logged from VkPhysicalDeviceDriverProperties (device, driverName, driverInfo, driver id, Vulkan version) and reported in graphics-report.txt. When a driver pair's display half was requested but a vendor driver answered (adrenotools falls back to the system driver when the requested one does not load), it says so. Based on DD_PRESENT_FAULT in vk_present.c / waylandcomp_jni.c / SessionActivity by jdmg28 (https://github.com/jdmg28/DroidDeck-Mali/blob/arena/cd8ab18a-droiddeck-mali/app/src/main/cpp/waylandcomp/src/vk_present.c) Based on the adrenotools silent-fallback finding by ryanistr (https://github.com/ryanistr/DroidDeck-Mali/blob/main/docs/development/panvk-mali-g77-bringup.md) * tests: steam presentation test sets 0.5.0's steam_client * Non-Adreno: find every driver pair, Venus before the bridge, fix the bridge's begin info From the logs testers sent sincec9ebb247: - The app read the drivers repo's newest 15 releases only; the component releases (gamescope, Venus) pushed every PanVK pair and RADV-Xclipse past them, so Auto found no pair on any Mali and switched the Mali bridge on. The non-Adreno repo is now read in one page of 100. - Auto's stand-in for a missing pair: Mali (Venus) where the apk carries it (Steam runs on it from the G57 to the G1-Ultra), the bridge otherwise, nothing on a driver below Vulkan 1.2. It no longer clears the Linux driver, does nothing when the list could not be read, records that it chose the route, and turns it off again once a pair is installed. A bridge that earlier builds left on under Auto is taken as Auto's. - Mali bridge: vkBeginCommandBuffer sent its begin info without the count the server decodes, so Mali got a zeroed begin info with stale flags and crashed at 0x10 (Pixel 8 Pro G715, Lenovo G615, Xiaomi G925, Tab S11). - Mali-G1 series (MT6993, arch v14) known by its chip; its label says Venus, not the bridge. - A session Android killed for memory is said so on the next start (the S24 FE "crashes" were low-memory kills, not driver faults). - The in-app updater never installs an official (Adreno-only) build over this test build. * Venus: destroy the device's object mutex after the objects that lock it Bionic aborts on locking a destroyed mutex ("pthread_mutex_lock called on a destroyed mutex", Tab S9 FE G68, Pixel 9a), so a client that exited holding objects took the render worker down. From BattleTempest's DroidDeck-Pixel (kevinbryant551-ux/DroidDeck-Pixel, GPL-3.0). * release check: a session helper may be extracted to another runtime path droiddeck-steam-taskset (#570) goes to usr/local/libexec/droiddeck-steam/taskset, where PATH puts it in front of Steam's own taskset for the client only; 0.5.0's check wanted every droiddeck-* helper at its own path. * Venus component93038b7d(destroyed-mutex fix) * Update MaliBridge to v0.5.1 (#1135) * Mali Auto: never leave a session on the runtime's Turnip Logs from a Retroid Pocket 4 Pro (G77), Galaxy S21 Ultra (G78), Tab S11 Ultra (G925) and Xiaomi G610 showed Auto ending on the runtime's Turnip, where gamescope finds no GPU ("failed to find physical device"): after a pair's trial rolled back, when the pair is on the bad list, and when the driver list could not be read. In each case Auto now switches on its stand-in (Venus, or the bridge) when no open driver, Venus or bridge is set. Under Auto the Mali display also leaves any imported driver, not only a pair's PanVK half (a lone PanVK_G720 import gave a black screen). * Mali bridge: MaliBridge 224b6e36 (v0.5.3 source, by ASEbrahim) From c65062b6 (v0.5.1). v0.5.2/v0.5.3: Steam mode on older Mali drivers (G77/G710/G610/G57) gets past "starting display and audio", OpenGL 4.6 on most Malis through dynamic-rendering and vertex-format emulation, Dimensity 9500 texture fixes, async pipeline compile, RE2 flicker on G925, DirectX on the Pixel 8 family. JNI entry and session env names are unchanged. * gamescope 0134: linear when the backend offers no modifier; Venus on Mesa 26.2.5 0134: CVulkanTexture::BInit asserted !modifiers.empty() when the nested Wayland backend offered no modifier for a flippable image's format (NieR Replicant on a Pixel 9a under Venus, session exit 134). It now tries linear and logs it. Venus ICD: mesa-26.2.5 (venus TLS teardown from an unloaded driver, virtio-gpu devices without 3D skipped); virglrenderer stays on 1.3.0. * gamescope p22-nonadreno (0134 + main's 0116 cursor fix; build run 40159674290) * CI: build the non-Adreno additions before the preload check * build.gradle: drop verifyHandModel (main moved the hand models into the tracking pack) * Venus component venus-proto13-e24ed8ab (Mesa 26.2.5; build run 40161447324) * CI: fetch the Mali (Venus) component again (lost when build.yml took main's jobs) Builda7a1ebf1(run 40161734101) had no assets/venus or libvirgl_test_server.so, so VenusComponent.available() was false and Auto's stand-in would have been the bridge. * Auto: the Mali bridge stands in on a Vulkan 1.1 Mali driver Auto refused both Venus and the bridge when the phone's driver reports Vulkan below 1.2, so on the G77, G78 and G610 (r32p1/r38, Vulkan 1.1) a rolled-back or missing pair left the runtime's Turnip: "failed to find physical device" (Retroid Pocket 4 Pro after the JM pair's trial, Xiaomi 13T). Only Venus needs 1.2; the bridge raises the driver for gamescope and runs on these phones. A Venus switch that cannot start on such a driver no longer counts as a route. * Tests: stub main's g_release_unpaced in the DMA-BUF quarantine probe The probe copies release_buffer out of compositor.c; since the merge it reads g_release_unpaced, which the harness did not declare (setUpClass failed to compile). * Update MaliBridge to v0.5.4 (ASEbrahim) 48477fe6 (tag v0.5.4): Dimensity 9500 green squares and red-tinted textures, Balatro and other OpenGL text, fewer crashes when memory runs low, one screen update per game frame, picture kept after a long background pause (SIGHUP no longer stops the server), wrong colours after changing graphics settings on the G720, more in the session report. The app-side changes of his DroidDeck Mali app (Steam menus setting, per-game setup, Send logs, updates) are not part of the MaliBridge repository and are not in this build. * gamescope 0135: linear when the driver rejects every offered modifier An r32p1 Mali-G610 (Vulkan 1.1) behind the Mali bridge answered both of the backend's modifiers for AR24 with VK_ERROR_FORMAT_NOT_SUPPORTED, so the first flippable image failed and gamescope asserted in vulkan_create_flat_texture (Xiaomi 13T). Linear, when offered, is tried anyway; the bridge makes such images without the handle type and exports them through a dma-heap. If the image cannot be made, BInit fails as before. * gamescope: pin the non-Adreno p23 build (0135) * Tests: the terminal-callers harness stubs take_shm's game-frame detection Main's take_shm now reads surface damage, parent/role/mapped and the HUD state to spot game frames; the harness declares them so the copied function compiles (setUpClass failed in Build APK run 40505286127). No damage, so it stays off. * gamescope: number the test branch's patches 0920-0935 Main now has its own 0121-0125 (window override walk, host-event wake, commit fences, done at import, HUD frame times), which sorted in between this branch's 0120-0135. The branch's sixteen patches move to 0920-0935 with the same last two digits, so they apply after main's set and stay clear of its next numbers. Applying all 38 to gamescope 3.16.29 in the old order and the new one gives the same tree (checked with patch -p1, as build-in-arch.sh does). PATCHES.md and the one code comment that named 0130 follow the new numbers. * check_session_assets: helpers count in usr/local/bin or the Steam taskset folder only The merge kept this branch's pattern (any usr/ target), which main's new test rejects: a helper extracted into a subfolder of usr/local/bin must not count. The pattern now takes usr/local/bin under any name, as on main, plus usr/local/libexec/droiddeck-steam for droiddeck-steam-taskset. Every helper in the overlay is still found extracted in SessionFiles.kt. * gamescope: pin 3.16.29 p24 (non-Adreno) Built from this branch @d13b9d88 (run 41119284267): main a5b035b2's patches plus this branch's, now 0920-0935. All 38 applied, gamescope's tests 2/2. sha256 1d1088d4. * Update MaliBridge to v0.5.4.2 (ASEbrahim) 95a1e600 (tag v0.5.4.2), was v0.5.4 (48477fe6). For the bridge: memory sharing without the handle type where that is all the self-test passed (unflagged buffers, client/memory.c, server_memory.c), the older-Mali (G52-G77) game-mode start fixes, the r38p1 beta geometry-shader erratum (gs_hide), present timeouts and an API cap per process. Client, server and the in-app library all build from the submodule with MaliBridge's own scripts, which did not change; the protocol only gained fields an older server sends as 0. * Session end: the compositor fault query no longer fails the hint when the native library is absent presentationFault() (6778a224) called WaylandCompositor.compositorFault() directly. Main's new SessionEndHintTest runs sessionEndHint() in Robolectric, where libdroiddeckwayland cannot load, so all six cases ended in UnsatisfiedLinkError (Build APK run 41125749537). The call is now wrapped like runtimeDamageHint()'s, and without an answer the hint reads wayland.log as before. * test: stub the GPU busy reader in the caller harness * fix: release build is not debuggable, Mali uses the system display driver, staging failure ends its own session * fix: address non-Adreno review findings * fix: preserve current gamescope and GPU warning behavior * fix: retain graphics failure hints and launch diagnostics * fix: identify non-Adreno GPUs in driver failure hints * test: harnesses follow the external client barrier and effects upscaling changes * fix: client sources return to foreign ownership after the overlay draws --------- Co-authored-by: Leask Wong <i@leaskh.com> Co-authored-by: wallentx <william.allentx@gmail.com> Co-authored-by: Stefan Zijlstra <6730062+stefanz92@users.noreply.github.com> Co-authored-by: William Allen <wallentx@users.noreply.github.com> Co-authored-by: The412Banner <the412banner@users.noreply.github.com> Co-authored-by: Dersim Abbas <derabb0620@gmail.com> Co-authored-by: root <root@localhost.localdomain> Co-authored-by: ASEbrahim <ahmadsmain@gmail.com> Co-authored-by: The412Banner <the412banner@gmail.com> Co-authored-by: The412Banner <205237651+The412Banner@users.noreply.github.com>
This commit is contained in:
215 files changed
+19024
-428
No files matched your search
@@ -0,0 +1,343 @@
|
||||
#define _GNU_SOURCE
|
||||
#include <assert.h>
|
||||
#include <dlfcn.h>
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <pthread.h>
|
||||
#include <stdarg.h>
|
||||
#include <stdatomic.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
|
||||
/* Only the device/driver boundary is simulated. Descriptors and their lifetimes are real.
|
||||
* F_DUPFD_QUERY is modelled so this test also runs on older CI kernels; the device probe
|
||||
* separately exercises the actual query on Android. */
|
||||
#define TEST_FD_LIMIT 65536
|
||||
static _Atomic unsigned identities[TEST_FD_LIMIT];
|
||||
static struct f_owner_ex owners[TEST_FD_LIMIT];
|
||||
static unsigned identity_serial = 1;
|
||||
static int identity_denied, owner_denied, owner_probe_delay, kgsl_present;
|
||||
static int kernel_error = EINVAL;
|
||||
static int native_imports, native_exports, native_closes;
|
||||
static const char *driver_name = "pvr";
|
||||
static const char *pvr_node = "/dev/dri/renderD129";
|
||||
static int fixture_stat(const char *path, struct stat *st);
|
||||
static long fixture_syscall(long number, ...);
|
||||
static int fixture_fcntl(int fd, int op, ...);
|
||||
static void *fixture_dlsym(void *object, const char *name);
|
||||
static int fixture_close(int fd);
|
||||
|
||||
#define stat(path, st) fixture_stat(path, st)
|
||||
#define syscall fixture_syscall
|
||||
#define fcntl fixture_fcntl
|
||||
#define dlsym fixture_dlsym
|
||||
#define close fixture_close
|
||||
#include "../linuxfs/preload/drm.c"
|
||||
#undef stat
|
||||
#undef syscall
|
||||
#undef fcntl
|
||||
#undef dlsym
|
||||
#undef close
|
||||
|
||||
static int test_open(const char *path) {
|
||||
int fd = open(path, O_RDWR | O_CLOEXEC);
|
||||
assert(fd >= 0 && fd < TEST_FD_LIMIT);
|
||||
identities[fd] = identity_serial++;
|
||||
return fd;
|
||||
}
|
||||
|
||||
static int fixture_close(int fd) {
|
||||
if (fd >= 0 && fd < TEST_FD_LIMIT) identities[fd] = 0;
|
||||
return close(fd);
|
||||
}
|
||||
|
||||
static int fixture_stat(const char *path, struct stat *st) {
|
||||
if (!strcmp(path, "/dev/kgsl-3d0")) {
|
||||
if (kgsl_present) return stat("/dev/zero", st);
|
||||
errno = ENOENT;
|
||||
return -1;
|
||||
}
|
||||
if (!strcmp(path, pvr_node)) return stat("/dev/null", st);
|
||||
if (!strcmp(path, "/dev/dri/renderD128")) return stat("/dev/zero", st);
|
||||
if (!strncmp(path, "/dev/dri/", 9)) { errno = ENOENT; return -1; }
|
||||
return stat(path, st);
|
||||
}
|
||||
|
||||
static int fixture_fcntl(int fd, int op, ...) {
|
||||
va_list ap;
|
||||
va_start(ap, op);
|
||||
if (op == F_GETOWN_EX || op == F_SETOWN_EX) {
|
||||
struct f_owner_ex *owner = va_arg(ap, struct f_owner_ex *);
|
||||
va_end(ap);
|
||||
if (owner_denied) { errno = EINVAL; return -1; }
|
||||
if (fd < 0 || fd >= TEST_FD_LIMIT || !identities[fd] || !owner) {
|
||||
errno = EBADF;
|
||||
return -1;
|
||||
}
|
||||
if (op == F_GETOWN_EX) {
|
||||
*owner = owners[identities[fd]];
|
||||
} else {
|
||||
owners[identities[fd]] = *owner;
|
||||
if (owner_probe_delay && owner->pid) usleep(1000);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
int arg = va_arg(ap, int);
|
||||
va_end(ap);
|
||||
if (op == F_DUPFD_QUERY) {
|
||||
if (identity_denied) { errno = EINVAL; return -1; }
|
||||
if (fd < 0 || arg < 0 || fd >= TEST_FD_LIMIT || arg >= TEST_FD_LIMIT ||
|
||||
!identities[fd] || !identities[arg]) { errno = EBADF; return -1; }
|
||||
return identities[fd] == identities[arg];
|
||||
}
|
||||
int ret = fcntl(fd, op, arg);
|
||||
if (ret >= 0 && (op == F_DUPFD || op == F_DUPFD_CLOEXEC)) {
|
||||
assert(ret < TEST_FD_LIMIT);
|
||||
identities[ret] = identities[fd];
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
static long fixture_syscall(long number, ...) {
|
||||
va_list ap;
|
||||
va_start(ap, number);
|
||||
if (number == SYS_ioctl) {
|
||||
(void)va_arg(ap, int);
|
||||
unsigned long request = va_arg(ap, unsigned long);
|
||||
struct bl_drm_version *v = va_arg(ap, void *);
|
||||
assert(request == BL_DRM_VERSION);
|
||||
snprintf(v->name, v->name_len, "%s", driver_name);
|
||||
v->name_len = strlen(driver_name);
|
||||
va_end(ap);
|
||||
return 0;
|
||||
}
|
||||
va_end(ap);
|
||||
assert(number == SYS_kcmp);
|
||||
errno = EPERM;
|
||||
return -1;
|
||||
}
|
||||
|
||||
static int native_import(int fd, int dma, uint32_t *handle) {
|
||||
(void)fd;
|
||||
native_imports++;
|
||||
if (fcntl(dma, F_GETFD) < 0) return -1;
|
||||
if (!handle) { errno = EFAULT; return -1; }
|
||||
if (kernel_error) { errno = kernel_error; return -1; }
|
||||
*handle = 42;
|
||||
return 0;
|
||||
}
|
||||
static int native_export(int fd, uint32_t handle, uint32_t flags, int *out) {
|
||||
(void)flags;
|
||||
native_exports++;
|
||||
if (handle != 42 || !out) { errno = EINVAL; return -1; }
|
||||
*out = fixture_fcntl(fd, F_DUPFD_CLOEXEC, 0);
|
||||
return *out < 0 ? -1 : 0;
|
||||
}
|
||||
static int native_close(int fd, uint32_t handle) {
|
||||
(void)fd;
|
||||
native_closes++;
|
||||
if (handle == 42) return 0;
|
||||
errno = EINVAL;
|
||||
return -1;
|
||||
}
|
||||
static void *fixture_dlsym(void *object, const char *name) {
|
||||
assert(object == RTLD_NEXT);
|
||||
if (!strcmp(name, "drmPrimeFDToHandle")) return native_import;
|
||||
if (!strcmp(name, "drmPrimeHandleToFD")) return native_export;
|
||||
if (!strcmp(name, "drmCloseBufferHandle")) return native_close;
|
||||
abort();
|
||||
}
|
||||
|
||||
static int count_fds(void) {
|
||||
int count = 0;
|
||||
for (int fd = 0; fd < TEST_FD_LIMIT; ++fd) count += identities[fd] != 0;
|
||||
return count;
|
||||
}
|
||||
static void empty_table(void) {
|
||||
for (int i = 0; i < MAX_HANDLES; ++i) assert(!handle_entries[i].handle);
|
||||
}
|
||||
|
||||
struct fallback_stress {
|
||||
int drm;
|
||||
int dma;
|
||||
int failures;
|
||||
};
|
||||
|
||||
static void *stress_fallback_imports(void *opaque) {
|
||||
struct fallback_stress *stress = opaque;
|
||||
for (int i = 0; i < 20; i++) {
|
||||
uint32_t handle = 0;
|
||||
if (drmPrimeFDToHandle(stress->drm, stress->dma, &handle) != 0 ||
|
||||
drmCloseBufferHandle(stress->drm, handle) != 0) {
|
||||
stress->failures++;
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
int drm = test_open("/dev/null"), dma = test_open("/dev/zero");
|
||||
uint32_t handle = 0;
|
||||
unsetenv("BL_POWERVR_DRM_HANDLES");
|
||||
setenv("BL_POWERVR_RENDER_NODE", pvr_node, 1);
|
||||
assert(drmPrimeFDToHandle(drm, dma, &handle) != 0);
|
||||
setenv("BL_POWERVR_DRM_HANDLES", "yes", 1);
|
||||
assert(drmPrimeFDToHandle(drm, dma, &handle) != 0);
|
||||
setenv("BL_POWERVR_DRM_HANDLES", "1", 1);
|
||||
unsetenv("BL_POWERVR_RENDER_NODE");
|
||||
assert(drmPrimeFDToHandle(drm, dma, &handle) != 0); /* no selected node */
|
||||
setenv("BL_POWERVR_RENDER_NODE", "", 1);
|
||||
assert(drmPrimeFDToHandle(drm, dma, &handle) != 0);
|
||||
setenv("BL_POWERVR_RENDER_NODE", "/dev/dri/renderD128", 1);
|
||||
assert(drmPrimeFDToHandle(drm, dma, &handle) != 0); /* another GPU owns 128 */
|
||||
setenv("BL_POWERVR_RENDER_NODE", "/dev/dri/renderD130", 1);
|
||||
assert(drmPrimeFDToHandle(drm, dma, &handle) != 0); /* selected node is absent */
|
||||
setenv("BL_POWERVR_RENDER_NODE", __FILE__, 1);
|
||||
assert(drmPrimeFDToHandle(drm, dma, &handle) != 0); /* regular files are not DRM nodes */
|
||||
setenv("BL_POWERVR_RENDER_NODE", pvr_node, 1);
|
||||
driver_name = "other";
|
||||
assert(drmPrimeFDToHandle(drm, dma, &handle) != 0);
|
||||
driver_name = "pvr";
|
||||
assert(drmPrimeFDToHandle(dma, dma, &handle) != 0); /* wrong character device */
|
||||
kernel_error = EACCES;
|
||||
assert(drmPrimeFDToHandle(drm, dma, &handle) != 0 && errno == EACCES);
|
||||
kernel_error = EINVAL;
|
||||
assert(drmPrimeFDToHandle(drm, -1, &handle) != 0 && errno == EBADF);
|
||||
empty_table();
|
||||
|
||||
int baseline = count_fds();
|
||||
identity_denied = 1;
|
||||
assert(drmPrimeFDToHandle(drm, dma, &handle) == 0 && (handle & PVR_HANDLE_BIT));
|
||||
int denied_alias = fixture_fcntl(drm, F_DUPFD_CLOEXEC, 0), denied_out = -1;
|
||||
int denied_separate = test_open("/dev/null");
|
||||
assert(drmPrimeHandleToFD(denied_separate, handle, O_CLOEXEC, &denied_out) != 0);
|
||||
assert(drmPrimeHandleToFD(denied_alias, handle, O_CLOEXEC, &denied_out) == 0);
|
||||
fixture_close(denied_out);
|
||||
assert(drmCloseBufferHandle(denied_alias, handle) == 0);
|
||||
fixture_close(denied_alias);
|
||||
fixture_close(denied_separate);
|
||||
assert(count_fds() == baseline);
|
||||
owner_denied = 1;
|
||||
assert(drmPrimeFDToHandle(drm, dma, &handle) == -EOPNOTSUPP);
|
||||
assert(count_fds() == baseline);
|
||||
owner_denied = 0;
|
||||
|
||||
/* Marker changes and restoration must be atomic across concurrent imports of one DRM OFD. */
|
||||
owner_probe_delay = 1;
|
||||
struct fallback_stress stress[8];
|
||||
pthread_t workers[8];
|
||||
for (int i = 0; i < 8; i++) {
|
||||
stress[i] = (struct fallback_stress){.drm = drm, .dma = dma};
|
||||
assert(pthread_create(&workers[i], NULL, stress_fallback_imports, &stress[i]) == 0);
|
||||
}
|
||||
for (int i = 0; i < 8; i++) {
|
||||
assert(pthread_join(workers[i], NULL) == 0);
|
||||
assert(stress[i].failures == 0);
|
||||
}
|
||||
owner_probe_delay = 0;
|
||||
assert(owners[identities[drm]].pid == 0);
|
||||
assert(count_fds() == baseline);
|
||||
empty_table();
|
||||
identity_denied = 0;
|
||||
|
||||
assert(drmPrimeFDToHandle(drm, dma, &handle) == 0 && (handle & PVR_HANDLE_BIT));
|
||||
assert(count_fds() == baseline + 2);
|
||||
int alias = fixture_fcntl(drm, F_DUPFD_CLOEXEC, 0), out = -1;
|
||||
int separate = test_open("/dev/null");
|
||||
assert(drmPrimeHandleToFD(separate, handle, O_CLOEXEC | O_RDWR, &out) != 0);
|
||||
struct gem_close close_request = {.handle = handle};
|
||||
int rc = 123;
|
||||
assert(bl_drm_gem_close(separate, GEM_CLOSE, &close_request, &rc) == 0 && rc == 123);
|
||||
assert(drmPrimeHandleToFD(alias, handle, O_CLOEXEC | O_RDWR, &out) == 0);
|
||||
assert(fcntl(out, F_GETFD) & FD_CLOEXEC);
|
||||
struct stat src, dst;
|
||||
assert(fstat(dma, &src) == 0 && fstat(out, &dst) == 0);
|
||||
assert(src.st_dev == dst.st_dev && src.st_ino == dst.st_ino);
|
||||
fixture_close(out);
|
||||
assert(drmPrimeHandleToFD(alias, handle, 0, &out) == 0);
|
||||
assert(!(fcntl(out, F_GETFD) & FD_CLOEXEC));
|
||||
fixture_close(out);
|
||||
assert(drmPrimeHandleToFD(alias, handle, 0x40, &out) == -EINVAL);
|
||||
|
||||
/* A closed-and-reused descriptor must not inherit the old open file's handles. */
|
||||
int old_number = drm;
|
||||
fixture_close(drm);
|
||||
drm = test_open("/dev/null");
|
||||
assert(drm == old_number);
|
||||
assert(drmPrimeHandleToFD(drm, handle, O_CLOEXEC, &out) != 0);
|
||||
assert(drmCloseBufferHandle(drm, handle) != 0);
|
||||
assert(drmPrimeHandleToFD(alias, handle, O_CLOEXEC, &out) == 0);
|
||||
fixture_close(out);
|
||||
assert(bl_drm_gem_close(alias, GEM_CLOSE, &close_request, &rc) == 1 && rc == 0);
|
||||
assert(drmPrimeHandleToFD(alias, handle, O_CLOEXEC, &out) != 0);
|
||||
fixture_close(alias);
|
||||
fixture_close(separate);
|
||||
assert(count_fds() == baseline);
|
||||
empty_table();
|
||||
|
||||
/* Real kernel handles and their direct GEM_CLOSE ioctls are never swallowed. */
|
||||
kernel_error = 0;
|
||||
assert(drmPrimeFDToHandle(drm, dma, &handle) == 0 && handle == 42);
|
||||
empty_table();
|
||||
assert(drmPrimeHandleToFD(drm, handle, O_CLOEXEC, &out) == 0);
|
||||
fixture_close(out);
|
||||
close_request.handle = handle;
|
||||
assert(bl_drm_gem_close(drm, GEM_CLOSE, &close_request, &rc) == 0);
|
||||
assert(drmCloseBufferHandle(drm, handle) == 0);
|
||||
assert(native_imports && native_exports && native_closes);
|
||||
kernel_error = EINVAL;
|
||||
|
||||
/* Slot reuse must not reuse public tokens or leak either owned descriptor. */
|
||||
uint32_t previous = 0;
|
||||
for (int n = 0; n < 1000; ++n) {
|
||||
assert(drmPrimeFDToHandle(drm, dma, &handle) == 0 && handle != previous);
|
||||
assert(drmCloseBufferHandle(drm, handle) == 0);
|
||||
if (previous) assert(drmPrimeHandleToFD(drm, previous, O_CLOEXEC, &out) != 0);
|
||||
previous = handle;
|
||||
}
|
||||
assert(count_fds() == baseline);
|
||||
empty_table();
|
||||
|
||||
assert(drmPrimeFDToHandle(drm, dma, &handle) == 0);
|
||||
pid_t child = fork();
|
||||
assert(child >= 0);
|
||||
if (child == 0) {
|
||||
assert(drmPrimeHandleToFD(drm, handle, O_CLOEXEC, &out) == 0);
|
||||
fixture_close(out);
|
||||
assert(drmCloseBufferHandle(drm, handle) == 0);
|
||||
_exit(0);
|
||||
}
|
||||
int status;
|
||||
assert(waitpid(child, &status, 0) == child && WIFEXITED(status) && WEXITSTATUS(status) == 0);
|
||||
assert(drmPrimeHandleToFD(drm, handle, O_CLOEXEC, &out) == 0);
|
||||
fixture_close(out);
|
||||
assert(drmCloseBufferHandle(drm, handle) == 0);
|
||||
|
||||
/* Preserve the original device layout when PowerVR owns renderD128. */
|
||||
pvr_node = "/dev/dri/renderD128";
|
||||
setenv("BL_POWERVR_RENDER_NODE", pvr_node, 1);
|
||||
assert(drmPrimeFDToHandle(drm, dma, &handle) == 0 && (handle & PVR_HANDLE_BIT));
|
||||
assert(drmCloseBufferHandle(drm, handle) == 0);
|
||||
|
||||
/* Retain the old KGSL path with the PowerVR opt-in unset. */
|
||||
unsetenv("BL_POWERVR_DRM_HANDLES");
|
||||
kgsl_present = 1;
|
||||
kgsl_state = 0;
|
||||
assert(drmPrimeFDToHandle(dma, drm, &handle) == 0 && !(handle & PVR_HANDLE_BIT));
|
||||
assert(drmPrimeHandleToFD(dma, handle, O_CLOEXEC | O_RDWR, &out) == 0);
|
||||
fixture_close(out);
|
||||
close_request.handle = handle;
|
||||
assert(bl_drm_gem_close(dma, GEM_CLOSE, &close_request, &rc) == 1 && rc == 0);
|
||||
assert(drmCloseBufferHandle(dma, handle) == -EINVAL);
|
||||
empty_table();
|
||||
assert(count_fds() == baseline);
|
||||
fixture_close(drm);
|
||||
fixture_close(dma);
|
||||
puts("DRM adapter scoping, ownership, reuse, fork and kernel-passthrough tests passed");
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
class DrmHandleTest(unittest.TestCase):
|
||||
def test_handle_lifetime_and_device_scope(self):
|
||||
compiler = shutil.which(os.environ.get("CC", "cc"))
|
||||
if not compiler:
|
||||
self.fail("A C compiler is required for the DRM adapter regression test")
|
||||
source = Path(__file__).with_name("drm_handles_test.c")
|
||||
with tempfile.TemporaryDirectory(prefix="droiddeck-drm-") as tmp:
|
||||
program = Path(tmp) / "drm-handles"
|
||||
built = subprocess.run([compiler, "-std=gnu11", "-Wall", "-Wextra", "-Werror",
|
||||
"-UNDEBUG", "-pthread", str(source), "-ldl", "-o", str(program)],
|
||||
capture_output=True, text=True)
|
||||
self.assertEqual(built.returncode, 0, built.stdout + built.stderr)
|
||||
ran = subprocess.run([str(program)], capture_output=True, text=True, timeout=30)
|
||||
self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,121 @@
|
||||
"""Exercise output isolation with a synthetic toolchain; no network/DLL build."""
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
# Substitute only external source/compiler/archive commands. The real build.sh
|
||||
# owns output checks, architecture iteration and manifest inputs.
|
||||
FAKE_TOOL = r'''
|
||||
import hashlib, json, os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
name = Path(sys.argv[0]).name
|
||||
args = sys.argv[1:]
|
||||
with open(os.environ['TOOL_CALLS'], 'a') as stream:
|
||||
stream.write(name + '\n')
|
||||
if name == 'git':
|
||||
if args[0] == 'init':
|
||||
Path(args[-1]).mkdir()
|
||||
(Path(args[-1]) / 'LICENSE').write_text('synthetic public license')
|
||||
elif 'rev-parse' in args:
|
||||
print(os.environ['TEST_REVISION'])
|
||||
elif name == 'meson':
|
||||
if args[0] == 'setup':
|
||||
p = Path(args[1]); p.mkdir()
|
||||
p.joinpath('config.json').write_text(json.dumps({
|
||||
'out': args[args.index('--prefix') + 1],
|
||||
'arch': args[args.index('--bindir') + 1]}))
|
||||
elif args[0] == 'install':
|
||||
config = json.loads(Path(args[2], 'config.json').read_text())
|
||||
out = Path(config['out'], config['arch']); out.mkdir(exist_ok=True)
|
||||
out.joinpath('current.dll').write_bytes(b'synthetic current pinned DLL')
|
||||
if config['arch'] == os.environ.get('FAIL_INSTALL_ARCH'):
|
||||
sys.exit(5)
|
||||
elif name == 'tar':
|
||||
Path(args[args.index('-cf') + 1]).write_bytes(b'synthetic source archive')
|
||||
elif name == 'sha256sum':
|
||||
for arg in args:
|
||||
print(hashlib.sha256(Path(arg).read_bytes()).hexdigest() + ' ' + arg)
|
||||
elif name != 'python3':
|
||||
raise AssertionError(name)
|
||||
'''
|
||||
|
||||
|
||||
class DxvkBuildTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temporary = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temporary.cleanup)
|
||||
self.base = Path(self.temporary.name)
|
||||
self.bin = self.base / 'bin'; self.bin.mkdir()
|
||||
executable = self.bin / 'fake-tool'
|
||||
executable.write_text('#!' + sys.executable + '\n' + FAKE_TOOL)
|
||||
executable.chmod(0o755)
|
||||
for name in ('git', 'meson', 'tar', 'sha256sum', 'python3'):
|
||||
(self.bin / name).symlink_to(executable)
|
||||
self.calls = self.base / 'calls'
|
||||
self.env = dict(os.environ, PATH=str(self.bin) + os.pathsep + os.environ['PATH'],
|
||||
TOOL_CALLS=str(self.calls))
|
||||
source_env = ROOT / 'tools/dxvk/source.env'
|
||||
self.env['TEST_REVISION'] = next(line.split('=', 1)[1].strip('"\'')
|
||||
for line in source_env.read_text().splitlines()
|
||||
if line.startswith('DXVK_REVISION='))
|
||||
self.output = self.base / 'component'
|
||||
|
||||
def build(self):
|
||||
return subprocess.run(['bash', str(ROOT / 'tools/dxvk/build.sh'), str(self.output)],
|
||||
env=self.env, capture_output=True, text=True, timeout=10)
|
||||
|
||||
def test_stale_dll_is_rejected_untouched_before_fetch(self):
|
||||
stale = self.output / 'x32/stale.dll'; stale.parent.mkdir(parents=True)
|
||||
stale.write_bytes(b'prior pinned build')
|
||||
result = self.build()
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn('output directory must be empty', result.stderr)
|
||||
self.assertEqual(stale.read_bytes(), b'prior pinned build')
|
||||
self.assertFalse(self.calls.exists())
|
||||
self.assertFalse((self.output / 'SHA256SUMS').exists())
|
||||
|
||||
def test_hidden_contents_are_also_rejected(self):
|
||||
self.output.mkdir(); (self.output / '.previous').write_text('retained')
|
||||
self.assertNotEqual(self.build().returncode, 0)
|
||||
self.assertFalse(self.calls.exists())
|
||||
self.assertEqual((self.output / '.previous').read_text(), 'retained')
|
||||
|
||||
def test_empty_or_new_output_contains_only_current_dlls(self):
|
||||
for existing in (False, True):
|
||||
with self.subTest(existing=existing):
|
||||
self.output = self.base / ('existing' if existing else 'new')
|
||||
if existing: self.output.mkdir()
|
||||
result = self.build()
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
rows = (self.output / 'SHA256SUMS').read_text().splitlines()
|
||||
self.assertEqual([row.split(' ')[1] for row in rows],
|
||||
['x32/current.dll', 'x64/current.dll'])
|
||||
for row in rows:
|
||||
digest, path = row.split(' ')
|
||||
self.assertEqual(digest, hashlib.sha256((self.output / path).read_bytes()).hexdigest())
|
||||
|
||||
def test_partial_build_is_not_reused_or_deleted(self):
|
||||
self.env['FAIL_INSTALL_ARCH'] = 'x64'
|
||||
result = self.build()
|
||||
self.assertEqual(result.returncode, 5, result.stderr)
|
||||
before = {str(p.relative_to(self.output)): p.read_bytes()
|
||||
for p in self.output.rglob('*') if p.is_file()}
|
||||
self.calls.unlink(); del self.env['FAIL_INSTALL_ARCH']
|
||||
result = self.build()
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertFalse(self.calls.exists())
|
||||
after = {str(p.relative_to(self.output)): p.read_bytes()
|
||||
for p in self.output.rglob('*') if p.is_file()}
|
||||
self.assertEqual(after, before)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -26,6 +26,7 @@ class EffectsSourceResolutionTest(unittest.TestCase):
|
||||
header = (REPO / 'app/src/main/cpp/waylandcomp/src/vk_present.h').read_text()
|
||||
effects = (REPO / 'app/src/main/cpp/waylandcomp/src/effects_chain.c').read_text()
|
||||
functions = '\n'.join(function(source, signature) for signature in (
|
||||
'static void release_external_client_image(', 'static void release_external_client_draws(',
|
||||
'static int map_draw(', 'static int draw_to_blit(',
|
||||
'static int draw_to_scene_blit(', 'static int effects_source_draw(',
|
||||
'static void effects_source_note(',
|
||||
@@ -37,11 +38,13 @@ class EffectsSourceResolutionTest(unittest.TestCase):
|
||||
image = source[source.index('struct vkp_image {'):source.index('\n};', source.index('struct vkp_image {')) + 3]
|
||||
draw = header[header.index('struct vkp_draw {'):header.index('\n};', header.index('struct vkp_draw {')) + 3]
|
||||
hdr = header[header.index('struct vkp_hdr_frame {'):header.index('\n};', header.index('struct vkp_hdr_frame {')) + 3]
|
||||
constants = sorted(set(re.findall(r'\bVK_[A-Z0-9_]+\b', functions + image)) -
|
||||
sync = (REPO / 'app/src/main/cpp/waylandcomp/src/vk_external_image_sync.h').read_text()
|
||||
sync = re.sub(r'^#(include|ifndef|define|endif).*$', '', sync, flags=re.M)
|
||||
constants = sorted(set(re.findall(r'\bVK_[A-Z0-9_]+\b', functions + image + sync)) -
|
||||
{'VK_FORMAT_R8G8B8A8_UNORM'})
|
||||
definitions = '\n'.join(f'#define {name} {0 if name in ("VK_SUCCESS", "VK_NULL_HANDLE") else i + 1}'
|
||||
for i, name in enumerate(constants))
|
||||
code = TYPES + definitions + '\n' + image + '\n' + draw + '\n' + hdr + STUBS + functions + CASES
|
||||
code = TYPES + definitions + '\n' + sync + '\n' + image + '\n' + draw + '\n' + hdr + STUBS + functions + CASES
|
||||
cls.temp = tempfile.TemporaryDirectory(prefix='droiddeck-effects-resolution-')
|
||||
cls.addClassCleanup(cls.temp.cleanup)
|
||||
folder = Path(cls.temp.name)
|
||||
@@ -148,10 +151,12 @@ typedef struct {
|
||||
#define droiddeck_log(...) ((void)0)
|
||||
#define LOGE(...) ((void)0)
|
||||
struct droiddeck_color { uint32_t identity; };
|
||||
typedef struct AHardwareBuffer AHardwareBuffer;
|
||||
'''
|
||||
|
||||
|
||||
STUBS = r'''
|
||||
static void quarantine_pending_work(VkResult result, const char *where) { (void)result; (void)where; }
|
||||
static int noop(int handle, ...) { return VK_SUCCESS; }
|
||||
static VkImageMemoryBarrier recorded_barriers[64];
|
||||
static int barrier_count;
|
||||
@@ -173,7 +178,7 @@ static struct {
|
||||
int (*EndCommandBuffer)(int, ...), (*ResetFences)(int, ...);
|
||||
int (*QueueSubmit)(int, ...), (*QueuePresentKHR)(int, ...);
|
||||
} g_vk = {noop, noop, note_barriers, noop, noop, noop, noop, noop};
|
||||
static int g_dev_state, g_window = 1, g_swapchain, g_swap_extra;
|
||||
static int g_dev_state = 1, g_window = 1, g_swapchain, g_swap_extra;
|
||||
static int g_colorspace_ext, g_swap_hdr_unavailable, g_swap_is_hdr, g_swap_hdr_want;
|
||||
static int g_plain_frame, g_first_frame_done, g_base_black;
|
||||
static int g_qfam, g_queue, g_dev, g_fence, g_swap_fmt = SCENE_FMT;
|
||||
@@ -195,7 +200,7 @@ static VkImageBlit copied;
|
||||
static struct vkp_draw recorded_draws[16];
|
||||
static VkImageBlit recorded_blits[16];
|
||||
static VkImage recorded_targets[16];
|
||||
static int recorded_after_effects[16];
|
||||
static int recorded_after_effects[16], recorded_barrier_marks[16];
|
||||
static void vkp_apply_window_request(void) {}
|
||||
static void sc_layer_hide_base(void) {}
|
||||
static void check_surface_changed(void) {}
|
||||
@@ -238,6 +243,7 @@ static void record_draw(int cmd, const struct vkp_draw *draw, const VkImageBlit
|
||||
assert(copy_count < 16);
|
||||
recorded_draws[copy_count] = *draw; recorded_blits[copy_count] = *blit;
|
||||
recorded_targets[copy_count] = target; recorded_after_effects[copy_count] = effects_count > 0;
|
||||
recorded_barrier_marks[copy_count] = barrier_count;
|
||||
copy_count++; copied = *blit;
|
||||
copied_w = draw->dw; copied_h = draw->dh; target_w = w; target_h = h;
|
||||
}
|
||||
@@ -509,11 +515,16 @@ static void check_overlay_barriers(void) {
|
||||
reset();
|
||||
struct vkp_draw layers[] = {background_draw(), fullscreen(), cursor_draw()};
|
||||
run_path(offscreen, layers, 3, NULL); check_input(1280, 720);
|
||||
int acquired = find_barrier(cursor.image, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
|
||||
int acquired = find_barrier(cursor.image, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
|
||||
assert(acquired >= 0 && recorded_barriers[acquired].srcQueueFamilyIndex == VK_QUEUE_FAMILY_FOREIGN_EXT);
|
||||
int writable = find_barrier(4, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
|
||||
int readable = find_barrier(4, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
|
||||
assert(writable > acquired && readable > writable);
|
||||
int released = find_barrier(cursor.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL);
|
||||
assert(released > acquired && recorded_barriers[released].dstQueueFamilyIndex == VK_QUEUE_FAMILY_FOREIGN_EXT);
|
||||
int last_cursor_draw = -1;
|
||||
for (int i = 0; i < copy_count; i++) if (recorded_draws[i].img == &cursor) last_cursor_draw = i;
|
||||
assert(last_cursor_draw >= 0 && released >= recorded_barrier_marks[last_cursor_draw]);
|
||||
}
|
||||
}
|
||||
static void check_postprocessing(void) {
|
||||
|
||||
@@ -11,6 +11,7 @@ import sys
|
||||
import tempfile
|
||||
from unittest import mock
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin"
|
||||
MODULE = runpy.run_path(str(BIN / "droiddeck-game-env"))
|
||||
@@ -410,6 +411,154 @@ class EgoCorePlanTest(unittest.TestCase):
|
||||
self.assertIn("added a copy of its 4-core plan", result.stderr)
|
||||
|
||||
|
||||
class SystemGraphicsLaunchTest(unittest.TestCase):
|
||||
def test_start_configures_ubisoft_with_proton_before_wrapping_the_game(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
runtime, _ = self.runtime(root)
|
||||
prefix = root / "42" / "pfx"
|
||||
(prefix / MODULE["UBISOFT_LAUNCHER"]).mkdir(parents=True)
|
||||
(prefix / "user.reg").write_text("WINE REGISTRY Version 2\n")
|
||||
env = {"DROIDDECK_POWERVR_RUNTIME": str(runtime), "STEAM_COMPAT_DATA_PATH": str(prefix.parent)}
|
||||
command = ["/selected/proton", "waitforexitandrun", "game.exe"]
|
||||
with mock.patch("subprocess.run") as run, mock.patch("os.execvpe") as execute:
|
||||
MODULE["start"](command, env, None)
|
||||
self.assertEqual(run.call_count, 2)
|
||||
for call in run.call_args_list:
|
||||
self.assertEqual(call.args[0][:3], ["/selected/proton", "runinprefix", "reg.exe"])
|
||||
self.assertEqual(execute.call_args.args[:2], (str(runtime / "run-proton.py"),
|
||||
[str(runtime / "run-proton.py"), *command]))
|
||||
|
||||
def runtime(self, root):
|
||||
runtime = root / "system_vulkan" / ("a" * 64)
|
||||
files = ["run-proton.py", "lib/libVkLayer_hybris_compat.so",
|
||||
"wsi/libVkLayer_window_system_integration.so",
|
||||
"wsi/VkLayer_window_system_integration.json"]
|
||||
files += ["dxvk/%s/%s.dll" % (arch, name) for arch in ("x32", "x64")
|
||||
for name in ("d3d8", "d3d9", "d3d10core", "d3d11", "dxgi")]
|
||||
for name in files:
|
||||
target = runtime / name
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_bytes(b"component")
|
||||
(runtime / "run-proton.py").chmod(0o755)
|
||||
return runtime, files
|
||||
|
||||
def test_other_gpus_and_non_game_calls_keep_the_original_launch(self):
|
||||
command = ["/proton", "waitforexitandrun", "game.exe"]
|
||||
base = {"STEAM_COMPAT_DATA_PATH": "/compatdata/42", "VK_LAYER_PATH": "original"}
|
||||
selected = dict(base, DROIDDECK_POWERVR_RUNTIME="/not-installed")
|
||||
cases = [(command, base), (command, dict(selected, STEAM_COMPAT_DATA_PATH="/compatdata/0")),
|
||||
(command, dict(selected, STEAM_COMPAT_DATA_PATH="/compatdata/invalid")),
|
||||
(["/proton", "run", "iscriptevaluator.exe"], selected),
|
||||
(["/proton", "getcompatpath", "x"], selected), (command[:2], selected)]
|
||||
for args, env in cases:
|
||||
with self.subTest(args=args, env=env):
|
||||
actual, inherited = MODULE["system_graphics_launch"](args, env)
|
||||
self.assertIs(actual, args)
|
||||
self.assertIs(inherited, env)
|
||||
|
||||
def test_system_graphics_follow_game_configuration_and_preserve_other_keys(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
runtime, _ = self.runtime(Path(tmp))
|
||||
base = {"DROIDDECK_POWERVR_RUNTIME": str(runtime), "STEAM_COMPAT_DATA_PATH": "/compatdata/42"}
|
||||
config = {"version": 1, "games": {"42": {
|
||||
"PROTON_USE_WINED3D": "1", "DISABLE_WSI_LAYER": "1",
|
||||
"ENABLE_VK_LAYER_VALVE_steam_fossilize_1": "1", "HYBRIS_BC_TEXTURES": "0",
|
||||
"VK_LAYER_PATH": "old", "VK_INSTANCE_LAYERS": "old", "ENABLE_GAMESCOPE_WSI": "1",
|
||||
"FEX_TSOENABLED": "1", "WINESERVER": "/selected/wineserver", "CUSTOM": "literal $value",
|
||||
}}}
|
||||
env = MODULE["apply_config"](base, config, "42")
|
||||
command = ["/selected/proton", "waitforexitandrun", "game with spaces.exe"]
|
||||
launch, result = MODULE["system_graphics_launch"](command, env)
|
||||
self.assertEqual(launch, [str(runtime / "run-proton.py"), *command])
|
||||
self.assertEqual(result["HYBRIS_BC_TEXTURES"], "dxvk")
|
||||
self.assertEqual(result["VK_LAYER_PATH"], f"{runtime}/wsi:{runtime}/lib")
|
||||
self.assertEqual(result["VK_INSTANCE_LAYERS"], "VK_LAYER_window_system_integration:VK_LAYER_HYBRIS_compat")
|
||||
self.assertEqual(result["VK_LOADER_LAYERS_DISABLE"], "*gamescope*")
|
||||
self.assertEqual(result["ENABLE_GAMESCOPE_WSI"], "0")
|
||||
self.assertEqual(result["DISABLE_VK_LAYER_VALVE_steam_fossilize_1"], "1")
|
||||
for key in ("PROTON_USE_WINED3D", "DISABLE_WSI_LAYER", "ENABLE_VK_LAYER_VALVE_steam_fossilize_1"):
|
||||
self.assertNotIn(key, result)
|
||||
self.assertIn(key, env)
|
||||
for key in ("FEX_TSOENABLED", "WINESERVER", "CUSTOM"):
|
||||
self.assertEqual(result[key], env[key])
|
||||
|
||||
def test_xclipse_selection_adds_its_layers_layer_path_and_dxvk_payload(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
runtime, _ = self.runtime(Path(tmp))
|
||||
env = {"DROIDDECK_POWERVR_RUNTIME": str(runtime), "STEAM_COMPAT_DATA_PATH": "/compatdata/42",
|
||||
"DROIDDECK_HYBRIS_LAYERS": "VK_LAYER_DROIDDECK_xclipse:VK_LAYER_HYBRIS_compat",
|
||||
"DROIDDECK_HYBRIS_LAYER_PATH": "/usr/local/lib/droiddeck-xclipse",
|
||||
"DROIDDECK_HYBRIS_DXVK": "dxvk-2.6.2"}
|
||||
command = ["/proton", "waitforexitandrun", "game.exe"]
|
||||
# The selected payload is required like the default one.
|
||||
with self.assertRaises(MODULE["SystemGraphicsError"]):
|
||||
MODULE["system_graphics_launch"](command, env)
|
||||
for arch in ("x32", "x64"):
|
||||
for name in ("d3d8", "d3d9", "d3d10core", "d3d11", "dxgi"):
|
||||
target = runtime / "dxvk-2.6.2" / arch / (name + ".dll")
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_bytes(b"component")
|
||||
launch, result = MODULE["system_graphics_launch"](command, env)
|
||||
self.assertEqual(launch, [str(runtime / "run-proton.py"), *command])
|
||||
self.assertEqual(result["VK_INSTANCE_LAYERS"],
|
||||
"VK_LAYER_window_system_integration:VK_LAYER_DROIDDECK_xclipse:VK_LAYER_HYBRIS_compat")
|
||||
self.assertEqual(result["VK_LAYER_PATH"], f"{runtime}/wsi:{runtime}/lib:/usr/local/lib/droiddeck-xclipse")
|
||||
self.assertEqual(result["DROIDDECK_HYBRIS_DXVK"], "dxvk-2.6.2")
|
||||
for name in ("../dxvk", "other", "dxvk/x"):
|
||||
with self.subTest(name=name), self.assertRaises(MODULE["SystemGraphicsError"]):
|
||||
MODULE["system_graphics_launch"](command, dict(env, DROIDDECK_HYBRIS_DXVK=name))
|
||||
|
||||
def test_incomplete_runtime_fails_before_any_proton_exec(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
runtime, files = self.runtime(Path(tmp))
|
||||
env = {"DROIDDECK_POWERVR_RUNTIME": str(runtime), "STEAM_COMPAT_DATA_PATH": "/compatdata/42"}
|
||||
command = ["/proton", "waitforexitandrun", "game.exe"]
|
||||
for name in files:
|
||||
target = runtime / name
|
||||
original = target.read_bytes()
|
||||
for missing in (False, True):
|
||||
with self.subTest(name=name, missing=missing):
|
||||
target.unlink() if missing else target.write_bytes(b"")
|
||||
with patch.object(os, "execvpe") as execute:
|
||||
with self.assertRaises(MODULE["SystemGraphicsError"]):
|
||||
MODULE["exec_proton"](command, env)
|
||||
execute.assert_not_called()
|
||||
target.write_bytes(original)
|
||||
if name == "run-proton.py":
|
||||
target.chmod(0o755)
|
||||
(runtime / "run-proton.py").chmod(0o644)
|
||||
with self.assertRaises(MODULE["SystemGraphicsError"]):
|
||||
MODULE["system_graphics_launch"](command, env)
|
||||
with self.assertRaises(MODULE["SystemGraphicsError"]):
|
||||
MODULE["system_graphics_launch"](command, dict(env, DROIDDECK_POWERVR_RUNTIME="relative"))
|
||||
|
||||
def test_wrapper_receives_the_sync_selected_proton(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
runtime, _ = self.runtime(root)
|
||||
env = {"HOME": tmp, "DROIDDECK_POWERVR_RUNTIME": str(runtime),
|
||||
"STEAM_COMPAT_DATA_PATH": "/compatdata/42"}
|
||||
command = ["/stock/proton", "waitforexitandrun", "game.exe"]
|
||||
selected = ["/sync-pack/proton", *command[1:]]
|
||||
selected_env = dict(env, WINESERVER="/sync-pack/wineserver", BL_SYNC_PACK="selected")
|
||||
main = MODULE["main"]
|
||||
with patch.dict(os.environ, env, clear=True), patch.object(sys, "argv", ["game-env", *command]), \
|
||||
patch.dict(main.__globals__, {"load_sync": lambda: {},
|
||||
"select_sync": lambda *args: (selected, selected_env),
|
||||
"win_components": lambda *args: ""}), \
|
||||
patch.object(os, "execvpe", side_effect=SystemExit(23)) as execute:
|
||||
with self.assertRaises(SystemExit) as stopped:
|
||||
main()
|
||||
self.assertEqual(stopped.exception.code, 23)
|
||||
execute.assert_called_once()
|
||||
path, args, actual_env = execute.call_args.args
|
||||
self.assertEqual(path, str(runtime / "run-proton.py"))
|
||||
self.assertEqual(args, [path, *selected])
|
||||
self.assertEqual(actual_env["WINESERVER"], "/sync-pack/wineserver")
|
||||
self.assertEqual(actual_env["BL_SYNC_PACK"], "selected")
|
||||
|
||||
|
||||
class GameDebugLoggingTest(unittest.TestCase):
|
||||
def test_maintenance_precision_survives_run_with_performance_game_settings(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
@@ -807,6 +956,55 @@ class GameEnvironmentTest(unittest.TestCase):
|
||||
subprocess.run(["bash", "-c", script, "test", str(base)], env=env, check=True)
|
||||
self.assertEqual(target.read_text(), "general")
|
||||
|
||||
def test_system_powervr_preserves_dxvk_profiles_without_applying_them(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
home = root / "home"
|
||||
component_dir = home / ".local/share/droiddeck-components"
|
||||
component_dir.mkdir(parents=True)
|
||||
base = root / "proton"
|
||||
paths = {
|
||||
"dxvk": "files/lib/wine/dxvk/aarch64-windows/d3d11.dll",
|
||||
"fex": "files/lib/wine/aarch64-windows/libarm64ecfex.dll",
|
||||
"vkd3d": "files/lib/wine/vkd3d-proton/aarch64-windows/d3d12.dll",
|
||||
}
|
||||
rows = []
|
||||
for comp, rel in paths.items():
|
||||
target = base / rel
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_text("bundled " + comp)
|
||||
for scope in ("*", "42"):
|
||||
source = root / (comp + ("-general" if scope == "*" else "-game"))
|
||||
source.write_text(source.name)
|
||||
rows.append("%s\tproton\tbuild-1\t%s\t%s\t%s\t%s\n" % (
|
||||
scope, comp, rel, hashlib.sha256(source.read_bytes()).hexdigest(), source,
|
||||
))
|
||||
leftover = (base / paths["dxvk"]).with_name("d3d8.dll")
|
||||
leftover.write_text("bundled d3d8")
|
||||
rows.append("42\tproton\tbuild-1\tdxvk\t%s\t-\t-\n" % leftover.relative_to(base))
|
||||
(base / "version").write_text("1 build-1\n")
|
||||
selection = component_dir / "desired.tsv"
|
||||
selection.write_text("".join(rows))
|
||||
saved = selection.read_bytes()
|
||||
script = COMPAT["BL_COMPONENTS_SETUP"] + '\nverb=waitforexitandrun; bl_components "$1"\n'
|
||||
env = dict(os.environ, HOME=str(home), STEAM_COMPAT_DATA_PATH="/steam/compatdata/42",
|
||||
DROIDDECK_POWERVR_RUNTIME="/system_vulkan/runtime")
|
||||
|
||||
subprocess.run(["bash", "-c", script, "test", str(base)], env=env, check=True)
|
||||
|
||||
self.assertEqual((base / paths["dxvk"]).read_text(), "bundled dxvk")
|
||||
self.assertEqual(leftover.read_text(), "bundled d3d8")
|
||||
for comp in ("fex", "vkd3d"):
|
||||
self.assertEqual((base / paths[comp]).read_text(), comp + "-game")
|
||||
self.assertEqual(selection.read_bytes(), saved)
|
||||
|
||||
# A subsequent manual-driver session still applies the saved per-game DXVK choice.
|
||||
env.pop("DROIDDECK_POWERVR_RUNTIME")
|
||||
subprocess.run(["bash", "-c", script, "test", str(base)], env=env, check=True)
|
||||
self.assertEqual((base / paths["dxvk"]).read_text(), "dxvk-game")
|
||||
self.assertFalse(leftover.exists())
|
||||
self.assertEqual(selection.read_bytes(), saved)
|
||||
|
||||
def test_component_scope_matches_environment_scope_for_shortcut_ids(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
@@ -1294,6 +1492,49 @@ class GameEnvironmentTest(unittest.TestCase):
|
||||
with self.assertRaises(ValueError):
|
||||
MODULE["apply_config"]({}, {**config, "dxvkConfigGames": []}, "42")
|
||||
|
||||
def test_game_logs_only_when_asked_and_only_for_game_launches(self):
|
||||
game_logs = MODULE["game_logs"]
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
command = ["/proton", "waitforexitandrun", "/games/Hades/Hades.exe"]
|
||||
env = {"BL_DEBUG_DIR": tmp, "VK_DRIVER_FILES": "/icd.json"}
|
||||
self.assertEqual(game_logs(command, env, "1145360", now=0), env)
|
||||
on = dict(env, BL_GAME_LOGS="1")
|
||||
self.assertEqual(game_logs(["/proton", "run", "x.exe"], on, "1145360", now=0), on)
|
||||
result = game_logs(command, on, "1145360", now=0)
|
||||
folder = Path(result["PROTON_LOG_DIR"])
|
||||
self.assertEqual(folder.parent, Path(tmp) / "games")
|
||||
self.assertTrue(folder.name.endswith("-1145360"))
|
||||
self.assertEqual(result["DXVK_LOG_PATH"], str(folder))
|
||||
self.assertEqual(result["PROTON_LOG"], "1")
|
||||
launch = (folder / "launch.txt").read_text()
|
||||
self.assertIn("VK_DRIVER_FILES=/icd.json", launch)
|
||||
self.assertNotIn("PROTON_LOG", env)
|
||||
named = game_logs(command, on, None, now=0)
|
||||
self.assertTrue(Path(named["PROTON_LOG_DIR"]).name.endswith("-Hades"))
|
||||
|
||||
def test_rapid_game_launches_keep_separate_diagnostics(self):
|
||||
with tempfile.TemporaryDirectory() as tmp, mock.patch("subprocess.Popen"):
|
||||
env = {"BL_GAME_LOGS": "1", "BL_DEBUG_DIR": tmp}
|
||||
first = MODULE["game_logs"](["/proton", "waitforexitandrun", "first.exe"], env, "42", now=0)
|
||||
second = MODULE["game_logs"](["/proton", "waitforexitandrun", "second.exe"], env, "42", now=0)
|
||||
self.assertNotEqual(first["PROTON_LOG_DIR"], second["PROTON_LOG_DIR"])
|
||||
self.assertIn("exe: first.exe", (Path(first["PROTON_LOG_DIR"]) / "launch.txt").read_text())
|
||||
self.assertIn("exe: second.exe", (Path(second["PROTON_LOG_DIR"]) / "launch.txt").read_text())
|
||||
|
||||
def test_open_driver_pairs_report_the_drivers_own_vkd3d_caps(self):
|
||||
apply = MODULE["apply_config"]
|
||||
config = {"version": 1, "shared": {"VKD3D_FEATURE_LEVEL": "12_2", "VKD3D_SHADER_MODEL": "6_9"},
|
||||
"games": {"42": {"VKD3D_SHADER_MODEL": "6_6"}}}
|
||||
adreno = apply({}, config, "1")
|
||||
self.assertEqual(adreno["VKD3D_FEATURE_LEVEL"], "12_2")
|
||||
pair = apply({"BL_OPEN_DRIVER": "1"}, config, "1")
|
||||
self.assertNotIn("VKD3D_FEATURE_LEVEL", pair)
|
||||
self.assertNotIn("VKD3D_SHADER_MODEL", pair)
|
||||
self.assertEqual(pair["DROIDDECK_VKD3D_CAPS"], "driver")
|
||||
own = apply({"BL_OPEN_DRIVER": "1"}, config, "42")
|
||||
self.assertEqual(own["VKD3D_SHADER_MODEL"], "6_6")
|
||||
self.assertNotIn("VKD3D_FEATURE_LEVEL", own)
|
||||
|
||||
def test_game_ids_and_probes(self):
|
||||
for prefix in ("", "/compatdata/0", "/compatdata/0-123", "/compatdata/nope", "/compatdata/4294967296"):
|
||||
self.assertIsNone(MODULE["game_id"]({"STEAM_COMPAT_DATA_PATH": prefix}))
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
SESSION = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-session"
|
||||
DESKTOP_GPU = Path(__file__).resolve().parents[1] / "linuxfs/desktop/droiddeck-gpu"
|
||||
|
||||
|
||||
class GamescopeBackendTest(unittest.TestCase):
|
||||
def select(self, backend=None):
|
||||
source = SESSION.read_text()
|
||||
start = source.index(' backend=${BL_GAMESCOPE_BACKEND:-wayland}')
|
||||
end = source.index('\n', source.index(' args=(--backend ', start))
|
||||
script = 'width=1280; height=720; nested=1280\n' + source[start:end]
|
||||
script += '\nprintf "%s\\n" "${args[0]}" "${args[1]}" "${SDL_VIDEODRIVER:-unset}"\n'
|
||||
env = dict(os.environ)
|
||||
env.pop("BL_GAMESCOPE_BACKEND", None)
|
||||
env.pop("SDL_VIDEODRIVER", None)
|
||||
if backend is not None:
|
||||
env["BL_GAMESCOPE_BACKEND"] = backend
|
||||
return subprocess.run(["bash", "-c", script], env=env, text=True,
|
||||
capture_output=True, timeout=5)
|
||||
|
||||
def test_default_retains_the_wayland_backend(self):
|
||||
result = self.select()
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
self.assertEqual(["--backend", "wayland", "unset"], result.stdout.splitlines())
|
||||
|
||||
def test_sdl_uses_the_host_wayland_vulkan_swapchain(self):
|
||||
result = self.select("sdl")
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
self.assertEqual(["--backend", "sdl", "wayland"], result.stdout.splitlines())
|
||||
|
||||
def test_unknown_backend_fails_before_gamescope(self):
|
||||
result = self.select("drm")
|
||||
self.assertEqual(64, result.returncode)
|
||||
self.assertIn("unsupported gamescope backend: drm", result.stdout)
|
||||
|
||||
|
||||
class DesktopGamescopeBackendTest(unittest.TestCase):
|
||||
def launch(self, backend=None):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
capture = root / "gamescope.json"
|
||||
gamescope = root / "gamescope"
|
||||
gamescope.write_text(
|
||||
f"#!{sys.executable}\n"
|
||||
"import json, os, sys\n"
|
||||
"from pathlib import Path\n"
|
||||
"Path(os.environ['GAMESCOPE_CAPTURE']).write_text(json.dumps({\n"
|
||||
" 'args': sys.argv[1:],\n"
|
||||
" 'sdl': os.environ.get('SDL_VIDEODRIVER'),\n"
|
||||
" 'gdk': os.environ.get('GDK_BACKEND'),\n"
|
||||
" 'qt': os.environ.get('QT_QPA_PLATFORM'),\n"
|
||||
" 'wayland': os.environ.get('WAYLAND_DISPLAY'),\n"
|
||||
"}))\n"
|
||||
)
|
||||
gamescope.chmod(0o755)
|
||||
env = dict(os.environ)
|
||||
for name in ("BL_GAMESCOPE_BACKEND", "BL_DEBUG_DIR", "BL_FPS", "BL_REFRESH", "BL_HDR"):
|
||||
env.pop(name, None)
|
||||
env.update(PATH=f"{root}{os.pathsep}{env.get('PATH', '')}",
|
||||
GAMESCOPE_CAPTURE=str(capture), WAYLAND_DISPLAY="desktop-0", BL_DESKTOP_GPU_WINDOW="0",
|
||||
SDL_VIDEODRIVER="dummy", GDK_BACKEND="wayland", QT_QPA_PLATFORM="wayland")
|
||||
if backend is not None:
|
||||
env["BL_GAMESCOPE_BACKEND"] = backend
|
||||
result = subprocess.run(["bash", str(DESKTOP_GPU), "demo", "one argument"],
|
||||
env=env, text=True, capture_output=True, timeout=5)
|
||||
return result, json.loads(capture.read_text()) if capture.exists() else None
|
||||
|
||||
def assert_xwayland_application(self, capture):
|
||||
args = capture["args"]
|
||||
self.assertEqual(["env", "SDL_VIDEODRIVER=x11", "/usr/local/bin/droiddeck-gpu-window",
|
||||
"demo", "one argument"], args[args.index("--") + 1:])
|
||||
self.assertEqual("x11", capture["gdk"])
|
||||
self.assertEqual("xcb", capture["qt"])
|
||||
self.assertEqual("wayland-0", capture["wayland"])
|
||||
|
||||
def test_default_keeps_wayland_and_xwayland_application(self):
|
||||
result, capture = self.launch()
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
self.assertEqual(["--backend", "wayland"], capture["args"][:2])
|
||||
self.assertEqual("x11", capture["sdl"])
|
||||
self.assert_xwayland_application(capture)
|
||||
|
||||
def test_sdl_uses_wayland_without_leaking_to_the_application(self):
|
||||
result, capture = self.launch("sdl")
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
self.assertEqual(["--backend", "sdl"], capture["args"][:2])
|
||||
self.assertEqual("wayland", capture["sdl"])
|
||||
self.assert_xwayland_application(capture)
|
||||
|
||||
def test_unknown_backend_fails_before_gamescope(self):
|
||||
result, capture = self.launch("drm")
|
||||
self.assertEqual(64, result.returncode)
|
||||
self.assertIn("unsupported gamescope backend: drm", result.stderr)
|
||||
self.assertIsNone(capture)
|
||||
@@ -0,0 +1,47 @@
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
SOURCE = Path(__file__).resolve().parents[1] / "linuxfs/preload/oomadj.c"
|
||||
|
||||
PROGRAM = r"""
|
||||
#include <stdio.h>
|
||||
const char *bl_oom_adj_redirect(const char *path, int writing);
|
||||
int main(int argc, char **argv) {
|
||||
for (int i = 1; i + 1 < argc; i += 2) printf("%s\n", bl_oom_adj_redirect(argv[i + 1], argv[i][0] == 'w'));
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which("cc"), "needs cc")
|
||||
class OomAdjPreloadTest(unittest.TestCase):
|
||||
def test_only_writes_to_oom_files_go_to_dev_null(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
main = Path(tmp) / "main.c"
|
||||
main.write_text(PROGRAM)
|
||||
binary = Path(tmp) / "probe"
|
||||
subprocess.run(["cc", "-o", str(binary), str(main), str(SOURCE)], check=True)
|
||||
cases = [
|
||||
("w", "/proc/self/oom_score_adj", "/dev/null"),
|
||||
("w", "/proc/123/oom_score_adj", "/dev/null"),
|
||||
("w", "/proc/thread-self/oom_score_adj", "/dev/null"),
|
||||
("w", "/proc/12/task/34/oom_score_adj", "/dev/null"),
|
||||
("w", "/proc/self/oom_adj", "/dev/null"),
|
||||
("r", "/proc/self/oom_score_adj", "/proc/self/oom_score_adj"),
|
||||
("w", "/proc/self/oom_score", "/proc/self/oom_score"),
|
||||
("w", "/proc/abc/oom_score_adj", "/proc/abc/oom_score_adj"),
|
||||
("w", "/tmp/oom_score_adj", "/tmp/oom_score_adj"),
|
||||
]
|
||||
args = [str(binary)]
|
||||
for mode, path, _ in cases:
|
||||
args += [mode, path]
|
||||
out = subprocess.run(args, capture_output=True, text=True, check=True)
|
||||
self.assertEqual(out.stdout.split(), [want for _, _, want in cases])
|
||||
self.assertIn("oom_score_adj raise was dropped", out.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,215 @@
|
||||
"""Test freshness, narrow output, and lock handling without accessing a device."""
|
||||
from datetime import datetime, timezone
|
||||
import importlib.util
|
||||
import json
|
||||
import io
|
||||
import os
|
||||
from pathlib import Path
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
spec = importlib.util.spec_from_file_location('reset_projection', Path(__file__).resolve().parents[1] / 'pixel_reset_diagnostics.py')
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
|
||||
|
||||
class ResetProjectionTest(unittest.TestCase):
|
||||
def test_only_primary_state(self):
|
||||
self.assertEqual(module.primary_state('Private space secret\nStarted users state: [0=RUNNING_UNLOCKED, 10=STOPPED]'), 'RUNNING_UNLOCKED')
|
||||
self.assertEqual(module.primary_state('State: RUNNING_UNLOCKED'), 'unknown')
|
||||
|
||||
def test_stale_body_not_used(self):
|
||||
raw = '2026-10-10 20:10:09 SYSTEM_LAST_KMSG (text, 1024 bytes)\nGNOC error type 0x2000'
|
||||
result = module.kernel_projection(raw, 'America/Toronto', datetime(2026, 10, 11, 21, tzinfo=timezone.utc))
|
||||
self.assertEqual(result['status'], 'stale_entry_not_attributed_to_current_trial')
|
||||
self.assertNotIn('categories', result)
|
||||
|
||||
def test_repeated_dst_hour_is_ambiguous_before_freshness(self):
|
||||
raw = '2026-11-01 01:30:00 SYSTEM_LAST_KMSG\nGNOC error type 0x2000'
|
||||
for after in (None, datetime(2026, 11, 1, 6, tzinfo=timezone.utc)):
|
||||
with self.subTest(after=after):
|
||||
result = module.kernel_projection(raw, 'America/Toronto', after)
|
||||
self.assertEqual(result['status'], 'ambiguous_device_local_time')
|
||||
self.assertNotIn('entry_date_utc', result)
|
||||
self.assertNotIn('categories', result)
|
||||
self.assertNotIn('hardware_fields', result)
|
||||
|
||||
def test_skipped_dst_hour_is_not_a_real_instant(self):
|
||||
raw = '2026-03-08 02:30:00 SYSTEM_LAST_KMSG\nGNOC error type 0x2000'
|
||||
result = module.kernel_projection(raw, 'America/Toronto')
|
||||
self.assertEqual(result['status'], 'nonexistent_device_local_time')
|
||||
self.assertNotIn('entry_date_utc', result)
|
||||
self.assertNotIn('categories', result)
|
||||
|
||||
def test_unambiguous_times_keep_correct_offsets_and_cutoff(self):
|
||||
for stamp, expected in (('2026-11-01 00:30:00', '2026-11-01T04:30:00+00:00'),
|
||||
('2026-11-01 02:30:00', '2026-11-01T07:30:00+00:00'),
|
||||
('2026-03-08 03:30:00', '2026-03-08T07:30:00+00:00')):
|
||||
with self.subTest(stamp=stamp):
|
||||
raw = stamp + ' SYSTEM_LAST_KMSG\nGNOC'
|
||||
result = module.kernel_projection(raw, 'America/Toronto')
|
||||
self.assertEqual(result['entry_date_utc'], expected)
|
||||
self.assertEqual(result['status'], 'projected_entry_not_a_root_cause')
|
||||
cutoff = datetime.fromisoformat(expected)
|
||||
self.assertEqual(module.kernel_projection(raw, 'America/Toronto', cutoff)['status'],
|
||||
'projected_entry_not_a_root_cause')
|
||||
|
||||
def test_latest_entry_and_no_arbitrary_body(self):
|
||||
raw = ('2026-10-10 20:10:09 SYSTEM_LAST_KMSG (text)\nGNOC error type 0x1111\n'
|
||||
'2026-10-11 17:35:01 SYSTEM_LAST_KMSG (text)\n'
|
||||
'PRIVATE_TEST_VALUE=a_secret_that_must_not_be_emitted\n'
|
||||
'Error from GNOC at addr 0x28220000\nGNOC error type 0x2000\n'
|
||||
'Reboot reason: 0xc005 - Secret arbitrary description\nLast boot reason: reset,warm,gnoc_error\n')
|
||||
result = module.kernel_projection(raw, 'America/Toronto', datetime(2026, 10, 11, 21, tzinfo=timezone.utc))
|
||||
self.assertEqual(result['entry_date_utc'], '2026-10-11T21:35:01+00:00')
|
||||
self.assertEqual(result['hardware_fields']['gnoc_error_types'], ['0x2000'])
|
||||
self.assertNotIn('0x1111', json.dumps(result))
|
||||
self.assertNotIn('a_secret', json.dumps(result))
|
||||
self.assertNotIn('arbitrary description', json.dumps(result))
|
||||
self.assertFalse(result['root_cause_proven'])
|
||||
|
||||
def test_missing_entry_and_timezone(self):
|
||||
self.assertEqual(module.kernel_projection('Permission denied', 'America/Toronto')['status'], 'no_accessible_entry')
|
||||
self.assertEqual(module.kernel_projection('2026-10-11 17:00:00 SYSTEM_LAST_KMSG\nGNOC', 'Unknown/Region')['status'], 'unknown_device_timezone')
|
||||
|
||||
def test_reason_rejects_paths_and_urls(self):
|
||||
self.assertEqual(module.safe_reason('reset,warm,gnoc_error\n'), 'reset,warm,gnoc_error')
|
||||
self.assertEqual(module.safe_reason('https://private.invalid/login?secret=abc'), 'unknown')
|
||||
self.assertEqual(module.safe_reason('/data/private'), 'unknown')
|
||||
|
||||
def test_reason_only_recognized_exact_values(self):
|
||||
for reason in ('cold', 'hard', 'warm', 'reboot', 'shutdown', 'recovery',
|
||||
'bootloader', 'kernel_panic', 'watchdog', 'reset,warm,gnoc_error'):
|
||||
with self.subTest(reason=reason):
|
||||
self.assertEqual(module.safe_reason(reason + '\n'), reason)
|
||||
for reason in ('PRIVATE TEST VALUE', 'private_test_value', '123456',
|
||||
'reboot,private_test_value', 'reset,warm,gnoc_error,private_test_value',
|
||||
'reset,warm,gnoc_error trailing_private_test_value', ''):
|
||||
with self.subTest(reason=reason):
|
||||
self.assertEqual(module.safe_reason(reason), 'unknown')
|
||||
|
||||
def test_kernel_reason_uses_same_fixed_projection(self):
|
||||
raw = ('2026-10-11 17:35:01 SYSTEM_LAST_KMSG (text)\n'
|
||||
'Last boot reason: private_test_value\n'
|
||||
'Last boot reason: reset,warm,gnoc_error trailing_private_test_value\n'
|
||||
'Last boot reason: reset,warm,gnoc_error\n'
|
||||
'Last boot reason:\nPRIVATE TEST VALUE\n')
|
||||
result = module.kernel_projection(raw, 'America/Toronto')
|
||||
self.assertEqual(result['last_boot_reasons'], ['reset,warm,gnoc_error', 'unknown'])
|
||||
self.assertNotIn('private_test_value', json.dumps(result))
|
||||
self.assertNotIn('PRIVATE TEST VALUE', json.dumps(result))
|
||||
|
||||
def test_primary_state_uses_fixed_categories(self):
|
||||
for state in ('RUNNING_LOCKED', 'RUNNING_UNLOCKING', 'RUNNING_UNLOCKED'):
|
||||
self.assertEqual(module.primary_state('Started users state: [0=' + state + ']'), state)
|
||||
for state in ('RUNNING_PRIVATE_TEST_VALUE', 'RUNNING_UNLOCKED_PRIVATE',
|
||||
'RUNNING_UNLOCKED=private_test_value'):
|
||||
self.assertEqual(module.primary_state('Started users state: [0=' + state + ']'), 'unknown')
|
||||
|
||||
def test_property_reason_never_exports_custom_text(self):
|
||||
def run(argv, **kwargs):
|
||||
if argv[-2:] == ['getprop', 'ro.boot.bootreason']:
|
||||
text = 'PRIVATE TEST VALUE'
|
||||
elif argv[-2:] == ['getprop', 'sys.boot.reason']:
|
||||
text = 'reset,warm,gnoc_error,private_test_value'
|
||||
elif argv[-1] == 'persist.sys.timezone':
|
||||
text = 'America/Toronto'
|
||||
else:
|
||||
text = ''
|
||||
return subprocess.CompletedProcess(argv, 0, text, '')
|
||||
with patch.object(module.subprocess, 'run', side_effect=run):
|
||||
result = module.collect('adb', 'test-device')
|
||||
self.assertEqual(result['bootloader_reason'], 'unknown')
|
||||
self.assertEqual(result['system_boot_reason'], 'unknown')
|
||||
self.assertNotIn('PRIVATE TEST VALUE', json.dumps(result))
|
||||
self.assertNotIn('private_test_value', json.dumps(result))
|
||||
|
||||
@unittest.skipUnless(os.name == 'posix', 'POSIX private file modes')
|
||||
def test_cli_output_is_private_before_writing(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
output = Path(directory) / 'diagnostics.json'
|
||||
saved_umask = os.umask(0)
|
||||
original_fdopen = os.fdopen
|
||||
original_path_open = Path.open
|
||||
creation_modes = []
|
||||
def inspect_stream(stream):
|
||||
try:
|
||||
creation_modes.append(stat.S_IMODE(os.fstat(stream.fileno()).st_mode))
|
||||
self.assertEqual(os.fstat(stream.fileno()).st_size, 0)
|
||||
self.assertEqual(creation_modes[-1], 0o600)
|
||||
except BaseException:
|
||||
stream.close()
|
||||
raise
|
||||
return stream
|
||||
def inspect_fd(fd, *args, **kwargs):
|
||||
return inspect_stream(original_fdopen(fd, *args, **kwargs))
|
||||
def inspect_path(path, *args, **kwargs):
|
||||
stream = original_path_open(path, *args, **kwargs)
|
||||
return inspect_stream(stream) if path == output else stream
|
||||
try:
|
||||
with patch.object(sys, 'argv', ['diagnostics', '--serial', 'test-device',
|
||||
'--output', str(output)]), \
|
||||
patch.object(module, 'collect', return_value={'boot_count': 12}), \
|
||||
patch.object(os, 'fdopen', side_effect=inspect_fd), \
|
||||
patch.object(Path, 'open', new=inspect_path), \
|
||||
patch('sys.stdout', new_callable=io.StringIO):
|
||||
module.main()
|
||||
finally:
|
||||
os.umask(saved_umask)
|
||||
self.assertEqual(creation_modes, [0o600])
|
||||
self.assertEqual(stat.S_IMODE(output.stat().st_mode), 0o600)
|
||||
self.assertEqual(json.loads(output.read_text()), {'boot_count': 12})
|
||||
|
||||
def test_output_refuses_existing_file(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
output = Path(directory) / 'diagnostics.json'
|
||||
output.write_text('existing controlled test data')
|
||||
with self.assertRaises(FileExistsError):
|
||||
module.write_private_output(output, '{"replacement":true}\n')
|
||||
self.assertEqual(output.read_text(), 'existing controlled test data')
|
||||
|
||||
@unittest.skipUnless(os.name == 'posix', 'POSIX symlink behavior')
|
||||
def test_output_refuses_symlink_without_touching_target(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
target = Path(directory) / 'target.json'
|
||||
target.write_text('existing controlled test data')
|
||||
output = Path(directory) / 'diagnostics.json'
|
||||
output.symlink_to(target)
|
||||
with self.assertRaises(FileExistsError):
|
||||
module.write_private_output(output, '{"replacement":true}\n')
|
||||
self.assertTrue(output.is_symlink())
|
||||
self.assertEqual(target.read_text(), 'existing controlled test data')
|
||||
|
||||
def test_locked_skips_kernel_body(self):
|
||||
commands = []
|
||||
def run(argv, **kwargs):
|
||||
commands.append(argv)
|
||||
if argv[-2:] == ['dumpsys', 'user']:
|
||||
text = 'Started users state: [0=RUNNING_LOCKED]'
|
||||
elif argv[-1] == 'persist.sys.timezone':
|
||||
text = 'America/Toronto'
|
||||
elif argv[-3:] == ['get', 'global', 'boot_count']:
|
||||
text = '12'
|
||||
else:
|
||||
text = ''
|
||||
return subprocess.CompletedProcess(argv, 0, text, 'PRIVATE_STDERR')
|
||||
with patch.object(module.subprocess, 'run', side_effect=run):
|
||||
result = module.collect('adb', 'test-device', True)
|
||||
self.assertEqual(result['kernel']['status'], 'requires_user_unlock')
|
||||
self.assertFalse(any('--print' in command for command in commands))
|
||||
self.assertNotIn('PRIVATE_STDERR', json.dumps(result))
|
||||
|
||||
def test_command_failure_does_not_export_stderr(self):
|
||||
with patch.object(module.subprocess, 'run', return_value=subprocess.CompletedProcess([], 1, 'UNRELATED_DATA', 'PRIVATE_STDERR')):
|
||||
result = module.collect('adb', 'test-device', True)
|
||||
self.assertIsNone(result['boot_count'])
|
||||
self.assertNotIn('UNRELATED_DATA', json.dumps(result))
|
||||
self.assertNotIn('PRIVATE_STDERR', json.dumps(result))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,291 @@
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tarfile
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
from zipfile import ZipFile, ZipInfo
|
||||
|
||||
|
||||
spec = importlib.util.spec_from_file_location('powervr_fetch',
|
||||
Path(__file__).resolve().parents[1] / 'powervr/fetch.py')
|
||||
runtime = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(runtime)
|
||||
|
||||
|
||||
def elf():
|
||||
content = bytearray(64)
|
||||
content[:6], content[18:20] = b'\x7fELF\x02\x01', b'\xb7\x00'
|
||||
return bytes(content)
|
||||
|
||||
|
||||
def pe(architecture):
|
||||
content = bytearray(128)
|
||||
content[:2], content[60:64], content[64:68] = b'MZ', (64).to_bytes(4, 'little'), b'PE\0\0'
|
||||
content[68:70] = b'\x4c\x01' if architecture == 'x32' else b'\x64\x86'
|
||||
content[88:90] = b'\x0b\x01' if architecture == 'x32' else b'\x0b\x02'
|
||||
return bytes(content)
|
||||
|
||||
|
||||
def tar(entries):
|
||||
stream = io.BytesIO()
|
||||
with tarfile.open(fileobj=stream, mode='w') as archive:
|
||||
for name, kind, content in entries:
|
||||
info = tarfile.TarInfo(name)
|
||||
info.type = kind
|
||||
if kind in (tarfile.SYMTYPE, tarfile.LNKTYPE):
|
||||
info.linkname = content
|
||||
archive.addfile(info)
|
||||
elif kind == tarfile.REGTYPE:
|
||||
info.size = len(content)
|
||||
archive.addfile(info, io.BytesIO(content))
|
||||
else:
|
||||
archive.addfile(info)
|
||||
return subprocess.run(['zstd', '-q', '-c'], input=stream.getvalue(),
|
||||
capture_output=True, check=True).stdout
|
||||
|
||||
|
||||
def tar_gz(entries):
|
||||
stream = io.BytesIO()
|
||||
with tarfile.open(fileobj=stream, mode='w:gz') as archive:
|
||||
for name, kind, content in entries:
|
||||
info = tarfile.TarInfo(name)
|
||||
info.type = kind
|
||||
if kind == tarfile.SYMTYPE:
|
||||
info.linkname = content
|
||||
archive.addfile(info)
|
||||
elif kind == tarfile.REGTYPE:
|
||||
info.size = len(content)
|
||||
archive.addfile(info, io.BytesIO(content))
|
||||
else:
|
||||
archive.addfile(info)
|
||||
return stream.getvalue()
|
||||
|
||||
|
||||
def upstream_dxvk(version, architecture_of=lambda arch: arch):
|
||||
return {'dxvk-%s/%s/%s' % (version, arch, name): pe(architecture_of(arch))
|
||||
for arch in ('x32', 'x64')
|
||||
for name in ('d3d8.dll', 'd3d9.dll', 'd3d10core.dll', 'd3d11.dll', 'dxgi.dll')}
|
||||
|
||||
|
||||
class PowerVRRuntimeTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temporary = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temporary.cleanup)
|
||||
self.root = Path(self.temporary.name)
|
||||
self.cache = self.root / 'cache'
|
||||
self.cache.mkdir()
|
||||
for name, content in {
|
||||
'tools/powervr/fetch.py': b'fixture assembler',
|
||||
'tools/hybris/run-proton.py': b'print("fixture Proton wrapper")\n',
|
||||
'tools/hybris/source.env': b'HYBRIS_REVISION=fixture\n',
|
||||
'tools/vulkan-wsi/licenses/Vulkan-Headers/LICENSE.md': b'Khronos headers attribution\n',
|
||||
'tools/vulkan-wsi/licenses/Vulkan-Headers/MIT.txt': b'MIT license fixture\n',
|
||||
}.items():
|
||||
path = self.root / name
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(content)
|
||||
bridge = {name: ('file', 0o755, elf()) for name in runtime.REQUIRED_LIBRARIES if name.startswith('lib/')}
|
||||
bridge['lib/libhybris-common.so.1.0.0'] = bridge.pop('lib/libhybris-common.so.1')
|
||||
bridge['lib/libhybris-common.so.1'] = ('symlink', 0o777, 'libhybris-common.so.1.0.0')
|
||||
data = runtime.pack(bridge)
|
||||
self.release = {'format': 1, 'hybris': self.component('bridge.tzst', data), 'archives': []}
|
||||
self.release['hybris'].update({
|
||||
'tree_sha256': runtime.tree_digest(bridge),
|
||||
'recipe_inputs': {'tools/hybris/source.env': runtime.sha256((self.root / 'tools/hybris/source.env').read_bytes())}})
|
||||
files = {'dxvk/' + arch + '/' + name: pe(arch)
|
||||
for arch in ('x32', 'x64')
|
||||
for name in ('d3d8.dll', 'd3d9.dll', 'd3d10core.dll', 'd3d11.dll', 'dxgi.dll')}
|
||||
files['wsi/libVkLayer_window_system_integration.so'] = elf()
|
||||
stream = io.BytesIO()
|
||||
with ZipFile(stream, 'w') as archive:
|
||||
for name, content in files.items():
|
||||
archive.writestr(name, content)
|
||||
component = self.component('graphics.zip', stream.getvalue())
|
||||
component.update({'ignored': [], 'files': [
|
||||
{'name': name, 'path': name, 'size': len(content), 'sha256': runtime.sha256(content), 'mode': 0o644}
|
||||
for name, content in files.items()]})
|
||||
self.release['archives'].append(component)
|
||||
self.pins = self.root / 'tools/powervr/release.json'
|
||||
self.pins.write_bytes(runtime.json_bytes(self.release))
|
||||
|
||||
def component(self, name, data):
|
||||
component = {'url': 'https://example.invalid/' + name, 'size': len(data),
|
||||
'sha256': runtime.sha256(data), 'recipe_inputs': {}}
|
||||
(self.cache / (component['sha256'] + '-' + name)).write_bytes(data)
|
||||
return component
|
||||
|
||||
def add_upstream_dxvk(self, files):
|
||||
top = next(iter(files)).split('/')[0]
|
||||
data = tar_gz([(top, tarfile.DIRTYPE, None)] +
|
||||
[(name, tarfile.REGTYPE, content) for name, content in files.items()])
|
||||
component = self.component('dxvk-upstream.tar.gz', data)
|
||||
component.update({'format': 'tar.gz', 'ignored': [], 'files': [
|
||||
{'name': name, 'path': name, 'size': len(content), 'sha256': runtime.sha256(content), 'mode': 0o755}
|
||||
for name, content in files.items()]})
|
||||
self.release['archives'].append(component)
|
||||
self.pins.write_bytes(runtime.json_bytes(self.release))
|
||||
return component
|
||||
|
||||
def assembled(self):
|
||||
runtime.assemble(self.root, self.cache)
|
||||
return runtime.read_tar((self.root / runtime.ASSETS / 'runtime.tzst').read_bytes())
|
||||
|
||||
def test_complete_payload_preserves_symlinks_and_is_reproducible(self):
|
||||
self.assembled()
|
||||
first = (self.root / runtime.ASSETS / 'runtime.tzst').read_bytes()
|
||||
runtime.verify(self.root)
|
||||
self.assembled()
|
||||
self.assertEqual(first, (self.root / runtime.ASSETS / 'runtime.tzst').read_bytes())
|
||||
self.assertEqual(runtime.read_tar(first)['lib/libhybris-common.so.1'][0], 'symlink')
|
||||
|
||||
def test_upstream_tarball_adds_a_second_dxvk_payload(self):
|
||||
files = upstream_dxvk('2.6.2')
|
||||
self.add_upstream_dxvk(files)
|
||||
entries = self.assembled()
|
||||
runtime.verify(self.root)
|
||||
for name, content in files.items():
|
||||
self.assertEqual(entries[name], ('file', 0o755, content))
|
||||
self.assertIn('dxvk/x64/d3d9.dll', entries)
|
||||
|
||||
def test_second_dxvk_payload_with_wrong_pe_architecture_is_rejected(self):
|
||||
self.add_upstream_dxvk(upstream_dxvk('2.6.2', lambda arch: 'x64' if arch == 'x32' else 'x32'))
|
||||
with self.assertRaisesRegex(ValueError, 'wrong PE architecture: dxvk-2.6.2/'):
|
||||
self.assembled()
|
||||
|
||||
def test_tar_gz_rejects_symlinks_unknown_members_and_changed_files(self):
|
||||
pin = {'name': 'dxvk-1/x64/d3d9.dll', 'path': 'dxvk-1/x64/d3d9.dll', 'size': 4,
|
||||
'sha256': runtime.sha256(b'good'), 'mode': 0o755}
|
||||
component = {'files': [pin], 'ignored': []}
|
||||
cases = [
|
||||
[('dxvk-1/x64/d3d9.dll', tarfile.SYMTYPE, '../../outside')],
|
||||
[('dxvk-1/x64/d3d9.dll', tarfile.REGTYPE, b'good'), ('dxvk-1/extra.dll', tarfile.REGTYPE, b'x')],
|
||||
[('dxvk-1/x64/d3d9.dll', tarfile.REGTYPE, b'evil')],
|
||||
[],
|
||||
]
|
||||
for entries in cases:
|
||||
with self.subTest(entries=[name for name, _, _ in entries]), self.assertRaises(ValueError):
|
||||
runtime.read_tar_gz(tar_gz(entries), component)
|
||||
self.assertEqual(runtime.read_tar_gz(tar_gz([('dxvk-1/x64/d3d9.dll', tarfile.REGTYPE, b'good')]), component),
|
||||
{'dxvk-1/x64/d3d9.dll': ('file', 0o755, b'good')})
|
||||
with self.assertRaisesRegex(ValueError, 'unsupported component archive format'):
|
||||
runtime.read_component(b'', {'format': 'rar'})
|
||||
|
||||
def test_stale_wrapper_cannot_pass_with_an_updated_archive_checksum(self):
|
||||
self.assembled()
|
||||
(self.root / 'tools/hybris/run-proton.py').write_text('print("new wrapper")\n')
|
||||
with self.assertRaisesRegex(ValueError, 'assembly inputs changed'):
|
||||
runtime.verify(self.root)
|
||||
|
||||
def test_header_licenses_are_bundled_verbatim(self):
|
||||
entries = self.assembled()
|
||||
for source, target in runtime.BUNDLED_LICENSES.items():
|
||||
self.assertEqual(runtime.read(entries, target), (self.root / source).read_bytes())
|
||||
|
||||
def test_missing_or_modified_header_license_is_rejected(self):
|
||||
original = self.assembled()
|
||||
target = 'licenses/Vulkan-Headers/MIT.txt'
|
||||
for replacement in (None, ('file', 0o644, b'stale license')):
|
||||
with self.subTest(replacement=replacement):
|
||||
entries = dict(original)
|
||||
if replacement is None:
|
||||
del entries[target]
|
||||
else:
|
||||
entries[target] = replacement
|
||||
with self.assertRaisesRegex(ValueError, 'license missing or stale'):
|
||||
runtime.check_bundle(entries, self.release, self.root)
|
||||
|
||||
def test_changed_tracked_header_license_rejects_old_bundle(self):
|
||||
self.assembled()
|
||||
source = next(iter(runtime.BUNDLED_LICENSES))
|
||||
(self.root / source).write_bytes(b'changed license text')
|
||||
with self.assertRaisesRegex(ValueError, 'assembly inputs changed'):
|
||||
runtime.verify(self.root)
|
||||
|
||||
def test_changed_component_recipe_requires_new_release_pin(self):
|
||||
self.assembled()
|
||||
(self.root / 'tools/hybris/source.env').write_text('HYBRIS_REVISION=new-source\n')
|
||||
with self.assertRaisesRegex(ValueError, 'recipe changed'):
|
||||
runtime.verify(self.root)
|
||||
|
||||
def test_old_dxvk_cannot_pass_by_updating_only_the_bundle_checksum(self):
|
||||
entries = self.assembled()
|
||||
entries['dxvk/x64/d3d11.dll'] = ('file', 0o644, pe('x64') + b'old DLL')
|
||||
archive = runtime.pack(entries)
|
||||
with self.assertRaisesRegex(ValueError, 'component mismatch'):
|
||||
runtime.verify_archive(archive, runtime.sha256(archive), self.root)
|
||||
|
||||
def test_wrong_pe_architecture_rejected_even_with_matching_member_pin(self):
|
||||
entries = self.assembled()
|
||||
name = 'dxvk/x32/d3d11.dll'
|
||||
entries[name] = ('file', 0o644, pe('x64'))
|
||||
pin = next(item for item in self.release['archives'][0]['files'] if item['path'] == name)
|
||||
pin['sha256'] = runtime.sha256(pe('x64'))
|
||||
with self.assertRaisesRegex(ValueError, 'wrong PE architecture'):
|
||||
runtime.check_bundle(entries, self.release, self.root)
|
||||
|
||||
def test_unpinned_bridge_file_is_rejected(self):
|
||||
entries = self.assembled()
|
||||
entries['lib/extra-loader.so'] = ('file', 0o755, elf())
|
||||
with self.assertRaisesRegex(ValueError, 'bridge differs'):
|
||||
runtime.check_bundle(entries, self.release, self.root)
|
||||
|
||||
def test_failed_download_leaves_the_previous_payload_ready(self):
|
||||
self.assembled()
|
||||
before = (self.root / runtime.ASSETS / 'version.txt').read_bytes()
|
||||
component = self.release['archives'][0]
|
||||
(self.cache / (component['sha256'] + '-graphics.zip')).write_bytes(b'bad cache')
|
||||
with patch.object(runtime, 'urlopen', return_value=io.BytesIO(b'corrupt response')):
|
||||
with self.assertRaisesRegex(ValueError, 'checksum mismatch'):
|
||||
runtime.assemble(self.root, self.cache)
|
||||
self.assertEqual(before, (self.root / runtime.ASSETS / 'version.txt').read_bytes())
|
||||
runtime.verify(self.root)
|
||||
|
||||
def test_tar_rejects_traversal_duplicate_special_files_and_symlink_escape(self):
|
||||
cases = [
|
||||
[('../escape', tarfile.REGTYPE, b'x')],
|
||||
[('file', tarfile.REGTYPE, b'x'), ('./file', tarfile.REGTYPE, b'y')],
|
||||
[('device', tarfile.CHRTYPE, b'')],
|
||||
[('file', tarfile.LNKTYPE, 'other')],
|
||||
[('lib/link', tarfile.SYMTYPE, '../../outside')],
|
||||
[('lib/link', tarfile.SYMTYPE, '/absolute')],
|
||||
[('lib/a', tarfile.SYMTYPE, 'b'), ('lib/b', tarfile.SYMTYPE, 'a')],
|
||||
[('lib', tarfile.SYMTYPE, 'target'), ('target', tarfile.REGTYPE, b'x'),
|
||||
('lib/child', tarfile.REGTYPE, b'x')],
|
||||
]
|
||||
for members in cases:
|
||||
with self.subTest(members=members):
|
||||
with self.assertRaises(ValueError):
|
||||
runtime.read_tar(tar(members))
|
||||
|
||||
def test_relative_symlink_that_stays_inside_runtime_is_preserved(self):
|
||||
entries = runtime.read_tar(tar([
|
||||
('lib/a', tarfile.REGTYPE, b'library'), ('lib/child/link', tarfile.SYMTYPE, '../a')]))
|
||||
self.assertEqual(runtime.read(entries, 'lib/child/link'), b'library')
|
||||
|
||||
def test_zip_rejects_symlink_even_if_name_is_allowed(self):
|
||||
stream = io.BytesIO()
|
||||
with ZipFile(stream, 'w') as archive:
|
||||
info = ZipInfo('allowed')
|
||||
info.create_system = 3
|
||||
info.external_attr = 0o120777 << 16
|
||||
archive.writestr(info, '../outside')
|
||||
with self.assertRaisesRegex(ValueError, 'unexpected component archive entry'):
|
||||
runtime.read_zip(stream.getvalue(), {'files': [], 'ignored': ['allowed']})
|
||||
|
||||
def test_zip_rejects_unknown_and_duplicate_members(self):
|
||||
for names in (['unexpected'], ['allowed', 'allowed'], ['../escape']):
|
||||
with self.subTest(names=names):
|
||||
stream = io.BytesIO()
|
||||
with ZipFile(stream, 'w') as archive:
|
||||
for name in names:
|
||||
archive.writestr(name, b'file')
|
||||
with self.assertRaises(ValueError):
|
||||
runtime.read_zip(stream.getvalue(), {'files': [], 'ignored': ['allowed']})
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,228 @@
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
TOOLS = Path(__file__).resolve().parents[1]
|
||||
WRAPPER_SOURCE = TOOLS / "hybris/run-proton.py"
|
||||
DLL_NAMES = ("d3d8.dll", "d3d9.dll", "d3d10core.dll", "d3d11.dll", "dxgi.dll")
|
||||
DXVK_X64_ANCHOR = 'g_proton.arch_pe_dir("wine/dxvk", False) + f + ".dll"'
|
||||
DXVK_X32_ANCHOR = 'g_proton.arch_pe_dir("wine/dxvk", True) + f + ".dll"'
|
||||
PREFIX_ANCHOR = " # check whether any prefix config has changed"
|
||||
|
||||
|
||||
PROTON_SOURCE = '''import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
from neighbor import NEIGHBOR
|
||||
|
||||
|
||||
class Proton:
|
||||
def arch_pe_dir(self, directory, is32):
|
||||
return str(Path(__file__).parent / "stock" / ("x32" if is32 else "x64")) + "/"
|
||||
|
||||
|
||||
g_proton = Proton()
|
||||
|
||||
|
||||
def prefix_marker():
|
||||
if True:
|
||||
prefix_info = "stock"
|
||||
# check whether any prefix config has changed
|
||||
return prefix_info
|
||||
|
||||
|
||||
def payloads():
|
||||
result = {"x64": {}, "x32": {}}
|
||||
for f in ("d3d8", "d3d9", "d3d10core", "d3d11", "dxgi"):
|
||||
x64 = g_proton.arch_pe_dir("wine/dxvk", False) + f + ".dll"
|
||||
x32 = g_proton.arch_pe_dir("wine/dxvk", True) + f + ".dll"
|
||||
result["x64"][f + ".dll"] = Path(x64).read_text()
|
||||
result["x32"][f + ".dll"] = Path(x32).read_text()
|
||||
return result
|
||||
|
||||
|
||||
def main():
|
||||
record = {
|
||||
"argv0": sys.argv[0],
|
||||
"argv": sys.argv[1:],
|
||||
"file": __file__,
|
||||
"neighbor": NEIGHBOR,
|
||||
"prefix": prefix_marker(),
|
||||
"payloads": payloads(),
|
||||
"openvr": g_proton.arch_pe_dir("wine/dxvk", False) + "openvr_api_dxvk.dll",
|
||||
}
|
||||
Path(os.environ["PROBE"]).write_text(json.dumps(record))
|
||||
raise SystemExit(int(os.environ.get("PROTON_EXIT", "0")))
|
||||
|
||||
|
||||
main()
|
||||
'''
|
||||
|
||||
|
||||
class ProtonWrapperTest(unittest.TestCase):
|
||||
def fixture(self, root):
|
||||
wrapper_dir = root / 'DXVK profile "quotes" $dollar `backticks`'
|
||||
wrapper_dir.mkdir(parents=True)
|
||||
wrapper = wrapper_dir / "run-proton.py"
|
||||
shutil.copy2(WRAPPER_SOURCE, wrapper)
|
||||
|
||||
dxvk = wrapper_dir / "dxvk"
|
||||
for architecture in ("x32", "x64"):
|
||||
payload = dxvk / architecture
|
||||
payload.mkdir(parents=True)
|
||||
for name in DLL_NAMES:
|
||||
(payload / name).write_text(f"{architecture}:{name}")
|
||||
|
||||
depot = root / "Proton depot with spaces"
|
||||
depot.mkdir()
|
||||
proton = depot / "selected proton.py"
|
||||
proton.write_text(PROTON_SOURCE)
|
||||
(depot / "neighbor.py").write_text('NEIGHBOR = "imported from selected depot"\n')
|
||||
return {"wrapper": wrapper, "dxvk": dxvk, "depot": depot, "proton": proton,
|
||||
"probe": root / "proton-ran.json"}
|
||||
|
||||
def run_wrapper(self, fixture, *proton_args, check=False, exit_status=0, env=None):
|
||||
command = [sys.executable, str(fixture["wrapper"])]
|
||||
if check:
|
||||
command.append("--check")
|
||||
command.extend((str(fixture["proton"]), *proton_args))
|
||||
return subprocess.run(
|
||||
command,
|
||||
cwd=fixture["wrapper"].parent,
|
||||
env={"PATH": os.defpath, "PROBE": str(fixture["probe"]),
|
||||
"PROTON_EXIT": str(exit_status), **(env or {})},
|
||||
text=True,
|
||||
capture_output=True,
|
||||
)
|
||||
|
||||
def test_launch_uses_both_staged_payloads_and_selected_proton_context(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
fixture = self.fixture(Path(tmp))
|
||||
original_source = fixture["proton"].read_bytes()
|
||||
arguments = ("waitforexitandrun", "game with spaces.exe", 'quoted "value"',
|
||||
"$literal-dollar", "`literal-backticks`")
|
||||
result = self.run_wrapper(fixture, *arguments)
|
||||
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(fixture["proton"].read_bytes(), original_source)
|
||||
record = json.loads(fixture["probe"].read_text())
|
||||
self.assertEqual(record["argv0"], str(fixture["proton"]))
|
||||
self.assertEqual(record["argv"], list(arguments))
|
||||
self.assertEqual(record["file"], str(fixture["proton"]))
|
||||
self.assertEqual(record["neighbor"], "imported from selected depot")
|
||||
self.assertEqual(record["prefix"], "stock\ndroiddeck-dxvk-profile-v1")
|
||||
self.assertEqual(record["openvr"], str(fixture["depot"] / "stock/x64/openvr_api_dxvk.dll"))
|
||||
for architecture in ("x32", "x64"):
|
||||
self.assertEqual(
|
||||
record["payloads"][architecture],
|
||||
{name: f"{architecture}:{name}" for name in DLL_NAMES},
|
||||
)
|
||||
|
||||
def test_named_sibling_payload_replaces_the_default(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
fixture = self.fixture(Path(tmp))
|
||||
for architecture in ("x32", "x64"):
|
||||
payload = fixture["wrapper"].parent / "dxvk-2.6.2" / architecture
|
||||
payload.mkdir(parents=True)
|
||||
for name in DLL_NAMES:
|
||||
(payload / name).write_text(f"2.6.2 {architecture}:{name}")
|
||||
result = self.run_wrapper(fixture, "waitforexitandrun", "game.exe",
|
||||
env={"DROIDDECK_HYBRIS_DXVK": "dxvk-2.6.2"})
|
||||
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
record = json.loads(fixture["probe"].read_text())
|
||||
for architecture in ("x32", "x64"):
|
||||
self.assertEqual(
|
||||
record["payloads"][architecture],
|
||||
{name: f"2.6.2 {architecture}:{name}" for name in DLL_NAMES},
|
||||
)
|
||||
|
||||
def test_payload_names_outside_the_wrapper_directory_are_refused(self):
|
||||
for name in ("../dxvk", "dxvk/../../x", "/tmp/dxvk", "other", ".dxvk"):
|
||||
with self.subTest(name=name), tempfile.TemporaryDirectory() as tmp:
|
||||
fixture = self.fixture(Path(tmp))
|
||||
result = self.run_wrapper(fixture, "waitforexitandrun", "game.exe",
|
||||
env={"DROIDDECK_HYBRIS_DXVK": name})
|
||||
|
||||
self.assertEqual(result.returncode, 1)
|
||||
self.assertIn("invalid payload name", result.stderr)
|
||||
self.assertFalse(fixture["probe"].exists())
|
||||
|
||||
def test_check_validates_without_executing_proton(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
fixture = self.fixture(Path(tmp))
|
||||
result = self.run_wrapper(fixture, check=True)
|
||||
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertIn("payload present and Proton layout supported", result.stdout)
|
||||
self.assertFalse(fixture["probe"].exists())
|
||||
|
||||
def test_check_rejects_malformed_source_before_its_top_level_code_runs(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
fixture = self.fixture(Path(tmp))
|
||||
source = fixture["proton"].read_text()
|
||||
source = source.replace(
|
||||
"import sys\n", 'import sys\n\nPath(os.environ["PROBE"]).write_text("top-level")\n', 1)
|
||||
fixture["proton"].write_text(source + "\nthis is not valid =\n")
|
||||
result = self.run_wrapper(fixture, check=True)
|
||||
|
||||
self.assertEqual(result.returncode, 1, result.stderr)
|
||||
self.assertIn("DroidDeck DXVK profile:", result.stderr)
|
||||
self.assertFalse(fixture["probe"].exists())
|
||||
|
||||
def test_preflight_rejects_each_missing_or_empty_payload_before_proton_runs(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
for state in ("missing", "empty"):
|
||||
for architecture in ("x32", "x64"):
|
||||
for name in DLL_NAMES:
|
||||
with self.subTest(state=state, architecture=architecture, name=name):
|
||||
fixture = self.fixture(root / f"{state}-{architecture}-{name}")
|
||||
payload = fixture["dxvk"] / architecture / name
|
||||
if state == "missing":
|
||||
payload.unlink()
|
||||
else:
|
||||
payload.write_bytes(b"")
|
||||
result = self.run_wrapper(fixture, "waitforexitandrun", "game.exe")
|
||||
self.assertEqual(result.returncode, 1, result.stderr)
|
||||
self.assertIn(f"{state} DXVK file", result.stderr)
|
||||
self.assertFalse(fixture["probe"].exists())
|
||||
|
||||
def test_preflight_rejects_changed_proton_layout_or_syntax_before_proton_runs(self):
|
||||
mutations = []
|
||||
for label, anchor in (("x64", DXVK_X64_ANCHOR), ("x32", DXVK_X32_ANCHOR),
|
||||
("prefix", PREFIX_ANCHOR)):
|
||||
mutations.extend(((f"missing-{label}", lambda text, anchor=anchor: text.replace(anchor, "missing_anchor", 1)),
|
||||
(f"duplicate-{label}", lambda text, anchor=anchor: text + "\n# " + anchor + "\n")))
|
||||
mutations.append(("syntax-error", lambda text: text + "\nthis is not valid =\n"))
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
for label, mutate in mutations:
|
||||
with self.subTest(layout=label):
|
||||
fixture = self.fixture(root / label)
|
||||
fixture["proton"].write_text(mutate(fixture["proton"].read_text()))
|
||||
result = self.run_wrapper(fixture, "waitforexitandrun", "game.exe")
|
||||
self.assertEqual(result.returncode, 1, result.stderr)
|
||||
self.assertIn("DroidDeck DXVK profile:", result.stderr)
|
||||
self.assertFalse(fixture["probe"].exists())
|
||||
|
||||
def test_proton_exit_status_is_propagated(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
fixture = self.fixture(Path(tmp))
|
||||
result = self.run_wrapper(fixture, "waitforexitandrun", "game.exe", exit_status=23)
|
||||
|
||||
self.assertEqual(result.returncode, 23, result.stderr)
|
||||
self.assertTrue(fixture["probe"].exists())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -6,6 +6,7 @@ import subprocess
|
||||
import tarfile
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
from unittest import mock
|
||||
from zipfile import ZipFile
|
||||
|
||||
@@ -20,6 +21,10 @@ class RuntimeInputsTest(unittest.TestCase):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.root = Path(self.temp.name)
|
||||
# Component archive validation has its own binary/archive fixtures.
|
||||
component_check = patch.object(runtime, 'verify_powervr')
|
||||
component_check.start()
|
||||
self.addCleanup(component_check.stop)
|
||||
paths = runtime.outputs(self.root)
|
||||
for name in runtime.required():
|
||||
path = self.root / paths.get(name, 'app/src/main/' + name)
|
||||
@@ -115,6 +120,20 @@ class RuntimeInputsTest(unittest.TestCase):
|
||||
with self.assertRaisesRegex(ValueError, 'quest1.tzst'):
|
||||
runtime.record(self.root)
|
||||
|
||||
def test_changed_powervr_wrapper_rejects_old_outputs(self):
|
||||
wrapper = self.root / 'tools/hybris/run-proton.py'
|
||||
wrapper.parent.mkdir(parents=True)
|
||||
wrapper.write_text('current wrapper')
|
||||
runtime.record(self.root)
|
||||
wrapper.write_text('changed wrapper')
|
||||
with self.assertRaisesRegex(ValueError, 'sources changed'):
|
||||
runtime.verify(self.root)
|
||||
|
||||
def test_missing_powervr_bundle_cannot_be_attested(self):
|
||||
(self.root / 'app/src/main/assets/hybris/runtime.tzst').unlink()
|
||||
with self.assertRaisesRegex(ValueError, 'assets/hybris/runtime.tzst'):
|
||||
runtime.record(self.root)
|
||||
|
||||
def test_modified_prebuilt_binary_is_rejected(self):
|
||||
runtime.record(self.root)
|
||||
(self.root / 'app/src/main/jniLibs/arm64-v8a/libproot.so').write_bytes(b'old APK binary')
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shlex
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
WRAPPER = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-steam-taskset"
|
||||
|
||||
|
||||
class SteamHelperAffinityTest(unittest.TestCase):
|
||||
def launch(self, status, form="helper", configured=True):
|
||||
with tempfile.TemporaryDirectory(prefix="droiddeck-helper-") as temporary:
|
||||
root = Path(temporary)
|
||||
helper = root / "steamwebhelper"
|
||||
helper.write_text(f"#!{sys.executable}\n" +
|
||||
'import json, os, sys\n'
|
||||
'with open(os.environ["STARTS"],"a") as f: f.write(json.dumps(sys.argv[1:])+"\\n")\n'
|
||||
'sys.exit(23)\n')
|
||||
helper.chmod(0o755)
|
||||
real = root / "real-taskset"
|
||||
real.write_text(f"#!{sys.executable}\n" +
|
||||
'import json, os, sys\n'
|
||||
'with open(os.environ["TRACE"],"a") as f: f.write(json.dumps(sys.argv[1:])+"\\n")\n'
|
||||
f'sys.exit({status})\n')
|
||||
real.chmod(0o755)
|
||||
wrapper = root / "taskset"
|
||||
wrapper.write_text(WRAPPER.read_text().replace("/usr/bin/taskset", shlex.quote(str(real))))
|
||||
helper_path = helper
|
||||
if form == "alias":
|
||||
helper_path = root / "helper symlink"
|
||||
helper_path.symlink_to(helper)
|
||||
elif form == "other":
|
||||
helper_path = root / "other/steamwebhelper"
|
||||
helper_path.parent.mkdir()
|
||||
helper_path.write_text(helper.read_text())
|
||||
helper_path.chmod(0o755)
|
||||
args = ["0x7c", str(helper_path), "arg with spaces", "--literal=$HOME"]
|
||||
if form == "query":
|
||||
args = ["-p", "12345"]
|
||||
elif form == "invalid":
|
||||
args[0] = "not-a-mask"
|
||||
elif form == "empty":
|
||||
args = []
|
||||
env = dict(os.environ, TRACE=str(root / "trace"), STARTS=str(root / "starts"))
|
||||
env.pop("BL_STEAM_WEBHELPER", None)
|
||||
if configured:
|
||||
env["BL_STEAM_WEBHELPER"] = str(helper)
|
||||
result = subprocess.run(["bash", str(wrapper), *args], env=env,
|
||||
capture_output=True, text=True, timeout=5)
|
||||
trace = [json.loads(x) for x in (root / "trace").read_text().splitlines()]
|
||||
starts = ([json.loads(x) for x in (root / "starts").read_text().splitlines()]
|
||||
if (root / "starts").exists() else [])
|
||||
return result, trace, starts, args
|
||||
|
||||
def test_denied_pinning_still_executes_helper_once(self):
|
||||
result, trace, starts, args = self.launch(1)
|
||||
self.assertEqual(result.returncode, 23)
|
||||
self.assertEqual(starts, [args[2:]])
|
||||
self.assertEqual(len(trace), 1)
|
||||
self.assertEqual(trace[0][:2], ["-p", "0x7c"])
|
||||
self.assertRegex(trace[0][2], r"^[1-9][0-9]*$")
|
||||
self.assertIn("using the allowed CPUs", result.stderr)
|
||||
|
||||
def test_successful_pinning_preserves_helper_exit_status(self):
|
||||
result, trace, starts, args = self.launch(0)
|
||||
self.assertEqual(result.returncode, 23)
|
||||
self.assertEqual(starts, [args[2:]])
|
||||
self.assertEqual(trace[0][:2], ["-p", "0x7c"])
|
||||
self.assertNotIn("pinning unavailable", result.stderr)
|
||||
|
||||
def test_symlink_to_actual_helper_is_recognized(self):
|
||||
result, _, starts, args = self.launch(1, "alias")
|
||||
self.assertEqual(result.returncode, 23)
|
||||
self.assertEqual(starts, [args[2:]])
|
||||
|
||||
def test_other_taskset_forms_and_targets_pass_through(self):
|
||||
for form, configured in [("other", True), ("query", True), ("invalid", True),
|
||||
("empty", True), ("helper", False)]:
|
||||
with self.subTest(form=form, configured=configured):
|
||||
result, trace, starts, args = self.launch(47, form, configured)
|
||||
self.assertEqual(result.returncode, 47)
|
||||
self.assertEqual(trace, [args])
|
||||
self.assertEqual(starts, [])
|
||||
self.assertNotIn("pinning unavailable", result.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,75 @@
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
SESSION = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-session"
|
||||
|
||||
|
||||
class SteamPresentationTest(unittest.TestCase):
|
||||
def launch(self, enabled=None, inherited=None):
|
||||
source = SESSION.read_text()
|
||||
begin = source.index(" bl_steam_path=$PATH")
|
||||
end = source.index("\n decky_loader=", begin)
|
||||
command = source.index(' PATH="$bl_steam_path"')
|
||||
command_end = source.index("\n rc=$?", command)
|
||||
script = (source[begin:end] + '\n_bl_ui=(-gamepadui); _bl_cdp=(); _bl_lang=()\n'
|
||||
# 0.5.0 launches through steam_client (the arm64 client, or the x86-64 one under FEX).
|
||||
+ 'steam_client=("$steam_root/steamrtarm64/steam")\n'
|
||||
+ source[command:command_end])
|
||||
env = dict(os.environ)
|
||||
for key in ("BL_STEAM_GL_PRESENT", "DISABLE_GAMESCOPE_WSI", "LIBGL_KOPPER_DISABLE"):
|
||||
env.pop(key, None)
|
||||
if enabled is not None:
|
||||
env["BL_STEAM_GL_PRESENT"] = enabled
|
||||
env.update(inherited or {})
|
||||
with tempfile.TemporaryDirectory(prefix="droiddeck-steam-gl-") as tmp:
|
||||
program = Path(tmp) / "steamrtarm64/steam"
|
||||
program.parent.mkdir()
|
||||
program.write_text(f"#!{sys.executable}\n" +
|
||||
'import json, os, sys\nprint(json.dumps({"args":sys.argv[1:],'
|
||||
'"disable":os.getenv("DISABLE_GAMESCOPE_WSI"),'
|
||||
'"kopper":os.getenv("LIBGL_KOPPER_DISABLE"),'
|
||||
'"path":os.getenv("PATH"),'
|
||||
'"helper":os.getenv("BL_STEAM_WEBHELPER")}))\n')
|
||||
program.chmod(0o755)
|
||||
env.update(steam_root=tmp, steam_channel="steamdeck_publicbeta")
|
||||
result = subprocess.run(["bash", "-c", script, "test", "steam://open/main"],
|
||||
env=env, capture_output=True, text=True, timeout=5)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
launch = json.loads(result.stdout.splitlines()[-1])
|
||||
self.assertEqual(enabled == "1", launch["path"].startswith("/usr/local/libexec/droiddeck-steam:"))
|
||||
self.assertEqual(launch["helper"], str(Path(tmp) / "steamrtarm64/steamwebhelper"))
|
||||
return launch
|
||||
|
||||
def test_default_keeps_vulkan(self):
|
||||
result = self.launch()
|
||||
self.assertIn("-cef-use-angle=vulkan", result["args"])
|
||||
self.assertNotIn("-cef-disable-gpu-compositing", result["args"])
|
||||
self.assertIsNone(result["disable"])
|
||||
self.assertIsNone(result["kopper"])
|
||||
|
||||
def test_system_powervr_keeps_gpu_gl_with_software_web_compositing(self):
|
||||
result = self.launch("1")
|
||||
self.assertIn("-cef-use-angle=gl", result["args"])
|
||||
self.assertIn("-cef-use-gl=angle", result["args"])
|
||||
self.assertIn("-cef-force-gpu", result["args"])
|
||||
self.assertIn("-cef-disable-gpu-compositing", result["args"])
|
||||
self.assertNotIn("-cef-disable-gpu", result["args"])
|
||||
self.assertEqual(result["disable"], "1")
|
||||
self.assertEqual(result["kopper"], "true")
|
||||
self.assertEqual(result["args"][-1], "steam://open/main")
|
||||
|
||||
def test_disabled_option_preserves_existing_environment(self):
|
||||
result = self.launch("0", {"DISABLE_GAMESCOPE_WSI": "0", "LIBGL_KOPPER_DISABLE": "false"})
|
||||
self.assertIn("-cef-use-angle=vulkan", result["args"])
|
||||
self.assertNotIn("-cef-disable-gpu-compositing", result["args"])
|
||||
self.assertEqual(result["disable"], "0")
|
||||
self.assertEqual(result["kopper"], "false")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,120 @@
|
||||
"""Exercise production DMA-BUF release/ownership paths without a GPU.
|
||||
|
||||
Wayland resources and OS timer/Android AHB endpoints are fake; list macros and
|
||||
the compositor/AHB lifecycle functions come directly from the repository.
|
||||
"""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from test_vk_pending_completion import function
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
SRC = ROOT / 'app/src/main/cpp/waylandcomp/src'
|
||||
|
||||
|
||||
class VkDmabufQuarantineTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cc = shutil.which(os.environ.get('CC', 'cc'))
|
||||
if not cc:
|
||||
raise AssertionError('C compiler required')
|
||||
# Optional old-head input allows a genuine negative control using the
|
||||
# identical harness, rather than a model of the previous behaviour.
|
||||
source_dir = Path(os.environ.get('DROIDDECK_DMABUF_TEST_SOURCE', SRC))
|
||||
comp = (source_dir / 'compositor.c').read_text()
|
||||
ahb = (source_dir / 'ahb_swapchain.c').read_text()
|
||||
vk = (source_dir / 'vk_present.c').read_text()
|
||||
names = ['get_dmabuf', 'pending_release_free',
|
||||
'pending_releases_forget_surface', 'on_pending_release_buffer_destroyed',
|
||||
'arm_release_timer', 'on_release_timer', 'release_buffer',
|
||||
'dmabuf_buffer_unref', 'drop_dmabuf', 'on_dmabuf_destroyed',
|
||||
'droiddeck_dmabuf_ahb_slot', 'droiddeck_dmabuf_unref',
|
||||
'droiddeck_release_buffer']
|
||||
helpers = []
|
||||
if re.search(r'\bstatic int buffer_release_blocked\(', comp):
|
||||
helpers = [function(comp, 'buffer_release_blocked')]
|
||||
if re.search(r'\bstatic void send_buffer_release_at\(', comp):
|
||||
# send_buffer_release is a macro over send_buffer_release_at (with buffer tracing).
|
||||
helpers += ['static void buf_trace_release(struct wl_resource *b, int line) { (void)b; (void)line; }',
|
||||
'#define send_buffer_release(b) send_buffer_release_at((b), __LINE__)',
|
||||
function(comp, 'send_buffer_release_at')]
|
||||
else:
|
||||
helpers += [function(comp, 'send_buffer_release')]
|
||||
else:
|
||||
helpers = ['static int __attribute__((unused)) buffer_release_blocked(struct wl_resource *b) { (void)b; return 0; }']
|
||||
if re.search(r'\bstatic int buffer_shown_elsewhere\(', comp):
|
||||
# One surface per buffer in these scenarios: never shown elsewhere.
|
||||
helpers += ['static int buffer_shown_elsewhere(struct wl_resource *b, const struct surface *e) '
|
||||
'{ (void)b; (void)e; return 0; }']
|
||||
if re.search(r'\bvolatile int g_release_unpaced;', comp):
|
||||
# Releases stay paced in these scenarios (fps limit -1 sends them at once).
|
||||
helpers.insert(0, 'static int g_release_unpaced;')
|
||||
query = function(vk, 'vkp_completion_unknown') if 'int vkp_completion_unknown(' in vk else \
|
||||
'int vkp_completion_unknown(void) { return g_dev_state == -3; }'
|
||||
comp_functions = [function(comp, names[0])] + helpers + [function(comp, n) for n in names[1:]]
|
||||
ahb_functions = [function(ahb, n) for n in ('buf_free', 'maybe_free',
|
||||
'on_buffer_resource_destroyed', 'send_deferred_release',
|
||||
'on_fence_readable', 'ahb_swapchain_defer_release',
|
||||
'ahb_swapchain_surface_gone')]
|
||||
structs = re.search(r'struct pending_release \{.*?\n\};', comp, re.S).group() + '\n' + \
|
||||
re.search(r'struct ahb_buf \{.*?\n\};', ahb, re.S).group()
|
||||
harness = Path(__file__).with_name('vk_dmabuf_quarantine_test.c').read_text()
|
||||
harness = harness.replace('/* PRODUCTION_STRUCTS */', structs)
|
||||
harness = harness.replace('/* PRODUCTION_FUNCTIONS */', '\n'.join([query] + comp_functions + ahb_functions))
|
||||
cls.tmp = tempfile.TemporaryDirectory(prefix='droiddeck-dmabuf-')
|
||||
cls.addClassCleanup(cls.tmp.cleanup)
|
||||
probe = Path(cls.tmp.name) / 'probe.c'
|
||||
probe.write_text(harness)
|
||||
cls.binary = probe.with_suffix('')
|
||||
built = subprocess.run([cc, '-std=c11', '-Wall', '-Wextra', '-Werror',
|
||||
'-Wno-unused-parameter', '-UNDEBUG',
|
||||
'-I', str(SRC.parent / 'prebuilt/include'),
|
||||
str(probe), '-o', str(cls.binary)], capture_output=True, text=True)
|
||||
if built.returncode:
|
||||
raise AssertionError(built.stdout + built.stderr)
|
||||
|
||||
def run_scenario(self, name):
|
||||
result = subprocess.run([str(self.binary), name], capture_output=True, text=True, timeout=10)
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
|
||||
def test_replacement_retains_reference_and_release(self):
|
||||
self.run_scenario('replacement')
|
||||
|
||||
def test_surface_destroy_retains_reference_and_release(self):
|
||||
self.run_scenario('surface-gone')
|
||||
|
||||
def test_queued_release_is_held_and_timer_disarmed(self):
|
||||
self.run_scenario('queued')
|
||||
|
||||
def test_mixed_queue_releases_only_copied_shm(self):
|
||||
self.run_scenario('mixed')
|
||||
|
||||
def test_client_destroy_retains_backing_fd(self):
|
||||
self.run_scenario('client-gone')
|
||||
|
||||
def test_ahb_callback_retains_ownership_and_release(self):
|
||||
self.run_scenario('ahb')
|
||||
|
||||
def test_active_client_destroy_retains_reference(self):
|
||||
self.run_scenario('active-client-gone')
|
||||
|
||||
def test_healthy_ahb_callback_and_cleanup(self):
|
||||
self.run_scenario('ahb-healthy')
|
||||
|
||||
def test_device_lost_ahb_callback_and_cleanup(self):
|
||||
self.run_scenario('ahb-device-lost')
|
||||
|
||||
def test_healthy_release_and_reference_cleanup(self):
|
||||
self.run_scenario('healthy')
|
||||
|
||||
def test_genuine_device_loss_keeps_existing_cleanup(self):
|
||||
self.run_scenario('device-lost')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,63 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
def vulkan_include_args():
|
||||
candidates = []
|
||||
for name in ("ANDROID_NDK_HOME", "ANDROID_NDK_ROOT"):
|
||||
if os.environ.get(name):
|
||||
candidates.append(Path(os.environ[name]))
|
||||
|
||||
android_home = os.environ.get("ANDROID_HOME")
|
||||
if android_home:
|
||||
ndk_root = Path(android_home) / "ndk"
|
||||
version = os.environ.get("NDK_VERSION")
|
||||
if version:
|
||||
candidates.append(ndk_root / version)
|
||||
if ndk_root.is_dir():
|
||||
candidates.extend(sorted(ndk_root.iterdir(), reverse=True))
|
||||
|
||||
for ndk in candidates:
|
||||
include = ndk / "toolchains/llvm/prebuilt/linux-x86_64/sysroot/usr/include"
|
||||
if (include / "vulkan/vulkan.h").is_file():
|
||||
return ["-idirafter", str(include)]
|
||||
return []
|
||||
|
||||
|
||||
class VkExternalImageSyncTest(unittest.TestCase):
|
||||
def test_client_barrier_pair(self):
|
||||
compiler = shutil.which(os.environ.get("CC", "cc"))
|
||||
if not compiler:
|
||||
self.fail("A C compiler is required for the Vulkan image-sync regression test")
|
||||
|
||||
tests = Path(__file__).resolve().parent
|
||||
source = tests / "vk_external_image_sync_test.c"
|
||||
includes = tests.parents[1] / "app/src/main/cpp/waylandcomp/src"
|
||||
with tempfile.TemporaryDirectory(prefix="droiddeck-vk-sync-") as tmp:
|
||||
program = Path(tmp) / "vk-external-image-sync"
|
||||
command = [
|
||||
compiler,
|
||||
"-std=c11",
|
||||
"-Wall",
|
||||
"-Wextra",
|
||||
"-Werror",
|
||||
"-UNDEBUG",
|
||||
"-I",
|
||||
str(includes),
|
||||
*vulkan_include_args(),
|
||||
str(source),
|
||||
"-o",
|
||||
str(program),
|
||||
]
|
||||
built = subprocess.run(command, capture_output=True, text=True)
|
||||
self.assertEqual(built.returncode, 0, built.stdout + built.stderr)
|
||||
ran = subprocess.run([str(program)], capture_output=True, text=True, timeout=30)
|
||||
self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,187 @@
|
||||
"""Fault-inject the production fence wait and imported-image destructor.
|
||||
|
||||
No GPU is wedged: a fake dispatch table returns the same result a timed-out
|
||||
submit would return. The compiled functions come from vk_present.c itself.
|
||||
"""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
SOURCE = Path(__file__).resolve().parents[2] / 'app/src/main/cpp/waylandcomp/src/vk_present.c'
|
||||
|
||||
|
||||
def function(text, name):
|
||||
match = re.search(r'^(?:static )?[^\n;]+\b' + name + r'\([^;]*?\)\s*\{', text, re.M)
|
||||
if not match:
|
||||
raise AssertionError('Production function not found: ' + name)
|
||||
start = match.start()
|
||||
pos = text.index('{', match.start())
|
||||
depth = 1
|
||||
end = pos + 1
|
||||
while depth:
|
||||
depth += (text[end] == '{') - (text[end] == '}')
|
||||
end += 1
|
||||
return text[start:end]
|
||||
|
||||
|
||||
HARNESS = r'''
|
||||
#include <assert.h>
|
||||
#include <stdint.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdarg.h>
|
||||
typedef int VkResult;
|
||||
typedef uintptr_t VkFence;
|
||||
#define VK_TRUE 1
|
||||
#define VK_SUCCESS 0
|
||||
#define VK_TIMEOUT 2
|
||||
#define VK_ERROR_DEVICE_LOST -4
|
||||
#define VK_ERROR_OUT_OF_HOST_MEMORY -1
|
||||
#define VK_ERROR_UNKNOWN -13
|
||||
static int g_dev_state, g_base_black;
|
||||
static uintptr_t g_dev = 1;
|
||||
static struct { int64_t wait_ns, wait_max_ns; unsigned waits; } g_perf;
|
||||
static VkResult answer;
|
||||
static unsigned destroyed, unmapped, freed_memory, forgotten, errors;
|
||||
static int64_t perf_now(void) { return 10; }
|
||||
static void perf_add(int64_t *s, int64_t *m, unsigned *c, int64_t d) { *s+=d; *m=d; ++*c; }
|
||||
static void __attribute__((unused)) droiddeck_log(const char *tag, const char *fmt, ...) { (void)tag; (void)fmt; ++errors; }
|
||||
#define LOGE(...) droiddeck_log("error", __VA_ARGS__)
|
||||
static VkResult wait_fn(uintptr_t dev, unsigned n, const VkFence *f, int all, uint64_t timeout) {
|
||||
(void)dev; (void)n; (void)f; (void)all; (void)timeout; return answer;
|
||||
}
|
||||
static void unmap_fn(uintptr_t dev, uintptr_t mem) { (void)dev; (void)mem; ++unmapped; }
|
||||
static void destroy_fn(uintptr_t dev, uintptr_t img, void *allocator) { (void)dev; (void)img; (void)allocator; ++destroyed; }
|
||||
static void free_fn(uintptr_t dev, uintptr_t mem, void *allocator) { (void)dev; (void)mem; (void)allocator; ++freed_memory; }
|
||||
static struct {
|
||||
VkResult (*WaitForFences)(uintptr_t, unsigned, const VkFence *, int, uint64_t);
|
||||
void (*UnmapMemory)(uintptr_t, uintptr_t);
|
||||
void (*DestroyImage)(uintptr_t, uintptr_t, void *);
|
||||
void (*FreeMemory)(uintptr_t, uintptr_t, void *);
|
||||
} g_vk = {wait_fn, unmap_fn, destroy_fn, free_fn};
|
||||
typedef struct AHardwareBuffer AHardwareBuffer;
|
||||
static int released_buffers;
|
||||
static void AHardwareBuffer_release(AHardwareBuffer *b) { (void)b; ++released_buffers; }
|
||||
struct vkp_image { uintptr_t image, mem; void *map; AHardwareBuffer *android_buffer; };
|
||||
static void blendp_forget_image(uintptr_t image) { (void)image; ++forgotten; }
|
||||
/* PRODUCTION_FUNCTIONS */
|
||||
static struct vkp_image *image(void) {
|
||||
struct vkp_image *p = calloc(1, sizeof(*p)); assert(p);
|
||||
p->image=1; p->mem=2; p->map=p; return p;
|
||||
}
|
||||
int main(void) {
|
||||
g_dev_state=1; answer=VK_SUCCESS;
|
||||
assert(timed_wait(1, 1000)==VK_SUCCESS);
|
||||
assert(g_dev_state==1);
|
||||
vkp_image_destroy(image());
|
||||
assert(destroyed==1 && unmapped==1 && freed_memory==1 && forgotten==1);
|
||||
|
||||
g_dev_state=1; g_base_black=1; answer=VK_TIMEOUT;
|
||||
assert(timed_wait(1, 1000)==VK_TIMEOUT);
|
||||
assert(g_dev_state!=1 && g_dev_state!=-2); /* pending work is not DEVICE_LOST */
|
||||
struct vkp_image *pending=image();
|
||||
vkp_image_destroy(pending);
|
||||
assert(destroyed==1 && unmapped==1 && freed_memory==1 && forgotten==1);
|
||||
unsigned first_errors=errors;
|
||||
assert(first_errors>0);
|
||||
assert(timed_wait(1, 1000)==VK_ERROR_UNKNOWN);
|
||||
assert(errors==first_errors); /* one terminal diagnostic, no repeated recovery */
|
||||
free(pending); /* fake GPU exists only in this test */
|
||||
|
||||
g_dev_state=1; answer=VK_ERROR_OUT_OF_HOST_MEMORY;
|
||||
assert(timed_wait(1, 1000)==VK_ERROR_OUT_OF_HOST_MEMORY);
|
||||
assert(g_dev_state!=1 && g_dev_state!=-2);
|
||||
pending=image(); vkp_image_destroy(pending);
|
||||
assert(destroyed==1 && unmapped==1 && freed_memory==1 && forgotten==1);
|
||||
free(pending);
|
||||
|
||||
g_dev_state=1; answer=VK_ERROR_DEVICE_LOST;
|
||||
assert(timed_wait(1, 1000)==VK_ERROR_DEVICE_LOST);
|
||||
assert(g_dev_state==1); /* existing caller performs genuine device-loss cleanup */
|
||||
return 0;
|
||||
}
|
||||
'''
|
||||
|
||||
SWAPCHAIN_HARNESS = r'''
|
||||
#include <assert.h>
|
||||
#include <stdint.h>
|
||||
#include <stdlib.h>
|
||||
typedef int VkResult;
|
||||
#define VK_SUCCESS 0
|
||||
#define VK_ERROR_DEVICE_LOST -4
|
||||
#define VK_ERROR_OUT_OF_HOST_MEMORY -1
|
||||
#define VK_NULL_HANDLE 0
|
||||
static int g_dev_state, g_base_black, g_swap_md_identity;
|
||||
static uintptr_t g_dev=1, g_inst=1, g_swapchain, g_surface, *g_images;
|
||||
static uint32_t g_nimg;
|
||||
static unsigned resets, forgotten, destroyed, errors, lost;
|
||||
static VkResult answer;
|
||||
#define LOGE(...) (++errors)
|
||||
static VkResult idle_fn(uintptr_t dev) { (void)dev; return answer; }
|
||||
static void destroy_fn(uintptr_t dev, uintptr_t obj, void *alloc) {
|
||||
(void)dev; (void)obj; (void)alloc; ++destroyed;
|
||||
}
|
||||
static struct {
|
||||
VkResult (*DeviceWaitIdle)(uintptr_t);
|
||||
void (*DestroySwapchainKHR)(uintptr_t, uintptr_t, void *);
|
||||
void (*DestroySurfaceKHR)(uintptr_t, uintptr_t, void *);
|
||||
} g_vk={idle_fn, destroy_fn, destroy_fn};
|
||||
static void reset_sync(void) { ++resets; }
|
||||
static void blendp_forget_image(uintptr_t img) { (void)img; ++forgotten; }
|
||||
static void device_lost(const char *where) { (void)where; ++lost; g_dev_state=-2; }
|
||||
/* PRODUCTION_FUNCTIONS */
|
||||
static void setup(void) {
|
||||
g_dev_state=1; g_base_black=1; g_swap_md_identity=1;
|
||||
g_swapchain=2; g_surface=3; g_nimg=1;
|
||||
g_images=calloc(1,sizeof(*g_images)); assert(g_images); *g_images=4;
|
||||
}
|
||||
int main(void) {
|
||||
setup(); answer=VK_SUCCESS; destroy_swapchain();
|
||||
assert(resets==1 && destroyed==2 && forgotten==1);
|
||||
assert(!g_swapchain && !g_surface && !g_images && !g_nimg && !g_swap_md_identity);
|
||||
setup(); answer=VK_ERROR_OUT_OF_HOST_MEMORY; destroy_swapchain();
|
||||
assert(g_dev_state==-3 && errors==1);
|
||||
assert(resets==1 && destroyed==2 && forgotten==1);
|
||||
assert(g_swapchain && g_surface && g_images && g_nimg);
|
||||
destroy_swapchain();
|
||||
assert(errors==1 && resets==1 && destroyed==2);
|
||||
free(g_images); /* fake GPU resources only */
|
||||
setup(); answer=VK_ERROR_DEVICE_LOST; destroy_swapchain();
|
||||
assert(lost==1 && g_dev_state==-2);
|
||||
assert(resets==1 && destroyed==2 && forgotten==1);
|
||||
free(g_images);
|
||||
return 0;
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
class VkPendingCompletionTest(unittest.TestCase):
|
||||
def compile_and_run(self, harness, names):
|
||||
cc = shutil.which(os.environ.get('CC', 'cc'))
|
||||
self.assertIsNotNone(cc, 'A C compiler is required')
|
||||
text = SOURCE.read_text()
|
||||
production = '\n'.join(function(text, n) for n in names)
|
||||
with tempfile.TemporaryDirectory(prefix='droiddeck-pending-') as tmp:
|
||||
source=Path(tmp)/'probe.c'; binary=Path(tmp)/'probe'
|
||||
source.write_text(harness.replace('/* PRODUCTION_FUNCTIONS */', production))
|
||||
built=subprocess.run([cc,'-std=c11','-Wall','-Wextra','-Werror','-UNDEBUG',str(source),'-o',str(binary)],capture_output=True,text=True)
|
||||
self.assertEqual(built.returncode,0,built.stdout+built.stderr)
|
||||
ran=subprocess.run([str(binary)],capture_output=True,text=True,timeout=10)
|
||||
self.assertEqual(ran.returncode,0,ran.stdout+ran.stderr)
|
||||
|
||||
def test_unknown_completion_retains_gpu_resources(self):
|
||||
self.compile_and_run(HARNESS, ['quarantine_pending_work', 'timed_wait', 'vkp_image_destroy'])
|
||||
|
||||
def test_failed_device_idle_does_not_destroy_swapchain(self):
|
||||
# LOGE's arguments must be evaluated as real production logging does.
|
||||
harness = SWAPCHAIN_HARNESS.replace('#define LOGE(...) (++errors)',
|
||||
'static void log_error(const char *fmt, int result, const char *where) { '
|
||||
'(void)fmt; (void)result; (void)where; ++errors; }\n#define LOGE(...) log_error(__VA_ARGS__)')
|
||||
self.compile_and_run(harness, ['quarantine_pending_work', 'destroy_swapchain'])
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,140 @@
|
||||
"""Fault-inject complete production render/blit/upload callers, without a GPU.
|
||||
|
||||
Uses Vulkan-Headers from the Android NDK (as installed by APK CI), or the host
|
||||
Vulkan development package. Only Android platform declarations and the external
|
||||
effect/frame-generation modules are mocked; vk_present.c is compiled unmodified.
|
||||
"""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from test_vk_pending_completion import function
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
SOURCE = ROOT / 'app/src/main/cpp/waylandcomp/src/vk_present.c'
|
||||
|
||||
|
||||
def vulkan_include():
|
||||
candidates = [Path(p) for p in [os.environ.get('DROIDDECK_VULKAN_INCLUDE', ''),
|
||||
'/usr/include', '/usr/local/include'] if p]
|
||||
for name in ('ANDROID_HOME', 'ANDROID_SDK_ROOT', 'ANDROID_NDK_HOME', 'NDK'):
|
||||
if os.environ.get(name):
|
||||
root = Path(os.environ[name])
|
||||
candidates += sorted(root.glob('ndk/*/toolchains/llvm/prebuilt/*/sysroot/usr/include'), reverse=True)
|
||||
candidates += list(root.glob('toolchains/llvm/prebuilt/*/sysroot/usr/include'))
|
||||
return next((p for p in candidates if (p / 'vulkan/vulkan.h').is_file()), None)
|
||||
|
||||
|
||||
class VkTerminalCallersTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
headers = vulkan_include()
|
||||
if headers is None:
|
||||
raise unittest.SkipTest('NDK or host Vulkan-Headers required for full production-C caller tests')
|
||||
cc = shutil.which(os.environ.get('CC', 'cc'))
|
||||
if not cc:
|
||||
raise AssertionError('C compiler required')
|
||||
cls.tmp = tempfile.TemporaryDirectory(prefix='droiddeck-callers-')
|
||||
cls.addClassCleanup(cls.tmp.cleanup)
|
||||
tmp = Path(cls.tmp.name)
|
||||
(tmp / 'android').mkdir()
|
||||
(tmp / 'android/native_window.h').write_text('''
|
||||
#pragma once
|
||||
#include <stdint.h>
|
||||
typedef struct ANativeWindow ANativeWindow;
|
||||
int32_t ANativeWindow_getWidth(ANativeWindow *);
|
||||
int32_t ANativeWindow_getHeight(ANativeWindow *);
|
||||
void ANativeWindow_release(ANativeWindow *);
|
||||
''')
|
||||
(tmp / 'android/hardware_buffer.h').write_text('''
|
||||
#pragma once
|
||||
#include <stdint.h>
|
||||
typedef struct AHardwareBuffer AHardwareBuffer;
|
||||
typedef struct AHardwareBuffer_Desc {
|
||||
uint32_t width, height, layers, format;
|
||||
uint64_t usage;
|
||||
uint32_t stride, rfu0;
|
||||
uint64_t rfu1;
|
||||
} AHardwareBuffer_Desc;
|
||||
#define AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE (1ULL << 8)
|
||||
#define AHARDWAREBUFFER_USAGE_PROTECTED_CONTENT (1ULL << 14)
|
||||
#define AHARDWAREBUFFER_USAGE_GPU_MIPMAP_COMPLETE (1ULL << 26)
|
||||
static inline void AHardwareBuffer_describe(const AHardwareBuffer *b, AHardwareBuffer_Desc *d) { (void)b; *d = (AHardwareBuffer_Desc){0}; }
|
||||
static inline void AHardwareBuffer_acquire(AHardwareBuffer *b) { (void)b; }
|
||||
static inline void AHardwareBuffer_release(AHardwareBuffer *b) { (void)b; }
|
||||
''')
|
||||
(tmp / 'sys').mkdir()
|
||||
(tmp / 'sys/system_properties.h').write_text('''
|
||||
#pragma once
|
||||
#define PROP_VALUE_MAX 92
|
||||
static inline int __system_property_get(const char *name, char *value) { (void)name; value[0] = 0; return 0; }
|
||||
''')
|
||||
(tmp / 'android/log.h').write_text('''
|
||||
#pragma once
|
||||
#define ANDROID_LOG_INFO 4
|
||||
int __android_log_print(int, const char *, const char *, ...);
|
||||
''')
|
||||
(tmp / 'wayland-server.h').write_text('#pragma once\nstruct wl_display; struct wl_resource; struct wl_client;\n')
|
||||
compositor = (SOURCE.parent / 'compositor.c').read_text()
|
||||
# send_buffer_release is a macro over send_buffer_release_at (with buffer tracing).
|
||||
callers = ('static void buf_trace_release(struct wl_resource *b, int line) { (void)b; (void)line; }\n'
|
||||
+ '#define send_buffer_release(b) send_buffer_release_at((b), __LINE__)\n'
|
||||
+ '\n'.join(function(compositor, n) for n in ('buffer_release_blocked', 'send_buffer_release_at', 'take_shm', 'take_pixel')))
|
||||
harness = (Path(__file__).with_name('vk_terminal_callers_test.c')).read_text()
|
||||
probe = tmp / 'probe.c'
|
||||
probe.write_text(harness.replace('/* COMPOSITOR_CALLERS */', callers))
|
||||
cls.binary = tmp / 'probe'
|
||||
built = subprocess.run([cc, '-std=c11', '-Wall', '-Wextra', '-Werror',
|
||||
'-Wno-unused-parameter', '-Wno-missing-field-initializers', '-UNDEBUG',
|
||||
'-I', str(tmp), '-idirafter', str(headers), '-I', str(SOURCE.parent),
|
||||
str(probe), '-pthread', '-o', str(cls.binary)],
|
||||
capture_output=True, text=True)
|
||||
if built.returncode:
|
||||
raise AssertionError(built.stdout + built.stderr)
|
||||
|
||||
def run_scenario(self, name):
|
||||
ran = subprocess.run([str(self.binary), name], capture_output=True, text=True, timeout=10)
|
||||
self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr)
|
||||
|
||||
def test_first_acquire_idle_failure(self):
|
||||
self.run_scenario('first-out-of-date')
|
||||
|
||||
def test_first_surface_lost_idle_failure(self):
|
||||
self.run_scenario('first-surface-lost')
|
||||
|
||||
def test_later_framegen_acquire_idle_failure(self):
|
||||
self.run_scenario('later-out-of-date')
|
||||
|
||||
def test_later_framegen_surface_lost_idle_failure(self):
|
||||
self.run_scenario('later-surface-lost')
|
||||
|
||||
def test_finite_blit_timeout_same_size_shm_upload(self):
|
||||
self.run_scenario('shm-timeout')
|
||||
|
||||
def test_finite_blit_timeout_same_size_pixel_upload(self):
|
||||
self.run_scenario('pixel-timeout')
|
||||
|
||||
def test_normal_present(self):
|
||||
self.run_scenario('normal')
|
||||
|
||||
def test_normal_framegen_present(self):
|
||||
self.run_scenario('framegen')
|
||||
|
||||
def test_healthy_later_acquire_timeout_drains_work(self):
|
||||
self.run_scenario('later-timeout')
|
||||
|
||||
def test_real_device_lost_on_acquire(self):
|
||||
self.run_scenario('acquire-device-lost')
|
||||
|
||||
def test_real_device_lost_on_present(self):
|
||||
self.run_scenario('present-device-lost')
|
||||
|
||||
def test_pass_copy_and_abort_terminal_entry(self):
|
||||
self.run_scenario('pass-terminal')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,47 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
TOOLS = Path(__file__).resolve().parents[1]
|
||||
LAYER = TOOLS / "linuxfs/xclipse-layer"
|
||||
|
||||
|
||||
class XclipseLayerTest(unittest.TestCase):
|
||||
def test_layer_against_a_mock_loader_and_driver(self):
|
||||
compiler = shutil.which(os.environ.get("CC", "cc"))
|
||||
if not compiler:
|
||||
self.fail("A C compiler is required for the Xclipse layer regression test")
|
||||
# The build compiles the layer against the distribution's headers (libvulkan-dev);
|
||||
# VULKAN_INCLUDE points elsewhere, e.g. a Vulkan-Headers checkout on macOS.
|
||||
include = Path(os.environ.get("VULKAN_INCLUDE", "/usr/include"))
|
||||
if not (include / "vulkan/vk_layer.h").is_file():
|
||||
self.fail("Vulkan headers are required: install libvulkan-dev or set VULKAN_INCLUDE")
|
||||
with tempfile.TemporaryDirectory(prefix="droiddeck-xclipse-") as tmp:
|
||||
program = Path(tmp) / "xclipse-layer"
|
||||
built = subprocess.run([compiler, "-std=gnu11", "-Wall", "-Wextra", "-Werror", "-Wno-unused-parameter",
|
||||
"-UNDEBUG", "-pthread", "-I", str(LAYER), "-I", str(include),
|
||||
str(Path(__file__).with_name("xclipse_layer_test.c")), "-ldl", "-o", str(program)],
|
||||
capture_output=True, text=True)
|
||||
self.assertEqual(built.returncode, 0, built.stdout + built.stderr)
|
||||
ran = subprocess.run([str(program)], capture_output=True, text=True, timeout=30)
|
||||
self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr)
|
||||
self.assertIn("xclipse layer ok", ran.stdout)
|
||||
|
||||
def test_device_chain_table_matches_its_generator(self):
|
||||
registry = os.environ.get("VULKAN_REGISTRY")
|
||||
if not registry:
|
||||
self.skipTest("set VULKAN_REGISTRY to a Vulkan-Headers 1.3.275 checkout to recheck device_chain.inc")
|
||||
with tempfile.TemporaryDirectory(prefix="droiddeck-chain-") as tmp:
|
||||
output = Path(tmp) / "device_chain.inc"
|
||||
subprocess.run(["python3", str(LAYER / "gen_device_chain.py"), str(Path(registry) / "registry/vk.xml"),
|
||||
str(Path(registry) / "include/vulkan/vulkan_core.h"), str(output)],
|
||||
check=True, capture_output=True)
|
||||
self.assertEqual(output.read_text(), (LAYER / "device_chain.inc").read_text())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,199 @@
|
||||
/* Production lifecycle functions are inserted verbatim by Python. No GPU,
|
||||
* Android app, external client or real timer is involved in this probe. */
|
||||
#define _POSIX_C_SOURCE 200809L
|
||||
#include <assert.h>
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <stdint.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
#include <wayland-util.h>
|
||||
#ifndef __linux__
|
||||
struct itimerspec { struct timespec it_interval, it_value; };
|
||||
#endif
|
||||
|
||||
struct wl_listener { struct wl_list link; void (*notify)(struct wl_listener *, void *); };
|
||||
struct wl_resource { int dma; void *user_data; struct wl_list listeners; unsigned releases; };
|
||||
struct wl_client;
|
||||
struct wl_event_source { int unused; };
|
||||
typedef struct AHardwareBuffer { int unused; } AHardwareBuffer;
|
||||
struct vkp_image { int unused; };
|
||||
struct dmabuf_buffer {
|
||||
int refs, n_planes, fd[4];
|
||||
struct vkp_image *img;
|
||||
void *ahb_state;
|
||||
};
|
||||
struct surface {
|
||||
struct wl_resource *dmabuf;
|
||||
struct dmabuf_buffer *dmabuf_buf;
|
||||
struct wl_listener dmabuf_destroy;
|
||||
int releases_pending;
|
||||
int64_t next_release_ns;
|
||||
};
|
||||
/* PRODUCTION_STRUCTS */
|
||||
static int g_dev_state, g_fps_limit, g_release_timer_fd;
|
||||
static int64_t g_refresh_ns;
|
||||
static struct wl_list g_pending_releases, g_bufs;
|
||||
static void *g_display;
|
||||
static unsigned image_destroys, ahb_releases, source_removes;
|
||||
static struct itimerspec last_timer;
|
||||
static const int wl_buffer_interface = 1, dbuf_buffer_impl = 2;
|
||||
#define TFD_TIMER_ABSTIME 1
|
||||
|
||||
/* List operations use the real Wayland layouts/macros. OS/IPC endpoints alone
|
||||
* are fakes, so no event is sent and no process or hardware is touched. */
|
||||
void wl_list_init(struct wl_list *l) { l->prev = l; l->next = l; }
|
||||
void wl_list_insert(struct wl_list *l, struct wl_list *e) {
|
||||
e->next = l->next; e->prev = l; l->next->prev = e; l->next = e;
|
||||
}
|
||||
void wl_list_remove(struct wl_list *e) { e->next->prev = e->prev; e->prev->next = e->next; }
|
||||
static int wl_resource_instance_of(struct wl_resource *r, const void *i, const void *impl) { return r->dma; }
|
||||
static void *wl_resource_get_user_data(struct wl_resource *r) { return r->user_data; }
|
||||
static void wl_resource_add_destroy_listener(struct wl_resource *r, struct wl_listener *l) {
|
||||
wl_list_insert(r->listeners.prev, &l->link);
|
||||
}
|
||||
static void wl_buffer_send_release(struct wl_resource *r) { ++r->releases; }
|
||||
static void wl_display_flush_clients(void *d) {}
|
||||
static int timerfd_settime(int fd, int flags, const struct itimerspec *v, void *old) { last_timer = *v; return 0; }
|
||||
static void perf_note_release(int64_t since) {}
|
||||
static int64_t now_ns(void) { return 1000000000LL; }
|
||||
static void vkp_image_destroy(struct vkp_image *img) { ++image_destroys; }
|
||||
static void AHardwareBuffer_release(AHardwareBuffer *ahb) { ++ahb_releases; }
|
||||
static int wl_event_source_remove(struct wl_event_source *src) { ++source_removes; return 0; }
|
||||
static struct dmabuf_buffer *get_dmabuf(struct wl_resource *r);
|
||||
int ahb_swapchain_defer_release(struct dmabuf_buffer *, struct wl_resource *, struct surface *, int);
|
||||
/* PRODUCTION_FUNCTIONS */
|
||||
|
||||
static void init_resource(struct wl_resource *r, struct dmabuf_buffer *b) {
|
||||
*r = (struct wl_resource){.dma = b != NULL, .user_data = b};
|
||||
wl_list_init(&r->listeners);
|
||||
}
|
||||
static struct dmabuf_buffer *init_buffer(struct surface *s, struct wl_resource *r) {
|
||||
struct dmabuf_buffer *b = calloc(1, sizeof(*b)); assert(b);
|
||||
b->refs = 2; b->n_planes = 1;
|
||||
int fds[2]; assert(pipe(fds) == 0); b->fd[0] = fds[0]; close(fds[1]);
|
||||
init_resource(r, b);
|
||||
assert(get_dmabuf(r) == b);
|
||||
*s = (struct surface){.dmabuf = r, .dmabuf_buf = b};
|
||||
s->dmabuf_destroy.notify = on_dmabuf_destroyed;
|
||||
wl_resource_add_destroy_listener(r, &s->dmabuf_destroy);
|
||||
return b;
|
||||
}
|
||||
static void destroy_resource(struct wl_resource *r) {
|
||||
while (r->listeners.next != &r->listeners) {
|
||||
struct wl_listener *l = wl_container_of(r->listeners.next, l, link);
|
||||
l->notify(l, r);
|
||||
}
|
||||
if (r->dma) dmabuf_buffer_unref(r->user_data);
|
||||
r->user_data = NULL;
|
||||
}
|
||||
static void fire_timer(void) {
|
||||
int fd[2]; uint64_t expirations = 1;
|
||||
assert(pipe(fd) == 0 && write(fd[1], &expirations, sizeof(expirations)) == sizeof(expirations));
|
||||
on_release_timer(fd[0], 0, NULL); close(fd[0]); close(fd[1]);
|
||||
}
|
||||
static void assert_retained(struct dmabuf_buffer *b, int refs) {
|
||||
assert(b->refs == refs && fcntl(b->fd[0], F_GETFD) >= 0 && !image_destroys);
|
||||
}
|
||||
static void test_drop(int paced) {
|
||||
struct surface s; struct wl_resource r;
|
||||
struct dmabuf_buffer *b = init_buffer(&s, &r);
|
||||
g_dev_state = -3; drop_dmabuf(&s, paced);
|
||||
assert(!s.dmabuf && !s.dmabuf_buf && !r.releases && !s.releases_pending);
|
||||
assert(r.listeners.next == &r.listeners); /* no listener into a dead surface */
|
||||
assert_retained(b, 2);
|
||||
destroy_resource(&r); assert_retained(b, 2);
|
||||
close(b->fd[0]); free(b); /* fake GPU only */
|
||||
}
|
||||
static void test_queue(int mixed, int client_gone) {
|
||||
struct surface s; struct wl_resource r, shm;
|
||||
struct dmabuf_buffer *b = init_buffer(&s, &r);
|
||||
g_release_timer_fd = 123; g_refresh_ns = 100000;
|
||||
drop_dmabuf(&s, 1); assert(s.releases_pending == 1 && !r.releases);
|
||||
assert(last_timer.it_value.tv_sec || last_timer.it_value.tv_nsec);
|
||||
if (mixed) { init_resource(&shm, NULL); release_buffer(&s, &shm, now_ns()); }
|
||||
pending_releases_forget_surface(&s);
|
||||
g_dev_state = -3;
|
||||
fire_timer();
|
||||
assert(!r.releases && g_pending_releases.next != &g_pending_releases);
|
||||
if (mixed) assert(shm.releases == 1);
|
||||
assert(!last_timer.it_value.tv_sec && !last_timer.it_value.tv_nsec);
|
||||
assert_retained(b, 1);
|
||||
if (client_gone) {
|
||||
destroy_resource(&r);
|
||||
assert(g_pending_releases.next == &g_pending_releases);
|
||||
assert_retained(b, 1);
|
||||
}
|
||||
close(b->fd[0]); free(b); /* fake GPU only */
|
||||
}
|
||||
static void test_active_client_destroy(void) {
|
||||
struct surface s; struct wl_resource r;
|
||||
struct dmabuf_buffer *b = init_buffer(&s, &r);
|
||||
g_dev_state = -3;
|
||||
destroy_resource(&r);
|
||||
assert(!s.dmabuf && s.dmabuf_buf == b && !r.releases);
|
||||
drop_dmabuf(&s, 0); assert(!s.dmabuf_buf);
|
||||
assert_retained(b, 2);
|
||||
close(b->fd[0]); free(b); /* fake GPU only */
|
||||
}
|
||||
static void test_ahb(int terminal, int lost) {
|
||||
struct surface s; struct wl_resource r;
|
||||
struct dmabuf_buffer *b = init_buffer(&s, &r);
|
||||
struct ahb_buf *ab = calloc(1, sizeof(*ab)); assert(ab);
|
||||
AHardwareBuffer ahb;
|
||||
*ab = (struct ahb_buf){.b = b, .ahb = &ahb, .resource = &r, .on_layer = 1, .fence_fd = -1};
|
||||
b->ahb_state = ab; ++b->refs;
|
||||
ab->resource_destroy.notify = on_buffer_resource_destroyed;
|
||||
wl_resource_add_destroy_listener(&r, &ab->resource_destroy);
|
||||
wl_list_insert(&g_bufs, &ab->link);
|
||||
drop_dmabuf(&s, 1); assert(ab->release_pending && ab->surface == &s);
|
||||
int backing_fd = b->fd[0];
|
||||
g_dev_state = terminal ? -3 : lost ? -2 : 1;
|
||||
ahb_swapchain_surface_gone(&s); assert(!ab->surface);
|
||||
/* Actual event-loop callback after the display's fence becomes readable. */
|
||||
struct wl_event_source source; int fds[2]; assert(pipe(fds) == 0);
|
||||
ab->on_layer = 0; ab->fence_src = &source; ab->fence_fd = fds[0];
|
||||
on_fence_readable(fds[0], 0, ab); close(fds[1]);
|
||||
assert(source_removes == 1 && ab->fence_fd == -1 && !ab->fence_src);
|
||||
assert(r.releases == (terminal ? 0u : 1u));
|
||||
assert(ab->release_pending == terminal && !ahb_releases);
|
||||
destroy_resource(&r);
|
||||
if (terminal) {
|
||||
assert(!ab->resource && b->ahb_state == ab && !ahb_releases);
|
||||
assert_retained(b, 2);
|
||||
close(b->fd[0]); free(ab); free(b); /* fake GPU only */
|
||||
} else {
|
||||
assert(ahb_releases == 1 && image_destroys == 1);
|
||||
errno = 0; assert(fcntl(backing_fd, F_GETFD) == -1 && errno == EBADF);
|
||||
}
|
||||
}
|
||||
static void test_cleanup(int lost) {
|
||||
struct surface s; struct wl_resource r;
|
||||
struct dmabuf_buffer *b = init_buffer(&s, &r);
|
||||
int fd = b->fd[0]; g_dev_state = lost ? -2 : 1;
|
||||
assert(!vkp_completion_unknown());
|
||||
drop_dmabuf(&s, 0);
|
||||
assert(r.releases == 1 && b->refs == 1 && !image_destroys);
|
||||
destroy_resource(&r); assert(image_destroys == 1);
|
||||
errno = 0; assert(fcntl(fd, F_GETFD) == -1 && errno == EBADF);
|
||||
}
|
||||
int main(int argc, char **argv) {
|
||||
assert(argc == 2);
|
||||
wl_list_init(&g_pending_releases); wl_list_init(&g_bufs);
|
||||
g_dev_state = 1; g_release_timer_fd = -1;
|
||||
if (!strcmp(argv[1], "replacement")) test_drop(1);
|
||||
else if (!strcmp(argv[1], "surface-gone")) test_drop(0);
|
||||
else if (!strcmp(argv[1], "queued")) test_queue(0, 0);
|
||||
else if (!strcmp(argv[1], "mixed")) test_queue(1, 0);
|
||||
else if (!strcmp(argv[1], "client-gone")) test_queue(0, 1);
|
||||
else if (!strcmp(argv[1], "ahb")) test_ahb(1, 0);
|
||||
else if (!strcmp(argv[1], "ahb-healthy")) test_ahb(0, 0);
|
||||
else if (!strcmp(argv[1], "ahb-device-lost")) test_ahb(0, 1);
|
||||
else if (!strcmp(argv[1], "active-client-gone")) test_active_client_destroy();
|
||||
else if (!strcmp(argv[1], "healthy")) test_cleanup(0);
|
||||
else if (!strcmp(argv[1], "device-lost")) test_cleanup(1);
|
||||
else assert(0 && "unknown scenario");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
#include <assert.h>
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "vk_external_image_sync.h"
|
||||
|
||||
static void check_external_pair(const struct vkp_external_client_barrier_pair *pair,
|
||||
VkImage image, uint32_t queue_family) {
|
||||
assert(pair->acquire.sType == VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER);
|
||||
assert(pair->acquire.oldLayout == VK_IMAGE_LAYOUT_GENERAL);
|
||||
assert(pair->acquire.newLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
|
||||
assert(pair->acquire.srcQueueFamilyIndex == VK_QUEUE_FAMILY_FOREIGN_EXT);
|
||||
assert(pair->acquire.dstQueueFamilyIndex == queue_family);
|
||||
assert(pair->acquire.image == image);
|
||||
assert(pair->acquire.srcAccessMask == 0);
|
||||
assert(pair->acquire.dstAccessMask == VK_ACCESS_TRANSFER_READ_BIT);
|
||||
assert(pair->acquire.subresourceRange.aspectMask == VK_IMAGE_ASPECT_COLOR_BIT);
|
||||
assert(pair->acquire.subresourceRange.baseMipLevel == 0);
|
||||
assert(pair->acquire.subresourceRange.levelCount == 1);
|
||||
assert(pair->acquire.subresourceRange.baseArrayLayer == 0);
|
||||
assert(pair->acquire.subresourceRange.layerCount == 1);
|
||||
|
||||
assert(pair->release.sType == VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER);
|
||||
assert(pair->release.oldLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
|
||||
assert(pair->release.newLayout == VK_IMAGE_LAYOUT_GENERAL);
|
||||
assert(pair->release.srcQueueFamilyIndex == queue_family);
|
||||
assert(pair->release.dstQueueFamilyIndex == VK_QUEUE_FAMILY_FOREIGN_EXT);
|
||||
assert(pair->release.image == image);
|
||||
assert(pair->release.srcAccessMask == VK_ACCESS_MEMORY_READ_BIT);
|
||||
assert(pair->release.dstAccessMask == 0);
|
||||
assert(pair->release.subresourceRange.aspectMask == VK_IMAGE_ASPECT_COLOR_BIT);
|
||||
assert(pair->release.subresourceRange.levelCount == 1);
|
||||
assert(pair->release.subresourceRange.layerCount == 1);
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
const VkImage image = (VkImage)(uintptr_t)0x1234;
|
||||
const VkImage ahb_image = (VkImage)(uintptr_t)0x5678;
|
||||
const uint32_t queue_family = 7;
|
||||
struct vkp_external_client_barrier_pair generic, ahb;
|
||||
|
||||
assert(vkp_external_client_barrier_pair(image, queue_family, 1, 0, &generic));
|
||||
check_external_pair(&generic, image, queue_family);
|
||||
|
||||
/* AHardwareBuffer imports deliberately use the same client flags and lifecycle. */
|
||||
assert(vkp_external_client_barrier_pair(ahb_image, queue_family, 1, 0, &ahb));
|
||||
check_external_pair(&ahb, ahb_image, queue_family);
|
||||
|
||||
unsigned char untouched[sizeof(generic)];
|
||||
memset(&generic, 0xa5, sizeof(generic));
|
||||
memcpy(untouched, &generic, sizeof(generic));
|
||||
assert(!vkp_external_client_barrier_pair(image, queue_family, 0, 0, &generic));
|
||||
assert(memcmp(&generic, untouched, sizeof(generic)) == 0);
|
||||
assert(!vkp_is_external_client_image(0, 0));
|
||||
|
||||
memset(&generic, 0x5a, sizeof(generic));
|
||||
memcpy(untouched, &generic, sizeof(generic));
|
||||
assert(!vkp_external_client_barrier_pair(image, queue_family, 1, 1, &generic));
|
||||
assert(memcmp(&generic, untouched, sizeof(generic)) == 0);
|
||||
assert(!vkp_is_external_client_image(1, 1));
|
||||
assert(vkp_is_external_client_image(1, 0));
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,290 @@
|
||||
/* Compiled with the complete, unmodified production translation unit. The
|
||||
* compositor's take_shm/take_pixel functions are inserted verbatim by Python. */
|
||||
#include "vk_present.c"
|
||||
#include <assert.h>
|
||||
|
||||
struct vk_api g_vk;
|
||||
static unsigned operations, acquires, submits, markers, waits, idle_calls, resets;
|
||||
static unsigned destroys, releases, lost_notifications, presented_notifications;
|
||||
static VkResult idle_answer, fence_answer, acquire_answer, present_answer;
|
||||
static unsigned fail_acquire_at;
|
||||
static int generated;
|
||||
|
||||
/* Every work-issuing callback is an oracle: no GPU operation after a terminal
|
||||
* result. Object destruction is counted separately for genuine device loss. */
|
||||
static void live(void) { assert(g_dev_state == 1); ++operations; }
|
||||
static VkResult acquire(VkDevice d, VkSwapchainKHR s, uint64_t t, VkSemaphore a, VkFence f, uint32_t *i) {
|
||||
live(); ++acquires; *i = 0;
|
||||
return acquires == fail_acquire_at ? acquire_answer : VK_SUCCESS;
|
||||
}
|
||||
static VkResult idle(VkDevice d) { live(); ++idle_calls; return idle_answer; }
|
||||
static VkResult wait_fences(VkDevice d, uint32_t n, const VkFence *f, VkBool32 all, uint64_t t) {
|
||||
live(); ++waits; return fence_answer;
|
||||
}
|
||||
static VkResult submit(VkQueue q, uint32_t n, const VkSubmitInfo *s, VkFence f) {
|
||||
live(); ++submits; if (!s->commandBufferCount) ++markers; return VK_SUCCESS;
|
||||
}
|
||||
static VkResult present(VkQueue q, const VkPresentInfoKHR *p) { live(); return present_answer; }
|
||||
static VkResult reset_cmd(VkCommandBuffer c, VkCommandBufferResetFlags f) { live(); ++resets; return VK_SUCCESS; }
|
||||
static VkResult reset_fence(VkDevice d, uint32_t n, const VkFence *f) { live(); ++resets; return VK_SUCCESS; }
|
||||
static VkResult begin_cmd(VkCommandBuffer c, const VkCommandBufferBeginInfo *b) { live(); return VK_SUCCESS; }
|
||||
static VkResult end_cmd(VkCommandBuffer c) { live(); return VK_SUCCESS; }
|
||||
static void barrier(VkCommandBuffer c, VkPipelineStageFlags s, VkPipelineStageFlags d, VkDependencyFlags f,
|
||||
uint32_t nm, const VkMemoryBarrier *m, uint32_t nb, const VkBufferMemoryBarrier *b,
|
||||
uint32_t ni, const VkImageMemoryBarrier *i) { live(); }
|
||||
static void clear(VkCommandBuffer c, VkImage i, VkImageLayout l, const VkClearColorValue *v,
|
||||
uint32_t n, const VkImageSubresourceRange *r) { live(); }
|
||||
static void blit(VkCommandBuffer c, VkImage s, VkImageLayout sl, VkImage d, VkImageLayout dl,
|
||||
uint32_t n, const VkImageBlit *b, VkFilter f) { live(); }
|
||||
static void destroy_swap(VkDevice d, VkSwapchainKHR s, const VkAllocationCallbacks *a) { ++destroys; }
|
||||
static void destroy_surface(VkInstance i, VkSurfaceKHR s, const VkAllocationCallbacks *a) { ++destroys; }
|
||||
static void destroy_sem(VkDevice d, VkSemaphore s, const VkAllocationCallbacks *a) { live(); ++destroys; }
|
||||
static VkResult create_sem(VkDevice d, const VkSemaphoreCreateInfo *c, const VkAllocationCallbacks *a, VkSemaphore *s) {
|
||||
live(); *s = (VkSemaphore)(uintptr_t)1; return VK_SUCCESS;
|
||||
}
|
||||
static void destroy_image(VkDevice d, VkImage i, const VkAllocationCallbacks *a) { ++destroys; }
|
||||
static void free_memory(VkDevice d, VkDeviceMemory m, const VkAllocationCallbacks *a) { ++destroys; }
|
||||
static void unmap(VkDevice d, VkDeviceMemory m) { ++destroys; }
|
||||
|
||||
/* External modules are not the subject of this fault injection. Their declared
|
||||
* signatures remain checked by the production headers. */
|
||||
int __android_log_print(int p, const char *t, const char *f, ...) { return 0; }
|
||||
void droiddeck_log(const char *t, const char *f, ...) {}
|
||||
void droiddeck_on_first_frame(void) {}
|
||||
int32_t ANativeWindow_getWidth(ANativeWindow *w) { return 64; }
|
||||
int32_t ANativeWindow_getHeight(ANativeWindow *w) { return 64; }
|
||||
void ANativeWindow_release(ANativeWindow *w) {}
|
||||
void sc_layer_window_gone(void) {}
|
||||
int sc_layer_present_pass(const struct vkp_draw *d, int n, int w, int h) { return 0; }
|
||||
void sc_layer_hide(void) {}
|
||||
int sc_layer_base_black(int w, int h) { return 0; }
|
||||
void sc_layer_hide_base(void) {}
|
||||
void sc_layer_hide_overlay(void) {}
|
||||
void vkp_cardboard_bind_device(VkDevice d, const VkPhysicalDeviceMemoryProperties *m) {}
|
||||
int vkp_cardboard_active(void) { return 0; }
|
||||
void vkp_cardboard_begin_frame(void) {}
|
||||
VkImage vkp_cardboard_run(VkCommandBuffer c, VkImage s, int sw, int sh, int ow, int oh) { return s; }
|
||||
int vk_loader_open(const char *a, const char *b, const char *c) { assert(0); return -1; }
|
||||
void vk_loader_load_instance(VkInstance i) { assert(0); }
|
||||
void vk_loader_load_device(VkDevice d) { assert(0); }
|
||||
PFN_vkGetInstanceProcAddr vk_loader_gipa(void) { return NULL; }
|
||||
void vkp_effects_bind_device(VkDevice d, VkPhysicalDevice p, const VkPhysicalDeviceMemoryProperties *m) {}
|
||||
int vkp_effects_active(void) { return 0; }
|
||||
int vkp_effects_upscaling(void) { return 0; }
|
||||
int vkp_effects_postprocessing(void) { return 0; }
|
||||
VkFilter vkp_effects_blit_filter(void) { return VK_FILTER_NEAREST; }
|
||||
void vkp_effects_set_formats(VkFormat a, VkFormat b) {}
|
||||
VkImage vkp_effects_run(VkCommandBuffer c, VkImage i, int w, int h, int ow, int oh, int *rw, int *rh) {
|
||||
*rw = w; *rh = h; return i;
|
||||
}
|
||||
const void *vkp_framegen_device_features(VkInstance i, PFN_vkGetInstanceProcAddr p, VkPhysicalDevice d) { return NULL; }
|
||||
void vkp_framegen_device_ready(VkDevice d, VkQueue q, uint32_t f, int e) {}
|
||||
void vkp_framegen_device_lost(void) { ++lost_notifications; }
|
||||
int vkp_framegen_active(void) { return generated != 0; }
|
||||
int vkp_framegen_extra_images(void) { return generated; }
|
||||
int vkp_framegen_format_ok(VkFormat f) { return 0; }
|
||||
int vkp_framegen_run(VkCommandBuffer c, VkImage s, VkImageView v, int w, int h,
|
||||
VkFormat f, VkImage images[VKP_FG_MAX_GENERATIONS]) {
|
||||
for (int i = 0; i < generated; ++i) images[i] = s;
|
||||
return generated;
|
||||
}
|
||||
void vkp_framegen_presented(int n) { ++presented_notifications; }
|
||||
void vkp_gpu_busy_device(VkPhysicalDevice p, VkDevice d, uint32_t f) {}
|
||||
void vkp_gpu_busy_device_lost(void) {}
|
||||
void hdrc_bind_device(VkDevice d, const VkPhysicalDeviceMemoryProperties *m) {}
|
||||
void hdrc_forget_image(VkImage i) {}
|
||||
int hdrc_encode(VkCommandBuffer c, VkImage a, VkImage b, VkFormat f, int w, int h, const struct hdrc_params *p) { return -1; }
|
||||
void blendp_bind_device(VkDevice d) {}
|
||||
void blendp_forget_image(VkImage i) {}
|
||||
void vkp_effects_forget_image(VkImage i) {}
|
||||
void blendp_begin_frame(void) {}
|
||||
int blendp_draw(VkCommandBuffer c, VkImage s, VkFormat sf, int sw, int sh, int sg,
|
||||
VkImage d, VkFormat df, int dw, int dh, const VkImageBlit *b) { return -1; }
|
||||
int droiddeck_color_requested(void) { return 0; }
|
||||
float droiddeck_color_sdr_white(void) { return 203.0f; }
|
||||
|
||||
enum surface_role { ROLE_NONE, ROLE_TOPLEVEL };
|
||||
struct damage_list { int n; };
|
||||
struct surface {
|
||||
struct vkp_image *shm_img;
|
||||
struct wl_resource *resource;
|
||||
int buf_w, buf_h, buf_alpha, has_content;
|
||||
/* Read by take_shm's game-frame detection; with no damage it stays off here. */
|
||||
int src_set; float src[4];
|
||||
struct damage_list damage_buf, damage_local;
|
||||
struct surface *parent; enum surface_role role; int mapped;
|
||||
};
|
||||
static void surface_size(const struct surface *s, int *w, int *h) { *w = s->buf_w; *h = s->buf_h; }
|
||||
static void scene_size(int *w, int *h) { *w = *h = 0; }
|
||||
static int64_t damage_area(const struct damage_list *d, int bound_w, int bound_h) { return 0; }
|
||||
static int64_t now_ns(void) { return 0; }
|
||||
static struct surface *g_hud_surface, *g_hud_shm;
|
||||
static int64_t g_hud_shm_ns, g_hud_last_ns;
|
||||
static int g_hud_new;
|
||||
static void droiddeck_on_game_frame(void) {}
|
||||
struct client_info { int asked_feedback, shm_frames; };
|
||||
struct wl_shm_buffer { int w, h, stride; const void *data; };
|
||||
#define WL_SHM_FORMAT_ARGB8888 0
|
||||
static unsigned g_stat_shm;
|
||||
static int wl_shm_buffer_get_width(struct wl_shm_buffer *b) { return b->w; }
|
||||
static int wl_shm_buffer_get_height(struct wl_shm_buffer *b) { return b->h; }
|
||||
static int wl_shm_buffer_get_stride(struct wl_shm_buffer *b) { return b->stride; }
|
||||
static int wl_shm_buffer_get_format(struct wl_shm_buffer *b) { return WL_SHM_FORMAT_ARGB8888; }
|
||||
static const void *wl_shm_buffer_get_data(struct wl_shm_buffer *b) { return b->data; }
|
||||
static void wl_shm_buffer_begin_access(struct wl_shm_buffer *b) {}
|
||||
static void wl_shm_buffer_end_access(struct wl_shm_buffer *b) {}
|
||||
struct wl_resource { int dmabuf; };
|
||||
static struct wl_resource *expected_release;
|
||||
static void wl_buffer_send_release(struct wl_resource *b) { assert(b && b == expected_release); ++releases; }
|
||||
static struct wl_client *wl_resource_get_client(struct wl_resource *r) { return NULL; }
|
||||
static struct client_info *client_info_of(struct wl_client *c) { return NULL; }
|
||||
struct dmabuf_buffer { int unused; };
|
||||
static struct dmabuf_buffer dmabuf_fixture;
|
||||
static struct dmabuf_buffer *get_dmabuf(struct wl_resource *buffer) {
|
||||
assert(buffer);
|
||||
return buffer->dmabuf ? &dmabuf_fixture : NULL;
|
||||
}
|
||||
/* COMPOSITOR_CALLERS */
|
||||
|
||||
static void setup(int extra) {
|
||||
g_vk = (struct vk_api){.AcquireNextImageKHR = acquire, .DeviceWaitIdle = idle,
|
||||
.WaitForFences = wait_fences, .QueueSubmit = submit, .QueuePresentKHR = present,
|
||||
.ResetCommandBuffer = reset_cmd, .ResetFences = reset_fence, .BeginCommandBuffer = begin_cmd,
|
||||
.EndCommandBuffer = end_cmd, .CmdPipelineBarrier = barrier, .CmdClearColorImage = clear,
|
||||
.CmdBlitImage = blit, .DestroySwapchainKHR = destroy_swap, .DestroySurfaceKHR = destroy_surface,
|
||||
.DestroySemaphore = destroy_sem, .CreateSemaphore = create_sem,
|
||||
.DestroyImage = destroy_image, .FreeMemory = free_memory, .UnmapMemory = unmap};
|
||||
idle_answer = fence_answer = acquire_answer = present_answer = VK_SUCCESS;
|
||||
generated = g_swap_extra = extra;
|
||||
g_dev_state = 1;
|
||||
g_dev = (VkDevice)(uintptr_t)1; g_inst = (VkInstance)(uintptr_t)1;
|
||||
g_window = (ANativeWindow *)(uintptr_t)1; g_queue = (VkQueue)(uintptr_t)1;
|
||||
g_swapchain = (VkSwapchainKHR)(uintptr_t)2; g_surface = (VkSurfaceKHR)(uintptr_t)3;
|
||||
g_images = calloc(1, sizeof(*g_images)); assert(g_images);
|
||||
*g_images = (VkImage)(uintptr_t)4; g_nimg = 1;
|
||||
g_extent = g_caps_extent = (VkExtent2D){64, 64};
|
||||
g_surface_checked_ns = INT64_MAX; /* no simulated geometry change */
|
||||
g_scene.img = (VkImage)(uintptr_t)5; g_scene.mem = (VkDeviceMemory)(uintptr_t)6;
|
||||
g_scene.w = g_scene.h = 64;
|
||||
for (int k = 0; k < MAX_PRESENTS; ++k) {
|
||||
g_cmds[k] = (VkCommandBuffer)(uintptr_t)(10 + k);
|
||||
g_acqs[k] = (VkSemaphore)(uintptr_t)(20 + k);
|
||||
g_rnds[k] = (VkSemaphore)(uintptr_t)(30 + k);
|
||||
}
|
||||
g_fence = (VkFence)(uintptr_t)40;
|
||||
}
|
||||
|
||||
/* Probe the public GPU entry points after a terminal result. This includes an
|
||||
* active off-screen pass and consumed release fds, not just the render guard. */
|
||||
static void assert_stopped(void) {
|
||||
unsigned before = operations, before_destroys = destroys;
|
||||
struct vkp_image src = {.image = (VkImage)(uintptr_t)7, .w = 1, .h = 1};
|
||||
struct vkp_image dst = {.image = (VkImage)(uintptr_t)8, .w = 1, .h = 1, .blit_dst = 1};
|
||||
uint32_t pixel = 0; uint64_t mod = 0;
|
||||
assert(vkp_render(64, 64, NULL, 0) == -1);
|
||||
assert(vkp_render_plain(64, 64) == -1);
|
||||
assert(vkp_render_hdr(64, 64, NULL, 0, NULL, NULL) == -1);
|
||||
assert(vkp_base_black(64, 64) == -1);
|
||||
assert(vkp_update_map(64, 64) == -1);
|
||||
assert(vkp_ready() == -1);
|
||||
assert(vkp_image_create_shm(1, 1) == NULL);
|
||||
assert(vkp_image_import_dmabuf(-1, 0, VKP_MOD_LINEAR, 1, 1, 4, 0, 0) == NULL);
|
||||
assert(vkp_dmabuf_modifiers(0, &mod, 1) == 0);
|
||||
assert(vkp_image_readback(&src, &pixel, 1) == -1);
|
||||
assert(vkp_pass_begin(64, 64, NULL, 0, NULL, NULL) == -1);
|
||||
int fd[2]; assert(pipe(fd) == 0);
|
||||
assert(vkp_blit_image(&src, &dst, fd[0]) == -1);
|
||||
errno = 0; assert(close(fd[0]) == -1 && errno == EBADF); close(fd[1]);
|
||||
g_pass.active = 1;
|
||||
assert(pipe(fd) == 0);
|
||||
assert(vkp_pass_copy_to(&dst, fd[0]) == -1 && !g_pass.active);
|
||||
errno = 0; assert(close(fd[0]) == -1 && errno == EBADF); close(fd[1]);
|
||||
g_pass.active = 1; vkp_pass_abort(); assert(!g_pass.active);
|
||||
assert(timed_wait(g_fence, UINT64_MAX) != VK_SUCCESS);
|
||||
assert(operations == before && destroys == before_destroys);
|
||||
}
|
||||
|
||||
static void acquire_failure(int later, VkResult result) {
|
||||
setup(later ? 1 : 0);
|
||||
fail_acquire_at = later ? 2 : 1; acquire_answer = result;
|
||||
idle_answer = VK_ERROR_OUT_OF_HOST_MEMORY;
|
||||
VkImage *retained = g_images;
|
||||
assert(vkp_render(64, 64, NULL, 0) == -1);
|
||||
assert(g_dev_state == -3 && vkp_completion_unknown() && !vkp_device_lost());
|
||||
assert(acquires == fail_acquire_at && idle_calls == 1);
|
||||
assert(submits == (unsigned)later && markers == 0 && waits == 0);
|
||||
assert(destroys == 0 && g_images == retained && g_nimg == 1);
|
||||
assert(g_swapchain && g_surface && g_fence && g_scene.img && g_scene.mem);
|
||||
assert_stopped();
|
||||
free(g_images); /* test-owned fake resources only */
|
||||
}
|
||||
|
||||
static void upload_timeout(int single_pixel) {
|
||||
setup(0);
|
||||
uint8_t bytes[48], saved[48], data[16];
|
||||
memset(bytes, 0xa5, sizeof(bytes)); memset(data, 0x3c, sizeof(data));
|
||||
struct vkp_image *img = calloc(1, sizeof(*img)); assert(img);
|
||||
*img = (struct vkp_image){.image = (VkImage)(uintptr_t)7, .mem = (VkDeviceMemory)(uintptr_t)8,
|
||||
.map = bytes, .offset = 3, .row_pitch = 16,
|
||||
.w = single_pixel ? 1 : 2, .h = single_pixel ? 1 : 2};
|
||||
struct surface s = {.shm_img = img};
|
||||
struct wl_shm_buffer b = {.w = img->w, .h = img->h, .stride = img->w * 4, .data = data};
|
||||
struct wl_resource resource = {0};
|
||||
expected_release = &resource;
|
||||
if (single_pixel) take_pixel(&s, data, &resource); else take_shm(&s, &b, &resource);
|
||||
assert(bytes[3] == 0x3c && bytes[0] == 0xa5 && releases == 1);
|
||||
memcpy(saved, bytes, sizeof(saved));
|
||||
struct vkp_image dst = {.image = (VkImage)(uintptr_t)9, .blit_dst = 1, .w = img->w, .h = img->h};
|
||||
fence_answer = VK_TIMEOUT;
|
||||
assert(vkp_blit_image(img, &dst, -1) == -1);
|
||||
assert(g_dev_state == -3 && submits == 1 && waits == 1);
|
||||
memset(data, 0x7e, sizeof(data));
|
||||
if (single_pixel) take_pixel(&s, data, &resource); else take_shm(&s, &b, &resource);
|
||||
assert(s.shm_img == img && memcmp(saved, bytes, sizeof(saved)) == 0 && releases == 2);
|
||||
struct wl_resource dmabuf = {.dmabuf = 1};
|
||||
expected_release = &dmabuf;
|
||||
assert(buffer_release_blocked(&dmabuf));
|
||||
send_buffer_release(&dmabuf);
|
||||
assert(releases == 2);
|
||||
vkp_image_destroy(img);
|
||||
assert(destroys == 0 && img->map == bytes && img->image && img->mem);
|
||||
assert_stopped();
|
||||
g_dev_state = 1;
|
||||
assert(!buffer_release_blocked(&dmabuf));
|
||||
send_buffer_release(&dmabuf);
|
||||
assert(releases == 3);
|
||||
free(img); free(g_images); /* fake resources only, not production cleanup */
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
assert(argc == 2);
|
||||
const char *name = argv[1];
|
||||
if (!strcmp(name, "first-out-of-date")) acquire_failure(0, VK_ERROR_OUT_OF_DATE_KHR);
|
||||
else if (!strcmp(name, "first-surface-lost")) acquire_failure(0, VK_ERROR_SURFACE_LOST_KHR);
|
||||
else if (!strcmp(name, "later-out-of-date")) acquire_failure(1, VK_ERROR_OUT_OF_DATE_KHR);
|
||||
else if (!strcmp(name, "later-surface-lost")) acquire_failure(1, VK_ERROR_SURFACE_LOST_KHR);
|
||||
else if (!strcmp(name, "shm-timeout")) upload_timeout(0);
|
||||
else if (!strcmp(name, "pixel-timeout")) upload_timeout(1);
|
||||
else if (!strcmp(name, "pass-terminal")) { setup(0); g_dev_state = -3; assert_stopped(); free(g_images); }
|
||||
else if (!strcmp(name, "normal") || !strcmp(name, "framegen")) {
|
||||
int extra = !strcmp(name, "framegen"); setup(extra);
|
||||
assert(vkp_render(64, 64, NULL, 0) == 0 && g_dev_state == 1);
|
||||
assert(acquires == (unsigned)(1 + extra) && submits == (unsigned)(1 + extra));
|
||||
assert(waits == 1 && markers == 0 && idle_calls == 0 && destroys == 0);
|
||||
assert(presented_notifications == (unsigned)extra); free(g_images);
|
||||
} else if (!strcmp(name, "later-timeout")) {
|
||||
setup(1); fail_acquire_at = 2; acquire_answer = VK_TIMEOUT;
|
||||
assert(vkp_render(64, 64, NULL, 0) == -1 && g_dev_state == 1);
|
||||
assert(acquires == 2 && submits == 2 && markers == 1 && waits == 1); free(g_images);
|
||||
} else if (!strcmp(name, "acquire-device-lost") || !strcmp(name, "present-device-lost")) {
|
||||
setup(1);
|
||||
if (!strcmp(name, "acquire-device-lost")) { fail_acquire_at = 2; acquire_answer = VK_ERROR_DEVICE_LOST; }
|
||||
else present_answer = VK_ERROR_DEVICE_LOST;
|
||||
assert(vkp_render(64, 64, NULL, 0) == -1 && vkp_device_lost());
|
||||
assert(!vkp_completion_unknown());
|
||||
assert(g_dev_state == -2 && lost_notifications == 1 && markers == 0 && waits == 0);
|
||||
assert(!g_images && !g_swapchain && !g_surface && destroys == 2);
|
||||
assert_stopped();
|
||||
} else assert(0 && "unknown scenario");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
/* The Xclipse layer between a simulated loader and a mock driver. The driver refuses what the compat
|
||||
* layer and Samsung's driver refuse: textureCompressionBC, and a compute layout holding an immutable
|
||||
* YCbCr sampler. Built by test_xclipse_layer.py with the layer source included directly. */
|
||||
#include "xclipse_layer.c"
|
||||
#include <assert.h>
|
||||
|
||||
struct object { void *dispatch; };
|
||||
static int instance_table, device_table[4];
|
||||
static struct object mock_instance = {&instance_table}, mock_physical = {&instance_table};
|
||||
static struct object mock_devices[4] = {{&device_table[0]}, {&device_table[1]}, {&device_table[2]}, {&device_table[3]}};
|
||||
static int devices_created;
|
||||
|
||||
/* What the driver last saw. */
|
||||
static int driver_saw_bc, driver_saw_layout_sampler_count;
|
||||
static VkSampler driver_layout_samplers[16];
|
||||
static uint64_t next_sampler = 0x100;
|
||||
static VkSampler driver_ycbcr[16];
|
||||
static int driver_ycbcr_count;
|
||||
|
||||
static VkResult VKAPI_CALL mock_create_instance(const VkInstanceCreateInfo *info, const VkAllocationCallbacks *allocator,
|
||||
VkInstance *instance) {
|
||||
*instance = (VkInstance)&mock_instance;
|
||||
return VK_SUCCESS;
|
||||
}
|
||||
|
||||
static void VKAPI_CALL mock_features(VkPhysicalDevice physical, VkPhysicalDeviceFeatures *features) {
|
||||
memset(features, 0, sizeof(*features));
|
||||
}
|
||||
|
||||
static void VKAPI_CALL mock_features2(VkPhysicalDevice physical, VkPhysicalDeviceFeatures2 *features) {
|
||||
mock_features(physical, &features->features);
|
||||
}
|
||||
|
||||
/* The compat layer's emulation: BC formats sample, the feature bit stays off. */
|
||||
static void VKAPI_CALL mock_format_properties(VkPhysicalDevice physical, VkFormat format, VkFormatProperties *out) {
|
||||
memset(out, 0, sizeof(*out));
|
||||
if (format >= VK_FORMAT_BC1_RGB_UNORM_BLOCK && format <= VK_FORMAT_BC7_SRGB_BLOCK)
|
||||
out->optimalTilingFeatures = VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT;
|
||||
}
|
||||
|
||||
static void VKAPI_CALL mock_format_properties2(VkPhysicalDevice physical, VkFormat format, VkFormatProperties2 *out) {
|
||||
mock_format_properties(physical, format, &out->formatProperties);
|
||||
}
|
||||
|
||||
static VkResult VKAPI_CALL mock_time_domains(VkPhysicalDevice physical, uint32_t *count, VkTimeDomainEXT *domains) {
|
||||
if (domains) { domains[0] = VK_TIME_DOMAIN_DEVICE_EXT; domains[1] = VK_TIME_DOMAIN_CLOCK_MONOTONIC_EXT; }
|
||||
*count = 2;
|
||||
return VK_SUCCESS;
|
||||
}
|
||||
|
||||
static VkResult VKAPI_CALL mock_create_device(VkPhysicalDevice physical, const VkDeviceCreateInfo *info,
|
||||
const VkAllocationCallbacks *allocator, VkDevice *device) {
|
||||
driver_saw_bc = info->pEnabledFeatures && info->pEnabledFeatures->textureCompressionBC;
|
||||
for (const VkBaseInStructure *p = info->pNext; p; p = p->pNext)
|
||||
if (p->sType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2 &&
|
||||
((const VkPhysicalDeviceFeatures2 *)p)->features.textureCompressionBC) driver_saw_bc = 1;
|
||||
if (driver_saw_bc) return VK_ERROR_FEATURE_NOT_PRESENT;
|
||||
assert(devices_created < 4);
|
||||
*device = (VkDevice)&mock_devices[devices_created++];
|
||||
return VK_SUCCESS;
|
||||
}
|
||||
|
||||
static VkResult VKAPI_CALL mock_create_sampler(VkDevice device, const VkSamplerCreateInfo *info,
|
||||
const VkAllocationCallbacks *allocator, VkSampler *sampler) {
|
||||
*sampler = (VkSampler)next_sampler++;
|
||||
for (const VkBaseInStructure *p = info->pNext; p; p = p->pNext)
|
||||
if (p->sType == VK_STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_INFO) driver_ycbcr[driver_ycbcr_count++] = *sampler;
|
||||
return VK_SUCCESS;
|
||||
}
|
||||
|
||||
static void VKAPI_CALL mock_destroy_sampler(VkDevice device, VkSampler sampler, const VkAllocationCallbacks *allocator) {
|
||||
for (int i = 0; i < driver_ycbcr_count; i++)
|
||||
if (driver_ycbcr[i] == sampler) driver_ycbcr[i] = driver_ycbcr[--driver_ycbcr_count];
|
||||
}
|
||||
|
||||
static VkResult VKAPI_CALL mock_create_set_layout(VkDevice device, const VkDescriptorSetLayoutCreateInfo *info,
|
||||
const VkAllocationCallbacks *allocator, VkDescriptorSetLayout *layout) {
|
||||
driver_saw_layout_sampler_count = 0;
|
||||
for (uint32_t b = 0; b < info->bindingCount; b++) {
|
||||
const VkDescriptorSetLayoutBinding *binding = &info->pBindings[b];
|
||||
for (uint32_t s = 0; binding->pImmutableSamplers && s < binding->descriptorCount; s++) {
|
||||
VkSampler sampler = binding->pImmutableSamplers[s];
|
||||
driver_layout_samplers[driver_saw_layout_sampler_count++] = sampler;
|
||||
for (int i = 0; i < driver_ycbcr_count; i++)
|
||||
if ((binding->stageFlags & VK_SHADER_STAGE_COMPUTE_BIT) && driver_ycbcr[i] == sampler)
|
||||
return VK_ERROR_UNKNOWN;
|
||||
}
|
||||
}
|
||||
*layout = (VkDescriptorSetLayout)0x5000;
|
||||
return VK_SUCCESS;
|
||||
}
|
||||
|
||||
static void VKAPI_CALL mock_destroy_device(VkDevice device, const VkAllocationCallbacks *allocator) {}
|
||||
|
||||
static VkResult VKAPI_CALL mock_timestamps(VkDevice device, uint32_t count, const VkCalibratedTimestampInfoEXT *infos,
|
||||
uint64_t *timestamps, uint64_t *deviation) {
|
||||
for (uint32_t i = 0; i < count; i++) timestamps[i] = 42;
|
||||
*deviation = 1;
|
||||
return VK_SUCCESS;
|
||||
}
|
||||
|
||||
#define MOCK(name, function) if (!strcmp(requested, name)) return (PFN_vkVoidFunction)function
|
||||
static VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL mock_gipa(VkInstance instance, const char *requested) {
|
||||
MOCK("vkCreateInstance", mock_create_instance);
|
||||
MOCK("vkCreateDevice", mock_create_device);
|
||||
MOCK("vkGetPhysicalDeviceFeatures", mock_features);
|
||||
MOCK("vkGetPhysicalDeviceFeatures2", mock_features2);
|
||||
MOCK("vkGetPhysicalDeviceFormatProperties", mock_format_properties);
|
||||
MOCK("vkGetPhysicalDeviceFormatProperties2", mock_format_properties2);
|
||||
MOCK("vkGetPhysicalDeviceCalibrateableTimeDomainsEXT", mock_time_domains);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL mock_gdpa(VkDevice device, const char *requested) {
|
||||
MOCK("vkCreateSampler", mock_create_sampler);
|
||||
MOCK("vkDestroySampler", mock_destroy_sampler);
|
||||
MOCK("vkCreateDescriptorSetLayout", mock_create_set_layout);
|
||||
MOCK("vkDestroyDevice", mock_destroy_device);
|
||||
MOCK("vkGetCalibratedTimestampsEXT", mock_timestamps);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/* The loader's link for one vkCreateDevice call, then the caller's own chain. */
|
||||
static VkResult create(const void *chain, const VkPhysicalDeviceFeatures *enabled, VkDevice *device) {
|
||||
VkLayerDeviceLink link = {NULL, mock_gipa, mock_gdpa};
|
||||
VkLayerDeviceCreateInfo loader = {VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO, chain, VK_LAYER_LINK_INFO, {&link}};
|
||||
VkDeviceCreateInfo info = {VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, &loader, 0, 0, NULL, 0, NULL, 0, NULL, enabled};
|
||||
PFN_vkCreateDevice create_device = (PFN_vkCreateDevice)vkGetInstanceProcAddr((VkInstance)&mock_instance, "vkCreateDevice");
|
||||
return create_device((VkPhysicalDevice)&mock_physical, &info, NULL, device);
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
VkNegotiateLayerInterface negotiate = {LAYER_NEGOTIATE_INTERFACE_STRUCT, NULL, 2, NULL, NULL, NULL};
|
||||
assert(vkNegotiateLoaderLayerInterfaceVersion(&negotiate) == VK_SUCCESS);
|
||||
|
||||
VkLayerInstanceLink instance_link = {NULL, mock_gipa, NULL};
|
||||
VkLayerInstanceCreateInfo instance_loader = {VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO, NULL, VK_LAYER_LINK_INFO,
|
||||
{&instance_link}};
|
||||
VkInstanceCreateInfo instance_info = {.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, .pNext = &instance_loader};
|
||||
VkInstance instance;
|
||||
PFN_vkCreateInstance create_instance_fn = (PFN_vkCreateInstance)vkGetInstanceProcAddr(NULL, "vkCreateInstance");
|
||||
assert(create_instance_fn(&instance_info, NULL, &instance) == VK_SUCCESS);
|
||||
|
||||
/* The emulated bit is reported... */
|
||||
VkPhysicalDeviceFeatures features;
|
||||
((PFN_vkGetPhysicalDeviceFeatures)vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceFeatures"))(
|
||||
(VkPhysicalDevice)&mock_physical, &features);
|
||||
assert(features.textureCompressionBC);
|
||||
|
||||
/* ...and cleared before the driver, through pEnabledFeatures... */
|
||||
VkDevice device;
|
||||
VkPhysicalDeviceFeatures legacy = {.textureCompressionBC = VK_TRUE};
|
||||
assert(create(NULL, &legacy, &device) == VK_SUCCESS && !driver_saw_bc && legacy.textureCompressionBC);
|
||||
|
||||
/* ...and through a VkPhysicalDeviceFeatures2 behind another structure, leaving the caller's chain intact. */
|
||||
VkPhysicalDeviceVulkan12Features vk12 = {.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES};
|
||||
VkPhysicalDeviceFeatures2 features2 = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &vk12,
|
||||
{.textureCompressionBC = VK_TRUE}};
|
||||
VkPhysicalDeviceTimelineSemaphoreFeatures timeline = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TIMELINE_SEMAPHORE_FEATURES,
|
||||
&features2, VK_TRUE};
|
||||
VkPhysicalDeviceFeatures2 features2_before = features2;
|
||||
VkPhysicalDeviceTimelineSemaphoreFeatures timeline_before = timeline;
|
||||
VkDevice chained;
|
||||
assert(create(&timeline, NULL, &chained) == VK_SUCCESS && !driver_saw_bc);
|
||||
assert(!memcmp(&features2, &features2_before, sizeof(features2)));
|
||||
assert(!memcmp(&timeline, &timeline_before, sizeof(timeline)));
|
||||
|
||||
/* A structure newer than the headers this was built with cannot be copied: the chain passes as it
|
||||
* is and the driver refuses the bit, without the caller's structures being written. */
|
||||
struct { VkStructureType sType; const void *pNext; uint32_t payload; } future = {(VkStructureType)0x7ffffff0, &features2, 7};
|
||||
VkDevice unused;
|
||||
assert(create(&future, NULL, &unused) == VK_ERROR_FEATURE_NOT_PRESENT);
|
||||
assert(!memcmp(&features2, &features2_before, sizeof(features2)) && future.pNext == &features2);
|
||||
|
||||
/* Compute layouts get a plain sampler in place of a YCbCr one. */
|
||||
PFN_vkCreateSampler create_sampler_fn = (PFN_vkCreateSampler)vkGetDeviceProcAddr(device, "vkCreateSampler");
|
||||
PFN_vkDestroySampler destroy_sampler_fn = (PFN_vkDestroySampler)vkGetDeviceProcAddr(device, "vkDestroySampler");
|
||||
PFN_vkCreateDescriptorSetLayout create_layout = (PFN_vkCreateDescriptorSetLayout)vkGetDeviceProcAddr(device, "vkCreateDescriptorSetLayout");
|
||||
VkSamplerYcbcrConversionInfo conversion = {VK_STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_INFO, NULL, (VkSamplerYcbcrConversion)1};
|
||||
VkSamplerCreateInfo ycbcr_info = {.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO, .pNext = &conversion};
|
||||
VkSamplerCreateInfo plain_info = {.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO};
|
||||
VkSampler ycbcr;
|
||||
assert(create_sampler_fn(device, &ycbcr_info, NULL, &ycbcr) == VK_SUCCESS);
|
||||
VkSampler immutable[2] = {ycbcr, ycbcr};
|
||||
VkDescriptorSetLayoutBinding binding = {4, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 2, VK_SHADER_STAGE_COMPUTE_BIT, immutable};
|
||||
VkDescriptorSetLayoutCreateInfo layout_info = {VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, NULL, 0, 1, &binding};
|
||||
VkDescriptorSetLayout layout;
|
||||
assert(create_layout(device, &layout_info, NULL, &layout) == VK_SUCCESS);
|
||||
assert(driver_layout_samplers[0] != ycbcr && immutable[0] == ycbcr);
|
||||
|
||||
/* A destroyed YCbCr sampler's handle, reused for a plain sampler, is left alone. */
|
||||
destroy_sampler_fn(device, ycbcr, NULL);
|
||||
next_sampler = (uint64_t)ycbcr;
|
||||
VkSampler reused;
|
||||
assert(create_sampler_fn(device, &plain_info, NULL, &reused) == VK_SUCCESS && reused == ycbcr);
|
||||
immutable[0] = immutable[1] = reused;
|
||||
assert(create_layout(device, &layout_info, NULL, &layout) == VK_SUCCESS && driver_layout_samplers[0] == reused);
|
||||
|
||||
/* Registrations belong to their device and go with it. */
|
||||
VkSampler other;
|
||||
assert(create_sampler_fn(chained, &ycbcr_info, NULL, &other) == VK_SUCCESS && ycbcr_count == 1);
|
||||
((PFN_vkDestroyDevice)vkGetDeviceProcAddr(chained, "vkDestroyDevice"))(chained, NULL);
|
||||
assert(ycbcr_count == 0);
|
||||
|
||||
/* The KHR calibrated-timestamp entry points reach the EXT ones. */
|
||||
uint32_t domains = 0;
|
||||
PFN_vkGetPhysicalDeviceCalibrateableTimeDomainsEXT time_domains = (PFN_vkGetPhysicalDeviceCalibrateableTimeDomainsEXT)
|
||||
vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceCalibrateableTimeDomainsKHR");
|
||||
assert(time_domains((VkPhysicalDevice)&mock_physical, &domains, NULL) == VK_SUCCESS && domains == 2);
|
||||
VkCalibratedTimestampInfoEXT stamp = {VK_STRUCTURE_TYPE_CALIBRATED_TIMESTAMP_INFO_EXT, NULL, VK_TIME_DOMAIN_DEVICE_EXT};
|
||||
uint64_t value = 0, deviation = 0;
|
||||
PFN_vkGetCalibratedTimestampsEXT timestamps = (PFN_vkGetCalibratedTimestampsEXT)vkGetDeviceProcAddr(device, "vkGetCalibratedTimestampsKHR");
|
||||
assert(timestamps(device, 1, &stamp, &value, &deviation) == VK_SUCCESS && value == 42);
|
||||
|
||||
puts("xclipse layer ok");
|
||||
return 0;
|
||||
}
|
||||
Reference in new issue
Block a user