Compare commits

..
Author SHA1 Message Date
MaxsTechReview 46f99b9e08 fix(nativeguest): Downloads and Documents are writable in the desktop file manager (#3274)
fix(nativeguest): shared storage files are root's like the SD card's

Android's internal shared storage reports its files as owned by the media
provider with the media_rw group, so desktop file managers saw Downloads and
Documents as someone else's and showed them read-only, with rename, delete and
new folder unavailable. Files in the media_rw group are now presented as
owned by root, as the SD card already is; the group is kept.
2026-11-26 10:30:32 -05:00
MaxsTechReview dcb1a3001b fix(desktop): Downloads, Documents and game folder links work again without proot (#3273)
Links made in a proot session store the guest path as their target, which the
kernel cannot follow in the middle of a path once the session runs without
proot: the folders listed, but nothing inside them could be opened or created.
The desktop setup now makes a link again when it cannot be walked into, so it
is stored in the form the current mode follows.
2026-11-26 10:30:28 -05:00
MaxsTechReview dbfcd764f3 perf(nativeguest): keep relative parent walks relative inside mounts without links (#3249)
* perf(nativeguest): keep relative parent walks relative inside mounts without links

A relative path with .. made the hook rebuild the full absolute host
path, so every component was looked up again from the root of the card.
Inside a mount that cannot hold symlinks, a path that never climbs
above the mount resolves the same way relative to the working
directory, so the kernel now gets it unchanged.

* Keep the absolute walk when another guest bind sits inside the mount

* Check every guest path of the card's folder for nested binds

* Keep the absolute walk inside the rootfs and under identity binds

* Keep the absolute walk when two binds share a guest path
2026-11-26 09:48:56 -05:00
MaxsTechReview 96e4bd4eab 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.
2026-11-26 05:34:42 -05:00
Kurt Himebauch d788afc126 fix(gamescope): enter Steam at the corner it is reset to (#3253)
* fix(gamescope): enter Steam at the corner it is reset to

* docs(gamescope): explain the corner entry patch
2026-11-26 02:28:42 -05:00
Kurt Himebauch 50a7b1b9f5 fix(compositor): report a client's first hidden cursor (#3245) 2026-11-25 23:23:38 -05:00
21 changed files with 1562 additions and 427 deletions

No files matched your search

+1
View File
@@ -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.
@@ -620,7 +620,8 @@ static void cursor_publish_shown(void) {
static void cursor_publish_hidden(void) {
pthread_mutex_lock(&g_cursor_lock);
if (!g_cursor_hidden) { g_cursor_hidden = 1; g_cursor_serial++; }
// A client that hides the cursor before ever showing one (gamescope drawing its own) must still be reported.
if (!g_cursor_hidden || g_cursor_serial == 0) { g_cursor_hidden = 1; g_cursor_serial++; }
pthread_mutex_unlock(&g_cursor_lock);
}
@@ -517,30 +517,3 @@ A program started from the card was traced the same way. Three things were measu
The rest of that launch was the program's own launcher and CPU-bound start-up, which did
not wait on the card in these traces.
## Cold listings in native sessions (2026-11-25)
A Wine program on the card lists each directory with `opendir(".")` after `fchdir`, so
the Steam client's listing cache (absolute `/steamapps` paths, client process only) never
applies to it. Tracing a Battle.net launch showed the repeat listings were already cheap
(0.5 to 1 ms each, 0.27 s in all); the cost was the first, cold read of each directory
(about 78 ms each, 22 s for 290 directories).
`dircache.c` now times each `readdir` call in every program. When a call takes 20 ms or
more on FUSE, exFAT, FAT, NTFS3 or sdcardfs, and the program already runs more than one
thread, the subfolders that listing returns are read ahead by three background threads.
A program listing a folder that was read ahead has that folder's subfolders read ahead in
turn, so the read-ahead follows the program's own walk. The threads only read
directories, so nothing the program sees can be stale. `DD_NO_DIR_PREFETCH=1` turns it
off.
Paired cold runs on the FIT, both halves of the WoW AddOns tree after the same memory
eviction, with the halves swapped between runs:
| Tree | Off | On |
| --- | --- | --- |
| Deep tree, 125 directories | 13.6, 14.0, 13.8 s | 10.0, 11.2, 12.6 s |
| Shallow tree, 136 directories | 11.3, 9.3, 12.6 s | 10.2, 12.2, 12.0 s |
The gain is limited because cold directory reads on the card do not overlap: more reader
threads only hide the card's latency behind the program's own work between listings.
@@ -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 <GL/glx.h>
#include <EGL/egl.h>
+#include <EGL/eglext.h>
+#include <X11/Xlib.h>
+#ifndef _GNU_SOURCE
+#define _GNU_SOURCE
+#endif
+#include <dlfcn.h>
#include <stdio.h>
#include <cstring>
+#include <mutex>
+#include <set>
+#include <string>
+#include <string_view>
#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<void*>(&Self), &info) && info.dli_fname ? dlopen(info.dli_fname, RTLD_LAZY | RTLD_NOLOAD) : nullptr;
+ }();
+ return self;
+}
+
+static constexpr std::pair<std::string_view, std::string_view> 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<voidFunc*>(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<std::string> 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<decltype(XSync)>::Unpack);
+ fexfn_pack_EGL_SetGuestXDisplayString((uintptr_t)XDisplayString, (uintptr_t)CallbackUnpack<decltype(XDisplayString)>::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 <atomic>
#include <cstdio>
+#include <cstdlib>
#include <dlfcn.h>
+#include <mutex>
+#include <string_view>
+#include <unordered_map>
+#define EGL_EGLEXT_PROTOTYPES 1
#include <EGL/egl.h>
+#include <EGL/eglext.h>
#include "common/Host.h"
-#include <dlfcn.h>
+#include <X11/Xutil.h>
+#include "common/X11Manager.h"
+
+static X11Manager x11_manager;
+static std::mutex x11_displays_mutex;
+static std::unordered_map<EGLDisplay, _XDisplay*> x11_displays;
+
+static void* fex_egl_get_proc_address(void* so, const char* name) {
+ static auto get_proc_address = reinterpret_cast<void* (*)(const char*)>(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<void*> 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<void**>(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<xcb_connection_t*>(native));
+#endif
+ case 0:
+ if (auto env = EnvPlatform(); !env.empty()) {
+ if (env == "xcb") {
+ return x11_manager.GuestToHostConnection(static_cast<xcb_connection_t*>(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<EGLNativeDisplayType> native) {
+ _XDisplay* guest_x11 = nullptr;
+ auto host = HostNativeDisplay(0, native.force_get_host_pointer(), &guest_x11);
+ return TrackDisplay(fexldr_ptr_libEGL_eglGetDisplay(static_cast<EGLNativeDisplayType>(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 <common/GeneratorInterface.h>
+#define EGL_EGLEXT_PROTOTYPES 1
#include <EGL/egl.h>
+#include <EGL/eglext.h>
+#include <X11/Xlib.h>
template<auto>
struct fex_gen_config {
unsigned version = 1;
};
-// Function, parameter index, parameter type [optional]
template<auto, int, typename = void>
struct fex_gen_param {};
+template<typename>
+struct fex_gen_type {};
+
+template<>
+struct fex_gen_type<void> : 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<EGL_SetGuestXSync> : fexgen::custom_guest_entrypoint, fexgen::custom_host_impl {};
+template<>
+struct fex_gen_config<EGL_SetGuestXDisplayString> : fexgen::custom_guest_entrypoint, fexgen::custom_host_impl {};
+
template<>
struct fex_gen_config<eglBindAPI> {};
template<>
+struct fex_gen_config<eglBindTexImage> {};
+template<>
struct fex_gen_config<eglChooseConfig> {};
template<>
+struct fex_gen_config<eglClientWaitSync> {};
+template<>
+struct fex_gen_config<eglCreateContext> {};
+template<>
+struct fex_gen_config<eglCreateImage> {};
+template<>
+struct fex_gen_config<eglCreatePbufferFromClientBuffer> {};
+template<>
+struct fex_gen_config<eglCreatePbufferSurface> {};
+template<>
+struct fex_gen_config<eglCreateSync> {};
+template<>
struct fex_gen_config<eglDestroyContext> {};
template<>
+struct fex_gen_config<eglDestroyImage> {};
+template<>
struct fex_gen_config<eglDestroySurface> {};
template<>
+struct fex_gen_config<eglDestroySync> {};
+template<>
+struct fex_gen_config<eglGetConfigAttrib> {};
+template<>
+struct fex_gen_config<eglGetConfigs> {};
+template<>
+struct fex_gen_config<eglGetCurrentContext> {};
+template<>
+struct fex_gen_config<eglGetCurrentDisplay> {};
+template<>
+struct fex_gen_config<eglGetCurrentSurface> {};
+template<>
+struct fex_gen_config<eglGetError> {};
+template<>
+struct fex_gen_config<eglGetSyncAttrib> {};
+template<>
struct fex_gen_config<eglInitialize> {};
template<>
struct fex_gen_config<eglMakeCurrent> {};
template<>
+struct fex_gen_config<eglQueryAPI> {};
+template<>
+struct fex_gen_config<eglQueryContext> {};
+template<>
+struct fex_gen_config<eglQueryString> : fexgen::custom_guest_entrypoint {};
+template<>
struct fex_gen_config<eglQuerySurface> {};
template<>
+struct fex_gen_config<eglReleaseTexImage> {};
+template<>
+struct fex_gen_config<eglReleaseThread> {};
+template<>
struct fex_gen_config<eglSurfaceAttrib> {};
template<>
struct fex_gen_config<eglSwapBuffers> {};
template<>
+struct fex_gen_config<eglSwapInterval> {};
+template<>
struct fex_gen_config<eglTerminate> {};
template<>
-struct fex_gen_config<eglGetError> {};
+struct fex_gen_config<eglWaitClient> {};
template<>
-struct fex_gen_config<eglCreateContext> {};
+struct fex_gen_config<eglWaitGL> {};
template<>
-struct fex_gen_config<eglCreateWindowSurface> {};
+struct fex_gen_config<eglWaitNative> {};
template<>
-struct fex_gen_config<eglGetCurrentContext> {};
+struct fex_gen_config<eglWaitSync> {};
template<>
-struct fex_gen_config<eglGetCurrentDisplay> {};
+struct fex_gen_config<eglGetDisplay> : fexgen::custom_host_impl {};
template<>
-struct fex_gen_config<eglGetCurrentSurface> {};
+struct fex_gen_config<eglGetPlatformDisplay> : fexgen::custom_host_impl {};
+template<>
+struct fex_gen_config<eglCreateWindowSurface> : fexgen::custom_host_impl {};
+template<>
+struct fex_gen_config<eglCreatePixmapSurface> : fexgen::custom_host_impl {};
+template<>
+struct fex_gen_config<eglCreatePlatformWindowSurface> : fexgen::custom_host_impl {};
+template<>
+struct fex_gen_config<eglCreatePlatformPixmapSurface> : fexgen::custom_host_impl {};
+template<>
+struct fex_gen_config<eglCopyBuffers> : fexgen::custom_host_impl {};
+template<>
+struct fex_gen_param<eglGetDisplay, 0, EGLNativeDisplayType> : fexgen::ptr_passthrough {};
+
+namespace ext {
+template<auto>
+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<eglGetDisplay> {};
+struct fex_gen_config<eglSwapBuffersWithDamageKHR> {};
+template<>
+struct fex_gen_config<eglSwapBuffersWithDamageEXT> {};
+template<>
+struct fex_gen_config<eglSetDamageRegionKHR> {};
+template<>
+struct fex_gen_config<eglCreateImageKHR> {};
+template<>
+struct fex_gen_config<eglDestroyImageKHR> {};
+template<>
+struct fex_gen_config<eglCreateSyncKHR> {};
+template<>
+struct fex_gen_config<eglDestroySyncKHR> {};
+template<>
+struct fex_gen_config<eglClientWaitSyncKHR> {};
+template<>
+struct fex_gen_config<eglGetSyncAttribKHR> {};
+template<>
+struct fex_gen_config<eglWaitSyncKHR> {};
+template<>
+struct fex_gen_config<eglDupNativeFenceFDANDROID> {};
+template<>
+struct fex_gen_config<eglQueryDmaBufFormatsEXT> {};
+template<>
+struct fex_gen_config<eglQueryDmaBufModifiersEXT> {};
+template<>
+struct fex_gen_config<eglExportDMABUFImageMESA> {};
+template<>
+struct fex_gen_config<eglExportDMABUFImageQueryMESA> {};
+template<>
+struct fex_gen_config<eglQueryDisplayAttribEXT> {};
+template<>
+struct fex_gen_config<eglQueryDeviceStringEXT> {};
+template<>
+struct fex_gen_config<eglQueryDeviceAttribEXT> {};
+template<>
+struct fex_gen_config<eglQueryDevicesEXT> {};
+template<>
+struct fex_gen_config<eglGetPlatformDisplayEXT> : fexgen::custom_host_impl {};
+template<>
+struct fex_gen_config<eglCreatePlatformWindowSurfaceEXT> : fexgen::custom_host_impl {};
template<>
-struct fex_gen_param<eglGetDisplay, 0, EGLNativeDisplayType> : fexgen::assume_compatible_data_layout {};
+struct fex_gen_config<eglCreatePlatformPixmapSurfaceEXT> : 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 <charconv>
#include <cstdio>
#include <cstdarg>
+#include <cstdint>
+#include <cstdlib>
#include <cstring>
#include <string>
+#include <utility>
#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<std::size_t... I>
+static uint64_t WaylandAllocateUniformHostTrampoline(void (*callback)(), std::index_sequence<I...>) {
+ using cb = void(void*, wl_proxy*, std::conditional_t<true, uintptr_t, std::integral_constant<std::size_t, I>>...);
+ return (uint64_t)(uintptr_t)(void*)AllocateHostTrampolineForGuestFunction((cb*)callback);
+}
+
+template<std::size_t... Counts>
+static uint64_t WaylandAllocateUniformHostTrampoline(void (*callback)(), std::size_t count, std::index_sequence<Counts...>) {
+ using allocator = uint64_t (*)(void (*)());
+ static constexpr allocator allocators[] = {
+ [](void (*cb)()) { return WaylandAllocateUniformHostTrampoline(cb, std::make_index_sequence<Counts> {}); }...};
+ 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<WAYLAND_UNIFORM_MAX_ARGS + 1> {});
} 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_interface*>(&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 <map>
#include <span>
#include <string>
+#include <utility>
#include <ranges>
@@ -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<wl_argument*> 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<std::size_t... I>
+static void WaylandFinalizeUniformHostTrampoline(void (*callback)(), std::index_sequence<I...>) {
+ using cb = void(void*, wl_proxy*, std::conditional_t<true, uint64_t, std::integral_constant<std::size_t, I>>...);
+ FinalizeHostTrampolineForGuestFunction((cb*)callback);
+}
+
+template<std::size_t... Counts>
+static void WaylandFinalizeUniformHostTrampoline(void (*callback)(), std::size_t count, std::index_sequence<Counts...>) {
+ using finalizer = void (*)(void (*)());
+ static constexpr finalizer finalizers[] = {
+ [](void (*cb)()) { WaylandFinalizeUniformHostTrampoline(cb, std::make_index_sequence<Counts> {}); }...};
+ finalizers[count](callback);
+}
+
extern "C" int
fexfn_impl_libwayland_client_wl_proxy_add_listener(struct wl_proxy* proxy, guest_layout<void (**)(void)> 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<WAYLAND_UNIFORM_MAX_ARGS + 1> {});
} 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<const wl_interface**> 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<uintptr_t>(guest);
+ }
+ }
+ if (!result) {
+ result = reinterpret_cast<uintptr_t>(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<wl_display_get_fd> {};
template<>
struct fex_gen_config<wl_event_queue_destroy> {};
+template<>
+struct fex_gen_config<wl_event_queue_get_name> {};
+template<>
+struct fex_gen_config<wl_display_create_queue_with_name> {};
+template<>
+struct fex_gen_config<wl_display_set_max_buffer_size> {};
+template<>
+struct fex_gen_config<wl_display_get_protocol_error> : fexgen::custom_host_impl {};
+template<>
+struct fex_gen_param<wl_display_get_protocol_error, 1, const wl_interface**> : fexgen::ptr_passthrough {};
template<>
struct fex_gen_config<wl_proxy_add_listener> : fexgen::custom_host_impl, fexgen::custom_guest_entrypoint {};
@@ -101,6 +111,10 @@ struct fex_gen_config<wl_proxy_create_wrapper> {};
template<>
struct fex_gen_config<wl_proxy_get_class> {};
template<>
+struct fex_gen_config<wl_proxy_get_display> {};
+template<>
+struct fex_gen_config<wl_proxy_get_queue> {};
+template<>
struct fex_gen_config<wl_proxy_get_id> {};
template<>
struct fex_gen_config<wl_proxy_get_listener> {};
@@ -164,6 +178,6 @@ struct fex_gen_config<fex_wl_get_interface_event_count> : fexgen::custom_host_im
void fex_wl_get_interface_event_name(wl_proxy*, int, char*);
template<>
struct fex_gen_config<fex_wl_get_interface_event_name> : 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<fex_wl_get_interface_event_signature> : 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 <wayland-egl.h>
+
+#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 <wayland-egl.h>
+
+#include "common/Host.h"
+#include <dlfcn.h>
+
+#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 <common/GeneratorInterface.h>
+
+#include <wayland-egl.h>
+
+template<auto>
+struct fex_gen_config {
+ unsigned version = 1;
+};
+
+template<typename>
+struct fex_gen_type {};
+
+template<>
+struct fex_gen_type<wl_egl_window> : fexgen::opaque_type {};
+template<>
+struct fex_gen_type<wl_surface> : fexgen::opaque_type {};
+
+template<>
+struct fex_gen_config<wl_egl_window_create> {};
+template<>
+struct fex_gen_config<wl_egl_window_destroy> {};
+template<>
+struct fex_gen_config<wl_egl_window_resize> {};
+template<>
+struct fex_gen_config<wl_egl_window_get_attached_size> {};
+19
View File
@@ -425,3 +425,22 @@ at a pointer that never left the top-left corner. Steam picks Disabled for some
cursor followed the mouse while every click landed at (0,0). In Disabled the nested pointer now warps the X pointer as
in the other modes; real fingers are still ignored. `tools/tests/test_gamescope_disabled_touch_mouse.py` compiles the
branch from this patch.
## 0142 Steam is entered at the corner it is reset to
When Steam's window takes focus with `bResetToCorner`, gamescope parks the pointer in its bottom-right corner so
nothing in Big Picture is hovered and the controller owns the UI. Upstream fe7f21c (3.16.24) moved
`wlserver_mousefocus` ahead of that reset, so the window is first entered under the current pointer, then warped to
its centre (`wlserver_mousewarp`, synthetic), then moved to the corner. SteamOS's 3.16.23 still resets before focus,
so its motions reach no window and the X pointer stays at (0,0). On upstream 3.16.29 they reach Steam: on a Steam Deck
the pointer is at (1279,799) right after focus. The Deck shows no hover because Big Picture's page exists about 1 s
before the reset. On a Retroid Pocket Duo the page is created at the same moment, Chromium keeps the centre position
as its hover, and the second library tile stayed highlighted on every start (4 of 4).
Steam is now entered at the corner. The centre is still stored in `mouse_surface_cursorx/y`, so the gamepad cursor
starts there as before, but no motion is sent for it. The fake pointer position stays in the corner. Only the
`bResetToCorner` path changes. Other windows are entered under the pointer as upstream does.
With the patch, the Duo starts with only the bottom bar under the parked pointer hovered and controller focus on the
first tile (4 of 4 starts), and returns from a game the same way (3 of 3). Making 0100 ignore the X server's initial
pointer instead was tried and rejected: the centre motion still arrived, and the header or search bar ended up hovered.
@@ -0,0 +1,31 @@
diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp
--- a/src/steamcompmgr.cpp
+++ b/src/steamcompmgr.cpp
@@ -5790,7 +5790,16 @@
if ( win_surface(pFocus->inputFocusWindow) != nullptr && pFocus->cursor )
{
- wlserver_mousefocus( pFocus->inputFocusWindow->main_surface(), pFocus->cursor->x(), pFocus->cursor->y() );
+ int nEnterX = pFocus->cursor->x();
+ int nEnterY = pFocus->cursor->y();
+ // A window reset to the corner below must not first be entered under the cursor:
+ // a page that loads during the reset keeps that position as its hover.
+ if ( pFocus->inputFocusWindow->GetFocus()->bResetToCorner )
+ {
+ nEnterX = pFocus->inputFocusWindow->GetGeometry().nWidth - 1;
+ nEnterY = pFocus->inputFocusWindow->GetGeometry().nHeight - 1;
+ }
+ wlserver_mousefocus( pFocus->inputFocusWindow->main_surface(), nEnterX, nEnterY );
focus_log.debugf( "Setting mouse focus to: %s (%x)", pFocus->inputFocusWindow->debug_name(), pFocus->inputFocusWindow->id() );
}
@@ -5813,7 +5822,8 @@
if ( pFocus->inputFocusWindow->GetFocus()->bResetToCorner )
{
wlserver_lock();
- wlserver_mousewarp( pFocus->inputFocusWindow->GetGeometry().nWidth / 2, pFocus->inputFocusWindow->GetGeometry().nHeight / 2, 0, true );
+ wlserver.mouse_surface_cursorx = pFocus->inputFocusWindow->GetGeometry().nWidth / 2;
+ wlserver.mouse_surface_cursory = pFocus->inputFocusWindow->GetGeometry().nHeight / 2;
wlserver_fake_mouse_pos( pFocus->inputFocusWindow->GetGeometry().nWidth - 1, pFocus->inputFocusWindow->GetGeometry().nHeight - 1 );
wlserver_unlock();
}
@@ -115,7 +115,7 @@ def link_libraries():
common = os.path.join(library, "steamapps", "common")
link = os.path.join(HOME, label)
if os.path.isdir(common):
if os.path.islink(link) and os.readlink(link) == common:
if os.path.islink(link) and os.readlink(link) == common and os.path.isdir(os.path.join(link, ".")):
continue
if os.path.islink(link) or os.path.isfile(link):
os.unlink(link)
@@ -10,7 +10,7 @@ free_name() {
share() {
local android=$HOME/Storage/$1 link=$HOME/$2 f
[ -d "$android" ] && [ -w "$android" ] || return 0
[ "$(readlink "$link" 2>/dev/null)" = "$android" ] && return 0
[ "$(readlink "$link" 2>/dev/null)" = "$android" ] && [ -d "$link/." ] && return 0
if [ -L "$link" ]; then
rm -f "$link"
elif [ -d "$link" ]; then
@@ -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")
@@ -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
+3 -260
View File
@@ -5,7 +5,6 @@
#include <fcntl.h>
#include <limits.h>
#include <pthread.h>
#include <signal.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdint.h>
@@ -683,267 +682,12 @@ static void finish(struct handle *h) {
give(&lock);
}
#define PREFETCH_SLOW_NS 20000000LL
#define PREFETCH_THREADS 3
#define PREFETCH_QUEUE 512
#define PREFETCH_BATCH 128
#define PREFETCH_SCANS 16
#define PREFETCH_SEEN 1024
#define EXFAT_MAGIC 0x2011BAB0
#define MSDOS_MAGIC 0x4d44
#define NTFS3_MAGIC 0x7366746e
#define SDCARDFS_MAGIC 0x5dca2df5
struct scan { char *path; char *names[PREFETCH_BATCH]; int n; };
static pthread_mutex_t qlock = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t qwake = PTHREAD_COND_INITIALIZER;
static char *queue[PREFETCH_QUEUE];
static int qtop, qcount;
static int workers;
static struct scan *scans[PREFETCH_SCANS];
static DIR *scan_keys[PREFETCH_SCANS];
static struct { dev_t dev; ino_t ino; } seen[PREFETCH_SEEN];
static int nseen, seen_at;
static int prefetching(void) {
static int on = -1;
if (on < 0) {
const char *off = getenv("DD_NO_DIR_PREFETCH");
on = !(off && strcmp(off, "1") == 0);
}
return on;
}
static void prefetch_fork(void) {
pthread_mutex_init(&qlock, NULL);
pthread_cond_init(&qwake, NULL);
for (int i = 0; i < PREFETCH_QUEUE; i++) queue[i] = NULL;
qtop = qcount = workers = 0;
for (int i = 0; i < PREFETCH_SCANS; i++) {
scans[i] = NULL;
scan_keys[i] = NULL;
}
nseen = seen_at = 0;
}
__attribute__((constructor)) static void prefetch_init(void) {
pthread_atfork(NULL, NULL, prefetch_fork);
}
static long long precise_ns(void) {
struct timespec t;
clock_gettime(CLOCK_MONOTONIC, &t);
return (long long)t.tv_sec * 1000000000LL + t.tv_nsec;
}
static int slow_storage(int fd) {
struct statfs fs;
if (fstatfs(fd, &fs) != 0) return 0;
unsigned long type = (unsigned long)fs.f_type;
return type == FUSE_MAGIC || type == EXFAT_MAGIC || type == MSDOS_MAGIC || type == NTFS3_MAGIC ||
type == SDCARDFS_MAGIC;
}
static int threaded(void) {
char buf[1024];
int fd = open("/proc/self/stat", O_RDONLY | O_CLOEXEC);
if (fd < 0) return 0;
ssize_t n = read(fd, buf, sizeof(buf) - 1);
close(fd);
if (n <= 0) return 0;
buf[n] = 0;
char *at = strrchr(buf, ')');
long count = 0;
if (at == NULL || sscanf(at + 2, "%*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %*u %*u %*d %*d %*d %*d %ld", &count) != 1)
return 0;
return count > 1;
}
static int was_seen(dev_t dev, ino_t ino) {
for (int i = 0; i < nseen; i++)
if (seen[i].ino == ino && seen[i].dev == dev) return 1;
return 0;
}
static void *prefetcher(void *arg) {
(void)arg;
pthread_setname_np(pthread_self(), "dd-prefetch");
NEXT(opendir);
NEXT(readdir64);
NEXT(closedir);
NEXT(dirfd);
for (;;) {
pthread_mutex_lock(&qlock);
while (qcount == 0) pthread_cond_wait(&qwake, &qlock);
qtop = (qtop + PREFETCH_QUEUE - 1) % PREFETCH_QUEUE;
char *path = queue[qtop];
queue[qtop] = NULL;
qcount--;
pthread_mutex_unlock(&qlock);
DIR *d = next_opendir(path);
free(path);
if (d == NULL) continue;
struct stat st;
if (fstat(next_dirfd(d), &st) == 0) {
pthread_mutex_lock(&qlock);
if (!was_seen(st.st_dev, st.st_ino)) {
seen[seen_at].dev = st.st_dev;
seen[seen_at].ino = st.st_ino;
seen_at = (seen_at + 1) % PREFETCH_SEEN;
if (nseen < PREFETCH_SEEN) __atomic_store_n(&nseen, nseen + 1, __ATOMIC_RELEASE);
}
pthread_mutex_unlock(&qlock);
}
while (next_readdir64(d)) {}
next_closedir(d);
}
return NULL;
}
static void start_prefetchers(void) {
pthread_attr_t attr;
sigset_t all, old;
if (pthread_attr_init(&attr) != 0) return;
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
pthread_attr_setstacksize(&attr, 256 * 1024);
sigfillset(&all);
pthread_sigmask(SIG_SETMASK, &all, &old);
while (workers < PREFETCH_THREADS) {
pthread_t t;
if (pthread_create(&t, &attr, prefetcher, NULL) != 0) break;
workers++;
}
pthread_sigmask(SIG_SETMASK, &old, NULL);
pthread_attr_destroy(&attr);
}
static void flush_scan(struct scan *s) {
size_t base = strlen(s->path);
pthread_mutex_lock(&qlock);
for (int i = s->n - 1; i >= 0; i--) {
size_t n = strlen(s->names[i]);
char *child = base + n + 2 <= PATH_MAX ? malloc(base + n + 2) : NULL;
if (child) {
memcpy(child, s->path, base);
child[base] = '/';
memcpy(child + base + 1, s->names[i], n + 1);
if (qcount == PREFETCH_QUEUE) free(queue[qtop]);
else qcount++;
queue[qtop] = child;
qtop = (qtop + 1) % PREFETCH_QUEUE;
}
free(s->names[i]);
}
s->n = 0;
if (qcount > 0) {
if (workers < PREFETCH_THREADS) start_prefetchers();
pthread_cond_broadcast(&qwake);
}
pthread_mutex_unlock(&qlock);
}
static int scan_slot(DIR *key) {
for (int i = 0; i < PREFETCH_SCANS; i++) {
if (__atomic_load_n(&scan_keys[i], __ATOMIC_ACQUIRE) == key) return i;
}
return -1;
}
static void end_scan(DIR *key) {
int i = scan_slot(key);
if (i < 0) return;
struct scan *s = scans[i];
scans[i] = NULL;
__atomic_store_n(&scan_keys[i], NULL, __ATOMIC_RELEASE);
flush_scan(s);
free(s->path);
free(s);
}
static void begin_scan(DIR *key, int fd) {
char link[64], path[PATH_MAX];
snprintf(link, sizeof(link), "/proc/self/fd/%d", fd);
ssize_t n = readlink(link, path, sizeof(path) - 1);
if (n <= 0 || path[0] != '/') return;
path[n] = 0;
struct scan *s = calloc(1, sizeof(*s));
if (s == NULL || (s->path = strdup(path)) == NULL) {
free(s);
return;
}
pthread_mutex_lock(&qlock);
for (int i = 0; i < PREFETCH_SCANS; i++) {
if (__atomic_load_n(&scan_keys[i], __ATOMIC_ACQUIRE) == NULL) {
scans[i] = s;
__atomic_store_n(&scan_keys[i], key, __ATOMIC_RELEASE);
s = NULL;
break;
}
}
pthread_mutex_unlock(&qlock);
if (s) {
free(s->path);
free(s);
}
}
static int continues_walk(DIR *real, int fd) {
if (__atomic_load_n(&nseen, __ATOMIC_ACQUIRE) == 0 || next_telldir(real) != 0) return 0;
struct stat st;
if (fstat(fd, &st) != 0) return 0;
pthread_mutex_lock(&qlock);
int found = was_seen(st.st_dev, st.st_ino);
pthread_mutex_unlock(&qlock);
return found;
}
static void note(struct scan *s, const struct dirent64 *r) {
if (r->d_type != DT_DIR || strcmp(r->d_name, ".") == 0 || strcmp(r->d_name, "..") == 0 || s->n >= PREFETCH_BATCH)
return;
if ((s->names[s->n] = strdup(r->d_name)) != NULL) s->n++;
}
static struct dirent64 *pull(DIR *key, DIR *real, struct dirent64 *(*next)(DIR *)) {
if (holding || !prefetching()) return next(real);
NEXT(telldir);
NEXT(dirfd);
int i = scan_slot(key);
if (i < 0) {
int saved = errno;
int fd = next_dirfd(real);
int walk = continues_walk(real, fd);
errno = saved;
long long start = walk ? 0 : precise_ns();
struct dirent64 *r = next(real);
if (r == NULL) return r;
saved = errno;
if (walk || (precise_ns() - start >= PREFETCH_SLOW_NS && slow_storage(fd) &&
(__atomic_load_n(&workers, __ATOMIC_ACQUIRE) > 0 || threaded())))
begin_scan(key, fd);
i = scan_slot(key);
errno = saved;
if (i < 0) return r;
note(scans[i], r);
return r;
}
struct dirent64 *r = next(real);
int saved = errno;
if (r == NULL) {
end_scan(key);
} else {
note(scans[i], r);
}
errno = saved;
return r;
}
static struct dirent64 *entry(struct handle *h) {
NEXT(readdir64);
if (h->real) {
int saved = errno;
errno = 0;
struct dirent64 *r = pull((DIR *)h, h->real, next_readdir64);
struct dirent64 *r = next_readdir64(h->real);
int error = errno;
if (h->fill) {
if (r) {
@@ -967,13 +711,13 @@ static struct dirent64 *entry(struct handle *h) {
struct dirent64 *readdir64(DIR *d) {
NEXT(readdir64);
struct handle *h = lookup(d);
return h ? entry(h) : pull(d, d, next_readdir64);
return h ? entry(h) : next_readdir64(d);
}
struct dirent *readdir(DIR *d) {
NEXT(readdir);
struct handle *h = lookup(d);
return h ? (struct dirent *)entry(h) : (struct dirent *)pull(d, d, (struct dirent64 * (*)(DIR *))next_readdir);
return h ? (struct dirent *)entry(h) : next_readdir(d);
}
#pragma GCC diagnostic push
@@ -1003,7 +747,6 @@ int readdir_r(DIR *d, struct dirent *out, struct dirent **result) {
int closedir(DIR *d) {
NEXT(closedir);
if (holding && registered(d) < 0) return next_closedir(d);
end_scan(d);
take(&lock);
int i = registered(d);
struct handle *h = i >= 0 ? handles[i] : NULL;
+3
View File
@@ -445,12 +445,15 @@ static void load_app_ids(void) {
__atomic_store_n(&g_app_uid, uid, __ATOMIC_RELAXED);
}
#define ANDROID_MEDIA_RW_GID ((gid_t)1023)
static void present_owner_as_root(uid_t *uid, gid_t *gid) {
if (__atomic_load_n(&g_app_uid, __ATOMIC_RELAXED) == (uid_t)-1) load_app_ids();
uid_t app_uid = __atomic_load_n(&g_app_uid, __ATOMIC_RELAXED);
gid_t app_gid = __atomic_load_n(&g_app_gid, __ATOMIC_RELAXED);
if (app_uid == (uid_t)-1) return;
if (uid && *uid == app_uid) *uid = 0;
if (uid && gid && *gid == ANDROID_MEDIA_RW_GID) *uid = 0;
if (gid && *gid == app_gid) *gid = 0;
}
+22
View File
@@ -1081,6 +1081,27 @@ static void ddnatv_build_at_dirs(void) {
}
#if defined(__aarch64__)
static int stays_in_plain_bind(const char *host, const char *rel) {
if (get_rootfs_subpath(host)) return 0;
struct ddnatv_bind *best = NULL;
for (int i = 0; i < g_nbinds; i++) {
struct ddnatv_bind *b = &g_binds[i];
if (b->identity || !is_path_prefix(host, b->src, b->src_len)) continue;
if (!best || b->src_len > best->src_len) best = b;
}
if (!best) return 0;
for (int i = 0; i < g_nbinds; i++) {
struct ddnatv_bind *cover = &g_binds[i];
if (cover->identity || !is_path_prefix(host, cover->src, cover->src_len)) continue;
for (int j = 0; j < g_nbinds; j++) {
struct ddnatv_bind *b = &g_binds[j];
if (j != i && b->dst_len >= cover->dst_len && is_path_prefix(b->dst, cover->dst, cover->dst_len))
return 0;
}
}
return !climbs_past_root(host + best->src_len, rel) && bind_holds_no_links(best);
}
static const char *map_parent_walk(int dirfd, const char *rel, char *buf, size_t size) {
char link[32], host[PATH_MAX], dir_buf[PATH_MAX], guest[PATH_MAX];
if (dirfd == AT_FDCWD) ddnatv_copy_cstr(link, sizeof(link), "/proc/self/cwd");
@@ -1088,6 +1109,7 @@ static const char *map_parent_walk(int dirfd, const char *rel, char *buf, size_t
long n = raw_readlinkat(AT_FDCWD, link, host, sizeof(host) - 1);
if (n <= 0 || host[0] != '/') return NULL;
host[n] = '\0';
if (stays_in_plain_bind(host, rel)) return NULL;
const char *dir = guest_path_of_host_dir(host, dir_buf, sizeof(dir_buf));
if (!dir || strcmp(dir, host) == 0) return NULL;
if (get_rootfs_subpath(host) && !climbs_past_root(dir, rel)) return NULL;
+59
View File
@@ -0,0 +1,59 @@
import os
import subprocess
import tempfile
import unittest
from pathlib import Path
SCRIPT = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-downloads"
class DesktopDownloadsTest(unittest.TestCase):
def run_script(self, home, shim=None):
env = dict(os.environ, HOME=str(home))
if shim:
env["PATH"] = f"{shim}:{env['PATH']}"
subprocess.run(["bash", str(SCRIPT)], env=env, check=True)
def make_home(self, temp):
home = Path(temp) / "home"
for name in ("Download", "Documents"):
(home / "Storage" / name).mkdir(parents=True)
return home
def test_links_to_the_android_folders_are_made(self):
with tempfile.TemporaryDirectory() as temp:
home = self.make_home(temp)
self.run_script(home)
self.assertEqual(str(home / "Storage/Download"), os.readlink(home / "Downloads"))
self.assertEqual(str(home / "Storage/Documents"), os.readlink(home / "Documents"))
def test_working_links_are_kept(self):
with tempfile.TemporaryDirectory() as temp:
home = self.make_home(temp)
self.run_script(home)
before = os.lstat(home / "Downloads").st_ino
self.run_script(home)
self.assertEqual(before, os.lstat(home / "Downloads").st_ino)
def test_links_that_name_the_folder_but_cannot_be_walked_are_made_again(self):
with tempfile.TemporaryDirectory() as temp:
home = self.make_home(temp)
for link in ("Downloads", "Documents"):
os.symlink(str(Path(temp) / "gone"), home / link)
shim = Path(temp) / "bin"
shim.mkdir()
(shim / "readlink").write_text(
'#!/bin/bash\ncase "${@: -1}" in\n'
f' "{home}/Downloads") echo "{home}/Storage/Download" ;;\n'
f' "{home}/Documents") echo "{home}/Storage/Documents" ;;\n'
' *) exec /usr/bin/readlink "$@" ;;\nesac\n')
(shim / "readlink").chmod(0o755)
self.run_script(home, shim)
for link, folder in (("Downloads", "Download"), ("Documents", "Documents")):
self.assertEqual(str(home / "Storage" / folder), os.readlink(home / link))
self.assertTrue((home / link / ".").is_dir())
self.assertEqual([], sorted(p.name for p in home.iterdir() if ".old." in p.name))
if __name__ == "__main__":
unittest.main()
-131
View File
@@ -20,40 +20,9 @@ FAKE = r"""
#include <sys/stat.h>
#include <sys/statfs.h>
#include <sys/inotify.h>
#include <sys/prctl.h>
#include <unistd.h>
int real_opendirs;
static int prefetcher(void) {
char name[16] = "";
prctl(PR_GET_NAME, name);
return strcmp(name, "dd-prefetch") == 0;
}
static void cold(DIR *d) {
const char *slow = getenv("SLOW");
char link[64], path[4096];
if (!slow || prefetcher()) return;
snprintf(link, sizeof(link), "/proc/self/fd/%d", dirfd(d));
ssize_t n = readlink(link, path, sizeof(path) - 1);
path[n > 0 ? n : 0] = 0;
if (n > 5 && !strcmp(path + n - 5, "/cold")) usleep(atoi(slow) * 1000);
}
struct dirent *readdir(DIR *d) {
static struct dirent *(*next)(DIR *);
if (!next) next = dlsym(RTLD_NEXT, "readdir");
cold(d);
return next(d);
}
struct dirent64 *readdir64(DIR *d) {
static struct dirent64 *(*next)(DIR *);
if (!next) next = dlsym(RTLD_NEXT, "readdir64");
cold(d);
return next(d);
}
int real_accesses;
int real_stats;
@@ -161,30 +130,9 @@ int statfs(const char *path, struct statfs *out) {
return r;
}
int closedir(DIR *d) {
static int (*next)(DIR *);
if (!next) next = dlsym(RTLD_NEXT, "closedir");
const char *log = prefetcher() ? getenv("PREFETCH_DONE") : NULL;
FILE *f = log ? fopen(log, "a") : NULL;
if (f) {
fprintf(f, "done\n");
fclose(f);
}
return next(d);
}
DIR *opendir(const char *path) {
static DIR *(*next)(const char *);
if (!next) next = dlsym(RTLD_NEXT, "opendir");
if (prefetcher()) {
const char *log = getenv("PREFETCH_LOG");
FILE *f = log ? fopen(log, "a") : NULL;
if (f) {
fprintf(f, "%s\n", path);
fclose(f);
}
return next(path);
}
if (getenv("FASTPATH")) {
int fd = open(path, O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NONBLOCK);
DIR *d = fd < 0 ? NULL : fdopendir(fd);
@@ -259,12 +207,6 @@ static void raw(const char *dir) {
print(names, n);
}
static void *idle(void *arg) {
(void)arg;
pause();
return NULL;
}
static const char *stress_dir;
static int stop;
@@ -408,29 +350,6 @@ int main(int argc, char **argv) {
if (d) closedir(d);
i += 2;
}
else if (!strcmp(op, "sleep")) { usleep(atoi(a) * 1000); i++; }
else if (!strcmp(op, "await")) {
const char *log = getenv("PREFETCH_DONE");
int lines = 0;
for (int tries = 0; tries < 2000 && lines < atoi(a); tries++) {
FILE *f = log ? fopen(log, "r") : NULL;
int c;
lines = 0;
while (f && (c = fgetc(f)) != EOF) lines += c == '\n';
if (f) fclose(f);
if (lines < atoi(a)) usleep(5000);
}
if (lines < atoi(a)) return 3;
i++;
}
else if (!strcmp(op, "threads")) {
FILE *f = fopen("/proc/self/status", "r");
char line[256];
while (f && fgets(line, sizeof(line), f))
if (!strncmp(line, "Threads:", 8)) printf("%d\n", atoi(line + 8));
if (f) fclose(f);
}
else if (!strcmp(op, "thread")) { pthread_t t; pthread_create(&t, NULL, idle, NULL); }
else if (!strcmp(op, "stats")) printf("%d\n", stats ? *stats : -1);
else if (!strcmp(op, "accesses")) printf("%d\n", accesses ? *accesses : -1);
else if (!strcmp(op, "opens")) printf("%d\n", opens ? *opens : -1);
@@ -978,56 +897,6 @@ class DirCachePreloadTest(unittest.TestCase):
out = self.run_program("list", self.staging, "list", self.staging, "opens", env={"DD_NO_DIR_CACHE": "1"})
self.assertEqual("2", out[-1])
def cold_tree(self, root):
top = root / "cold"
for sub in ("a/deep/leaf", "b", "c"):
(top / sub).mkdir(parents=True)
(top / "f.txt").touch()
return top.resolve()
def prefetched(self, *args, program=None, env=None):
logs = Path(tempfile.mkdtemp(dir=self.dir))
log = logs / "prefetch.log"
out = self.run_program("thread", *args, program=program,
env=dict({"SLOW": "40", "PREFETCH_LOG": str(log),
"PREFETCH_DONE": str(logs / "done.log")}, **(env or {})))
return out, sorted(log.read_text().splitlines()) if log.exists() else []
def test_slow_listings_on_slow_storage_prefetch_the_walk_ahead(self):
for program, root in ((self.other, self.lib.parent), (self.steam, self.lib)):
top = self.cold_tree(root)
out, fetched = self.prefetched("list", top, "await", 3, "list", top / "a", "await", 4, program=program)
self.assertEqual(["a,b,c,f.txt", "deep"], out)
self.assertEqual(sorted(str(top / d) for d in ("a", "a/deep", "b", "c")), fetched)
def test_only_slow_listings_on_slow_storage_are_prefetched(self):
internal = self.cold_tree(Path(tempfile.mkdtemp(dir=self.dir)) / "ext4")
warm = self.lib.parent / "warm"
(warm / "child").mkdir(parents=True)
top = self.cold_tree(self.lib.parent)
out, fetched = self.prefetched("list", internal, "list", warm, "list", top, "await", 3, program=self.other)
self.assertEqual(["a,b,c,f.txt", "child", "a,b,c,f.txt"], out)
self.assertEqual(sorted(str(top / d) for d in ("a", "b", "c")), fetched)
def test_single_threaded_programs_stay_single_threaded(self):
top = self.cold_tree(self.lib.parent)
logs = Path(tempfile.mkdtemp(dir=self.dir))
log = logs / "prefetch.log"
env = {"SLOW": "40", "PREFETCH_LOG": str(log), "PREFETCH_DONE": str(logs / "done.log")}
out = self.run_program("list", top, "threads", program=self.other, env=env)
self.assertEqual(["a,b,c,f.txt", "1"], out)
self.assertFalse(log.exists())
self.run_program("thread", "list", top, "await", 3, program=self.other, env=env)
self.assertEqual(sorted(str(top / d) for d in ("a", "b", "c")), sorted(log.read_text().splitlines()))
def test_prefetching_can_be_turned_off(self):
top = self.cold_tree(self.lib.parent)
out, off = self.prefetched("list", top, "threads", program=self.other, env={"DD_NO_DIR_PREFETCH": "1"})
_, on = self.prefetched("list", top, "await", 3, program=self.other)
self.assertEqual(["a,b,c,f.txt", "2"], out)
self.assertEqual([], off)
self.assertEqual(sorted(str(top / d) for d in ("a", "b", "c")), on)
if __name__ == "__main__":
unittest.main()
+16
View File
@@ -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)
+39 -1
View File
@@ -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)
+151
View File
@@ -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()
+62 -1
View File
@@ -195,7 +195,7 @@ class NativeHookMountTest(unittest.TestCase):
if syscalls and not shutil.which("strace"):
self.skipTest("no strace")
if syscalls:
cmd = ["strace", "-f", "-qq", "-e", "trace=readlinkat"]
cmd = ["strace", "-f", "-qq", "-e", "trace=readlinkat,newfstatat,fstatat64,statx"]
cmd += [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
else:
cmd = []
@@ -482,6 +482,67 @@ class NativeHookMountTest(unittest.TestCase):
self.assertNotEqual(self.readlinks_of(log, f"{self.links}/guest"), [], table)
self.assertNotEqual(self.readlinks_of(log, f"{self.root}/etc/hostname"), [], table)
def test_relative_parent_walks_inside_mounts_without_links_stay_relative(self):
real, _, _ = self.links_volume()
binds = f"{self.links}:/mnt/links"
paths = {"sub/deeper/../file.txt": ["1", "deep"], "sub/deeper/more/../more/leaf.txt": ["1", "leaf"],
"../real/sub/file.txt": ["1", "deep"], "../../../etc/hostname": ["1", "rootfs"],
"sub/../../../../etc/hostname": ["1", "rootfs"]}
for kind, relative in (("exfat", True), ("ext4", False)):
table = [("/", "ext4", "/dev/root"), (real, kind, "/dev/sdb1")]
result, log = self.run_probe("cd:/mnt/links/real", *paths, binds=binds, mounts=table, syscalls=True)
for path, want in paths.items():
self.assertEqual(result[path], want, (path, kind))
stats = [m.group(1) for m in re.finditer(r'(?:fstatat|statx)\([^,"]*,\s*"([^"]*)"', log)]
for path in ("sub/deeper/../file.txt", "sub/deeper/more/../more/leaf.txt", "../real/sub/file.txt"):
self.assertEqual(path in stats, relative, (path, kind, stats))
for path in ("../../../etc/hostname", "sub/../../../../etc/hostname"):
self.assertNotIn(path, stats, (path, kind))
nested = f"{binds}|{self.library}:/mnt/links/real/sub"
table = [("/", "ext4", "/dev/root"), (real, "exfat", "/dev/sdb1")]
result, log = self.run_probe("cd:/mnt/links/real", "sub/deeper/../game.txt", binds=nested, mounts=table,
syscalls=True)
stats = [m.group(1) for m in re.finditer(r'(?:fstatat|statx)\([^,"]*,\s*"([^"]*)"', log)]
self.assertNotIn("sub/deeper/../game.txt", stats)
walk = "sub/Some Game/../Some Game/game.txt"
for order in ((f"{self.links}:/mnt/links", f"{self.links}:/mnt/longer/alias"),
(f"{self.links}:/mnt/longer/alias", f"{self.links}:/mnt/links")):
shared = "|".join(order) + f"|{self.library}:/mnt/links/real/sub"
results = [self.run_probe("cd:/mnt/links/real", walk, binds=shared,
mounts=[("/", "ext4", "/dev/root"), (real, kind, "/dev/sdb1")])[walk]
for kind in ("ext4", "exfat")]
self.assertEqual(results[0], results[1], order)
def test_relative_parent_walks_honour_identity_binds_shared_guest_paths_and_the_rootfs(self):
real, _, _ = self.links_volume()
tmp = os.path.realpath(self.tmp.name)
card = f"{tmp}/identity-card"
os.makedirs(f"{card}/real/sub/deeper", exist_ok=True)
Path(f"{card}/real/sub/file.txt").write_text("identity")
binds = f"{self.links}:{card}|{card}/real/sub:{card}/real/sub"
walk = "sub/deeper/../file.txt"
results = [self.run_probe(f"cd:{card}/real", walk, binds=binds,
mounts=[("/", "ext4", "/dev/root"), (real, kind, "/dev/sdb1")])[walk]
for kind in ("ext4", "exfat")]
self.assertEqual(results[0], results[1])
twins = (f"{tmp}/twin-a", f"{tmp}/twin-b")
for twin in twins:
os.makedirs(f"{twin}/only/sub/deeper", exist_ok=True)
Path(f"{twin}/only/sub/file.txt").write_text(os.path.basename(twin))
for order in (twins, twins[::-1]):
shared = "|".join(f"{src}:/mnt/twin" for src in order)
result, log = self.run_probe("cd:/mnt/twin/only", walk, binds=shared, syscalls=True,
mounts=[("/", "ext4", "/dev/root")] +
[(twin, "exfat", f"/dev/sd{i}1") for i, twin in zip("bc", twins)])
stats = [m.group(1) for m in re.finditer(r'(?:fstatat|statx)\([^,"]*,\s*"([^"]*)"', log)]
self.assertEqual(result[walk], ["1", os.path.basename(order[0])], order)
self.assertNotIn(walk, stats, order)
climb = "../../etc/hostname"
for kind in ("ext4", "exfat"):
result = self.run_probe("cd:/etc", climb, binds=f"{tmp}:/mnt/card",
mounts=[("/", "ext4", "/dev/root"), (tmp, kind, "/dev/sdb1")])
self.assertEqual(result[climb], ["1", "rootfs"], kind)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,131 @@
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
from tools.tests.test_usr2_preload import runner
HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh"
OWNERS = r"""
#define _GNU_SOURCE
#include <dlfcn.h>
#include <fcntl.h>
#include <string.h>
#include <sys/stat.h>
static void owner(const char *path, unsigned *uid, unsigned *gid) {
if (!path) return;
if (strstr(path, "shared")) { *uid = 4242; *gid = 1023; }
else if (strstr(path, "other")) { *uid = 4242; *gid = 4242; }
}
int stat(const char *path, struct stat *st) {
int (*next)(const char *, struct stat *) = dlsym(RTLD_NEXT, "stat");
int ret = next(path, st);
if (ret == 0) owner(path, &st->st_uid, &st->st_gid);
return ret;
}
int lstat(const char *path, struct stat *st) {
int (*next)(const char *, struct stat *) = dlsym(RTLD_NEXT, "lstat");
int ret = next(path, st);
if (ret == 0) owner(path, &st->st_uid, &st->st_gid);
return ret;
}
int fstatat(int dirfd, const char *path, struct stat *st, int flags) {
int (*next)(int, const char *, struct stat *, int) = dlsym(RTLD_NEXT, "fstatat");
int ret = next(dirfd, path, st, flags);
if (ret == 0) owner(path, &st->st_uid, &st->st_gid);
return ret;
}
int statx(int dirfd, const char *path, int flags, unsigned mask, struct statx *sx) {
int (*next)(int, const char *, int, unsigned, struct statx *) = dlsym(RTLD_NEXT, "statx");
int ret = next(dirfd, path, flags, mask, sx);
if (ret == 0) owner(path, &sx->stx_uid, &sx->stx_gid);
return ret;
}
"""
PROBE = r"""
#define _GNU_SOURCE
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
int main(int argc, char **argv) {
struct stat st;
struct statx sx;
for (int i = 1; i < argc; i++) {
if (stat(argv[i], &st) != 0) return 2;
printf("%s\tstat\t%u\t%u\n", argv[i], st.st_uid, st.st_gid);
if (lstat(argv[i], &st) != 0) return 3;
printf("%s\tlstat\t%u\t%u\n", argv[i], st.st_uid, st.st_gid);
if (fstatat(AT_FDCWD, argv[i], &st, 0) != 0) return 4;
printf("%s\tfstatat\t%u\t%u\n", argv[i], st.st_uid, st.st_gid);
if (statx(AT_FDCWD, argv[i], 0, STATX_BASIC_STATS, &sx) != 0) return 5;
printf("%s\tstatx\t%u\t%u\n", argv[i], sx.stx_uid, sx.stx_gid);
}
return 0;
}
"""
class NativeHookStorageOwnerTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.cc, cls.prefix = runner()
if cls.cc is None:
raise unittest.SkipTest("no aarch64 compiler and runner")
cls.tmp = tempfile.TemporaryDirectory(dir="/tmp")
tmp = Path(cls.tmp.name)
cls.hook = tmp / "hook.so"
subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True)
(tmp / "owners.c").write_text(OWNERS)
cls.owners = tmp / "owners.so"
subprocess.run([cls.cc, "-shared", "-fPIC", "-O1", "-o", str(cls.owners), str(tmp / "owners.c"), "-ldl"], check=True)
(tmp / "probe.c").write_text(PROBE)
cls.probe = tmp / "probe"
subprocess.run([cls.cc, "-O1", "-o", str(cls.probe), str(tmp / "probe.c")], check=True)
cls.root = tmp / "root"
cls.root.mkdir()
for name in ("shared", "other", "own"):
(cls.root / name).write_text("")
@classmethod
def tearDownClass(cls):
cls.tmp.cleanup()
def owners_of(self, *paths):
hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": f"{self.hook} {self.owners}"}
env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT")}
if self.prefix:
cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
else:
cmd = []
env.update(hook_env)
out = subprocess.run(cmd + [str(self.probe), *paths], env=env, capture_output=True, text=True, timeout=120)
self.assertEqual(0, out.returncode, out.stdout + out.stderr)
result = {}
for line in out.stdout.splitlines():
path, call, uid, gid = line.split("\t")
result.setdefault(path, {})[call] = (int(uid), int(gid))
return result
def test_shared_storage_files_are_owned_by_root_and_keep_their_group(self):
for call, ids in self.owners_of("/shared")["/shared"].items():
self.assertEqual((0, 1023), ids, call)
def test_other_owners_and_the_apps_own_files_are_unchanged(self):
result = self.owners_of("/other", "/own")
for call, ids in result["/other"].items():
self.assertEqual((4242, 4242), ids, call)
for call, ids in result["/own"].items():
self.assertEqual((0, 0), ids, call)
if __name__ == "__main__":
unittest.main()
+22
View File
@@ -150,6 +150,28 @@ class CompatLibrariesTest(unittest.TestCase):
class DesktopGamesTest(unittest.TestCase):
def test_library_links_that_cannot_be_walked_are_made_again(self):
with tempfile.TemporaryDirectory() as temp:
root = Path(temp)
steam, home = root / "Steam", root / "home"
(steam / "steamapps/common/Game").mkdir(parents=True)
home.mkdir()
common = str(steam / "steamapps/common")
stale, kept = home / "Steam Games", home / "SD Games"
os.symlink(str(root / "elsewhere"), stale)
card = root / "card/steamapps/common"
card.mkdir(parents=True)
os.symlink(str(card), kept)
before = os.lstat(kept).st_ino
real = os.readlink
with patch.object(desktop, "HOME", str(home)), \
patch.object(desktop, "LIBRARIES", ((str(steam), "Steam Games"), (str(root / "card"), "SD Games"))), \
patch.object(desktop.os, "readlink", lambda p: common if p == str(stale) else real(p)):
desktop.link_libraries()
self.assertEqual(common, os.readlink(stale))
self.assertTrue((stale / "Game").is_dir())
self.assertEqual(before, os.lstat(kept).st_ino)
def test_games_in_registered_libraries_get_entries(self):
with tempfile.TemporaryDirectory() as temp:
root = Path(temp)