Files
DroidDeck/tools/nativeguest/hook/privileged.c
T
5cd6fe8864 feat(session): run the session outside Android's child-process count (#3338)
* docs: research Android's child-process limit without developer options

* docs: confirm the child-process gaps on the Thor

* feat(session): start long-lived daemons in uncounted worker processes

* feat(nativeguest): hand long-lived programs to uncounted worker processes

* test(session): run the session bus block with dd_spawn

* test(nativeguest): cover the exec handoff's wait and kill

* feat(session): run the session root, its jobs and the gamescope chain outside the child-process count

* feat(setup): the child-process limit no longer blocks Steam while the session runs in workers

* feat(audio): run PulseAudio outside the child-process count

* feat(nativeguest): hand off posix_spawn children and keep handed-off daemons alive

* fix(nativeguest): let Steam end a handed-off game and keep process-group signals

* perf(session): exec a worker as soon as its reply is in and keep two bound ahead; fix review findings

* fix(nativeguest): address review findings in handoff waits, signals and spawn errors

* fix(session): commit each worker launch explicitly and keep workers with the session that asked

* fix(session): let a worker wait for its launch commit on the main thread

* fix(session): confirm handoffs, honour wait selectors and stop spawns at teardown

* fix(session): one owner per handoff exit, worker launch answers and spawn edge cases

* fix(session): send a working directory outside the program's root by its real path

* fix(session): recheck a taken exit's child and commit a launch only on a whole go line

* fix(session): three-step launch, tagged exit reports and lock-free popen and system children

* test(native): popen test shell is static, as the other hook fixtures

* test(native): run the popen test program with a clean environment

* test(native): skip the popen test where a spawn child cannot exec aarch64

* fix(session): confirm the hook before the worker runs, prefer a late report and free a reused pid

* fix(session): tell a reused pid's old entry by start time, not the reaped flag

* fix(session): silent failed launches, bounded spawn requests and held check-gone writes

* test(native): check the unlisted child's status only where a child can exec aarch64

* fix(session): every exit-only waitid goes through the handoff wait

* fix(handoff): exact waitid events, safe exit timer, bounded request receipt

* feat(handoff): hand off shell children near Android's process limit

* fix(agent): tag handed-off game windows outside the reaper

* fix(handoff): a handed-off program's getppid() is its forking process

* fix(handoff): exact waitid selection, kept Steam and pipe readers, held reports

* fix(handoff): getppid() gives init for an exited or replaced parent

* fix(handoff): keep __WALL waitid calls on the handoff path

* test(handoff): require a zombie parent in the unreaped-parent case

* fix(handoff): honor __WNOTHREAD and check every argument for Steam

* fix(handoff): stop waiting on a held entry once its parent has exited

* fix(handoff): __WNOTHREAD on waits for a pid, flags on every shim reap

* fix(handoff): keep the forking thread of each child in the parent

* fix(handoff): a wait that finds no child rechecks live handoffs

* fix(handoff): keep a child's forking thread until its end is taken

* fix(handoff): the thread selector applies to claims in progress too

* fix(handoff): controlling-terminal check via /dev/tty, owned records only

* fix(handoff): a child whose forking thread ended is any thread's

* fix(handoff): a parent /proc cannot read is checked with kill(), then given up

* fix(handoff): one-word fork records, changed only by compare-and-swap

* fix(handoff): watch the forking parent through a pidfd opened at start

* fix(handoff): fork records by pid, a gone thread's children go to the main one

* fix(handoff): keep the parent pidfd through dup2 and check it before use

* fix(handoff): no handoff without fork records, unknown thread state keeps the owner

* fix(handoff): undo a pidfd move when dup fails, recheck it after the poll

* fix(handoff): fresh fork records in a forked child, heir is the first live thread

* fix(handoff): one lock over a pidfd move, its dup and the undo

* fix(handoff): liveness check under the pidfd lock, forget only a reaped pid's record

* fix(handoff): lock only dups onto the pidfd, with signals blocked

* fix(handoff): fork record generations, no pidfd restore after a failed move

* fix(handoff): every dup in a pidfd process locks, fork prep blocks signals

* test(semaphores): tell a child hung in qemu-user from a guest deadlock

* fix(handoff): fork records matched by the child's start time, never removed

* test(semaphores): count only reaped children, only futex waits as emulator stalls

* fix(handoff): a known-start bit in fork records

* fix(handoff): dup bookkeeping before the pidfd lock, newer fork records kept

* fix(handoff): a fork record stays only for the pid's current process

* fix(handoff): keep a pending child's fork record when an older fork records late

* fix(handoff): an unknown-start fork record never replaces a pending one

* fix(handoff): self-recorded forks, ELF and wait option checks, both nofile limits

* test(handoff): find the module in the namespace run under discover too

* fix(handoff): a spare parent pidfd made at start, so a dup2 onto it makes no fd

* test(handoff): require ENOEXEC for an ELF stub; skip the namespace run without binfmt

* fix(hook): change the kept fd list under a sequence lock; readers take a copy

* fix(handoff): one report per handed-off child; stops keep a claim; nested waits keep their selector

* fix(hook): a table made at runtime outlives closes begun before it; unknown-start fork records kept

* fix(handoff): waits look before they reap, so a handed-off fork's child is never reported

* fix(hook): settle waits out earlier epochs; unknown-start fork records kept for any handoff under way

* fix(handoff): generation-checked reap marks, stops taken as stops, close counts reset in a fork

* fix(handoff): one given-up table at most, whole stop codes and rusage, WNOWAIT exits rechecked

* fix(handoff): requests name their session; stops of handed-off programs reported; cancellable look

* fix(handoff): table setup not cancellable; test spawner never runs what it cannot end

* fix(handoff): job-control jobs stay counted; unnamed requests refused; cancel-safe setup

* docs(phantom): job-control jobs stay counted; listed programs report no stops

* fix(handoff): a listed program a shell runs as a job-control job stays counted

* refactor(hook): kept descriptors in their own part, a handoff matched by another program

The descriptors close(), close_range() and closefrom() leave open move from
privileged.c to hook/kept.c (unchanged), so the bionic runtime's exec shim can
build the handoff with them. ddh_try_as() matches DD_HANDOFF against one
program and sends another: the bionic shim sends "/system/bin/linker64 PROGRAM
ARGS" and lists it by PROGRAM. ddh_try() is ddh_try_as() with both the same.

