mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-22 22:36:00 +00:00
Merge branch 'main' into fix/steam-client-download
This commit is contained in:
123 files changed
+2637
-331
No files matched your search
@@ -21,6 +21,30 @@ unpack() {
|
||||
{ rm -rf "$dir.new"; echo "droiddeck-pipewire: could not unpack $bundle" >&2; return 1; }
|
||||
}
|
||||
|
||||
access_config() {
|
||||
mkdir -p "$dir/share/pipewire/pipewire.conf.d" "$dir/share/wireplumber/wireplumber.conf.d" || return 1
|
||||
cat > "$dir/share/pipewire/pipewire.conf.d/droiddeck-access.conf" <<'EOF' || return 1
|
||||
context.properties = {
|
||||
module.access = false
|
||||
}
|
||||
context.modules = [
|
||||
{ name = libpipewire-module-access
|
||||
args = {
|
||||
access.socket = { pipewire-0 = "unrestricted", pipewire-0-manager = "unrestricted" }
|
||||
}
|
||||
}
|
||||
]
|
||||
EOF
|
||||
cat > "$dir/share/wireplumber/wireplumber.conf.d/droiddeck-access.conf" <<'EOF' || return 1
|
||||
access.rules = [
|
||||
{
|
||||
matches = [ { pipewire.access = "unrestricted" } ]
|
||||
actions = { update-props = { default_permissions = "all" } }
|
||||
}
|
||||
]
|
||||
EOF
|
||||
}
|
||||
|
||||
stop() {
|
||||
for pid in $(cat "$state/pids" 2>/dev/null); do kill "$pid" 2>/dev/null; done
|
||||
rm -f "$state/pids"
|
||||
@@ -32,6 +56,7 @@ env)
|
||||
;;
|
||||
start)
|
||||
unpack || exit 1
|
||||
access_config || { echo "droiddeck-pipewire: could not write the access settings" >&2; exit 1; }
|
||||
stop
|
||||
mkdir -p "$state"
|
||||
eval "$(client_env)"
|
||||
|
||||
@@ -60,6 +60,9 @@ clear_stale_tmp() {
|
||||
return 0
|
||||
}
|
||||
[ -z "${BL_INSIDE:-}" ] && clear_stale_tmp
|
||||
if [ -z "${BL_INSIDE:-}" ]; then
|
||||
if [ "${BL_ZRAM:-0}" = 1 ]; then printf 0 > /tmp/.bl-zram; else rm -f /tmp/.bl-zram; fi
|
||||
fi
|
||||
|
||||
steam_update_stuck() {
|
||||
[ "$1" -lt 60 ] || steam_updates=0
|
||||
@@ -443,7 +446,6 @@ case $mode in
|
||||
step "client cores: $BL_CLIENT_CPUS"
|
||||
fi
|
||||
if [ "${BL_ZRAM:-0}" = 1 ]; then
|
||||
printf 0 > /tmp/.bl-zram
|
||||
step "zRAM compression: on"
|
||||
(
|
||||
bl_zram_scan() {
|
||||
@@ -492,8 +494,6 @@ case $mode in
|
||||
nap 5
|
||||
done
|
||||
) &
|
||||
else
|
||||
rm -f /tmp/.bl-zram
|
||||
fi
|
||||
if [ "${BL_LAUNCHER_CORES:-1}" != 0 ] && [ -n "${BL_LAUNCH_DIR:-}" ] && [ -z "${BL_DESKTOP:-}" ] \
|
||||
&& [ "${BL_STEAM_UI:-}" != desktop ] && [ -x /usr/local/bin/droiddeck-launcher-cores ]; then
|
||||
|
||||
@@ -409,6 +409,8 @@ int bl_drm_gem_close(int fd, unsigned long request, void *arg, int *rc) __attrib
|
||||
int bl_venc_ioctl(int fd, unsigned long request, void *arg, int *rc) __attribute__((visibility("hidden")));
|
||||
int bl_winebus_rumble_ioctl(int (*real)(int, unsigned long, void *), int fd, unsigned long request,
|
||||
void *arg, void *caller, int *rc) __attribute__((visibility("hidden")));
|
||||
int bl_writewatch_ioctl(int (*real)(int, unsigned long, void *), int fd, unsigned long request, void *arg,
|
||||
int *rc) __attribute__((visibility("hidden")));
|
||||
|
||||
int ioctl(int fd, unsigned long request, ...) {
|
||||
typedef int (*ioctl_fn)(int, unsigned long, void *);
|
||||
@@ -424,6 +426,7 @@ int ioctl(int fd, unsigned long request, ...) {
|
||||
if (bl_drm_gem_close(fd, request, arg, &rc)) return rc;
|
||||
if (real == NULL) real = (ioctl_fn) dlsym(RTLD_NEXT, "ioctl");
|
||||
if (bl_winebus_rumble_ioctl(real, fd, request, arg, __builtin_return_address(0), &rc)) return rc;
|
||||
if (bl_writewatch_ioctl(real, fd, request, arg, &rc)) return rc;
|
||||
if (!bl_kgsl_poll(real, fd, request, arg, &rc)) rc = quest_kgsl_ioctl(real, fd, request, arg);
|
||||
bl_kgsl_chip_id_fixup(request, arg, rc);
|
||||
if (arg == NULL || !is_link_query(request)) return rc;
|
||||
|
||||
@@ -329,6 +329,8 @@ static int execveat_is_execve(const long *args) {
|
||||
return path[0] == '/' || (int)args[0] == AT_FDCWD;
|
||||
}
|
||||
|
||||
int bl_writewatch_syscall(long number, const long *args, long (*real)(long, ...), long *rc) __attribute__((visibility("hidden")));
|
||||
|
||||
long syscall(long number, ...) {
|
||||
va_list ap;
|
||||
long args[6];
|
||||
@@ -354,6 +356,9 @@ long syscall(long number, ...) {
|
||||
if (!real_syscall) {
|
||||
real_syscall = (long (*)(long, ...)) dlsym(RTLD_NEXT, "syscall");
|
||||
}
|
||||
if (bl_writewatch_syscall(number, args, real_syscall, &handled)) {
|
||||
return handled;
|
||||
}
|
||||
if (number == SYS_openat2) {
|
||||
if (!__atomic_load_n(&openat2_missing, __ATOMIC_RELAXED)) {
|
||||
long fd = real_syscall(number, args[0], args[1], args[2], args[3]);
|
||||
|
||||
@@ -16,6 +16,8 @@
|
||||
#define STATUS_MAX 16384
|
||||
#define TRACER_FIELD "\nTracerPid:\t"
|
||||
|
||||
int bl_from_ntdll(const void *caller) __attribute__((visibility("hidden")));
|
||||
|
||||
static const char *skip_digits(const char *s) {
|
||||
const char *end = s;
|
||||
while (isdigit((unsigned char)*end)) end++;
|
||||
@@ -77,7 +79,8 @@ __attribute__((visibility("hidden"))) int bl_status_without_tracer(const char *p
|
||||
int out = -1;
|
||||
|
||||
long pid;
|
||||
if ((flags & O_ACCMODE) != O_RDONLY || (pid = status_pid(path)) < 0 || is_web_helper(caller)) return -1;
|
||||
if ((flags & O_ACCMODE) != O_RDONLY || (pid = status_pid(path)) < 0 || is_web_helper(caller) || bl_from_ntdll(caller))
|
||||
return -1;
|
||||
int in = (int)syscall(SYS_openat, AT_FDCWD, path, O_RDONLY | O_CLOEXEC);
|
||||
if (in < 0) goto done;
|
||||
for (;;) {
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
#define _GNU_SOURCE
|
||||
#include <dlfcn.h>
|
||||
#include <link.h>
|
||||
#include <signal.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
#include <sys/auxv.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <ucontext.h>
|
||||
#include <unistd.h>
|
||||
|
||||
static uintptr_t ntdll_lo, ntdll_hi;
|
||||
|
||||
static int find_ntdll(struct dl_phdr_info *info, size_t size, void *data) {
|
||||
(void)size;
|
||||
(void)data;
|
||||
const char *slash = strrchr(info->dlpi_name, '/');
|
||||
if (strcmp(slash ? slash + 1 : info->dlpi_name, "ntdll.so") != 0) return 0;
|
||||
for (int i = 0; i < info->dlpi_phnum; i++) {
|
||||
const ElfW(Phdr) *ph = &info->dlpi_phdr[i];
|
||||
if (ph->p_type != PT_LOAD || !(ph->p_flags & PF_X)) continue;
|
||||
uintptr_t lo = info->dlpi_addr + ph->p_vaddr;
|
||||
__atomic_store_n(&ntdll_hi, lo + ph->p_memsz, __ATOMIC_RELAXED);
|
||||
__atomic_store_n(&ntdll_lo, lo, __ATOMIC_RELEASE);
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden"))) int bl_from_ntdll(const void *caller) {
|
||||
uintptr_t pc = (uintptr_t)caller, lo = __atomic_load_n(&ntdll_lo, __ATOMIC_ACQUIRE);
|
||||
if (!lo) {
|
||||
dl_iterate_phdr(find_ntdll, NULL);
|
||||
lo = __atomic_load_n(&ntdll_lo, __ATOMIC_ACQUIRE);
|
||||
if (!lo) return 0;
|
||||
}
|
||||
return pc >= lo && pc < __atomic_load_n(&ntdll_hi, __ATOMIC_RELAXED);
|
||||
}
|
||||
|
||||
#if defined(__aarch64__)
|
||||
#include <asm/hwcap.h>
|
||||
#include <asm/sigcontext.h>
|
||||
|
||||
#define BL_STR2(x) #x
|
||||
#define BL_STR(x) BL_STR2(x)
|
||||
|
||||
#define BL_HWCAP_GCS (1UL << 32)
|
||||
#define BL_FRAME_SIZE 4688
|
||||
#define BL_REGS 312
|
||||
#define BL_SP 560
|
||||
#define BL_PC 568
|
||||
#define BL_PSTATE 576
|
||||
#define BL_FPSIMD 592
|
||||
|
||||
struct bl_sigframe {
|
||||
siginfo_t info;
|
||||
ucontext_t uc;
|
||||
};
|
||||
|
||||
struct bl_kernel_sigaction {
|
||||
void (*handler)(int, siginfo_t *, void *);
|
||||
unsigned long flags;
|
||||
void *restorer;
|
||||
uint64_t mask;
|
||||
};
|
||||
|
||||
struct bl_usr2_call {
|
||||
void (*handler)(int, siginfo_t *, void *);
|
||||
uint64_t old_mask;
|
||||
};
|
||||
|
||||
_Static_assert(sizeof(struct bl_sigframe) == BL_FRAME_SIZE, "rt_sigframe size");
|
||||
_Static_assert(offsetof(struct bl_sigframe, uc.uc_mcontext.regs) == BL_REGS, "regs offset");
|
||||
_Static_assert(offsetof(struct bl_sigframe, uc.uc_mcontext.sp) == BL_SP, "sp offset");
|
||||
_Static_assert(offsetof(struct bl_sigframe, uc.uc_mcontext.pc) == BL_PC, "pc offset");
|
||||
_Static_assert(offsetof(struct bl_sigframe, uc.uc_mcontext.pstate) == BL_PSTATE, "pstate offset");
|
||||
_Static_assert(offsetof(struct bl_sigframe, uc.uc_mcontext.__reserved) == BL_FPSIMD, "reserved offset");
|
||||
_Static_assert(sizeof(struct fpsimd_context) + sizeof(struct _aarch64_ctx) <=
|
||||
sizeof(((mcontext_t *)0)->__reserved), "reserved space");
|
||||
|
||||
__attribute__((visibility("hidden"))) void bl_usr2_frame(struct bl_usr2_call *call);
|
||||
__attribute__((visibility("hidden"), used)) void bl_usr2_run(struct bl_usr2_call *call, struct bl_sigframe *frame);
|
||||
|
||||
__asm__(".text\n"
|
||||
".p2align 2\n"
|
||||
".type bl_usr2_frame, %function\n"
|
||||
"bl_usr2_frame:\n"
|
||||
" mov x16, #" BL_STR(BL_FRAME_SIZE) "\n"
|
||||
" sub sp, sp, x16\n"
|
||||
" add x17, sp, #" BL_STR(BL_REGS) "\n"
|
||||
" stp x0, x1, [x17, #0]\n"
|
||||
" stp x2, x3, [x17, #16]\n"
|
||||
" stp x4, x5, [x17, #32]\n"
|
||||
" stp x6, x7, [x17, #48]\n"
|
||||
" stp x8, x9, [x17, #64]\n"
|
||||
" stp x10, x11, [x17, #80]\n"
|
||||
" stp x12, x13, [x17, #96]\n"
|
||||
" stp x14, x15, [x17, #112]\n"
|
||||
" stp xzr, xzr, [x17, #128]\n"
|
||||
" stp x18, x19, [x17, #144]\n"
|
||||
" stp x20, x21, [x17, #160]\n"
|
||||
" stp x22, x23, [x17, #176]\n"
|
||||
" stp x24, x25, [x17, #192]\n"
|
||||
" stp x26, x27, [x17, #208]\n"
|
||||
" stp x28, x29, [x17, #224]\n"
|
||||
" str x30, [x17, #240]\n"
|
||||
" str xzr, [x17, #0]\n"
|
||||
" add x16, sp, x16\n"
|
||||
" str x16, [sp, #" BL_STR(BL_SP) "]\n"
|
||||
" adr x16, 1f\n"
|
||||
" str x16, [sp, #" BL_STR(BL_PC) "]\n"
|
||||
" mrs x16, nzcv\n"
|
||||
" str x16, [sp, #" BL_STR(BL_PSTATE) "]\n"
|
||||
" add x17, sp, #" BL_STR(BL_FPSIMD) "\n"
|
||||
" mrs x16, fpsr\n"
|
||||
" str w16, [x17, #8]\n"
|
||||
" mrs x16, fpcr\n"
|
||||
" str w16, [x17, #12]\n"
|
||||
" stp q0, q1, [x17, #16]\n"
|
||||
" stp q2, q3, [x17, #48]\n"
|
||||
" stp q4, q5, [x17, #80]\n"
|
||||
" stp q6, q7, [x17, #112]\n"
|
||||
" stp q8, q9, [x17, #144]\n"
|
||||
" stp q10, q11, [x17, #176]\n"
|
||||
" stp q12, q13, [x17, #208]\n"
|
||||
" stp q14, q15, [x17, #240]\n"
|
||||
" stp q16, q17, [x17, #272]\n"
|
||||
" stp q18, q19, [x17, #304]\n"
|
||||
" stp q20, q21, [x17, #336]\n"
|
||||
" stp q22, q23, [x17, #368]\n"
|
||||
" stp q24, q25, [x17, #400]\n"
|
||||
" stp q26, q27, [x17, #432]\n"
|
||||
" stp q28, q29, [x17, #464]\n"
|
||||
" stp q30, q31, [x17, #496]\n"
|
||||
" mov x1, sp\n"
|
||||
" bl bl_usr2_run\n"
|
||||
" mov x8, #" BL_STR(__NR_rt_sigreturn) "\n"
|
||||
" svc #0\n"
|
||||
" brk #0\n"
|
||||
"1:\n"
|
||||
" ret\n"
|
||||
".size bl_usr2_frame, .-bl_usr2_frame\n");
|
||||
|
||||
static int (*usr2_real_raise)(int);
|
||||
|
||||
static long usr2_sys(long nr, long a, long b, long c, long d) {
|
||||
register long x8 __asm__("x8") = nr;
|
||||
register long x0 __asm__("x0") = a;
|
||||
register long x1 __asm__("x1") = b;
|
||||
register long x2 __asm__("x2") = c;
|
||||
register long x3 __asm__("x3") = d;
|
||||
__asm__ volatile("svc #0" : "+r"(x0) : "r"(x8), "r"(x1), "r"(x2), "r"(x3) : "memory");
|
||||
return x0;
|
||||
}
|
||||
|
||||
static uint64_t usr2_ssbs(void) {
|
||||
uint64_t value = 0;
|
||||
if (getauxval(AT_HWCAP) & HWCAP_SSBS) __asm__ volatile("mrs %0, s3_3_c4_c2_6" : "=r"(value));
|
||||
return value & (1UL << 12);
|
||||
}
|
||||
|
||||
void bl_usr2_run(struct bl_usr2_call *call, struct bl_sigframe *frame) {
|
||||
struct fpsimd_context *fp = (struct fpsimd_context *)frame->uc.uc_mcontext.__reserved;
|
||||
struct _aarch64_ctx *end = (struct _aarch64_ctx *)(fp + 1);
|
||||
|
||||
memset(&frame->info, 0, sizeof(frame->info));
|
||||
frame->info.si_signo = SIGUSR2;
|
||||
frame->info.si_code = SI_TKILL;
|
||||
frame->info.si_pid = (pid_t)usr2_sys(__NR_getpid, 0, 0, 0, 0);
|
||||
frame->info.si_uid = (uid_t)usr2_sys(__NR_getuid, 0, 0, 0, 0);
|
||||
frame->uc.uc_flags = 0;
|
||||
frame->uc.uc_link = NULL;
|
||||
if (usr2_sys(__NR_sigaltstack, 0, (long)&frame->uc.uc_stack, 0, 0) != 0) {
|
||||
memset(&frame->uc.uc_stack, 0, sizeof(frame->uc.uc_stack));
|
||||
frame->uc.uc_stack.ss_flags = SS_DISABLE;
|
||||
}
|
||||
memset(&frame->uc.uc_sigmask, 0, sizeof(frame->uc.uc_sigmask));
|
||||
memcpy(&frame->uc.uc_sigmask, &call->old_mask, sizeof(call->old_mask));
|
||||
frame->uc.uc_mcontext.fault_address = 0;
|
||||
frame->uc.uc_mcontext.pstate |= usr2_ssbs();
|
||||
fp->head.magic = FPSIMD_MAGIC;
|
||||
fp->head.size = sizeof(*fp);
|
||||
end->magic = 0;
|
||||
end->size = 0;
|
||||
call->handler(SIGUSR2, &frame->info, &frame->uc);
|
||||
}
|
||||
|
||||
int raise(int sig) {
|
||||
int (*real)(int) = __atomic_load_n(&usr2_real_raise, __ATOMIC_ACQUIRE);
|
||||
if (!real) {
|
||||
real = (int (*)(int))dlsym(RTLD_NEXT, "raise");
|
||||
__atomic_store_n(&usr2_real_raise, real, __ATOMIC_RELEASE);
|
||||
}
|
||||
if (sig != SIGUSR2 || (getauxval(AT_HWCAP) & BL_HWCAP_GCS) || !bl_from_ntdll(__builtin_return_address(0))) {
|
||||
return real(sig);
|
||||
}
|
||||
|
||||
struct bl_kernel_sigaction action;
|
||||
if (usr2_sys(__NR_rt_sigaction, SIGUSR2, 0, (long)&action, sizeof(action.mask)) != 0) return real(sig);
|
||||
if (!(action.flags & SA_SIGINFO) || (action.flags & SA_RESETHAND) || (uintptr_t)action.handler <= 1) {
|
||||
return real(sig);
|
||||
}
|
||||
|
||||
uint64_t bit = 1ULL << (SIGUSR2 - 1);
|
||||
uint64_t block = action.mask | ((action.flags & SA_NODEFER) ? 0 : bit);
|
||||
struct bl_usr2_call call = {action.handler, 0};
|
||||
if (usr2_sys(__NR_rt_sigprocmask, SIG_BLOCK, (long)&block, (long)&call.old_mask, sizeof(block)) != 0) {
|
||||
return real(sig);
|
||||
}
|
||||
if (call.old_mask & bit) {
|
||||
usr2_sys(__NR_rt_sigprocmask, SIG_SETMASK, (long)&call.old_mask, 0, sizeof(call.old_mask));
|
||||
return real(sig);
|
||||
}
|
||||
bl_usr2_frame(&call);
|
||||
return 0;
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,113 @@
|
||||
#define _GNU_SOURCE
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <linux/fs.h>
|
||||
#include <linux/userfaultfd.h>
|
||||
#include <stdint.h>
|
||||
#include <sys/ioctl.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#define WINE_ARM64_USERFAULTFD 374
|
||||
#define PM_UFFD_WP (1ULL << 57)
|
||||
#define PM_SWAP (1ULL << 62)
|
||||
#define PM_PRESENT (1ULL << 63)
|
||||
|
||||
#if defined(PAGEMAP_SCAN) && defined(UFFD_USER_MODE_ONLY)
|
||||
static int ww_uffd = -1;
|
||||
static int scan_blocked;
|
||||
#endif
|
||||
|
||||
__attribute__((visibility("hidden"))) int bl_writewatch_syscall(long number, const long *args, long (*real)(long, ...), long *rc) {
|
||||
#if defined(__aarch64__) && defined(PAGEMAP_SCAN) && defined(UFFD_USER_MODE_ONLY)
|
||||
if (number != WINE_ARM64_USERFAULTFD || (args[0] & ~(long)(O_CLOEXEC | O_NONBLOCK | UFFD_USER_MODE_ONLY))) return 0;
|
||||
*rc = real(SYS_userfaultfd, args[0]);
|
||||
if (*rc >= 0) __atomic_store_n(&ww_uffd, (int)*rc, __ATOMIC_RELEASE);
|
||||
return 1;
|
||||
#else
|
||||
(void)number;
|
||||
(void)args;
|
||||
(void)real;
|
||||
(void)rc;
|
||||
return 0;
|
||||
#endif
|
||||
}
|
||||
|
||||
#if defined(PAGEMAP_SCAN) && defined(UFFD_USER_MODE_ONLY)
|
||||
static int protect(int uffd, uint64_t start, uint64_t end) {
|
||||
if (start == end) return 0;
|
||||
struct uffdio_writeprotect wp = { .range = { start, end - start }, .mode = UFFDIO_WRITEPROTECT_MODE_WP };
|
||||
return ioctl(uffd, UFFDIO_WRITEPROTECT, &wp);
|
||||
}
|
||||
|
||||
static long emulate_scan(int fd, int uffd, struct pm_scan_arg *a) {
|
||||
uint64_t page = (uint64_t)getpagesize();
|
||||
if (a->size < sizeof(*a) || (a->flags & ~(uint64_t)PM_SCAN_WP_MATCHING) || a->category_inverted || a->category_anyof_mask
|
||||
|| a->category_mask != PAGE_IS_WRITTEN || (a->return_mask & ~(uint64_t)PAGE_IS_WRITTEN) || a->end < a->start
|
||||
|| ((a->start | a->end) & (page - 1)) || (a->vec_len && !a->vec)) {
|
||||
errno = EINVAL;
|
||||
return -1;
|
||||
}
|
||||
struct page_region *vec = (struct page_region *)(uintptr_t)a->vec;
|
||||
uint64_t regions = 0, pages = 0, addr = a->start, wp_start = 0, wp_end = 0;
|
||||
uint64_t entries[512];
|
||||
int wp = (a->flags & PM_SCAN_WP_MATCHING) != 0;
|
||||
while (addr < a->end) {
|
||||
uint64_t want = (a->end - addr) / page;
|
||||
if (want > 512) want = 512;
|
||||
ssize_t got = pread(fd, entries, want * sizeof(entries[0]), (off_t)(addr / page * sizeof(entries[0])));
|
||||
if (got < 0) return -1;
|
||||
if (got == 0) break;
|
||||
for (uint64_t i = 0; i < (uint64_t)got / sizeof(entries[0]); i++, addr += page) {
|
||||
uint64_t e = entries[i];
|
||||
if (!(e & (PM_PRESENT | PM_SWAP)) || (e & PM_UFFD_WP)) continue;
|
||||
if (a->max_pages && pages >= a->max_pages) goto done;
|
||||
if (a->vec_len) {
|
||||
if (regions && vec[regions - 1].end == addr) {
|
||||
vec[regions - 1].end += page;
|
||||
} else {
|
||||
if (regions == a->vec_len) goto done;
|
||||
vec[regions].start = addr;
|
||||
vec[regions].end = addr + page;
|
||||
vec[regions].categories = PAGE_IS_WRITTEN & a->return_mask;
|
||||
regions++;
|
||||
}
|
||||
}
|
||||
pages++;
|
||||
if (!wp) continue;
|
||||
if (wp_end != addr) {
|
||||
if (protect(uffd, wp_start, wp_end) < 0) return -1;
|
||||
wp_start = addr;
|
||||
}
|
||||
wp_end = addr + page;
|
||||
}
|
||||
}
|
||||
done:
|
||||
if (wp && protect(uffd, wp_start, wp_end) < 0) return -1;
|
||||
a->walk_end = addr < a->end ? addr : a->end;
|
||||
return (long)regions;
|
||||
}
|
||||
#endif
|
||||
|
||||
__attribute__((visibility("hidden"))) int bl_writewatch_ioctl(int (*real)(int, unsigned long, void *), int fd, unsigned long request,
|
||||
void *arg, int *rc) {
|
||||
#if defined(PAGEMAP_SCAN) && defined(UFFD_USER_MODE_ONLY)
|
||||
if (request != PAGEMAP_SCAN) return 0;
|
||||
int uffd = __atomic_load_n(&ww_uffd, __ATOMIC_ACQUIRE);
|
||||
if (uffd < 0) return 0;
|
||||
if (!__atomic_load_n(&scan_blocked, __ATOMIC_RELAXED)) {
|
||||
*rc = real(fd, request, arg);
|
||||
if (*rc >= 0 || errno != EACCES) return 1;
|
||||
__atomic_store_n(&scan_blocked, 1, __ATOMIC_RELAXED);
|
||||
}
|
||||
*rc = (int)emulate_scan(fd, uffd, (struct pm_scan_arg *)arg);
|
||||
return 1;
|
||||
#else
|
||||
(void)real;
|
||||
(void)fd;
|
||||
(void)request;
|
||||
(void)arg;
|
||||
(void)rc;
|
||||
return 0;
|
||||
#endif
|
||||
}
|
||||
@@ -126,6 +126,25 @@ static void zr_walk(int compress) {
|
||||
zr_sys(SYS_close, maps);
|
||||
}
|
||||
|
||||
// Before it stops a session for suspend, the app waits for <ZR_CTL>.ack.<pid> to appear (the handler
|
||||
// runs here, not one a program installed over it) and then to hold a byte (the page-out finished).
|
||||
static void zr_ack(int done) {
|
||||
static const char suffix[] = ".ack.";
|
||||
char path[sizeof(ZR_CTL) + sizeof(suffix) + 20];
|
||||
char digits[20];
|
||||
size_t n = 0, d = 0;
|
||||
for (const char *p = ZR_CTL; *p; p++) path[n++] = *p;
|
||||
for (const char *p = suffix; *p; p++) path[n++] = *p;
|
||||
long pid = zr_sys(SYS_getpid);
|
||||
do digits[d++] = (char)('0' + pid % 10); while ((pid /= 10) > 0);
|
||||
while (d > 0) path[n++] = digits[--d];
|
||||
path[n] = 0;
|
||||
int fd = (int)zr_sys(SYS_openat, AT_FDCWD, path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600);
|
||||
if (fd < 0) return;
|
||||
if (done) zr_sys(SYS_write, fd, "1", 1UL);
|
||||
zr_sys(SYS_close, fd);
|
||||
}
|
||||
|
||||
static void zr_handler(int sig, siginfo_t *info, void *context) {
|
||||
(void)sig;
|
||||
(void)context;
|
||||
@@ -136,7 +155,9 @@ static void zr_handler(int sig, siginfo_t *info, void *context) {
|
||||
&& !__atomic_exchange_n(&zr_busy, 1, __ATOMIC_SEQ_CST)) {
|
||||
__atomic_store_n(&zr_pending, 0, __ATOMIC_SEQ_CST);
|
||||
int mode = zr_mode();
|
||||
if (mode == 1) zr_ack(0);
|
||||
if (mode >= 0) zr_walk(mode);
|
||||
if (mode == 1) zr_ack(1);
|
||||
__atomic_store_n(&zr_busy, 0, __ATOMIC_SEQ_CST);
|
||||
}
|
||||
errno = saved;
|
||||
@@ -148,8 +169,6 @@ static void zr_child(void) {
|
||||
}
|
||||
|
||||
__attribute__((constructor)) static void zr_init(void) {
|
||||
const char *name = program_invocation_short_name;
|
||||
if (strcmp(name, "steam") != 0 && strcmp(name, "steamwebhelper") != 0) return;
|
||||
void *libc = dlopen("libc.so.6", RTLD_LAZY | RTLD_NOLOAD);
|
||||
if (libc == NULL) return;
|
||||
zr_sys = (long (*)(long, ...))dlsym(libc, "syscall");
|
||||
|
||||
@@ -2,4 +2,4 @@
|
||||
4028f44d83b2956ba2931d32aee8cceecbd6481e2febf86a3b6bfed69ef403d5 https://github.com/Droid-Deck/DroidDeck/releases/download/msitools-0.106-r1/libgsf-1.14.60-1-aarch64.pkg.tar.xz
|
||||
3d7bd103313cb36d6cb703a5e583363e56ff255f105bcc0727916d195967976d https://github.com/Droid-Deck/DroidDeck/releases/download/msitools-0.106-r1/gcab-1.6-2-aarch64.pkg.tar.xz
|
||||
87fe375a22de1519982234ce99f909ae13c06500784baaa1e8d7a0c0be0d14ee https://github.com/Droid-Deck/DroidDeck/releases/download/msitools-0.106-r1/cabextract-1.11-3-aarch64.pkg.tar.xz
|
||||
e3bc83ac5960a4363f7ce05eb1d50b03d60d627a4a29f9b02c8e0466a5381b1f http://mirror.archlinuxarm.org/aarch64/extra/7zip-26.04-1-aarch64.pkg.tar.xz
|
||||
e3bc83ac5960a4363f7ce05eb1d50b03d60d627a4a29f9b02c8e0466a5381b1f https://github.com/Droid-Deck/DroidDeck-Components/releases/download/build-dependency-7zip-26.04-r1/7zip-26.04-1-aarch64.pkg.tar.xz
|
||||
@@ -337,34 +337,73 @@ static int to_guest(const char *h, char *g, size_t size) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int guest_text(const char *h, char *g) {
|
||||
int in = h[0] == '/' && under(h, root, rootlen);
|
||||
for (int i = 0; h[0] == '/' && !in && i < nbinds; i++) {
|
||||
int live = held(&binds[i]);
|
||||
if (live < 0) return -1;
|
||||
in = live && under(h, binds[i].host, binds[i].hlen);
|
||||
static int host_order[MAX_BINDS + 1], norder, ordered;
|
||||
|
||||
static int contains(const char *a, const char *b) {
|
||||
size_t la = strlen(a);
|
||||
return strlen(b) > la && under(b, a, la);
|
||||
}
|
||||
|
||||
static const char *side_of(int i, int host) {
|
||||
return host ? (i < 0 ? root : binds[i].host) : (i < 0 ? "/" : binds[i].guest);
|
||||
}
|
||||
|
||||
static int insort(int *list, int m, int i, int host) {
|
||||
const char *p = side_of(i, host);
|
||||
int prev = -1;
|
||||
for (int j = 0; j < m; j++) {
|
||||
const char *q = side_of(list[j], host);
|
||||
if (!strcmp(p, q) && !host) {
|
||||
list[j] = i;
|
||||
return m;
|
||||
}
|
||||
if (!strcmp(p, q) || contains(p, q)) prev = j;
|
||||
}
|
||||
if (in) return to_guest(h, g, PATH_MAX);
|
||||
memcpy(g, h, strlen(h) + 1);
|
||||
memmove(list + prev + 2, list + prev + 1, (m - prev - 1) * sizeof *list);
|
||||
list[prev + 1] = i;
|
||||
return m + 1;
|
||||
}
|
||||
|
||||
static int order_binds(void) {
|
||||
if (__atomic_load_n(&ordered, __ATOMIC_ACQUIRE)) return 0;
|
||||
for (int i = 0; i < nbinds; i++)
|
||||
if (held(&binds[i]) < 0) return -1;
|
||||
if (pthread_mutex_trylock(&bind_lock) != 0) return -1;
|
||||
if (!ordered) {
|
||||
int pending[MAX_BINDS + 1], m = 1;
|
||||
pending[0] = -1;
|
||||
for (int i = 0; i < nbinds; i++)
|
||||
if (!binds[i].dropped) m = insort(pending, m, i, 0);
|
||||
norder = 0;
|
||||
for (int j = m - 1; j >= 0; j--) norder = insort(host_order, norder, pending[j], 1);
|
||||
__atomic_store_n(&ordered, 1, __ATOMIC_RELEASE);
|
||||
}
|
||||
pthread_mutex_unlock(&bind_lock);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int host_bind(const char *h) {
|
||||
int found = -1;
|
||||
for (int i = 0; i < nbinds; i++) {
|
||||
int live = held(&binds[i]);
|
||||
if (live < 0) return -2;
|
||||
if (!live || !under(h, binds[i].host, binds[i].hlen)) continue;
|
||||
if (found < 0 || binds[i].hlen > binds[found].hlen) found = i;
|
||||
else if (binds[i].hlen == binds[found].hlen && strcmp(binds[i].guest, binds[found].guest) != 0) found = -3;
|
||||
}
|
||||
return found == -3 ? -2 : found;
|
||||
if (order_binds() < 0) return -2;
|
||||
for (int j = 0; j < norder; j++)
|
||||
if (host_order[j] >= 0 && under(h, binds[host_order[j]].host, binds[host_order[j]].hlen)) return host_order[j];
|
||||
return -1;
|
||||
}
|
||||
|
||||
static int guest_text(const char *h, char *g) {
|
||||
if (h[0] == '/' && under(h, root, rootlen)) return to_guest(h, g, PATH_MAX);
|
||||
int i = h[0] == '/' ? host_bind(h) : -1;
|
||||
if (i == -2) return -1;
|
||||
if (i >= 0)
|
||||
return snprintf(g, PATH_MAX, "%s%s", binds[i].guest, h + binds[i].hlen) >= PATH_MAX || reserved(g) ? -1 : 0;
|
||||
memcpy(g, h, strlen(h) + 1);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static long detranslated(char *text, const char *at) {
|
||||
if (text[0] != '/') return 0;
|
||||
if (!under(at, root, rootlen) && !under(text, root, rootlen)) {
|
||||
int own = host_bind(at), to = host_bind(text);
|
||||
if (to == -1) return 0;
|
||||
if (own == -2 || to == -2) return FP_SLOW;
|
||||
if (own >= 0 && to >= 0 && strcmp(binds[own].host, binds[to].host) == 0) {
|
||||
const struct bind *bd = &binds[to];
|
||||
@@ -635,8 +674,9 @@ static long resolve_in(const char *base, const char *path, int follow, struct re
|
||||
char norm[PATH_MAX];
|
||||
size_t o = 0;
|
||||
int dotdot = 0;
|
||||
size_t plen = strlen(path);
|
||||
int trailing = plen > 1 && path[plen - 1] == '/';
|
||||
size_t plen = strlen(path), end = plen;
|
||||
while (end > 1 && path[end - 1] == '/') end--;
|
||||
int trailing = (plen > 1 && path[plen - 1] == '/') || (end > 0 && path[end - 1] == '.' && (end == 1 || path[end - 2] == '/'));
|
||||
for (int part = base ? 0 : 1; part < 2; part++) {
|
||||
for (const char *c = part ? path : base; *c;) {
|
||||
while (*c == '/') c++;
|
||||
|
||||
@@ -4,7 +4,7 @@ from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
from check_authorship import BOT, COAUTHOR, check_revision
|
||||
from check_authorship import COAUTHOR, check_revision, is_bot
|
||||
|
||||
|
||||
def main():
|
||||
@@ -23,13 +23,13 @@ def main():
|
||||
return 1
|
||||
else:
|
||||
identity = subprocess.check_output(["git", "var", "GIT_AUTHOR_IDENT"], text=True)
|
||||
if BOT.search(identity):
|
||||
if is_bot(identity):
|
||||
print("Bot commit author is forbidden: " + identity.strip(), file=sys.stderr)
|
||||
return 1
|
||||
message = Path(args[0])
|
||||
original = message.read_text(encoding="utf-8")
|
||||
cleaned = "".join(line for line in original.splitlines(keepends=True)
|
||||
if not (COAUTHOR.match(line) and BOT.search(line)))
|
||||
if not (COAUTHOR.match(line) and is_bot(line)))
|
||||
if cleaned != original:
|
||||
message.write_text(cleaned, encoding="utf-8")
|
||||
print("Removed bot co-author trailers; human credits preserved.", file=sys.stderr)
|
||||
|
||||
@@ -6,15 +6,34 @@ import re
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
BOT = re.compile(
|
||||
r"Claude|Anthropic|OpenAI|ChatGPT|GPT|Copilot|Cursor|Gemini|Codex|Devin|"
|
||||
r"Windsurf|Codeium|Amazon Q|Tabnine|Cody|\[bot\]|github-actions|"
|
||||
r"dependabot|renovate(?:\[bot\])?",
|
||||
PRODUCT = re.compile(
|
||||
r"(?<![a-z0-9])(?:Anthropic|OpenAI|ChatGPT|GPT(?:-?\d[\w.]*)?|Copilot|Codex|Codeium|Windsurf|"
|
||||
r"Amazon Q|Tabnine|github-actions|dependabot|renovate)(?![a-z0-9])|\[bot\]",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
# These are also people's names, so they only count alone or followed by a product word.
|
||||
ASSISTANT = r"(?:Claude|Cursor|Devin|Cody|Gemini)"
|
||||
ASSISTANT_ALONE = re.compile(ASSISTANT, re.IGNORECASE)
|
||||
ASSISTANT_PRODUCT = re.compile(
|
||||
ASSISTANT + r"[\s_-]+(?:Code|Opus|Sonnet|Haiku|Fable|Instant|AI|Agent|Bot|Assistant|CLI|Pro|Flash|Ultra|\d)(?![a-z])",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
BOT_DOMAIN = re.compile(
|
||||
r"@(?:[\w-]+\.)*(?:anthropic\.com|openai\.com|cursor\.(?:com|sh)|cognition\.ai|sourcegraph\.com|"
|
||||
r"codeium\.com|tabnine\.com)$",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
COAUTHOR = re.compile(r"^\s*Co-authored-by\s*:", re.IGNORECASE)
|
||||
|
||||
|
||||
def is_bot(identity):
|
||||
name, _, rest = identity.partition("<")
|
||||
email = rest.partition(">")[0].strip()
|
||||
name = COAUTHOR.sub("", name).strip()
|
||||
return bool(PRODUCT.search(name) or PRODUCT.search(email) or BOT_DOMAIN.search(email)
|
||||
or ASSISTANT_ALONE.fullmatch(name) or ASSISTANT_PRODUCT.search(name))
|
||||
|
||||
|
||||
def commit_violations(commit, raw):
|
||||
header, separator, message = raw.partition(b"\n\n")
|
||||
if not separator:
|
||||
@@ -24,10 +43,10 @@ def commit_violations(commit, raw):
|
||||
return [f"{commit}: expected one author"]
|
||||
identity = authors[0].decode("utf-8", errors="replace")
|
||||
errors = []
|
||||
if BOT.search(identity):
|
||||
if is_bot(identity):
|
||||
errors.append(f"{commit}: bot author: {identity}")
|
||||
for line in message.decode("utf-8", errors="replace").splitlines():
|
||||
if COAUTHOR.match(line) and BOT.search(line):
|
||||
if COAUTHOR.match(line) and is_bot(line):
|
||||
errors.append(f"{commit}: bot co-author: {line.strip()}")
|
||||
return errors
|
||||
|
||||
@@ -36,11 +55,11 @@ def event_violations(event):
|
||||
pr = event.get("pull_request", {})
|
||||
user = pr.get("user", {})
|
||||
errors = []
|
||||
if user.get("type") == "Bot" or BOT.search(user.get("login", "")):
|
||||
if user.get("type") == "Bot" or is_bot(user.get("login", "")):
|
||||
errors.append("pull request: bot authorship is forbidden")
|
||||
for field in ("title", "body"):
|
||||
for line in (pr.get(field) or "").splitlines():
|
||||
if COAUTHOR.match(line) and BOT.search(line):
|
||||
if COAUTHOR.match(line) and is_bot(line):
|
||||
errors.append(f"pull request {field}: bot co-author trailer")
|
||||
return errors
|
||||
|
||||
|
||||
@@ -40,6 +40,27 @@ class AuthorshipTest(unittest.TestCase):
|
||||
def test_bot_pr_author_is_rejected(self):
|
||||
self.assertTrue(check.event_violations({"pull_request": {"user": {"login": "service", "type": "Bot"}}}))
|
||||
|
||||
def test_people_named_like_assistants_are_not_bots(self):
|
||||
for author in ("Claudemirovsky <63046606+Claudemirovsky@users.noreply.github.com>",
|
||||
"Claude Monet <claude@example.com>", "Devin Smith <devin@example.com>",
|
||||
"Cody Allen <cody@example.com>", "Gemini Patel <gp@example.com>"):
|
||||
with self.subTest(author=author):
|
||||
self.assertEqual([], check.commit_violations("abc", self.commit(author=author)))
|
||||
self.assertEqual([], check.event_violations({"pull_request": {"user": {"login": "Claudemirovsky", "type": "User"}}}))
|
||||
|
||||
def test_assistant_identities_are_still_bots(self):
|
||||
for author in ("Claude Opus 5.5 <noreply@anthropic.com>", "Claude Code <cc@example.com>",
|
||||
"Cursor Agent <cursoragent@cursor.com>",
|
||||
"Devin AI <devin-ai-integration[bot]@users.noreply.github.com>",
|
||||
"Gemini <gemini@example.com>", "GPT-5 <a@example.com>"):
|
||||
with self.subTest(author=author):
|
||||
self.assertTrue(check.commit_violations("abc", self.commit(author=author)))
|
||||
for login in ("chatgpt-codex-connector", "Copilot", "claude"):
|
||||
with self.subTest(login=login):
|
||||
self.assertTrue(check.event_violations({"pull_request": {"user": {"login": login, "type": "User"}}}))
|
||||
message = "Fix\n\nCo-authored-by: Claude Opus 5.5 <noreply@anthropic.com>\n"
|
||||
self.assertEqual(1, len(check.commit_violations("abc", self.commit(message=message))))
|
||||
|
||||
def test_missing_author_fails_closed(self):
|
||||
self.assertTrue(check.commit_violations("abc", b"tree 000\n\nmessage\n"))
|
||||
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
FASTPATH = Path(__file__).resolve().parents[1] / "proot/fastpath/fastpath.c"
|
||||
|
||||
PROGRAM = r"""
|
||||
#include "FASTPATH"
|
||||
|
||||
static long host_sys(long nr, long a, long b, long c, long d, long e, long f) {
|
||||
long r = syscall(nr, a, b, c, d, e, f);
|
||||
return r < 0 ? -errno : r;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
static char hosts[MAX_BINDS][PATH_MAX], guests[MAX_BINDS][512];
|
||||
fp_sys = host_sys;
|
||||
snprintf(root, sizeof root, "%s", argv[1]);
|
||||
rootlen = strlen(root);
|
||||
int i = 2;
|
||||
for (; i + 1 < argc && strcmp(argv[i], "--"); i += 2) {
|
||||
struct bind *bd = &binds[nbinds];
|
||||
bd->host = hosts[nbinds];
|
||||
bd->guest = guests[nbinds];
|
||||
snprintf(bd->host, PATH_MAX, "%s", argv[i]);
|
||||
snprintf(bd->guest, sizeof guests[0], "%s", argv[i + 1]);
|
||||
bd->hlen = strlen(bd->host);
|
||||
bd->glen = strlen(bd->guest);
|
||||
nbinds++;
|
||||
}
|
||||
pthread_once(&init_once, fp_init);
|
||||
fp_on = 1;
|
||||
for (i++; i < argc; i++) {
|
||||
char text[PATH_MAX];
|
||||
if (!strcmp(argv[i], "name")) {
|
||||
if (guest_text(argv[++i], text) < 0) strcpy(text, "SLOW");
|
||||
puts(text);
|
||||
} else if (!strcmp(argv[i], "link")) {
|
||||
snprintf(text, sizeof text, "%s", argv[i + 2]);
|
||||
if (detranslated(text, argv[i + 1]) == FP_SLOW) strcpy(text, "SLOW");
|
||||
i += 2;
|
||||
puts(text);
|
||||
} else if (!strcmp(argv[i], "lstat")) {
|
||||
struct stat st;
|
||||
long r = fstatat(AT_FDCWD, argv[++i], &st, AT_SYMLINK_NOFOLLOW);
|
||||
puts(r < 0 ? "error" : S_ISDIR(st.st_mode) ? "dir" : S_ISLNK(st.st_mode) ? "link" : "other");
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
class FastPathBindNamesTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
if shutil.which("gcc") is None:
|
||||
raise unittest.SkipTest("gcc is not available")
|
||||
cls.work = Path(tempfile.mkdtemp())
|
||||
source = cls.work / "names.c"
|
||||
source.write_text(PROGRAM.replace("FASTPATH", str(FASTPATH)))
|
||||
cls.program = cls.work / "names"
|
||||
subprocess.run(["gcc", "-O1", "-w", "-pthread", "-o", str(cls.program), str(source), "-ldl"], check=True)
|
||||
t = cls.work / "tree"
|
||||
for d in ["root/etc", "root/mnt", "root/opt", "root/d/real", "lib/common/game", "fonts", "a", "b"]:
|
||||
(t / d).mkdir(parents=True, exist_ok=True)
|
||||
for f in ["root/etc/x", "lib/f", "lib/common/game/f", "fonts/f", "a/f", "b/f"]:
|
||||
(t / f).touch()
|
||||
os.symlink(t / "lib/f", t / "lib/l2")
|
||||
os.symlink(t / "lib/common", t / "lib/l")
|
||||
os.symlink("real", t / "root/d/link")
|
||||
cls.tree = t
|
||||
cls.binds = [
|
||||
(t / "lib", "/mnt/droiddeck-sd"),
|
||||
(t / "lib", "/mnt/bannerlator-sd"),
|
||||
(t / "lib", "/mnt/DroidDeck-SD"),
|
||||
(t / "lib/common", "/opt/common"),
|
||||
(t / "fonts", "/usr/share/fonts/android"),
|
||||
(t / "a", "/opt/g"),
|
||||
(t / "b", "/opt/g"),
|
||||
(t / "fonts", "/mnt/x"),
|
||||
]
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
shutil.rmtree(cls.work, ignore_errors=True)
|
||||
|
||||
def ask(self, *queries):
|
||||
argv = [str(self.program), str(self.tree / "root")]
|
||||
for host, guest in self.binds:
|
||||
argv += [str(host), guest]
|
||||
argv.append("--")
|
||||
for q in queries:
|
||||
argv += [str(x) for x in q]
|
||||
out = subprocess.run(argv, capture_output=True, text=True, timeout=20, check=True).stdout
|
||||
return out.splitlines()
|
||||
|
||||
def test_a_host_file_takes_the_name_proot_gives_it(self):
|
||||
t = self.tree
|
||||
self.assertEqual(self.ask(
|
||||
("name", t / "lib/f"),
|
||||
("name", t / "lib/common/game/f"),
|
||||
("name", t / "fonts/f"),
|
||||
("name", t / "b/f"),
|
||||
("name", t / "a/f"),
|
||||
("name", t / "root/etc/x"),
|
||||
), [
|
||||
"/mnt/droiddeck-sd/f",
|
||||
"/opt/common/game/f",
|
||||
"/usr/share/fonts/android/f",
|
||||
"/opt/g/f",
|
||||
str(t / "a/f"),
|
||||
"/etc/x",
|
||||
])
|
||||
|
||||
def test_a_link_inside_a_library_reads_back_like_proot(self):
|
||||
t = self.tree
|
||||
self.assertEqual(self.ask(
|
||||
("link", t / "lib/l2", t / "lib/f"),
|
||||
("link", t / "lib/l", t / "lib/common"),
|
||||
), [
|
||||
"/mnt/droiddeck-sd/f",
|
||||
str(t / "lib/common"),
|
||||
])
|
||||
|
||||
def test_a_final_dot_follows_the_link(self):
|
||||
self.assertEqual(self.ask(
|
||||
("lstat", "/d/link"),
|
||||
("lstat", "/d/link/."),
|
||||
("lstat", "/d/link/./"),
|
||||
("lstat", "/d/link/"),
|
||||
), ["link", "dir", "dir", "dir"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -319,7 +319,7 @@ class FsyncPreloadTest(unittest.TestCase):
|
||||
source = base / "fsync-test.c"
|
||||
source.write_text(PROGRAM)
|
||||
subprocess.run(["cc", "-O2", "-Wall", "-fPIC", "-shared", "-pthread", "-o", str(cls.lib),
|
||||
str(PRELOAD / "fsync.c"), str(PRELOAD / "robust.c"), str(PRELOAD / "noexec.c"), "-ldl"], check=True)
|
||||
str(PRELOAD / "fsync.c"), str(PRELOAD / "robust.c"), str(PRELOAD / "noexec.c"), str(PRELOAD / "writewatch.c"), "-ldl"], check=True)
|
||||
subprocess.run(["cc", "-O2", "-Wall", "-pthread", "-o", str(cls.exe), str(source)], check=True)
|
||||
|
||||
@classmethod
|
||||
|
||||
@@ -43,7 +43,7 @@ class NoexecPreloadTest(unittest.TestCase):
|
||||
cls.tmp = Path(tempfile.mkdtemp())
|
||||
cls.lib = cls.tmp / "libnoexec.so"
|
||||
subprocess.run(["cc", "-O2", "-Wall", "-Werror", "-fPIC", "-shared", "-pthread", "-DNOEXEC_TEST", "-o", str(cls.lib),
|
||||
str(PRELOAD / "noexec.c"), str(PRELOAD / "fsync.c"), str(PRELOAD / "robust.c"), "-ldl"], check=True)
|
||||
str(PRELOAD / "noexec.c"), str(PRELOAD / "fsync.c"), str(PRELOAD / "robust.c"), str(PRELOAD / "writewatch.c"), "-ldl"], check=True)
|
||||
source = cls.tmp / "program.c"
|
||||
source.write_text(PROGRAM)
|
||||
for name in ("FEX", "game"):
|
||||
|
||||
@@ -230,7 +230,7 @@ class Openat2PreloadTest(unittest.TestCase):
|
||||
cls.tmp = Path(tempfile.mkdtemp())
|
||||
cls.lib = cls.tmp / "libopenat2.so"
|
||||
subprocess.run(["cc", "-O2", "-Wall", "-Werror", "-fPIC", "-shared", "-pthread", "-o", str(cls.lib),
|
||||
str(PRELOAD / "robust.c"), str(PRELOAD / "fsync.c"), str(PRELOAD / "noexec.c"), "-ldl"], check=True)
|
||||
str(PRELOAD / "robust.c"), str(PRELOAD / "fsync.c"), str(PRELOAD / "noexec.c"), str(PRELOAD / "writewatch.c"), "-ldl"], check=True)
|
||||
source = cls.tmp / "openat2.c"
|
||||
source.write_text(PROGRAM)
|
||||
subprocess.run(["cc", "-O2", "-Wall", "-Werror", "-o", str(cls.tmp / "openat2"), str(source), "-ldl"], check=True)
|
||||
|
||||
@@ -74,6 +74,36 @@ class PipeWireHelperTest(unittest.TestCase):
|
||||
self.assertIn('did not open', result.stderr)
|
||||
self.assertFalse((self.runtime / 'droiddeck-pipewire/pids').exists())
|
||||
|
||||
def test_clients_get_full_access_without_the_flatpak_check(self):
|
||||
self.pack('python3 -c "import socket,sys; s=socket.socket(socket.AF_UNIX); s.bind(sys.argv[1]); '
|
||||
'import time; time.sleep(30)" "$XDG_RUNTIME_DIR/pipewire-0"')
|
||||
for _ in range(2):
|
||||
result = self.run_helper('start')
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
daemon = (self.dir / 'share/pipewire/pipewire.conf.d/droiddeck-access.conf').read_text()
|
||||
self.assertIn('module.access = false', daemon)
|
||||
self.assertIn('name = libpipewire-module-access', daemon)
|
||||
self.assertIn('access.socket = { pipewire-0 = "unrestricted", pipewire-0-manager = "unrestricted" }',
|
||||
daemon)
|
||||
self.assertNotIn('access.legacy', daemon)
|
||||
manager = (self.dir / 'share/wireplumber/wireplumber.conf.d/droiddeck-access.conf').read_text()
|
||||
self.assertIn('matches = [ { pipewire.access = "unrestricted" } ]', manager)
|
||||
self.assertIn('default_permissions = "all"', manager)
|
||||
|
||||
def test_start_fails_cleanly_when_the_access_settings_cannot_be_written(self):
|
||||
self.pack('exec sleep 30')
|
||||
self.run_helper('start')
|
||||
self.run_helper('stop')
|
||||
conf = self.dir / 'share/pipewire/pipewire.conf.d'
|
||||
for child in conf.iterdir():
|
||||
child.unlink()
|
||||
conf.rmdir()
|
||||
conf.write_text('')
|
||||
result = self.run_helper('start')
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn('could not write the access settings', result.stderr)
|
||||
self.assertFalse((self.runtime / 'droiddeck-pipewire/pids').exists())
|
||||
|
||||
def test_unchanged_bundle_is_not_unpacked_again(self):
|
||||
self.pack('exec sleep 30')
|
||||
self.run_helper('start')
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload"
|
||||
|
||||
NTDLL = r"""
|
||||
#define _GNU_SOURCE
|
||||
#include <fcntl.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
|
||||
__attribute__((noinline)) int ntdll_open(const char *path) {
|
||||
int fd = open(path, O_RDONLY | O_CLOEXEC);
|
||||
__asm__ volatile("" ::: "memory");
|
||||
return fd;
|
||||
}
|
||||
|
||||
__attribute__((noinline)) int ntdll_openat(const char *path) {
|
||||
int fd = openat(AT_FDCWD, path, O_RDONLY | O_CLOEXEC);
|
||||
__asm__ volatile("" ::: "memory");
|
||||
return fd;
|
||||
}
|
||||
|
||||
__attribute__((noinline)) FILE *ntdll_fopen(const char *path) {
|
||||
FILE *f = fopen(path, "r");
|
||||
__asm__ volatile("" ::: "memory");
|
||||
return f;
|
||||
}
|
||||
"""
|
||||
|
||||
PROGRAM = r"""
|
||||
#define _GNU_SOURCE
|
||||
#include <fcntl.h>
|
||||
#include <signal.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/ptrace.h>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
|
||||
int ntdll_open(const char *path);
|
||||
int ntdll_openat(const char *path);
|
||||
FILE *ntdll_fopen(const char *path);
|
||||
|
||||
static void report(const char *name, int fd) {
|
||||
char link[64], target[256] = "", text[16384], *field;
|
||||
ssize_t n;
|
||||
long tracer = -1;
|
||||
if (fd < 0) {
|
||||
printf("%s failed\n", name);
|
||||
return;
|
||||
}
|
||||
snprintf(link, sizeof(link), "/proc/self/fd/%d", fd);
|
||||
n = readlink(link, target, sizeof(target) - 1);
|
||||
target[n > 0 ? n : 0] = '\0';
|
||||
n = pread(fd, text, sizeof(text) - 1, 0);
|
||||
text[n > 0 ? n : 0] = '\0';
|
||||
if ((field = strstr(text, "\nTracerPid:\t")) != NULL) tracer = strtol(field + 12, NULL, 10);
|
||||
const char *kind = strncmp(target, "/proc/", 6) == 0 ? "proc"
|
||||
: strncmp(target, "/memfd:", 7) == 0 ? "memfd"
|
||||
: strncmp(target, "/tmp/.droiddeck-status-", 23) == 0 ? "copy" : target;
|
||||
printf("%s kind=%s tracer=%s rdonly=%d vm=%d\n", name, kind, tracer == 0 ? "hidden" : tracer > 0 ? "shown" : "missing",
|
||||
(fcntl(fd, F_GETFL) & O_ACCMODE) == O_RDONLY, strstr(text, "\nVmRSS:") != NULL);
|
||||
close(fd);
|
||||
}
|
||||
|
||||
static void report_stream(const char *name, FILE *f) {
|
||||
if (f == NULL) {
|
||||
printf("%s failed\n", name);
|
||||
return;
|
||||
}
|
||||
report(name, dup(fileno(f)));
|
||||
fclose(f);
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
int ready[2];
|
||||
if (pipe(ready) != 0) return 1;
|
||||
pid_t child = fork();
|
||||
if (child == 0) {
|
||||
char ok = ptrace(PTRACE_TRACEME, 0, NULL, NULL) == 0;
|
||||
if (write(ready[1], &ok, 1) != 1) _exit(1);
|
||||
for (;;) pause();
|
||||
}
|
||||
char ok = 0;
|
||||
if (read(ready[0], &ok, 1) != 1 || !ok) {
|
||||
kill(child, SIGKILL);
|
||||
waitpid(child, NULL, 0);
|
||||
puts("no ptrace");
|
||||
return 0;
|
||||
}
|
||||
char other[64], self[64];
|
||||
snprintf(other, sizeof(other), "/proc/%d/status", (int)child);
|
||||
snprintf(self, sizeof(self), "/proc/%d/status", (int)getpid());
|
||||
report("main_other_open", open(other, O_RDONLY | O_CLOEXEC));
|
||||
report_stream("main_other_fopen", fopen(other, "r"));
|
||||
report("main_self_open", open("/proc/self/status", O_RDONLY | O_CLOEXEC));
|
||||
report("ntdll_other_open", ntdll_open(other));
|
||||
report("ntdll_other_openat", ntdll_openat(other));
|
||||
report_stream("ntdll_other_fopen", ntdll_fopen(other));
|
||||
report_stream("ntdll_self_fopen", ntdll_fopen(self));
|
||||
kill(child, SIGKILL);
|
||||
waitpid(child, NULL, 0);
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
class TracerPreloadTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
if not shutil.which("cc"):
|
||||
raise unittest.SkipTest("no compiler")
|
||||
cls.tmp = tempfile.TemporaryDirectory()
|
||||
tmp = Path(cls.tmp.name)
|
||||
(tmp / "ntdll.c").write_text(NTDLL)
|
||||
(tmp / "prog.c").write_text(PROGRAM)
|
||||
sources = sorted(str(p) for p in PRELOAD.glob("*.c"))
|
||||
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-Wall", "-pthread", "-o", str(tmp / "libblsession.so"), *sources, "-ldl"],
|
||||
check=True)
|
||||
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-o", str(tmp / "ntdll.so"), str(tmp / "ntdll.c")], check=True)
|
||||
subprocess.run(["cc", "-O1", "-o", str(tmp / "prog"), str(tmp / "prog.c"), str(tmp / "ntdll.so"), "-Wl,-rpath," + str(tmp)],
|
||||
check=True)
|
||||
env = dict(os.environ, LD_PRELOAD=str(tmp / "libblsession.so"))
|
||||
out = subprocess.run([str(tmp / "prog")], env=env, capture_output=True, text=True, timeout=60)
|
||||
if out.returncode != 0:
|
||||
raise AssertionError(out.stdout + out.stderr)
|
||||
if "no ptrace" in out.stdout:
|
||||
raise unittest.SkipTest("ptrace not allowed")
|
||||
cls.lines = dict(line.split(" ", 1) for line in out.stdout.splitlines())
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.tmp.cleanup()
|
||||
|
||||
def test_other_programs_still_see_no_tracer(self):
|
||||
self.assertEqual(self.lines["main_other_open"], "kind=copy tracer=hidden rdonly=1 vm=1")
|
||||
self.assertEqual(self.lines["main_other_fopen"], "kind=copy tracer=hidden rdonly=1 vm=1")
|
||||
self.assertEqual(self.lines["main_self_open"], "kind=memfd tracer=hidden rdonly=0 vm=1")
|
||||
|
||||
def test_wine_reads_the_real_status_file(self):
|
||||
for name in ("ntdll_other_open", "ntdll_other_openat", "ntdll_other_fopen"):
|
||||
self.assertEqual(self.lines[name], "kind=proc tracer=shown rdonly=1 vm=1", name)
|
||||
self.assertEqual(self.lines["ntdll_self_fopen"], "kind=proc tracer=hidden rdonly=1 vm=1")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,301 @@
|
||||
import ctypes
|
||||
import os
|
||||
from pathlib import Path
|
||||
import platform
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload"
|
||||
|
||||
NTDLL = r"""
|
||||
#include <signal.h>
|
||||
__attribute__((noinline)) void syscall_dispatcher_return_slowpath(void) { raise(SIGUSR2); }
|
||||
void slowpath(void) {
|
||||
syscall_dispatcher_return_slowpath();
|
||||
__asm__ volatile("" ::: "memory");
|
||||
}
|
||||
void slowpath_other(int sig) {
|
||||
raise(sig);
|
||||
__asm__ volatile("" ::: "memory");
|
||||
}
|
||||
"""
|
||||
|
||||
PROGRAM = r"""
|
||||
#define _GNU_SOURCE
|
||||
#include <asm/sigcontext.h>
|
||||
#include <pthread.h>
|
||||
#include <setjmp.h>
|
||||
#include <signal.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <ucontext.h>
|
||||
#include <unistd.h>
|
||||
|
||||
void slowpath(void);
|
||||
void slowpath_other(int sig);
|
||||
|
||||
static char altstack[65536];
|
||||
static char landing_stack[65536] __attribute__((aligned(16)));
|
||||
static volatile int mode;
|
||||
static int calls;
|
||||
static volatile int on_alt, usr2_blocked, usr1_blocked, code_ok, stack_ok;
|
||||
static volatile long handler_sp;
|
||||
static jmp_buf back;
|
||||
static uint64_t saved[31];
|
||||
static unsigned __int128 saved_v[32];
|
||||
static uint32_t saved_fpsr;
|
||||
|
||||
void landing(void);
|
||||
__asm__(".text\n.globl landing\n.type landing, %function\nlanding:\n"
|
||||
" sub sp, sp, #784\n"
|
||||
" stp x0, x1, [sp, #0]\n stp x2, x3, [sp, #16]\n stp x4, x5, [sp, #32]\n stp x6, x7, [sp, #48]\n"
|
||||
" stp x8, x9, [sp, #64]\n stp x10, x11, [sp, #80]\n stp x12, x13, [sp, #96]\n stp x14, x15, [sp, #112]\n"
|
||||
" stp x16, x17, [sp, #128]\n stp x18, x19, [sp, #144]\n stp x20, x21, [sp, #160]\n stp x22, x23, [sp, #176]\n"
|
||||
" stp x24, x25, [sp, #192]\n stp x26, x27, [sp, #208]\n stp x28, x29, [sp, #224]\n str x30, [sp, #240]\n"
|
||||
" add x9, sp, #256\n"
|
||||
" stp q0, q1, [x9, #0]\n stp q2, q3, [x9, #32]\n stp q4, q5, [x9, #64]\n stp q6, q7, [x9, #96]\n"
|
||||
" stp q8, q9, [x9, #128]\n stp q10, q11, [x9, #160]\n stp q12, q13, [x9, #192]\n stp q14, q15, [x9, #224]\n"
|
||||
" stp q16, q17, [x9, #256]\n stp q18, q19, [x9, #288]\n stp q20, q21, [x9, #320]\n stp q22, q23, [x9, #352]\n"
|
||||
" stp q24, q25, [x9, #384]\n stp q26, q27, [x9, #416]\n stp q28, q29, [x9, #448]\n stp q30, q31, [x9, #480]\n"
|
||||
" mrs x10, fpsr\n str w10, [sp, #768]\n"
|
||||
" mov x0, sp\n bl landed\n brk #0\n");
|
||||
|
||||
void landed(uint64_t *regs) {
|
||||
memcpy(saved, regs, sizeof(saved));
|
||||
memcpy(saved_v, regs + 32, sizeof(saved_v));
|
||||
saved_fpsr = *(uint32_t *)(regs + 96);
|
||||
longjmp(back, 1);
|
||||
}
|
||||
|
||||
static struct fpsimd_context *fpsimd_of(ucontext_t *uc) {
|
||||
struct _aarch64_ctx *c = (struct _aarch64_ctx *)uc->uc_mcontext.__reserved;
|
||||
while (c->magic) {
|
||||
if (c->magic == FPSIMD_MAGIC) return (struct fpsimd_context *)c;
|
||||
c = (struct _aarch64_ctx *)((char *)c + c->size);
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static void handler(int sig, siginfo_t *info, void *ctx) {
|
||||
ucontext_t *uc = ctx;
|
||||
sigset_t now;
|
||||
long sp = (long)&now;
|
||||
__atomic_add_fetch(&calls, 1, __ATOMIC_RELAXED);
|
||||
handler_sp = sp;
|
||||
on_alt = sp >= (long)altstack && sp < (long)altstack + (long)sizeof(altstack);
|
||||
pthread_sigmask(SIG_BLOCK, NULL, &now);
|
||||
usr2_blocked = sigismember(&now, SIGUSR2);
|
||||
usr1_blocked = sigismember(&now, SIGUSR1);
|
||||
code_ok = sig == SIGUSR2 && info->si_signo == SIGUSR2 && info->si_code == SI_TKILL && info->si_pid == getpid();
|
||||
stack_ok = uc->uc_stack.ss_sp == altstack && uc->uc_stack.ss_size == sizeof(altstack) && !(uc->uc_stack.ss_flags & SS_DISABLE);
|
||||
if (mode == 1) {
|
||||
struct fpsimd_context *fp = fpsimd_of(uc);
|
||||
for (int i = 0; i <= 28; i++) uc->uc_mcontext.regs[i] = 0x1000 + i;
|
||||
uc->uc_mcontext.regs[29] = 0x2900;
|
||||
uc->uc_mcontext.regs[30] = 0x3000;
|
||||
uc->uc_mcontext.sp = (uint64_t)(landing_stack + sizeof(landing_stack));
|
||||
uc->uc_mcontext.pc = (uint64_t)landing;
|
||||
uc->uc_mcontext.pstate = 0x60000000;
|
||||
for (int i = 0; i < 32; i++) fp->vregs[i] = ((unsigned __int128)(0x7700 + i) << 64) | (0x5500 + i);
|
||||
fp->fpsr = 0x8;
|
||||
}
|
||||
}
|
||||
|
||||
static void usr1(int sig, siginfo_t *info, void *ctx) {
|
||||
(void)sig;
|
||||
(void)info;
|
||||
(void)ctx;
|
||||
}
|
||||
|
||||
uint64_t kept_x[10];
|
||||
double kept_d[8];
|
||||
|
||||
static int keep_callee_saved(void) {
|
||||
uint64_t *out = kept_x;
|
||||
double *d = kept_d;
|
||||
__asm__ volatile(
|
||||
"mov x19, #19\n mov x20, #20\n mov x21, #21\n mov x22, #22\n mov x23, #23\n"
|
||||
"mov x24, #24\n mov x25, #25\n mov x26, #26\n mov x27, #27\n mov x28, #28\n"
|
||||
"fmov d8, #1.0\n fmov d9, #2.0\n fmov d10, #3.0\n fmov d11, #4.0\n"
|
||||
"fmov d12, #5.0\n fmov d13, #6.0\n fmov d14, #7.0\n fmov d15, #8.0\n"
|
||||
"bl slowpath\n"
|
||||
"adrp x0, kept_x\n add x0, x0, :lo12:kept_x\n"
|
||||
"stp x19, x20, [x0, #0]\n stp x21, x22, [x0, #16]\n stp x23, x24, [x0, #32]\n"
|
||||
"stp x25, x26, [x0, #48]\n stp x27, x28, [x0, #64]\n"
|
||||
"adrp x0, kept_d\n add x0, x0, :lo12:kept_d\n"
|
||||
"stp d8, d9, [x0, #0]\n stp d10, d11, [x0, #16]\n stp d12, d13, [x0, #32]\n stp d14, d15, [x0, #48]\n"
|
||||
:
|
||||
:
|
||||
: "x0", "x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x9", "x10", "x11", "x12", "x13", "x14", "x15",
|
||||
"x16", "x17", "x19", "x20", "x21", "x22", "x23", "x24", "x25", "x26", "x27", "x28", "x30",
|
||||
"v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15",
|
||||
"v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", "v28", "v29", "v30",
|
||||
"v31", "memory", "cc");
|
||||
for (int i = 0; i < 10; i++)
|
||||
if (out[i] != (uint64_t)(19 + i)) return 0;
|
||||
for (int i = 0; i < 8; i++)
|
||||
if (d[i] != (double)(i + 1)) return 0;
|
||||
return 1;
|
||||
}
|
||||
|
||||
static void *stress(void *arg) {
|
||||
(void)arg;
|
||||
for (int i = 0; i < 2000; i++) slowpath();
|
||||
return NULL;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
stack_t ss = {.ss_sp = altstack, .ss_size = sizeof(altstack), .ss_flags = 0};
|
||||
struct sigaction sa;
|
||||
sigset_t mask, now;
|
||||
sigaltstack(&ss, NULL);
|
||||
memset(&sa, 0, sizeof(sa));
|
||||
sa.sa_sigaction = handler;
|
||||
sa.sa_flags = SA_SIGINFO | SA_ONSTACK | SA_RESTART;
|
||||
sigemptyset(&sa.sa_mask);
|
||||
sigaddset(&sa.sa_mask, SIGUSR1);
|
||||
sigaction(SIGUSR2, &sa, NULL);
|
||||
sa.sa_sigaction = usr1;
|
||||
sigemptyset(&sa.sa_mask);
|
||||
sigaction(SIGUSR1, &sa, NULL);
|
||||
|
||||
if (argc > 1 && strcmp(argv[1], "bench") == 0) {
|
||||
int n = argc > 2 ? atoi(argv[2]) : 20000;
|
||||
struct timespec a, b;
|
||||
clock_gettime(CLOCK_MONOTONIC, &a);
|
||||
for (int i = 0; i < n; i++) slowpath();
|
||||
clock_gettime(CLOCK_MONOTONIC, &b);
|
||||
printf("%.2f us per raise, alt %d\n", ((b.tv_sec - a.tv_sec) * 1e9 + (b.tv_nsec - a.tv_nsec)) / 1e3 / n, on_alt);
|
||||
return 0;
|
||||
}
|
||||
|
||||
mode = 0;
|
||||
calls = 0;
|
||||
int kept = keep_callee_saved();
|
||||
pthread_sigmask(SIG_BLOCK, NULL, &now);
|
||||
printf("returned calls=%d kept=%d usr2_blocked=%d usr1_blocked=%d code=%d stack=%d after_usr2=%d after_usr1=%d\n",
|
||||
calls, kept, usr2_blocked, usr1_blocked, code_ok, stack_ok, sigismember(&now, SIGUSR2),
|
||||
sigismember(&now, SIGUSR1));
|
||||
printf("path %s\n", on_alt ? "kernel" : "inline");
|
||||
|
||||
mode = 1;
|
||||
calls = 0;
|
||||
if (!setjmp(back)) {
|
||||
slowpath();
|
||||
printf("redirect did not happen\n");
|
||||
} else {
|
||||
int ok = 1;
|
||||
for (int i = 0; i <= 28; i++)
|
||||
if (saved[i] != (uint64_t)(0x1000 + i)) ok = 0;
|
||||
if (saved[29] != 0x2900 || saved[30] != 0x3000) ok = 0;
|
||||
for (int i = 0; i < 32; i++)
|
||||
if (saved_v[i] != (((unsigned __int128)(0x7700 + i) << 64) | (0x5500 + i))) ok = 0;
|
||||
printf("redirect calls=%d regs=%d fpsr=%u\n", calls, ok, saved_fpsr & 0x8);
|
||||
}
|
||||
mode = 0;
|
||||
|
||||
sigemptyset(&mask);
|
||||
sigaddset(&mask, SIGUSR2);
|
||||
pthread_sigmask(SIG_BLOCK, &mask, NULL);
|
||||
calls = 0;
|
||||
slowpath();
|
||||
int while_blocked = calls;
|
||||
pthread_sigmask(SIG_UNBLOCK, &mask, NULL);
|
||||
printf("blocked during=%d after=%d\n", while_blocked, calls);
|
||||
|
||||
calls = 0;
|
||||
slowpath_other(SIGUSR1);
|
||||
raise(SIGUSR2);
|
||||
printf("other calls=%d main_path=%s\n", calls, on_alt ? "kernel" : "inline");
|
||||
|
||||
calls = 0;
|
||||
pthread_t t[4];
|
||||
for (int i = 0; i < 4; i++) pthread_create(&t[i], NULL, stress, NULL);
|
||||
for (int i = 0; i < 4; i++) pthread_join(t[i], NULL);
|
||||
printf("threads calls=%d\n", calls);
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def has_gcs_hwcap():
|
||||
try:
|
||||
getauxval = ctypes.CDLL(None).getauxval
|
||||
except (AttributeError, OSError):
|
||||
return False
|
||||
getauxval.restype = ctypes.c_ulong
|
||||
getauxval.argtypes = [ctypes.c_ulong]
|
||||
return bool(getauxval(16) & (1 << 32))
|
||||
|
||||
|
||||
def runner():
|
||||
if platform.machine() in ("aarch64", "arm64") and shutil.which("gcc") and not has_gcs_hwcap():
|
||||
return "gcc", []
|
||||
if shutil.which("aarch64-linux-gnu-gcc") and shutil.which("qemu-aarch64") and Path("/usr/aarch64-linux-gnu").is_dir():
|
||||
return "aarch64-linux-gnu-gcc", ["qemu-aarch64", "-cpu", "neoverse-n1", "-L", "/usr/aarch64-linux-gnu"]
|
||||
return None, None
|
||||
|
||||
|
||||
class Usr2PreloadTest(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()
|
||||
tmp = Path(cls.tmp.name)
|
||||
(tmp / "ntdll.c").write_text(NTDLL)
|
||||
(tmp / "prog.c").write_text(PROGRAM)
|
||||
sources = sorted(str(p) for p in PRELOAD.glob("*.c"))
|
||||
subprocess.run([cls.cc, "-shared", "-fPIC", "-O2", "-Wall", "-pthread", "-o", str(tmp / "libblsession.so"),
|
||||
*sources, "-ldl"], check=True)
|
||||
subprocess.run([cls.cc, "-shared", "-fPIC", "-O2", "-o", str(tmp / "ntdll.so"), str(tmp / "ntdll.c")], check=True)
|
||||
subprocess.run([cls.cc, "-O1", "-U_FORTIFY_SOURCE", "-pthread", "-o", str(tmp / "prog"), str(tmp / "prog.c"), str(tmp / "ntdll.so"),
|
||||
"-Wl,-rpath," + str(tmp)], check=True)
|
||||
cls.program = tmp / "prog"
|
||||
cls.preload = tmp / "libblsession.so"
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.tmp.cleanup()
|
||||
|
||||
def run_program(self, preload):
|
||||
env = dict(os.environ)
|
||||
env.pop("LD_PRELOAD", None)
|
||||
cmd = list(self.prefix) + [str(self.program)]
|
||||
if preload:
|
||||
if self.prefix:
|
||||
cmd = list(self.prefix) + ["-E", "LD_PRELOAD=" + str(self.preload), str(self.program)]
|
||||
else:
|
||||
env["LD_PRELOAD"] = str(self.preload)
|
||||
out = subprocess.run(cmd, env=env, capture_output=True, text=True, timeout=120)
|
||||
self.assertEqual(out.returncode, 0, out.stderr)
|
||||
return out.stdout.splitlines()
|
||||
|
||||
def test_a_ntdll_raise_runs_the_handler_without_a_kernel_signal(self):
|
||||
lines = self.run_program(True)
|
||||
self.assertIn("path inline", lines)
|
||||
self.assertIn("returned calls=1 kept=1 usr2_blocked=1 usr1_blocked=1 code=1 stack=1 after_usr2=0 after_usr1=0", lines)
|
||||
|
||||
def test_b_context_the_handler_writes_is_the_one_that_resumes(self):
|
||||
self.assertIn("redirect calls=1 regs=1 fpsr=8", self.run_program(True))
|
||||
|
||||
def test_c_behaves_like_the_kernel_signal(self):
|
||||
stock = [line for line in self.run_program(False) if not line.startswith("path ")]
|
||||
inline = [line for line in self.run_program(True) if not line.startswith("path ")]
|
||||
self.assertIn("returned calls=1 kept=1 usr2_blocked=1 usr1_blocked=1 code=1 stack=1 after_usr2=0 after_usr1=0", stock)
|
||||
self.assertEqual(stock, inline)
|
||||
|
||||
def test_d_blocked_other_signals_and_other_callers_use_the_kernel(self):
|
||||
lines = self.run_program(True)
|
||||
self.assertIn("blocked during=0 after=1", lines)
|
||||
self.assertIn("other calls=1 main_path=kernel", lines)
|
||||
self.assertIn("threads calls=8000", lines)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -32,6 +32,7 @@ int probe(void) {
|
||||
#include <assert.h>
|
||||
#include <dlfcn.h>
|
||||
int bl_fsync_syscall(long n, const long *a, long *r) { (void)n; (void)a; (void)r; return 0; }
|
||||
int bl_writewatch_syscall(long n, const long *a, long (*real)(long, ...), long *r) { (void)n; (void)a; (void)real; (void)r; return 0; }
|
||||
#include """ + '"' + robust.as_posix() + '"' + r"""
|
||||
int main(int argc, char **argv) {
|
||||
assert(argc == 3);
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload"
|
||||
|
||||
PROGRAM = r"""
|
||||
#include "WRITEWATCH"
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/mman.h>
|
||||
|
||||
#define PAGES 96
|
||||
|
||||
static int uffd, pagemap;
|
||||
static uint64_t page;
|
||||
|
||||
static char *region(void) {
|
||||
char *m = mmap(NULL, PAGES * page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
|
||||
madvise(m, PAGES * page, MADV_NOHUGEPAGE);
|
||||
struct uffdio_register reg = { .range = { (uintptr_t)m, PAGES * page }, .mode = UFFDIO_REGISTER_MODE_WP };
|
||||
if (m == MAP_FAILED || ioctl(uffd, UFFDIO_REGISTER, ®)) exit(3);
|
||||
protect(uffd, (uintptr_t)m, (uintptr_t)m + PAGES * page);
|
||||
return m;
|
||||
}
|
||||
|
||||
static long scan(char *m, int emulated, uint64_t flags, uint64_t vec_len, uint64_t max_pages, uint64_t from, uint64_t to,
|
||||
struct page_region *vec, uint64_t *walk_end) {
|
||||
struct pm_scan_arg a = { .size = sizeof a, .flags = flags, .start = (uintptr_t)m + from * page, .end = (uintptr_t)m + to * page,
|
||||
.vec = vec_len ? (uintptr_t)vec : 0, .vec_len = vec_len, .max_pages = max_pages,
|
||||
.category_mask = PAGE_IS_WRITTEN, .return_mask = PAGE_IS_WRITTEN };
|
||||
long n = emulated ? emulate_scan(pagemap, uffd, &a) : ioctl(pagemap, PAGEMAP_SCAN, &a);
|
||||
*walk_end = (a.walk_end - (uintptr_t)m) / page;
|
||||
return n;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
page = (uint64_t)getpagesize();
|
||||
uffd = syscall(SYS_userfaultfd, O_CLOEXEC | O_NONBLOCK | UFFD_USER_MODE_ONLY);
|
||||
struct uffdio_api api = { .api = UFFD_API, .features = UFFD_FEATURE_WP_ASYNC | UFFD_FEATURE_WP_UNPOPULATED };
|
||||
pagemap = open("/proc/self/pagemap", O_RDONLY | O_CLOEXEC);
|
||||
if (uffd < 0 || ioctl(uffd, UFFDIO_API, &api) || pagemap < 0) { puts("unsupported"); return 0; }
|
||||
char *kernel = region(), *ours = region();
|
||||
struct page_region probe[1];
|
||||
uint64_t end;
|
||||
if (scan(kernel, 0, 0, 1, 0, 0, PAGES, probe, &end) < 0) { puts("unsupported"); return 0; }
|
||||
srand(atoi(argv[1]));
|
||||
int rounds = atoi(argv[2]), differing = 0;
|
||||
for (int r = 0; r < rounds; r++) {
|
||||
int writes = rand() % 24;
|
||||
for (int w = 0; w < writes; w++) {
|
||||
int p = rand() % PAGES;
|
||||
if (rand() % 4 == 0) {
|
||||
volatile char x = kernel[p * page] + ours[p * page];
|
||||
(void)x;
|
||||
continue;
|
||||
}
|
||||
kernel[p * page + rand() % page] = (char)r;
|
||||
ours[p * page + rand() % page] = (char)r;
|
||||
}
|
||||
uint64_t flags = rand() % 2 ? PM_SCAN_WP_MATCHING : 0;
|
||||
uint64_t vec_len = rand() % 3 == 0 ? 0 : 1 + rand() % 5;
|
||||
uint64_t max_pages = rand() % 3 == 0 ? 1 + rand() % 8 : 0;
|
||||
if (!vec_len) flags = PM_SCAN_WP_MATCHING, max_pages = 0;
|
||||
uint64_t from = rand() % PAGES, to = from + rand() % (PAGES - from + 1);
|
||||
struct page_region kv[8], ov[8];
|
||||
uint64_t kend, oend;
|
||||
long kn = scan(kernel, 0, flags, vec_len, max_pages, from, to, kv, &kend);
|
||||
long on = scan(ours, 1, flags, vec_len, max_pages, from, to, ov, &oend);
|
||||
int same = kn == on && (kn < 0 || kend == oend);
|
||||
for (long i = 0; same && i < kn; i++)
|
||||
same = kv[i].start - (uintptr_t)kernel == ov[i].start - (uintptr_t)ours
|
||||
&& kv[i].end - (uintptr_t)kernel == ov[i].end - (uintptr_t)ours && kv[i].categories == ov[i].categories;
|
||||
struct page_region kall[PAGES], oall[PAGES];
|
||||
long ka = scan(kernel, 0, 0, PAGES, 0, 0, PAGES, kall, &kend), oa = scan(ours, 1, 0, PAGES, 0, 0, PAGES, oall, &oend);
|
||||
same = same && ka == oa;
|
||||
for (long i = 0; same && i < ka; i++)
|
||||
same = kall[i].start - (uintptr_t)kernel == oall[i].start - (uintptr_t)ours && kall[i].end - (uintptr_t)kernel == oall[i].end - (uintptr_t)ours;
|
||||
if (!same) {
|
||||
differing++;
|
||||
printf("round %d flags %llu vec %llu max %llu range %llu-%llu: kernel %ld end %llu, ours %ld end %llu\n", r,
|
||||
(unsigned long long)flags, (unsigned long long)vec_len, (unsigned long long)max_pages, (unsigned long long)from,
|
||||
(unsigned long long)to, kn, (unsigned long long)kend, on, (unsigned long long)oend);
|
||||
}
|
||||
}
|
||||
printf("rounds %d differing %d\n", rounds, differing);
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
class WriteWatchPreloadTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
if shutil.which("gcc") is None:
|
||||
raise unittest.SkipTest("gcc is not available")
|
||||
cls.work = Path(tempfile.mkdtemp())
|
||||
source = cls.work / "writewatch.c"
|
||||
source.write_text(PROGRAM.replace("WRITEWATCH", str(PRELOAD / "writewatch.c")))
|
||||
cls.program = cls.work / "writewatch"
|
||||
subprocess.run(["gcc", "-O1", "-Wall", "-o", str(cls.program), str(source)], check=True)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
shutil.rmtree(cls.work, ignore_errors=True)
|
||||
|
||||
def test_a_scan_android_refuses_answers_like_the_kernel_one(self):
|
||||
for seed in range(4):
|
||||
out = subprocess.run([str(self.program), str(seed), "400"], capture_output=True, text=True, timeout=60).stdout
|
||||
if out.strip() == "unsupported":
|
||||
self.skipTest("this kernel has no asynchronous userfaultfd write protection")
|
||||
self.assertTrue(out.rstrip().endswith("differing 0"), out)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -129,6 +129,8 @@ class ZramPreloadTest(unittest.TestCase):
|
||||
|
||||
def setUp(self):
|
||||
self.ctl.write_text("0")
|
||||
for ack in self.dir.glob("ctl.ack.*"):
|
||||
ack.unlink()
|
||||
|
||||
def run_program(self, program=None, mb=48, cycles=1, *extra):
|
||||
environment = dict(os.environ, LD_PRELOAD=str(self.lib))
|
||||
@@ -140,9 +142,10 @@ class ZramPreloadTest(unittest.TestCase):
|
||||
out.setdefault(key, []).append(int(value))
|
||||
return out
|
||||
|
||||
def test_only_the_client_takes_the_signal(self):
|
||||
def test_every_process_takes_the_signal(self):
|
||||
self.assertEqual([1], self.run_program()["handler"])
|
||||
self.assertEqual([0], self.run_program(self.game)["handler"])
|
||||
self.assertEqual([1], self.run_program(self.game)["handler"])
|
||||
self.assertEqual(2, len(list(self.dir.glob("ctl.ack.*"))))
|
||||
|
||||
def test_nothing_is_installed_without_the_control_file(self):
|
||||
self.ctl.unlink()
|
||||
@@ -157,6 +160,7 @@ class ZramPreloadTest(unittest.TestCase):
|
||||
self.assertGreater(out["out"][0], 32 * 1024)
|
||||
self.assertLess(out["back"][0], out["out"][0] // 4)
|
||||
self.assertEqual([1], out["intact"])
|
||||
self.assertEqual(["1"], [ack.read_text() for ack in self.dir.glob("ctl.ack.*")])
|
||||
|
||||
@unittest.skipUnless(swap_total_kb() > 256 * 1024, "needs swap")
|
||||
def test_reads_back_what_the_kernel_swapped_elsewhere(self):
|
||||
|
||||
Reference in new issue
Block a user