Gate direct Steam frames on verified producer acquire fences

This commit is contained in:
Kurt Himebauch committed 2026-12-03 14:23:21 -05:00
1 parent 18d735b4c4
commit b164212c8f
35 files changed
+2245 -35

No files matched your search

@@ -42,6 +42,11 @@ add_library(droiddeckwayland SHARED
src/hudframes.c
src/hudframes_jni.c
)
option(DROIDDECK_FRAME_ACQUIRE_PROBE "Build opt-in signaled producer acquire protocol support" ON)
if (DROIDDECK_FRAME_ACQUIRE_PROBE)
target_sources(droiddeckwayland PRIVATE generated/droiddeck-frame-acquire-v1-protocol.c)
target_compile_definitions(droiddeckwayland PRIVATE DROIDDECK_FRAME_ACQUIRE_PROBE=1)
endif()
target_compile_options(droiddeckwayland PRIVATE
$<$<COMPILE_LANGUAGE:C>:-Wall -Wextra -Wno-unused-parameter -Wno-missing-field-initializers>)
target_include_directories(droiddeckwayland PRIVATE
@@ -0,0 +1,35 @@
/* Generated by wayland-scanner 1.22.0 */
#include <stdlib.h>
#include <stdint.h>
#include "wayland-util.h"
#ifndef __has_attribute
# define __has_attribute(x) 0 /* Compatibility with non-clang compilers. */
#endif
#if (__has_attribute(visibility) || defined(__GNUC__) && __GNUC__ >= 4)
#define WL_PRIVATE __attribute__ ((visibility("hidden")))
#else
#define WL_PRIVATE
#endif
extern const struct wl_interface wl_buffer_interface;
extern const struct wl_interface wl_surface_interface;
static const struct wl_interface *droiddeck_frame_acquire_v1_types[] = {
&wl_surface_interface,
&wl_buffer_interface,
NULL,
};
static const struct wl_message droiddeck_frame_acquire_v1_requests[] = {
{ "destroy", "", droiddeck_frame_acquire_v1_types + 0 },
{ "set_acquire_fence", "ooh", droiddeck_frame_acquire_v1_types + 0 },
};
WL_PRIVATE const struct wl_interface droiddeck_frame_acquire_v1_interface = {
"droiddeck_frame_acquire_v1", 1,
2, droiddeck_frame_acquire_v1_requests,
0, NULL,
};
@@ -0,0 +1,128 @@
/* Generated by wayland-scanner 1.22.0 */
#ifndef DROIDDECK_FRAME_ACQUIRE_V1_SERVER_PROTOCOL_H
#define DROIDDECK_FRAME_ACQUIRE_V1_SERVER_PROTOCOL_H
#include <stdint.h>
#include <stddef.h>
#include "wayland-server.h"
#ifdef __cplusplus
extern "C" {
#endif
struct wl_client;
struct wl_resource;
/**
* @page page_droiddeck_frame_acquire_v1 The droiddeck_frame_acquire_v1 protocol
* @section page_ifaces_droiddeck_frame_acquire_v1 Interfaces
* - @subpage page_iface_droiddeck_frame_acquire_v1 - DroidDeck producer write completion for a single Wayland attachment
*/
struct droiddeck_frame_acquire_v1;
struct wl_buffer;
struct wl_surface;
#ifndef DROIDDECK_FRAME_ACQUIRE_V1_INTERFACE
#define DROIDDECK_FRAME_ACQUIRE_V1_INTERFACE
/**
* @page page_iface_droiddeck_frame_acquire_v1 droiddeck_frame_acquire_v1
* @section page_iface_droiddeck_frame_acquire_v1_desc Description
*
* Optional explicit acquire sideband independent of DRM syncobj and buffer
* allocation. Binding does not opt the client out of ordinary wl_buffer
* release or existing synchronization protocols. The server advertises it
* only when it implements all semantics for the selected display path.
* @section page_iface_droiddeck_frame_acquire_v1_api API
* See @ref iface_droiddeck_frame_acquire_v1.
*/
/**
* @defgroup iface_droiddeck_frame_acquire_v1 The droiddeck_frame_acquire_v1 interface
*
* Optional explicit acquire sideband independent of DRM syncobj and buffer
* allocation. Binding does not opt the client out of ordinary wl_buffer
* release or existing synchronization protocols. The server advertises it
* only when it implements all semantics for the selected display path.
*/
extern const struct wl_interface droiddeck_frame_acquire_v1_interface;
#endif
#ifndef DROIDDECK_FRAME_ACQUIRE_V1_ERROR_ENUM
#define DROIDDECK_FRAME_ACQUIRE_V1_ERROR_ENUM
enum droiddeck_frame_acquire_v1_error {
/**
* not the same client's pending DMA-BUF attachment
*/
DROIDDECK_FRAME_ACQUIRE_V1_ERROR_INVALID_ATTACHMENT = 0,
/**
* that attachment already has an acquire fence
*/
DROIDDECK_FRAME_ACQUIRE_V1_ERROR_DUPLICATE_FENCE = 1,
/**
* not a real successfully signaled Linux sync_file
*/
DROIDDECK_FRAME_ACQUIRE_V1_ERROR_INVALID_FENCE = 2,
/**
* not the paired test peer
*/
DROIDDECK_FRAME_ACQUIRE_V1_ERROR_UNAUTHORIZED_PEER = 3,
};
#endif /* DROIDDECK_FRAME_ACQUIRE_V1_ERROR_ENUM */
/**
* @ingroup iface_droiddeck_frame_acquire_v1
* @struct droiddeck_frame_acquire_v1_interface
*/
struct droiddeck_frame_acquire_v1_interface {
/**
*/
void (*destroy)(struct wl_client *client,
struct wl_resource *resource);
/**
* set a one-shot kernel sync_file for the pending attachment
*
* After wl_surface.attach of a non-null buffer, and before its
* next wl_surface.commit, send the producer's final writer fence
* for that exact attachment. This outer probe requires that fence
* to have already successfully signaled. The fence must be a real
* Linux sync_file, not a dma-buf, eventfd, or Vulkan OPAQUE_FD.
* The server consumes its received descriptor once for that
* attachment; the caller closes its local FD after marshalling.
*
* The receiver validates the matching pending surface and buffer
* and validates the descriptor. A duplicate, invalid, pending or
* mismatched request is a protocol error; it is never downgraded
* to implicit sync. Another attach (even the same wl_buffer),
* detach, surface/resource loss or supersession makes the old
* proof inapplicable. Metadata-only commits may amend
* receiver-side still-pending state but cannot introduce or re-use
* a fence themselves. If no request was made, the receiver keeps
* its established safe path. If a valid fence has been accepted
* and later the layer is ineligible, the buffer must not be
* copied/read before that fence is satisfied or imported as the
* source dependency. Transport never implies readiness on missed
* deadlines and never changes release/retirement requirements.
* @param fence producer's native acquire sync_file
*/
void (*set_acquire_fence)(struct wl_client *client,
struct wl_resource *resource,
struct wl_resource *surface,
struct wl_resource *buffer,
int32_t fence);
};
/**
* @ingroup iface_droiddeck_frame_acquire_v1
*/
#define DROIDDECK_FRAME_ACQUIRE_V1_DESTROY_SINCE_VERSION 1
/**
* @ingroup iface_droiddeck_frame_acquire_v1
*/
#define DROIDDECK_FRAME_ACQUIRE_V1_SET_ACQUIRE_FENCE_SINCE_VERSION 1
#ifdef __cplusplus
}
#endif
#endif
@@ -0,0 +1,45 @@
<?xml version="1.0" encoding="UTF-8"?>
<protocol name="droiddeck_frame_acquire_v1">
<interface name="droiddeck_frame_acquire_v1" version="1">
<description summary="DroidDeck producer write completion for a single Wayland attachment">
Optional explicit acquire sideband independent of DRM syncobj and buffer
allocation. Binding does not opt the client out of ordinary wl_buffer
release or existing synchronization protocols. The server advertises it
only when it implements all semantics for the selected display path and
only to the test fixture's app-authorized Gamescope worker.
</description>
<request name="destroy" type="destructor"/>
<enum name="error">
<entry name="invalid_attachment" value="0" summary="not the same client's pending DMA-BUF attachment"/>
<entry name="duplicate_fence" value="1" summary="that attachment already has an acquire fence"/>
<entry name="invalid_fence" value="2" summary="not a real successfully signaled Linux sync_file"/>
<entry name="unauthorized_peer" value="3" summary="not the paired test peer"/>
</enum>
<request name="set_acquire_fence">
<description summary="set a one-shot kernel sync_file for the pending attachment">
After wl_surface.attach of a non-null buffer, and before its next
wl_surface.commit, send the producer's final writer fence for that
exact attachment. This outer probe requires that fence to have already
successfully signaled. The fence must be a real Linux sync_file, not a
dma-buf, eventfd, or Vulkan OPAQUE_FD. The server consumes its received
descriptor once for that attachment; the caller closes its local FD
after marshalling.
The receiver validates the matching pending surface and buffer and
validates the descriptor. A duplicate, invalid, pending or mismatched
request is a protocol error; it is never downgraded to implicit sync. Another attach (even the same
wl_buffer), detach, surface/resource loss or supersession makes the
old proof inapplicable. Metadata-only commits may amend receiver-side
still-pending state but cannot introduce or re-use a fence themselves.
If no request was made, the receiver keeps its established safe path.
If a valid fence has been accepted and later the layer is ineligible,
the buffer must not be copied/read before that fence is satisfied or
imported as the source dependency. Transport never implies readiness
on missed deadlines and never changes release/retirement requirements.
</description>
<arg name="surface" type="object" interface="wl_surface"/>
<arg name="buffer" type="object" interface="wl_buffer"/>
<arg name="fence" type="fd" summary="producer's native acquire sync_file"/>
</request>
</interface>
</protocol>
@@ -54,6 +54,7 @@ static struct wl_list g_clients;
static uint64_t g_next_id = 1;
static struct wl_event_loop *g_loop;
static unsigned g_stat_zero_copy;
static unsigned g_stat_producer_fence;
static int g_export_failed_logged, g_import_failed_logged;
static int g_advertised;
static int g_mode_sent = -1;
@@ -201,31 +202,47 @@ int ahb_swapchain_present(struct dmabuf_buffer *b, struct surface *s, int scene_
struct ahb_buf *ab = b ? *droiddeck_dmabuf_ahb_slot(b) : NULL;
if (!ab) return -1;
int dmabuf_fd = droiddeck_dmabuf_fd(b);
int acquire = -1;
struct droiddeck_dma_buf_sync_file exp = {.flags = DROIDDECK_DMA_BUF_SYNC_READ, .fd = -1};
if (dmabuf_fd >= 0 && ioctl(dmabuf_fd, DROIDDECK_DMA_BUF_IOCTL_EXPORT_SYNC_FILE, &exp) == 0 && exp.fd >= 0) {
acquire = exp.fd;
} else {
if (!g_export_failed_logged) {
g_export_failed_logged = 1;
droiddeck_log("layer", "zero-copy: no acquire fence from the game's dma-buf (%s): %s",
dmabuf_fd >= 0 ? strerror(errno) : "no dma-buf fd",
draw ? "its frames are copied instead" : "it cannot be copied, so each frame is waited for on the CPU");
int acquire = droiddeck_surface_dup_acquire(s, b);
if (acquire == -2) return -1;
#ifdef DROIDDECK_FRAME_ACQUIRE_PROBE
const int explicit_acquire = acquire >= 0;
#endif
if (acquire < 0) {
struct droiddeck_dma_buf_sync_file exp = {.flags = DROIDDECK_DMA_BUF_SYNC_READ, .fd = -1};
if (dmabuf_fd >= 0 && ioctl(dmabuf_fd, DROIDDECK_DMA_BUF_IOCTL_EXPORT_SYNC_FILE, &exp) == 0 && exp.fd >= 0) {
acquire = exp.fd;
} else {
if (!g_export_failed_logged) {
g_export_failed_logged = 1;
droiddeck_log("layer", "zero-copy: no acquire fence from the game's dma-buf (%s): %s",
dmabuf_fd >= 0 ? strerror(errno) : "no dma-buf fd",
draw ? "its frames are copied instead" : "it cannot be copied, so each frame is waited for on the CPU");
}
if (dmabuf_fd >= 0) {
struct pollfd p = {.fd = dmabuf_fd, .events = POLLIN};
int r;
do { r = poll(&p, 1, 100); } while (r < 0 && errno == EINTR);
}
if (draw) return -1;
}
if (dmabuf_fd >= 0) {
struct pollfd p = {.fd = dmabuf_fd, .events = POLLIN};
int r;
do { r = poll(&p, 1, 100); } while (r < 0 && errno == EINTR);
}
if (draw) return -1;
}
int r = sc_layer_present_ahb(ab->ahb, ab->w, ab->h, acquire, (void *)(uintptr_t)ab->id, scene_w, scene_h, draw,
s ? droiddeck_surface_color(s) : NULL, ab->format);
if (r < 0) return -1;
if (r == 1) return 0;
#ifdef DROIDDECK_FRAME_ACQUIRE_PROBE
static int explicit_logged;
if (explicit_acquire && !explicit_logged) {
explicit_logged = 1;
droiddeck_log("layer", "probe: SurfaceControl accepted a verified producer acquire fence");
}
#endif
if (!ab->on_layer) {
ab->on_layer = 1;
g_stat_zero_copy++;
#ifdef DROIDDECK_FRAME_ACQUIRE_PROBE
if (explicit_acquire) g_stat_producer_fence++;
#endif
g_last_zero_copy_ns = now_ns();
}
if (s && g_announced != s) {
@@ -265,6 +282,12 @@ unsigned ahb_swapchain_stats_take(void) {
return n;
}
unsigned ahb_swapchain_producer_fence_stats_take(void) {
unsigned n = g_stat_producer_fence;
g_stat_producer_fence = 0;
return n;
}
int ahb_swapchain_advertised(void) { return g_advertised; }
uint32_t ahb_swapchain_ahb_format(const struct dmabuf_buffer *b) {
@@ -20,7 +20,9 @@ int ahb_swapchain_present(struct dmabuf_buffer *b, struct surface *s, int scene_
int ahb_swapchain_defer_release(struct dmabuf_buffer *b, struct wl_resource *buffer, struct surface *s, int paced);
void ahb_swapchain_surface_gone(struct surface *s);
unsigned ahb_swapchain_stats_take(void);
unsigned ahb_swapchain_producer_fence_stats_take(void);
int ahb_swapchain_advertised(void);
int droiddeck_surface_dup_acquire(const struct surface *s, const struct dmabuf_buffer *b);
uint32_t ahb_swapchain_ahb_format(const struct dmabuf_buffer *b);
void ahb_swapchain_layer_released(void *token, int release_fd);
+238 -1
View File
@@ -24,6 +24,14 @@
#include "linux-dmabuf-v1-server-protocol.h"
#include "sc_layer.h"
#include "ahb_swapchain.h"
#include "frame_acquire.h"
#ifdef DROIDDECK_FRAME_ACQUIRE_PROBE
#include "droiddeck-frame-acquire-v1-server-protocol.h"
#include <sys/syscall.h>
#include <sys/sysmacros.h>
#include <sys/stat.h>
#include "frame_worker_peer.h"
#endif
#include "display_buffers.h"
#include "viewporter-server-protocol.h"
#include "droiddeck-desktop-v1-server-protocol.h"
@@ -211,6 +219,7 @@ struct surface {
struct wl_list link;
struct wl_resource *pending_buffer;
struct dd_frame_acquire pending_frame_acquire, frame_acquire;
struct wl_listener pending_buffer_destroy;
int pending_attach;
int pending_src_set, pending_dst_set;
@@ -827,6 +836,7 @@ static void unmap_toplevel(struct surface *s) {
}
static void drop_dmabuf(struct surface *s, int paced) {
dd_frame_acquire_clear(&s->frame_acquire);
if (s->dmabuf) {
wl_list_remove(&s->dmabuf_destroy.link);
if (buffer_shown_elsewhere(s->dmabuf, s)) {
@@ -842,18 +852,21 @@ static void drop_dmabuf(struct surface *s, int paced) {
static void on_dmabuf_destroyed(struct wl_listener *l, void *data) {
struct surface *s = wl_container_of(l, s, dmabuf_destroy);
dd_frame_acquire_clear(&s->frame_acquire);
wl_list_remove(&s->dmabuf_destroy.link);
s->dmabuf = NULL;
}
static void on_pending_buffer_destroyed(struct wl_listener *l, void *data) {
struct surface *s = wl_container_of(l, s, pending_buffer_destroy);
dd_frame_acquire_clear(&s->pending_frame_acquire);
wl_list_remove(&s->pending_buffer_destroy.link);
wl_list_init(&s->pending_buffer_destroy.link);
s->pending_buffer = NULL;
}
struct surface_state {
struct dd_frame_acquire frame_acquire;
struct wl_resource *buffer;
struct wl_listener buffer_destroy;
int attach;
@@ -866,6 +879,7 @@ struct surface_state {
static void on_state_buffer_destroyed(struct wl_listener *l, void *data) {
struct surface_state *st = wl_container_of(l, st, buffer_destroy);
dd_frame_acquire_clear(&st->frame_acquire);
wl_list_remove(&st->buffer_destroy.link);
wl_list_init(&st->buffer_destroy.link);
st->buffer = NULL;
@@ -874,6 +888,8 @@ static void on_state_buffer_destroyed(struct wl_listener *l, void *data) {
static void surface_state_take(struct surface *s, struct surface_state *st) {
st->attach = s->pending_attach;
st->frame_acquire = s->pending_frame_acquire;
s->pending_frame_acquire.fd_plus_one = 0;
st->buffer = s->pending_buffer;
wl_list_init(&st->buffer_destroy.link);
if (st->buffer) {
@@ -1186,6 +1202,7 @@ static void surface_attach(struct wl_client *c, struct wl_resource *r,
if (s->pending_buffer) wl_list_remove(&s->pending_buffer_destroy.link);
wl_list_init(&s->pending_buffer_destroy.link);
s->pending_buffer = buffer;
dd_frame_acquire_clear(&s->pending_frame_acquire);
s->pending_attach = 1;
if (buffer) {
s->pending_buffer_destroy.notify = on_pending_buffer_destroyed;
@@ -1451,6 +1468,7 @@ static void surface_state_apply(struct surface *s, struct surface_state *st) {
surface_drop_idle(s);
buf_trace_attach(buffer);
dd_frame_acquire_clear(&s->frame_acquire);
if (s->role == ROLE_CURSOR) {
if (!buffer) {
cursor_publish_hidden();
@@ -1462,6 +1480,8 @@ static void surface_state_apply(struct surface *s, struct surface_state *st) {
if (buffer) surface_hold_idle(s, buffer);
} else if (db) {
take_dmabuf(s, db, buffer);
s->frame_acquire = st->frame_acquire;
st->frame_acquire.fd_plus_one = 0;
} else if (shm) {
drop_dmabuf(s, 1);
take_shm(s, shm, buffer);
@@ -1474,6 +1494,7 @@ static void surface_state_apply(struct surface *s, struct surface_state *st) {
if (buffer) send_buffer_release(buffer);
}
}
dd_frame_acquire_clear(&st->frame_acquire);
pending_releases_apply(s);
wl_list_for_each(child, &s->children, child_link) {
@@ -1538,6 +1559,7 @@ static void settle_unwaited(void) {
}
static void surface_state_discard(struct surface_state *st) {
dd_frame_acquire_clear(&st->frame_acquire);
struct wl_resource *cb, *tmp;
wl_list_remove(&st->buffer_destroy.link);
wl_resource_for_each_safe(cb, tmp, &st->frames) wl_resource_destroy(cb);
@@ -1549,6 +1571,8 @@ static void surface_state_merge(struct surface_state *older, struct surface_stat
if (older->attach && !newer->attach) {
newer->attach = 1;
newer->buffer = older->buffer;
newer->frame_acquire = older->frame_acquire;
older->frame_acquire.fd_plus_one = 0;
wl_list_remove(&older->buffer_destroy.link);
wl_list_init(&older->buffer_destroy.link);
if (newer->buffer) {
@@ -1700,6 +1724,210 @@ static const struct wl_surface_interface surface_impl = {
.offset = surface_offset,
};
int droiddeck_surface_dup_acquire(const struct surface *s, const struct dmabuf_buffer *b) {
return s && s->dmabuf && s->dmabuf_buf == b ? dd_frame_acquire_dup(&s->frame_acquire) : -1;
}
#ifdef DROIDDECK_FRAME_ACQUIRE_PROBE
// Private signed fixture: only the app-owned worker decision may issue a grant.
static pthread_mutex_t frame_worker_lock = PTHREAD_MUTEX_INITIALIZER;
static char frame_worker_file[PATH_MAX];
static struct dd_worker_grant frame_worker_grant;
static int frame_worker_pidfd = -1;
static bool frame_worker_map_reported;
static enum dd_worker_stat_result frame_worker_starttime(pid_t pid, uint64_t *out) {
char proc[64], line[4096];
snprintf(proc, sizeof(proc), "/proc/%d/stat", pid);
FILE *f = fopen(proc, "re");
if (!f) return dd_worker_open_failure(errno);
// Proc writes one bounded line; truncation is a read failure, not invisibility.
bool read = fgets(line, sizeof(line), f) != NULL && strchr(line, '\n') != NULL;
fclose(f);
return read ? dd_worker_parse_start(line, out) : DD_WORKER_STAT_READ;
}
void droiddeck_frame_worker_revoke(int owner, int pid) {
pthread_mutex_lock(&frame_worker_lock);
if (frame_worker_grant.owner == (uint32_t)owner &&
(!pid || frame_worker_grant.pid == (uint32_t)pid)) {
if (frame_worker_pidfd >= 0) close(frame_worker_pidfd);
frame_worker_pidfd = -1;
frame_worker_grant = (struct dd_worker_grant){0};
}
pthread_mutex_unlock(&frame_worker_lock);
}
int droiddeck_frame_worker_grant(int owner, pid_t pid, uint64_t expires, const char *path,
uint64_t expected_dev, uint64_t expected_ino, uint64_t receipt) {
struct stat st;
if (owner <= 0 || pid <= 1 || !receipt || !path ||
strlen(path) >= sizeof(frame_worker_file) || lstat(path, &st) < 0 || !S_ISREG(st.st_mode) ||
(uint64_t)st.st_dev != expected_dev || (uint64_t)st.st_ino != expected_ino ||
st.st_uid != getuid()) {
droiddeck_log("probe", "worker_admission=NATIVE_FILE");
return 0;
}
int pidfd = syscall(__NR_pidfd_open, pid, 0);
if (pidfd < 0) {
droiddeck_log("probe", "worker_admission=NATIVE_PIDFD");
return 0; // No fallback to a recyclable PID.
}
struct pollfd alive = {.fd = pidfd, .events = POLLIN};
uint64_t raw_start = 0;
enum dd_worker_stat_result stat = frame_worker_starttime(pid, &raw_start);
switch (stat) {
case DD_WORKER_STAT_OK:
if (raw_start != receipt) droiddeck_log("probe", "worker_admission=NATIVE_STAT_MISMATCH");
break;
case DD_WORKER_STAT_DENIED: droiddeck_log("probe", "worker_admission=NATIVE_STAT_OPEN_DENIED"); break;
case DD_WORKER_STAT_HIDDEN: droiddeck_log("probe", "worker_admission=NATIVE_STAT_OPEN_HIDDEN"); break;
case DD_WORKER_STAT_OPEN: droiddeck_log("probe", "worker_admission=NATIVE_STAT_OPEN_OTHER"); break;
case DD_WORKER_STAT_READ: droiddeck_log("probe", "worker_admission=NATIVE_STAT_READ"); break;
case DD_WORKER_STAT_PARSE: droiddeck_log("probe", "worker_admission=NATIVE_STAT_PARSE"); break;
case DD_WORKER_STAT_ZERO: droiddeck_log("probe", "worker_admission=NATIVE_STAT_ZERO"); break;
}
if (!dd_worker_receipt_allows_reserve(stat, raw_start, receipt)) { close(pidfd); return 0; }
if (poll(&alive, 1, 0) != 0) {
droiddeck_log("probe", "worker_admission=NATIVE_PIDFD_NOT_LIVE");
close(pidfd);
return 0;
}
pthread_mutex_lock(&frame_worker_lock);
if (frame_worker_pidfd < 0) {
strcpy(frame_worker_file, path);
frame_worker_grant = (struct dd_worker_grant){
.owner = owner, .uid = getuid(), .pid = pid, .start_ticks = receipt, .expires = expires,
.dev_major = major(st.st_dev), .dev_minor = minor(st.st_dev), .ino = st.st_ino,
.canonical_file = frame_worker_file, .app_launch_verified = true, .final_go = true,
};
frame_worker_map_reported = false;
frame_worker_pidfd = pidfd;
pidfd = -1;
}
pthread_mutex_unlock(&frame_worker_lock);
if (pidfd >= 0) {
droiddeck_log("probe", "worker_admission=NATIVE_ALREADY_RESERVED");
close(pidfd);
return 0;
}
droiddeck_log("probe", "frame acquire reserved one app-verified worker");
return 1;
}
static bool frame_worker_verified_exec_locked(const struct dd_worker_grant *g, uint64_t now) {
char proc[64], line[PATH_MAX + 128];
const char *failure = "worker_admission=MAP_STARTTIME";
uint64_t raw_start = 0;
if (frame_worker_starttime(g->pid, &raw_start) != DD_WORKER_STAT_OK || raw_start != g->start_ticks)
goto reject;
snprintf(proc, sizeof(proc), "/proc/%u/maps", g->pid);
FILE *f = fopen(proc, "re");
failure = "worker_admission=MAP_OPEN";
if (!f) goto reject;
bool matched = false;
size_t budget = 2 * 1024 * 1024;
while (budget && fgets(line, sizeof(line), f)) {
size_t n = strlen(line);
if (!n || line[n - 1] != '\n' || n > budget) break;
budget -= n;
if (dd_worker_grant_matches(g, g->owner, g->uid, g->pid, raw_start, now, line)) {
matched = true;
break;
}
}
fclose(f);
if (matched) return true;
failure = "worker_admission=MAP_IDENTITY";
reject:
if (!frame_worker_map_reported) {
frame_worker_map_reported = true;
droiddeck_log("probe", "%s", failure);
}
return false;
}
static int frame_acquire_peer_allowed(const struct wl_client *client, bool verify_exec, bool bind) {
pid_t pid = 0;
uid_t uid = (uid_t)-1;
wl_client_get_credentials(client, &pid, &uid, NULL);
struct timespec t;
if (clock_gettime(CLOCK_BOOTTIME, &t) < 0) return 0;
uint64_t now = (uint64_t)t.tv_sec * 1000 + (uint64_t)t.tv_nsec / 1000000;
pthread_mutex_lock(&frame_worker_lock);
const struct dd_worker_grant *g = &frame_worker_grant;
struct pollfd alive = {.fd = frame_worker_pidfd, .events = POLLIN};
bool allowed = frame_worker_pidfd >= 0 && uid == getuid() && pid > 1 &&
g->pid == (uint32_t)pid && g->uid == uid && now < g->expires &&
poll(&alive, 1, 0) == 0 && (!verify_exec ||
(frame_worker_verified_exec_locked(g, now) && poll(&alive, 1, 0) == 0));
// The short startup authorization may not be renewed by registry enumeration.
// Only an authenticated bind activates the grant for the lifetime of this live,
// unreplaced worker; session teardown revokes it independently of process exit.
if (allowed && bind) frame_worker_grant.expires = UINT64_MAX;
pthread_mutex_unlock(&frame_worker_lock);
return allowed;
}
static bool frame_acquire_global_filter(const struct wl_client *client, const struct wl_global *global, void *data) {
return wl_global_get_interface(global) != &droiddeck_frame_acquire_v1_interface ||
frame_acquire_peer_allowed(client, true, false);
}
static void frame_acquire_destroy(struct wl_client *client, struct wl_resource *resource) {
wl_resource_destroy(resource);
}
static void frame_acquire_set(struct wl_client *client, struct wl_resource *resource,
struct wl_resource *surface, struct wl_resource *buffer, int32_t fd) {
if (!frame_acquire_peer_allowed(client, false, false)) {
close(fd);
wl_resource_post_error(resource, DROIDDECK_FRAME_ACQUIRE_V1_ERROR_UNAUTHORIZED_PEER,
"paired capture peer is not authorized");
return;
}
struct surface *s = NULL;
if (surface && buffer && wl_resource_get_client(surface) == client &&
wl_resource_get_client(buffer) == client &&
wl_resource_instance_of(surface, &wl_surface_interface, &surface_impl) &&
get_dmabuf(buffer))
s = wl_resource_get_user_data(surface);
if (!s || !s->pending_attach || s->pending_buffer != buffer) {
close(fd);
wl_resource_post_error(resource, DROIDDECK_FRAME_ACQUIRE_V1_ERROR_INVALID_ATTACHMENT,
"fence does not match pending DMA-BUF attachment");
return;
}
enum dd_frame_acquire_result result = dd_frame_acquire_set(&s->pending_frame_acquire, fd);
if (result == DD_ACQUIRE_DUPLICATE)
wl_resource_post_error(resource, DROIDDECK_FRAME_ACQUIRE_V1_ERROR_DUPLICATE_FENCE,
"pending attachment already has a fence");
else if (result == DD_ACQUIRE_INVALID)
wl_resource_post_error(resource, DROIDDECK_FRAME_ACQUIRE_V1_ERROR_INVALID_FENCE,
"expected an already signaled Linux sync_file");
}
static const struct droiddeck_frame_acquire_v1_interface frame_acquire_impl = {
.destroy = frame_acquire_destroy,
.set_acquire_fence = frame_acquire_set,
};
static void bind_frame_acquire(struct wl_client *client, void *data, uint32_t version, uint32_t id) {
if (!frame_acquire_peer_allowed(client, true, true)) {
wl_client_post_implementation_error(client, "paired capture peer is not authorized");
return;
}
struct wl_resource *resource =
wl_resource_create(client, &droiddeck_frame_acquire_v1_interface, 1, id);
if (!resource) {
wl_client_post_no_memory(client);
return;
}
wl_resource_set_implementation(resource, &frame_acquire_impl, NULL, NULL);
droiddeck_log("probe", "frame acquire bound to app-issued worker and exact executable map");
}
#endif
static void detach_from_parent(struct surface *s) {
if (!s->parent) return;
wl_list_remove(&s->child_link);
@@ -1709,6 +1937,7 @@ static void detach_from_parent(struct surface *s) {
static void surface_resource_destroy(struct wl_resource *r) {
struct surface *s = wl_resource_get_user_data(r);
dd_frame_acquire_clear(&s->pending_frame_acquire);
struct surface *child, *tmp;
struct wl_resource *cb, *cbtmp;
@@ -4804,6 +5033,7 @@ static int on_stats_timer(void *data) {
struct surface *s;
wl_list_for_each(s, &g_toplevels, toplevel_link) windows++;
unsigned zero_copy = ahb_swapchain_stats_take();
unsigned verified = ahb_swapchain_producer_fence_stats_take();
unsigned layer_frames = sc_layer_frames_take();
g_zero_copy_last = zero_copy;
unsigned generated = vkp_framegen_stats_take();
@@ -4812,7 +5042,8 @@ static int on_stats_timer(void *data) {
int off = 0;
if (g_zero_copy || zero_copy) off += snprintf(extra + off, sizeof(extra) - (size_t)off, " | %u zero-copy frames", zero_copy);
if (layer_frames) off += snprintf(extra + off, sizeof(extra) - (size_t)off, " | %u layer frames", layer_frames);
if (generated) snprintf(extra + off, sizeof(extra) - (size_t)off, " | %u generated frames", generated);
if (generated) off += snprintf(extra + off, sizeof(extra) - (size_t)off, " | %u generated frames", generated);
if (verified) snprintf(extra + off, sizeof(extra) - (size_t)off, " | %u verified acquire frames", verified);
droiddeck_log("stats", "last 10 s: %u frames on screen (%.1f fps) | %u GPU frames from games | %u window redraws | %d windows open%s",
g_stat_frames + generated, (g_stat_frames + generated) / 10.0, g_stat_dmabuf, g_stat_shm, windows, extra);
}
@@ -5013,6 +5244,12 @@ int droiddeck_wayland_run(void) {
wl_global_create(display, &zwp_relative_pointer_manager_v1_interface, 1, NULL, bind_relative_pointer_manager);
droiddeck_ext_init(display);
ahb_swapchain_init(display);
#ifdef DROIDDECK_FRAME_ACQUIRE_PROBE
if (ahb_swapchain_advertised()) {
wl_display_set_global_filter(display, frame_acquire_global_filter, NULL);
wl_global_create(display, &droiddeck_frame_acquire_v1_interface, 1, NULL, bind_frame_acquire);
}
#endif
display_buffers_init(display);
@@ -0,0 +1,39 @@
#ifndef DD_FRAME_ACQUIRE_H
#define DD_FRAME_ACQUIRE_H
#include <fcntl.h>
#include <limits.h>
#include <linux/sync_file.h>
#include <sys/ioctl.h>
#include <unistd.h>
/* A zero-initialized slot owns no descriptor. Only an already successful
* sync_file can enter this slot; display-side release ownership is separate. */
struct dd_frame_acquire { int fd_plus_one; };
enum dd_frame_acquire_result { DD_ACQUIRE_OK, DD_ACQUIRE_DUPLICATE, DD_ACQUIRE_INVALID };
static inline void dd_frame_acquire_clear(struct dd_frame_acquire *f) {
if (f->fd_plus_one) close(f->fd_plus_one - 1);
f->fd_plus_one = 0;
}
static inline enum dd_frame_acquire_result
dd_frame_acquire_set(struct dd_frame_acquire *f, int fd) {
enum dd_frame_acquire_result result;
struct sync_file_info info = {0};
if (f->fd_plus_one) result = DD_ACQUIRE_DUPLICATE;
else if (fd < 0 || fd == INT_MAX || ioctl(fd, SYNC_IOC_FILE_INFO, &info) != 0 ||
info.status != 1 || info.num_fences == 0) result = DD_ACQUIRE_INVALID;
else {
f->fd_plus_one = fd + 1;
return DD_ACQUIRE_OK;
}
if (fd >= 0) close(fd);
return result;
}
static inline int dd_frame_acquire_dup(const struct dd_frame_acquire *f) {
if (!f->fd_plus_one) return -1; /* Legacy: no explicit attachment proof. */
int fd = fcntl(f->fd_plus_one - 1, F_DUPFD_CLOEXEC, 0);
return fd < 0 ? -2 : fd; /* Do not re-enter the legacy direct path. */
}
#endif
@@ -0,0 +1,81 @@
#ifndef DD_WORKER_PEER_H
#define DD_WORKER_PEER_H
#include <stdbool.h>
#include <stdint.h>
#include <inttypes.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
/* Model of one app-issued, session-bound authorization record. No callers,
* property access, proc traversal, or authorization is installed by this file. */
struct dd_worker_grant {
uint32_t owner, uid, pid, dev_major, dev_minor;
uint64_t start_ticks, ino, expires;
const char *canonical_file;
bool app_launch_verified, final_go;
};
enum dd_worker_stat_result {
DD_WORKER_STAT_OK, DD_WORKER_STAT_DENIED, DD_WORKER_STAT_HIDDEN, DD_WORKER_STAT_OPEN,
DD_WORKER_STAT_READ, DD_WORKER_STAT_PARSE, DD_WORKER_STAT_ZERO,
};
static inline enum dd_worker_stat_result dd_worker_parse_start(const char *line, uint64_t *out) {
const char *p = strrchr(line, ')');
if (!p || p[1] != ' ' || !p[2] || p[3] != ' ') return DD_WORKER_STAT_PARSE;
p += 2;
// State is field 3. The starttime (22) is always followed by vsize (23).
for (int field = 3; field < 22; ++field) {
p = strchr(p, ' ');
if (!p) return DD_WORKER_STAT_PARSE;
while (*p == ' ') ++p;
}
char *end;
if (*p < '0' || *p > '9') return DD_WORKER_STAT_PARSE;
errno = 0;
uint64_t value = strtoull(p, &end, 10);
if (errno || end == p || *end != ' ') return DD_WORKER_STAT_PARSE;
if (!value) return DD_WORKER_STAT_ZERO;
*out = value;
return DD_WORKER_STAT_OK;
}
static inline enum dd_worker_stat_result dd_worker_open_failure(int error) {
if (error == EACCES || error == EPERM) return DD_WORKER_STAT_DENIED;
if (error == ENOENT || error == ESRCH) return DD_WORKER_STAT_HIDDEN;
return DD_WORKER_STAT_OPEN;
}
static inline bool dd_worker_receipt_allows_reserve(enum dd_worker_stat_result stat,
uint64_t raw, uint64_t receipt) {
if (!receipt) return false;
if (stat == DD_WORKER_STAT_OK) return raw == receipt;
// Only a visibility denial can defer the broker-side stat check, not any
// bad read, malformed record, mismatched timestamp, or other open error.
return stat == DD_WORKER_STAT_DENIED || stat == DD_WORKER_STAT_HIDDEN;
}
static inline bool dd_worker_map_matches(const struct dd_worker_grant *g, const char *line) {
unsigned major, minor;
uint64_t lo, hi, off, ino;
int prefix = 0;
char mode[5];
if (!g->canonical_file || !*g->canonical_file ||
sscanf(line, "%" SCNx64 "-%" SCNx64 " %4s %" SCNx64 " %x:%x %" SCNu64 " %n",
&lo,&hi,mode,&off,&major,&minor,&ino,&prefix)!=7 ||
prefix <= 0 || hi <= lo || strlen(mode)!=4 || mode[2]!='x' ||
major!=g->dev_major || minor!=g->dev_minor || !ino || ino!=g->ino)
return false;
size_t path_len=strcspn(line+prefix,"\r\n");
return strlen(g->canonical_file)==path_len && !memcmp(line+prefix,g->canonical_file,path_len);
}
static inline bool dd_worker_grant_matches(const struct dd_worker_grant *g, uint32_t owner,
uint32_t uid, uint32_t pid, uint64_t start, uint64_t now, const char *executable_map) {
return g && g->app_launch_verified && g->final_go && owner && owner==g->owner &&
uid==g->uid && pid>1 && pid==g->pid && start && start==g->start_ticks &&
now<g->expires && executable_map && dd_worker_map_matches(g,executable_map);
}
#endif
@@ -916,3 +916,42 @@ JNIEXPORT jint JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeStreamFrames(JNIEnv *env, jclass clazz) {
return (jint)droiddeck_stream_frames();
}
#ifdef DROIDDECK_FRAME_ACQUIRE_PROBE
extern int droiddeck_frame_worker_grant(int owner, pid_t pid, uint64_t expires, const char *path,
uint64_t dev, uint64_t ino, uint64_t receipt);
extern void droiddeck_frame_worker_revoke(int owner, int pid);
#endif
JNIEXPORT jboolean JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_frameWorkerProbeEnabled(JNIEnv *env, jclass c) {
#ifdef DROIDDECK_FRAME_ACQUIRE_PROBE
return JNI_TRUE;
#else
return JNI_FALSE;
#endif
}
JNIEXPORT jboolean JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_frameWorkerProbeGrant(JNIEnv *env, jclass c,
jint owner, jint pid, jlong expires, jstring path, jlong dev, jlong ino, jlong start_ticks) {
#ifdef DROIDDECK_FRAME_ACQUIRE_PROBE
if (!path || expires <= 0 || ino <= 0 || start_ticks <= 0) return JNI_FALSE;
const char *name = (*env)->GetStringUTFChars(env, path, NULL);
if (!name) return JNI_FALSE;
int granted = droiddeck_frame_worker_grant(owner, pid, (uint64_t)expires, name, (uint64_t)dev, (uint64_t)ino, (uint64_t)start_ticks);
(*env)->ReleaseStringUTFChars(env, path, name);
return granted ? JNI_TRUE : JNI_FALSE;
#else
return JNI_FALSE;
#endif
}
JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_frameWorkerProbeRevoke(JNIEnv *env, jclass c,
jint owner, jint pid) {
#ifdef DROIDDECK_FRAME_ACQUIRE_PROBE
droiddeck_frame_worker_revoke(owner, pid);
#endif
}
@@ -625,6 +625,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private var appScale by mutableStateOf(com.droiddeck.launcher.core.AppUiPrefs.DEFAULT_SCALE)
private var hdrOn by mutableStateOf(false)
private var zeroCopyOn by mutableStateOf(true)
private var producerAcquireFences by mutableStateOf(false)
private var upscaler by mutableStateOf(0)
private var upscaleSharpness by mutableStateOf(75)
private var hdrReason by mutableStateOf<String?>(null)
@@ -2921,6 +2922,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
mode = mode, resolution = resolution, resolutionPortrait = resolutionPortrait,
panelSize = com.droiddeck.launcher.session.SessionDisplay.panelSize(this),
hdr = hdrOn, hdrReason = hdrReason, hdrDisplay = hdrDisplay, zeroCopy = zeroCopyOn,
producerAcquireFences = producerAcquireFences.takeIf {
mode == SessionService.MODE_STEAM &&
com.droiddeck.launcher.runtime.FrameAcquireWorkerProbe.available(this)
},
upscaler = upscaler, upscaleSharpness = upscaleSharpness,
gpuDrivers = drivers.summary(),
touchMode = touchMode,
@@ -2985,6 +2990,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
SessionPrefs.prefMode(SessionState.mode) == SessionPrefs.prefMode(mode))
com.droiddeck.launcher.wayland.WaylandCompositor.nativeSetZeroCopy(on)
},
onProducerAcquireFences = {
SessionPrefs.setProducerAcquireFences(this, it)
producerAcquireFences = it
},
onGpuDrivers = { openComponents(focusContent = true, tab = com.droiddeck.launcher.ui.GPU_TAB) },
onUpscaler = { m -> SessionPrefs.setUpscaler(this, m); upscaler = m },
onUpscaleSharpness = { pct -> SessionPrefs.setUpscaleSharpness(this, pct); upscaleSharpness = pct },
@@ -3346,6 +3355,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
loadBootMovie()
hdrOn = SessionPrefs.hdr(this, mode)
zeroCopyOn = SessionPrefs.zeroCopy(this, mode)
producerAcquireFences = SessionPrefs.producerAcquireFences(this)
upscaler = SessionPrefs.upscaler(this)
upscaleSharpness = SessionPrefs.upscaleSharpness(this)
hdrReason = com.droiddeck.launcher.wayland.HdrSupport.blocked(this)
@@ -0,0 +1,257 @@
package com.droiddeck.launcher.runtime
import android.content.Context
import android.os.SystemClock
import android.system.Os
import android.system.OsConstants
import android.util.Log
import com.droiddeck.launcher.wayland.WaylandCompositor
import java.io.File
import java.io.InputStream
import java.nio.file.Files
import java.nio.file.LinkOption.NOFOLLOW_LINKS
import java.security.MessageDigest
/** One app-issued Steam session and one attested Gamescope worker. This is not an
* isolation boundary against arbitrary code already running as the Android app UID. */
internal object FrameAcquireWorkerProbe {
private const val SESSION_SCRIPT = "/usr/local/bin/droiddeck-session"
private const val PATH = "/usr/local/bin/gamescope"
private const val CAPABILITY = "linuxfs/usr/local/share/droiddeck/gamescope-producer-acquire-v1"
internal const val GAMESCOPE_ENABLE = "GAMESCOPE_DROIDDECK_PRODUCER_ACQUIRE=1"
internal const val GAME_ENABLE = "DROIDDECK_GAME_DROIDDECK_GAME_FRAME_ACQUIRE=1"
private const val MAX_BINARY_BYTES = 32L * 1024L * 1024L
internal const val RECEIPT_TAG = 0x44445046
internal const val RECEIPT_BYTES = Int.SIZE_BYTES + Long.SIZE_BYTES
private const val TTL_MS = 90_000L
internal data class Ticket(val owner: Int, val root: File, val configuredRoot: File, val binary: File, val expected: ByteArray, val expires: Long)
internal data class Qualified(val ticket: Ticket, val dev: Long, val ino: Long, val mtime: Long, val ctime: Long)
private var intent: Ticket? = null
private var nativeOwner = 0
private var nativePid = 0
private enum class Stage { ARM, MATCH, PUBLISH }
private enum class Reason {
ENABLED, MATCH_ACK, MATCH_OWNER, MATCH_EXPIRED, MATCH_PATH, MATCH_ROOT,
MATCH_ARGV, MATCH_FILE, MATCH_DIGEST, QUALIFIED, PUBLISH_TICKET, PUBLISH_RESTAT,
PUBLISH_NATIVE, PUBLISH_RECEIPT, RESERVED
}
private val reported = mutableSetOf<Stage>()
@Synchronized private fun breadcrumb(stage: Stage, reason: Reason) {
if (reported.add(stage)) Log.i("FrameAcquireWorkerProbe", "worker_admission=" + reason.name)
}
internal fun validEnvironment(agentEnvironment: List<String>, customEnvironment: List<String>): Boolean {
// AgentEnv supplies a replacement PATH whenever any executable override is staged.
// Custom env is user-editable, including names not known to this build; it is not a trust root.
return agentEnvironment.isEmpty() && customEnvironment.isEmpty()
}
fun available(context: Context): Boolean =
android.os.Build.VERSION.SDK_INT >= 30 && com.droiddeck.launcher.core.DeviceSupport.adreno() &&
runCatching { context.assets.open(CAPABILITY).use { it.readBytes().decodeToString() } }
.getOrNull() == "droiddeck-producer-acquire-v1\n"
private fun digest(input: InputStream, maxBytes: Long): ByteArray {
val out = MessageDigest.getInstance("SHA-256")
val buffer = ByteArray(64 * 1024)
var size = 0L
while (true) {
val n = input.read(buffer)
if (n == -1) break
require(n > 0)
size += n
require(size <= maxBytes)
out.update(buffer, 0, n)
}
require(size > 0)
return out.digest()
}
// Compute asset identity outside SessionService's stop lock and before a worker
// exists. The resulting ticket still has to be assigned to that exact owner.
internal fun prepare(context: Context): Ticket? {
if (!available(context) || !WaylandCompositor.frameWorkerProbeEnabled()) return null
return runCatching {
val configuredRoot = LinuxRuntime.rootDir(context).absoluteFile
val root = configuredRoot.canonicalFile
val file = File(root.path + PATH)
require(file.canonicalFile == file && Files.isRegularFile(file.toPath(), NOFOLLOW_LINKS))
val script = File(root.path + SESSION_SCRIPT)
require(exactSteamScript(SESSION_SCRIPT, root, configuredRoot))
val stagedScript = script.inputStream().use { digest(it, 1024L * 1024L) }
val signedScript = context.assets.open("linuxfs" + SESSION_SCRIPT).use { digest(it, 1024L * 1024L) }
require(MessageDigest.isEqual(stagedScript, signedScript))
val expected = context.assets.open("linuxfs" + PATH).use { digest(it, MAX_BINARY_BYTES) }
Ticket(0, root, configuredRoot, file, expected, SystemClock.elapsedRealtime() + TTL_MS)
}.getOrNull()
}
@Synchronized fun arm(owner: Int, prepared: Ticket): Boolean {
if (owner <= 0 || SystemClock.elapsedRealtime() >= prepared.expires) return false
reported.clear()
intent = prepared.copy(owner = owner)
breadcrumb(Stage.ARM, Reason.ENABLED)
return true
}
/** Native shebang handling can give Bash the staged host filename as its $0. */
internal fun exactSteamScript(token: String, root: File, configuredRoot: File): Boolean {
if (token != SESSION_SCRIPT && token != root.path + SESSION_SCRIPT &&
token != configuredRoot.path + SESSION_SCRIPT) return false
return runCatching {
val expected = File(root.path + SESSION_SCRIPT)
val supplied = if (token == SESSION_SCRIPT) expected else File(token)
// Reject symlinks within the authorized root, including a symlink replacing the script.
// Android's configured root itself may be an alias of its app-issued canonical root.
require(configuredRoot.canonicalFile == root && expected.canonicalFile == expected &&
supplied.canonicalFile == expected &&
Files.isRegularFile(expected.toPath(), NOFOLLOW_LINKS) &&
Files.isRegularFile(supplied.toPath(), NOFOLLOW_LINKS))
Files.isSameFile(supplied.toPath(), expected.toPath())
}.getOrDefault(false)
}
internal fun exactGamescopeArgs(argv: List<String>, script: (String) -> Boolean): Boolean {
if (argv.firstOrNull() !in listOf("gamescope", PATH)) return false
val delimiter = argv.indexOf("--")
if (delimiter < 4 || argv.size != delimiter + 3 || argv[delimiter + 2] != "steam" ||
!script(argv[delimiter + 1])) return false
val opts = argv.subList(1, delimiter)
if (opts.take(4) != listOf("--backend", "wayland", "--expose-wayland", "-f")) return false
val dimensions = setOf("-W", "-H", "-w", "-h")
val seen = mutableSetOf<String>()
var i = 4
while (i < opts.size) {
val option = opts[i++]
if (!seen.add(option)) return false
when (option) {
"-e", "--hdr-enabled", "--mangoapp" -> Unit
"-S" -> if (opts.getOrNull(i++) != "stretch") return false
"--default-touch-mode" -> if (opts.getOrNull(i++) != "4") return false
"-W", "-H", "-w", "-h", "-r", "--xwayland-count" -> {
val value = opts.getOrNull(i++) ?: return false
if (value.length !in 1..6 || value.any { it !in '0'..'9' } ||
value.toIntOrNull()?.let { it > 0 } != true) return false
}
else -> return false
}
}
return seen.containsAll(dimensions)
}
fun match(owner: Int, root: File, file: String, argv: List<String>, ack: Boolean): Qualified? {
val t = synchronized(this) { intent } ?: return null
// Startup's --version worker and unrelated workers must not consume the one diagnostic.
val candidate = "--version" !in argv && (file.substringAfterLast('/') == "gamescope" ||
argv.firstOrNull()?.substringAfterLast('/') == "gamescope")
val rejection = when {
!ack -> Reason.MATCH_ACK
t.owner != owner -> Reason.MATCH_OWNER
SystemClock.elapsedRealtime() >= t.expires -> Reason.MATCH_EXPIRED
file != PATH -> Reason.MATCH_PATH
runCatching { root.canonicalFile }.getOrNull() != t.root -> Reason.MATCH_ROOT
!exactGamescopeArgs(argv) { exactSteamScript(it, t.root, t.configuredRoot) } -> Reason.MATCH_ARGV
else -> null
}
if (rejection != null) {
if (candidate) breadcrumb(Stage.MATCH, rejection)
return null
}
// Hash an actual descriptor rather than two pathname opens. Check both the
// descriptor and pathname identity; a race or substituted executable denies the grant.
val qualified = runCatching {
require(t.binary.canonicalFile == t.binary)
val before = Os.lstat(t.binary.path)
require(OsConstants.S_ISREG(before.st_mode) && before.st_size in 1..MAX_BINARY_BYTES)
val fd = Os.open(t.binary.path, OsConstants.O_RDONLY or OsConstants.O_NOFOLLOW or OsConstants.O_CLOEXEC, 0)
val sum = try {
require(stillSame(before, Os.fstat(fd)))
android.os.ParcelFileDescriptor.AutoCloseInputStream(android.os.ParcelFileDescriptor.dup(fd)).use {
digest(it, MAX_BINARY_BYTES)
}.also { require(stillSame(before, Os.fstat(fd))) }
} finally {
Os.close(fd)
}
val after = Os.lstat(t.binary.path)
require(stillSame(before, after))
if (!MessageDigest.isEqual(sum, t.expected)) {
breadcrumb(Stage.MATCH, Reason.MATCH_DIGEST)
return null
}
Qualified(t, after.st_dev, after.st_ino, after.st_mtime, after.st_ctime)
}.getOrNull()
breadcrumb(Stage.MATCH, if (qualified == null) Reason.MATCH_FILE else Reason.QUALIFIED)
return qualified
}
private fun stillSame(a: android.system.StructStat, b: android.system.StructStat): Boolean =
a.st_dev == b.st_dev && a.st_ino == b.st_ino && a.st_size == b.st_size &&
a.st_mtime == b.st_mtime && a.st_ctime == b.st_ctime &&
OsConstants.S_ISREG(b.st_mode)
internal fun validReceipt(pid: Int, workerPid: Int, ticks: Long, bytes: Int): Long =
if (pid > 1 && pid == workerPid && ticks > 0 && bytes == RECEIPT_BYTES) ticks else 0L
internal fun parseSelfStat(stat: String, pid: Int): Long {
if (pid <= 1 || !stat.startsWith("$pid (")) return 0L
val comm = stat.lastIndexOf(')')
if (comm < 3 || stat.getOrNull(comm + 1) != ' ') return 0L
val fields = stat.substring(comm + 2).split(' ').filter { it.isNotEmpty() }
if (fields.firstOrNull()?.length != 1 || fields.size < 21) return 0L
val value = fields[19] // field 22 from field 3 (the single-character task state).
return value.takeIf { it.isNotEmpty() && it.all { ch -> ch in '0'..'9' } }
?.toLongOrNull()?.takeIf { it > 0 } ?: 0L
}
internal fun selfStartTicks(pid: Int): Long = runCatching {
File("/proc/self/stat").inputStream().use { input ->
val bytes = ByteArray(4096)
var used = 0
while (used < bytes.size) {
val n = input.read(bytes, used, bytes.size - used)
if (n < 0) break
if (n == 0) return@runCatching 0L
used += n
}
if (used == bytes.size || used == 0 || bytes[used-1] != '\n'.code.toByte()) 0L
else parseSelfStat(String(bytes, 0, used, Charsets.US_ASCII), pid)
}
}.getOrDefault(0L)
/** Runs just before the final GO byte. Failure never changes ordinary launch. */
@Synchronized fun publish(q: Qualified, pid: Int, startTicks: Long) {
val t = q.ticket
if (intent !== t || pid <= 1 || SystemClock.elapsedRealtime() >= t.expires) {
if (intent === t) breadcrumb(Stage.PUBLISH, Reason.PUBLISH_TICKET)
return
}
intent = null // At most one candidate per explicitly armed session.
if (startTicks <= 0L) {
breadcrumb(Stage.PUBLISH, Reason.PUBLISH_RECEIPT)
return
}
val status = runCatching {
val st = Os.lstat(t.binary.path)
require(OsConstants.S_ISREG(st.st_mode) && st.st_dev == q.dev && st.st_ino == q.ino &&
st.st_mtime == q.mtime && st.st_ctime == q.ctime)
if (WaylandCompositor.frameWorkerProbeGrant(t.owner, pid, t.expires, t.binary.path, st.st_dev, st.st_ino, startTicks)) {
nativeOwner = t.owner
nativePid = pid
Reason.RESERVED
} else Reason.PUBLISH_NATIVE
}.getOrDefault(Reason.PUBLISH_RESTAT)
breadcrumb(Stage.PUBLISH, status)
}
@Synchronized fun revoke(owner: Int, pid: Int = 0) {
if (owner <= 0) return
if (pid == 0 && intent?.owner == owner) intent = null
if (nativeOwner == owner && (pid == 0 || pid == nativePid)) {
WaylandCompositor.frameWorkerProbeRevoke(owner, pid)
nativeOwner = 0
nativePid = 0
}
}
}
@@ -45,7 +45,16 @@ open class GuestWorker : Service() {
val fillBinderFd = data.readInt() != 0
val go = data.readFileDescriptor()
val nice = data.readInt()
reply?.writeInt(Process.myPid())
val pid = Process.myPid()
reply?.writeInt(pid)
// Optional fixed-size receipt, on the exact local, non-exported worker's Binder.
// Nothing in the guest socket request populates these fields.
if (reply != null &&
Binder.getCallingUid() == Process.myUid() &&
data.dataAvail() == Int.SIZE_BYTES && data.readInt() == FrameAcquireWorkerProbe.RECEIPT_TAG) {
reply.writeInt(pid)
reply.writeLong(FrameAcquireWorkerProbe.selfStartTicks(pid))
}
Handler(Looper.getMainLooper()).post {
// The app writes a byte once it has the reply and has taken the launch on: an exec
// before then would end this process with the reply undelivered, and with none (the
@@ -437,7 +446,8 @@ object GuestWorkers {
private fun start(context: Context, argv: List<String>, env: List<String>, fds: List<ParcelFileDescriptor>, targets: IntArray,
guest: Boolean, onExit: (Int) -> Unit, commit: (Int) -> Boolean = { true },
confirmed: () -> Boolean = { true }, owner: Int = session,
nice: Int = Process.getThreadPriority(Process.myTid())): Int {
nice: Int = Process.getThreadPriority(Process.myTid()),
testWorker: FrameAcquireWorkerProbe.Qualified? = null): Int {
val app = context.applicationContext
if (guest && owner <= stopped) {
Log.w(TAG, (if (owner == 0) "a request naming no session" else "session $owner is stopping") +
@@ -473,13 +483,21 @@ object GuestWorkers {
data.writeInt(if (guest) 0 else 1)
data.writeFileDescriptor(go[0].fileDescriptor)
data.writeInt(nice)
slot.service!!.transact(GuestWorker.RUN, data, reply, 0)
val service = checkNotNull(slot.service)
if (testWorker != null) data.writeInt(FrameAcquireWorkerProbe.RECEIPT_TAG)
check(service.transact(GuestWorker.RUN, data, reply, 0))
// The worker has its own copy: with ours closed (and the request's, which holds one too),
// a worker that gave up leaves no reader
data.recycle()
data = null
go[0].close()
val pid = reply.readInt()
val startTicks = if (testWorker != null) {
val size = reply.dataAvail()
if (size == FrameAcquireWorkerProbe.RECEIPT_BYTES)
FrameAcquireWorkerProbe.validReceipt(pid, reply.readInt(), reply.readLong(), size)
else 0L
} else 0L
// Once a session's teardown has begun (stopGuests), none of its programs may start: it
// would not find them.
val stopping = { guest && owner <= stopped }
@@ -508,7 +526,12 @@ object GuestWorkers {
// launching slot), or never.
val answered = Os.poll(arrayOf(answer), ANSWER_TIMEOUT_MS) > 0 && Os.read(go[1].fileDescriptor, ByteArray(1), 0, 1) == 1
val accepted = answered && synchronized(authorizing) {
!stopping() && confirmed() && Os.write(go[1].fileDescriptor, byteArrayOf(1), 0, 1) == 1
if (stopping() || !confirmed()) false
else {
if (testWorker != null) FrameAcquireWorkerProbe.publish(testWorker, pid,
if (slot.service === service) startTicks else 0L)
Os.write(go[1].fileDescriptor, byteArrayOf(1), 0, 1) == 1
}
}
val endedRunning = synchronized(slots) {
slot.launching = false
@@ -685,6 +708,7 @@ object GuestWorkers {
}
}
context?.let { app -> drained.forEach { release(app, it) } }
FrameAcquireWorkerProbe.revoke(of)
val pids = guestPids(of)
if (pids.isEmpty()) return
pids.forEach { Process.sendSignal(it, OsConstants.SIGTERM) }
@@ -902,16 +926,19 @@ object GuestWorkers {
val owner = request.optInt("session", 0).coerceAtLeast(0)
// The sender is the forked child (or droiddeck-spawn): its priority is the one the program would inherit
val nice = runCatching { Process.getThreadPriority(client.peerCredentials.pid) }.getOrDefault(Process.THREAD_PRIORITY_DEFAULT)
val testWorker = FrameAcquireWorkerProbe.match(owner, root, file, argv, ack)
val pid = start(app, command, env.map { (k, v) -> "$k=$v" }, programFds, targets, true, owner = owner, nice = nice, onExit = { code ->
if (testWorker != null && worker > 1) FrameAcquireWorkerProbe.revoke(owner, worker)
status = code
if (table != null && slot >= 0) reportExit(table, slot, code, parent, child, worker)
exited.countDown()
}, confirmed = {
!ack || runCatching {
val confirmed = !ack || runCatching {
out.write("ok\n".toByteArray())
out.flush()
confirmedToHook = true
}.isSuccess
confirmed
}, commit = { started ->
worker = started
if (!ack) return@start true
@@ -930,7 +957,8 @@ object GuestWorkers {
}
ended && line.toString() == "go"
}.getOrDefault(false)
})
}, testWorker = testWorker)
if (pid <= 0 && testWorker != null && worker > 1) FrameAcquireWorkerProbe.revoke(owner, worker)
handedOver = true
programFds.filter { it !== table }.forEach { runCatching { it.close() } }
if (pid <= 0) table?.let { runCatching { it.close() } }
@@ -1874,6 +1874,13 @@ object SessionPrefs {
prefs(context).edit().putBoolean(hdrKey(mode), on).apply()
}
/** Restart-scoped opt-in; not inferred from Zero-copy (which defaults on). */
fun producerAcquireFences(context: Context): Boolean = prefs(context).getBoolean("producerAcquireFences", false)
fun setProducerAcquireFences(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("producerAcquireFences", on).apply()
}
fun zeroCopy(context: Context, mode: String): Boolean = prefs(context).getBoolean("zeroCopy.${prefMode(mode)}", true)
fun setZeroCopy(context: Context, mode: String, on: Boolean) {
@@ -555,9 +555,10 @@ class SessionService : Service() {
return
}
}
val agentEnvironment = runCatching { com.droiddeck.launcher.agent.AgentEnv.beginSession(this) }
val nextAgentEnvironment = runCatching { com.droiddeck.launcher.agent.AgentEnv.beginSession(this) }
.onFailure { Log.w(TAG, "agent environment skipped", it) }
.getOrDefault(emptyList())
val agentEnvironment = nextAgentEnvironment.getOrDefault(emptyList())
val customEnvironment = extraEnv()
try {
if (systemVulkan) {
SystemVulkanDriver.prepare(this)
@@ -623,7 +624,7 @@ class SessionService : Service() {
.onFailure { Log.w(TAG, "forced components", it) }
}
try {
SessionEvents.step("client-environment") { addClientEnvironment(guest, steamHere, agentEnvironment) }
SessionEvents.step("client-environment") { addClientEnvironment(guest, steamHere, agentEnvironment, customEnvironment) }
} catch (e: IllegalStateException) {
Log.e(TAG, "Could not resolve the selected Linux Vulkan driver", e)
failSession(gen, "VULKAN_DRIVER_UNAVAILABLE", e.message ?: "Selected Linux Vulkan driver is unavailable", -1)
@@ -708,15 +709,27 @@ class SessionService : Service() {
// this session's worker number: the shared field may be a newer session's by the time it is used
var ownWorkers = 0
if (com.droiddeck.launcher.runtime.GuestWorkers.enabled(this)) {
val fenceWorker = com.droiddeck.launcher.runtime.FrameAcquireWorkerProbe
val preparedFence = if (steamHere && !systemVulkan && !VenusComponent.wanted(this) &&
SessionPrefs.zeroCopy(this, MODE_STEAM) && SessionPrefs.producerAcquireFences(this) &&
nextAgentEnvironment.isSuccess && fenceWorker.validEnvironment(agentEnvironment, customEnvironment)) fenceWorker.prepare(this) else null
var fenceArmed = false
// Under the lock a stop takes its number with: a stop either comes first (and this session
// starts no workers) or owns them
ownWorkers = synchronized(stopLock) {
if (gen != sessionGen || !SessionState.running) 0
else com.droiddeck.launcher.runtime.GuestWorkers.serve(this).also { guestWorkerSession = it }
else com.droiddeck.launcher.runtime.GuestWorkers.serve(this).also {
guestWorkerSession = it
if (preparedFence != null) fenceArmed = fenceWorker.arm(it, preparedFence)
}
}
if (ownWorkers > 0) {
guest.add("DD_SPAWN=" + com.droiddeck.launcher.runtime.GuestWorkers.socketName(this))
guest.add("DD_SPAWN_SESSION=$ownWorkers")
if (fenceArmed) {
guest.add(fenceWorker.GAMESCOPE_ENABLE)
guest.add(fenceWorker.GAME_ENABLE)
}
}
}
// Proton builds up to 11.12 report X11 text fields under this name.
@@ -1017,7 +1030,8 @@ class SessionService : Service() {
return com.droiddeck.launcher.input.GesturePrefs.read(this, game).relativeMouseMode
}
private fun addClientEnvironment(guest: MutableList<String>, steamHere: Boolean, agentEnvironment: List<String>) {
private fun addClientEnvironment(guest: MutableList<String>, steamHere: Boolean,
agentEnvironment: List<String>, customEnvironment: List<String>) {
guest.add("/usr/bin/env")
guest.add("-i")
guest.add("DROIDDECK_BWRAP_SOCKET=" + com.droiddeck.launcher.runtime.BwrapSpawner.socket(this))
@@ -1135,7 +1149,7 @@ class SessionService : Service() {
guest.add("DD_ZRAM=1")
}
guest.add("AUDIO_DIRECT_DECAY=0")
val extra = extraEnv() + agentEnvironment
val extra = customEnvironment + agentEnvironment
guest.addAll(TurnipEnvironment.gameEnvironment(tuOverride, tuDriver, SessionPrefs.tuSysmem(this), extra))
if (extra.none { it.startsWith("MESA_NO_ERROR=") }) guest.add("${GAME_PREFIX}MESA_NO_ERROR=")
extra.forEach { guest.add(it) }
@@ -20,7 +20,7 @@ object SettingsReset {
"gamepadLeft", "gamepadRight", "pipAutoEnter", "unfoldedControls", "unfoldedControlsWithController",
"stretch16x9", "avoidNotch", "picturePosition", "integerScaling", "railLabels", "developerTools", "navTabOrder", "navTabShelved", "navTabHidden", "drawerPageOrder", "drawerPageHidden", "drawerSections", "pcKeyboardSize", "pcKeyboardOpacity", "pcKeyboardHiddenKeys",
"gpuDriverMode", "androidDriver", "linuxDriver", "linuxDriver.steam", "linuxDriver.desktop",
"tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "paceCores",
"tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "producerAcquireFences", "paceCores",
"directAudio", "mic", "wifiDiscovery", "clientCpusOverride", "clientCpus", "gameCpus",
"noXalia", "fastSync", "fsyncFirst", "syncFallback", "prootNoSeccomp", "prootFastPath", "nativeUserland", "cursorComposite", "mountSharedStorage",
"guestHostname", "fexPreset", "forceSsbs", "logs", "gameDebugLogsEnabled", "enhancedDiagnosticsNext", "storageDiagnostics", "buildWatermark",
@@ -62,6 +62,7 @@ class ModeSettings(
val hdrReason: String?,
val hdrDisplay: Boolean = true,
val zeroCopy: Boolean = true,
val producerAcquireFences: Boolean? = null,
val gpuDrivers: String? = null,
val upscaler: Int = 0,
val upscaleSharpness: Int = 75,
@@ -125,6 +126,7 @@ class ModeSettingsActions(
val onResolutionPortrait: (String) -> Unit = {},
val onHdr: (Boolean) -> Unit,
val onZeroCopy: (Boolean) -> Unit = {},
val onProducerAcquireFences: (Boolean) -> Unit = {},
val onGpuDrivers: () -> Unit = {},
val onUpscaler: (Int) -> Unit = {},
val onUpscaleSharpness: (Int) -> Unit = {},
@@ -284,6 +286,11 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
stringResource(R.string.display_avoid_notch_hint), checked = enabled, onChange = a.onAvoidNotch)
}
ToggleRow(host, "zero-copy", stringResource(R.string.display_zero_copy), null, checked = s.zeroCopy, onChange = a.onZeroCopy)
s.producerAcquireFences?.let { enabled ->
ToggleRow(host, "producer-acquire-fences", stringResource(R.string.producer_acquire_fences),
stringResource(R.string.producer_acquire_fences_summary), checked = enabled,
onChange = a.onProducerAcquireFences)
}
}
SettingsGroup(stringResource(R.string.display_image_scaling)) {
s.integerScaling?.let { enabled ->
@@ -9,6 +9,10 @@ public final class WaylandCompositor {
private WaylandCompositor() {}
public static native boolean frameWorkerProbeEnabled();
public static native boolean frameWorkerProbeGrant(int owner, int pid, long expires, String path, long dev, long ino, long startTicks);
public static native void frameWorkerProbeRevoke(int owner, int pid);
private static volatile Runnable firstFrameListener;
public static void setFirstFrameListener(Runnable r) { firstFrameListener = r; }
+2
View File
@@ -4514,4 +4514,6 @@
<string name="steam_store_close_steam">Close Steam first</string>
<string name="steam_store_session_wait">Pause the Steam download first</string>
<string name="steam_store_linux_build">This game installs its Linux build. Install it from Steam.</string>
<string name="producer_acquire_fences">Direct game frames (experimental)</string>
<string name="producer_acquire_fences_summary">With Zero-copy enabled, compatible Steam games can avoid a frame copy. Takes effect next session.</string>
</resources>
@@ -0,0 +1,88 @@
package com.droiddeck.launcher.runtime
import java.io.File
import java.nio.file.Files
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class FrameAcquireWorkerProbeTest {
@Test fun requiresExactSteamScriptInTheAppIssuedGuestRoot() {
val dir = Files.createTempDirectory("worker-probe-script").toFile().canonicalFile
try {
val root = File(dir, "root").apply { mkdir() }
val configured = File(dir, "configured")
Files.createSymbolicLink(configured.toPath(), root.toPath())
val untrustedAlias = File(dir, "other-alias")
Files.createSymbolicLink(untrustedAlias.toPath(), root.toPath())
val script = "/usr/local/bin/droiddeck-session"
val expected = File(root.path + script).apply { parentFile!!.mkdirs(); writeText("#!/bin/bash\n") }
val otherRoot = File(dir, "sibling")
File(otherRoot.path + script).apply { parentFile!!.mkdirs(); writeText("#!/bin/bash\n") }
val otherScript = File(expected.parentFile, "other-script").apply { writeText("#!/bin/bash\n") }
val args = listOf("gamescope", "--backend", "wayland", "--expose-wayland", "-f",
"-W", "1280", "-H", "720", "-w", "1280", "-h", "720", "-r", "60",
"-e", "--xwayland-count", "2", "--default-touch-mode", "4", "--hdr-enabled",
"--", script, "steam")
fun valid(argv: List<String>) = FrameAcquireWorkerProbe.exactGamescopeArgs(argv) {
FrameAcquireWorkerProbe.exactSteamScript(it, root, configured)
}
fun child(path: String) = args.dropLast(2) + listOf(path, "steam")
assertTrue(valid(args))
assertTrue(valid(args.toMutableList().also { it[0] = "/usr/local/bin/gamescope" }))
assertFalse(valid(args.toMutableList().also { it[0] = "/opt/droiddeck-agent/bin/gamescope" }))
assertTrue(valid(child(root.path + script)))
assertTrue(valid(child(configured.path + script)))
for (path in listOf(otherRoot.path + script, untrustedAlias.path + script,
root.path + "/usr/local/bin/./droiddeck-session", root.path + "/../sibling" + script,
otherScript.path, "droiddeck-session")) {
assertFalse(valid(child(path)))
}
for (bad in listOf(listOf("gamescope", "--version"), args + "",
args + "steam://open/library", args.dropLast(1) + "desktop",
args.take(5) + "--unknown-flag" + args.drop(5),
args.take(5) + listOf("-W", "64") + args.drop(5))) {
assertFalse(valid(bad))
}
assertTrue(expected.delete())
Files.createSymbolicLink(expected.toPath(), otherScript.toPath())
assertFalse(valid(args))
assertFalse(valid(child(configured.path + script)))
} finally {
// Don't follow the intentionally broken/foreign symlinks in this fixture.
Files.walk(dir.toPath()).use { paths ->
paths.sorted(Comparator.reverseOrder()).forEach { Files.deleteIfExists(it) }
}
}
}
@Test fun selfStatAndFixedBinderReceiptRejectWrongWorkerAndExtraBytes() {
val probe = FrameAcquireWorkerProbe
val fields = (1..18).joinToString(" ")
fun stat(pid: Int, ticks: String) = "$pid (guest )worker) S $fields $ticks 123\n"
assertTrue(probe.parseSelfStat(stat(400, "125"), 400) == 125L)
for (bad in listOf(stat(401, "125"), stat(400, "0"), stat(400, "-1"),
stat(400, "1x"), stat(400, "9223372036854775808"), "400 (guest)")) {
assertTrue(probe.parseSelfStat(bad, 400) == 0L)
}
val size = probe.RECEIPT_BYTES
assertTrue(probe.validReceipt(400, 400, 125L, size) == 125L)
assertTrue(probe.validReceipt(400, 401, 125L, size) == 0L)
assertTrue(probe.validReceipt(1, 1, 125L, size) == 0L)
assertTrue(probe.validReceipt(400, 400, 0L, size) == 0L)
assertTrue(probe.validReceipt(400, 400, -1L, size) == 0L)
assertTrue(probe.validReceipt(400, 400, 125L, size - 4) == 0L)
assertTrue(probe.validReceipt(400, 400, 125L, size + 4) == 0L)
}
@Test fun anyCustomOrAgentEnvironmentDisablesTheProductionTicket() {
val probe = FrameAcquireWorkerProbe
assertTrue(probe.validEnvironment(emptyList(), emptyList()))
assertFalse(probe.validEnvironment(listOf("PATH=/opt/droiddeck-agent/bin"), emptyList()))
assertFalse(probe.validEnvironment(emptyList(), listOf("LD_PRELOAD=/tmp/custom.so")))
assertFalse(probe.validEnvironment(listOf("DD_THOR_WORKER_ACQUIRE_TEST=1"), emptyList()))
}
}