* feat(bionic): hand the bionic runtime's Wine programs to the app's workers

The glibc session's hook never sees DroidDeck-Bionic's processes (Wine on
Android's libc), so a bionic game's Wine programs all stayed counted under the
worker running the tool's launch.sh. The handoff is now built into the
runtime's exec shim (tools/bionic-runtime/handoff.c, part of libexecshim.so):

- hook/handoff.c and hook/kept.c with what the native hook's other parts do
  around them: fork(), close(), close_range(), dup2(), dup3(), and exit() for
  the on_exit() bionic lacks
- bionic's execv(), execvp(), execl*() reach the execve system call inside
  libc, past execshim's execve(); Wine starts its preloader with execv(), so
  the shim defines them on top of its execve()
- a linker64 start is listed by its program
- the app starts a handed-off program from the glibc root's bash, which cannot
  load the runtime's LD_PRELOAD/LD_LIBRARY_PATH: they go as arguments of
  /system/bin/env, which puts them back for the program
- launch.sh keeps DD_SPAWN, DD_SPAWN_SESSION, DD_HANDOFF*, DDH_* and
  DDNATV_ROOT, and its /proc/N/environ reads no longer print "Permission
  denied" for idle workers (2>/dev/null before the redirect)

Pocket FIT, DroidDeck-Bionic 14.1-r67 with this shim and launcher, handoff on:
counted during Brawlhalla 25 -> 17, DiRT Showdown 24-27 -> 16, whole run
28 -> 19-20; with Android's limit on no DroidDeck process and no other app's
process was killed (before: Discord, BatteryLog helpers); DiRT 75 fps either
way. docs/phantom-processes.md: "The bionic runtime".

* fix(bionic): hand off only starts that would succeed here; bionic's execvp fallbacks

Review follow-ups on the bionic runtime's handoff (tools/bionic-runtime/handoff.c):

- A start is handed to a worker only when it would get past execve() in this process: the file is a
  regular executable outside the app's data (Android refuses execve() there), and for a linker64 start
  the program it loads is a readable regular file. A start that failed in the worker failed where the
  caller could not see it, so Wine never tried its next candidate. The hook's own check looked at
  /system/bin/env, not the program.
- A start whose argv[0] is not its file stays here: env starts FILE with FILE as argv[0]. linker64 and
  interpreter starts are unaffected (their argv[0] is the file). An empty argv stays here too.
- Nothing is built for the handoff without DD_SPAWN and DD_HANDOFF.
- execvp()/execvpe()/execlp() follow bionic's: an unset PATH is libc's default, an empty PATH or entry
  is the current directory, and a file the kernel cannot start (ENOEXEC) runs under /system/bin/sh.
- close_range() refuses first > last and unknown flags before it splits the range or unshares the table.
- The debug line reads the table's owner only once the table is seen published.

* fix(bionic): hand off app-data starts only where SELinux lets them run; bare names stay here

Follow-up to 7d95564f7 (review, and a Pocket FIT test of its pack):

- 7d95564f7 kept every start of a file in the app's data here. Wine's preloader is one (a static ELF,
  so execshim.c cannot make it a linker64 start), and where SELinux is permissive, as on AYANEO's
  firmware, it runs: Wine then never reached its loader, and its programs ran here, counted again
  (Pocket FIT: Brawlhalla 26-28 counted vs 16-17 before). Where SELinux enforces, Android refuses the
  exec, here and in a worker alike, and Wine falls back to its loader, which goes as a linker64 start.
  Such a start is now handed off when /sys/fs/selinux/enforce reads 0, and stays here otherwise
  (also when the setting cannot be read).
- The program a start would run is checked with the hook's own ddh_startable() (an ELF the kernel
  loads with its interpreter there, or a script with its interpreter): for a linker64 start, the
  program it loads.
- A file name without '/' stays here: env would look it up in PATH, the exec here in the caller's
  working directory.
- execvpe() skips a PATH entry whose candidate exceeds PATH_MAX (ENAMETOOLONG) instead of copying
  it onto the stack.

* fix(handoff): spawn blocks signals and cancellation across the fork; root flag stored under the stop lock

* fix(handoff): a thread that unshares its fd table keeps its own copy of the kept fds

* fix(handoff): register the kept list's fork handlers before a split takes its lock

* test(handoff): cover WNOHANG with a held forked child, early reaps, blocked waitid and pidfd parents; keep the counted-process exception in translations

* test(handoff): exited-entry precondition, atomic checkpoints, a pidfd-only zombie check; validate the shim hold fd

* test(handoff): WNOHANG with two handed-off children and for a group; a program's exit while its entry is held

* test(handoff): a held exit with no free fd, with and without the parent's pidfd

* test(handoff): held-exit tests require the program's own exit status

* test(handoff): time held exits from the run, and only once the program is at its exit

* perf(handoff): keep the asker's priority, quick tools local, workers bound ahead of a game (#3582)

Three fixes that bring handoff-on speed to within 1-2 % of handoff off
(AIO D3D11 same session: 3196 -> 3520 fps, 1 % low 444 -> 637) with the
same counted processes (benchmark mean 18.5, peak 23):

- A handed-off program keeps its asker's priority. Workers are bound
  from the top app with BIND_IMPORTANT, so Android boosts their main
  thread to THREAD_PRIORITY_TOP_APP_BOOST (-10); the program the worker
  execs inherited it. The asker's nice value is sent with the request and
  set before execve, and a watcher resets it if Android boosts it again.
- Quick script tools (awk, sed, grep, cat, ...) stay where they are when
  the count is near the limit. Sent to a worker, the forked child waits
  (counted) while a worker starts; run locally it is counted for a few ms.
- Workers are bound ahead when a Steam game is queued (16 for 20 s), so
  Wine's services do not wait on zygote forks at game start.

---------

Co-authored-by: The412Banner <the412banner@users.noreply.github.com>
Co-authored-by: The412Banner <205237651+The412Banner@users.noreply.github.com>
2026-12-02 14:02:55 -05:00

936 lines
32 KiB
C

