From 96e4bd4eab03dee81d21b27eaed3a93858050dbd Mon Sep 17 00:00:00 2001 From: MaxsTechReview Date: Thu, 26 Nov 2026 05:34:42 -0500 Subject: [PATCH] fix(fex): x86-64 programs on Wayland render on the GPU (#3174) * fix(fex): x86-64 programs on Wayland render on the GPU * fix(fex): address review on the Wayland and EGL thunks Keep the GLES overlay on the 64-bit EGL thunk only, filter EGL extensions whose entrypoints the guest lacks, accept EGLDeviceEXT displays, make the Wayland display check thread-safe, bound event signature copies, reject a second listener without freeing the first and guard wl_array_add growth. The FEX updater now removes thunk libraries a new build no longer ships, so an older 32-bit Wayland or EGL thunk cannot be enabled by the new config. * fix(fex): check every EGL extension entrypoint and every host device EGL_EXTENSIONS now hides an extension unless the guest exports all of its entrypoints, using a table built from the EGL registry. eglGetDisplay asks the host for its device count before matching EGLDeviceEXT handles. * fix(fex): pick the eglGetDisplay platform the way Mesa does A legacy eglGetDisplay handle now follows EGL_PLATFORM or EGL_DISPLAY first, then Wayland detection, and only then the X11 mapping, so device handles no longer depend on enumerating host devices. --- README.md | 1 + ...and-and-egl-thunks-for-64-bit-guests.patch | 982 ++++++++++++++++++ .../overlay/usr/local/bin/droiddeck-fex | 12 +- .../usr/local/bin/droiddeck-fex-update | 9 +- tools/tests/test_droiddeck_fex.py | 16 + tools/tests/test_fex_install.py | 40 +- tools/tests/test_fex_wayland_egl_thunks.py | 151 +++ 7 files changed, 1206 insertions(+), 5 deletions(-) create mode 100644 tools/fex/patches/0019-wayland-and-egl-thunks-for-64-bit-guests.patch create mode 100644 tools/tests/test_fex_wayland_egl_thunks.py diff --git a/README.md b/README.md index ead893cf4..576cf61c5 100644 --- a/README.md +++ b/README.md @@ -68,6 +68,7 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V - Runtime, shim, input and controller work build on WinNative and Bannerlator by maxjivi05. - mmap ring buffer controller input by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)). - [FEX](https://github.com/FEX-Emu/FEX) (MIT) runs x86 code. DroidDeck's build puts the platform name under `AT_PLATFORM` so [sharun](https://github.com/VHSgunzo/sharun) AppImages by VHSgunzo (MIT) start through its [userland-execve](https://crates.io/crates/userland-execve) loader (MIT), and its GL thunk hands X errors to the program's own error handler. FEX's code disk cache was checked in its source. The fix for host stack left behind when a program leaves a signal handler without returning follows the approach suggested in [FEX-Emu/FEX#2487](https://github.com/FEX-Emu/FEX/issues/2487). The host stack fix for system calls that end a block is a backport of Ryan Houdek's [FEX-Emu/FEX#6122](https://github.com/FEX-Emu/FEX/pull/6122). +- x86-64 programs on Wayland reach the GPU through FEX's Wayland client, wayland-egl and EGL thunks. The guest `wl_list` and `wl_array` helpers follow [libwayland](https://gitlab.freedesktop.org/wayland/wayland)'s `src/wayland-util.c` (MIT). The EGL extension table comes from the [Khronos EGL registry](https://github.com/KhronosGroup/EGL-Registry) (Apache-2.0) and Mesa's `egl_other.xml` (MIT). - x86 AppImages, and arm64 ones whose runtime can't unpack on Android, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence. - DwarFS AppImages are unpacked without proot by `dwarfsextract` from [DwarFS](https://github.com/mhx/dwarfs) by Marcus Holland-Moritz (MIT), the release binary uruntime embeds, taken out of its self-extracting wrapper and shipped with its licence. - x86 programs linking OpenSSL 3 use the copy in the [Steam Linux Runtime 4.0](https://gitlab.steamos.cloud/steamrt/steamrt). x86 Linux games get the `/etc/asound.conf` that [pressure-vessel](https://gitlab.steamos.cloud/steamrt/steam-runtime-tools) writes. diff --git a/tools/fex/patches/0019-wayland-and-egl-thunks-for-64-bit-guests.patch b/tools/fex/patches/0019-wayland-and-egl-thunks-for-64-bit-guests.patch new file mode 100644 index 000000000..4e365315e --- /dev/null +++ b/tools/fex/patches/0019-wayland-and-egl-thunks-for-64-bit-guests.patch @@ -0,0 +1,982 @@ +diff --git a/Data/ThunksDB.json b/Data/ThunksDB.json +index 886379a..7844b27 100644 +--- a/Data/ThunksDB.json ++++ b/Data/ThunksDB.json +@@ -49,6 +49,24 @@ + "@PREFIX_LIB@/libwayland-client.so.0.20.0" + ] + }, ++ "EGL": { ++ "Library" : "libEGL-guest.so", ++ "Overlay": [ ++ "@PREFIX_LIB@/libEGL.so", ++ "@PREFIX_LIB@/libEGL.so.1", ++ "@PREFIX_LIB@/libEGL.so.1.1.0", ++ "@PREFIX_LIB@/libGLESv2.so.2", ++ "@PREFIX_LIB@/libGLESv2.so.2.1.0" ++ ] ++ }, ++ "WaylandEGL": { ++ "Library" : "libwayland-egl-guest.so", ++ "Overlay": [ ++ "@PREFIX_LIB@/libwayland-egl.so", ++ "@PREFIX_LIB@/libwayland-egl.so.1", ++ "@PREFIX_LIB@/libwayland-egl.so.1.0.0" ++ ] ++ }, + "cuda": { + "Library" : "libcuda-guest.so", + "Overlay": [ +diff --git a/ThunkLibs/GuestLibs/CMakeLists.txt b/ThunkLibs/GuestLibs/CMakeLists.txt +index bf666d9..72b0832 100644 +--- a/ThunkLibs/GuestLibs/CMakeLists.txt ++++ b/ThunkLibs/GuestLibs/CMakeLists.txt +@@ -211,6 +211,21 @@ if (BITNESS EQUAL 64) + target_include_directories_from_pkgconfig(libasound-guest-deps alsa) + add_guest_lib(asound "libasound.so.2") + ++ generate(libwayland-client ${CMAKE_CURRENT_SOURCE_DIR}/../libwayland-client/libwayland-client_interface.cpp) ++ add_guest_lib(wayland-client "libwayland-client.so.0.20.0") ++ target_include_directories_from_pkgconfig(libwayland-client-guest-deps wayland-client /usr/include/wayland) ++ ++ generate(libwayland-egl ${CMAKE_CURRENT_SOURCE_DIR}/../libwayland-egl/libwayland-egl_interface.cpp) ++ add_guest_lib(wayland-egl "libwayland-egl.so.1") ++ target_include_directories_from_pkgconfig(libwayland-egl-guest-deps wayland-egl /usr/include/wayland) ++ ++ generate(libEGL ${CMAKE_CURRENT_SOURCE_DIR}/../libEGL/libEGL_interface.cpp) ++ target_include_directories_from_pkgconfig(libEGL-guest-deps egl) ++ add_guest_lib(EGL "libEGL.so.1") ++ target_link_libraries(EGL-guest PRIVATE GL-guest) ++ target_link_libraries(EGL-guest PRIVATE PlaceholderX11) ++ target_include_directories_from_pkgconfig(libEGL-guest-deps "xcb;x11") ++ + # disabled for now, headers are platform specific + # find_package(SDL2 REQUIRED) + # generate(libSDL2) +@@ -229,10 +244,6 @@ if (BITNESS EQUAL 64) + add_guest_lib(drm "libdrm.so.2") + endif() + +-generate(libwayland-client ${CMAKE_CURRENT_SOURCE_DIR}/../libwayland-client/libwayland-client_interface.cpp) +-add_guest_lib(wayland-client "libwayland-client.so.0.20.0") +-target_include_directories_from_pkgconfig(libwayland-client-guest-deps wayland-client /usr/include/wayland) +- + generate(libVDSO ${CMAKE_CURRENT_SOURCE_DIR}/../libVDSO/libVDSO_interface.cpp) + add_guest_lib(VDSO "linux-vdso.so.1") + # Can't use a stack protector because otherwise cross-compiling fails +@@ -271,11 +282,6 @@ target_include_directories_from_pkgconfig(libGL-guest-deps gl) + target_include_directories_from_pkgconfig(libGL-guest-deps "xcb;x11;xrandr;xrender") + add_guest_lib(GL "libGL.so.1") + +-generate(libEGL ${CMAKE_CURRENT_SOURCE_DIR}/../libEGL/libEGL_interface.cpp) +-target_include_directories_from_pkgconfig(libEGL-guest-deps egl) +-add_guest_lib(EGL "libEGL.so.1") +-target_link_libraries(EGL-guest PRIVATE GL-guest) +- + # libGL must pull in libX11.so, so generate a placeholder libX11.so to link against + add_library(PlaceholderX11 SHARED ../libX11/libX11_NativeGuest.cpp) + target_link_options(PlaceholderX11 PRIVATE "LINKER:-soname,libX11.so.6") +diff --git a/ThunkLibs/HostLibs/CMakeLists.txt b/ThunkLibs/HostLibs/CMakeLists.txt +index 8d18d0e..c10066f 100644 +--- a/ThunkLibs/HostLibs/CMakeLists.txt ++++ b/ThunkLibs/HostLibs/CMakeLists.txt +@@ -167,13 +167,19 @@ foreach(GUEST_BITNESS IN LISTS BITNESS_LIST) + target_include_directories_from_pkgconfig(libvulkan-${GUEST_BITNESS}-deps "xcb;x11;xrandr;xrender") + add_host_lib(vulkan ${GUEST_BITNESS}) + +- generate(libwayland-client ${CMAKE_CURRENT_SOURCE_DIR}/../libwayland-client/libwayland-client_interface.cpp ${GUEST_BITNESS}) +- add_host_lib(wayland-client ${GUEST_BITNESS}) +- target_include_directories_from_pkgconfig(libwayland-client-${GUEST_BITNESS}-deps wayland-client /usr/include/wayland) +- +- generate(libEGL ${CMAKE_CURRENT_SOURCE_DIR}/../libEGL/libEGL_interface.cpp ${GUEST_BITNESS}) +- target_include_directories_from_pkgconfig(libEGL-${GUEST_BITNESS}-deps egl) +- add_host_lib(EGL ${GUEST_BITNESS}) ++ if (GUEST_BITNESS EQUAL 64) ++ generate(libwayland-client ${CMAKE_CURRENT_SOURCE_DIR}/../libwayland-client/libwayland-client_interface.cpp ${GUEST_BITNESS}) ++ add_host_lib(wayland-client ${GUEST_BITNESS}) ++ target_include_directories_from_pkgconfig(libwayland-client-${GUEST_BITNESS}-deps wayland-client /usr/include/wayland) ++ ++ generate(libwayland-egl ${CMAKE_CURRENT_SOURCE_DIR}/../libwayland-egl/libwayland-egl_interface.cpp ${GUEST_BITNESS}) ++ add_host_lib(wayland-egl ${GUEST_BITNESS}) ++ target_include_directories_from_pkgconfig(libwayland-egl-${GUEST_BITNESS}-deps wayland-egl /usr/include/wayland) ++ ++ generate(libEGL ${CMAKE_CURRENT_SOURCE_DIR}/../libEGL/libEGL_interface.cpp ${GUEST_BITNESS}) ++ target_include_directories_from_pkgconfig(libEGL-${GUEST_BITNESS}-deps "egl;xcb;x11") ++ add_host_lib(EGL ${GUEST_BITNESS}) ++ endif() + + generate(libGL ${CMAKE_CURRENT_SOURCE_DIR}/../libGL/libGL_interface.cpp ${GUEST_BITNESS}) + target_include_directories_from_pkgconfig(libGL-${GUEST_BITNESS}-deps gl) +diff --git a/ThunkLibs/libEGL/libEGL_Guest.cpp b/ThunkLibs/libEGL/libEGL_Guest.cpp +index c157f00..196c7e8 100644 +--- a/ThunkLibs/libEGL/libEGL_Guest.cpp ++++ b/ThunkLibs/libEGL/libEGL_Guest.cpp +@@ -5,11 +5,22 @@ desc: Depends on glXGetProcAddress thunk + $end_info$ + */ + ++#define EGL_EGLEXT_PROTOTYPES 1 + #include + #include ++#include ++#include + ++#ifndef _GNU_SOURCE ++#define _GNU_SOURCE ++#endif ++#include + #include + #include ++#include ++#include ++#include ++#include + + #include "common/Guest.h" + +@@ -17,12 +28,128 @@ $end_info$ + + typedef void voidFunc(); + ++static void* Self() { ++ static void* self = [] { ++ Dl_info info {}; ++ return dladdr(reinterpret_cast(&Self), &info) && info.dli_fname ? dlopen(info.dli_fname, RTLD_LAZY | RTLD_NOLOAD) : nullptr; ++ }(); ++ return self; ++} ++ ++static constexpr std::pair ExtensionEntrypoints[] = { ++ {"EGL_ANDROID_blob_cache", "eglSetBlobCacheFuncsANDROID"}, ++ {"EGL_ANDROID_create_native_client_buffer", "eglCreateNativeClientBufferANDROID"}, ++ {"EGL_ANDROID_get_frame_timestamps", "eglGetCompositorTimingSupportedANDROID eglGetCompositorTimingANDROID eglGetNextFrameIdANDROID eglGetFrameTimestampSupportedANDROID eglGetFrameTimestampsANDROID"}, ++ {"EGL_ANDROID_get_native_client_buffer", "eglGetNativeClientBufferANDROID"}, ++ {"EGL_ANDROID_native_fence_sync", "eglDupNativeFenceFDANDROID"}, ++ {"EGL_ANDROID_presentation_time", "eglPresentationTimeANDROID"}, ++ {"EGL_ANGLE_query_surface_pointer", "eglQuerySurfacePointerANGLE"}, ++ {"EGL_ANGLE_sync_control_rate", "eglGetMscRateANGLE"}, ++ {"EGL_EXT_client_sync", "eglClientSignalSyncEXT"}, ++ {"EGL_EXT_compositor", "eglCompositorSetContextListEXT eglCompositorSetContextAttributesEXT eglCompositorSetWindowListEXT eglCompositorSetWindowAttributesEXT eglCompositorBindTexWindowEXT eglCompositorSetSizeEXT eglCompositorSwapPolicyEXT"}, ++ {"EGL_EXT_device_base", "eglQueryDeviceAttribEXT eglQueryDeviceStringEXT eglQueryDevicesEXT eglQueryDisplayAttribEXT"}, ++ {"EGL_EXT_device_enumeration", "eglQueryDevicesEXT"}, ++ {"EGL_EXT_device_persistent_id", "eglQueryDeviceBinaryEXT"}, ++ {"EGL_EXT_device_query", "eglQueryDeviceAttribEXT eglQueryDeviceStringEXT eglQueryDisplayAttribEXT"}, ++ {"EGL_EXT_image_dma_buf_import_modifiers", "eglQueryDmaBufFormatsEXT eglQueryDmaBufModifiersEXT"}, ++ {"EGL_EXT_output_base", "eglGetOutputLayersEXT eglGetOutputPortsEXT eglOutputLayerAttribEXT eglQueryOutputLayerAttribEXT eglQueryOutputLayerStringEXT eglOutputPortAttribEXT eglQueryOutputPortAttribEXT eglQueryOutputPortStringEXT"}, ++ {"EGL_EXT_platform_base", "eglGetPlatformDisplayEXT eglCreatePlatformWindowSurfaceEXT eglCreatePlatformPixmapSurfaceEXT"}, ++ {"EGL_EXT_stream_consumer_egloutput", "eglStreamConsumerOutputEXT"}, ++ {"EGL_EXT_surface_compression", "eglQuerySupportedCompressionRatesEXT"}, ++ {"EGL_EXT_swap_buffers_with_damage", "eglSwapBuffersWithDamageEXT"}, ++ {"EGL_EXT_sync_reuse", "eglUnsignalSyncEXT"}, ++ {"EGL_HI_clientpixmap", "eglCreatePixmapSurfaceHI"}, ++ {"EGL_KHR_cl_event2", "eglCreateSync64KHR"}, ++ {"EGL_KHR_debug", "eglDebugMessageControlKHR eglQueryDebugKHR eglLabelObjectKHR"}, ++ {"EGL_KHR_display_reference", "eglQueryDisplayAttribKHR"}, ++ {"EGL_KHR_fence_sync", "eglCreateSyncKHR eglDestroySyncKHR eglClientWaitSyncKHR eglGetSyncAttribKHR"}, ++ {"EGL_KHR_image", "eglCreateImageKHR eglDestroyImageKHR"}, ++ {"EGL_KHR_image_base", "eglCreateImageKHR eglDestroyImageKHR"}, ++ {"EGL_KHR_lock_surface", "eglLockSurfaceKHR eglUnlockSurfaceKHR"}, ++ {"EGL_KHR_lock_surface3", "eglLockSurfaceKHR eglUnlockSurfaceKHR eglQuerySurface64KHR"}, ++ {"EGL_KHR_partial_update", "eglSetDamageRegionKHR"}, ++ {"EGL_KHR_reusable_sync", "eglCreateSyncKHR eglDestroySyncKHR eglClientWaitSyncKHR eglSignalSyncKHR eglGetSyncAttribKHR"}, ++ {"EGL_KHR_stream", "eglCreateStreamKHR eglDestroyStreamKHR eglStreamAttribKHR eglQueryStreamKHR eglQueryStreamu64KHR"}, ++ {"EGL_KHR_stream_attrib", "eglCreateStreamAttribKHR eglSetStreamAttribKHR eglQueryStreamAttribKHR eglStreamConsumerAcquireAttribKHR eglStreamConsumerReleaseAttribKHR"}, ++ {"EGL_KHR_stream_consumer_gltexture", "eglStreamConsumerGLTextureExternalKHR eglStreamConsumerAcquireKHR eglStreamConsumerReleaseKHR"}, ++ {"EGL_KHR_stream_cross_process_fd", "eglGetStreamFileDescriptorKHR eglCreateStreamFromFileDescriptorKHR"}, ++ {"EGL_KHR_stream_fifo", "eglQueryStreamTimeKHR"}, ++ {"EGL_KHR_stream_producer_eglsurface", "eglCreateStreamProducerSurfaceKHR"}, ++ {"EGL_KHR_swap_buffers_with_damage", "eglSwapBuffersWithDamageKHR"}, ++ {"EGL_KHR_wait_sync", "eglWaitSyncKHR"}, ++ {"EGL_MESA_drm_image", "eglCreateDRMImageMESA eglExportDRMImageMESA"}, ++ {"EGL_MESA_image_dma_buf_export", "eglExportDMABUFImageQueryMESA eglExportDMABUFImageMESA"}, ++ {"EGL_MESA_query_driver", "eglGetDisplayDriverConfig eglGetDisplayDriverName"}, ++ {"EGL_NOK_swap_region", "eglSwapBuffersRegionNOK"}, ++ {"EGL_NOK_swap_region2", "eglSwapBuffersRegion2NOK"}, ++ {"EGL_NV_native_query", "eglQueryNativeDisplayNV eglQueryNativeWindowNV eglQueryNativePixmapNV"}, ++ {"EGL_NV_post_sub_buffer", "eglPostSubBufferNV"}, ++ {"EGL_NV_stream_consumer_eglimage", "eglStreamImageConsumerConnectNV eglQueryStreamConsumerEventNV eglStreamAcquireImageNV eglStreamReleaseImageNV"}, ++ {"EGL_NV_stream_consumer_gltexture_yuv", "eglStreamConsumerGLTextureExternalAttribsNV"}, ++ {"EGL_NV_stream_flush", "eglStreamFlushNV"}, ++ {"EGL_NV_stream_metadata", "eglQueryDisplayAttribNV eglSetStreamMetadataNV eglQueryStreamMetadataNV"}, ++ {"EGL_NV_stream_reset", "eglResetStreamNV"}, ++ {"EGL_NV_stream_sync", "eglCreateStreamSyncNV"}, ++ {"EGL_NV_sync", "eglCreateFenceSyncNV eglDestroySyncNV eglFenceNV eglClientWaitSyncNV eglSignalSyncNV eglGetSyncAttribNV"}, ++ {"EGL_NV_system_time", "eglGetSystemTimeFrequencyNV eglGetSystemTimeNV"}, ++ {"EGL_WL_bind_wayland_display", "eglBindWaylandDisplayWL eglUnbindWaylandDisplayWL eglQueryWaylandBufferWL"}, ++ {"EGL_WL_create_wayland_buffer_from_image", "eglCreateWaylandBufferFromImageWL"}, ++}; ++ ++static bool GuestHasEntrypoints(std::string_view extension) { ++ for (const auto& [name, entrypoints] : ExtensionEntrypoints) { ++ if (name != extension) { ++ continue; ++ } ++ std::string_view rest = entrypoints; ++ while (!rest.empty()) { ++ auto end = rest.find(' '); ++ if (!Self() || !dlsym(Self(), std::string {rest.substr(0, end)}.c_str())) { ++ return false; ++ } ++ rest = end == std::string_view::npos ? std::string_view {} : rest.substr(end + 1); ++ } ++ return true; ++ } ++ return true; ++} + + extern "C" { + voidFunc* eglGetProcAddress(const char* procname) { +- // TODO: Fix this HACK ++ if (strncmp(procname, "egl", 3) == 0) { ++ return Self() ? reinterpret_cast(dlsym(Self(), procname)) : nullptr; ++ } + return glXGetProcAddress((const GLubyte*)procname); + } ++ ++const char* eglQueryString(EGLDisplay display, EGLint name) { ++ const char* result = fexfn_pack_eglQueryString(display, name); ++ if (!result || name != EGL_EXTENSIONS) { ++ return result; ++ } ++ std::string filtered; ++ std::string_view all {result}; ++ while (!all.empty()) { ++ auto end = all.find(' '); ++ auto extension = all.substr(0, end); ++ if (!extension.empty() && GuestHasEntrypoints(extension)) { ++ if (!filtered.empty()) { ++ filtered += ' '; ++ } ++ filtered += extension; ++ } ++ all = end == std::string_view::npos ? std::string_view {} : all.substr(end + 1); ++ } ++ static std::mutex mutex; ++ static std::set strings; ++ std::lock_guard lock(mutex); ++ return strings.insert(std::move(filtered)).first->c_str(); ++} ++} ++ ++static void OnInit() { ++ fexfn_pack_EGL_SetGuestXSync((uintptr_t)XSync, (uintptr_t)CallbackUnpack::Unpack); ++ fexfn_pack_EGL_SetGuestXDisplayString((uintptr_t)XDisplayString, (uintptr_t)CallbackUnpack::Unpack); + } + +-LOAD_LIB(libEGL) ++LOAD_LIB_INIT(libEGL, OnInit) +diff --git a/ThunkLibs/libEGL/libEGL_Host.cpp b/ThunkLibs/libEGL/libEGL_Host.cpp +index ac8a87e..9b154b8 100644 +--- a/ThunkLibs/libEGL/libEGL_Host.cpp ++++ b/ThunkLibs/libEGL/libEGL_Host.cpp +@@ -4,14 +4,163 @@ tags: thunklibs|EGL + $end_info$ + */ + ++#include + #include ++#include + #include ++#include ++#include ++#include + ++#define EGL_EGLEXT_PROTOTYPES 1 + #include ++#include + + #include "common/Host.h" +-#include ++#include ++#include "common/X11Manager.h" ++ ++static X11Manager x11_manager; ++static std::mutex x11_displays_mutex; ++static std::unordered_map x11_displays; ++ ++static void* fex_egl_get_proc_address(void* so, const char* name) { ++ static auto get_proc_address = reinterpret_cast(dlsym(so, "eglGetProcAddress")); ++ return get_proc_address ? get_proc_address(name) : nullptr; ++} ++ ++static void fexfn_impl_libEGL_EGL_SetGuestXSync(uintptr_t GuestTarget, uintptr_t GuestUnpacker) { ++ MakeHostTrampolineForGuestFunctionAt(GuestTarget, GuestUnpacker, &x11_manager.GuestXSync); ++} ++ ++static void fexfn_impl_libEGL_EGL_SetGuestXDisplayString(uintptr_t GuestTarget, uintptr_t GuestUnpacker) { ++ MakeHostTrampolineForGuestFunctionAt(GuestTarget, GuestUnpacker, &x11_manager.GuestXDisplayString); ++} + + #include "thunkgen_host_libEGL.inl" + ++static bool IsWaylandDisplay(void* native) { ++ static std::atomic cached_interface {nullptr}; ++ void* wl_display_interface = cached_interface.load(std::memory_order_acquire); ++ if (!wl_display_interface) { ++ if (void* so = dlopen("libwayland-client.so.0", RTLD_LAZY | RTLD_NOLOAD)) { ++ wl_display_interface = dlsym(so, "wl_display_interface"); ++ dlclose(so); ++ cached_interface.store(wl_display_interface, std::memory_order_release); ++ } ++ } ++ return wl_display_interface && *reinterpret_cast(native) == wl_display_interface; ++} ++ ++static std::string_view EnvPlatform() { ++ const char* name = getenv("EGL_PLATFORM"); ++ if (!name || !*name) { ++ name = getenv("EGL_DISPLAY"); ++ } ++ return name ? std::string_view {name} : std::string_view {}; ++} ++ ++static void* HostNativeDisplay(EGLenum platform, void* native, _XDisplay** guest_x11) { ++ if (!native) { ++ return nullptr; ++ } ++ switch (platform) { ++ case EGL_PLATFORM_X11_KHR: break; ++#ifdef EGL_PLATFORM_XCB_EXT ++ case EGL_PLATFORM_XCB_EXT: return x11_manager.GuestToHostConnection(static_cast(native)); ++#endif ++ case 0: ++ if (auto env = EnvPlatform(); !env.empty()) { ++ if (env == "xcb") { ++ return x11_manager.GuestToHostConnection(static_cast(native)); ++ } ++ if (env != "x11") { ++ return native; ++ } ++ break; ++ } ++ if (IsWaylandDisplay(native)) { ++ return native; ++ } ++ break; ++ default: return native; ++ } ++ *guest_x11 = static_cast<_XDisplay*>(native); ++ return x11_manager.GuestToHostDisplay(*guest_x11); ++} ++ ++static EGLDisplay TrackDisplay(EGLDisplay display, _XDisplay* guest_x11) { ++ if (display != EGL_NO_DISPLAY && guest_x11) { ++ std::lock_guard lock(x11_displays_mutex); ++ x11_displays[display] = guest_x11; ++ } ++ return display; ++} ++ ++static void SyncGuestDisplay(EGLDisplay display) { ++ _XDisplay* guest_x11 = nullptr; ++ { ++ std::lock_guard lock(x11_displays_mutex); ++ if (auto it = x11_displays.find(display); it != x11_displays.end()) { ++ guest_x11 = it->second; ++ } ++ } ++ if (guest_x11) { ++ x11_manager.GuestXSync(guest_x11, 0); ++ } ++} ++ ++EGLDisplay fexfn_impl_libEGL_eglGetDisplay(guest_layout native) { ++ _XDisplay* guest_x11 = nullptr; ++ auto host = HostNativeDisplay(0, native.force_get_host_pointer(), &guest_x11); ++ return TrackDisplay(fexldr_ptr_libEGL_eglGetDisplay(static_cast(host)), guest_x11); ++} ++ ++EGLDisplay fexfn_impl_libEGL_eglGetPlatformDisplay(EGLenum platform, void* native, const EGLAttrib* attribs) { ++ _XDisplay* guest_x11 = nullptr; ++ auto host = HostNativeDisplay(platform, native, &guest_x11); ++ return TrackDisplay(fexldr_ptr_libEGL_eglGetPlatformDisplay(platform, host, attribs), guest_x11); ++} ++ ++EGLDisplay fexfn_impl_libEGL_eglGetPlatformDisplayEXT(EGLenum platform, void* native, const EGLint* attribs) { ++ _XDisplay* guest_x11 = nullptr; ++ auto host = HostNativeDisplay(platform, native, &guest_x11); ++ return TrackDisplay(fexldr_ptr_libEGL_eglGetPlatformDisplayEXT(platform, host, attribs), guest_x11); ++} ++ ++EGLSurface fexfn_impl_libEGL_eglCreateWindowSurface(EGLDisplay display, EGLConfig config, EGLNativeWindowType window, const EGLint* attribs) { ++ SyncGuestDisplay(display); ++ return fexldr_ptr_libEGL_eglCreateWindowSurface(display, config, window, attribs); ++} ++ ++EGLSurface fexfn_impl_libEGL_eglCreatePixmapSurface(EGLDisplay display, EGLConfig config, EGLNativePixmapType pixmap, const EGLint* attribs) { ++ SyncGuestDisplay(display); ++ return fexldr_ptr_libEGL_eglCreatePixmapSurface(display, config, pixmap, attribs); ++} ++ ++EGLSurface fexfn_impl_libEGL_eglCreatePlatformWindowSurface(EGLDisplay display, EGLConfig config, void* window, const EGLAttrib* attribs) { ++ SyncGuestDisplay(display); ++ return fexldr_ptr_libEGL_eglCreatePlatformWindowSurface(display, config, window, attribs); ++} ++ ++EGLSurface fexfn_impl_libEGL_eglCreatePlatformPixmapSurface(EGLDisplay display, EGLConfig config, void* pixmap, const EGLAttrib* attribs) { ++ SyncGuestDisplay(display); ++ return fexldr_ptr_libEGL_eglCreatePlatformPixmapSurface(display, config, pixmap, attribs); ++} ++ ++EGLSurface fexfn_impl_libEGL_eglCreatePlatformWindowSurfaceEXT(EGLDisplay display, EGLConfig config, void* window, const EGLint* attribs) { ++ SyncGuestDisplay(display); ++ return fexldr_ptr_libEGL_eglCreatePlatformWindowSurfaceEXT(display, config, window, attribs); ++} ++ ++EGLSurface fexfn_impl_libEGL_eglCreatePlatformPixmapSurfaceEXT(EGLDisplay display, EGLConfig config, void* pixmap, const EGLint* attribs) { ++ SyncGuestDisplay(display); ++ return fexldr_ptr_libEGL_eglCreatePlatformPixmapSurfaceEXT(display, config, pixmap, attribs); ++} ++ ++EGLBoolean fexfn_impl_libEGL_eglCopyBuffers(EGLDisplay display, EGLSurface surface, EGLNativePixmapType pixmap) { ++ SyncGuestDisplay(display); ++ return fexldr_ptr_libEGL_eglCopyBuffers(display, surface, pixmap); ++} ++ + EXPORTS(libEGL) +diff --git a/ThunkLibs/libEGL/libEGL_interface.cpp b/ThunkLibs/libEGL/libEGL_interface.cpp +index 27de16d..19f8b86 100644 +--- a/ThunkLibs/libEGL/libEGL_interface.cpp ++++ b/ThunkLibs/libEGL/libEGL_interface.cpp +@@ -1,51 +1,170 @@ + #include + ++#define EGL_EGLEXT_PROTOTYPES 1 + #include ++#include ++#include + + template + struct fex_gen_config { + unsigned version = 1; + }; + +-// Function, parameter index, parameter type [optional] + template + struct fex_gen_param {}; + ++template ++struct fex_gen_type {}; ++ ++template<> ++struct fex_gen_type : fexgen::opaque_type {}; ++template<> ++struct fex_gen_type<_XDisplay> : fexgen::opaque_type {}; ++ ++void EGL_SetGuestXSync(uintptr_t, uintptr_t); ++void EGL_SetGuestXDisplayString(uintptr_t, uintptr_t); ++template<> ++struct fex_gen_config : fexgen::custom_guest_entrypoint, fexgen::custom_host_impl {}; ++template<> ++struct fex_gen_config : fexgen::custom_guest_entrypoint, fexgen::custom_host_impl {}; ++ + template<> + struct fex_gen_config {}; + template<> ++struct fex_gen_config {}; ++template<> + struct fex_gen_config {}; + template<> ++struct fex_gen_config {}; ++template<> ++struct fex_gen_config {}; ++template<> ++struct fex_gen_config {}; ++template<> ++struct fex_gen_config {}; ++template<> ++struct fex_gen_config {}; ++template<> ++struct fex_gen_config {}; ++template<> + struct fex_gen_config {}; + template<> ++struct fex_gen_config {}; ++template<> + struct fex_gen_config {}; + template<> ++struct fex_gen_config {}; ++template<> ++struct fex_gen_config {}; ++template<> ++struct fex_gen_config {}; ++template<> ++struct fex_gen_config {}; ++template<> ++struct fex_gen_config {}; ++template<> ++struct fex_gen_config {}; ++template<> ++struct fex_gen_config {}; ++template<> ++struct fex_gen_config {}; ++template<> + struct fex_gen_config {}; + template<> + struct fex_gen_config {}; + template<> ++struct fex_gen_config {}; ++template<> ++struct fex_gen_config {}; ++template<> ++struct fex_gen_config : fexgen::custom_guest_entrypoint {}; ++template<> + struct fex_gen_config {}; + template<> ++struct fex_gen_config {}; ++template<> ++struct fex_gen_config {}; ++template<> + struct fex_gen_config {}; + template<> + struct fex_gen_config {}; + template<> ++struct fex_gen_config {}; ++template<> + struct fex_gen_config {}; + template<> +-struct fex_gen_config {}; ++struct fex_gen_config {}; + template<> +-struct fex_gen_config {}; ++struct fex_gen_config {}; + template<> +-struct fex_gen_config {}; ++struct fex_gen_config {}; + template<> +-struct fex_gen_config {}; ++struct fex_gen_config {}; + template<> +-struct fex_gen_config {}; ++struct fex_gen_config : fexgen::custom_host_impl {}; + template<> +-struct fex_gen_config {}; ++struct fex_gen_config : fexgen::custom_host_impl {}; ++template<> ++struct fex_gen_config : fexgen::custom_host_impl {}; ++template<> ++struct fex_gen_config : fexgen::custom_host_impl {}; ++template<> ++struct fex_gen_config : fexgen::custom_host_impl {}; ++template<> ++struct fex_gen_config : fexgen::custom_host_impl {}; ++template<> ++struct fex_gen_config : fexgen::custom_host_impl {}; ++template<> ++struct fex_gen_param : fexgen::ptr_passthrough {}; ++ ++namespace ext { ++template ++struct fex_gen_config { ++ const char* load_host_endpoint_via = "fex_egl_get_proc_address"; ++}; + +-// EGLNativeDisplayType is a pointer to opaque data (wl_display/(X)Display/...) + template<> +-struct fex_gen_config {}; ++struct fex_gen_config {}; ++template<> ++struct fex_gen_config {}; ++template<> ++struct fex_gen_config {}; ++template<> ++struct fex_gen_config {}; ++template<> ++struct fex_gen_config {}; ++template<> ++struct fex_gen_config {}; ++template<> ++struct fex_gen_config {}; ++template<> ++struct fex_gen_config {}; ++template<> ++struct fex_gen_config {}; ++template<> ++struct fex_gen_config {}; ++template<> ++struct fex_gen_config {}; ++template<> ++struct fex_gen_config {}; ++template<> ++struct fex_gen_config {}; ++template<> ++struct fex_gen_config {}; ++template<> ++struct fex_gen_config {}; ++template<> ++struct fex_gen_config {}; ++template<> ++struct fex_gen_config {}; ++template<> ++struct fex_gen_config {}; ++template<> ++struct fex_gen_config {}; ++template<> ++struct fex_gen_config : fexgen::custom_host_impl {}; ++template<> ++struct fex_gen_config : fexgen::custom_host_impl {}; + template<> +-struct fex_gen_param : fexgen::assume_compatible_data_layout {}; ++struct fex_gen_config : fexgen::custom_host_impl {}; ++} +diff --git a/ThunkLibs/libwayland-client/Guest.cpp b/ThunkLibs/libwayland-client/Guest.cpp +index 2f887a6..8fa6476 100644 +--- a/ThunkLibs/libwayland-client/Guest.cpp ++++ b/ThunkLibs/libwayland-client/Guest.cpp +@@ -42,8 +42,11 @@ extern "C" const wl_interface wl_subsurface_interface {}; + #include + #include + #include ++#include ++#include + #include + #include ++#include + + #include "common/Guest.h" + +@@ -92,18 +95,39 @@ static uint64_t WaylandAllocateHostTrampolineForGuestListener(void (*callback)() + } + + #define WL_CLOSURE_MAX_ARGS 20 ++#define WAYLAND_UNIFORM_MAX_ARGS 17 ++ ++template ++static uint64_t WaylandAllocateUniformHostTrampoline(void (*callback)(), std::index_sequence) { ++ using cb = void(void*, wl_proxy*, std::conditional_t>...); ++ return (uint64_t)(uintptr_t)(void*)AllocateHostTrampolineForGuestFunction((cb*)callback); ++} ++ ++template ++static uint64_t WaylandAllocateUniformHostTrampoline(void (*callback)(), std::size_t count, std::index_sequence) { ++ using allocator = uint64_t (*)(void (*)()); ++ static constexpr allocator allocators[] = { ++ [](void (*cb)()) { return WaylandAllocateUniformHostTrampoline(cb, std::make_index_sequence {}); }...}; ++ return allocators[count](callback); ++} + + extern "C" int wl_proxy_add_listener(wl_proxy* proxy, void (**callback)(void), void* data) { + // Replace guest-provided callback table with host-callable function pointers + // NOTE: A reference to this table is stored in the wl_proxy, so the data + // must remain valid until the proxy is destroyed (or another listener + // is added) +- delete[] (uint64_t*)wl_proxy_get_listener(proxy); // Delete previous substitute, if any +- auto host_callbacks = new uint64_t[WL_CLOSURE_MAX_ARGS]; ++ if (wl_proxy_get_listener(proxy)) { ++ fprintf(stderr, "proxy %p already has listener\n", proxy); ++ return -1; ++ } ++ auto host_callbacks = new uint64_t[std::max(fex_wl_get_interface_event_count(proxy), WL_CLOSURE_MAX_ARGS)]; + + for (int i = 0; i < fex_wl_get_interface_event_count(proxy); ++i) { +- char event_signature[16]; +- fex_wl_get_interface_event_signature(proxy, i, event_signature); ++ char event_signature[64]; ++ if (fex_wl_get_interface_event_signature(proxy, i, event_signature, sizeof(event_signature)) >= sizeof(event_signature)) { ++ fprintf(stderr, "TODO: Unknown wayland event signature descriptor %s\n", event_signature); ++ std::abort(); ++ } + auto signature2 = std::string_view {event_signature}; + + // A leading number indicates the minimum protocol version +@@ -227,13 +251,19 @@ extern "C" int wl_proxy_add_listener(wl_proxy* proxy, void (**callback)(void), v + } else if (signature == "sii") { + // E.g. zwp_text_input_v3::preedit_string + host_callbacks[i] = WaylandAllocateHostTrampolineForGuestListener<'s', 'i', 'i'>(callback[i]); ++ } else if (signature.size() <= WAYLAND_UNIFORM_MAX_ARGS) { ++ host_callbacks[i] = WaylandAllocateUniformHostTrampoline(callback[i], signature.size(), std::make_index_sequence {}); + } else { + fprintf(stderr, "TODO: Unknown wayland event signature descriptor %s\n", signature.data()); + std::abort(); + } + } + +- return fexfn_pack_wl_proxy_add_listener(proxy, (void (**)())host_callbacks, data); ++ int result = fexfn_pack_wl_proxy_add_listener(proxy, (void (**)())host_callbacks, data); ++ if (result != 0) { ++ delete[] host_callbacks; ++ } ++ return result; + } + + extern "C" void wl_proxy_destroy(wl_proxy* proxy) { +@@ -353,6 +383,92 @@ extern "C" void wl_log_set_handler_client(wl_log_func_t handler) { + // Ignore + } + ++extern "C" void wl_list_init(wl_list* list) { ++ list->prev = list; ++ list->next = list; ++} ++ ++extern "C" void wl_list_insert(wl_list* list, wl_list* elm) { ++ elm->prev = list; ++ elm->next = list->next; ++ list->next = elm; ++ elm->next->prev = elm; ++} ++ ++extern "C" void wl_list_remove(wl_list* elm) { ++ elm->prev->next = elm->next; ++ elm->next->prev = elm->prev; ++ elm->next = nullptr; ++ elm->prev = nullptr; ++} ++ ++extern "C" int wl_list_length(const wl_list* list) { ++ int count = 0; ++ for (auto e = list->next; e != list; e = e->next) { ++ ++count; ++ } ++ return count; ++} ++ ++extern "C" int wl_list_empty(const wl_list* list) { ++ return list->next == list; ++} ++ ++extern "C" void wl_list_insert_list(wl_list* list, wl_list* other) { ++ if (wl_list_empty(other)) { ++ return; ++ } ++ other->next->prev = list; ++ other->prev->next = list->next; ++ list->next->prev = other->prev; ++ list->next = other->next; ++} ++ ++extern "C" void wl_array_init(wl_array* array) { ++ memset(array, 0, sizeof(*array)); ++} ++ ++extern "C" void wl_array_release(wl_array* array) { ++ free(array->data); ++ array->data = (void*)4; ++} ++ ++extern "C" void* wl_array_add(wl_array* array, size_t size) { ++ if (size > SIZE_MAX - array->size) { ++ return nullptr; ++ } ++ size_t needed = array->size + size; ++ size_t alloc = array->alloc > 0 ? array->alloc : 16; ++ while (alloc < needed) { ++ alloc = alloc > SIZE_MAX / 2 ? needed : alloc * 2; ++ } ++ if (array->alloc < alloc) { ++ void* data = array->alloc > 0 ? realloc(array->data, alloc) : malloc(alloc); ++ if (!data) { ++ return nullptr; ++ } ++ array->data = data; ++ array->alloc = alloc; ++ } ++ void* p = (char*)array->data + array->size; ++ array->size += size; ++ return p; ++} ++ ++extern "C" int wl_array_copy(wl_array* array, wl_array* source) { ++ if (array->size < source->size) { ++ if (!wl_array_add(array, source->size - array->size)) { ++ return -1; ++ } ++ } else { ++ array->size = source->size; ++ } ++ if (source->size > 0) { ++ memcpy(array->data, source->data, source->size); ++ } ++ return 0; ++} ++ + + void OnInit() { + fex_wl_exchange_interface_pointer(const_cast(&wl_output_interface), "wl_output_interface"); +diff --git a/ThunkLibs/libwayland-client/Host.cpp b/ThunkLibs/libwayland-client/Host.cpp +index 68c2ded..25f964c 100644 +--- a/ThunkLibs/libwayland-client/Host.cpp ++++ b/ThunkLibs/libwayland-client/Host.cpp +@@ -22,6 +22,7 @@ $end_info$ + #include + #include + #include ++#include + + #include + +@@ -166,6 +167,7 @@ static wl_proxy* fexfn_impl_libwayland_client_wl_proxy_create(wl_proxy* proxy, g + } + + #define WL_CLOSURE_MAX_ARGS 20 ++#define WAYLAND_UNIFORM_MAX_ARGS 17 + static auto fex_wl_remap_argument_list(guest_layout args, const wl_message& message) { + #ifndef IS_32BIT_THUNK + // Cast to host layout and return as std::span +@@ -309,6 +311,21 @@ static void WaylandFinalizeHostTrampolineForGuestListener(void (*callback)()) { + FinalizeHostTrampolineForGuestFunction((cb*)callback); + } + ++ ++template ++static void WaylandFinalizeUniformHostTrampoline(void (*callback)(), std::index_sequence) { ++ using cb = void(void*, wl_proxy*, std::conditional_t>...); ++ FinalizeHostTrampolineForGuestFunction((cb*)callback); ++} ++ ++template ++static void WaylandFinalizeUniformHostTrampoline(void (*callback)(), std::size_t count, std::index_sequence) { ++ using finalizer = void (*)(void (*)()); ++ static constexpr finalizer finalizers[] = { ++ [](void (*cb)()) { WaylandFinalizeUniformHostTrampoline(cb, std::make_index_sequence {}); }...}; ++ finalizers[count](callback); ++} ++ + extern "C" int + fexfn_impl_libwayland_client_wl_proxy_add_listener(struct wl_proxy* proxy, guest_layout callback_table_raw, void* data) { + auto interface = get_proxy_interface(proxy); +@@ -446,6 +463,8 @@ fexfn_impl_libwayland_client_wl_proxy_add_listener(struct wl_proxy* proxy, guest + WaylandFinalizeHostTrampolineForGuestListener<'s', 'i', 'i'>(callback); + } else if (signature == "ss") { + WaylandFinalizeHostTrampolineForGuestListener<'s', 's'>(callback); ++ } else if (signature.size() <= WAYLAND_UNIFORM_MAX_ARGS) { ++ WaylandFinalizeUniformHostTrampoline(callback, signature.size(), std::make_index_sequence {}); + } else { + fprintf(stderr, "TODO: Unknown wayland event signature descriptor %s\n", signature.data()); + std::abort(); +@@ -514,8 +533,35 @@ void fexfn_impl_libwayland_client_fex_wl_get_interface_event_name(wl_proxy* prox + strcpy(out, get_proxy_interface(proxy)->events[i].name); + } + +-void fexfn_impl_libwayland_client_fex_wl_get_interface_event_signature(wl_proxy* proxy, int i, char* out) { +- strcpy(out, get_proxy_interface(proxy)->events[i].signature); ++size_t fexfn_impl_libwayland_client_fex_wl_get_interface_event_signature(wl_proxy* proxy, int i, char* out, size_t size) { ++ const char* signature = get_proxy_interface(proxy)->events[i].signature; ++ size_t length = strlen(signature); ++ if (size > 0) { ++ size_t copied = std::min(length, size - 1); ++ memcpy(out, signature, copied); ++ out[copied] = '\0'; ++ } ++ return length; ++} ++ ++uint32_t fexfn_impl_libwayland_client_wl_display_get_protocol_error(wl_display* display, guest_layout guest_interface, ++ uint32_t* id) { ++ const wl_interface* host_interface = nullptr; ++ auto code = fexldr_ptr_libwayland_client_wl_display_get_protocol_error(display, &host_interface, id); ++ if (!guest_interface.force_get_host_pointer()) { ++ return code; ++ } ++ uintptr_t result = 0; ++ for (auto& [guest, host] : guest_to_host_interface) { ++ if (host == host_interface) { ++ result = reinterpret_cast(guest); ++ } ++ } ++ if (!result) { ++ result = reinterpret_cast(host_interface); ++ } ++ guest_interface.get_pointer()->data = result; ++ return code; + } + + EXPORTS(libwayland_client) +diff --git a/ThunkLibs/libwayland-client/libwayland-client_interface.cpp b/ThunkLibs/libwayland-client/libwayland-client_interface.cpp +index 575d2e1..9723a3c 100644 +--- a/ThunkLibs/libwayland-client/libwayland-client_interface.cpp ++++ b/ThunkLibs/libwayland-client/libwayland-client_interface.cpp +@@ -83,6 +83,16 @@ struct fex_gen_config {}; + + template<> + struct fex_gen_config {}; ++template<> ++struct fex_gen_config {}; ++template<> ++struct fex_gen_config {}; ++template<> ++struct fex_gen_config {}; ++template<> ++struct fex_gen_config : fexgen::custom_host_impl {}; ++template<> ++struct fex_gen_param : fexgen::ptr_passthrough {}; + + template<> + struct fex_gen_config : fexgen::custom_host_impl, fexgen::custom_guest_entrypoint {}; +@@ -101,6 +111,10 @@ struct fex_gen_config {}; + template<> + struct fex_gen_config {}; + template<> ++struct fex_gen_config {}; ++template<> ++struct fex_gen_config {}; ++template<> + struct fex_gen_config {}; + template<> + struct fex_gen_config {}; +@@ -164,6 +178,6 @@ struct fex_gen_config : fexgen::custom_host_im + void fex_wl_get_interface_event_name(wl_proxy*, int, char*); + template<> + struct fex_gen_config : fexgen::custom_host_impl {}; +-void fex_wl_get_interface_event_signature(wl_proxy*, int, char*); ++size_t fex_wl_get_interface_event_signature(wl_proxy*, int, char*, size_t); + template<> + struct fex_gen_config : fexgen::custom_host_impl {}; +diff --git a/ThunkLibs/libwayland-egl/Guest.cpp b/ThunkLibs/libwayland-egl/Guest.cpp +new file mode 100644 +index 0000000..300a8fc +--- /dev/null ++++ b/ThunkLibs/libwayland-egl/Guest.cpp +@@ -0,0 +1,7 @@ ++#include ++ ++#include "common/Guest.h" ++ ++#include "thunkgen_guest_libwayland-egl.inl" ++ ++LOAD_LIB(libwayland-egl) +diff --git a/ThunkLibs/libwayland-egl/Host.cpp b/ThunkLibs/libwayland-egl/Host.cpp +new file mode 100644 +index 0000000..81ad83b +--- /dev/null ++++ b/ThunkLibs/libwayland-egl/Host.cpp +@@ -0,0 +1,8 @@ ++#include ++ ++#include "common/Host.h" ++#include ++ ++#include "thunkgen_host_libwayland-egl.inl" ++ ++EXPORTS(libwayland_egl) +diff --git a/ThunkLibs/libwayland-egl/libwayland-egl_interface.cpp b/ThunkLibs/libwayland-egl/libwayland-egl_interface.cpp +new file mode 100644 +index 0000000..bc5d743 +--- /dev/null ++++ b/ThunkLibs/libwayland-egl/libwayland-egl_interface.cpp +@@ -0,0 +1,25 @@ ++#include ++ ++#include ++ ++template ++struct fex_gen_config { ++ unsigned version = 1; ++}; ++ ++template ++struct fex_gen_type {}; ++ ++template<> ++struct fex_gen_type : fexgen::opaque_type {}; ++template<> ++struct fex_gen_type : fexgen::opaque_type {}; ++ ++template<> ++struct fex_gen_config {}; ++template<> ++struct fex_gen_config {}; ++template<> ++struct fex_gen_config {}; ++template<> ++struct fex_gen_config {}; diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex b/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex index af236125f..5585f68a8 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex @@ -71,6 +71,7 @@ RUNTIME_LIBRARIES = (("libc.so.6", b"GLIBC_"), ("libstdc++.so.6", b"GLIBCXX_")) VERSION_NAME = re.compile(rb"GLIBC(?:XX)?_[0-9][0-9.]*[0-9]") BUNDLE_DEPTH = 3 THUNKS = {"GL": 1, "Vulkan": 1} +WAYLAND_THUNKS = {"WaylandClient": "libwayland-client-guest.so", "EGL": "libEGL-guest.so", "WaylandEGL": "libwayland-egl-guest.so"} X86 = {3: "i386", 62: "x86_64"} ARM = {40: "arm", 183: "arm64"} SCAN_DEPTH = 4 @@ -448,13 +449,20 @@ def install_preloads(root): write_if_changed(os.path.join(root, "etc", "asound.conf"), ASOUND_CONF) +def enabled_thunks(fex): + thunks = dict(THUNKS) + if all(os.path.isfile(os.path.join(fex["guest_thunks"], name)) for name in WAYLAND_THUNKS.values()): + thunks.update(dict.fromkeys(WAYLAND_THUNKS, 1)) + return thunks + + def write_config(fex, root): config = {"Config": {"RootFS": root}} if fex["host_thunks"] and fex["guest_thunks"] and fex["thunks_db"]: config["Config"]["ThunkHostLibs"] = fex["host_thunks"] config["Config"]["ThunkGuestLibs"] = fex["guest_thunks"] - config["ThunksDB"] = dict(THUNKS) - write_if_changed(os.path.join(CONFIG_DIR, "ThunksConfig.json"), json.dumps({"ThunksDB": dict(THUNKS)}, indent=2) + "\n") + config["ThunksDB"] = enabled_thunks(fex) + write_if_changed(os.path.join(CONFIG_DIR, "ThunksConfig.json"), json.dumps({"ThunksDB": config["ThunksDB"]}, indent=2) + "\n") write_if_changed(os.path.join(CONFIG_DIR, "Config.json"), json.dumps(config, indent=2) + "\n") diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex-update b/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex-update index 5e663308d..25f445ade 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex-update +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex-update @@ -29,14 +29,19 @@ fex_install() { return 1 fi (cd "$tmp/root" && find . ! -type d) > "$tmp/files" + for d in usr/local/share/fex-emu/GuestThunks usr/local/share/fex-emu/GuestThunks_32 usr/local/lib/fex-emu/HostThunks usr/local/lib/fex-emu/HostThunks_32; do + [ -d "$tmp/root/$d" ] && [ -d "$dst$d" ] || continue + (cd "$dst" && find "$d" ! -type d) | while IFS= read -r f; do grep -qxF "./$f" "$tmp/files" || echo "$f"; done + done > "$tmp/stale" mkdir "$tmp/old" while IFS= read -r f; do f=${f#./} if [ -e "$dst$f" ] || [ -L "$dst$f" ]; then cp -a --parents "$dst$f" "$tmp/old" || { echo "== FEX $tag: could not keep $dst$f aside" >&2; rm -rf "$tmp"; return 1; } fi - done < "$tmp/files" - if tar -C "$tmp/root" -c . | tar -C "$dst" -x && fex_loads "$dst" && + done < <(cat "$tmp/files" "$tmp/stale") + if tar -C "$tmp/root" -c . | tar -C "$dst" -x && + ( while IFS= read -r f; do rm -f "$dst$f" || exit 1; done < "$tmp/stale" ) && fex_loads "$dst" && mkdir -p "${dst}usr/local/share/fex-emu" && echo "$tag" > "${dst}usr/local/share/fex-emu/.droiddeck-tag"; then rm -rf "$tmp" return 0 diff --git a/tools/tests/test_droiddeck_fex.py b/tools/tests/test_droiddeck_fex.py index 07aa01d76..e59b21c7c 100644 --- a/tools/tests/test_droiddeck_fex.py +++ b/tools/tests/test_droiddeck_fex.py @@ -1188,6 +1188,22 @@ class LaunchTest(FexTestCase): thunks = json.loads((self.home / ".local/share/droiddeck-fex/config/ThunksConfig.json").read_text()) self.assertEqual(thunks, {"ThunksDB": {"GL": 1, "Vulkan": 1}}) + def test_wayland_and_egl_thunks_turn_on_only_when_the_build_ships_all_of_them(self): + guest = self.tmp / "guest-thunks" + guest.mkdir() + fex = {"host_thunks": "/h", "guest_thunks": str(guest), "thunks_db": "/db"} + thunks_file = self.home / ".local/share/droiddeck-fex/config/ThunksConfig.json" + for name in ("libwayland-client-guest.so", "libEGL-guest.so"): + (guest / name).write_bytes(b"") + FEX["write_config"](fex, "/root") + self.assertEqual({"GL": 1, "Vulkan": 1}, json.loads(thunks_file.read_text())["ThunksDB"]) + (guest / "libwayland-egl-guest.so").write_bytes(b"") + FEX["write_config"](fex, "/root") + expected = {"GL": 1, "Vulkan": 1, "WaylandClient": 1, "EGL": 1, "WaylandEGL": 1} + self.assertEqual(expected, json.loads(thunks_file.read_text())["ThunksDB"]) + config = json.loads((self.home / ".local/share/droiddeck-fex/config/Config.json").read_text()) + self.assertEqual(expected, config["ThunksDB"]) + def test_host_libc_tunables_stay_on_the_host(self): guest = FEX["guest_environment"]({"portable": True}, {"GLIBC_TUNABLES": "glibc.pthread.rseq=0"}) self.assertNotIn("GLIBC_TUNABLES", guest) diff --git a/tools/tests/test_fex_install.py b/tools/tests/test_fex_install.py index 51d5279e8..50c79084d 100644 --- a/tools/tests/test_fex_install.py +++ b/tools/tests/test_fex_install.py @@ -11,6 +11,7 @@ SOURCE = SCRIPT.read_text() START = SOURCE.index("fex_install() {") END = SOURCE.index("\n}\n", START) + 3 FEX_INSTALL = SOURCE[START:END] +THUNK_DIRS = (("share/fex-emu/GuestThunks_32", "libGL-guest.so"), ("lib/fex-emu/HostThunks_32", "libGL-host.so")) HARNESS = textwrap.dedent("""\ set -eu @@ -37,9 +38,25 @@ class FexInstallTest(unittest.TestCase): (new / "lib").mkdir() (new / "lib/libxxhash.so.0").write_text("lib\n") self.pkg = base / "fex.tzst" - subprocess.run(f"tar -C '{base / 'pkg'}' -c . | zstd -q -o '{self.pkg}'", shell=True, check=True) + self.pack() + + def pack(self): + base = Path(self.temp.name) + subprocess.run(f"tar -C '{base / 'pkg'}' -c . | zstd -q -f -o '{self.pkg}'", shell=True, check=True) self.sha = hashlib.sha256(self.pkg.read_bytes()).hexdigest() + def add_old_thunks(self): + old, new = self.root / "usr/local", Path(self.temp.name) / "pkg/usr/local" + for side, name in THUNK_DIRS: + (new / side).mkdir(parents=True) + (new / side / name).write_text("new thunk\n") + (old / side).mkdir(parents=True) + (old / side / name).write_text("old thunk\n") + (old / side / "libwayland-client-thunk.so").write_text("stale\n") + (old / "share/fex-emu/GuestThunks").mkdir() + (old / "share/fex-emu/GuestThunks/libkept-guest.so").write_text("kept\n") + self.pack() + def install(self, installed_loads, sha=None): body = FEX_INSTALL.replace("local tag=$1 sha=$2 urls=$3 dst=/ ", "local tag=$1 sha=$2 urls=$3 dst=$ROOT/ ") self.assertNotEqual(body, FEX_INSTALL) @@ -79,6 +96,27 @@ class FexInstallTest(unittest.TestCase): self.assertEqual("old FEX\n", (self.root / "usr/local/bin/FEX").read_text()) self.assertFalse((self.root / "usr/local/lib/libxxhash.so.0").exists()) + def test_thunks_the_new_build_no_longer_ships_are_removed(self): + self.add_old_thunks() + self.assertEqual("OK", self.install(installed_loads=True)[0]) + for side, name in THUNK_DIRS: + with self.subTest(side=side): + self.assertEqual("new thunk\n", (self.root / "usr/local" / side / name).read_text()) + self.assertFalse((self.root / "usr/local" / side / "libwayland-client-thunk.so").exists()) + + def test_a_thunk_folder_the_new_build_does_not_ship_is_left_alone(self): + self.add_old_thunks() + self.assertEqual("OK", self.install(installed_loads=True)[0]) + self.assertEqual("kept\n", (self.root / "usr/local/share/fex-emu/GuestThunks/libkept-guest.so").read_text()) + + def test_a_failed_install_puts_removed_thunks_back(self): + self.add_old_thunks() + self.assertEqual("FAILED", self.install(installed_loads=False)[0]) + for side, name in THUNK_DIRS: + with self.subTest(side=side): + self.assertEqual("old thunk\n", (self.root / "usr/local" / side / name).read_text()) + self.assertEqual("stale\n", (self.root / "usr/local" / side / "libwayland-client-thunk.so").read_text()) + def test_an_archive_that_does_not_match_installs_nothing(self): result, err = self.install(installed_loads=True, sha="0" * 64) self.assertEqual("FAILED", result) diff --git a/tools/tests/test_fex_wayland_egl_thunks.py b/tools/tests/test_fex_wayland_egl_thunks.py new file mode 100644 index 000000000..06195738b --- /dev/null +++ b/tools/tests/test_fex_wayland_egl_thunks.py @@ -0,0 +1,151 @@ +import re +import runpy +import unittest +from pathlib import Path + +REPO = Path(__file__).resolve().parents[2] +PATCH = REPO / "tools/fex/patches/0019-wayland-and-egl-thunks-for-64-bit-guests.patch" +LAUNCHER = REPO / "tools/linuxfs/overlay/usr/local/bin/droiddeck-fex" +THUNKS = {"WaylandClient": "wayland-client", "EGL": "EGL", "WaylandEGL": "wayland-egl"} + + +def blocks(): + return {re.match(r"a/(\S+) ", block).group(1): block + for block in re.split(r"^diff --git ", PATCH.read_text(), flags=re.M)[1:]} + + +def files(): + return {name: [line[1:] for line in block.splitlines() if line.startswith("+") and not line.startswith("+++")] + for name, block in blocks().items()} + + +def built_libs(block): + out, base, stack = set(), False, [] + for line in block.splitlines(): + if line.startswith("@@"): + base, stack = "BITNESS EQUAL 64" in line, [] + continue + if line[:1] == "-": + continue + text = line[1:].strip() + if text.startswith("if ("): + stack.append("gate" if "BITNESS EQUAL 64" in text else "other") + elif text.startswith("else"): + if stack: + stack[-1] = {"gate": "inverted", "inverted": "gate"}.get(stack[-1], stack[-1]) + else: + base = False + elif text == "endif()": + if stack: + stack.pop() + else: + base = False + found = re.match(r"add_(?:guest|host)_lib\(([\w-]+)", text) + if found and line[:1] == "+": + out.add((found.group(1), "inverted" not in stack and (base or "gate" in stack))) + return out + + +def database(): + entries, name = {}, None + for line in blocks()["Data/ThunksDB.json"].splitlines(): + if line[:1] == "-": + continue + found = re.match(r'[ +]\s*"(\w+)": \{', line) + if found: + name = found.group(1) + found = re.search(r'"Library" : "([^"]+)"', line) + if found and name: + entries[name] = found.group(1) + return entries + + +class FexWaylandEglThunksTest(unittest.TestCase): + def test_only_thunk_sources_and_the_thunk_database_change(self): + for name in files(): + with self.subTest(name=name): + self.assertTrue(name == "Data/ThunksDB.json" or name.startswith("ThunkLibs/")) + + def test_each_enabled_thunk_maps_to_the_guest_library_the_build_ships(self): + launcher = runpy.run_path(str(LAUNCHER), run_name="droiddeck_fex")["WAYLAND_THUNKS"] + self.assertEqual(set(THUNKS), set(launcher)) + built = {name for name, _ in built_libs(blocks()["ThunkLibs/GuestLibs/CMakeLists.txt"])} + entries = database() + for name, lib in THUNKS.items(): + with self.subTest(name=name): + self.assertIn(lib, built) + self.assertEqual(f"lib{lib}-guest.so", launcher[name]) + if name in entries: + self.assertEqual(launcher[name], entries[name]) + self.assertEqual({"EGL", "WaylandEGL"}, set(entries) & set(THUNKS)) + + def test_the_upstream_wayland_client_entry_is_left_unchanged(self): + changed = [line for line in blocks()["Data/ThunksDB.json"].splitlines() + if line[:1] in "+-" and not line.startswith(("+++", "---"))] + self.assertFalse([line for line in changed if "WaylandClient" in line or "wayland-client" in line]) + + def test_an_extension_is_advertised_only_with_every_entrypoint(self): + guest = "\n".join(files()["ThunkLibs/libEGL/libEGL_Guest.cpp"]) + table = dict(re.findall(r'\{"(EGL_\w+)", "([\w ]+)"\}', guest)) + self.assertEqual("eglQueryNativeDisplayNV eglQueryNativeWindowNV eglQueryNativePixmapNV", + table["EGL_NV_native_query"]) + self.assertIn("eglSignalSyncKHR", table["EGL_KHR_reusable_sync"].split()) + self.assertIn("eglCreateSyncKHR", table["EGL_KHR_reusable_sync"].split()) + body = re.search(r"static bool GuestHasEntrypoints\(.*?\n\}", guest, re.S).group(0) + self.assertRegex(body, r"while \(!rest\.empty\(\)\)") + self.assertRegex(body, r"dlsym\(Self\(\), .*rest\.substr\(0, end\)") + + def test_a_legacy_display_follows_the_platform_mesa_would_pick(self): + host = "\n".join(files()["ThunkLibs/libEGL/libEGL_Host.cpp"]) + env = re.search(r"static std::string_view EnvPlatform\(\) \{.*?\n\}", host, re.S).group(0) + self.assertLess(env.index('getenv("EGL_PLATFORM")'), env.index('getenv("EGL_DISPLAY")')) + legacy = re.search(r"case 0:\n(.*?)\n default:", host, re.S).group(1) + self.assertLess(legacy.index("EnvPlatform()"), legacy.index("IsWaylandDisplay(native)")) + self.assertIn('env == "xcb"', legacy) + self.assertIn('env != "x11"', legacy) + self.assertNotIn("IsHostDevice", host) + + def test_gles_is_overlaid_only_by_the_64_bit_egl_thunk(self): + overlays, name = {}, None + for line in blocks()["Data/ThunksDB.json"].splitlines(): + found = re.match(r'[ +]\s*"(\w+)": \{', line) + if found: + name = found.group(1) + if "libGLESv2" in line: + overlays.setdefault(line[:1], set()).add(name) + self.assertEqual({"EGL"}, overlays.get("+")) + self.assertNotIn("-", overlays) + + def test_guest_and_host_libraries_are_built_for_64_bit_guests_only(self): + changed = blocks() + for side in ("GuestLibs", "HostLibs"): + built = built_libs(changed[f"ThunkLibs/{side}/CMakeLists.txt"]) + for lib in THUNKS.values(): + with self.subTest(side=side, lib=lib): + self.assertEqual({(lib, True)}, {entry for entry in built if entry[0] == lib}) + + def test_listener_trampolines_stay_inside_the_packed_argument_limit(self): + guest = "\n".join(files()["ThunkLibs/libwayland-client/Guest.cpp"]) + limit = int(re.search(r"#define WAYLAND_UNIFORM_MAX_ARGS (\d+)", guest).group(1)) + self.assertLessEqual(limit + 2, 19) + + def test_the_guest_provides_the_inline_list_and_array_helpers(self): + guest = "\n".join(files()["ThunkLibs/libwayland-client/Guest.cpp"]) + for name in ("wl_list_init", "wl_list_insert", "wl_list_remove", "wl_list_length", "wl_list_empty", + "wl_list_insert_list", "wl_array_init", "wl_array_release", "wl_array_add", "wl_array_copy"): + with self.subTest(name=name): + self.assertRegex(guest, rf"\b{name}\(") + + def test_the_inverse_branch_of_the_bitness_gate_is_not_64_bit_only(self): + block = "@@ -1 +1 @@\n+if (GUEST_BITNESS EQUAL 64)\n+else()\n+ add_host_lib(EGL ${GUEST_BITNESS})\n+endif()\n" + self.assertEqual({("EGL", False)}, built_libs(block)) + + def test_no_comments_are_added(self): + for name, lines in files().items(): + for line in lines: + with self.subTest(name=name, line=line): + self.assertNotRegex(line, r"(^|\s)(//|/\*)|\$info\$") + + +if __name__ == "__main__": + unittest.main()