Merge #570 (PowerVR + Xclipse system Vulkan) into the non-Adreno test branch

# Conflicts:
#	.github/workflows/build.yml
#	app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt
#	app/src/main/java/com/droiddeck/launcher/session/SessionService.kt
#	tools/build_local.sh
#	tools/dxvk/build.sh
#	tools/linuxfs/overlay/usr/local/bin/droiddeck-session
#	tools/release/runtime_inputs.py
#	tools/tests/test_runtime_inputs.py
This commit is contained in:
The412Banner committed 2026-10-12 18:34:02 -04:00
commit 56dc433673
104 files changed
+7206 -206

No files matched your search

+7 -1
View File
@@ -13,7 +13,7 @@ else
fi
sdk_dir=${ANDROID_HOME:-${ANDROID_SDK_ROOT:-"${HOME}/Library/Android/sdk"}}
java_dir=${JAVA_HOME:-"/opt/homebrew/opt/openjdk@17/libexec/openjdk.jdk/Contents/Home"}
image_name=${DROIDDECK_BUILD_IMAGE:-droiddeck-local-cross:24.04-v3}
image_name=${DROIDDECK_BUILD_IMAGE:-droiddeck-local-cross:24.04-v4}
build_variant=${DROIDDECK_BUILD_VARIANT:-release}
case "$build_variant" in
debug) gradle_task=assembleDebug ;;
@@ -102,6 +102,11 @@ docker run --rm --platform linux/amd64 \
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \
-o "$d/libssbs.so" tools/linuxfs/ssbs/ssbs_adapter.c -ldl
aarch64-linux-gnu-strip --strip-unneeded "$d/libssbs.so"
mkdir -p "$d/usr/local/lib/droiddeck-xclipse"
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -Wextra -Wno-unused-parameter -fvisibility=hidden -pthread \
-o "$d/usr/local/lib/droiddeck-xclipse/libVkLayer_droiddeck_xclipse.so" tools/linuxfs/xclipse-layer/xclipse_layer.c -ldl
aarch64-linux-gnu-strip --strip-unneeded "$d/usr/local/lib/droiddeck-xclipse/libVkLayer_droiddeck_xclipse.so"
install -m644 tools/linuxfs/xclipse-layer/VkLayer_droiddeck_xclipse.json "$d/usr/local/lib/droiddeck-xclipse/"
mkdir -p "$d/usr/local/bin"
aarch64-linux-gnu-gcc -O2 -Wall -Wextra -o "$d/usr/local/bin/droiddeck-clipboard" tools/linuxfs/clipboard/clipboard.c -ldl
aarch64-linux-gnu-strip --strip-unneeded "$d/usr/local/bin/droiddeck-clipboard"
@@ -322,6 +327,7 @@ fi
cd "${repo_root}"
python3 tools/quest/build-driver.py "${NDK}"
bash tools/comet/build-local.sh
python3 tools/powervr/fetch.py
python3 tools/release/runtime_inputs.py record
./gradlew "${gradle_task}" --console=plain -PndkVersion="${ndk_version}" ${gradle_rust_arg}
python3 tools/release/check_session_assets.py "app/build/outputs/apk/${build_variant}/app-${build_variant}.apk"
+15
View File
@@ -45,5 +45,20 @@ library list, before anything is published.
`GAMESCOPE_FOCUSABLE_WINDOWS`, so the client kept its loading screen over the running game
(Skyrim SE, A Plague Tale: Innocence, on the games' own Xwayland). MapNotify now refreshes the flag.
The system PowerVR driver uses the existing SDL/Wayland swapchain backend. Its additional patches are:
- `0120-nested-swapchain-capability-fallback.patch`: negotiate the surface's usages, mutable-format
support, image count, alpha and extent; use offscreen composition and GPU copies when required.
- `0121-powervr-single-pixel-rcas.patch`: use the existing single-pixel RCAS shader on PowerVR,
where the quad variant fails compilation.
- `0122-powervr-linear-dmabuf-import.patch`: retain the explicit linear layout when PowerVR
rejects the mutable-format query, and intersect imported-image and FD memory-type masks.
- `0123-powervr-rgba-copy-surface.patch`: require an advertised RGBA SDR copy surface matching
the shader's `rgba8` storage view. The tested workaround leaves other vendors, HDR and direct
composition unchanged; it does not restrict game-facing BGRA formats.
- `0124-sdl-preserve-explicit-refresh.patch` and `0125-sdl-wait-before-present.patch`: preserve
configured refresh across SDL events and finish composition before presenting without a
render-finished semaphore. The build runs the focused capability, format and refresh tests.
Sixteen more of Armada's patches are DRM/lease/HDR-on-KMS work for a native display, which this
app's Wayland-hosted gamescope never reaches, or need a newer gamescope than the runtime has.
+4 -1
View File
@@ -55,9 +55,12 @@ makepkg -A -s --noconfirm --skipchecksums --skippgpcheck # -A: the PKGBUILD lis
ls -l *.pkg.tar.*
"
cd "$WORK"
g++ -std=c++17 -Wall -Wextra -Werror -UNDEBUG -I pkg/arch/src/gamescope/src \
tools/gamescope/tests/nested-swapchain.cpp -o pkg/test-nested-swapchain
pkg/test-nested-swapchain
rm -rf out && mkdir -p out/usr/local/bin
PKG=$(ls pkg/arch/gamescope-*.pkg.tar.* | grep -v -- '-debug-' | head -1)
tar --use-compress-program=unzstd -xf "$PKG" -C out --strip-components=2 usr/bin/gamescope
tar -xf "$PKG" -C out --strip-components=2 usr/bin/gamescope
mv out/gamescope out/usr/local/bin/gamescope
chmod 755 out/usr/local/bin/gamescope
strip --strip-unneeded out/usr/local/bin/gamescope || true
@@ -0,0 +1,358 @@
diff --git a/src/nested_swapchain.hpp b/src/nested_swapchain.hpp
new file mode 100644
index 0000000..06fc987
--- /dev/null
+++ b/src/nested_swapchain.hpp
@@ -0,0 +1,53 @@
+#pragma once
+
+#include <algorithm>
+#include <vulkan/vulkan_core.h>
+
+namespace gamescope
+{
+struct NestedSwapchainConfig
+{
+ bool copy = false;
+ uint32_t imageCount = 0;
+ VkImageUsageFlags usage = 0;
+ VkCompositeAlphaFlagBitsKHR alpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
+ VkExtent2D extent = {};
+};
+
+inline bool ChooseNestedSwapchainConfig( const VkSurfaceCapabilitiesKHR &caps,
+ bool mutableFormat, uint32_t width, uint32_t height, NestedSwapchainConfig &config )
+{
+ constexpr VkImageUsageFlags direct = VK_IMAGE_USAGE_SAMPLED_BIT |
+ VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
+ config.copy = !mutableFormat || ( caps.supportedUsageFlags & direct ) != direct;
+ config.usage = config.copy ? VkImageUsageFlags{VK_IMAGE_USAGE_TRANSFER_DST_BIT} : direct;
+ if ( ( caps.supportedUsageFlags & config.usage ) != config.usage )
+ return false;
+
+ bool foundAlpha = false;
+ for ( auto alpha : { VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR, VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR,
+ VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR, VK_COMPOSITE_ALPHA_POST_MULTIPLIED_BIT_KHR } )
+ {
+ if ( caps.supportedCompositeAlpha & alpha )
+ {
+ config.alpha = alpha;
+ foundAlpha = true;
+ break;
+ }
+ }
+ if ( !foundAlpha || caps.maxImageExtent.width < caps.minImageExtent.width ||
+ caps.maxImageExtent.height < caps.minImageExtent.height )
+ return false;
+
+ config.imageCount = caps.minImageCount + ( caps.minImageCount != UINT32_MAX );
+ if ( caps.maxImageCount )
+ config.imageCount = std::min( config.imageCount, caps.maxImageCount );
+ if ( config.imageCount < caps.minImageCount )
+ return false;
+ config.extent = caps.currentExtent.width == UINT32_MAX
+ ? VkExtent2D{ std::clamp( width, caps.minImageExtent.width, caps.maxImageExtent.width ),
+ std::clamp( height, caps.minImageExtent.height, caps.maxImageExtent.height ) }
+ : caps.currentExtent;
+ return config.extent.width && config.extent.height;
+}
+}
diff --git a/src/rendervulkan.cpp b/src/rendervulkan.cpp
index ffad695..ffc8e28 100644
--- a/src/rendervulkan.cpp
+++ b/src/rendervulkan.cpp
@@ -12,6 +12,7 @@
#include <deque>
#include <dlfcn.h>
#include "vulkan_include.h"
+#include "nested_swapchain.hpp"
#include "Utils/Algorithm.h"
#if defined(__linux__)
@@ -450,6 +451,8 @@ bool CVulkanDevice::createDevice()
bool hasDrmProps = vulkan_has_drm_props();
bool supportsForeignQueue = false;
bool supportsHDRMetadata = false;
+ bool presentIdExtension = false;
+ bool presentWaitExtension = false;
for (const auto& ext : m_supportedExts) {
if ( strcmp(ext.extensionName, VK_EXT_IMAGE_DRM_FORMAT_MODIFIER_EXTENSION_NAME) == 0 )
m_bSupportsModifiers = true;
@@ -457,6 +460,13 @@ bool CVulkanDevice::createDevice()
if ( strcmp(ext.extensionName, VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME) == 0 )
supportsForeignQueue = true;
+ if ( strcmp(ext.extensionName, VK_KHR_SWAPCHAIN_MUTABLE_FORMAT_EXTENSION_NAME) == 0 )
+ m_bSupportsMutableSwapchain = true;
+ if ( strcmp(ext.extensionName, VK_KHR_PRESENT_ID_EXTENSION_NAME) == 0 )
+ presentIdExtension = true;
+ if ( strcmp(ext.extensionName, VK_KHR_PRESENT_WAIT_EXTENSION_NAME) == 0 )
+ presentWaitExtension = true;
+
if ( strcmp(ext.extensionName, VK_EXT_HDR_METADATA_EXTENSION_NAME) == 0 )
supportsHDRMetadata = true;
}
@@ -576,10 +586,24 @@ bool CVulkanDevice::createDevice()
if ( GetBackend()->UsesVulkanSwapchain() )
{
enabledExtensions.push_back( VK_KHR_SWAPCHAIN_EXTENSION_NAME );
- enabledExtensions.push_back( VK_KHR_SWAPCHAIN_MUTABLE_FORMAT_EXTENSION_NAME );
+ if ( m_bSupportsMutableSwapchain )
+ enabledExtensions.push_back( VK_KHR_SWAPCHAIN_MUTABLE_FORMAT_EXTENSION_NAME );
- enabledExtensions.push_back( VK_KHR_PRESENT_ID_EXTENSION_NAME );
- enabledExtensions.push_back( VK_KHR_PRESENT_WAIT_EXTENSION_NAME );
+ if ( presentIdExtension && presentWaitExtension )
+ {
+ VkPhysicalDevicePresentWaitFeaturesKHR wait = { .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PRESENT_WAIT_FEATURES_KHR };
+ VkPhysicalDevicePresentIdFeaturesKHR id = { .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PRESENT_ID_FEATURES_KHR, .pNext = &wait };
+ VkPhysicalDeviceFeatures2 features = { .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, .pNext = &id };
+ vk.GetPhysicalDeviceFeatures2( physDev(), &features );
+ m_bSupportsPresentWait = id.presentId && wait.presentWait;
+ }
+ if ( m_bSupportsPresentWait )
+ {
+ enabledExtensions.push_back( VK_KHR_PRESENT_ID_EXTENSION_NAME );
+ enabledExtensions.push_back( VK_KHR_PRESENT_WAIT_EXTENSION_NAME );
+ }
+ else
+ vk_log.infof( "Using FIFO acquire pacing; presentation timestamps unavailable" );
if ( supportsHDRMetadata )
enabledExtensions.push_back( VK_EXT_HDR_METADATA_EXTENSION_NAME );
@@ -654,7 +678,7 @@ bool CVulkanDevice::createDevice()
VkPhysicalDeviceFeatures2 features2 = {
.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2,
- .pNext = &presentIdFeatures,
+ .pNext = m_bSupportsPresentWait ? static_cast<void *>( &presentIdFeatures ) : static_cast<void *>( &features13 ),
.features = {
.shaderInt16 = m_bSupportsFp16,
},
@@ -2660,7 +2684,7 @@ bool CVulkanTexture::BInit( uint32_t width, uint32_t height, uint32_t depth, uin
return true;
}
-bool CVulkanTexture::BInitFromSwapchain( VkImage image, uint32_t width, uint32_t height, VkFormat format )
+bool CVulkanTexture::BInitFromSwapchain( VkImage image, uint32_t width, uint32_t height, VkFormat format, bool transferOnly )
{
m_drmFormat = VulkanFormatToDRM( format );
m_vkImage = image;
@@ -2672,6 +2696,12 @@ bool CVulkanTexture::BInitFromSwapchain( VkImage image, uint32_t width, uint32_t
m_contentWidth = width;
m_contentHeight = height;
m_bOutputImage = true;
+ if ( transferOnly )
+ {
+ // A copy destination needs no views (and the swapchain need not be mutable).
+ m_bInitialized = true;
+ return true;
+ }
VkImageViewCreateInfo createInfo = {
.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
@@ -3094,7 +3124,7 @@ void vulkan_present_to_window( void )
VkPresentInfoKHR presentInfo = {
.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
- .pNext = &presentIdInfo,
+ .pNext = g_device.supportsPresentWait() ? &presentIdInfo : nullptr,
.swapchainCount = 1,
.pSwapchains = &g_output.swapChain,
.pImageIndices = &g_output.nOutImage,
@@ -3102,14 +3132,22 @@ void vulkan_present_to_window( void )
if ( g_device.vk.QueuePresentKHR( g_device.queue(), &presentInfo ) == VK_SUCCESS )
{
- g_currentPresentWaitId = presentId;
- g_currentPresentWaitId.notify_all();
+ if ( g_device.supportsPresentWait() )
+ {
+ g_currentPresentWaitId = presentId;
+ g_currentPresentWaitId.notify_all();
+ }
}
else
vulkan_remake_swapchain();
while ( !acquire_next_image() )
vulkan_remake_swapchain();
+ if ( !g_device.supportsPresentWait() )
+ {
+ // Estimated scheduling anchor after FIFO buffer acquisition, not presentation feedback.
+ GetVBlankTimer().MarkVBlank( get_time_in_nanos(), true );
+ }
}
gamescope::Rc<CVulkanTexture> vulkan_create_1d_lut(uint32_t size)
@@ -3219,7 +3257,19 @@ extern bool g_bOutputHDREnabled;
bool vulkan_make_swapchain( VulkanOutput_t *pOutput )
{
- uint32_t imageCount = pOutput->surfaceCaps.minImageCount + 1;
+ // Re-query on resize as well as initial creation.
+ if ( g_device.vk.GetPhysicalDeviceSurfaceCapabilitiesKHR( g_device.physDev(), pOutput->surface, &pOutput->surfaceCaps ) != VK_SUCCESS )
+ return false;
+ gamescope::NestedSwapchainConfig config;
+ if ( !gamescope::ChooseNestedSwapchainConfig( pOutput->surfaceCaps, g_device.supportsMutableSwapchain(), g_nOutputWidth, g_nOutputHeight, config ) )
+ {
+ vk_log.errorf( "Surface supports neither direct composition nor transfer presentation" );
+ return false;
+ }
+ pOutput->copyToSwapchain = config.copy;
+ g_nOutputWidth = config.extent.width;
+ g_nOutputHeight = config.extent.height;
+ uint32_t imageCount = config.imageCount;
uint32_t formatCount = pOutput->surfaceFormats.size();
uint32_t surfaceFormat = formatCount;
VkColorSpaceKHR preferredColorSpace = g_bOutputHDREnabled ? VK_COLOR_SPACE_HDR10_ST2084_EXT : VK_COLOR_SPACE_SRGB_NONLINEAR_KHR;
@@ -3254,6 +3304,13 @@ bool vulkan_make_swapchain( VulkanOutput_t *pOutput )
}
}
+ if ( surfaceFormat == formatCount )
+ {
+ for ( surfaceFormat = 0; surfaceFormat < formatCount; ++surfaceFormat )
+ if ( pOutput->surfaceFormats[surfaceFormat].format == VK_FORMAT_R8G8B8A8_UNORM &&
+ pOutput->surfaceFormats[surfaceFormat].colorSpace == preferredColorSpace )
+ break;
+ }
if ( surfaceFormat == formatCount )
return false;
@@ -3276,8 +3333,8 @@ bool vulkan_make_swapchain( VulkanOutput_t *pOutput )
VkSwapchainCreateInfoKHR createInfo = {
.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR,
- .pNext = formats[0] != formats[1] ? &usageListInfo : nullptr,
- .flags = formats[0] != formats[1] ? VK_SWAPCHAIN_CREATE_MUTABLE_FORMAT_BIT_KHR : (VkSwapchainCreateFlagBitsKHR )0,
+ .pNext = !config.copy && formats[0] != formats[1] ? &usageListInfo : nullptr,
+ .flags = !config.copy && formats[0] != formats[1] ? VK_SWAPCHAIN_CREATE_MUTABLE_FORMAT_BIT_KHR : (VkSwapchainCreateFlagBitsKHR )0,
.surface = pOutput->surface,
.minImageCount = imageCount,
.imageFormat = eVkFormat,
@@ -3287,10 +3344,10 @@ bool vulkan_make_swapchain( VulkanOutput_t *pOutput )
.height = g_nOutputHeight,
},
.imageArrayLayers = 1,
- .imageUsage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT,
+ .imageUsage = config.usage,
.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE,
.preTransform = pOutput->surfaceCaps.currentTransform,
- .compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR,
+ .compositeAlpha = config.alpha,
.presentMode = VK_PRESENT_MODE_FIFO_KHR,
.clipped = VK_TRUE,
};
@@ -3304,12 +3361,30 @@ bool vulkan_make_swapchain( VulkanOutput_t *pOutput )
g_device.vk.GetSwapchainImagesKHR( g_device.device(), pOutput->swapChain, &imageCount, swapchainImages.data() );
pOutput->outputImages.resize(imageCount);
+ pOutput->presentationImages.clear();
+ if ( config.copy )
+ {
+ vk_log.infof( "Nested swapchain: composing offscreen and copying to FIFO presentation images" );
+ pOutput->presentationImages.resize(imageCount);
+ }
for ( uint32_t i = 0; i < pOutput->outputImages.size(); i++ )
{
pOutput->outputImages[i] = new CVulkanTexture();
- if ( !pOutput->outputImages[i]->BInitFromSwapchain(swapchainImages[i], g_nOutputWidth, g_nOutputHeight, eVkFormat))
+ if ( config.copy )
+ {
+ CVulkanTexture::createFlags flags;
+ flags.bStorage = true;
+ flags.bSampled = true;
+ flags.bTransferSrc = true;
+ if ( !pOutput->outputImages[i]->BInit( g_nOutputWidth, g_nOutputHeight, 1, pOutput->uOutputFormat, flags ) )
+ return false;
+ pOutput->presentationImages[i] = new CVulkanTexture();
+ if ( !pOutput->presentationImages[i]->BInitFromSwapchain( swapchainImages[i], g_nOutputWidth, g_nOutputHeight, eVkFormat, true ) )
+ return false;
+ }
+ else if ( !pOutput->outputImages[i]->BInitFromSwapchain(swapchainImages[i], g_nOutputWidth, g_nOutputHeight, eVkFormat))
return false;
}
@@ -3335,6 +3410,10 @@ bool vulkan_remake_swapchain( void )
g_device.vk.QueueWaitIdle( g_device.queue() );
pOutput->outputImages.clear();
+ pOutput->presentationImages.clear();
+ if ( pOutput->acquireFence )
+ g_device.vk.DestroyFence( g_device.device(), pOutput->acquireFence, nullptr );
+ pOutput->acquireFence = VK_NULL_HANDLE;
g_device.vk.DestroySwapchainKHR( g_device.device(), pOutput->swapChain, nullptr );
@@ -3670,7 +3749,7 @@ bool vulkan_init( VkInstance instance, VkSurfaceKHR surface )
if (!init_nis_data())
return false;
- if ( GetBackend()->UsesVulkanSwapchain() )
+ if ( GetBackend()->UsesVulkanSwapchain() && g_device.supportsPresentWait() )
{
std::thread present_wait_thread( present_wait_thread_func );
present_wait_thread.detach();
@@ -4579,6 +4658,9 @@ std::optional<uint64_t> vulkan_composite( struct FrameInfo_t *frameInfo, gamesco
CompositeTimingEnd( cmdBuffer.get(), *oTimingSlot, pszKey, pszKeyPre, pszKeyPost );
}
+ if ( !pOutputOverride && g_output.copyToSwapchain )
+ cmdBuffer->copyImage( compositeImage, g_output.presentationImages[g_output.nOutImage] );
+
uint64_t sequence = g_device.submit(std::move(cmdBuffer));
if ( oTimingSlot )
g_CompositeTiming.pending.back().ulSeqNo = sequence;
diff --git a/src/rendervulkan.hpp b/src/rendervulkan.hpp
index fa519db..674a3b4 100644
--- a/src/rendervulkan.hpp
+++ b/src/rendervulkan.hpp
@@ -162,7 +162,7 @@ public:
};
bool BInit( uint32_t width, uint32_t height, uint32_t depth, uint32_t drmFormat, createFlags flags, wlr_dmabuf_attributes *pDMA = nullptr, uint32_t contentWidth = 0, uint32_t contentHeight = 0, CVulkanTexture *pExistingImageToReuseMemory = nullptr, gamescope::OwningRc<gamescope::IBackendFb> pBackendFb = nullptr );
- bool BInitFromSwapchain( VkImage image, uint32_t width, uint32_t height, VkFormat format );
+ bool BInitFromSwapchain( VkImage image, uint32_t width, uint32_t height, VkFormat format, bool transferOnly = false );
uint32_t IncRef();
uint32_t DecRef();
@@ -586,7 +586,9 @@ struct VulkanOutput_t
std::shared_ptr<gamescope::BackendBlob> swapchainHDRMetadata;
VkSwapchainKHR swapChain;
- VkFence acquireFence;
+ VkFence acquireFence = VK_NULL_HANDLE;
+ bool copyToSwapchain = false;
+ std::vector<gamescope::OwningRc<CVulkanTexture>> presentationImages;
uint32_t nOutImage; // swapchain index in nested mode, or ping/pong between two RTs
std::vector<gamescope::OwningRc<CVulkanTexture>> outputImages;
@@ -756,6 +758,7 @@ static inline uint32_t div_roundup(uint32_t x, uint32_t y)
VK_FUNC(CreateDescriptorPool) \
VK_FUNC(CreateDescriptorSetLayout) \
VK_FUNC(CreateFence) \
+ VK_FUNC(DestroyFence) \
VK_FUNC(CreateGraphicsPipelines) \
VK_FUNC(CreateImage) \
VK_FUNC(CreateImageView) \
@@ -862,6 +865,8 @@ public:
inline VkPipelineLayout pipelineLayout() {return m_pipelineLayout;}
inline int drmRenderFd() {return m_drmRendererFd;}
inline bool supportsModifiers() {return m_bSupportsModifiers;}
+ inline bool supportsMutableSwapchain() {return m_bSupportsMutableSwapchain;}
+ inline bool supportsPresentWait() {return m_bSupportsPresentWait;}
inline bool hasDrmPrimaryDevId() {return m_bHasDrmPrimaryDevId;}
inline dev_t primaryDevId() {return m_drmPrimaryDevId;}
inline bool supportsFp16() {return m_bSupportsFp16;}
@@ -930,6 +935,8 @@ protected:
uint32_t m_uVendorID = 0;
bool m_bHasDrmPrimaryDevId = false;
bool m_bSupportsModifiers = false;
+ bool m_bSupportsMutableSwapchain = false;
+ bool m_bSupportsPresentWait = false;
bool m_bInitialized = false;
@@ -0,0 +1,15 @@
diff --git a/src/rendervulkan.cpp b/src/rendervulkan.cpp
--- a/src/rendervulkan.cpp
+++ b/src/rendervulkan.cpp
@@ -996,8 +996,9 @@
SHADER(BLUR, cs_composite_blur);
SHADER(BLUR_COND, cs_composite_blur_cond);
SHADER(BLUR_FIRST_PASS, cs_gaussian_blur_horizontal);
- // The one pixel layout is only measured on Adreno, every other vendor keeps the quad swizzle.
- if (m_uVendorID == 0x5143) /* Qualcomm */
+ // PowerVR rejects the quad-swizzled RCAS for 3+ layers with YCbCr mask 2.
+ // The existing one-pixel shader compiles those variants and covers the same 16x16 tile.
+ if (m_uVendorID == 0x5143 || m_uVendorID == 0x1010) /* Qualcomm or Imagination */
{
SHADER(RCAS, cs_composite_rcas_1px);
}
@@ -0,0 +1,156 @@
diff --git a/src/rendervulkan.cpp b/src/rendervulkan.cpp
--- a/src/rendervulkan.cpp
+++ b/src/rendervulkan.cpp
@@ -13,6 +13,7 @@
#include <dlfcn.h>
#include "vulkan_include.h"
#include "nested_swapchain.hpp"
+#include "dmabuf_import.hpp"
#include "Utils/Algorithm.h"
#if defined(__linux__)
@@ -2229,8 +2230,27 @@
return false;
}
- if ( res == VK_SUCCESS &&
- ( externalImageProperties.externalMemoryProperties.externalMemoryFeatures & VK_EXTERNAL_MEMORY_FEATURE_IMPORTABLE_BIT ) )
+ bool importable = res == VK_SUCCESS &&
+ ( externalImageProperties.externalMemoryProperties.externalMemoryFeatures & VK_EXTERNAL_MEMORY_FEATURE_IMPORTABLE_BIT );
+ if ( gamescope::RetryPowerVRLinearQuery( g_device.vendorID(), imageInfo.format,
+ pDMA->modifier, pDMA->n_planes, imageInfo.flags, res ) )
+ {
+ // PowerVR's mutable-format query rejects this linear import even though
+ // explicit-layout imports and UNORM/sRGB GPU sampling work. Query the base
+ // format without changing the image we actually create or its supplied stride.
+ VkImageCreateInfo baseFormat = imageInfo;
+ baseFormat.flags &= ~VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT;
+ baseFormat.pNext = nullptr;
+ res = getModifierProps( &baseFormat, pDMA->modifier, &externalImageProperties );
+ importable = res == VK_SUCCESS &&
+ ( externalImageProperties.externalMemoryProperties.externalMemoryFeatures & VK_EXTERNAL_MEMORY_FEATURE_IMPORTABLE_BIT );
+ }
+ if ( !importable && g_device.vendorID() == 0x1010 )
+ {
+ vk_log.errorf( "PowerVR DMA-BUF modifier is not importable; refusing a different tiling" );
+ return false;
+ }
+ if ( importable )
{
modifierInfo = {
.sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_EXPLICIT_CREATE_INFO_EXT,
@@ -2348,6 +2368,22 @@
m_format = imageInfo.format;
+ VkMemoryFdPropertiesKHR fdProperties = {
+ .sType = VK_STRUCTURE_TYPE_MEMORY_FD_PROPERTIES_KHR,
+ };
+ if ( pDMA )
+ {
+ if ( !g_device.vk.GetMemoryFdPropertiesKHR )
+ return false;
+ res = g_device.vk.GetMemoryFdPropertiesKHR( g_device.device(),
+ VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT, pDMA->fd[0], &fdProperties );
+ if ( res != VK_SUCCESS )
+ {
+ vk_errorf( res, "vkGetMemoryFdPropertiesKHR failed" );
+ return false;
+ }
+ }
+
res = g_device.vk.CreateImage(g_device.device(), &imageInfo, nullptr, &m_vkImage);
if (res != VK_SUCCESS) {
vk_errorf( res, "vkCreateImage failed" );
@@ -2357,10 +2393,22 @@
VkMemoryRequirements memRequirements;
g_device.vk.GetImageMemoryRequirements(g_device.device(), m_vkImage, &memRequirements);
+ uint32_t memoryType = pDMA
+ ? gamescope::DmabufMemoryType( g_device.memoryProperties(), memRequirements.memoryTypeBits,
+ fdProperties.memoryTypeBits, properties )
+ : uint32_t( g_device.findMemoryType( properties, memRequirements.memoryTypeBits ) );
+ if ( memoryType == UINT32_MAX )
+ {
+ vk_log.errorf( "No compatible image memory type (image=0x%x, fd=0x%x)",
+ memRequirements.memoryTypeBits, fdProperties.memoryTypeBits );
+ g_device.vk.DestroyImage( g_device.device(), m_vkImage, nullptr );
+ m_vkImage = VK_NULL_HANDLE;
+ return false;
+ }
VkMemoryAllocateInfo allocInfo = {
.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
.allocationSize = memRequirements.size,
- .memoryTypeIndex = uint32_t(g_device.findMemoryType(properties, memRequirements.memoryTypeBits)),
+ .memoryTypeIndex = memoryType,
};
m_size = allocInfo.allocationSize;
@@ -2453,6 +2501,13 @@
if ( res != VK_SUCCESS )
{
vk_errorf( res, "vkBindImageMemory failed" );
+ if ( pDMA )
+ vk_log.errorf( "DMA-BUF: %ux%u format=%u modifier=0x%" PRIx64
+ " planes=%d stride=%u offset=%u tiling=%u allocation=%" PRIu64
+ " memoryType=%u imageBits=0x%x fdBits=0x%x", width, height, imageInfo.format,
+ pDMA->modifier, pDMA->n_planes, pDMA->stride[0], pDMA->offset[0], imageInfo.tiling,
+ uint64_t( allocInfo.allocationSize ), allocInfo.memoryTypeIndex,
+ memRequirements.memoryTypeBits, fdProperties.memoryTypeBits );
return false;
}
diff --git a/src/rendervulkan.hpp b/src/rendervulkan.hpp
--- a/src/rendervulkan.hpp
+++ b/src/rendervulkan.hpp
@@ -791,6 +791,7 @@
VK_FUNC(GetImageMemoryRequirements) \
VK_FUNC(GetImageSubresourceLayout) \
VK_FUNC(GetMemoryFdKHR) \
+ VK_FUNC(GetMemoryFdPropertiesKHR) \
VK_FUNC(GetQueryPoolResults) \
VK_FUNC(GetSemaphoreCounterValue) \
VK_FUNC(GetSwapchainImagesKHR) \
@@ -865,6 +866,8 @@
inline VkPipelineLayout pipelineLayout() {return m_pipelineLayout;}
inline int drmRenderFd() {return m_drmRendererFd;}
inline bool supportsModifiers() {return m_bSupportsModifiers;}
+ inline uint32_t vendorID() const {return m_uVendorID;}
+ inline const VkPhysicalDeviceMemoryProperties &memoryProperties() const {return m_memoryProperties;}
inline bool supportsMutableSwapchain() {return m_bSupportsMutableSwapchain;}
inline bool supportsPresentWait() {return m_bSupportsPresentWait;}
inline bool hasDrmPrimaryDevId() {return m_bHasDrmPrimaryDevId;}
diff --git a/src/dmabuf_import.hpp b/src/dmabuf_import.hpp
new file mode 100644
--- /dev/null
+++ b/src/dmabuf_import.hpp
@@ -0,0 +1,29 @@
+#pragma once
+#include <vulkan/vulkan_core.h>
+
+namespace gamescope
+{
+inline bool RetryPowerVRLinearQuery( uint32_t vendor, VkFormat format, uint64_t modifier,
+ uint32_t planes, VkImageCreateFlags flags, VkResult result )
+{
+ return vendor == 0x1010 && modifier == 0 && planes == 1 &&
+ flags == VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT && result == VK_ERROR_FORMAT_NOT_SUPPORTED &&
+ ( format == VK_FORMAT_R8G8B8A8_UNORM || format == VK_FORMAT_B8G8R8A8_UNORM );
+}
+
+inline uint32_t DmabufMemoryType( const VkPhysicalDeviceMemoryProperties &memory,
+ uint32_t imageBits, uint32_t fdBits, VkMemoryPropertyFlags preferred )
+{
+ uint32_t fallback = UINT32_MAX;
+ const uint32_t compatible = imageBits & fdBits;
+ for ( uint32_t i = 0; i < memory.memoryTypeCount; ++i )
+ {
+ if ( !( compatible & ( 1u << i ) ) ) continue;
+ if ( fallback == UINT32_MAX ) fallback = i;
+ if ( ( memory.memoryTypes[i].propertyFlags & preferred ) == preferred ) return i;
+ }
+ // Device-local is a preference for an existing imported buffer. CPU mapping
+ // properties are requirements and must never be silently relaxed.
+ return preferred == VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT ? fallback : UINT32_MAX;
+}
+}
@@ -0,0 +1,61 @@
diff --git a/src/nested_surface_format.hpp b/src/nested_surface_format.hpp
new file mode 100644
--- /dev/null
+++ b/src/nested_surface_format.hpp
@@ -0,0 +1,31 @@
+#pragma once
+
+#include <vulkan/vulkan_core.h>
+
+namespace gamescope
+{
+// The SDR composition shader declares rgba8, which requires an R8G8B8A8_UNORM
+// storage view. Binding a BGRA view is a format mismatch; a same-format copy
+// cannot correct it. Keep the workaround scoped to the PowerVR SDR copy path
+// where the channel reversal was reproduced, not game-facing texture formats.
+// On success, formatCount means the existing selector should choose the format.
+// On failure, no matching RGBA SDR surface was advertised for this scoped path.
+inline bool ChooseNestedSDRCopySurfaceFormat( uint32_t vendorId, bool copy, bool hdr,
+ const VkSurfaceFormatKHR *formats, uint32_t formatCount, uint32_t &surfaceFormat )
+{
+ surfaceFormat = formatCount;
+ if ( vendorId != 0x1010 || !copy || hdr )
+ return true;
+
+ for ( uint32_t i = 0; i < formatCount; ++i )
+ {
+ if ( formats[i].format == VK_FORMAT_R8G8B8A8_UNORM &&
+ formats[i].colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR )
+ {
+ surfaceFormat = i;
+ return true;
+ }
+ }
+ return false;
+}
+}
diff --git a/src/rendervulkan.cpp b/src/rendervulkan.cpp
--- a/src/rendervulkan.cpp
+++ b/src/rendervulkan.cpp
@@ -14,6 +14,7 @@
#include "vulkan_include.h"
#include "nested_swapchain.hpp"
#include "dmabuf_import.hpp"
+#include "nested_surface_format.hpp"
#include "Utils/Algorithm.h"
#if defined(__linux__)
@@ -3330,6 +3331,13 @@
uint32_t surfaceFormat = formatCount;
VkColorSpaceKHR preferredColorSpace = g_bOutputHDREnabled ? VK_COLOR_SPACE_HDR10_ST2084_EXT : VK_COLOR_SPACE_SRGB_NONLINEAR_KHR;
+ if ( !gamescope::ChooseNestedSDRCopySurfaceFormat( g_device.vendorID(), config.copy,
+ g_bOutputHDREnabled, pOutput->surfaceFormats.data(), formatCount, surfaceFormat ) )
+ {
+ vk_log.errorf( "PowerVR copy composition requires an RGBA SDR surface" );
+ return false;
+ }
+
if ( surfaceFormat == formatCount )
{
for ( surfaceFormat = 0; surfaceFormat < formatCount; surfaceFormat++ )
@@ -0,0 +1,78 @@
diff --git a/src/sdl_refresh.hpp b/src/sdl_refresh.hpp
new file mode 100644
--- /dev/null
+++ b/src/sdl_refresh.hpp
@@ -0,0 +1,22 @@
+#pragma once
+
+#include <cstdint>
+
+namespace gamescope
+{
+struct SDLRefreshChoice
+{
+ int32_t refresh = 0;
+ bool configured = false;
+};
+
+// SDL reports the desktop mode again when its window is shown, moved or resized. Keep an
+// explicit -r as the rate exposed by nested Gamescope; discover the desktop rate only when the
+// caller did not configure one.
+inline constexpr SDLRefreshChoice ChooseSDLRefresh( int32_t configuredRefresh, int32_t desktopRefresh )
+{
+ return configuredRefresh > 0
+ ? SDLRefreshChoice{ configuredRefresh, true }
+ : SDLRefreshChoice{ desktopRefresh, false };
+}
+}
diff --git a/src/Backends/SDLBackend.cpp b/src/Backends/SDLBackend.cpp
--- a/src/Backends/SDLBackend.cpp
+++ b/src/Backends/SDLBackend.cpp
@@ -18,14 +18,20 @@
#include "steamcompmgr.hpp"
#include "Utils/Defer.h"
#include "refresh_rate.h"
+#include "log.hpp"
+#include "sdl_refresh.hpp"
#include "sdlscancodetable.hpp"
static int g_nOldNestedRefresh = 0;
static bool g_bWindowFocused = true;
+static int g_nLastLoggedConfiguredRefresh = -1;
+static int g_nLastLoggedDesktopRefresh = -1;
+static int g_nLastLoggedEffectiveRefresh = -1;
static int g_nOutputWidthPts = 0;
static int g_nOutputHeightPts = 0;
+static LogScope sdl_log( "sdl_backend" );
extern bool g_bForceHDR10OutputDebug;
extern bool steamMode;
@@ -846,9 +851,25 @@ namespace gamescope
SDL_DisplayMode mode = { SDL_PIXELFORMAT_UNKNOWN, 0, 0, 0, 0 };
display_index = SDL_GetWindowDisplayIndex( m_Connector.GetSDLWindow() );
if ( SDL_GetDesktopDisplayMode( display_index, &mode ) == 0 )
{
- g_nOutputRefresh = ConvertHztomHz( mode.refresh_rate );
+ const int nDesktopRefresh = ConvertHztomHz( mode.refresh_rate );
+ const SDLRefreshChoice refresh = ChooseSDLRefresh( g_nOldNestedRefresh, nDesktopRefresh );
+ g_nOutputRefresh = refresh.refresh;
+
+ if ( g_nLastLoggedConfiguredRefresh != g_nOldNestedRefresh ||
+ g_nLastLoggedDesktopRefresh != nDesktopRefresh ||
+ g_nLastLoggedEffectiveRefresh != refresh.refresh )
+ {
+ sdl_log.infof( "Refresh mode: configured=%.3fHz desktop=%.3fHz effective=%.3fHz source=%s",
+ ConvertmHzToHz( float( g_nOldNestedRefresh ) ),
+ ConvertmHzToHz( float( nDesktopRefresh ) ),
+ ConvertmHzToHz( float( refresh.refresh ) ),
+ refresh.configured ? "configured -r" : "SDL desktop" );
+ g_nLastLoggedConfiguredRefresh = g_nOldNestedRefresh;
+ g_nLastLoggedDesktopRefresh = nDesktopRefresh;
+ g_nLastLoggedEffectiveRefresh = refresh.refresh;
+ }
}
}
break;
@@ -0,0 +1,23 @@
diff --git a/src/Backends/SDLBackend.cpp b/src/Backends/SDLBackend.cpp
--- a/src/Backends/SDLBackend.cpp
+++ b/src/Backends/SDLBackend.cpp
@@ -351,14 +351,15 @@ namespace gamescope
std::optional oCompositeResult = vulkan_composite( (FrameInfo_t *)pFrameInfo, nullptr, false );
if ( !oCompositeResult )
return -EINVAL;
+ // Present has no render-finished semaphore, so wait before the native consumer can read
+ // the old contents. This serializes composition and present; a future pipelined path must
+ // signal a binary render-finished semaphore and make vkQueuePresentKHR wait on it.
+ vulkan_wait( *oCompositeResult, true );
+
vulkan_present_to_window();
// TODO: Hook up PresentationFeedback.
-
- // Wait for the composite result on our side *after* we
- // commit the buffer to the compositor to avoid a bubble.
- vulkan_wait( *oCompositeResult, true );
GetVBlankTimer().UpdateWasCompositing( true );
GetVBlankTimer().UpdateLastDrawTime( get_time_in_nanos() - g_SteamCompMgrVBlankTime.ulWakeupTime );
+3 -3
View File
@@ -1,3 +1,3 @@
GAMESCOPE_REPO=Droid-Deck/DroidDeck-Components
GAMESCOPE_TAG=gamescope-3.16.29-p9
GAMESCOPE_SHA256=7123a37bdbcd0d76d4bd1d7490e5d2017221e036395fdd48c1e92458594ca769
GAMESCOPE_REPO=wallentx/DroidDeck
GAMESCOPE_TAG=gamescope-3.16.29-p13-powervr
GAMESCOPE_SHA256=39e70fe9d8674da86442805d137f6bb078a83c5fac503d45b50ca66d4d3b7b04
+156
View File
@@ -0,0 +1,156 @@
#include "nested_swapchain.hpp"
#include "nested_surface_format.hpp"
#include "dmabuf_import.hpp"
#include "sdl_refresh.hpp"
#include <cassert>
#include <cstdio>
int main()
{
using gamescope::ChooseSDLRefresh;
constexpr int configured60 = 60'000;
constexpr int desktop120 = 120'000;
auto capped = ChooseSDLRefresh(configured60, desktop120);
assert(capped.configured && capped.refresh == configured60);
auto discovered = ChooseSDLRefresh(0, desktop120);
assert(!discovered.configured && discovered.refresh == desktop120);
auto configured120 = ChooseSDLRefresh(120'000, 60'000);
assert(configured120.configured && configured120.refresh == 120'000);
VkSurfaceCapabilitiesKHR caps = {};
caps.minImageCount = 2;
caps.maxImageCount = 3;
caps.currentExtent = {UINT32_MAX, UINT32_MAX};
caps.minImageExtent = {16, 16};
caps.maxImageExtent = {4096, 4096};
caps.supportedCompositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
caps.supportedUsageFlags = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT |
VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
gamescope::NestedSwapchainConfig config;
// Existing desktop drivers retain direct composition into mutable swapchains.
assert(gamescope::ChooseNestedSwapchainConfig(caps, true, 1280, 720, config));
assert(!config.copy && config.imageCount == 3 && config.extent.width == 1280);
// No mutable formats: compose offscreen and request only a copy destination.
assert(gamescope::ChooseNestedSwapchainConfig(caps, false, 1280, 720, config));
assert(config.copy && config.usage == VK_IMAGE_USAGE_TRANSFER_DST_BIT);
// The Android bridge exposes transfer usage and inherited alpha, but no storage.
caps.supportedUsageFlags &= ~VK_IMAGE_USAGE_STORAGE_BIT;
caps.supportedCompositeAlpha = VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR;
caps.maxImageCount = 2;
caps.currentExtent = {1602, 720};
assert(gamescope::ChooseNestedSwapchainConfig(caps, true, 1920, 1080, config));
assert(config.copy && config.alpha == VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR);
assert(config.imageCount == 2 && config.extent.width == 1602);
// Fail rather than submitting unsupported image usage or alpha.
caps.supportedUsageFlags &= ~VK_IMAGE_USAGE_TRANSFER_DST_BIT;
assert(!gamescope::ChooseNestedSwapchainConfig(caps, true, 1280, 720, config));
caps.supportedUsageFlags |= VK_IMAGE_USAGE_TRANSFER_DST_BIT;
caps.supportedCompositeAlpha = 0;
assert(!gamescope::ChooseNestedSwapchainConfig(caps, false, 1280, 720, config));
caps.supportedCompositeAlpha = VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR;
caps.currentExtent = {0, 0};
assert(!gamescope::ChooseNestedSwapchainConfig(caps, false, 1280, 720, config));
caps.currentExtent = {UINT32_MAX, UINT32_MAX};
assert(gamescope::ChooseNestedSwapchainConfig(caps, false, 1, 9000, config));
assert(config.extent.width == 16 && config.extent.height == 4096);
caps.maxImageCount = 1;
assert(!gamescope::ChooseNestedSwapchainConfig(caps, false, 1280, 720, config));
using gamescope::ChooseNestedSDRCopySurfaceFormat;
const VkSurfaceFormatKHR rgba = {
VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR};
const VkSurfaceFormatKHR bgra = {
VK_FORMAT_B8G8R8A8_UNORM, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR};
uint32_t surfaceFormat = UINT32_MAX;
// PowerVR SDR copy output needs the RGBA view matching the rgba8 shader.
const VkSurfaceFormatKHR bgraFirst[] = {bgra, rgba, rgba};
assert(ChooseNestedSDRCopySurfaceFormat(0x1010, true, false,
bgraFirst, 3, surfaceFormat));
assert(surfaceFormat == 1);
const VkSurfaceFormatKHR rgbaFirst[] = {rgba, bgra};
assert(ChooseNestedSDRCopySurfaceFormat(0x1010, true, false,
rgbaFirst, 2, surfaceFormat));
assert(surfaceFormat == 0);
assert(ChooseNestedSDRCopySurfaceFormat(0x1010, true, false,
&rgba, 1, surfaceFormat));
assert(surfaceFormat == 0);
// Reusing a successful index must not hide a missing compatible format.
assert(!ChooseNestedSDRCopySurfaceFormat(0x1010, true, false,
&bgra, 1, surfaceFormat));
assert(surfaceFormat == 1);
const VkSurfaceFormatKHR wrongColorSpace = {
VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT};
assert(!ChooseNestedSDRCopySurfaceFormat(0x1010, true, false,
&wrongColorSpace, 1, surfaceFormat));
assert(surfaceFormat == 1);
const VkSurfaceFormatKHR srgbFormat = {
VK_FORMAT_R8G8B8A8_SRGB, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR};
assert(!ChooseNestedSDRCopySurfaceFormat(0x1010, true, false,
&srgbFormat, 1, surfaceFormat));
assert(surfaceFormat == 1);
const VkSurfaceFormatKHR compatibleLast[] = {wrongColorSpace, srgbFormat, rgba};
assert(ChooseNestedSDRCopySurfaceFormat(0x1010, true, false,
compatibleLast, 3, surfaceFormat));
assert(surfaceFormat == 2);
assert(!ChooseNestedSDRCopySurfaceFormat(0x1010, true, false,
nullptr, 0, surfaceFormat));
assert(surfaceFormat == 0);
// The existing selector still owns HDR, direct output, and other vendors.
// Each call clears a stale index even when BGRA is the only advertised format.
surfaceFormat = 0;
assert(ChooseNestedSDRCopySurfaceFormat(0x1010, true, true,
&bgra, 1, surfaceFormat));
assert(surfaceFormat == 1);
surfaceFormat = 0;
assert(ChooseNestedSDRCopySurfaceFormat(0x1010, false, false,
&bgra, 1, surfaceFormat));
assert(surfaceFormat == 1);
surfaceFormat = 0;
assert(ChooseNestedSDRCopySurfaceFormat(0x5143, true, false,
&bgra, 1, surfaceFormat));
assert(surfaceFormat == 1);
// Retry only the device/format/layout/flag combination reproduced on PowerVR.
using gamescope::RetryPowerVRLinearQuery;
assert(RetryPowerVRLinearQuery(0x1010, VK_FORMAT_B8G8R8A8_UNORM, 0, 1,
VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT, VK_ERROR_FORMAT_NOT_SUPPORTED));
assert(RetryPowerVRLinearQuery(0x1010, VK_FORMAT_R8G8B8A8_UNORM, 0, 1,
VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT, VK_ERROR_FORMAT_NOT_SUPPORTED));
assert(!RetryPowerVRLinearQuery(0x5143, VK_FORMAT_B8G8R8A8_UNORM, 0, 1,
VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT, VK_ERROR_FORMAT_NOT_SUPPORTED));
assert(!RetryPowerVRLinearQuery(0x1010, VK_FORMAT_B8G8R8A8_UNORM, 1, 1,
VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT, VK_ERROR_FORMAT_NOT_SUPPORTED));
assert(!RetryPowerVRLinearQuery(0x1010, VK_FORMAT_B8G8R8A8_UNORM, 0, 2,
VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT, VK_ERROR_FORMAT_NOT_SUPPORTED));
assert(!RetryPowerVRLinearQuery(0x1010, VK_FORMAT_R16G16B16A16_SFLOAT, 0, 1,
VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT, VK_ERROR_FORMAT_NOT_SUPPORTED));
assert(!RetryPowerVRLinearQuery(0x1010, VK_FORMAT_B8G8R8A8_UNORM, 0, 1,
0, VK_ERROR_FORMAT_NOT_SUPPORTED));
assert(!RetryPowerVRLinearQuery(0x1010, VK_FORMAT_B8G8R8A8_UNORM, 0, 1,
VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT, VK_ERROR_DEVICE_LOST));
VkPhysicalDeviceMemoryProperties memory = {};
memory.memoryTypeCount = 3;
memory.memoryTypes[0].propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
memory.memoryTypes[1].propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT |
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
memory.memoryTypes[2].propertyFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;
using gamescope::DmabufMemoryType;
assert(DmabufMemoryType(memory, 7, 6, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) == 1);
assert(DmabufMemoryType(memory, 7, 4, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) == 2);
assert(DmabufMemoryType(memory, 1, 6, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) == UINT32_MAX);
assert(DmabufMemoryType(memory, 7, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) == UINT32_MAX);
assert(DmabufMemoryType(memory, 7, 4, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) == UINT32_MAX);
std::puts("Gamescope presentation and DMA-BUF import tests passed");
}
+51
View File
@@ -0,0 +1,51 @@
#!/usr/bin/env bash
# CI-only full libhybris build, using the upstream pinned cross-toolchain recipe.
set -euo pipefail
root=$(cd "$(dirname "$0")/../.." && pwd)
out=${1:?output directory required}
mkdir -p "$out"
out=$(cd "$out" && pwd)
. "$root/tools/hybris/source.env"
work=$(mktemp -d "${TMPDIR:-/tmp}/droiddeck-hybris.XXXXXX")
trap 'rm -rf "$work"' EXIT
fetch() {
git init -q "$3"
git -C "$3" fetch --depth=1 "$1" "$2"
git -C "$3" checkout -q --detach FETCH_HEAD
test "$(git -C "$3" rev-parse HEAD)" = "$2"
}
fetch https://github.com/taowen/libhybris.git "$HYBRIS_REVISION" "$work/libhybris"
fetch https://github.com/taowen/arlinux-rootfs.git "$PROTOCOL_REVISION" "$work/rootfs"
git -C "$work/libhybris" apply --check "$root/tools/hybris/powervr-hal-version.patch"
git -C "$work/libhybris" apply "$root/tools/hybris/powervr-hal-version.patch"
for patch in "$root"/tools/hybris/patches/*.patch; do
git -C "$work/libhybris" apply --check "$patch"
git -C "$work/libhybris" apply "$patch"
done
export ARLINUX_WSI_PROTOCOL_DIR="$work/rootfs/graphics-protocols"
export CONTAINER_ENGINE=podman
"$work/libhybris/tools/build-aarch64.sh" --out "$work/build"
mkdir -p "$work/package/lib" "$work/package/licenses"
cp -a "$work/build/install/usr/lib/hybris/." "$work/package/lib/"
find "$work/package/lib" -name '*.la' -delete
rm -rf "$work/package/lib/include" "$work/package/lib/pkgconfig" "$work/package/lib/bin"
# Resolve the wrapper's private dependencies without putting its EGL/Vulkan frontends
# on the session's LD_LIBRARY_PATH. The Linux runtime keeps owning its Mesa loader.
while IFS= read -r -d '' library; do
patchelf --set-rpath '$ORIGIN:$ORIGIN/../..' "$library"
done < <(find "$work/package/lib" -type f -name '*.so*' -print0)
for library in libhybris-vulkan-icd.so.0 libhybris-common.so.1 libVkLayer_hybris_compat.so libhybris/linker/q.so; do
test -s "$work/package/lib/$library"
done
cp "$work/libhybris"/LICENSE.* "$work/package/licenses/"
cp "$work/build/manifest.json" "$work/package/build-manifest.json"
printf '%s\n' "$HYBRIS_REVISION" > "$work/package/source-commit"
# Ship the exact patched source and protocol license with the runtime.
git -C "$work/libhybris" diff > "$work/package/licenses/powervr.patch"
git -C "$work/libhybris" archive HEAD | zstd -T0 -q -o "$work/package/licenses/libhybris-source.tar.zst"
cp "$ARLINUX_WSI_PROTOCOL_DIR/wayland-android.xml" "$work/package/licenses/"
(cd "$work/package" && find lib -type f -print0 | sort -z | xargs -0 sha256sum > SHA256SUMS)
tar --zstd -cf "$out/runtime.tzst" -C "$work/package" .
sha256sum "$out/runtime.tzst" | cut -d' ' -f1 > "$out/version.txt"
printf 'Built libhybris %s for Android HAL access from AArch64 Linux\n' "$HYBRIS_REVISION"
@@ -0,0 +1,505 @@
diff --git a/hybris/vulkan/compat/bc_commands.c b/hybris/vulkan/compat/bc_commands.c
index 90dac59..cf62d7d 100644
--- a/hybris/vulkan/compat/bc_commands.c
+++ b/hybris/vulkan/compat/bc_commands.c
@@ -2,6 +2,7 @@
#define VK_NO_PROTOTYPES
#include "bc_context.h"
#include <string.h>
+#include <stdio.h>
#define PROC(name) PFN_vk##name name = (PFN_vk##name)device->resolver(device->handle, "vk" #name)
static VkResult VKAPI_CALL allocate_commands(VkDevice handle, const VkCommandBufferAllocateInfo *info,
@@ -76,6 +77,7 @@ static VkResult VKAPI_CALL end_command(VkCommandBuffer handle)
PROC(EndCommandBuffer);
VkResult result = EndCommandBuffer(handle);
VkResult recorded = command->state.error;
+ if (result != VK_SUCCESS || recorded != VK_SUCCESS) fprintf(stderr, "HYBRIS_BC end: native=%d recorded=%d\n", result, recorded);
if (recorded == VK_SUCCESS) return result;
if (recorded == VK_ERROR_OUT_OF_HOST_MEMORY || recorded == VK_ERROR_OUT_OF_DEVICE_MEMORY ||
recorded == VK_ERROR_DEVICE_LOST) return recorded;
@@ -198,6 +200,37 @@ static void VKAPI_CALL push_constants(VkCommandBuffer handle, VkPipelineLayout l
CmdPushConstants(handle, layout, stages, offset, size, values);
if (device->format_mask) hybris_bc_save_push(&command->state, layout, stages, offset, size, values);
}
+static void bind_descriptors2(VkCommandBuffer handle, const VkBindDescriptorSetsInfo *info, const char *name)
+{
+ struct hybris_bc_device *device;
+ struct hybris_bc_command *command = hybris_bc_command_find(handle, &device);
+ if (!command) return;
+ PFN_vkCmdBindDescriptorSets2 call = (void *)device->resolver(device->handle, name);
+ call(handle, info);
+ if (device->format_mask && (info->stageFlags & VK_SHADER_STAGE_COMPUTE_BIT))
+ hybris_bc_save_descriptors(&command->state, VK_PIPELINE_BIND_POINT_COMPUTE,
+ info->layout, info->firstSet, info->descriptorSetCount, info->pDescriptorSets,
+ info->dynamicOffsetCount, info->pDynamicOffsets);
+}
+static void VKAPI_CALL bind_descriptors2_core(VkCommandBuffer handle, const VkBindDescriptorSetsInfo *info)
+{ bind_descriptors2(handle, info, "vkCmdBindDescriptorSets2"); }
+static void VKAPI_CALL bind_descriptors2_khr(VkCommandBuffer handle, const VkBindDescriptorSetsInfo *info)
+{ bind_descriptors2(handle, info, "vkCmdBindDescriptorSets2KHR"); }
+static void push_constants2(VkCommandBuffer handle, const VkPushConstantsInfo *info, const char *name)
+{
+ struct hybris_bc_device *device;
+ struct hybris_bc_command *command = hybris_bc_command_find(handle, &device);
+ if (!command) return;
+ PFN_vkCmdPushConstants2 call = (void *)device->resolver(device->handle, name);
+ call(handle, info);
+ if (device->format_mask)
+ hybris_bc_save_push(&command->state, info->layout, info->stageFlags,
+ info->offset, info->size, info->pValues);
+}
+static void VKAPI_CALL push_constants2_core(VkCommandBuffer handle, const VkPushConstantsInfo *info)
+{ push_constants2(handle, info, "vkCmdPushConstants2"); }
+static void VKAPI_CALL push_constants2_khr(VkCommandBuffer handle, const VkPushConstantsInfo *info)
+{ push_constants2(handle, info, "vkCmdPushConstants2KHR"); }
PFN_vkVoidFunction hybris_bc_commands_proc(const char *name)
{
static const struct { const char *name; PFN_vkVoidFunction function; } commands[] = {
@@ -207,7 +240,9 @@ PFN_vkVoidFunction hybris_bc_commands_proc(const char *name)
ENTRY(ResetCommandBuffer, reset_command), ENTRY(ResetCommandPool, reset_pool),
ENTRY(DestroyCommandPool, destroy_pool), ENTRY(CreatePipelineLayout, create_layout),
ENTRY(DestroyPipelineLayout, destroy_layout), ENTRY(CmdBindPipeline, bind_pipeline),
- ENTRY(CmdBindDescriptorSets, bind_descriptors), ENTRY(CmdPushConstants, push_constants)
+ ENTRY(CmdBindDescriptorSets, bind_descriptors), ENTRY(CmdPushConstants, push_constants),
+ ENTRY(CmdBindDescriptorSets2, bind_descriptors2_core), ENTRY(CmdBindDescriptorSets2KHR, bind_descriptors2_khr),
+ ENTRY(CmdPushConstants2, push_constants2_core), ENTRY(CmdPushConstants2KHR, push_constants2_khr)
#undef ENTRY
};
for (size_t i = 0; i < sizeof(commands) / sizeof(commands[0]); ++i)
diff --git a/hybris/vulkan/compat/bc_image.c b/hybris/vulkan/compat/bc_image.c
index fe25344..44faaf6 100644
--- a/hybris/vulkan/compat/bc_image.c
+++ b/hybris/vulkan/compat/bc_image.c
@@ -5,6 +5,19 @@
#define PROC(name) PFN_vk##name name = (PFN_vk##name)image->resolver(image->device, "vk" #name)
+int hybris_bc_srgb_family(VkFormat format)
+{
+ return (format >= VK_FORMAT_BC1_RGB_UNORM_BLOCK && format <= VK_FORMAT_BC3_SRGB_BLOCK) ||
+ format == VK_FORMAT_BC7_UNORM_BLOCK || format == VK_FORMAT_BC7_SRGB_BLOCK;
+}
+int hybris_bc_view_compatible(VkFormat image, VkFormat view)
+{
+ if (image == view) return 1;
+ return hybris_bc_srgb_family(image) &&
+ ((image - VK_FORMAT_BC1_RGB_UNORM_BLOCK) / 2 ==
+ (view - VK_FORMAT_BC1_RGB_UNORM_BLOCK) / 2) && hybris_bc_srgb_family(view);
+}
+
VkFormat hybris_bc_image_format(VkFormat format, unsigned rgb_mask)
{
switch (format) {
@@ -71,19 +84,28 @@ VkResult hybris_bc_image_describe(const VkImageCreateInfo *info, struct hybris_b
info->imageType != VK_IMAGE_TYPE_2D || info->tiling != VK_IMAGE_TILING_OPTIMAL ||
info->samples != VK_SAMPLE_COUNT_1_BIT ||
(info->initialLayout != VK_IMAGE_LAYOUT_UNDEFINED && info->initialLayout != VK_IMAGE_LAYOUT_PREINITIALIZED) ||
- (info->flags & ~VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT) ||
+ (info->flags & ~(VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT | VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT)) ||
+ ((info->flags & VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT) && !hybris_bc_srgb_family(info->format)) ||
!info->usage ||
(info->usage & ~(VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT)) ||
!info->extent.width || !info->extent.height || info->extent.depth != 1 ||
!info->mipLevels || info->mipLevels > 32 || !info->arrayLayers)
return VK_ERROR_FORMAT_NOT_SUPPORTED;
+ image->flags = info->flags;
+ image->view_mask = (info->flags & VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT) ? 3 : 1;
/* These chains only constrain views or request no external/swapchain
* binding. The decoded image has the same view restriction in our wrapper. */
for (const VkBaseInStructure *next = info->pNext; next; next = next->pNext) {
if (next->sType == VK_STRUCTURE_TYPE_IMAGE_FORMAT_LIST_CREATE_INFO) {
const VkImageFormatListCreateInfo *list = (const void *)next;
- for (uint32_t i = 0; i < list->viewFormatCount; ++i)
- if (list->pViewFormats[i] != info->format) return VK_ERROR_FORMAT_NOT_SUPPORTED;
+ if (list->viewFormatCount) image->view_mask = 0;
+ for (uint32_t i = 0; i < list->viewFormatCount; ++i) {
+ VkFormat view = list->pViewFormats[i];
+ if (!hybris_bc_view_compatible(info->format, view) ||
+ (view != info->format && !(info->flags & VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT)))
+ return VK_ERROR_FORMAT_NOT_SUPPORTED;
+ image->view_mask |= view == info->format ? 1u : 2u;
+ }
} else if (next->sType == VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO) {
if (((const VkExternalMemoryImageCreateInfo *)next)->handleTypes)
return VK_ERROR_FORMAT_NOT_SUPPORTED;
diff --git a/hybris/vulkan/compat/bc_image.h b/hybris/vulkan/compat/bc_image.h
index 9e62eb3..c950cc2 100644
--- a/hybris/vulkan/compat/bc_image.h
+++ b/hybris/vulkan/compat/bc_image.h
@@ -12,10 +12,14 @@ struct hybris_bc_image {
VkMemoryRequirements requirements;
VkBool32 requires_dedicated, prefers_dedicated;
VkFormat format, decoded_format;
+ VkImageCreateFlags flags;
+ unsigned view_mask;
VkExtent3D extent;
uint32_t mip_levels, layers, block_bytes;
VkDeviceSize mip_offset[32], block_size;
};
+int hybris_bc_srgb_family(VkFormat format);
+int hybris_bc_view_compatible(VkFormat image, VkFormat view);
VkFormat hybris_bc_image_format(VkFormat format, unsigned rgb_mask);
VkResult hybris_bc_image_describe(const VkImageCreateInfo *info, struct hybris_bc_image *image);
void hybris_bc_image_backing_info(const struct hybris_bc_image *image,
diff --git a/hybris/vulkan/compat/bc_policy.c b/hybris/vulkan/compat/bc_policy.c
index c5856f6..3124a25 100644
--- a/hybris/vulkan/compat/bc_policy.c
+++ b/hybris/vulkan/compat/bc_policy.c
@@ -5,6 +5,7 @@
#include "bc_context.h"
#include "../layer/layer.h"
#include <stdlib.h>
+#include <stddef.h>
#include <string.h>
#include <sys/auxv.h>
@@ -16,12 +17,18 @@ static void initialize_policy(void)
const char *value = getenv("HYBRIS_BC_TEXTURES");
if (!value || !strcmp(value, "missing") || !strcmp(value, "1")) policy = 1;
else if (value && !strcmp(value, "force")) policy = 2;
+ else if (value && !strcmp(value, "dxvk")) policy = 3;
}
int hybris_bc_enabled(void)
{
pthread_once(&policy_once, initialize_policy);
return policy != 0;
}
+static int dxvk_profile(void)
+{
+ pthread_once(&policy_once, initialize_policy);
+ return policy == 3;
+}
#define PHYSICAL_PROC(name) PFN_vk##name name = (PFN_vk##name)context.resolver(context.instance, "vk" #name)
/* Preserve three-channel border replacement when the native image format
* supports the full sampled/transfer domain. Selection is per physical device;
@@ -52,7 +59,7 @@ unsigned hybris_bc_physical_mask(VkPhysicalDevice physical)
VkPhysicalDeviceProperties properties;
GetPhysicalDeviceProperties(physical, &properties);
/* Core 1.4 includes descriptor-state commands that are not intercepted yet. */
- if (properties.apiVersion < VK_API_VERSION_1_1 || properties.apiVersion >= VK_MAKE_API_VERSION(0, 1, 4, 0) ||
+ if (properties.apiVersion < VK_API_VERSION_1_1 || (!dxvk_profile() && properties.apiVersion >= VK_MAKE_API_VERSION(0, 1, 4, 0)) ||
properties.limits.maxStorageBufferRange < 256 ||
properties.limits.minStorageBufferOffsetAlignment >= properties.limits.maxStorageBufferRange) return 0;
uint32_t count = 0;
@@ -72,6 +79,9 @@ unsigned hybris_bc_physical_mask(VkPhysicalDevice physical)
unsigned mask = 0;
for (unsigned i = 0; i < 16; ++i) {
VkFormat format = VK_FORMAT_BC1_RGB_UNORM_BLOCK + i;
+ /* D3D uses BC1 RGBA. Keep RGB-only BC1 unadvertised until absent-alpha
+ * border semantics are implemented on devices without RGB8 images. */
+ if (dxvk_profile() && i < 2) continue;
VkFormat backing = hybris_bc_image_format(format, physical_rgb_mask(physical));
if (backing == VK_FORMAT_UNDEFINED) continue;
VkFormatProperties native, decoded;
@@ -84,6 +94,33 @@ unsigned hybris_bc_physical_mask(VkPhysicalDevice physical)
}
return mask;
}
+/* The emulation profile implements Vulkan 1.3 plus maintenance6. Do not expose
+ * 1.4 core host-copy/push-descriptor operations that bypass our state tracking. */
+static void cap_properties(VkPhysicalDevice physical, VkPhysicalDeviceProperties *out)
+{
+ if (dxvk_profile() && hybris_bc_physical_mask(physical) && out->apiVersion > VK_API_VERSION_1_3)
+ out->apiVersion = VK_API_VERSION_1_3;
+}
+static void VKAPI_CALL properties(VkPhysicalDevice physical, VkPhysicalDeviceProperties *out)
+{
+ struct hybris_layer_physical context;
+ if (!hybris_layer_lookup_physical(physical, &context)) return;
+ PHYSICAL_PROC(GetPhysicalDeviceProperties);
+ GetPhysicalDeviceProperties(physical, out);
+ cap_properties(physical, out);
+}
+static void properties2(VkPhysicalDevice physical, VkPhysicalDeviceProperties2 *out, const char *name)
+{
+ struct hybris_layer_physical context;
+ if (!hybris_layer_lookup_physical(physical, &context)) return;
+ PFN_vkGetPhysicalDeviceProperties2 query = (void *)context.resolver(context.instance, name);
+ query(physical, out);
+ cap_properties(physical, &out->properties);
+}
+static void VKAPI_CALL properties2_core(VkPhysicalDevice physical, VkPhysicalDeviceProperties2 *out)
+{ properties2(physical, out, "vkGetPhysicalDeviceProperties2"); }
+static void VKAPI_CALL properties2_khr(VkPhysicalDevice physical, VkPhysicalDeviceProperties2 *out)
+{ properties2(physical, out, "vkGetPhysicalDeviceProperties2KHR"); }
static int emulates(VkPhysicalDevice physical, VkFormat format)
{
return format >= VK_FORMAT_BC1_RGB_UNORM_BLOCK && format <= VK_FORMAT_BC7_SRGB_BLOCK &&
@@ -109,10 +146,13 @@ int hybris_bc_extension_allowed(const char *name)
"VK_KHR_maintenance6", "VK_KHR_maintenance8", "VK_EXT_host_image_copy",
"VK_QCOM_rotated_copy_commands", "VK_EXT_device_generated_commands",
"VK_NV_device_generated_commands", "VK_NV_device_generated_commands_compute",
- "VK_NV_dedicated_allocation", "VK_NV_copy_memory_indirect"
+ "VK_NV_dedicated_allocation", "VK_NV_copy_memory_indirect", "VK_NV_per_stage_descriptor_set"
};
for (size_t i = 0; i < sizeof(unsupported) / sizeof(unsupported[0]); ++i)
- if (!strcmp(name, unsupported[i])) return 0;
+ if (!strcmp(name, unsupported[i])) {
+ if (dxvk_profile() && !strcmp(name, "VK_KHR_maintenance6")) continue;
+ return 0;
+ }
return 1;
}
/* Extension feature queries must agree with the filtered extension list. Each
@@ -121,8 +161,12 @@ static unsigned unsupported_feature_count(VkStructureType type)
{
switch (type) {
case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_BUFFER_FEATURES_EXT: return 4;
+ case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_4_FEATURES:
+ return dxvk_profile() ? (offsetof(VkPhysicalDeviceVulkan14Features, pushDescriptor) -
+ offsetof(VkPhysicalDeviceVulkan14Features, globalPriorityQuery)) / sizeof(VkBool32) + 1 : 0;
+ case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_6_FEATURES_KHR: return dxvk_profile() ? 0 : 1;
+ case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PER_STAGE_DESCRIPTOR_SET_FEATURES_NV: return 2;
case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_OBJECT_FEATURES_EXT:
- case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_6_FEATURES_KHR:
case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_HOST_IMAGE_COPY_FEATURES_EXT:
case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COPY_MEMORY_INDIRECT_FEATURES_NV:
case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DEVICE_GENERATED_COMMANDS_FEATURES_NV: return 1;
@@ -252,11 +296,12 @@ static void VKAPI_CALL sparse_properties2_core(VkPhysicalDevice physical, const
static void VKAPI_CALL sparse_properties2_khr(VkPhysicalDevice physical, const VkPhysicalDeviceSparseImageFormatInfo2 *info,
uint32_t *count, VkSparseImageFormatProperties2 *out)
{ sparse_properties2(physical, info, count, out, "vkGetPhysicalDeviceSparseImageFormatProperties2KHR"); }
-static int image_supported(VkImageType type, VkImageTiling tiling, VkImageUsageFlags usage, VkImageCreateFlags flags)
+static int image_supported(VkFormat format, VkImageType type, VkImageTiling tiling, VkImageUsageFlags usage, VkImageCreateFlags flags)
{
return type == VK_IMAGE_TYPE_2D && tiling == VK_IMAGE_TILING_OPTIMAL && usage &&
!(usage & ~(VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT)) &&
- !(flags & ~VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT);
+ !(flags & ~(VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT | VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT)) &&
+ (!(flags & VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT) || hybris_bc_srgb_family(format));
}
static VkResult VKAPI_CALL image_properties(VkPhysicalDevice physical, VkFormat format, VkImageType type,
VkImageTiling tiling, VkImageUsageFlags usage, VkImageCreateFlags flags, VkImageFormatProperties *out)
@@ -265,7 +310,7 @@ static VkResult VKAPI_CALL image_properties(VkPhysicalDevice physical, VkFormat
if (!hybris_layer_lookup_physical(physical, &context)) return VK_ERROR_INITIALIZATION_FAILED;
PHYSICAL_PROC(GetPhysicalDeviceImageFormatProperties);
if (emulates(physical, format)) {
- if (!image_supported(type, tiling, usage, flags)) { *out = (VkImageFormatProperties){0}; return VK_ERROR_FORMAT_NOT_SUPPORTED; }
+ if (!image_supported(format, type, tiling, usage, flags)) { *out = (VkImageFormatProperties){0}; return VK_ERROR_FORMAT_NOT_SUPPORTED; }
VkResult result = GetPhysicalDeviceImageFormatProperties(physical, hybris_bc_image_format(format, physical_rgb_mask(physical)), type,
tiling, usage | VK_IMAGE_USAGE_TRANSFER_DST_BIT, flags, out);
if (result == VK_SUCCESS) out->sampleCounts &= VK_SAMPLE_COUNT_1_BIT;
@@ -282,14 +327,16 @@ static VkResult image_properties2(VkPhysicalDevice physical, const VkPhysicalDev
(PFN_vkGetPhysicalDeviceImageFormatProperties2)context.resolver(context.instance, name);
if (!emulates(physical, info->format)) return query(physical, info, out);
out->imageFormatProperties = (VkImageFormatProperties){0};
- if (!image_supported(info->type, info->tiling, info->usage, info->flags)) return VK_ERROR_FORMAT_NOT_SUPPORTED;
+ if (!image_supported(info->format, info->type, info->tiling, info->usage, info->flags)) return VK_ERROR_FORMAT_NOT_SUPPORTED;
for (const VkBaseInStructure *node = info->pNext; node; node = node->pNext) {
if (node->sType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO) {
if (((const VkPhysicalDeviceExternalImageFormatInfo *)node)->handleType) return VK_ERROR_FORMAT_NOT_SUPPORTED;
} else if (node->sType == VK_STRUCTURE_TYPE_IMAGE_FORMAT_LIST_CREATE_INFO) {
const VkImageFormatListCreateInfo *list = (const void *)node;
for (uint32_t i = 0; i < list->viewFormatCount; ++i)
- if (list->pViewFormats[i] != info->format) return VK_ERROR_FORMAT_NOT_SUPPORTED;
+ if (!hybris_bc_view_compatible(info->format, list->pViewFormats[i]) ||
+ (list->pViewFormats[i] != info->format && !(info->flags & VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT)))
+ return VK_ERROR_FORMAT_NOT_SUPPORTED;
} else if (node->sType != VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_VIEW_IMAGE_FORMAT_INFO_EXT) {
return VK_ERROR_FORMAT_NOT_SUPPORTED;
}
@@ -322,6 +369,9 @@ PFN_vkVoidFunction hybris_bc_policy_proc(const char *name)
if (!hybris_bc_enabled()) return NULL;
static const struct { const char *name; PFN_vkVoidFunction function; } commands[] = {
#define ENTRY(name, function) {"vk" #name, (PFN_vkVoidFunction)function}
+ ENTRY(GetPhysicalDeviceProperties, properties),
+ ENTRY(GetPhysicalDeviceProperties2, properties2_core),
+ ENTRY(GetPhysicalDeviceProperties2KHR, properties2_khr),
ENTRY(GetPhysicalDeviceQueueFamilyProperties, queue_properties),
ENTRY(GetPhysicalDeviceQueueFamilyProperties2, queue_properties2_core),
ENTRY(GetPhysicalDeviceQueueFamilyProperties2KHR, queue_properties2_khr),
diff --git a/hybris/vulkan/compat/bc_resources.c b/hybris/vulkan/compat/bc_resources.c
index 526c3f1..74cc0c9 100644
--- a/hybris/vulkan/compat/bc_resources.c
+++ b/hybris/vulkan/compat/bc_resources.c
@@ -210,8 +210,10 @@ static VkResult VKAPI_CALL create_view(VkDevice handle, const VkImageViewCreateI
struct hybris_bc_resource *resource = hybris_bc_resource_find(device, info->image);
VkImageViewCreateInfo translated = *info;
if (resource && resource->emulated.image) {
- if (info->format != resource->format) return VK_ERROR_FORMAT_NOT_SUPPORTED;
- translated.format = resource->emulated.decoded_format;
+ unsigned bit = info->format == resource->format ? 1u : 2u;
+ if (!hybris_bc_view_compatible(resource->format, info->format) ||
+ !(resource->emulated.view_mask & bit)) return VK_ERROR_FORMAT_NOT_SUPPORTED;
+ translated.format = hybris_bc_image_format(info->format, device->rgb_mask);
}
PROC(CreateImageView);
return CreateImageView(handle, &translated, allocator, view);
diff --git a/hybris/vulkan/compat/bc_transfer.c b/hybris/vulkan/compat/bc_transfer.c
index 6edb652..799fb62 100644
--- a/hybris/vulkan/compat/bc_transfer.c
+++ b/hybris/vulkan/compat/bc_transfer.c
@@ -2,6 +2,7 @@
#define VK_NO_PROTOTYPES
#include "bc_transfer.h"
#include <stdlib.h>
+#include <stdio.h>
#include <string.h>
#define PROC(name) PFN_vk##name name = (PFN_vk##name)t->decoder->resolver(t->decoder->device, "vk" #name)
@@ -59,16 +60,29 @@ static VkResult scratch(struct hybris_bc_transfer *t)
if (type == t->memory->memoryTypeCount) type = i;
if (t->memory->memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) { type = i; break; }
}
- if (type == t->memory->memoryTypeCount) { result = VK_ERROR_OUT_OF_DEVICE_MEMORY; goto fail; }
+ if (type == t->memory->memoryTypeCount) {
+ fprintf(stderr, "HYBRIS_BC scratch: no memory type (bits=0x%x count=%u size=%llu)\n",
+ requirements.memoryRequirements.memoryTypeBits, t->memory->memoryTypeCount,
+ (unsigned long long)requirements.memoryRequirements.size);
+ result = VK_ERROR_OUT_OF_DEVICE_MEMORY; goto fail;
+ }
VkMemoryDedicatedAllocateInfo owner = {
.sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO, .buffer = buffer};
VkMemoryAllocateInfo allocation = {.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
.pNext = dedicated.requiresDedicatedAllocation || dedicated.prefersDedicatedAllocation ? &owner : NULL,
.allocationSize = requirements.memoryRequirements.size, .memoryTypeIndex = type};
result = AllocateMemory(device, &allocation, NULL, &memory);
- if (result != VK_SUCCESS) goto fail;
+ if (result != VK_SUCCESS) {
+ fprintf(stderr, "HYBRIS_BC scratch allocation: result=%d size=%llu type=%u bits=0x%x\n",
+ result, (unsigned long long)allocation.allocationSize, type, requirements.memoryRequirements.memoryTypeBits);
+ goto fail;
+ }
result = BindBufferMemory(device, buffer, memory, 0);
- if (result != VK_SUCCESS) goto fail;
+ if (result != VK_SUCCESS) {
+ fprintf(stderr, "HYBRIS_BC scratch bind: result=%d size=%llu type=%u\n",
+ result, (unsigned long long)allocation.allocationSize, type);
+ goto fail;
+ }
t->scratch = buffer;
t->scratch_memory = memory;
t->scratch_size = size;
@@ -193,7 +207,7 @@ VkResult hybris_bc_decode_image(struct hybris_bc_transfer *t,
buffer_barrier(t, command, image->blocks, VK_PIPELINE_STAGE_TRANSFER_BIT,
VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_SHADER_READ_BIT);
VkResult result = decode(t, command, image, layout, region);
- if (result != VK_SUCCESS) { state->error = result; return result; }
+ if (result != VK_SUCCESS) { fprintf(stderr, "HYBRIS_BC transfer failed: %d\n", result); state->error = result; return result; }
buffer_barrier(t, command, image->blocks, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
VK_ACCESS_SHADER_READ_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT);
diff --git a/hybris/vulkan/compat/shader_policy.c b/hybris/vulkan/compat/shader_policy.c
index a1dcf6d..21a4cc7 100644
--- a/hybris/vulkan/compat/shader_policy.c
+++ b/hybris/vulkan/compat/shader_policy.c
@@ -92,7 +92,8 @@ static void properties2(VkPhysicalDevice physical, VkPhysicalDeviceProperties2 *
{
struct hybris_layer_physical context;
if (!hybris_layer_lookup_physical(physical, &context)) return;
- PFN_vkGetPhysicalDeviceProperties2 query = (PFN_vkGetPhysicalDeviceProperties2)context.resolver(context.instance, name);
+ PFN_vkGetPhysicalDeviceProperties2 query = (void *)hybris_bc_policy_proc(name);
+ if (!query) query = (void *)context.resolver(context.instance, name);
query(physical, out);
VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT *legacy = NULL;
for (VkBaseOutStructure *node = out->pNext; node; node = node->pNext)
diff --git a/tests/baseline/probe_bc_images.c b/tests/baseline/probe_bc_images.c
index 85ba6e6..55e069c 100644
--- a/tests/baseline/probe_bc_images.c
+++ b/tests/baseline/probe_bc_images.c
@@ -95,9 +95,10 @@ int bc_images_probe(int validate, int route)
}
free(queues);
if (family == UINT32_MAX) return 3;
+ unsigned first_format = getenv("BC_D3D_FORMATS") ? 2 : 0;
VkBool32 linear_filter[BC_IMAGE_FORMAT_COUNT] = {0};
unsigned unsupported_formats = 0;
- for (unsigned f = 0; f < BC_IMAGE_FORMAT_COUNT; ++f) {
+ for (unsigned f = first_format; f < BC_IMAGE_FORMAT_COUNT; ++f) {
VkFormatProperties format;
p_vkGetPhysicalDeviceFormatProperties(physical, bc_formats[f], &format);
VkFormatProperties2 format2 = {.sType = VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_2};
@@ -164,19 +165,28 @@ int bc_images_probe(int validate, int route)
p_vkGetPhysicalDeviceFeatures2(physical, &queried);
maintenance4 = maintenance.maintenance4;
}
- synchronization.pNext = maintenance4 ? &maintenance : NULL;
- const char *device_extensions[4];
+ int maintenance6 = getenv("BC_MAINTENANCE6") != NULL;
+ VkPhysicalDeviceMaintenance6FeaturesKHR maintenance_six = {.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_6_FEATURES_KHR};
+ if (maintenance6) {
+ VkPhysicalDeviceFeatures2 q = {.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, .pNext = &maintenance_six};
+ p_vkGetPhysicalDeviceFeatures2(physical, &q);
+ if (!maintenance_six.maintenance6) { puts("MISSING maintenance6"); return 3; }
+ }
+ maintenance.pNext = maintenance6 ? &maintenance_six : NULL;
+ synchronization.pNext = maintenance4 ? (void *)&maintenance : maintenance6 ? (void *)&maintenance_six : NULL;
+ const char *device_extensions[5];
uint32_t device_extension_count = 0;
if (copies2) device_extensions[device_extension_count++] = VK_KHR_COPY_COMMANDS_2_EXTENSION_NAME;
if (sync2) device_extensions[device_extension_count++] = VK_KHR_SYNCHRONIZATION_2_EXTENSION_NAME;
if (maintenance4) device_extensions[device_extension_count++] = VK_KHR_MAINTENANCE_4_EXTENSION_NAME;
if (format_list) device_extensions[device_extension_count++] = VK_KHR_IMAGE_FORMAT_LIST_EXTENSION_NAME;
+ if (maintenance6) device_extensions[device_extension_count++] = VK_KHR_MAINTENANCE_6_EXTENSION_NAME;
float priority = 1;
VkDeviceQueueCreateInfo qc = {.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO,
.queueFamilyIndex = family, .queueCount = 1, .pQueuePriorities = &priority};
VkDeviceCreateInfo dc = {.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO,
.queueCreateInfoCount = 1, .pQueueCreateInfos = &qc,
- .pNext = sync2 ? (void *)&synchronization : maintenance4 ? (void *)&maintenance : NULL,
+ .pNext = sync2 ? (void *)&synchronization : maintenance4 ? (void *)&maintenance : maintenance6 ? (void *)&maintenance_six : NULL,
.enabledExtensionCount = device_extension_count, .ppEnabledExtensionNames = device_extensions};
VkDebugUtilsMessengerEXT messenger = VK_NULL_HANDLE;
PFN_vkDestroyDebugUtilsMessengerEXT destroy_messenger = NULL;
@@ -307,8 +317,12 @@ int bc_images_probe(int validate, int route)
VkFenceCreateInfo fence_info = {.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO};
VkFence fence;
CHECK(p_vkCreateFence(device, &fence_info, NULL, &fence));
+ PFN_vkCmdBindDescriptorSets2KHR bind2 = (PFN_vkCmdBindDescriptorSets2KHR)p_vkGetDeviceProcAddr(device, "vkCmdBindDescriptorSets2KHR");
+ PFN_vkCmdPushConstants2KHR push2 = (PFN_vkCmdPushConstants2KHR)p_vkGetDeviceProcAddr(device, "vkCmdPushConstants2KHR");
+ if (maintenance6 && (!bind2 || !push2)) return 2;
+ printf("BC_EXTENDED maintenance6=%d mutable=%d\n", maintenance6, getenv("BC_MUTABLE") != NULL);
unsigned failures = 0, readbacks = 0, copies2_cases = 0, sync2_cases = 0;
- for (unsigned f = 0; f < BC_IMAGE_FORMAT_COUNT; ++f) {
+ for (unsigned f = first_format; f < BC_IMAGE_FORMAT_COUNT; ++f) {
for (unsigned shape_index = 0; shape_index < 2; ++shape_index) {
uint32_t base_width = shape_index ? 32 : 9, base_height = shape_index ? 32 : 7;
for (uint32_t mip = 0; mip < 4; ++mip) {
@@ -337,6 +351,13 @@ int bc_images_probe(int validate, int route)
(i != 2 ? VK_IMAGE_USAGE_SAMPLED_BIT : 0), .sharingMode = VK_SHARING_MODE_EXCLUSIVE};
VkImageFormatListCreateInfo formats = {.sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_LIST_CREATE_INFO,
.viewFormatCount = 1, .pViewFormats = &image_info.format};
+ VkFormat paired[2] = {bc_formats[f], bc_formats[f ^ 1]};
+ if (getenv("BC_MUTABLE") && (f < 8 || (f >= 12 && f < 14)) && i < 2) {
+ image_info.flags |= VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT;
+ image_info.format = paired[1];
+ formats.viewFormatCount = 2;
+ formats.pViewFormats = paired;
+ }
if (format_list) image_info.pNext = &formats;
VkMemoryRequirements2 described = {.sType = VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2};
if (maintenance4) {
@@ -414,9 +435,19 @@ int bc_images_probe(int validate, int route)
VkCommandBufferBeginInfo begin = {.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO};
CHECK(p_vkBeginCommandBuffer(command, &begin));
p_vkCmdBindPipeline(command, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline);
- p_vkCmdBindDescriptorSets(command, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_layout, 0, 1, &descriptors, 1, &dynamic_offset);
+ if (maintenance6) {
+ VkBindDescriptorSetsInfoKHR bind = {.sType = VK_STRUCTURE_TYPE_BIND_DESCRIPTOR_SETS_INFO_KHR,
+ .stageFlags = VK_SHADER_STAGE_COMPUTE_BIT, .layout = pipeline_layout,
+ .descriptorSetCount = 1, .pDescriptorSets = &descriptors,
+ .dynamicOffsetCount = 1, .pDynamicOffsets = &dynamic_offset};
+ bind2(command, &bind);
+ } else p_vkCmdBindDescriptorSets(command, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_layout, 0, 1, &descriptors, 1, &dynamic_offset);
uint32_t shape[] = {width, height, LAYERS, f >= 14 ? 3 : f >= 8 && f < 12 ? 1 + (f & 1) : 0, linear_filter[f] != 0};
- p_vkCmdPushConstants(command, pipeline_layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(shape), shape);
+ if (maintenance6) {
+ VkPushConstantsInfoKHR push = {.sType = VK_STRUCTURE_TYPE_PUSH_CONSTANTS_INFO_KHR,
+ .layout = pipeline_layout, .stageFlags = VK_SHADER_STAGE_COMPUTE_BIT, .size = sizeof(shape), .pValues = shape};
+ push2(command, &push);
+ } else p_vkCmdPushConstants(command, pipeline_layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(shape), shape);
VkMemoryBarrier before = {.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER,
.srcAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT,
.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT};
@@ -614,7 +645,7 @@ int bc_images_probe(int validate, int route)
p_vkDestroyDevice(device, NULL);
if (destroy_messenger) destroy_messenger(instance, messenger, NULL);
p_vkDestroyInstance(instance, NULL); dlclose(h);
- printf("BC_IMAGES_SUMMARY formats=16 shapes=2 readbacks=%u copy2_cases=%u sync2_cases=%u maintenance4=%u format_list=%u failures=%u validation_errors=%u route=%d\n",
- readbacks, copies2_cases, sync2_cases, maintenance4, format_list, failures, validation.errors, route);
- return failures || validation.errors || readbacks != BC_IMAGE_FORMAT_COUNT * 2 * 4 * 3 ? 2 : 0;
+ printf("BC_IMAGES_SUMMARY formats=%u shapes=2 readbacks=%u copy2_cases=%u sync2_cases=%u maintenance4=%u format_list=%u failures=%u validation_errors=%u route=%d\n",
+ (unsigned)BC_IMAGE_FORMAT_COUNT - first_format, readbacks, copies2_cases, sync2_cases, maintenance4, format_list, failures, validation.errors, route);
+ return failures || validation.errors || readbacks != (BC_IMAGE_FORMAT_COUNT - first_format) * 2 * 4 * 3 ? 2 : 0;
}
+12
View File
@@ -0,0 +1,12 @@
--- a/hybris/vulkan/icd/icd.c
+++ b/hybris/vulkan/icd/icd.c
@@ -71,7 +71,8 @@
int result = module->methods->open(module, HWVULKAN_DEVICE_0,
(hw_device_t **)&candidate);
if (result || !candidate || candidate->common.tag != HARDWARE_DEVICE_TAG ||
- candidate->common.version != HWVULKAN_DEVICE_API_VERSION_0_1 ||
+ (candidate->common.version != HWVULKAN_DEVICE_API_VERSION_0_1 &&
+ candidate->common.version != HARDWARE_DEVICE_API_VERSION(0, 1)) ||
!candidate->CreateInstance || !candidate->GetInstanceProcAddr ||
!candidate->EnumerateInstanceExtensionProperties) {
fprintf(stderr, "hybris ICD: incompatible Vulkan HAL device (open=%d)\n", result);
+89
View File
@@ -0,0 +1,89 @@
#!/usr/bin/python3
"""Select a staged DXVK payload for one DroidDeck Proton game launch.
Place this script beside dxvk/x32/ and dxvk/x64/, then select its absolute
path with DROIDDECK_PROTON_WRAPPER in the game's environment settings.
Run `python3 run-proton.py --check /path/to/proton` to check the payload and
Proton source layout without starting Proton or changing a game prefix.
This wrapper does not install the graphics runtime, select Vulkan layers,
change synchronization settings, or provide game-specific workarounds.
"""
import argparse
import os
from pathlib import Path
import sys
DLL_NAMES = ("d3d8.dll", "d3d9.dll", "d3d10core.dll", "d3d11.dll", "dxgi.dll")
PREFIX_MARKER = "droiddeck-dxvk-profile-v1"
def prepare(proton, dxvk):
"""Validate all inputs and compile an in-memory copy of the Proton script."""
for architecture in ("x32", "x64"):
for name in DLL_NAMES:
dll = dxvk / architecture / name
if not dll.is_file():
raise ValueError(f"missing DXVK file: {dll}")
with dll.open("rb") as stream:
if not stream.read(1):
raise ValueError(f"empty DXVK file: {dll}")
source = proton.read_text(encoding="utf-8")
for is32, architecture in (("False", "x64"), ("True", "x32")):
needle = f'g_proton.arch_pe_dir("wine/dxvk", {is32}) + f + ".dll"'
if source.count(needle) != 1:
raise ValueError(f"unsupported Proton layout: expected one {architecture} DXVK copy expression")
directory = str(dxvk / architecture) + "/"
source = source.replace(needle, repr(directory) + ' + f + ".dll"', 1)
needle = " # check whether any prefix config has changed"
if source.count(needle) != 1:
raise ValueError("unsupported Proton layout: expected one prefix configuration marker")
# The supported Proton copies DXVK DLLs on every launch. This marker records
# profile activation; it does not need changing whenever the payload changes.
marker = repr("\n" + PREFIX_MARKER)
source = source.replace(needle, f" prefix_info += {marker}\n" + needle, 1)
return compile(source, str(proton), "exec")
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--check", action="store_true", help="validate inputs without running Proton")
parser.add_argument("proton", help="selected Proton Python script")
parser.add_argument("proton_args", nargs=argparse.REMAINDER)
args = parser.parse_args()
if not args.check and (len(args.proton_args) < 2 or args.proton_args[0] != "waitforexitandrun"):
parser.error("expected: PROTON waitforexitandrun GAME [ARGUMENTS...]")
proton = Path(args.proton)
# A sibling payload directory by name (dxvk-2.6.2 for Xclipse); never a path.
name = os.environ.get("DROIDDECK_HYBRIS_DXVK") or "dxvk"
if not name.startswith("dxvk") or "/" in name or name.startswith("."):
print(f"DroidDeck DXVK profile: invalid payload name {name!r}", file=sys.stderr)
return 1
dxvk = Path(__file__).resolve().parent / name
try:
code = prepare(proton, dxvk)
except (OSError, ValueError, SyntaxError) as error:
print(f"DroidDeck DXVK profile: {error}", file=sys.stderr)
return 1
if args.check:
print(f"DroidDeck DXVK profile: payload present and Proton layout supported ({dxvk})")
return 0
print(f"DROIDDECK_GRAPHICS profile={PREFIX_MARKER} dxvk={dxvk}", flush=True)
# Preserve the selected Proton path, including symlinks, and its arguments.
# Proton uses argv[0] and sibling Python imports to locate its own depot.
sys.argv = [args.proton, *args.proton_args]
sys.path.insert(0, str(proton.absolute().parent))
exec(code, {"__name__": "__main__", "__file__": args.proton,
"__package__": None, "__spec__": None})
return 0
if __name__ == "__main__":
raise SystemExit(main())
+2
View File
@@ -0,0 +1,2 @@
HYBRIS_REVISION=bc8cb3586b79d208fd21b925fa0209b3e432e008
PROTOCOL_REVISION=c6ae3c22a804da3cda017f4c8eaa6c6a3da55457
+5
View File
@@ -31,5 +31,10 @@ SSBS=$(syms "$D/libssbs.so")
for sym in sigaction signal bsd_signal sysv_signal; do
grep -qx "$sym" <<<"$SSBS" || { echo "::error::libssbs.so does not export $sym"; exit 1; }
done
XCLIPSE=$(syms "$D/usr/local/lib/droiddeck-xclipse/libVkLayer_droiddeck_xclipse.so")
for sym in vkNegotiateLoaderLayerInterfaceVersion vkGetInstanceProcAddr vkGetDeviceProcAddr; do
grep -qx "$sym" <<<"$XCLIPSE" || { echo "::error::the Xclipse layer does not export $sym"; exit 1; }
done
test -f "$D/usr/local/lib/droiddeck-xclipse/VkLayer_droiddeck_xclipse.json"
test -f "$D/usr/local/bin/droiddeck-session"
test -f "$D/usr/local/bin/droiddeck-proton-extra"
+10 -2
View File
@@ -12,7 +12,12 @@ if [ -n "${BL_DEBUG_DIR:-}" ]; then
fi
width=${BL_WIDTH:-1280}
height=${BL_HEIGHT:-720}
args=(--backend wayland --expose-wayland -f -W "$width" -H "$height" -w "$width" -h "$height")
backend=${BL_GAMESCOPE_BACKEND:-wayland}
case "$backend" in
wayland|sdl) ;;
*) echo "== unsupported gamescope backend: $backend" >&2; exit 64 ;;
esac
args=(--backend "$backend" --expose-wayland -f -W "$width" -H "$height" -w "$width" -h "$height")
if [ "${BL_FPS:-0}" -gt 0 ]; then
args+=(-r "$BL_FPS")
elif [ "${BL_REFRESH:-0}" -gt 0 ]; then
@@ -24,6 +29,9 @@ echo "== droiddeck-gpu $(date -u +%H:%M:%S): $* (gamescope ${width}x${height} on
# through gamescope's own Xwayland, as in a Steam session.
export WAYLAND_DISPLAY=wayland-0
export GDK_BACKEND=x11 QT_QPA_PLATFORM=xcb SDL_VIDEODRIVER=x11
# PowerVR's SDL backend presents to the app's Wayland compositor. Only the
# program inside gamescope uses its Xwayland display.
[ "$backend" = sdl ] && export SDL_VIDEODRIVER=wayland
# GL on the GPU again (zink on Turnip, as the session sets it): the desktop itself draws GL in software.
# Qt Quick back on its GPU renderer and KWin's software compositing not passed on, too.
unset LIBGL_ALWAYS_SOFTWARE QT_QUICK_BACKEND KWIN_COMPOSE
@@ -31,7 +39,7 @@ export MESA_LOADER_DRIVER_OVERRIDE=zink GALLIUM_DRIVER=zink LIBGL_KOPPER_DRI2=tr
[ -n "${DROIDDECK_GLTHREAD:-}" ] && export mesa_glthread=$DROIDDECK_GLTHREAD
# AppImages cannot mount under proot; the menu entries already say so, a hand-typed one may not.
export APPIMAGE_EXTRACT_AND_RUN=1
gamescope "${args[@]}" -- /usr/local/bin/droiddeck-gpu-window "$@"
gamescope "${args[@]}" -- env SDL_VIDEODRIVER=x11 /usr/local/bin/droiddeck-gpu-window "$@"
rc=$?
echo "== droiddeck-gpu $(date -u +%H:%M:%S): exited $rc"
exit $rc
@@ -305,6 +305,60 @@ def mark_install_scripts(command, env):
print("droiddeck-game-env: install scripts not marked (%s)" % error, file=sys.stderr)
class SystemGraphicsError(ValueError):
pass
def system_graphics_launch(command, env):
"""Use the APK's PowerVR compatibility files only for actual Proton game launches."""
runtime = env.get("DROIDDECK_POWERVR_RUNTIME")
if not runtime or not game_id(env) or len(command) < 3 or command[1] != "waitforexitandrun":
return command, env
directory = Path(runtime)
if not directory.is_absolute():
raise SystemGraphicsError("system Vulkan runtime path is not absolute")
# run-proton.py picks the same payload by name; Xclipse needs a DXVK within 128 bytes of push data.
payload = env.get("DROIDDECK_HYBRIS_DXVK") or "dxvk"
if not payload.startswith("dxvk") or "/" in payload:
raise SystemGraphicsError("invalid DXVK payload name: %s" % payload)
required = (
"run-proton.py", "wsi/libVkLayer_window_system_integration.so",
"wsi/VkLayer_window_system_integration.json", "lib/libVkLayer_hybris_compat.so",
*("%s/%s/%s.dll" % (payload, arch, name) for arch in ("x32", "x64")
for name in ("d3d8", "d3d9", "d3d10core", "d3d11", "dxgi")),
)
try:
for name in required:
path = directory / name
if not path.is_file() or not path.stat().st_size:
raise SystemGraphicsError("missing system Vulkan component: %s" % name)
wrapper = directory / "run-proton.py"
if not os.access(wrapper, os.X_OK):
raise SystemGraphicsError("system Vulkan Proton wrapper is not executable")
except OSError as error:
raise SystemGraphicsError("system Vulkan component is unreadable: %s" % error) from error
result = dict(env)
layers = "VK_LAYER_window_system_integration:" + env.get("DROIDDECK_HYBRIS_LAYERS", "VK_LAYER_HYBRIS_compat")
result.update({
"HYBRIS_BC_TEXTURES": "dxvk",
"VK_LAYER_PATH": ":".join(filter(None, (str(directory / "wsi"), str(directory / "lib"),
env.get("DROIDDECK_HYBRIS_LAYER_PATH")))),
"VK_INSTANCE_LAYERS": layers,
"ENABLE_GAMESCOPE_WSI": "0",
"VK_LOADER_LAYERS_DISABLE": "*gamescope*",
"DISABLE_VK_LAYER_VALVE_steam_fossilize_1": "1",
})
for name in ("DISABLE_WSI_LAYER", "PROTON_USE_WINED3D", "ENABLE_VK_LAYER_VALVE_steam_fossilize_1"):
result.pop(name, None)
return [str(wrapper), *command], result
def exec_proton(command, env):
# Synchronization selection has already picked the actual Proton executable.
command, env = system_graphics_launch(command, env)
os.execvpe(command[0], command, env)
def main():
command = sys.argv[1:]
if not command:
@@ -344,13 +398,17 @@ def main():
launch, launch_env = select_sync(command, env, sync)
if launch[0] != command[0]:
try:
os.execvpe(launch[0], launch, launch_env)
exec_proton(launch, launch_env)
except OSError as error:
print("droiddeck-game-env: %s could not start (%s); stock launch" % (launch[0], error), file=sys.stderr)
launch, launch_env = command, without_pack(launch_env, env)
record_stock(sync, launch, launch_env)
os.execvpe(launch[0], launch, launch_env)
exec_proton(launch, launch_env)
if __name__ == "__main__":
sys.exit(main())
try:
sys.exit(main())
except SystemGraphicsError as error:
print("droiddeck-game-env: PowerVR graphics runtime unavailable (%s)" % error, file=sys.stderr)
sys.exit(1)
@@ -273,7 +273,13 @@ if [ -z "${BL_INSIDE:-}" ]; then
echo "== gamescope: games at ${nested}x${height} stretched to the ${width}x${height} output"
fi
fi
args=(--backend wayland --expose-wayland -f -W "$width" -H "$height" -w "$nested" -h "$height")
backend=${BL_GAMESCOPE_BACKEND:-wayland}
case "$backend" in
wayland) ;;
sdl) export SDL_VIDEODRIVER=wayland ;;
*) echo "== unsupported gamescope backend: $backend"; exit 64 ;;
esac
args=(--backend "$backend" --expose-wayland -f -W "$width" -H "$height" -w "$nested" -h "$height")
[ "$nested" != "$width" ] && args+=(-S stretch) && export BL_STRETCHED=1
# -r is what gamescope advertises as the refresh rate, and what a game reads as the display's.
# Left unset it defaults to 60, so a 120 Hz panel offers only 60 Hz in game settings. The FPS
@@ -823,6 +829,21 @@ BUSCONF
export STEAM_RUNTIME=1
export LD_LIBRARY_PATH=$steam_root/steamrtarm64:$steam_root/steamrtarm64/panorama${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}
export SDL_VIDEO_X11_DGAMOUSE=0
bl_steam_path=$PATH
bl_steam_angle=vulkan
bl_steam_presentation=()
if [ "${BL_STEAM_GL_PRESENT:-}" = 1 ]; then
bl_steam_path="/usr/local/libexec/droiddeck-steam:$PATH"
# Keep the system driver for GPU rendering, but present Steam through ordinary DRI3.
# The inner compositor has neither android_wlegl nor the bridge's TAWC-DRI extension.
export DISABLE_GAMESCOPE_WSI=1 LIBGL_KOPPER_DISABLE=true
bl_steam_angle=gl
# CEF renders correctly internally, but its accelerated shared-texture output is
# corrupted on this path. Software web compositing avoids that handoff; Gamescope
# and the selected game driver still use the system GPU.
bl_steam_presentation=(-cef-disable-gpu-compositing)
echo "== steam: system PowerVR uses OpenGL/DRI3 through Zink with software CEF compositing"
fi
# Decky is optional and session scoped: the app's marker opts in, and this supervisor is
# reaped with the client session. Native ARM64 runs directly. A legacy x86_64 asset is used
# only when its recorded architecture says so and droiddeck-fex has FEX and its runtime ready.
@@ -880,7 +901,9 @@ BUSCONF
# desktop's launchers ask for. KDE owns its windows when BL_DESKTOP=1.
_bl_ui=(-gamepadui)
[ "${BL_STEAM_UI:-}" = desktop ] && _bl_ui=()
_bl_cef=(-cef-force-gpu -cef-use-gl=angle -cef-use-angle=vulkan)
# bl_steam_angle / bl_steam_presentation default to the Adreno values (vulkan, none); only
# the system-PowerVR path (BL_STEAM_GL_PRESENT=1) changes them.
_bl_cef=(-cef-force-gpu "${bl_steam_presentation[@]}" -cef-use-gl=angle "-cef-use-angle=$bl_steam_angle")
if [ "${BL_DESKTOP:-}" = 1 ] && [ "${BL_STEAM_UI:-}" = desktop ]; then
# KDE uses QPainter/shm on Android. CEF's Vulkan buffers cannot be
# presented there; its software path keeps the library and dialogs on KDE.
@@ -1052,6 +1075,9 @@ BUSCONF
/usr/local/bin/droiddeck-steam-desktop-ui &
desktop_ui_pid=$!
fi
# Keep Valve's optional webhelper CPU pinning from aborting browser startup.
PATH="$bl_steam_path" \
BL_STEAM_WEBHELPER="$steam_root/steamrtarm64/steamwebhelper" \
"$steam_root/steamrtarm64/steam" "${_bl_ui[@]}" "${_bl_cdp[@]}" "${_bl_lang[@]}" -clientbeta "$steam_channel" \
-no-cef-sandbox -cef-ozone-platform=x11 "${_bl_cef[@]}" "$@"
rc=$?
@@ -0,0 +1,17 @@
#!/bin/bash
# Staged as taskset in a PATH directory used only by the Steam client.
# Valve's ARM64 helper uses `taskset 0x7c /path/to/steamwebhelper ...` and exits
# before starting the browser when Android denies sched_setaffinity.
set -u
if [ "$#" -ge 2 ] && [[ "$1" =~ ^(0[xX])?[0-9a-fA-F]+$ ]] &&
[ -n "${BL_STEAM_WEBHELPER:-}" ] && [ "$2" -ef "$BL_STEAM_WEBHELPER" ]; then
mask=$1
shift
# Pin this wrapper before exec; never retry a helper that has already run.
if ! /usr/bin/taskset -p "$mask" "$$" >/dev/null 2>&1; then
echo "droiddeck: Steam helper CPU pinning unavailable; using the allowed CPUs" >&2
fi
exec -- "$@"
fi
# Queries, existing-process changes, and other programs retain taskset's behavior.
exec /usr/bin/taskset "$@"
@@ -198,6 +198,9 @@ bl_components() {
local -A cm_sums=()
while IFS=$'\\t' read -r scope t want comp rel sum src; do
[ -n "$scope" ] || continue
# The selected system PowerVR runtime supplies DXVK at launch. Keep saved selections
# for a later manual-driver session without rewriting this Proton's bundled files now.
[ "$comp" = dxvk ] && [ -n "${DROIDDECK_POWERVR_RUNTIME:-}" ] && continue
cm_rows+=("$comp"$'\\t'"$rel"$'\\t'"$sum"$'\\t'"$src")
[ "$src" != "-" ] && [ -f "$base/$rel" ] && cm_files+=("$base/$rel")
done <<< "$cm_selected"
+108 -27
View File
@@ -1,9 +1,10 @@
/*
* GEM handle emulation for the KGSL device presented as a DRM render node.
* GEM handle emulation for KGSL and explicitly enabled system-PowerVR sessions.
*
* Compositors and Mesa validate or convert dma-bufs with PRIME ioctls on the render node; KGSL
* has no GEM. Handles only serve as tokens to these callers, so a table of duplicated dma-buf
* descriptors stands in for the kernel's, and every other device is left to libdrm.
* descriptors stands in for the kernel's. PowerVR's Android driver can import DMA-BUFs
* through Vulkan but rejects PRIME-to-GEM conversion; its real handles still go to libdrm.
*/
#define _GNU_SOURCE
#include <dlfcn.h>
@@ -11,6 +12,7 @@
#include <fcntl.h>
#include <pthread.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
@@ -18,6 +20,10 @@
#include <unistd.h>
#define MAX_HANDLES 4096
#ifndef F_DUPFD_QUERY
#define F_DUPFD_QUERY 1027
#endif
#define PVR_HANDLE_BIT UINT32_C(0x80000000)
/* DRM_IOCTL_GEM_CLOSE from drm.h: _IOW('d', 0x09, struct drm_gem_close { u32 handle, pad; }). */
struct gem_close {
@@ -30,11 +36,14 @@ struct handle_entry {
uint32_t handle;
int dma_fd;
int drm_fd;
int owned_drm_fd; /* PowerVR: pin the open file description, not its reusable fd number. */
int powervr;
};
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
static struct handle_entry handle_entries[MAX_HANDLES];
static uint32_t next_handle = 1;
static uint32_t next_pvr_handle = PVR_HANDLE_BIT;
static dev_t kgsl_dev;
static int kgsl_state; /* 0 unknown, 1 known, -1 absent */
@@ -43,12 +52,40 @@ static int is_kgsl(int fd) {
pthread_mutex_lock(&lock);
if (kgsl_state == 0) {
kgsl_state = stat("/dev/kgsl-3d0", &st) == 0 ? 1 : -1;
kgsl_dev = st.st_rdev;
if (kgsl_state > 0) kgsl_dev = st.st_rdev;
}
pthread_mutex_unlock(&lock);
return kgsl_state > 0 && fstat(fd, &st) == 0 && S_ISCHR(st.st_mode) && st.st_rdev == kgsl_dev;
}
/* Keep the opt-in separate from GPU detection: manual ICDs must retain native DRM behavior. */
struct bl_drm_version {
int major, minor, patch;
size_t name_len;
char *name;
size_t date_len;
char *date;
size_t desc_len;
char *desc;
};
#define BL_DRM_VERSION _IOWR('d', 0x00, struct bl_drm_version)
static int is_powervr(int fd) {
const char *enabled = getenv("BL_POWERVR_DRM_HANDLES");
if (!enabled || strcmp(enabled, "1")) return 0;
const char *path = getenv("BL_POWERVR_RENDER_NODE");
if (!path || !*path) return 0;
struct stat node, candidate;
if (stat(path, &node) || fstat(fd, &candidate) ||
!S_ISCHR(candidate.st_mode) || !S_ISCHR(node.st_mode) ||
candidate.st_rdev != node.st_rdev) return 0;
char name[16] = {0};
struct bl_drm_version version = {.name_len = sizeof(name) - 1, .name = name};
/* Bypass the preload's ioctl dispatcher to avoid recursively entering this hook. */
return syscall(SYS_ioctl, fd, BL_DRM_VERSION, &version) == 0 &&
version.name_len == 3 && !memcmp(name, "pvr", 3);
}
static void *real(const char *name) {
void *fn = dlsym(RTLD_NEXT, name);
if (!fn) {
@@ -71,10 +108,20 @@ static int same_file_description(int a, int b) {
#endif
}
static int same_owned_description(int owned, int fd) {
int saved_errno = errno;
int result = fcntl(owned, F_DUPFD_QUERY, fd);
errno = saved_errno;
if (result >= 0) return result == 1;
return same_file_description(owned, fd);
}
static int find_handle_locked(int fd, uint32_t handle) {
for (int i = 0; i < MAX_HANDLES; i++) {
if (handle_entries[i].handle == handle &&
same_file_description(handle_entries[i].drm_fd, fd)) {
(handle_entries[i].powervr
? same_owned_description(handle_entries[i].owned_drm_fd, fd)
: same_file_description(handle_entries[i].drm_fd, fd))) {
return i;
}
}
@@ -86,11 +133,15 @@ static int find_handle_locked(int fd, uint32_t handle) {
* rapidly recreated swapchains immediately reused those numbers. Keep storage slots reusable but
* make the public token monotonic so a stale handle can fail instead of aliasing a newer buffer.
*/
static uint32_t alloc_handle_locked(void) {
static uint32_t alloc_handle_locked(int powervr) {
for (int tries = 0; tries <= MAX_HANDLES; tries++) {
uint32_t candidate = next_handle++;
if (next_handle == 0) {
next_handle = 1;
uint32_t candidate;
if (powervr) {
candidate = next_pvr_handle++;
if (!(next_pvr_handle & PVR_HANDLE_BIT)) next_pvr_handle = PVR_HANDLE_BIT;
} else {
candidate = next_handle++;
if (next_handle == PVR_HANDLE_BIT) next_handle = 1;
}
if (candidate == 0) {
continue;
@@ -110,25 +161,45 @@ static uint32_t alloc_handle_locked(void) {
}
int drmPrimeFDToHandle(int fd, int prime_fd, uint32_t *handle) {
if (!is_kgsl(fd)) {
int kgsl = is_kgsl(fd);
int powervr = !kgsl && is_powervr(fd);
if (!kgsl) {
int (*fn)(int, int, uint32_t *) = (int (*)(int, int, uint32_t *)) real("drmPrimeFDToHandle");
return fn ? fn(fd, prime_fd, handle) : -ENOSYS;
if (!fn) return -ENOSYS;
int result = fn(fd, prime_fd, handle);
if (!result || !powervr || errno != EINVAL) return result;
}
if (!handle) { errno = EINVAL; return -EINVAL; }
int owner = -1;
if (powervr) {
owner = fcntl(fd, F_DUPFD_CLOEXEC, 0);
if (owner < 0) return -errno;
if (!same_owned_description(owner, fd)) {
close(owner);
errno = EOPNOTSUPP;
return -EOPNOTSUPP;
}
}
int dup_fd = fcntl(prime_fd, F_DUPFD_CLOEXEC, 0);
if (dup_fd < 0) {
return -errno;
int error = errno;
if (owner >= 0) close(owner);
errno = error;
return -error;
}
int ret = -ENOMEM;
pthread_mutex_lock(&lock);
for (int i = 0; i < MAX_HANDLES; i++) {
if (handle_entries[i].handle == 0) {
uint32_t token = alloc_handle_locked();
uint32_t token = alloc_handle_locked(powervr);
if (!token) {
break;
}
handle_entries[i].handle = token;
handle_entries[i].dma_fd = dup_fd;
handle_entries[i].drm_fd = fd;
handle_entries[i].owned_drm_fd = owner;
handle_entries[i].powervr = powervr;
*handle = token;
ret = 0;
break;
@@ -137,33 +208,42 @@ int drmPrimeFDToHandle(int fd, int prime_fd, uint32_t *handle) {
pthread_mutex_unlock(&lock);
if (ret) {
close(dup_fd);
if (owner >= 0) close(owner);
errno = -ret;
}
return ret;
}
int drmPrimeHandleToFD(int fd, uint32_t handle, uint32_t flags, int *prime_fd) {
if (!is_kgsl(fd)) {
int (*fn)(int, uint32_t, uint32_t, int *) = (int (*)(int, uint32_t, uint32_t, int *)) real("drmPrimeHandleToFD");
return fn ? fn(fd, handle, flags, prime_fd) : -ENOSYS;
}
int kgsl = is_kgsl(fd);
int ret = -EINVAL;
pthread_mutex_lock(&lock);
int index = find_handle_locked(fd, handle);
if (index >= 0) {
*prime_fd = fcntl(handle_entries[index].dma_fd, F_DUPFD_CLOEXEC, 0);
ret = *prime_fd < 0 ? -errno : 0;
if (!prime_fd || (handle_entries[index].powervr && (flags & ~(O_CLOEXEC | O_RDWR)))) {
errno = EINVAL;
} else {
int command = handle_entries[index].powervr && !(flags & O_CLOEXEC) ? F_DUPFD : F_DUPFD_CLOEXEC;
*prime_fd = fcntl(handle_entries[index].dma_fd, command, 0);
ret = *prime_fd < 0 ? -errno : 0;
}
}
pthread_mutex_unlock(&lock);
return ret;
if (index >= 0 || kgsl) return ret;
/* Unknown handles (including real PowerVR GEM handles) retain kernel semantics. */
int (*fn)(int, uint32_t, uint32_t, int *) =
(int (*)(int, uint32_t, uint32_t, int *)) real("drmPrimeHandleToFD");
return fn ? fn(fd, handle, flags, prime_fd) : -ENOSYS;
}
/* Drops only a handle belonging to this KGSL file description. */
/* Drops only an emulated handle belonging to this file description. */
static int release_handle(int fd, uint32_t handle) {
int found = 0;
pthread_mutex_lock(&lock);
int index = find_handle_locked(fd, handle);
if (index >= 0) {
close(handle_entries[index].dma_fd);
if (handle_entries[index].powervr) close(handle_entries[index].owned_drm_fd);
handle_entries[index] = (struct handle_entry){0};
found = 1;
}
@@ -172,11 +252,10 @@ static int release_handle(int fd, uint32_t handle) {
}
int drmCloseBufferHandle(int fd, uint32_t handle) {
if (!is_kgsl(fd)) {
int (*fn)(int, uint32_t) = (int (*)(int, uint32_t)) real("drmCloseBufferHandle");
return fn ? fn(fd, handle) : -ENOSYS;
}
return release_handle(fd, handle) ? 0 : -EINVAL;
if (release_handle(fd, handle)) return 0;
if (is_kgsl(fd)) { errno = EINVAL; return -EINVAL; }
int (*fn)(int, uint32_t) = (int (*)(int, uint32_t)) real("drmCloseBufferHandle");
return fn ? fn(fd, handle) : -ENOSYS;
}
/*
@@ -190,14 +269,16 @@ int drmCloseBufferHandle(int fd, uint32_t handle) {
* judder replaying old frames in No Man's Sky on an Adreno 840 even with no handle released.
*/
__attribute__((visibility("hidden"))) int bl_drm_gem_close(int fd, unsigned long request, void *arg, int *rc) {
if (request != GEM_CLOSE || !arg || !is_kgsl(fd)) {
if (request != GEM_CLOSE || !arg) {
return 0;
}
if (release_handle(fd, ((struct gem_close *) arg)->handle)) {
*rc = 0;
} else {
} else if (is_kgsl(fd)) {
errno = EINVAL;
*rc = -1;
} else {
return 0;
}
return 1;
}
@@ -0,0 +1,11 @@
{
"file_format_version": "1.2.0",
"layer": {
"name": "VK_LAYER_DROIDDECK_xclipse",
"type": "GLOBAL",
"library_path": "./libVkLayer_droiddeck_xclipse.so",
"api_version": "1.3.0",
"implementation_version": "1",
"description": "Workarounds for Samsung Xclipse drivers loaded through libhybris"
}
}
@@ -0,0 +1,180 @@
/* Generated by gen_device_chain.py from Vulkan-Headers 1.3.275; do not edit. */
DEVICE_CHAIN(VK_STRUCTURE_TYPE_DEVICE_DEVICE_MEMORY_REPORT_CREATE_INFO_EXT, VkDeviceDeviceMemoryReportCreateInfoEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_DEVICE_DIAGNOSTICS_CONFIG_CREATE_INFO_NV, VkDeviceDiagnosticsConfigCreateInfoNV)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_DEVICE_GROUP_DEVICE_CREATE_INFO, VkDeviceGroupDeviceCreateInfo)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_DEVICE_MEMORY_OVERALLOCATION_CREATE_INFO_AMD, VkDeviceMemoryOverallocationCreateInfoAMD)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_DEVICE_PRIVATE_DATA_CREATE_INFO, VkDevicePrivateDataCreateInfo)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_DEVICE_QUEUE_SHADER_CORE_CONTROL_CREATE_INFO_ARM, VkDeviceQueueShaderCoreControlCreateInfoARM)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_16BIT_STORAGE_FEATURES, VkPhysicalDevice16BitStorageFeatures)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_4444_FORMATS_FEATURES_EXT, VkPhysicalDevice4444FormatsFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_8BIT_STORAGE_FEATURES, VkPhysicalDevice8BitStorageFeatures)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ACCELERATION_STRUCTURE_FEATURES_KHR, VkPhysicalDeviceAccelerationStructureFeaturesKHR)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ADDRESS_BINDING_REPORT_FEATURES_EXT, VkPhysicalDeviceAddressBindingReportFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_AMIGO_PROFILING_FEATURES_SEC, VkPhysicalDeviceAmigoProfilingFeaturesSEC)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ASTC_DECODE_FEATURES_EXT, VkPhysicalDeviceASTCDecodeFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ATTACHMENT_FEEDBACK_LOOP_DYNAMIC_STATE_FEATURES_EXT, VkPhysicalDeviceAttachmentFeedbackLoopDynamicStateFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ATTACHMENT_FEEDBACK_LOOP_LAYOUT_FEATURES_EXT, VkPhysicalDeviceAttachmentFeedbackLoopLayoutFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_BLEND_OPERATION_ADVANCED_FEATURES_EXT, VkPhysicalDeviceBlendOperationAdvancedFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_BORDER_COLOR_SWIZZLE_FEATURES_EXT, VkPhysicalDeviceBorderColorSwizzleFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_BUFFER_DEVICE_ADDRESS_FEATURES, VkPhysicalDeviceBufferDeviceAddressFeatures)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_BUFFER_DEVICE_ADDRESS_FEATURES_EXT, VkPhysicalDeviceBufferDeviceAddressFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CLUSTER_CULLING_SHADER_FEATURES_HUAWEI, VkPhysicalDeviceClusterCullingShaderFeaturesHUAWEI)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COHERENT_MEMORY_FEATURES_AMD, VkPhysicalDeviceCoherentMemoryFeaturesAMD)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COLOR_WRITE_ENABLE_FEATURES_EXT, VkPhysicalDeviceColorWriteEnableFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COMPUTE_SHADER_DERIVATIVES_FEATURES_NV, VkPhysicalDeviceComputeShaderDerivativesFeaturesNV)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CONDITIONAL_RENDERING_FEATURES_EXT, VkPhysicalDeviceConditionalRenderingFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_FEATURES_KHR, VkPhysicalDeviceCooperativeMatrixFeaturesKHR)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_FEATURES_NV, VkPhysicalDeviceCooperativeMatrixFeaturesNV)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COPY_MEMORY_INDIRECT_FEATURES_NV, VkPhysicalDeviceCopyMemoryIndirectFeaturesNV)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CORNER_SAMPLED_IMAGE_FEATURES_NV, VkPhysicalDeviceCornerSampledImageFeaturesNV)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COVERAGE_REDUCTION_MODE_FEATURES_NV, VkPhysicalDeviceCoverageReductionModeFeaturesNV)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CUBIC_CLAMP_FEATURES_QCOM, VkPhysicalDeviceCubicClampFeaturesQCOM)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CUBIC_WEIGHTS_FEATURES_QCOM, VkPhysicalDeviceCubicWeightsFeaturesQCOM)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CUDA_KERNEL_LAUNCH_FEATURES_NV, VkPhysicalDeviceCudaKernelLaunchFeaturesNV)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CUSTOM_BORDER_COLOR_FEATURES_EXT, VkPhysicalDeviceCustomBorderColorFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DEDICATED_ALLOCATION_IMAGE_ALIASING_FEATURES_NV, VkPhysicalDeviceDedicatedAllocationImageAliasingFeaturesNV)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DEPTH_BIAS_CONTROL_FEATURES_EXT, VkPhysicalDeviceDepthBiasControlFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DEPTH_CLAMP_ZERO_ONE_FEATURES_EXT, VkPhysicalDeviceDepthClampZeroOneFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DEPTH_CLIP_CONTROL_FEATURES_EXT, VkPhysicalDeviceDepthClipControlFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DEPTH_CLIP_ENABLE_FEATURES_EXT, VkPhysicalDeviceDepthClipEnableFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_BUFFER_FEATURES_EXT, VkPhysicalDeviceDescriptorBufferFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_INDEXING_FEATURES, VkPhysicalDeviceDescriptorIndexingFeatures)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_POOL_OVERALLOCATION_FEATURES_NV, VkPhysicalDeviceDescriptorPoolOverallocationFeaturesNV)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_SET_HOST_MAPPING_FEATURES_VALVE, VkPhysicalDeviceDescriptorSetHostMappingFeaturesVALVE)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DEVICE_GENERATED_COMMANDS_COMPUTE_FEATURES_NV, VkPhysicalDeviceDeviceGeneratedCommandsComputeFeaturesNV)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DEVICE_GENERATED_COMMANDS_FEATURES_NV, VkPhysicalDeviceDeviceGeneratedCommandsFeaturesNV)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DEVICE_MEMORY_REPORT_FEATURES_EXT, VkPhysicalDeviceDeviceMemoryReportFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DIAGNOSTICS_CONFIG_FEATURES_NV, VkPhysicalDeviceDiagnosticsConfigFeaturesNV)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_FEATURES, VkPhysicalDeviceDynamicRenderingFeatures)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_UNUSED_ATTACHMENTS_FEATURES_EXT, VkPhysicalDeviceDynamicRenderingUnusedAttachmentsFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXCLUSIVE_SCISSOR_FEATURES_NV, VkPhysicalDeviceExclusiveScissorFeaturesNV)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTENDED_DYNAMIC_STATE_2_FEATURES_EXT, VkPhysicalDeviceExtendedDynamicState2FeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTENDED_DYNAMIC_STATE_3_FEATURES_EXT, VkPhysicalDeviceExtendedDynamicState3FeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTENDED_DYNAMIC_STATE_FEATURES_EXT, VkPhysicalDeviceExtendedDynamicStateFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTENDED_SPARSE_ADDRESS_SPACE_FEATURES_NV, VkPhysicalDeviceExtendedSparseAddressSpaceFeaturesNV)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_MEMORY_RDMA_FEATURES_NV, VkPhysicalDeviceExternalMemoryRDMAFeaturesNV)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FAULT_FEATURES_EXT, VkPhysicalDeviceFaultFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, VkPhysicalDeviceFeatures2)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_DENSITY_MAP_2_FEATURES_EXT, VkPhysicalDeviceFragmentDensityMap2FeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_DENSITY_MAP_FEATURES_EXT, VkPhysicalDeviceFragmentDensityMapFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_DENSITY_MAP_OFFSET_FEATURES_QCOM, VkPhysicalDeviceFragmentDensityMapOffsetFeaturesQCOM)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_BARYCENTRIC_FEATURES_KHR, VkPhysicalDeviceFragmentShaderBarycentricFeaturesKHR)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_INTERLOCK_FEATURES_EXT, VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADING_RATE_ENUMS_FEATURES_NV, VkPhysicalDeviceFragmentShadingRateEnumsFeaturesNV)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADING_RATE_FEATURES_KHR, VkPhysicalDeviceFragmentShadingRateFeaturesKHR)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAME_BOUNDARY_FEATURES_EXT, VkPhysicalDeviceFrameBoundaryFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_GLOBAL_PRIORITY_QUERY_FEATURES_KHR, VkPhysicalDeviceGlobalPriorityQueryFeaturesKHR)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_GRAPHICS_PIPELINE_LIBRARY_FEATURES_EXT, VkPhysicalDeviceGraphicsPipelineLibraryFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_HOST_IMAGE_COPY_FEATURES_EXT, VkPhysicalDeviceHostImageCopyFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_HOST_QUERY_RESET_FEATURES, VkPhysicalDeviceHostQueryResetFeatures)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGELESS_FRAMEBUFFER_FEATURES, VkPhysicalDeviceImagelessFramebufferFeatures)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_2D_VIEW_OF_3D_FEATURES_EXT, VkPhysicalDeviceImage2DViewOf3DFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_COMPRESSION_CONTROL_FEATURES_EXT, VkPhysicalDeviceImageCompressionControlFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_COMPRESSION_CONTROL_SWAPCHAIN_FEATURES_EXT, VkPhysicalDeviceImageCompressionControlSwapchainFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_PROCESSING_2_FEATURES_QCOM, VkPhysicalDeviceImageProcessing2FeaturesQCOM)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_PROCESSING_FEATURES_QCOM, VkPhysicalDeviceImageProcessingFeaturesQCOM)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_ROBUSTNESS_FEATURES, VkPhysicalDeviceImageRobustnessFeatures)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_SLICED_VIEW_OF_3D_FEATURES_EXT, VkPhysicalDeviceImageSlicedViewOf3DFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_VIEW_MIN_LOD_FEATURES_EXT, VkPhysicalDeviceImageViewMinLodFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_INDEX_TYPE_UINT8_FEATURES_EXT, VkPhysicalDeviceIndexTypeUint8FeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_INHERITED_VIEWPORT_SCISSOR_FEATURES_NV, VkPhysicalDeviceInheritedViewportScissorFeaturesNV)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_INLINE_UNIFORM_BLOCK_FEATURES, VkPhysicalDeviceInlineUniformBlockFeatures)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_INVOCATION_MASK_FEATURES_HUAWEI, VkPhysicalDeviceInvocationMaskFeaturesHUAWEI)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_LEGACY_DITHERING_FEATURES_EXT, VkPhysicalDeviceLegacyDitheringFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_LINEAR_COLOR_ATTACHMENT_FEATURES_NV, VkPhysicalDeviceLinearColorAttachmentFeaturesNV)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_LINE_RASTERIZATION_FEATURES_EXT, VkPhysicalDeviceLineRasterizationFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_4_FEATURES, VkPhysicalDeviceMaintenance4Features)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_5_FEATURES_KHR, VkPhysicalDeviceMaintenance5FeaturesKHR)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_6_FEATURES_KHR, VkPhysicalDeviceMaintenance6FeaturesKHR)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_DECOMPRESSION_FEATURES_NV, VkPhysicalDeviceMemoryDecompressionFeaturesNV)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_PRIORITY_FEATURES_EXT, VkPhysicalDeviceMemoryPriorityFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT, VkPhysicalDeviceMeshShaderFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_NV, VkPhysicalDeviceMeshShaderFeaturesNV)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTISAMPLED_RENDER_TO_SINGLE_SAMPLED_FEATURES_EXT, VkPhysicalDeviceMultisampledRenderToSingleSampledFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_FEATURES, VkPhysicalDeviceMultiviewFeatures)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_PER_VIEW_RENDER_AREAS_FEATURES_QCOM, VkPhysicalDeviceMultiviewPerViewRenderAreasFeaturesQCOM)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_PER_VIEW_VIEWPORTS_FEATURES_QCOM, VkPhysicalDeviceMultiviewPerViewViewportsFeaturesQCOM)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTI_DRAW_FEATURES_EXT, VkPhysicalDeviceMultiDrawFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MUTABLE_DESCRIPTOR_TYPE_FEATURES_EXT, VkPhysicalDeviceMutableDescriptorTypeFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_NESTED_COMMAND_BUFFER_FEATURES_EXT, VkPhysicalDeviceNestedCommandBufferFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_NON_SEAMLESS_CUBE_MAP_FEATURES_EXT, VkPhysicalDeviceNonSeamlessCubeMapFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_OPACITY_MICROMAP_FEATURES_EXT, VkPhysicalDeviceOpacityMicromapFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_OPTICAL_FLOW_FEATURES_NV, VkPhysicalDeviceOpticalFlowFeaturesNV)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PAGEABLE_DEVICE_LOCAL_MEMORY_FEATURES_EXT, VkPhysicalDevicePageableDeviceLocalMemoryFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PERFORMANCE_QUERY_FEATURES_KHR, VkPhysicalDevicePerformanceQueryFeaturesKHR)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PER_STAGE_DESCRIPTOR_SET_FEATURES_NV, VkPhysicalDevicePerStageDescriptorSetFeaturesNV)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_CREATION_CACHE_CONTROL_FEATURES, VkPhysicalDevicePipelineCreationCacheControlFeatures)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_EXECUTABLE_PROPERTIES_FEATURES_KHR, VkPhysicalDevicePipelineExecutablePropertiesFeaturesKHR)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_LIBRARY_GROUP_HANDLES_FEATURES_EXT, VkPhysicalDevicePipelineLibraryGroupHandlesFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_PROPERTIES_FEATURES_EXT, VkPhysicalDevicePipelinePropertiesFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_PROTECTED_ACCESS_FEATURES_EXT, VkPhysicalDevicePipelineProtectedAccessFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_ROBUSTNESS_FEATURES_EXT, VkPhysicalDevicePipelineRobustnessFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PRESENT_BARRIER_FEATURES_NV, VkPhysicalDevicePresentBarrierFeaturesNV)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PRESENT_ID_FEATURES_KHR, VkPhysicalDevicePresentIdFeaturesKHR)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PRESENT_WAIT_FEATURES_KHR, VkPhysicalDevicePresentWaitFeaturesKHR)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PRIMITIVES_GENERATED_QUERY_FEATURES_EXT, VkPhysicalDevicePrimitivesGeneratedQueryFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PRIMITIVE_TOPOLOGY_LIST_RESTART_FEATURES_EXT, VkPhysicalDevicePrimitiveTopologyListRestartFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PRIVATE_DATA_FEATURES, VkPhysicalDevicePrivateDataFeatures)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROTECTED_MEMORY_FEATURES, VkPhysicalDeviceProtectedMemoryFeatures)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROVOKING_VERTEX_FEATURES_EXT, VkPhysicalDeviceProvokingVertexFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RASTERIZATION_ORDER_ATTACHMENT_ACCESS_FEATURES_EXT, VkPhysicalDeviceRasterizationOrderAttachmentAccessFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_QUERY_FEATURES_KHR, VkPhysicalDeviceRayQueryFeaturesKHR)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_INVOCATION_REORDER_FEATURES_NV, VkPhysicalDeviceRayTracingInvocationReorderFeaturesNV)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_MAINTENANCE_1_FEATURES_KHR, VkPhysicalDeviceRayTracingMaintenance1FeaturesKHR)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_MOTION_BLUR_FEATURES_NV, VkPhysicalDeviceRayTracingMotionBlurFeaturesNV)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_PIPELINE_FEATURES_KHR, VkPhysicalDeviceRayTracingPipelineFeaturesKHR)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_POSITION_FETCH_FEATURES_KHR, VkPhysicalDeviceRayTracingPositionFetchFeaturesKHR)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RELAXED_LINE_RASTERIZATION_FEATURES_IMG, VkPhysicalDeviceRelaxedLineRasterizationFeaturesIMG)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RENDER_PASS_STRIPED_FEATURES_ARM, VkPhysicalDeviceRenderPassStripedFeaturesARM)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_REPRESENTATIVE_FRAGMENT_TEST_FEATURES_NV, VkPhysicalDeviceRepresentativeFragmentTestFeaturesNV)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RGBA10X6_FORMATS_FEATURES_EXT, VkPhysicalDeviceRGBA10X6FormatsFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ROBUSTNESS_2_FEATURES_EXT, VkPhysicalDeviceRobustness2FeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_YCBCR_CONVERSION_FEATURES, VkPhysicalDeviceSamplerYcbcrConversionFeatures)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SCALAR_BLOCK_LAYOUT_FEATURES, VkPhysicalDeviceScalarBlockLayoutFeatures)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SCHEDULING_CONTROLS_FEATURES_ARM, VkPhysicalDeviceSchedulingControlsFeaturesARM)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SEPARATE_DEPTH_STENCIL_LAYOUTS_FEATURES, VkPhysicalDeviceSeparateDepthStencilLayoutsFeatures)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_ATOMIC_FLOAT_2_FEATURES_EXT, VkPhysicalDeviceShaderAtomicFloat2FeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_ATOMIC_FLOAT_FEATURES_EXT, VkPhysicalDeviceShaderAtomicFloatFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_ATOMIC_INT64_FEATURES, VkPhysicalDeviceShaderAtomicInt64Features)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_CLOCK_FEATURES_KHR, VkPhysicalDeviceShaderClockFeaturesKHR)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_CORE_BUILTINS_FEATURES_ARM, VkPhysicalDeviceShaderCoreBuiltinsFeaturesARM)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_DEMOTE_TO_HELPER_INVOCATION_FEATURES, VkPhysicalDeviceShaderDemoteToHelperInvocationFeatures)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_DRAW_PARAMETERS_FEATURES, VkPhysicalDeviceShaderDrawParametersFeatures)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_EARLY_AND_LATE_FRAGMENT_TESTS_FEATURES_AMD, VkPhysicalDeviceShaderEarlyAndLateFragmentTestsFeaturesAMD)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_FLOAT16_INT8_FEATURES, VkPhysicalDeviceShaderFloat16Int8Features)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_IMAGE_ATOMIC_INT64_FEATURES_EXT, VkPhysicalDeviceShaderImageAtomicInt64FeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_IMAGE_FOOTPRINT_FEATURES_NV, VkPhysicalDeviceShaderImageFootprintFeaturesNV)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_INTEGER_DOT_PRODUCT_FEATURES, VkPhysicalDeviceShaderIntegerDotProductFeatures)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_INTEGER_FUNCTIONS_2_FEATURES_INTEL, VkPhysicalDeviceShaderIntegerFunctions2FeaturesINTEL)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_MODULE_IDENTIFIER_FEATURES_EXT, VkPhysicalDeviceShaderModuleIdentifierFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_OBJECT_FEATURES_EXT, VkPhysicalDeviceShaderObjectFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_SM_BUILTINS_FEATURES_NV, VkPhysicalDeviceShaderSMBuiltinsFeaturesNV)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_SUBGROUP_EXTENDED_TYPES_FEATURES, VkPhysicalDeviceShaderSubgroupExtendedTypesFeatures)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_SUBGROUP_UNIFORM_CONTROL_FLOW_FEATURES_KHR, VkPhysicalDeviceShaderSubgroupUniformControlFlowFeaturesKHR)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_TERMINATE_INVOCATION_FEATURES, VkPhysicalDeviceShaderTerminateInvocationFeatures)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_TILE_IMAGE_FEATURES_EXT, VkPhysicalDeviceShaderTileImageFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADING_RATE_IMAGE_FEATURES_NV, VkPhysicalDeviceShadingRateImageFeaturesNV)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_FEATURES, VkPhysicalDeviceSubgroupSizeControlFeatures)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBPASS_MERGE_FEEDBACK_FEATURES_EXT, VkPhysicalDeviceSubpassMergeFeedbackFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBPASS_SHADING_FEATURES_HUAWEI, VkPhysicalDeviceSubpassShadingFeaturesHUAWEI)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SWAPCHAIN_MAINTENANCE_1_FEATURES_EXT, VkPhysicalDeviceSwapchainMaintenance1FeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SYNCHRONIZATION_2_FEATURES, VkPhysicalDeviceSynchronization2Features)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TEXEL_BUFFER_ALIGNMENT_FEATURES_EXT, VkPhysicalDeviceTexelBufferAlignmentFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TEXTURE_COMPRESSION_ASTC_HDR_FEATURES, VkPhysicalDeviceTextureCompressionASTCHDRFeatures)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TILE_PROPERTIES_FEATURES_QCOM, VkPhysicalDeviceTilePropertiesFeaturesQCOM)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TIMELINE_SEMAPHORE_FEATURES, VkPhysicalDeviceTimelineSemaphoreFeatures)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TRANSFORM_FEEDBACK_FEATURES_EXT, VkPhysicalDeviceTransformFeedbackFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_UNIFORM_BUFFER_STANDARD_LAYOUT_FEATURES, VkPhysicalDeviceUniformBufferStandardLayoutFeatures)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VARIABLE_POINTERS_FEATURES, VkPhysicalDeviceVariablePointersFeatures)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VERTEX_ATTRIBUTE_DIVISOR_FEATURES_KHR, VkPhysicalDeviceVertexAttributeDivisorFeaturesKHR)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VERTEX_INPUT_DYNAMIC_STATE_FEATURES_EXT, VkPhysicalDeviceVertexInputDynamicStateFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VIDEO_MAINTENANCE_1_FEATURES_KHR, VkPhysicalDeviceVideoMaintenance1FeaturesKHR)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES, VkPhysicalDeviceVulkan11Features)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, VkPhysicalDeviceVulkan12Features)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES, VkPhysicalDeviceVulkan13Features)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_MEMORY_MODEL_FEATURES, VkPhysicalDeviceVulkanMemoryModelFeatures)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_WORKGROUP_MEMORY_EXPLICIT_LAYOUT_FEATURES_KHR, VkPhysicalDeviceWorkgroupMemoryExplicitLayoutFeaturesKHR)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_YCBCR_2_PLANE_444_FORMATS_FEATURES_EXT, VkPhysicalDeviceYcbcr2Plane444FormatsFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_YCBCR_DEGAMMA_FEATURES_QCOM, VkPhysicalDeviceYcbcrDegammaFeaturesQCOM)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_YCBCR_IMAGE_ARRAYS_FEATURES_EXT, VkPhysicalDeviceYcbcrImageArraysFeaturesEXT)
DEVICE_CHAIN(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ZERO_INITIALIZE_WORKGROUP_MEMORY_FEATURES, VkPhysicalDeviceZeroInitializeWorkgroupMemoryFeatures)
+43
View File
@@ -0,0 +1,43 @@
#!/usr/bin/env python3
"""Generate device_chain.inc: the structures a VkDeviceCreateInfo chain may hold, with their sizes.
The Xclipse layer copies the chain ahead of the VkPhysicalDeviceFeatures2 it edits, and copying a
structure needs its size. Run against the Vulkan-Headers release the build compiles with (Ubuntu
24.04's libvulkan-dev is 1.3.275):
gen_device_chain.py Vulkan-Headers/registry/vk.xml Vulkan-Headers/include/vulkan/vulkan_core.h
"""
import re
import sys
import xml.etree.ElementTree as ElementTree
from pathlib import Path
def main(registry, core_header, output):
core = Path(core_header).read_text()
root = ElementTree.parse(registry).getroot()
entries = []
for struct in root.iter("type"):
if struct.get("category") != "struct" or struct.get("alias"):
continue
if "VkDeviceCreateInfo" not in (struct.get("structextends") or "").split(","):
continue
name = struct.get("name")
stype = next((member.get("values") for member in struct.findall("member")
if member.findtext("name") == "sType"), None)
# Platform and provisional structures live outside vulkan_core.h; the layer never builds them.
if not stype or not re.search(r"\}\s*" + re.escape(name) + r"\s*;", core):
continue
entries.append((stype, name))
version = re.search(r"#define VK_HEADER_VERSION (\d+)", core).group(1)
lines = ["/* Generated by gen_device_chain.py from Vulkan-Headers 1.3.%s; do not edit. */" % version]
lines += ["DEVICE_CHAIN(%s, %s)" % entry for entry in sorted(entries)]
Path(output).write_text("\n".join(lines) + "\n")
print("%d structures" % len(entries))
if __name__ == "__main__":
if len(sys.argv) not in (3, 4):
sys.exit(__doc__)
main(sys.argv[1], sys.argv[2], sys.argv[3] if len(sys.argv) == 4 else
Path(__file__).with_name("device_chain.inc"))
+493
View File
@@ -0,0 +1,493 @@
/*
* VK_LAYER_DROIDDECK_xclipse: workarounds for Samsung's Xclipse driver loaded through libhybris.
*
* 1. bionic environ. A glibc process never initializes bionic's `environ`; the driver's
* AMD-derived shader compiler walks it for AMD_SC_* settings and crashed on the NULL.
* Once instance creation has loaded the driver, point it at a snapshot of ours.
* 2. YCbCr immutable samplers in compute. Compute pipelines whose layout binds an array of
* immutable YCbCr-conversion samplers fail to compile (VK_ERROR_UNKNOWN); gamescope's
* composite shaders all bind one. Such bindings get a plain linear sampler instead, so only
* multi-planar (NV12) layers sample incorrectly.
* 3. Calibrated timestamps. The driver has only VK_EXT_calibrated_timestamps, but the bridge
* lists the KHR names too, and Wine calls those; the loader then aborts (it took down Wine's
* explorer.exe and with it every game window). The KHR entry points forward to the EXT ones.
* 4. BC4/BC5 filtering. The libhybris compat layer emulates BC textures; BC4/BC5 decode into
* R16/R16G16 images, for which this driver advertises no linear filtering, so DXVK would
* treat them as unfilterable. The layer reports linear filtering for BC4/BC5 where they are
* sampled at all (RDNA filters 16-bit normalized formats; at worst they sample unfiltered).
* 5. textureCompressionBC. The compat layer emulates BC formats but keeps the feature bit off;
* DXVK before 3.0 (the last that fits this driver's 128 bytes of push constants) requires
* it. The layer reports it while BC formats are sampleable and clears it at device creation.
* Everything else passes straight through.
*/
#define _GNU_SOURCE
#include <vulkan/vk_layer.h>
#include <vulkan/vulkan.h>
#include <dlfcn.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define EXPORT __attribute__((visibility("default")))
#define MAX_OBJECTS 64
extern char **environ;
/* The loader's dispatch table pointer heads every dispatchable object: an instance shares it
* with its physical devices, a device with its queues and command buffers. */
typedef void *dispatch_key;
static dispatch_key key_of(const void *object) { return *(dispatch_key *)object; }
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
static int debug;
struct instance_data {
dispatch_key key;
VkInstance handle;
PFN_vkGetInstanceProcAddr next;
PFN_vkGetPhysicalDeviceCalibrateableTimeDomainsEXT time_domains;
PFN_vkGetPhysicalDeviceFeatures features;
PFN_vkGetPhysicalDeviceFeatures2 features2;
PFN_vkGetPhysicalDeviceFormatProperties format_properties;
PFN_vkGetPhysicalDeviceFormatProperties2 format_properties2;
};
struct device_data {
dispatch_key key;
VkDevice handle;
PFN_vkGetDeviceProcAddr next;
PFN_vkCreateSampler create_sampler;
PFN_vkDestroySampler destroy_sampler;
PFN_vkCreateDescriptorSetLayout create_set_layout;
PFN_vkDestroyDevice destroy_device;
PFN_vkGetCalibratedTimestampsEXT timestamps;
VkSampler fallback;
};
static struct instance_data instances[MAX_OBJECTS];
static struct device_data devices[MAX_OBJECTS];
/* The live YCbCr samplers each device created, so set layouts can recognise them. Guarded by lock. */
static struct ycbcr_sampler { VkDevice device; VkSampler sampler; } *ycbcr_samplers;
static size_t ycbcr_count, ycbcr_capacity;
static struct instance_data *instance_by_key(dispatch_key key) {
for (int i = 0; i < MAX_OBJECTS; i++)
if (instances[i].handle && instances[i].key == key) return &instances[i];
return NULL;
}
static struct device_data *device_by_key(dispatch_key key) {
for (int i = 0; i < MAX_OBJECTS; i++)
if (devices[i].handle && devices[i].key == key) return &devices[i];
return NULL;
}
/* Entries are never freed while their object lives, so a looked-up copy of the pointers is safe. */
static struct instance_data instance_of(const void *object) {
struct instance_data copy = {0};
pthread_mutex_lock(&lock);
struct instance_data *data = instance_by_key(key_of(object));
if (data) copy = *data;
pthread_mutex_unlock(&lock);
return copy;
}
static struct device_data device_of(const void *object) {
struct device_data copy = {0};
pthread_mutex_lock(&lock);
struct device_data *data = device_by_key(key_of(object));
if (data) copy = *data;
pthread_mutex_unlock(&lock);
return copy;
}
static void fix_bionic_environ(void) {
void *common = dlopen("libhybris-common.so.1", RTLD_NOW | RTLD_NOLOAD);
if (!common) return; /* not a libhybris driver */
void *(*h_dlopen)(const char *, int) = (void *(*)(const char *, int))dlsym(common, "hybris_dlopen");
void *(*h_dlsym)(void *, const char *) = (void *(*)(void *, const char *))dlsym(common, "hybris_dlsym");
if (!h_dlopen || !h_dlsym) return;
void *libc = h_dlopen("libc.so", RTLD_NOW);
char ***bionic_environ = libc ? (char ***)h_dlsym(libc, "environ") : NULL;
if (!bionic_environ || *bionic_environ) return;
size_t count = 0;
while (environ && environ[count]) count++;
char **snapshot = calloc(count + 1, sizeof(*snapshot));
if (!snapshot) return;
for (size_t i = 0; i < count; i++) snapshot[i] = strdup(environ[i]);
*bionic_environ = snapshot;
if (debug) fprintf(stderr, "xclipse layer: bionic environ set (%zu entries)\n", count);
}
/* ---- instance ---- */
static VkResult VKAPI_CALL create_instance(const VkInstanceCreateInfo *info, const VkAllocationCallbacks *allocator,
VkInstance *instance) {
VkLayerInstanceCreateInfo *chain = (VkLayerInstanceCreateInfo *)info->pNext;
while (chain && !(chain->sType == VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO && chain->function == VK_LAYER_LINK_INFO))
chain = (VkLayerInstanceCreateInfo *)chain->pNext;
if (!chain || !chain->u.pLayerInfo) return VK_ERROR_INITIALIZATION_FAILED;
PFN_vkGetInstanceProcAddr next = chain->u.pLayerInfo->pfnNextGetInstanceProcAddr;
chain->u.pLayerInfo = chain->u.pLayerInfo->pNext;
PFN_vkCreateInstance next_create = (PFN_vkCreateInstance)next(NULL, "vkCreateInstance");
if (!next_create) return VK_ERROR_INITIALIZATION_FAILED;
VkResult result = next_create(info, allocator, instance);
if (result != VK_SUCCESS) return result;
fix_bionic_environ();
struct instance_data data = {
.key = key_of(*instance),
.handle = *instance,
.next = next,
.time_domains = (PFN_vkGetPhysicalDeviceCalibrateableTimeDomainsEXT)
next(*instance, "vkGetPhysicalDeviceCalibrateableTimeDomainsEXT"),
.features = (PFN_vkGetPhysicalDeviceFeatures)next(*instance, "vkGetPhysicalDeviceFeatures"),
.features2 = (PFN_vkGetPhysicalDeviceFeatures2)next(*instance, "vkGetPhysicalDeviceFeatures2"),
.format_properties = (PFN_vkGetPhysicalDeviceFormatProperties)next(*instance, "vkGetPhysicalDeviceFormatProperties"),
.format_properties2 = (PFN_vkGetPhysicalDeviceFormatProperties2)next(*instance, "vkGetPhysicalDeviceFormatProperties2"),
};
pthread_mutex_lock(&lock);
for (int i = 0; i < MAX_OBJECTS; i++)
if (!instances[i].handle) { instances[i] = data; break; }
pthread_mutex_unlock(&lock);
return result;
}
static void VKAPI_CALL destroy_instance(VkInstance instance, const VkAllocationCallbacks *allocator) {
PFN_vkGetInstanceProcAddr next = instance_of(instance).next;
pthread_mutex_lock(&lock);
struct instance_data *data = instance_by_key(key_of(instance));
if (data) memset(data, 0, sizeof(*data));
pthread_mutex_unlock(&lock);
PFN_vkDestroyInstance next_destroy = next ? (PFN_vkDestroyInstance)next(instance, "vkDestroyInstance") : NULL;
if (next_destroy) next_destroy(instance, allocator);
}
static VkResult VKAPI_CALL time_domains_khr(VkPhysicalDevice physical, uint32_t *count, VkTimeDomainEXT *domains) {
PFN_vkGetPhysicalDeviceCalibrateableTimeDomainsEXT ext = instance_of(physical).time_domains;
if (!ext) { *count = 0; return VK_SUCCESS; }
return ext(physical, count, domains);
}
/* BC formats sampleable below us although the driver's feature bit is off: the compat layer emulates them. */
static int bc_emulated(VkPhysicalDevice physical) {
struct instance_data data = instance_of(physical);
if (!data.features || !data.format_properties) return 0;
VkPhysicalDeviceFeatures native;
data.features(physical, &native);
if (native.textureCompressionBC) return 0;
VkFormatProperties bc1, bc7;
data.format_properties(physical, VK_FORMAT_BC1_RGBA_UNORM_BLOCK, &bc1);
data.format_properties(physical, VK_FORMAT_BC7_UNORM_BLOCK, &bc7);
return (bc1.optimalTilingFeatures & bc7.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) != 0;
}
static void VKAPI_CALL get_features(VkPhysicalDevice physical, VkPhysicalDeviceFeatures *features) {
PFN_vkGetPhysicalDeviceFeatures next = instance_of(physical).features;
if (next) next(physical, features);
if (bc_emulated(physical)) features->textureCompressionBC = VK_TRUE;
}
static void VKAPI_CALL get_features2(VkPhysicalDevice physical, VkPhysicalDeviceFeatures2 *features) {
PFN_vkGetPhysicalDeviceFeatures2 next = instance_of(physical).features2;
if (next) next(physical, features);
if (bc_emulated(physical)) features->features.textureCompressionBC = VK_TRUE;
}
static int bc45(VkFormat format) {
return format >= VK_FORMAT_BC4_UNORM_BLOCK && format <= VK_FORMAT_BC5_SNORM_BLOCK;
}
static void VKAPI_CALL get_format_properties(VkPhysicalDevice physical, VkFormat format, VkFormatProperties *out) {
PFN_vkGetPhysicalDeviceFormatProperties next = instance_of(physical).format_properties;
if (next) next(physical, format, out);
if (bc45(format) && (out->optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT))
out->optimalTilingFeatures |= VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT;
}
static void VKAPI_CALL get_format_properties2(VkPhysicalDevice physical, VkFormat format, VkFormatProperties2 *out) {
PFN_vkGetPhysicalDeviceFormatProperties2 next = instance_of(physical).format_properties2;
if (next) next(physical, format, out);
if (!bc45(format)) return;
if (out->formatProperties.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT)
out->formatProperties.optimalTilingFeatures |= VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT;
for (VkBaseOutStructure *p = (VkBaseOutStructure *)out->pNext; p; p = p->pNext) {
if (p->sType != VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_3) continue;
VkFormatProperties3 *f3 = (VkFormatProperties3 *)p;
if (f3->optimalTilingFeatures & VK_FORMAT_FEATURE_2_SAMPLED_IMAGE_BIT)
f3->optimalTilingFeatures |= VK_FORMAT_FEATURE_2_SAMPLED_IMAGE_FILTER_LINEAR_BIT;
}
}
/* ---- device ---- */
/* The size of each structure a VkDeviceCreateInfo chain may hold (device_chain.inc, generated from the
* Vulkan registry), plus the loader's own; 0 for anything else. */
static size_t chain_size(VkStructureType type) {
switch (type) {
#define DEVICE_CHAIN(stype, name) case stype: return sizeof(name);
#include "device_chain.inc"
#undef DEVICE_CHAIN
case VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO: return sizeof(VkLayerDeviceCreateInfo);
default: return 0;
}
}
struct chain_copy { void **nodes; size_t count; };
static void free_chain_copy(struct chain_copy *copy) {
for (size_t i = 0; i < copy->count; i++) free(copy->nodes[i]);
free(copy->nodes);
copy->nodes = NULL;
copy->count = 0;
}
/* The chain with textureCompressionBC cleared in a copy of the VkPhysicalDeviceFeatures2 that enables
* it: every structure up to it is copied into [copy], the rest is shared. The caller's structures are
* never written. *head_out stays [head] when nothing needs clearing, or when a structure ahead of it
* is unknown to this build (newer than its Vulkan headers); the compat layer then refuses the bit. */
static VkResult chain_without_bc(const void *head, struct chain_copy *copy, const void **head_out) {
*head_out = head;
const VkBaseInStructure *target = NULL;
size_t count = 0;
for (const VkBaseInStructure *p = head; p && !target; p = p->pNext) {
if (!chain_size(p->sType)) return VK_SUCCESS;
count++;
if (p->sType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2 &&
((const VkPhysicalDeviceFeatures2 *)p)->features.textureCompressionBC) target = p;
}
if (!target) return VK_SUCCESS;
if (!(copy->nodes = calloc(count, sizeof(*copy->nodes)))) return VK_ERROR_OUT_OF_HOST_MEMORY;
VkBaseOutStructure *first = NULL, *last = NULL;
for (const VkBaseInStructure *p = head; ; p = p->pNext) {
size_t size = chain_size(p->sType);
VkBaseOutStructure *node = malloc(size);
if (!node) { free_chain_copy(copy); return VK_ERROR_OUT_OF_HOST_MEMORY; }
copy->nodes[copy->count++] = node;
memcpy(node, p, size);
if (last) last->pNext = node; else first = node;
last = node;
if (p == target) {
((VkPhysicalDeviceFeatures2 *)node)->features.textureCompressionBC = VK_FALSE;
*head_out = first; /* its pNext still leads to the caller's remaining structures */
return VK_SUCCESS;
}
}
}
static VkResult VKAPI_CALL create_device(VkPhysicalDevice physical, const VkDeviceCreateInfo *info,
const VkAllocationCallbacks *allocator, VkDevice *device) {
VkLayerDeviceCreateInfo *chain = (VkLayerDeviceCreateInfo *)info->pNext;
while (chain && !(chain->sType == VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO && chain->function == VK_LAYER_LINK_INFO))
chain = (VkLayerDeviceCreateInfo *)chain->pNext;
if (!chain || !chain->u.pLayerInfo) return VK_ERROR_INITIALIZATION_FAILED;
PFN_vkGetInstanceProcAddr next_gipa = chain->u.pLayerInfo->pfnNextGetInstanceProcAddr;
PFN_vkGetDeviceProcAddr next_gdpa = chain->u.pLayerInfo->pfnNextGetDeviceProcAddr;
chain->u.pLayerInfo = chain->u.pLayerInfo->pNext;
PFN_vkCreateDevice next_create = (PFN_vkCreateDevice)next_gipa(NULL, "vkCreateDevice");
if (!next_create) return VK_ERROR_INITIALIZATION_FAILED;
VkDeviceCreateInfo patched = *info;
/* An emulated textureCompressionBC never reaches the compat layer, which refuses the bit. */
int strip_bc = bc_emulated(physical);
VkPhysicalDeviceFeatures plain_features;
if (strip_bc && info->pEnabledFeatures && info->pEnabledFeatures->textureCompressionBC) {
plain_features = *info->pEnabledFeatures;
plain_features.textureCompressionBC = VK_FALSE;
patched.pEnabledFeatures = &plain_features;
}
struct chain_copy copy = {0};
if (strip_bc) {
VkResult copied = chain_without_bc(info->pNext, &copy, &patched.pNext);
if (copied != VK_SUCCESS) return copied;
}
VkResult result = next_create(physical, &patched, allocator, device);
free_chain_copy(&copy);
if (result != VK_SUCCESS) return result;
PFN_vkCreateSampler create_sampler = (PFN_vkCreateSampler)next_gdpa(*device, "vkCreateSampler");
VkSamplerCreateInfo plain = {
.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO,
.magFilter = VK_FILTER_LINEAR, .minFilter = VK_FILTER_LINEAR,
.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK,
};
VkSampler fallback = VK_NULL_HANDLE;
if (create_sampler) create_sampler(*device, &plain, NULL, &fallback);
struct device_data data = {
.key = key_of(*device),
.handle = *device,
.next = next_gdpa,
.create_sampler = create_sampler,
.destroy_sampler = (PFN_vkDestroySampler)next_gdpa(*device, "vkDestroySampler"),
.create_set_layout = (PFN_vkCreateDescriptorSetLayout)next_gdpa(*device, "vkCreateDescriptorSetLayout"),
.destroy_device = (PFN_vkDestroyDevice)next_gdpa(*device, "vkDestroyDevice"),
.timestamps = (PFN_vkGetCalibratedTimestampsEXT)next_gdpa(*device, "vkGetCalibratedTimestampsEXT"),
.fallback = fallback,
};
pthread_mutex_lock(&lock);
for (int i = 0; i < MAX_OBJECTS; i++)
if (!devices[i].handle) { devices[i] = data; break; }
pthread_mutex_unlock(&lock);
return result;
}
static void VKAPI_CALL destroy_device(VkDevice device, const VkAllocationCallbacks *allocator) {
struct device_data data = device_of(device);
pthread_mutex_lock(&lock);
struct device_data *entry = device_by_key(key_of(device));
if (entry) memset(entry, 0, sizeof(*entry));
for (size_t k = 0; k < ycbcr_count;)
if (ycbcr_samplers[k].device == device) ycbcr_samplers[k] = ycbcr_samplers[--ycbcr_count];
else k++;
pthread_mutex_unlock(&lock);
if (data.fallback && data.destroy_sampler) data.destroy_sampler(device, data.fallback, NULL);
if (data.destroy_device) data.destroy_device(device, allocator);
}
static VkResult VKAPI_CALL timestamps_khr(VkDevice device, uint32_t count, const VkCalibratedTimestampInfoEXT *infos,
uint64_t *timestamps, uint64_t *deviation) {
PFN_vkGetCalibratedTimestampsEXT ext = device_of(device).timestamps;
return ext ? ext(device, count, infos, timestamps, deviation) : VK_ERROR_FEATURE_NOT_PRESENT;
}
static VkResult VKAPI_CALL create_sampler(VkDevice device, const VkSamplerCreateInfo *info,
const VkAllocationCallbacks *allocator, VkSampler *sampler) {
PFN_vkCreateSampler next = device_of(device).create_sampler;
if (!next) return VK_ERROR_INITIALIZATION_FAILED;
VkResult result = next(device, info, allocator, sampler);
if (result != VK_SUCCESS) return result;
int ycbcr = 0;
for (const VkBaseInStructure *p = info->pNext; p && !ycbcr; p = p->pNext)
ycbcr = p->sType == VK_STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_INFO;
if (!ycbcr) return result;
pthread_mutex_lock(&lock);
if (ycbcr_count == ycbcr_capacity) {
size_t capacity = ycbcr_capacity ? ycbcr_capacity * 2 : 16;
struct ycbcr_sampler *grown = realloc(ycbcr_samplers, capacity * sizeof(*grown));
if (!grown) {
pthread_mutex_unlock(&lock);
/* An untracked YCbCr sampler would reach a compute layout unreplaced: fail instead. */
PFN_vkDestroySampler destroy = device_of(device).destroy_sampler;
if (destroy) destroy(device, *sampler, allocator);
*sampler = VK_NULL_HANDLE;
return VK_ERROR_OUT_OF_HOST_MEMORY;
}
ycbcr_samplers = grown;
ycbcr_capacity = capacity;
}
ycbcr_samplers[ycbcr_count++] = (struct ycbcr_sampler){device, *sampler};
pthread_mutex_unlock(&lock);
return result;
}
static void VKAPI_CALL destroy_sampler(VkDevice device, VkSampler sampler, const VkAllocationCallbacks *allocator) {
pthread_mutex_lock(&lock);
for (size_t k = 0; k < ycbcr_count; k++)
if (ycbcr_samplers[k].device == device && ycbcr_samplers[k].sampler == sampler) {
ycbcr_samplers[k] = ycbcr_samplers[--ycbcr_count];
break;
}
pthread_mutex_unlock(&lock);
PFN_vkDestroySampler next = device_of(device).destroy_sampler;
if (next) next(device, sampler, allocator);
}
/* Called with lock held. */
static int is_ycbcr(VkDevice device, VkSampler sampler) {
for (size_t k = 0; sampler && k < ycbcr_count; k++)
if (ycbcr_samplers[k].device == device && ycbcr_samplers[k].sampler == sampler) return 1;
return 0;
}
static VkResult VKAPI_CALL create_set_layout(VkDevice device, const VkDescriptorSetLayoutCreateInfo *info,
const VkAllocationCallbacks *allocator, VkDescriptorSetLayout *layout) {
struct device_data data = device_of(device);
if (!data.create_set_layout) return VK_ERROR_INITIALIZATION_FAILED;
int replace = 0;
pthread_mutex_lock(&lock);
for (uint32_t b = 0; data.fallback && b < info->bindingCount && !replace; b++) {
const VkDescriptorSetLayoutBinding *binding = &info->pBindings[b];
if (!(binding->stageFlags & VK_SHADER_STAGE_COMPUTE_BIT) || !binding->pImmutableSamplers) continue;
for (uint32_t s = 0; s < binding->descriptorCount; s++)
if (is_ycbcr(device, binding->pImmutableSamplers[s])) { replace = 1; break; }
}
pthread_mutex_unlock(&lock);
if (!replace) return data.create_set_layout(device, info, allocator, layout);
VkResult result = VK_ERROR_OUT_OF_HOST_MEMORY;
VkDescriptorSetLayoutBinding *bindings = calloc(info->bindingCount, sizeof(*bindings));
VkSampler **arrays = calloc(info->bindingCount, sizeof(*arrays));
if (!bindings || !arrays) goto done;
for (uint32_t b = 0; b < info->bindingCount; b++) {
bindings[b] = info->pBindings[b];
if (!(bindings[b].stageFlags & VK_SHADER_STAGE_COMPUTE_BIT) || !bindings[b].pImmutableSamplers) continue;
/* Without the replacement the driver would see the samplers it cannot compile: fail instead. */
if (!(arrays[b] = malloc(bindings[b].descriptorCount * sizeof(VkSampler)))) goto done;
pthread_mutex_lock(&lock);
for (uint32_t s = 0; s < bindings[b].descriptorCount; s++) {
VkSampler original = bindings[b].pImmutableSamplers[s];
arrays[b][s] = is_ycbcr(device, original) ? data.fallback : original;
}
pthread_mutex_unlock(&lock);
bindings[b].pImmutableSamplers = arrays[b];
}
VkDescriptorSetLayoutCreateInfo patched = *info;
patched.pBindings = bindings;
result = data.create_set_layout(device, &patched, allocator, layout);
if (debug) fprintf(stderr, "xclipse layer: compute YCbCr immutable samplers replaced (%d)\n", result);
done:
for (uint32_t b = 0; arrays && b < info->bindingCount; b++) free(arrays[b]);
free(arrays);
free(bindings);
return result;
}
/* ---- dispatch ---- */
static PFN_vkVoidFunction device_hook(const char *name) {
if (!strcmp(name, "vkGetDeviceProcAddr")) return NULL; /* handled by the caller */
if (!strcmp(name, "vkDestroyDevice")) return (PFN_vkVoidFunction)destroy_device;
if (!strcmp(name, "vkCreateSampler")) return (PFN_vkVoidFunction)create_sampler;
if (!strcmp(name, "vkDestroySampler")) return (PFN_vkVoidFunction)destroy_sampler;
if (!strcmp(name, "vkCreateDescriptorSetLayout")) return (PFN_vkVoidFunction)create_set_layout;
if (!strcmp(name, "vkGetCalibratedTimestampsKHR")) return (PFN_vkVoidFunction)timestamps_khr;
return NULL;
}
EXPORT VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vkGetDeviceProcAddr(VkDevice device, const char *name) {
if (!strcmp(name, "vkGetDeviceProcAddr")) return (PFN_vkVoidFunction)vkGetDeviceProcAddr;
PFN_vkVoidFunction hook = device_hook(name);
if (hook) return hook;
struct device_data data = device ? device_of(device) : (struct device_data){0};
return data.next ? data.next(device, name) : NULL;
}
EXPORT VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vkGetInstanceProcAddr(VkInstance instance, const char *name) {
if (!strcmp(name, "vkGetInstanceProcAddr")) return (PFN_vkVoidFunction)vkGetInstanceProcAddr;
if (!strcmp(name, "vkCreateInstance")) return (PFN_vkVoidFunction)create_instance;
if (!strcmp(name, "vkDestroyInstance")) return (PFN_vkVoidFunction)destroy_instance;
if (!strcmp(name, "vkCreateDevice")) return (PFN_vkVoidFunction)create_device;
if (!strcmp(name, "vkGetDeviceProcAddr")) return (PFN_vkVoidFunction)vkGetDeviceProcAddr;
if (!strcmp(name, "vkGetPhysicalDeviceFeatures")) return (PFN_vkVoidFunction)get_features;
if (!strcmp(name, "vkGetPhysicalDeviceFeatures2") || !strcmp(name, "vkGetPhysicalDeviceFeatures2KHR"))
return (PFN_vkVoidFunction)get_features2;
if (!strcmp(name, "vkGetPhysicalDeviceCalibrateableTimeDomainsKHR")) return (PFN_vkVoidFunction)time_domains_khr;
if (!strcmp(name, "vkGetPhysicalDeviceFormatProperties")) return (PFN_vkVoidFunction)get_format_properties;
if (!strcmp(name, "vkGetPhysicalDeviceFormatProperties2") || !strcmp(name, "vkGetPhysicalDeviceFormatProperties2KHR"))
return (PFN_vkVoidFunction)get_format_properties2;
PFN_vkVoidFunction hook = device_hook(name);
if (hook) return hook;
PFN_vkGetInstanceProcAddr next = instance ? instance_of(instance).next : NULL;
return next ? next(instance, name) : NULL;
}
EXPORT VKAPI_ATTR VkResult VKAPI_CALL vkNegotiateLoaderLayerInterfaceVersion(VkNegotiateLayerInterface *negotiate) {
if (!negotiate || negotiate->loaderLayerInterfaceVersion < 2) return VK_ERROR_INITIALIZATION_FAILED;
debug = getenv("DROIDDECK_XCLIPSE_LAYER_DEBUG") != NULL;
negotiate->loaderLayerInterfaceVersion = 2;
negotiate->pfnGetInstanceProcAddr = vkGetInstanceProcAddr;
negotiate->pfnGetDeviceProcAddr = vkGetDeviceProcAddr;
negotiate->pfnGetPhysicalDeviceProcAddr = NULL;
return VK_SUCCESS;
}
+1
View File
@@ -10,6 +10,7 @@ RUN apt-get update \
g++ \
gcc-aarch64-linux-gnu \
g++-aarch64-linux-gnu \
libvulkan-dev \
python3 \
zstd \
unzip \
+366
View File
@@ -0,0 +1,366 @@
#!/usr/bin/env python3
"""Assemble the pinned PowerVR components into the APK's isolated Linux runtime.
Like DirectAudio, APK builds download published components rather than compile
them. Their source, licenses and patches travel with the payload. Build recipes
remain in tools/{hybris,dxvk,vulkan-wsi}; release.json pins their reviewed inputs.
"""
import argparse
import hashlib
import io
import json
import os
from pathlib import Path, PurePosixPath
import posixpath
import re
import stat
import subprocess
import tarfile
import tempfile
from urllib.parse import urlparse
from urllib.request import urlopen
from zipfile import ZipFile
ROOT = Path(__file__).resolve().parents[2]
ASSETS = Path("app/src/main/assets/hybris")
REQUIRED_LIBRARIES = (
"lib/libhybris-vulkan-icd.so.0", "lib/libhybris-common.so.1",
"lib/libhybris/linker/q.so", "lib/libVkLayer_hybris_compat.so",
"wsi/libVkLayer_window_system_integration.so",
)
MAX_UNPACKED = 256 * 1024 * 1024
BUNDLED_LICENSES = {
'tools/vulkan-wsi/licenses/Vulkan-Headers/' + name: 'licenses/Vulkan-Headers/' + name
for name in ('LICENSE.md', 'MIT.txt')
}
def sha256(data):
return hashlib.sha256(data).hexdigest()
def json_bytes(value):
return (json.dumps(value, sort_keys=True, indent=2) + "\n").encode()
def safe_name(name):
path = PurePosixPath(name)
if not name or path.is_absolute() or ".." in path.parts or "\\" in name:
raise ValueError("unsafe archive path: " + name)
return str(path)
def check_tree(entries):
# Never extract through a symlink, even one pointing inside the tree.
for name, entry in entries.items():
for parent in PurePosixPath(name).parents:
if str(parent) in entries:
raise ValueError("archive member below a file or symlink: " + name)
if entry[0] == "symlink":
read(entries, name)
def read(entries, name, seen=()):
if name in seen or len(seen) > 16:
raise ValueError("runtime symlink cycle: " + name)
if name not in entries:
raise ValueError("missing runtime file: " + name)
kind, mode, data = entries[name]
if kind == "symlink":
if PurePosixPath(data).is_absolute() or "\\" in data:
raise ValueError("unsafe runtime symlink: " + name)
target = safe_name(posixpath.normpath(posixpath.join(posixpath.dirname(name), data)))
return read(entries, target, (*seen, name))
return data
def read_tar(data):
unpacked = subprocess.run(["zstd", "-q", "-dc"], input=data,
capture_output=True, check=True).stdout
if len(unpacked) > MAX_UNPACKED:
raise ValueError("runtime archive exceeds size limit")
entries, seen = {}, set()
with tarfile.open(fileobj=io.BytesIO(unpacked)) as package:
for member in package:
name = safe_name(member.name)
if name in seen:
raise ValueError("duplicate archive path: " + name)
seen.add(name)
if member.isdir():
continue
if name == ".":
raise ValueError("archive root must be a directory")
if member.issym():
entries[name] = ("symlink", 0o777, member.linkname)
elif member.isfile():
entries[name] = ("file", 0o755 if member.mode & 0o111 else 0o644,
package.extractfile(member).read())
else:
raise ValueError("unsupported archive entry type: " + name)
check_tree(entries)
return entries
def tree_digest(entries):
return sha256(json_bytes({name: [kind, mode, sha256(data) if kind == "file" else data]
for name, (kind, mode, data) in sorted(entries.items())}))
def load_release(root):
release = json.loads((root / "tools/powervr/release.json").read_bytes())
if release.get("format") != 1:
raise ValueError("unsupported PowerVR release pins")
# These identify the reviewed recipe, not a new attestation from the old
# producer. The original build metadata is preserved inside the runtime.
for component in [release["hybris"], *release["archives"]]:
for name, expected in component["recipe_inputs"].items():
if sha256((root / name).read_bytes()) != expected:
raise ValueError("PowerVR component recipe changed; update its release pin: " + name)
return release
def assembly_inputs(root):
return {"format": 1, "inputs": {
name: sha256((root / name).read_bytes()) for name in
("tools/powervr/release.json", "tools/powervr/fetch.py", "tools/hybris/run-proton.py", *BUNDLED_LICENSES)}}
def fetch(component, cache):
url = component["url"]
if urlparse(url).scheme != "https":
raise ValueError("component URL must use HTTPS")
cache.mkdir(parents=True, exist_ok=True)
target = cache / (component["sha256"] + "-" + PurePosixPath(urlparse(url).path).name)
def valid(path):
return (path.is_file() and path.stat().st_size == component["size"]
and sha256(path.read_bytes()) == component["sha256"])
if valid(target):
return target.read_bytes()
# No unverified response is ever parsed or promoted into the cache.
with tempfile.NamedTemporaryFile(dir=cache, prefix=".download-", delete=False) as output:
temporary = Path(output.name)
try:
with urlopen(url, timeout=60) as response:
remaining = component["size"]
while block := response.read(min(1024 * 1024, remaining + 1)):
remaining -= len(block)
if remaining < 0:
raise ValueError("component download exceeds pinned size")
output.write(block)
output.flush()
if not valid(temporary):
raise ValueError("component download checksum mismatch: " + url)
os.replace(temporary, target)
finally:
temporary.unlink(missing_ok=True)
return target.read_bytes()
def read_zip(data, component):
entries, seen = {}, set()
expected = {item["name"]: item for item in component["files"]}
allowed = set(expected) | set(component["ignored"])
total = 0
with ZipFile(io.BytesIO(data)) as archive:
for member in archive.infolist():
name = safe_name(member.filename)
if name in seen:
raise ValueError("duplicate archive path: " + name)
seen.add(name)
mode = member.external_attr >> 16
kind = stat.S_IFMT(mode)
if member.is_dir() and kind in (0, stat.S_IFDIR):
continue
if kind not in (0, stat.S_IFREG) or name not in allowed:
raise ValueError("unexpected component archive entry: " + name)
total += member.file_size
if total > MAX_UNPACKED:
raise ValueError("component archive exceeds size limit")
if name not in expected:
continue
pin = expected[name]
content = archive.read(member)
if len(content) != pin["size"] or sha256(content) != pin["sha256"]:
raise ValueError("component member checksum mismatch: " + name)
path = safe_name(pin["path"])
if path in entries:
raise ValueError("duplicate component destination: " + path)
entries[path] = ("file", pin["mode"], content)
if set(expected) - seen:
raise ValueError("component archive missing files: " + ", ".join(sorted(set(expected) - seen)))
check_tree(entries)
return entries
def read_tar_gz(data, component):
"""An upstream release tarball, held to the same per-file pins as a CI archive."""
entries, seen = {}, set()
expected = {item["name"]: item for item in component["files"]}
allowed = set(expected) | set(component["ignored"])
total = 0
with tarfile.open(fileobj=io.BytesIO(data), mode="r:gz") as archive:
for member in archive:
name = safe_name(member.name)
if name in seen:
raise ValueError("duplicate archive path: " + name)
seen.add(name)
if member.isdir():
continue
if not member.isfile() or name not in allowed:
raise ValueError("unexpected component archive entry: " + name)
total += member.size
if total > MAX_UNPACKED:
raise ValueError("component archive exceeds size limit")
if name not in expected:
continue
pin = expected[name]
content = archive.extractfile(member).read()
if len(content) != pin["size"] or sha256(content) != pin["sha256"]:
raise ValueError("component member checksum mismatch: " + name)
path = safe_name(pin["path"])
if path in entries:
raise ValueError("duplicate component destination: " + path)
entries[path] = ("file", pin["mode"], content)
if set(expected) - seen:
raise ValueError("component archive missing files: " + ", ".join(sorted(set(expected) - seen)))
check_tree(entries)
return entries
def read_component(data, component):
kind = component.get("format", "zip")
if kind == "zip":
return read_zip(data, component)
if kind == "tar.gz":
return read_tar_gz(data, component)
raise ValueError("unsupported component archive format: " + kind)
def check_bundle(entries, release, root):
check_tree(entries)
if read(entries, "assembly-inputs.json") != json_bytes(assembly_inputs(root)):
raise ValueError("PowerVR assembly inputs changed; run tools/powervr/fetch.py")
if entries["run-proton.py"] != ("file", 0o755, (root / "tools/hybris/run-proton.py").read_bytes()):
raise ValueError("PowerVR Proton wrapper is stale or not executable")
compile(read(entries, "run-proton.py"), "run-proton.py", "exec")
bridge = dict(entries)
del bridge["assembly-inputs.json"], bridge["run-proton.py"]
for source, target in BUNDLED_LICENSES.items():
if entries.get(target) != ("file", 0o644, (root / source).read_bytes()):
raise ValueError("Vulkan-Headers license missing or stale: " + target)
for component in release["archives"]:
for pin in component["files"]:
content = read(entries, pin["path"])
if (entries[pin["path"]][:2] != ("file", pin["mode"])
or len(content) != pin["size"] or sha256(content) != pin["sha256"]):
raise ValueError("PowerVR component mismatch: " + pin["path"])
del bridge[pin["path"]]
for target in BUNDLED_LICENSES.values():
bridge.pop(target, None)
if tree_digest(bridge) != release["hybris"]["tree_sha256"]:
raise ValueError("PowerVR bridge differs from the pinned archive")
for name in REQUIRED_LIBRARIES:
content = read(entries, name)
if content[:6] != b"\x7fELF\x02\x01" or content[18:20] != b"\xb7\x00":
raise ValueError("runtime library is not ELF64 AArch64: " + name)
# dxvk/ is the default payload; run-proton.py can select another dxvk-* sibling by name.
payloads = sorted({name.split("/")[0] for name in entries if re.fullmatch(r"dxvk[^/]*/x(32|64)/[^/]+\.dll", name)})
if "dxvk" not in payloads:
raise ValueError("default DXVK payload missing")
for payload in payloads:
for architecture, machine, magic in (("x32", b"\x4c\x01", b"\x0b\x01"),
("x64", b"\x64\x86", b"\x0b\x02")):
for name in ("d3d8.dll", "d3d9.dll", "d3d10core.dll", "d3d11.dll", "dxgi.dll"):
path = payload + "/" + architecture + "/" + name
content = read(entries, path)
pe = int.from_bytes(content[60:64], "little")
if (content[:2] != b"MZ" or pe < 64 or content[pe:pe + 4] != b"PE\0\0"
or content[pe + 4:pe + 6] != machine or content[pe + 24:pe + 26] != magic):
raise ValueError("DXVK library has wrong PE architecture: " + path)
def pack(entries):
stream = io.BytesIO()
directories = {str(parent) for name in entries for parent in PurePosixPath(name).parents
if str(parent) != "."}
with tarfile.open(fileobj=stream, mode="w", format=tarfile.USTAR_FORMAT) as archive:
for name in sorted(directories | set(entries)):
info = tarfile.TarInfo(name)
info.mtime = info.uid = info.gid = 0
if name in directories:
info.type, info.mode = tarfile.DIRTYPE, 0o755
archive.addfile(info)
continue
kind, info.mode, data = entries[name]
if kind == "symlink":
info.type, info.linkname = tarfile.SYMTYPE, data
archive.addfile(info)
else:
info.size = len(data)
archive.addfile(info, io.BytesIO(data))
return subprocess.run(["zstd", "-q", "-10", "-T1", "-c"], input=stream.getvalue(),
capture_output=True, check=True).stdout
def verify_archive(archive, version, root=ROOT):
release = load_release(root)
if sha256(archive) != version.strip():
raise ValueError("PowerVR runtime archive checksum mismatch")
check_bundle(read_tar(archive), release, root)
def verify(root=ROOT):
verify_archive((root / ASSETS / "runtime.tzst").read_bytes(),
(root / ASSETS / "version.txt").read_text(), root)
def assemble(root, cache):
release = load_release(root)
entries = read_tar(fetch(release["hybris"], cache))
if tree_digest(entries) != release["hybris"]["tree_sha256"]:
raise ValueError("PowerVR bridge tree checksum mismatch")
for component in release["archives"]:
additions = read_component(fetch(component, cache), component)
if set(entries) & set(additions):
raise ValueError("component overwrites existing runtime files")
entries.update(additions)
for source, target in BUNDLED_LICENSES.items():
license_entry = ("file", 0o644, (root / source).read_bytes())
if target in entries and entries[target] != license_entry:
raise ValueError("bundled license overwrites component file: " + target)
entries[target] = license_entry
entries["run-proton.py"] = ("file", 0o755, (root / "tools/hybris/run-proton.py").read_bytes())
entries["assembly-inputs.json"] = ("file", 0o644, json_bytes(assembly_inputs(root)))
check_bundle(entries, release, root)
archive = pack(entries)
assets = root / ASSETS
assets.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(dir=assets.parent, prefix=".hybris-") as directory:
stage = Path(directory)
(stage / "runtime.tzst").write_bytes(archive)
(stage / "version.txt").write_text(sha256(archive) + "\n")
# version.txt is the readiness marker; an interrupted replacement fails
# closed instead of presenting a partially updated payload as ready.
(assets / "version.txt").unlink(missing_ok=True)
os.replace(stage / "runtime.tzst", assets / "runtime.tzst")
os.replace(stage / "version.txt", assets / "version.txt")
print("PowerVR runtime prepared: " + sha256(archive))
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--verify", action="store_true")
parser.add_argument("--cache-dir", type=Path, default=Path(os.environ.get(
"DROIDDECK_BUILD_CACHE", str(Path.home() / ".cache/droiddeck-build"))))
args = parser.parse_args()
if args.verify:
verify()
else:
assemble(ROOT, args.cache_dir)
if __name__ == "__main__":
main()
+335
View File
@@ -0,0 +1,335 @@
{
"archives": [
{
"files": [
{
"mode": 493,
"name": "x32/d3d8.dll",
"path": "dxvk/x32/d3d8.dll",
"sha256": "c9612be6aac99390156cdcd3b22054fba62cf68bfc948d753cc39282d37f67ab",
"size": 1658894
},
{
"mode": 493,
"name": "x32/d3d9.dll",
"path": "dxvk/x32/d3d9.dll",
"sha256": "fbd0e7d7aae39d5d623757ead228930c4be78cb3b16db6f352796577831ce36e",
"size": 7598094
},
{
"mode": 493,
"name": "x32/d3d10core.dll",
"path": "dxvk/x32/d3d10core.dll",
"sha256": "cd6052b1f6a02ab94fea5bfa3519e556fb353f585da4b64e3c810ef4cc37c808",
"size": 192526
},
{
"mode": 493,
"name": "x32/d3d11.dll",
"path": "dxvk/x32/d3d11.dll",
"sha256": "9bf51b5ab913e1bd84513b2b1608586bc0a651788df9e664b8135840b8c8c54d",
"size": 7942158
},
{
"mode": 493,
"name": "x32/dxgi.dll",
"path": "dxvk/x32/dxgi.dll",
"sha256": "d3772dc86267fe94eee7afc30c993f44297fd43b50210f1691f3d03ebf4d4402",
"size": 5738510
},
{
"mode": 493,
"name": "x64/d3d8.dll",
"path": "dxvk/x64/d3d8.dll",
"sha256": "cd870a8f5cdbfef33e7ccf7884d6f1c442e2c8ec22d6adea60fea3dbe83c32e2",
"size": 1499136
},
{
"mode": 493,
"name": "x64/d3d9.dll",
"path": "dxvk/x64/d3d9.dll",
"sha256": "4f80af96991073bb3dc25f3b93ec2c07ba25fcabb8a6e30ffd5eaae38c8465c7",
"size": 6934528
},
{
"mode": 493,
"name": "x64/d3d10core.dll",
"path": "dxvk/x64/d3d10core.dll",
"sha256": "4950e952ca291b13c0645322f1831414e77df87183ed2f81d5dde02c1fd43ff9",
"size": 978944
},
{
"mode": 493,
"name": "x64/d3d11.dll",
"path": "dxvk/x64/d3d11.dll",
"sha256": "3497d5f7dc78fa7affdba6777d3ab4aac7ec744d7e2c795fbf07dbff54058e6c",
"size": 7143424
},
{
"mode": 493,
"name": "x64/dxgi.dll",
"path": "dxvk/x64/dxgi.dll",
"sha256": "d6e0ca242dba6cb8606106a7fcb65268225520f03c68e36a365f44d65f863e74",
"size": 5230592
},
{
"mode": 420,
"name": "LICENSE",
"path": "licenses/dxvk-LICENSE",
"sha256": "a5cb1a6ded7d2d7e92d550ba28edd21be2d1d4044662b399887351023e30ce64",
"size": 1074
},
{
"mode": 420,
"name": "source-commit",
"path": "provenance/dxvk-source-commit",
"sha256": "cb748e54f2fcdca516189435647ea001dbd14f97e2df5b36fd2f13fc185a5dbf",
"size": 41
},
{
"mode": 420,
"name": "SHA256SUMS",
"path": "provenance/dxvk-SHA256SUMS",
"sha256": "8a106cb90288052cc91768b569980ed7381c89591fb7cea3bc6d0312c6f30a47",
"size": 802
},
{
"mode": 420,
"name": "downstream.patch",
"path": "licenses/dxvk-downstream.patch",
"sha256": "e44b8d656a37c3b1059bbf3dcbcf11922a00634301f2509024fb263a45e9f50e",
"size": 3604
},
{
"mode": 420,
"name": "source.tar.zst",
"path": "licenses/dxvk-source.tar.zst",
"sha256": "dfdebe8aa71b85af638f2565c1d5abe31417c6db643a827bcf0988e29ded55e7",
"size": 6043001
},
{
"mode": 420,
"name": "submodules.txt",
"path": "provenance/dxvk-submodules.txt",
"sha256": "01e74c750ca473590e17f1ca33f204b8272f84898ee6e8a8509be9740919092c",
"size": 472
}
],
"id": "dxvk",
"ignored": [
"x32/d3d10core.dll.a",
"x32/d3d11.dll.a",
"x32/d3d8.dll.a",
"x32/d3d9.dll.a",
"x32/dxgi.dll.a",
"x64/d3d10core.dll.a",
"x64/d3d11.dll.a",
"x64/d3d8.dll.a",
"x64/d3d9.dll.a",
"x64/dxgi.dll.a"
],
"provenance": {
"ci_run": "https://github.com/wallentx/DroidDeck/actions/runs/38119192562",
"repository_commit": "aee0ebd43557ef9964ba7f6a11d7d30efaf983ac"
},
"recipe_inputs": {
"tools/dxvk/build.sh": "f37efdc1dbcc511b0399e1027d582dfd09f689bddb434eed31c33d88867460ad",
"tools/dxvk/check_present_sync.py": "42e2a590e17c1f53e5cd4100ef3d19a5bdcce31a6d7a18fbf9961f4ef27d5063",
"tools/dxvk/patches/0001-check-direct3d-bc-formats.patch": "d38fc4d773b7974498dcb377dbaa883c9bba36aefa3235b39bca69d6dd220c77",
"tools/dxvk/patches/0002-present-semaphore-per-swapchain-image.patch": "c802789a33099d3efc3413a297e2b752f8eb84c18cbfbdfc04e188f4090410d0",
"tools/dxvk/source.env": "e49b0757f203f88783360c06118f60945242fde8738419e0b27cf2531bf3a365"
},
"sha256": "d08dd962ced3482883ad9e9eb4903a4d27a3756b4f989a97ecdfcccb53fbee66",
"size": 24063241,
"url": "https://github.com/wallentx/DroidDeck/releases/download/v0.3.2-progress.20261011.3/dxvk-aee0ebd.zip"
},
{
"files": [
{
"mode": 420,
"name": "libVkLayer_window_system_integration.so",
"path": "wsi/libVkLayer_window_system_integration.so",
"sha256": "d07b961181b9547fd48ad9f05cc6d3b808b824676eb5a186fe3feb8caa013f19",
"size": 436888
},
{
"mode": 420,
"name": "VkLayer_window_system_integration.json",
"path": "wsi/VkLayer_window_system_integration.json",
"sha256": "a1df8b1cee7315015d8fe82534451e373ae4d9cb2adfc232c68346ecbf2818ee",
"size": 3683
},
{
"mode": 420,
"name": "LICENSE",
"path": "licenses/wsi-LICENSE",
"sha256": "5eb8d2da52230d2d66ce078a89ae0173aac63e2e73bed5f907a34736d114ea30",
"size": 1086
},
{
"mode": 420,
"name": "source-commit",
"path": "provenance/wsi-source-commit",
"sha256": "8367150b20502af36c472651850694a15a3e2a1fd6b6beb1f6e12a85a97824f5",
"size": 41
},
{
"mode": 420,
"name": "SHA256SUMS",
"path": "provenance/wsi-SHA256SUMS",
"sha256": "fda6f61028659648801de0e3a6fe1676efd99e1551881a5db8630970eae86158",
"size": 108
},
{
"mode": 420,
"name": "downstream.patch",
"path": "licenses/wsi-downstream.patch",
"sha256": "e2ed113d22f05563248ef606c774c22658b184fbc05912229007cd5281027e78",
"size": 769
},
{
"mode": 420,
"name": "source.tar.zst",
"path": "licenses/wsi-source.tar.zst",
"sha256": "22ae7c2d8aa3dfffdda601c3442d1966ab53ad225acdfadee69ba38974d0c4c5",
"size": 209468
},
{
"mode": 420,
"name": "vulkan-headers-commit",
"path": "provenance/wsi-vulkan-headers-commit",
"sha256": "16706d6cdbeb788426a90d66574dfd71068c4d993d39e76ec5c281b1f30dc7a6",
"size": 41
}
],
"id": "wsi",
"ignored": [],
"provenance": {
"ci_run": "https://github.com/wallentx/DroidDeck/actions/runs/38047627963",
"repository_commit": "abe58618a5194f1f15499cbd5f9ec75503782556",
"vulkan_headers_licenses": {
"note": "Added from tracked assembly inputs; the original WSI archive and compiled library are unchanged.",
"revision": "8d6039a455a7ecc7d2a592ff97f62db4e59b70bf",
"source_urls": [
"https://raw.githubusercontent.com/KhronosGroup/Vulkan-Headers/8d6039a455a7ecc7d2a592ff97f62db4e59b70bf/LICENSE.md",
"https://raw.githubusercontent.com/KhronosGroup/Vulkan-Headers/8d6039a455a7ecc7d2a592ff97f62db4e59b70bf/LICENSES/MIT.txt"
]
}
},
"recipe_inputs": {
"tools/vulkan-wsi/build.sh": "9e403151c58e6b2ee15241f525c4bacb2495f072191da6a63065e7fcc25b3b3c",
"tools/vulkan-wsi/licenses/Vulkan-Headers/LICENSE.md": "95ad366d23fadf701d355bc45fb8b82ae2d700239471d35d41286ac3b08ff903",
"tools/vulkan-wsi/licenses/Vulkan-Headers/MIT.txt": "1ca3502222d967f3be5751c55f6b7ee735b5383909c3b501495f54b216dbf227",
"tools/vulkan-wsi/patches/0001-link-x11-external-memory.patch": "e2ed113d22f05563248ef606c774c22658b184fbc05912229007cd5281027e78",
"tools/vulkan-wsi/source.env": "71a88087265a09b4ce06e7c9b98ef6799c6a7657cc6ef9084de663e96f5cfe63"
},
"sha256": "348f9ec42159c1ee6e2baba4312a5e845d26687238f29e3f4a1b0c3c97e13b3c",
"size": 362717,
"url": "https://github.com/wallentx/DroidDeck/releases/download/v0.3.2-progress.20261010.4/wsi-abe5861.zip"
},
{
"files": [
{
"mode": 493,
"name": "dxvk-2.6.2/x32/d3d10core.dll",
"path": "dxvk-2.6.2/x32/d3d10core.dll",
"sha256": "b34b479fa0bce29eba6dcff5b1f8584c2ae699d53a123668590f8a2b84e84094",
"size": 176142
},
{
"mode": 493,
"name": "dxvk-2.6.2/x32/d3d11.dll",
"path": "dxvk-2.6.2/x32/d3d11.dll",
"sha256": "858d1a848dd5023191cb16cd986e0f00008faf5df8a87b5c835b56cf4b646910",
"size": 4845582
},
{
"mode": 493,
"name": "dxvk-2.6.2/x32/d3d8.dll",
"path": "dxvk-2.6.2/x32/d3d8.dll",
"sha256": "617459c8d1239f98687f8157bdaec85738ee4699885ed7d1ff13deb32609c759",
"size": 1658894
},
{
"mode": 493,
"name": "dxvk-2.6.2/x32/d3d9.dll",
"path": "dxvk-2.6.2/x32/d3d9.dll",
"sha256": "00bc142e98ddad1e334a4d88fa630038e092b0758b3d79e295172b181a4c772d",
"size": 4460558
},
{
"mode": 493,
"name": "dxvk-2.6.2/x32/dxgi.dll",
"path": "dxvk-2.6.2/x32/dxgi.dll",
"sha256": "67d7ca4a4f8f66baabd381c73b52a8e85870083e868ed474a4bc58b7da486883",
"size": 3137550
},
{
"mode": 493,
"name": "dxvk-2.6.2/x64/d3d10core.dll",
"path": "dxvk-2.6.2/x64/d3d10core.dll",
"sha256": "565154a0763c6460843fe47e5aaec62e609163d9995a922d5e19e85027fe2f88",
"size": 155662
},
{
"mode": 493,
"name": "dxvk-2.6.2/x64/d3d11.dll",
"path": "dxvk-2.6.2/x64/d3d11.dll",
"sha256": "5b63515a432d19302f7dc81dd2ee5bf40043683b5064a2bce03a2b6d27dcce5d",
"size": 4399118
},
{
"mode": 493,
"name": "dxvk-2.6.2/x64/d3d8.dll",
"path": "dxvk-2.6.2/x64/d3d8.dll",
"sha256": "dfd837c3467eeb15f69a773e18bbc0550cb69c9e33d5d57b4ea42c5f63bfdc4b",
"size": 1544206
},
{
"mode": 493,
"name": "dxvk-2.6.2/x64/d3d9.dll",
"path": "dxvk-2.6.2/x64/d3d9.dll",
"sha256": "01e7ae2b0544b6031fe695fd16fbc76786ded57fdbe3f6bd11eee7c98d2c370d",
"size": 4108302
},
{
"mode": 493,
"name": "dxvk-2.6.2/x64/dxgi.dll",
"path": "dxvk-2.6.2/x64/dxgi.dll",
"sha256": "074616e1af172edf175f3fc6ed7ca30f6c685a70875eed3af10797a10840ed39",
"size": 2891790
}
],
"format": "tar.gz",
"id": "dxvk-xclipse",
"ignored": [],
"provenance": {
"note": "Unmodified upstream release, selected on Samsung Xclipse: its 128 bytes of push constants predate DXVK 3's 256-byte requirement. Covered by the zlib license already shipped as licenses/dxvk-LICENSE.",
"upstream_release": "https://github.com/doitsujin/dxvk/releases/tag/v2.6.2"
},
"recipe_inputs": {},
"sha256": "17761876556afd55736cb895d184f5a1c55d43350f1b1e3b129f8d28706d7992",
"size": 10107492,
"url": "https://github.com/doitsujin/dxvk/releases/download/v2.6.2/dxvk-2.6.2.tar.gz"
}
],
"format": 1,
"hybris": {
"provenance": {
"apk_ci_run": "https://github.com/wallentx/DroidDeck/actions/runs/38123715308",
"extracted_from_apk": "https://github.com/wallentx/DroidDeck/releases/download/v0.3.2-progress.20261011.3/DroidDeck-0.3.2-1b6185b.apk",
"note": "APK build reused a cached bridge. Original source and compiler metadata are preserved in build-manifest.json; no APK commit is claimed as the bridge producer.",
"upstream_source_commit": "bc8cb3586b79d208fd21b925fa0209b3e432e008"
},
"recipe_inputs": {
"tools/hybris/build_runtime.sh": "bc83472ecfd886841c8c2c436080cdee0a27ce0d860ffbffe45a75fbc6b2b21d",
"tools/hybris/patches/0001-dxvk-bc-profile.patch": "b90605e51256595de4453352865aa198e59bd2d392ac6b7c2a60f38c57727c9d",
"tools/hybris/powervr-hal-version.patch": "d3ed8ca03e5a874b9dc46651983117760c7490b96127335625d0480a2b85e66f",
"tools/hybris/source.env": "9ae7985f2052dbcc8b9666494bc8a711ec85013f6a27d6d72d9729c32b919dd8"
},
"sha256": "f4f12c26ed21003c2c98a7cececd76c8a3b332d79ece9d1f963cf3b9e8943978",
"size": 5552486,
"tree_sha256": "de9cc2c4107bf396e4f963d7e91f936a966593fb1df680a0b5d43db0f9fef4e1",
"url": "https://github.com/wallentx/DroidDeck/releases/download/v0.3.2-progress.20261011.3/hybris-runtime-f4f12c26.tzst"
}
}
+11
View File
@@ -1,5 +1,6 @@
"""Reject an APK with missing or stale session helpers, including cached local bundles."""
from pathlib import Path
import importlib.util
import sys
from zipfile import ZipFile
@@ -33,6 +34,16 @@ def check(apk, overlay=OVERLAY):
continue
if content != source.read_bytes():
errors.append('stale ' + asset)
if overlay == OVERLAY:
spec = importlib.util.spec_from_file_location('powervr_fetch',
OVERLAY.parents[1] / 'powervr/fetch.py')
runtime = importlib.util.module_from_spec(spec)
spec.loader.exec_module(runtime)
try:
runtime.verify_archive(package.read('assets/hybris/runtime.tzst'),
package.read('assets/hybris/version.txt').decode('ascii'))
except (KeyError, ValueError, OSError) as error:
errors.append('invalid PowerVR runtime: ' + str(error))
return errors
+14 -1
View File
@@ -1,6 +1,7 @@
"""Attest prepared runtime inputs and reject stale local or CI APK payloads."""
import hashlib
import gzip
import importlib.util
import json
from pathlib import Path
import subprocess
@@ -16,6 +17,7 @@ SOURCE_PATHS = ['app/build.gradle', 'app/src/main/cpp/fakeinput_steam.cpp', 'app
'tools/linuxfs', 'tools/proot', 'tools/aaudio-sink', 'tools/directaudio',
'tools/gamescope/release.env', 'tools/droiddeck-esync/release.env',
'tools/mangoapp', 'tools/msitools', 'tools/comet', 'tools/build_local.sh',
'tools/powervr', 'tools/hybris', 'tools/dxvk', 'tools/vulkan-wsi',
'tools/release/runtime_inputs.py', 'app/src/main/assets/desktop-removal',
'tools/quest', 'app/src/main/cpp/adrenotools/src/hook/kgsl.h',
'app/src/main/assets/graphics_driver/adrenotools-turnip25.1.0.tzst']
@@ -42,7 +44,7 @@ def sources(root):
def outputs(root):
result = {}
for tree in ['linuxfs', 'directaudio', 'droiddeck-esync', 'desktop-removal']:
for tree in ['linuxfs', 'directaudio', 'droiddeck-esync', 'desktop-removal', 'hybris']:
base = root / 'app/src/main/assets' / tree
for path in base.rglob('*'):
if path.is_file() and not any(part.startswith('.') for part in path.relative_to(base).parts):
@@ -67,6 +69,8 @@ def required():
paths += ['assets/linuxfs/i386/libfaultreport.so']
paths += ['assets/linuxfs/usr/local/lib/droiddeck-msitools/' + name for name in
['msiinfo', 'cabextract', '7z', '7z.so', 'libmsi-1.0.so.0', 'libgsf-1.so.114', 'libgcab-1.0.so.0']]
paths += ['assets/linuxfs/usr/local/lib/droiddeck-xclipse/' + name for name in
['libVkLayer_droiddeck_xclipse.so', 'VkLayer_droiddeck_xclipse.json']]
paths += ['assets/linuxfs/usr/local/lib/mangoapp/' + name for name in
['mangoapp', 'libfmt.so.10', 'libspdlog.so.1.13', 'libglfw.so.3', 'libtraceevent.so.1', 'libtracefs.so.1']]
paths += ['assets/linuxfs/usr/local/lib/droiddeck-comet/' + name for name in
@@ -81,9 +85,17 @@ def required():
paths += ['assets/desktop-removal/' + name for name in
['lxqt-r1.tsv.gzip', 'kde-remove.tsv.gzip', 'kde-keep.txt.gzip',
'emulators-keep.txt.gzip', 'versions.txt', 'sources.json']]
paths += ['assets/hybris/runtime.tzst', 'assets/hybris/version.txt']
return paths
def verify_powervr(root):
spec = importlib.util.spec_from_file_location('powervr_fetch', ROOT / 'tools/powervr/fetch.py')
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
module.verify(root)
def record(root=ROOT):
# Refresh scripts even on a CI native-cache hit; these are source, not cached binaries.
if root == ROOT:
@@ -96,6 +108,7 @@ def record(root=ROOT):
missing = [name for name in required() if name not in paths or not (root / paths[name]).is_file()]
if missing:
raise ValueError('Missing runtime inputs:\n' + '\n'.join(missing))
verify_powervr(root)
for name, path in paths.items():
if name.startswith('assets/desktop-removal/') and name.endswith('.gzip'):
try:
+1 -1
View File
@@ -6,7 +6,7 @@ cd "$repo_root"
if [[ $(uname -s) == Linux ]]; then
exec python3 -m unittest discover -s tools/tests "$@"
fi
image=${DROIDDECK_BUILD_IMAGE:-droiddeck-local-cross:24.04-v3}
image=${DROIDDECK_BUILD_IMAGE:-droiddeck-local-cross:24.04-v4}
python3 tools/docker_preflight.py "$image"
exec docker run --rm --platform linux/amd64 --user "$(id -u):$(id -g)" \
-v "$repo_root:/src:ro" -w /src "$image" python3 -m unittest discover -s tools/tests "$@"
+277
View File
@@ -0,0 +1,277 @@
#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 unsigned identity_serial = 1;
static int identity_denied, 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, int arg);
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);
}
/* The intercepted DRM calls all take an integer argument. Keep that contract
* explicit; native_import's argument-free F_GETFD uses libc after #undef above. */
static int fixture_fcntl(int fd, int op, int arg) {
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);
}
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) == -EOPNOTSUPP);
assert(count_fds() == baseline);
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");
}
+26
View File
@@ -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()
+181
View File
@@ -8,6 +8,7 @@ import subprocess
import sys
import tempfile
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"))
@@ -26,6 +27,137 @@ def config_text(entries):
return '"InstallConfigStore" { "Software" { "Valve" { "Steam" { "CompatToolMapping" { %s } } } } }' % mapping
class SystemGraphicsLaunchTest(unittest.TestCase):
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 GameEnvironmentTest(unittest.TestCase):
def test_the_install_script_evaluator_gets_its_scripts_marked_first(self):
with tempfile.TemporaryDirectory() as tmp:
@@ -87,6 +219,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)
+102
View File
@@ -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",
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)
+291
View File
@@ -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()
+228
View File
@@ -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()
+19
View File
@@ -6,6 +6,7 @@ import subprocess
import tarfile
import tempfile
import unittest
from unittest.mock import patch
from zipfile import ZipFile
@@ -19,6 +20,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)
@@ -69,6 +74,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')
+91
View File
@@ -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()
+73
View File
@@ -0,0 +1,73 @@
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", 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'
+ 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,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()
+47
View File
@@ -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()
+63
View File
@@ -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;
}
+217
View File
@@ -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;
}
+34
View File
@@ -0,0 +1,34 @@
#!/usr/bin/env bash
# CI build of a vendor-neutral X11 surface/swapchain layer.
set -euo pipefail
root=$(cd "$(dirname "$0")/../.." && pwd)
. "$root/tools/vulkan-wsi/source.env"
mkdir -p "${1:?output directory required}"
out=$(cd "$1" && pwd)
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
fetch() {
git init -q "$3"
git -C "$3" fetch --depth=1 "$1" "$2"
git -C "$3" checkout -q --detach FETCH_HEAD
test "$(git -C "$3" rev-parse HEAD)" = "$2"
}
fetch https://github.com/ginkage/vulkan-wsi-layer.git "$WSI_REVISION" "$work/source"
fetch https://github.com/KhronosGroup/Vulkan-Headers.git "$VULKAN_HEADERS_REVISION" "$work/headers"
git -C "$work/source" apply --check "$root/tools/vulkan-wsi/patches/0001-link-x11-external-memory.patch"
git -C "$work/source" apply "$root/tools/vulkan-wsi/patches/0001-link-x11-external-memory.patch"
cmake -S "$work/source" -B "$work/build" -G Ninja -DCMAKE_BUILD_TYPE=Release \
-DCMAKE_INSTALL_PREFIX=/usr -DVULKAN_CXX_INCLUDE="$work/headers/include" \
-DBUILD_WSI_HEADLESS=OFF -DBUILD_WSI_WAYLAND=OFF -DBUILD_WSI_DISPLAY=OFF -DBUILD_WSI_X11=ON \
-DSELECT_EXTERNAL_ALLOCATOR=dma_buf_heaps -DWSIALLOC_MEMORY_HEAP_NAME=system -DKERNEL_HEADER_DIR=/usr/include
cmake --build "$work/build" --parallel 4
DESTDIR="$work/stage" cmake --install "$work/build"
cp "$work/stage/usr/share/vulkan/implicit_layer.d/"* "$out/"
cp "$root/tools/vulkan-wsi/patches/0001-link-x11-external-memory.patch" "$out/downstream.patch"
cp "$work/source/LICENSE" "$out/LICENSE"
mkdir -p "$out/licenses/Vulkan-Headers"
cp "$root/tools/vulkan-wsi/licenses/Vulkan-Headers/"* "$out/licenses/Vulkan-Headers/"
printf '%s\n' "$WSI_REVISION" > "$out/source-commit"
printf '%s\n' "$VULKAN_HEADERS_REVISION" > "$out/vulkan-headers-commit"
tar --exclude-vcs --zstd -cf "$out/source.tar.zst" -C "$work/source" .
(cd "$out" && sha256sum ./*.so > SHA256SUMS)
@@ -0,0 +1,19 @@
Copyright 2015-2026 The Khronos Group Inc.
Files in this repository fall under one of these licenses:
- `Apache-2.0`
- `MIT`
Note: With the exception of `parse_dependency.py`, which is based on an
external file, files using the `MIT` license also fall under `Apache-2.0`.
Example:
```
SPDX-License-Identifier: Apache-2.0 OR MIT
```
Full license text of these licenses is available at:
* Apache-2.0: https://opensource.org/licenses/Apache-2.0
* MIT: https://opensource.org/licenses/MIT
@@ -0,0 +1,9 @@
MIT License
Copyright (c) 2015-2023 The Khronos Group Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,16 @@
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -421,6 +421,13 @@
cp ${PROJECT_SOURCE_DIR}/layer/VkLayer_window_system_integration.json ${CMAKE_CURRENT_BINARY_DIR}
${JSON_COMMANDS})
+# X11 DRI3 uses these shared sources even when Wayland and display are disabled.
+if(BUILD_WSI_X11 AND NOT BUILD_WSI_WAYLAND AND NOT BUILD_WSI_DISPLAY)
+ target_sources(${PROJECT_NAME} PRIVATE
+ wsi/extensions/external_memory_extension.cpp
+ wsi/image_backing_memory_external.cpp)
+endif()
+
# Install the layer and its manifest into a Vulkan implicit layer directory. Upstream leaves this to
# manual copying; the fork adds install rules so the Debian package picks up the .so and JSON.
install(TARGETS ${PROJECT_NAME} DESTINATION share/vulkan/implicit_layer.d/)
+2
View File
@@ -0,0 +1,2 @@
WSI_REVISION=40cfec09d0e2d42c5e1f2642cf4cba11e7008112
VULKAN_HEADERS_REVISION=8d6039a455a7ecc7d2a592ff97f62db4e59b70bf