// Part of libddnatv-hook.so, included by ddnatv-hook.c (one translation unit, so the
// parts share their static functions and are built with the same command as before).
//
// Calls an app may not make (chown, mknod, capabilities, prctl, landlock, seccomp, namespaces,
// close_range) and the generic syscall() entry point.
#ifndef DDNATV_HOST_TEST
// ndk_translation's file is "/memfd:child"; any memory file counts in a process whose executable is
// a translator's runner (houdini). ndk_translation shows a program its own path as /proc/self/exe,
// so the name is what tells there.
//
// This runs at the start of every program, so it costs three system calls on a phone that runs ARM
// code itself: the descriptors that are open (/proc/self/fd, read at once) are all that are asked
// about, where asking about each of the numbers from 3 to 63 was 61 readlink() calls in every
// process that was started.
// Set once this process knows that it has none (it looked, or was told by DDNATV_NT=0 in its
// environment, which prepare_ddnatv_env hands on to the programs it starts)
static int g_no_translator = 0;
__attribute__((constructor(102))) static void find_translator_files(void) {
// The first program of a session looks; the ones it starts are told (a translator is there for
// all the programs of a machine or for none, and where it is not known they look as before)
const char *known = getenv("DDNATV_NT");
if (known && known[0] == '0' && known[1] == '\0') {
g_no_translator = 1;
return;
}
ssize_t (*real_readlink)(const char *, char *, size_t) = (ssize_t (*)(const char *, char *, size_t))dlsym(RTLD_NEXT, "readlink");
int (*real_open)(const char *, int, ...) = (int (*)(const char *, int, ...))dlsym(RTLD_NEXT, "open");
int (*real_close)(int) = (int (*)(int))dlsym(RTLD_NEXT, "close");
ssize_t (*real_getdents64)(int, void *, size_t) = (ssize_t (*)(int, void *, size_t))dlsym(RTLD_NEXT, "getdents64");
if (!real_readlink || !real_open || !real_close) return;
int dir = real_getdents64 ? real_open("/proc/self/fd", O_RDONLY | O_DIRECTORY | O_CLOEXEC) : -1;
if (dir < 0) return;
// The numbers of the descriptors open now, those from 3 to 63 (the directory's own left out)
char entries[2048];
unsigned char open_fds[64];
int nopen = 0;
for (;;) {
long n = real_getdents64(dir, entries, sizeof(entries));
if (n <= 0) break;
for (long off = 0; off < n;) {
// struct linux_dirent64: d_ino (8), d_off (8), d_reclen (2), d_type (1), then d_name
unsigned short reclen;
memcpy(&reclen, entries + off + 16, sizeof(reclen));
const char *name = entries + off + 19;
off += reclen ? reclen : n; // a record without a length ends the buffer
if (name[0] < '0' || name[0] > '9') continue; // "." and ".."
int fd = atoi(name);
if (fd >= 3 && fd < 64 && fd != dir) open_fds[nopen++] = (unsigned char)fd;
}
// A short answer is the whole directory; asking again would only be told "no more"
if ((size_t)n + 64 <= sizeof(entries)) break;
}
real_close(dir);
if (nopen == 0) {
g_no_translator = 1;
return;
}
char path[PATH_MAX];
int runner = 0;
ssize_t n = real_readlink("/proc/self/exe", path, sizeof(path) - 1);
if (n > 0) {
path[n] = '\0';
const char *base = strrchr(path, '/');
base = base ? base + 1 : path;
runner = strncmp(base, "ndk_translation", 15) == 0 || strncmp(base, "houdini", 7) == 0;
}
// In ascending order, as the list is kept
for (int i = 0; i < nopen - 1; i++) {
for (int j = i + 1; j < nopen; j++) {
if (open_fds[j] < open_fds[i]) {
unsigned char t = open_fds[i];
open_fds[i] = open_fds[j];
open_fds[j] = t;
}
}
}
for (int i = 0; i < nopen && g_kept_fd_count < DDNATV_MAX_KEPT_FDS; i++) {
char link[32], target[64];
snprintf(link, sizeof(link), "/proc/self/fd/%d", open_fds[i]);
ssize_t m = real_readlink(link, target, sizeof(target) - 1);
if (m <= 0) continue;
target[m] = '\0';
if (strncmp(target, "/memfd:child", 12) == 0 || (runner && strncmp(target, "/memfd:", 7) == 0)) {
g_kept_fds[g_kept_fd_count++] = open_fds[i];
}
}
if (g_kept_fd_count == 0) g_no_translator = 1;
}
int chown(const char *pathname, uid_t owner, gid_t group) { (void)pathname; (void)owner; (void)group; return 0; }
int fchown(int fd, uid_t owner, gid_t group) { (void)fd; (void)owner; (void)group; return 0; }
int lchown(const char *pathname, uid_t owner, gid_t group) { (void)pathname; (void)owner; (void)group; return 0; }
int fchownat(int dirfd, const char *pathname, uid_t owner, gid_t group, int flags) {
DDNATV_AT_REMAP(dirfd, pathname);
(void)dirfd; (void)pathname; (void)owner; (void)group; (void)flags; return 0;
}
int chroot(const char *path) { (void)path; return 0; }
// Hook mkfifo / mkfifoat / mknod / mknodat
int mkfifo(const char *pathname, mode_t mode);
int mkfifoat(int dirfd, const char *pathname, mode_t mode);
int mknodat(int dirfd, const char *pathname, mode_t mode, dev_t dev) {
DDNATV_AT_REMAP(dirfd, pathname);
(void)dev;
if (!pathname) {
errno = EFAULT;
return -1;
}
char buf[PATH_MAX];
const char *target = (pathname[0] == '/') ? rewrite_path(pathname, buf, sizeof(buf)) : pathname;
// A file type of 0 means a regular file, as in mknod(2), which also fails with EEXIST instead
// of touching an existing file.
if (S_ISREG(mode) || (mode & S_IFMT) == 0) {
// mknod(2) returns 0 on success, never a file descriptor: close the
// transient fd instead of leaking one per call (tar/dpkg extract
// thousands of files; leaked fds exhaust the table -> EBADF noise).
int fd = openat(dirfd, target, O_CREAT | O_EXCL | O_WRONLY | O_CLOEXEC, mode & 07777);
if (fd >= 0) {
close(fd);
return 0;
}
return -1;
}
if (S_ISFIFO(mode)) {
return mkfifoat(dirfd, target, mode);
}
return 0;
}
int mknod(const char *pathname, mode_t mode, dev_t dev) {
return mknodat(AT_FDCWD, pathname, mode, dev);
}
int mkfifoat(int dirfd, const char *pathname, mode_t mode) {
static int (*orig_mkfifoat)(int, const char *, mode_t) = NULL;
if (!orig_mkfifoat) orig_mkfifoat = (int (*)(int, const char *, mode_t))dlsym(RTLD_NEXT, "mkfifoat");
if (!pathname) {
errno = EFAULT;
return -1;
}
char buf[PATH_MAX];
const char *target = (pathname[0] == '/') ? rewrite_path(pathname, buf, sizeof(buf)) : pathname;
if (orig_mkfifoat) {
return orig_mkfifoat(dirfd, target, mode);
}
static int (*orig_mkfifo)(const char *, mode_t) = NULL;
if (!orig_mkfifo) orig_mkfifo = (int (*)(const char *, mode_t))dlsym(RTLD_NEXT, "mkfifo");
if (orig_mkfifo && dirfd == AT_FDCWD) {
return orig_mkfifo(target, mode);
}
return -1;
}
int mkfifo(const char *pathname, mode_t mode) {
return mkfifoat(AT_FDCWD, pathname, mode);
}
// Hook sync / syncfs to prevent Android flash storage stalls during dpkg operations
void sync(void) {
// No-op
}
int syncfs(int fd) {
(void)fd;
return 0;
}
int capget(void *hdrp, void *datap) {
static int (*orig_capget)(void *, void *) = NULL;
if (!orig_capget) orig_capget = (int (*)(void *, void *))dlsym(RTLD_NEXT, "capget");
if (orig_capget && orig_capget(hdrp, datap) == 0) {
return 0;
}
if (datap) {
uint32_t ver = hdrp ? *(const uint32_t *)hdrp : 0;
size_t nbytes = (ver == 0x20071026U || ver == 0x20080522U) ? 24 : 12;
memset(datap, 0, nbytes);
}
errno = 0;
return 0;
}
int capset(void *hdrp, const void *datap) { (void)hdrp; (void)datap; return 0; }
int prctl(int option, ...) {
va_list ap;
va_start(ap, option);
unsigned long arg2 = va_arg(ap, unsigned long);
unsigned long arg3 = va_arg(ap, unsigned long);
unsigned long arg4 = va_arg(ap, unsigned long);
unsigned long arg5 = va_arg(ap, unsigned long);
va_end(ap);
// PR_SET_NO_NEW_PRIVS = 38, PR_GET_NO_NEW_PRIVS = 39
#ifdef PR_SET_NO_NEW_PRIVS
if (option == PR_SET_NO_NEW_PRIVS) return 0;
#endif
if (option == 38) return 0;
#ifdef PR_GET_NO_NEW_PRIVS
if (option == PR_GET_NO_NEW_PRIVS) return 1;
#endif
if (option == 39) return 1;
// PR_SET_SECCOMP = 22, PR_GET_SECCOMP = 21
#ifdef PR_SET_SECCOMP
if (option == PR_SET_SECCOMP) { errno = EINVAL; return -1; }
#endif
if (option == 22) { errno = EINVAL; return -1; }
#ifdef PR_GET_SECCOMP
if (option == PR_GET_SECCOMP) return 0;
#endif
if (option == 21) return 0;
// PR_SET_SPECULATION_CTRL = 47
if (option == 47) return 0;
static int (*orig_prctl)(int, unsigned long, unsigned long, unsigned long, unsigned long) = NULL;
if (!orig_prctl) orig_prctl = (int (*)(int, unsigned long, unsigned long, unsigned long, unsigned long))dlsym(RTLD_NEXT, "prctl");
return orig_prctl ? orig_prctl(option, arg2, arg3, arg4, arg5) : 0;
}
// Limits that leave a process no new descriptors (RLIMIT_NOFILE below 16) or no file writes
// (RLIMIT_FSIZE 0) are not applied. Sandboxes give them to their unprivileged part (sshd's before
// login sets 1 and 0, with the seccomp filter above), and Android's ARM translator (emulators, x86
// devices) needs new descriptors and memory files in the process: sshd's died in it ("CHECK failed"
// in its mmap) and the client's connection was reset. Other limits are set as asked.
static int sandbox_only_limit(int resource, const struct rlimit *rlim) {
if (!rlim) return 0;
if (resource == RLIMIT_NOFILE) return rlim->rlim_cur < 16;
if (resource == RLIMIT_FSIZE) return rlim->rlim_cur == 0;
return 0;
}
int setrlimit(__rlimit_resource_t resource, const struct rlimit *rlim) {
if (sandbox_only_limit((int)resource, rlim)) return 0;
static int (*orig_setrlimit)(__rlimit_resource_t, const struct rlimit *) = NULL;
#if defined(__USE_FILE_OFFSET64) && !defined(__LP64__)
// With 64-bit file offsets on a 32-bit system this function is setrlimit64
if (!orig_setrlimit) orig_setrlimit = (int (*)(__rlimit_resource_t, const struct rlimit *))dlsym(RTLD_NEXT, "setrlimit64");
#else
if (!orig_setrlimit) orig_setrlimit = (int (*)(__rlimit_resource_t, const struct rlimit *))dlsym(RTLD_NEXT, "setrlimit");
#endif
if (!orig_setrlimit) {
errno = ENOSYS;
return -1;
}
return orig_setrlimit(resource, rlim);
}
#if defined(__LP64__)
__asm__(".globl setrlimit64\n" ".set setrlimit64, setrlimit\n");
#endif
#ifndef LANDLOCK_CREATE_RULESET_VERSION
#define LANDLOCK_CREATE_RULESET_VERSION (1U << 0)
#endif
#ifndef __NR_landlock_create_ruleset
#define __NR_landlock_create_ruleset 444
#endif
#ifndef __NR_landlock_add_rule
#define __NR_landlock_add_rule 445
#endif
#ifndef __NR_landlock_restrict_self
#define __NR_landlock_restrict_self 446
#endif
#ifndef __NR_seccomp
#if defined(__aarch64__)
#define __NR_seccomp 277
#elif defined(__x86_64__)
#define __NR_seccomp 317
#elif defined(__arm__)
#define __NR_seccomp 383
#else
#define __NR_seccomp 277
#endif
#endif
#ifndef __NR_unshare
#if defined(__aarch64__)
#define __NR_unshare 97
#elif defined(__x86_64__)
#define __NR_unshare 272
#elif defined(__arm__)
#define __NR_unshare 337
#else
#define __NR_unshare 97
#endif
#endif
#ifndef __NR_setns
#if defined(__aarch64__)
#define __NR_setns 268
#elif defined(__x86_64__)
#define __NR_setns 308
#elif defined(__arm__)
#define __NR_setns 375
#else
#define __NR_setns 268
#endif
#endif
#ifndef __NR_clone3
#define __NR_clone3 435
#endif
#ifndef __NR_pidfd_open
#define __NR_pidfd_open 434
#endif
#ifndef __NR_pidfd_send_signal
#define __NR_pidfd_send_signal 424
#endif
#ifndef __NR_pidfd_getfd
#define __NR_pidfd_getfd 438
#endif
#ifndef __NR_close_range
#define __NR_close_range 436
#endif
#ifndef __NR_faccessat
#if defined(__aarch64__)
#define __NR_faccessat 48
#elif defined(__arm__)
#define __NR_faccessat 334
#elif defined(__x86_64__)
#define __NR_faccessat 269
#endif
#endif
#ifndef __NR_faccessat2
#define __NR_faccessat2 439
#endif
#ifndef __NR_statx
#if defined(__aarch64__) || defined(__arm__)
#define __NR_statx 291
#elif defined(__x86_64__)
#define __NR_statx 332
#endif
#endif
#ifndef SECCOMP_SET_MODE_STRICT
#define SECCOMP_SET_MODE_STRICT 0
#endif
#ifndef SECCOMP_SET_MODE_FILTER
#define SECCOMP_SET_MODE_FILTER 1
#endif
#ifndef SECCOMP_GET_ACTION_AVAIL
#define SECCOMP_GET_ACTION_AVAIL 2
#endif
int landlock_create_ruleset(const void *attr, size_t size, uint32_t flags) {
(void)attr;
(void)size;
(void)flags;
errno = ENOSYS;
return -1;
}
int landlock_add_rule(int ruleset_fd, int rule_type, const void *rule_attr, uint32_t flags) {
(void)ruleset_fd;
(void)rule_type;
(void)rule_attr;
(void)flags;
errno = ENOSYS;
return -1;
}
int landlock_restrict_self(int ruleset_fd, uint32_t flags) {
(void)ruleset_fd;
(void)flags;
errno = ENOSYS;
return -1;
}
int seccomp(unsigned int operation, unsigned int flags, void *args) {
(void)flags;
(void)args;
if (operation != SECCOMP_SET_MODE_STRICT &&
operation != SECCOMP_SET_MODE_FILTER &&
operation != SECCOMP_GET_ACTION_AVAIL &&
operation != 3 /* SECCOMP_GET_NOTIF_SIZES */) {
errno = EINVAL;
return -1;
}
errno = ENOSYS;
return -1;
}
int unshare(int flags) {
(void)flags;
errno = ENOSYS;
return -1;
}
int setns(int fd, int nstype) {
(void)fd;
(void)nstype;
errno = ENOSYS;
return -1;
}
#ifndef CLOSE_RANGE_CLOEXEC
#define CLOSE_RANGE_CLOEXEC (1U << 2)
#endif
#ifndef CLOSE_RANGE_UNSHARE
#define CLOSE_RANGE_UNSHARE (1U << 1)
#endif
static int close_range_all(unsigned int first, unsigned int last, int flags);
// Tests only ("IN OUT TID"): before each part it closes, once it has looked at the kept fds, thread
// TID's close_range() writes a byte to OUT and waits for one on IN, as a thread descheduled there
// would.
static void close_range_test_gate(void) {
const char *gate = getenv("DDNATV_TEST_CLOSE_RANGE_GATE");
int in, out, tid;
if (!gate || sscanf(gate, "%d %d %d", &in, &out, &tid) != 3 || tid != (int)syscall(SYS_gettid)) return;
int saved = errno;
char c = 1;
syscall(SYS_write, out, &c, 1);
while (syscall(SYS_read, in, &c, 1) < 0 && errno == EINTR) {}
errno = saved;
}
static int close_range_part(unsigned int first, unsigned int last, void *flags) {
close_range_test_gate();
return close_range_all(first, last, *(int *)flags);
}
// The system call itself on the one number no fd has (close_range_all() would emulate a missing call
// by closing fds)
static int close_range_unshare(void) {
static long (*raw_syscall)(long, ...) = NULL;
if (!raw_syscall) raw_syscall = (long (*)(long, ...))dlsym(RTLD_NEXT, "syscall");
if (!raw_syscall) {
errno = ENOSYS;
return -1;
}
return raw_syscall(__NR_close_range, ~0U, ~0U, CLOSE_RANGE_UNSHARE) == 0 ? 0 : -1;
}
static int close_range_kept(unsigned int first, unsigned int last, int flags) {
// The table is unshared first, once, even when every fd in the range is kept, and this thread
// goes on with its own copy of the kept list (kept_split()). Without the system call, it is
// emulated where nothing is kept, and refused otherwise.
if (flags & CLOSE_RANGE_UNSHARE) {
if (kept_split(close_range_unshare) == 0) flags &= ~CLOSE_RANGE_UNSHARE;
else if (errno != ENOSYS || kept_any() > 0) return -1;
}
// Close-on-exec only (CLOSE_RANGE_CLOEXEC) leaves the translator's files open
int snapshot[DDNATV_MAX_KEPT_FDS];
const int *kept = (flags & CLOSE_RANGE_CLOEXEC) ? g_cloexec_kept_fds : snapshot;
int kept_count = (flags & CLOSE_RANGE_CLOEXEC) ? g_cloexec_kept_count : kept_snapshot(snapshot);
if (kept_count == 0) return close_range_part(first, last, &flags);
return for_each_range_without(first, last, kept, kept_count, close_range_part, &flags);
}
int close_range(unsigned int first, unsigned int last, int flags) {
if (!(flags & CLOSE_RANGE_CLOEXEC)) forget_proc_root_range(first, last);
uint64_t ticket = kept_close_begin();
int r = close_range_kept(first, last, flags);
int saved = errno;
kept_close_end(ticket);
errno = saved;
return r;
}
// glibc's closefrom() makes the close_range system call itself, past the function above
void closefrom(int lowfd) {
close_range(lowfd < 0 ? 0U : (unsigned int)lowfd, ~0U, 0);
}
static int close_range_all(unsigned int first, unsigned int last, int flags) {
static int (*orig_close_range)(unsigned int, unsigned int, int) = NULL;
if (!orig_close_range) {
orig_close_range = (int (*)(unsigned int, unsigned int, int))dlsym(RTLD_NEXT, "close_range");
}
#ifdef __NR_close_range
static long (*orig_raw_syscall)(long, ...) = NULL;
if (!orig_raw_syscall) orig_raw_syscall = (long (*)(long, ...))dlsym(RTLD_NEXT, "syscall");
if (orig_raw_syscall) {
long sret = orig_raw_syscall(__NR_close_range, first, last, flags);
if (sret == 0) return 0;
if (sret < 0 && errno != ENOSYS) return -1;
}
#endif
if (orig_close_range) {
int cret = orig_close_range(first, last, flags);
if (cret == 0) return 0;
if (cret < 0 && errno != ENOSYS) return -1;
}
int set_cloexec = (flags & CLOSE_RANGE_CLOEXEC) != 0;
DIR *d = opendir("/proc/self/fd");
if (d) {
int dfd = dirfd(d);
struct dirent *de;
while ((de = readdir(d)) != NULL) {
if (de->d_name[0] == '.') continue;
int fd = atoi(de->d_name);
if (fd >= (int)first && (last == ~0U || (unsigned int)fd <= last) && fd != dfd) {
if (set_cloexec) {
int fl = fcntl(fd, F_GETFD);
if (fl >= 0) {
fcntl(fd, F_SETFD, fl | FD_CLOEXEC);
}
} else {
close(fd);
}
}
}
closedir(d);
return 0;
}
int max_fd = (int)sysconf(_SC_OPEN_MAX);
if (max_fd <= 0 || max_fd > 1024) max_fd = 1024;
int end = (last < (unsigned int)max_fd) ? (int)last : max_fd;
for (int fd = (int)first; fd <= end; fd++) {
if (set_cloexec) {
int fl = fcntl(fd, F_GETFD);
if (fl >= 0) {
fcntl(fd, F_SETFD, fl | FD_CLOEXEC);
}
} else {
close(fd);
}
}
return 0;
}
static __thread int t_syscall_redirect = 0;
static long nested_path_syscall(long number, unsigned long dirfd, unsigned long pathname, unsigned long arg3, unsigned long arg4) {
char nested_buf[PATH_MAX];
const char *path = (const char *)pathname;
if (path && path[0] == '/') path = rewrite_path(path, nested_buf, sizeof(nested_buf));
return call_orig_syscall(number, dirfd, (unsigned long)path, arg3, arg4, 0, 0);
}
static long fake_root_ids(long number, unsigned int *real, unsigned int *effective, unsigned int *saved) {
long rc = call_orig_syscall(number, (unsigned long)real, (unsigned long)effective, (unsigned long)saved, 0, 0, 0);
if (rc == 0 && !app_user_mode()) *real = *effective = *saved = 0;
return rc;
}
long syscall(long number, ...) {
va_list ap;
va_start(ap, number);
unsigned long arg1 = va_arg(ap, unsigned long);
unsigned long arg2 = va_arg(ap, unsigned long);
unsigned long arg3 = va_arg(ap, unsigned long);
unsigned long arg4 = va_arg(ap, unsigned long);
unsigned long arg5 = va_arg(ap, unsigned long);
unsigned long arg6 = va_arg(ap, unsigned long);
va_end(ap);
#if defined(__NR_readlinkat)
if (number == __NR_readlinkat) {
return (long)readlinkat((int)arg1, (const char *)arg2, (char *)arg3, (size_t)arg4);
}
#endif
#if defined(__NR_readlink)
if (number == __NR_readlink) {
return (long)readlink((const char *)arg1, (char *)arg2, (size_t)arg3);
}
#endif
#if defined(__NR_linkat)
if (number == __NR_linkat) {
return (long)linkat((int)arg1, (const char *)arg2, (int)arg3, (const char *)arg4, (int)arg5);
}
#endif
#if defined(__NR_link)
if (number == __NR_link) {
return (long)link((const char *)arg1, (const char *)arg2);
}
#endif
#ifdef __NR_landlock_create_ruleset
if (number == __NR_landlock_create_ruleset) {
return (long)landlock_create_ruleset((const void *)arg1, (size_t)arg2, (uint32_t)arg3);
}
if (number == __NR_landlock_add_rule) {
return (long)landlock_add_rule((int)arg1, (int)arg2, (const void *)arg3, (uint32_t)arg4);
}
if (number == __NR_landlock_restrict_self) {
return (long)landlock_restrict_self((int)arg1, (uint32_t)arg2);
}
#endif
#ifdef __NR_rt_sigprocmask
if (number == __NR_rt_sigprocmask && arg2 && (arg1 == SIG_BLOCK || arg1 == SIG_SETMASK) && arg4 == sizeof(uint64_t)) {
uint64_t mask;
memcpy(&mask, (const void *)arg2, sizeof(mask));
mask &= ~(1ULL << (SIGSYS - 1));
return call_orig_syscall(number, arg1, (unsigned long)&mask, arg3, arg4, 0, 0);
}
#endif
#ifdef __NR_rt_sigaction
if (number == __NR_rt_sigaction && arg1 == SIGSYS && arg4 == sizeof(uint64_t)) {
struct { void *handler; unsigned long flags; void *restorer; uint64_t mask; } kact, kold;
struct sigaction act, old;
memset(&act, 0, sizeof(act));
if (arg2) {
memcpy(&kact, (const void *)arg2, sizeof(kact));
act.sa_sigaction = (void (*)(int, siginfo_t *, void *))kact.handler;
act.sa_flags = (int)kact.flags;
memcpy(&act.sa_mask, &kact.mask, sizeof(kact.mask));
}
remember_app_sigsys(arg2 ? &act : NULL, arg3 ? &old : NULL);
if (arg3) {
memset(&kold, 0, sizeof(kold));
kold.handler = (void *)old.sa_sigaction;
kold.flags = (unsigned long)(unsigned int)old.sa_flags;
memcpy(&kold.mask, &old.sa_mask, sizeof(kold.mask));
memcpy((void *)arg3, &kold, sizeof(kold));
}
return 0;
}
#endif
#ifdef __NR_seccomp
if (number == __NR_seccomp) {
return (long)seccomp((unsigned int)arg1, (unsigned int)arg2, (void *)arg3);
}
#endif
#ifdef __NR_unshare
if (number == __NR_unshare) {
return (long)unshare((int)arg1);
}
#endif
#ifdef __NR_setns
if (number == __NR_setns) {
return (long)setns((int)arg1, (int)arg2);
}
#endif
#ifdef __NR_clone3
if (number == __NR_clone3) {
errno = ENOSYS;
return -1;
}
#endif
#ifdef __NR_pidfd_open
if (number == __NR_pidfd_open) {
errno = ENOSYS;
return -1;
}
#endif
#ifdef __NR_pidfd_send_signal
if (number == __NR_pidfd_send_signal) {
errno = ENOSYS;
return -1;
}
#endif
#ifdef __NR_pidfd_getfd
if (number == __NR_pidfd_getfd) {
errno = ENOSYS;
return -1;
}
#endif
#ifdef __NR_close_range
if (number == __NR_close_range) {
// libddsession's close_range() calls syscall() again: the nested call goes straight to the kernel
if (t_syscall_redirect) return call_orig_syscall(number, arg1, arg2, arg3, 0, 0, 0);
t_syscall_redirect++;
long ret = (long)close_range((unsigned int)arg1, (unsigned int)arg2, (int)arg3);
t_syscall_redirect--;
return ret;
}
#endif
if (g_initialized) {
#ifdef __NR_openat
if (number == __NR_openat) {
if (t_syscall_redirect) return nested_path_syscall(number, arg1, arg2, arg3, arg4);
t_syscall_redirect++;
long ret = (long)openat((int)arg1, (const char *)arg2, (int)arg3, (mode_t)arg4);
t_syscall_redirect--;
return ret;
}
#endif
#if defined(__NR_mkdirat)
if (number == __NR_mkdirat) {
return (long)mkdirat((int)arg1, (const char *)arg2, (mode_t)arg3);
}
#endif
#if defined(__NR_unlinkat)
if (number == __NR_unlinkat) {
return (long)unlinkat((int)arg1, (const char *)arg2, (int)arg3);
}
#endif
#if defined(__NR_renameat)
if (number == __NR_renameat) {
return (long)renameat((int)arg1, (const char *)arg2, (int)arg3, (const char *)arg4);
}
#endif
#if defined(__NR_renameat2)
if (number == __NR_renameat2) {
return (long)renameat2((int)arg1, (const char *)arg2, (int)arg3, (const char *)arg4, (unsigned int)arg5);
}
#endif
#if defined(__NR_symlinkat)
if (number == __NR_symlinkat) {
return (long)symlinkat((const char *)arg1, (int)arg2, (const char *)arg3);
}
#endif
#if defined(__NR_fchmodat)
if (number == __NR_fchmodat) {
return (long)fchmodat((int)arg1, (const char *)arg2, (mode_t)arg3, 0);
}
#endif
#if defined(__NR_fchownat)
if (number == __NR_fchownat) {
return (long)fchownat((int)arg1, (const char *)arg2, (uid_t)arg3, (gid_t)arg4, (int)arg5);
}
#endif
#if defined(__NR_utimensat)
if (number == __NR_utimensat) {
if (!arg2) return call_orig_syscall(number, arg1, arg2, arg3, arg4, 0, 0);
return (long)utimensat((int)arg1, (const char *)arg2, (const struct timespec *)arg3, (int)arg4);
}
#endif
#if defined(__NR_connect)
if (number == __NR_connect) {
return (long)connect((int)arg1, (const struct sockaddr *)arg2, (socklen_t)arg3);
}
#endif
#if defined(__NR_bind)
if (number == __NR_bind) {
return (long)bind((int)arg1, (const struct sockaddr *)arg2, (socklen_t)arg3);
}
#endif
#if defined(__NR_sendmsg)
if (number == __NR_sendmsg) {
return (long)sendmsg((int)arg1, (const struct msghdr *)arg2, (int)arg3);
}
#endif
#if defined(__NR_recvmsg)
if (number == __NR_recvmsg) {
return (long)recvmsg((int)arg1, (struct msghdr *)arg2, (int)arg3);
}
#endif
#if defined(__NR_getsockopt)
if (number == __NR_getsockopt) {
return (long)getsockopt((int)arg1, (int)arg2, (int)arg3, (void *)arg4, (socklen_t *)arg5);
}
#endif
#if defined(__NR_truncate)
if (number == __NR_truncate) {
return (long)truncate((const char *)arg1, (off_t)arg2);
}
#endif
#if defined(__NR_chdir)
if (number == __NR_chdir) {
return (long)chdir((const char *)arg1);
}
#endif
#if defined(__NR_chroot)
if (number == __NR_chroot) {
return (long)chroot((const char *)arg1);
}
#endif
#if defined(__NR_inotify_add_watch)
if (number == __NR_inotify_add_watch) {
return (long)inotify_add_watch((int)arg1, (const char *)arg2, (uint32_t)arg3);
}
#endif
}
#ifdef __NR_openat2
if (number == __NR_openat2) {
// libddsession's openat2() calls syscall() again (an endless loop until the stack ran out): the nested
// call maps the path and goes straight to the kernel
if (t_syscall_redirect) return nested_path_syscall(number, arg1, arg2, arg3, arg4);
t_syscall_redirect++;
long ret = (long)openat2((int)arg1, (const char *)arg2, (struct ddnatv_open_how *)arg3, (size_t)arg4);
t_syscall_redirect--;
return ret;
}
#endif
#ifdef __NR_fchmodat2
if (number == __NR_fchmodat2) {
return (long)fchmodat2((int)arg1, (const char *)arg2, (mode_t)arg3, (int)arg4);
}
#endif
#if defined(__NR_statx)
if (number == __NR_statx) {
return (long)statx((int)arg1, (const char *)arg2, (int)arg3, (unsigned int)arg4, (struct statx *)arg5);
}
#endif
#if defined(__NR_faccessat)
if (number == __NR_faccessat) {
if (t_syscall_redirect) return nested_path_syscall(number, arg1, arg2, arg3, 0);
t_syscall_redirect++;
long ret = (long)faccessat((int)arg1, (const char *)arg2, (int)arg3, 0);
t_syscall_redirect--;
return ret;
}
#endif
#if defined(__NR_faccessat2)
if (number == __NR_faccessat2) {
return (long)faccessat2((int)arg1, (const char *)arg2, (int)arg3, (int)arg4);
}
#endif
#if defined(__NR_mknodat)
if (number == __NR_mknodat) {
return (long)mknodat((int)arg1, (const char *)arg2, (mode_t)arg3, (dev_t)arg4);
}
#endif
#if defined(__NR_mknod)
if (number == __NR_mknod) {
return (long)mknod((const char *)arg1, (mode_t)arg2, (dev_t)arg3);
}
#endif
#if defined(__NR_mkfifoat)
if (number == __NR_mkfifoat) {
return (long)mkfifoat((int)arg1, (const char *)arg2, (mode_t)arg3);
}
#endif
#if defined(__NR_setresuid)
if (number == __NR_setresuid) return (long)setresuid((uid_t)arg1, (uid_t)arg2, (uid_t)arg3);
#endif
#if defined(__NR_setresuid32)
if (number == __NR_setresuid32) return (long)setresuid((uid_t)arg1, (uid_t)arg2, (uid_t)arg3);
#endif
#if defined(__NR_setresgid)
if (number == __NR_setresgid) return (long)setresgid((gid_t)arg1, (gid_t)arg2, (gid_t)arg3);
#endif
#if defined(__NR_setresgid32)
if (number == __NR_setresgid32) return (long)setresgid((gid_t)arg1, (gid_t)arg2, (gid_t)arg3);
#endif
#if defined(__NR_setuid)
if (number == __NR_setuid) return (long)setuid((uid_t)arg1);
#endif
#if defined(__NR_setuid32)
if (number == __NR_setuid32) return (long)setuid((uid_t)arg1);
#endif
#if defined(__NR_setgid)
if (number == __NR_setgid) return (long)setgid((gid_t)arg1);
#endif
#if defined(__NR_setgid32)
if (number == __NR_setgid32) return (long)setgid((gid_t)arg1);
#endif
#if defined(__NR_setreuid)
if (number == __NR_setreuid) return (long)setreuid((uid_t)arg1, (uid_t)arg2);
#endif
#if defined(__NR_setreuid32)
if (number == __NR_setreuid32) return (long)setreuid((uid_t)arg1, (uid_t)arg2);
#endif
#if defined(__NR_setregid)
if (number == __NR_setregid) return (long)setregid((gid_t)arg1, (gid_t)arg2);
#endif
#if defined(__NR_setregid32)
if (number == __NR_setregid32) return (long)setregid((gid_t)arg1, (gid_t)arg2);
#endif
#if defined(__NR_setgroups)
if (number == __NR_setgroups) return (long)setgroups((size_t)arg1, (const gid_t *)arg2);
#endif
#if defined(__NR_setgroups32)
if (number == __NR_setgroups32) return (long)setgroups((size_t)arg1, (const gid_t *)arg2);
#endif
#if defined(__NR_setfsuid)
if (number == __NR_setfsuid) return (long)presented_uid();
#endif
#if defined(__NR_setfsuid32)
if (number == __NR_setfsuid32) return (long)presented_uid();
#endif
#if defined(__NR_setfsgid)
if (number == __NR_setfsgid) return (long)presented_gid();
#endif
#if defined(__NR_setfsgid32)
if (number == __NR_setfsgid32) return (long)presented_gid();
#endif
#if defined(__NR_getuid)
if (number == __NR_getuid) return (long)presented_uid();
#endif
#if defined(__NR_getuid32)
if (number == __NR_getuid32) return (long)presented_uid();
#endif
#if defined(__NR_geteuid)
if (number == __NR_geteuid) return (long)presented_uid();
#endif
#if defined(__NR_geteuid32)
if (number == __NR_geteuid32) return (long)presented_uid();
#endif
#if defined(__NR_getgid)
if (number == __NR_getgid) return (long)presented_gid();
#endif
#if defined(__NR_getgid32)
if (number == __NR_getgid32) return (long)presented_gid();
#endif
#if defined(__NR_getegid)
if (number == __NR_getegid) return (long)presented_gid();
#endif
#if defined(__NR_getegid32)
if (number == __NR_getegid32) return (long)presented_gid();
#endif
#if defined(__NR_getresuid)
if (number == __NR_getresuid) return fake_root_ids(number, (unsigned int *)arg1, (unsigned int *)arg2, (unsigned int *)arg3);
#endif
#if defined(__NR_getresuid32)
if (number == __NR_getresuid32) return fake_root_ids(number, (unsigned int *)arg1, (unsigned int *)arg2, (unsigned int *)arg3);
#endif
#if defined(__NR_getresgid)
if (number == __NR_getresgid) return fake_root_ids(number, (unsigned int *)arg1, (unsigned int *)arg2, (unsigned int *)arg3);
#endif
#if defined(__NR_getresgid32)
if (number == __NR_getresgid32) return fake_root_ids(number, (unsigned int *)arg1, (unsigned int *)arg2, (unsigned int *)arg3);
#endif
#if defined(__NR_getgroups)
if (number == __NR_getgroups) return (long)getgroups((int)arg1, (gid_t *)arg2);
#endif
#if defined(__NR_fchown)
if (number == __NR_fchown) return (long)fchown((int)arg1, (uid_t)arg2, (gid_t)arg3);
#endif
return call_orig_syscall(number, arg1, arg2, arg3, arg4, arg5, arg6);
}
#endif /* !DDNATV_HOST_TEST */