mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-05 12:35:42 +00:00
* FEX: emulate x86-64 ptrace, seccomp and /proc for anti-cheat launchers * Guest hook: route raw execve/execveat through the exec wrapper and pass self-sent SIGSYS to the program A program that execs with syscall(SYS_execveat, ...) bypassed the environment the guest needs, so re-executing /proc/self/exe died in the loader. /proc/self/exe now maps to the real program on exec as it already does on open. A SIGSYS the program queues itself, or one from a filter for another architecture, went to the Android-filter emulation instead of the program's handler. * FEX: list only guest mappings in /proc/<pid>/maps on hosts below 47 address bits Credit the anti-cheat emulation source in the patch header. * Preloads: leave poll, ppoll and select buffers untouched when no emulated device is open A bad user pointer now reaches the kernel and returns EFAULT instead of crashing the caller inside the wrapper. * Emulate only host-architecture seccomp traps in the guest hook; report the calling thread's seccomp mode in FEX's /proc/self/status A SIGSYS carrying another architecture's seccomp siginfo now takes its default action when the program has no handler, so a process whose emulated filter traps a syscall while SIGSYS is blocked or ignored dies as on Linux. * FEX: read the host status file through the raw openat syscall * README: credit StonkGuy's FEX anti-cheat emulation * FEX: open the host status file with a direct system call so preloads cannot rewrite it * FEX: hand a traced program's ptrace state across exec * Credit StonkGuy in the FEX anti-cheat patches and README Co-authored-by: StonkGuy <68372320+StonkGuy@users.noreply.github.com> * FEX: open guest paths with the raw openat system call so host preloads cannot replace the file * FEX: serve emulated proc files by the requested path when the host returns a memfd * FEX: map fixed guest memory above a small host address space Co-authored-by: StonkGuy <StonkGuy@users.noreply.github.com> * FEX: serve decoder reads from fixed guest memory above the host limit * Run games with anti-cheat files on an x86-64 DroidDeck-Proton under FEX The Proton launchers look for Easy Anti-Cheat or BattlEye bridge files in the game folder and, when an x86-64 DroidDeck-Proton and the matching Proton runtime are installed, hand the launch to that Proton under FEX with the game's own prefix. Picking the x86-64 tool directly also runs it under FEX. DROIDDECK_ANTICHEAT=off keeps a game on ARM64. * Keep x86-64 DroidDeck-Proton builds out of the ARM64 tool list * droiddeck-fex: take the runtime from an adopted tool's original manifest * FEX: show the guest command line when the argument area cannot be remapped * FEX: describe the container's procfs in emulated mount tables * FEX: order the anti-cheat series after the guest stack patch from main * Test the container procfs view of FEX's emulated mount tables * Docs: describe the anti-cheat signal mask fix and the container procfs view * README: match the StonkGuy credit to the renumbered FEX patches * Keep anti-cheat games on a tool the user chose instead of moving them to x86-64 * test(game-env): build the adopted-tool wrapper through extra_wrapper_sh * Check anti-cheat runtime bridges, apply component choices under FEX and honour MAP_FIXED_NOREPLACE above the host limit * Check the driver query is answered before each wrapper's call sites * Keep x86-64 Proton builds out of the automatic default tool * Keep high guest mappings intact when a fixed map or unmap fails Check room in the region table, splits included, before a fixed map or unmap removes anything, return the host munmap error without touching the table entry, and keep write-protecting low shared aliases of executable ranges that sit above the host address limit. * Keep a requested x86-64 default and accept linked anti-cheat runtimes A request for the current automatic x86-64 default now marks it as the app's choice, so the next settle no longer moves it back to ARM64. Anti-cheat runtime discovery follows a symlinked runtime directory. * Route anti-cheat games to x86-64 Proton only on a capable FEX The FEX build now lists its patches in share/fex-emu/.droiddeck-patches. Anti-cheat routing needs the fixed guest memory patch in that list and otherwise keeps the launch on ARM64, as an older FEX cannot map the anti-cheat helper buffer above the host address limit. Installing a FEX build without the list removes a list left by an earlier build. * Update FEX before deciding anti-cheat routing A device on an older FEX build never went through droiddeck-fex on the ARM64 path, so the catalog FEX was never installed and the gate kept anti-cheat games on ARM64 forever. dd_anticheat now runs the new droiddeck-fex update action first, which installs the catalog build under the same lock and retry window as other FEX launches. * Leave MAP_FIXED_NOREPLACE above the host limit to the host Wine finds the top of the address space with MAP_FIXED_NOREPLACE probes. Claiming those probes above a 39-bit host limit made Wine place its stacks in relocated memory, and every wineserver request then failed with EFAULT because the iovec buffers it passes to writev are nested pointers that are not translated. Only MAP_FIXED requests are relocated again, so the probes see the real host limit while fixed mappings above it keep working. * Translate only pointer syscall arguments into high guest memory Pointer arguments are now picked from a per-syscall layout table, so scalar values such as a truncate length are never rewritten. Sized buffers must map to one contiguous host range or the call fails with EFAULT, and new host backings are placed next to their guest neighbours so adjacent mappings stay contiguous. readv, writev and the preadv/pwritev family, sendmsg and recvmsg get a host-side copy of their iovec and msghdr with translated bases, leaving the guest copies untouched. Code invalidation for kernel writes maps the host buffer back to its guest address, and an unmap checks the table before it changes any host mapping. * Claim high guest memory only with LSE atomics and invalidate every code alias High guest mappings are claimed only when the JIT emits LSE atomics, and exclusive load/store instructions are never single-stepped, so an atomic on high memory cannot spin. A store into high code invalidates every mirror of the written page through the tracked mapping. madvise and mprotect on high memory apply to each region at its own host address. * Reject wrapping lengths and drop stale code on discarded high memory A nonzero length that wraps when page-aligned now fails madvise with EINVAL and mprotect with ENOMEM, as on Linux. Discarding advice on high memory invalidates translated code for the range whenever advice reached any region. * Add an end-to-end probe for guest memory above the host address limit * Emulate exclusive pairs on high guest memory and release failed host unmaps later * Size counted guest buffers by element and keep exclusive access within guest protection poll, ppoll, epoll waits, mmsg calls and select bitmaps now translate the whole array their count describes, so a buffer that crosses into an unrelated host range fails with EFAULT and oversized counts cannot wrap. High regions remember their protection through mprotect, splitting at the range edges, and exclusive stores to read-only pages or loads from inaccessible pages reach the guest as a fault instead of being emulated. * Refuse a high unmap when failed host unmaps could not all be retained UnmapLocked counts the overlapping regions before it changes anything and returns ENOMEM when the retired list could not hold all of them, so a host range is never dropped from tracking while still mapped. * Serve memory trim requests while syscall user dispatch blocks A thread that runs with syscall user dispatch on and its selector set to block (as x86-64 Wine does while in Windows code) took the trim signal with the selector still blocking. Every raw syscall the handler made was then dispatched to the program's SIGSYS handler, which either deadlocked the thread or killed the process when SIGSYS was blocked, so the session saw it as a deaf process and the game stalled during loading. Track the selector each thread registers through prctl, allow syscalls for the length of the handler and restore the selector before returning. * Allow syscalls for a forwarded prctl while dispatch blocks The prctl wrapper issues its syscall from the preload's own text, so a thread whose selector blocks got SIGSYS where the plain libc call would have been dispatched the same way by the caller's own rules. Allow syscalls for the forwarded call and restore the selector afterwards. The dispatch test now waits until the selector blocks before it sends the trim request, and checks a prctl call made while it blocks. * Merge high regions after protection changes and translate message batches Protect now merges neighbouring high regions whose guest and host ranges touch and whose protection and code state match, so toggling page protections no longer fills the region table. Exclusive loads on high memory accept write-only pages and exclusive stores need only PROT_WRITE, matching x86-64 where writable pages are readable. sendmmsg and recvmmsg translate the name, control and io vectors of every message in the batch, return msg_len for each processed message and the received header fields for recvmmsg. Counted arrays passed to getgroups, setgroups, semop, semtimedop, io_submit, io_getevents, io_pgetevents, move_pages, futex_waitv and listmount are now checked to stay within one host range. The unused ToHost helper is removed. * Translate fixed-size, string and in-array guest pointers in high memory Give every syscall pointer without a length a fixed x86-64 size, a length read through another argument, or a terminator scan for strings, so spans crossing separately backed regions are refused before the kernel sees them. Size message queue buffers as the type word plus msgsz. Translate io_submit control blocks and their buffers, including vectored reads and writes, through bounded host copies, restore the guest words afterwards, and report guest iocb addresses back from io_getevents. Translate move_pages page lists for the calling process and futex_waitv addresses. Merge new mappings with matching neighbours. * Size high-memory syscall spans by kernel widths and embedded sizes Read counts with the width the kernel uses for each argument, so int and unsigned int counts ignore the upper register bits and negative counts reach the handler. Size capability data by its header version, perf and scheduler attributes, file handles and mount requests by their own size fields, and landlock rules by rule type. Keep the translated prefix of a message batch, read headers that span separate backings one by one, write results back through the current guest mapping, and stop counting messages whose length cannot be stored. Revisit an entry moved into an earlier slot while merging regions. Give newer syscalls fallback numbers in the test harness. * Send translated message batches one message at a time Submit sendmmsg batches that need scratch headers one message per call, storing each length before the next message goes out, so a length that cannot be stored stops the batch where Linux would. Skip the name length when no name was given and store flags before the control length. Check the whole fixed file-handle header even when its size is invalid. Hand capget and capset a private header so the checked data size matches the version the kernel reads, and return a rewritten version to the guest. Patch and restore AIO control blocks under the mapping lock and restore only the block that was patched. * Harden high-memory aio, capability and message batch write-backs Restore patched aio buffers through /proc/self/mem when the control block became read-only and keep the scratch vectors alive if that fails too, fault capability calls whose header write-back fails, stop send batches after a short message, and pin the batch socket with a private dup. * Pin batch sockets, fall back to whole batches and reconcile pending aio restores Follow-up message sends and the first dispatch share one duplicated socket. When it cannot be duplicated, the whole translated batch goes to the kernel in one call and lengths are written back up to the first one that cannot be stored. Short sends compare against the iovec lengths given to the kernel. Unrestorable aio_buf edits, including unreadable control blocks, keep their storage in a bounded list that later submissions reconcile. * Stop message batches at unreadable vectors, send singly without a spare descriptor and reserve aio restore slots A message whose iovec snapshot cannot be taken ends the prepared batch instead of being sent with an unknown length; when it is the first message the kernel handles the original array natively. When the batch socket cannot be duplicated, messages still go one at a time on the original descriptor with each length written before the next send. Pending aio restore slots are reserved under the pending mutex before the first guest edit and released or handed to the pending record, so concurrent submissions cannot exceed the bound. Tests use a real socket pair, injected descriptor exhaustion and concurrent reservations. * Send only the first message of a batch when the socket cannot be pinned * Replay high-memory faults over the whole access and reconcile aio restores on unmap * Keep high-memory traps ordered, fault-exact and locked against unmap Protect, Map and low mmap/munmap/mremap/mprotect reconcile pending aio restores at once, and io_submit reconciles them even when no high region is mapped. Ordered loads and stores split across backings are emulated between full fences instead of being byte-copied through the trampoline; atomics and exclusives are still refused. Gather and scatter use fault-safe copies, and a failing piece is re-faulted at the guest instruction through a probe load, with SIGBUS redelivered the same way. The VMA lock is held from planning until the scatter finishes, so unmap and protect cannot race a resumed access. Sign-extending loads are no longer classified as writes. * Defer user signals while guest high memory mappings are held Only the trampoline breakpoint completes a replay, user-sent SIGSEGV, SIGBUS and SIGTRAP raised while the mapping lock is held are requeued after it is released, and stranded control block words are restored when their page turns readable again. The harness now runs under a timeout. * Rebase the FEX patch series onto FEX-2612 * FEX: restore stranded aio words before readable protection, report failures Restore every pending aio word in the range before a readable guest protection is applied, on both the high and low paths, and fail the guest mprotect with the old protection kept when a word cannot be restored or its window cannot be closed. Ignore user-sent SIGSEGV/SIGBUS after deferral, read the cleared syscall info when resuming with guest GPRs and on restore, and check exclusive acquisition from a separate thread in the harness. * FEX: submit aio control blocks through private host copies Stop editing guest IOCBs in place when aio_buf needs translation. io_submit now hands the kernel a host copy of each such control block, maps io_event.obj back to the guest pointer when the completion is reaped, redirects io_cancel by guest pointer and context to the copy, and frees copies on reap, on io_destroy, or when the kernel did not accept them. The guest control block is never patched and its protection is never touched, so the pending restore records, the protection windows and the restore hooks in mmap, munmap, mremap and mprotect are removed with their tests. * fex: keep aio keys, cancels and reaped events native for copied control blocks Guest aio_key is no longer cleared before dispatch: the slot is probed with a same-value write and only the first n accepted copies get key 0 after the host io_submit returns n. io_cancel redirects to a copy only when the guest block is readable and its key is 0, so unreadable blocks fault in the kernel as before. io_getevents and io_pgetevents reap into emulator storage, translate and release copies there, then copy the events out, returning -EFAULT if that fails. A successful io_setup clears the ring header magic so userspace ring reapers fall back to io_getevents, where copies are translated and released. * fex: leave aio rejections, keys and unwritable event buffers to the kernel A copied control block whose key slot is read-only is now passed to the kernel as the guest's own block at the end of the list, so the kernel reports its native fd, eventfd or key error. After io_submit, guest keys follow the private copies through the first rejected position, and they are stored through a fresh translation of the guest address, skipped when it no longer maps. io_getevents and io_pgetevents probe the guest event buffer and reap at most its writable prefix, handing an unwritable buffer to the kernel so completions are not consumed. * Kept AIO completions and key stores stable against sibling remaps Wrapped event buffers go to the kernel unchanged. Direct reaps report guest control blocks and release copies only after the store lands. Guest stores and reads hold the mapping lock across translation and copy. Completions whose copy-out fails are stashed per context and delivered first on the next reap, and dropped on io_destroy. * fex: stage every AIO reap and keep stashed completions recoverable Hold the guest mapping for every high address, restore the caller's signal mask after thread-context holds, replace the fixed event stash with a per-context table that reserves space before dispatch, stage all reaps so control block identities are translated before copy-out, keep collecting ready completions once the stash meets min_nr, and restash events on every error except an interrupted delivery or a destroyed context. * fex: own AIO recovery storage before dispatch and bind it to the context lifetime Allocate the recovery node with the event buffer before the kernel consumes completions and hand the buffer itself to the stash when copy-out fails, so settling never allocates. Track each context by a generation that io_setup advances, so a destroy that finishes after a replacement context reuses the ring address only releases the old context's copies and stash. Drop the reservation cap so blocking reaps keep their min_nr. * fex: publish AIO contexts from private storage, keep their generation, wake blocked reapers for stashed completions * fex: wait for AIO events in bounded slices instead of wake markers, roll back setup by its own generation, fault unreadable io_setup output Blocked reapers wait in the kernel for at most 20 ms at a time and take stashed completions between waits until the guest minimum or timeout is met, so no eventfd or io_submit notification is needed. Deferred signals end the wait like EINTR. io_setup rollback uses the generation BeginContext installed, and an unreadable context output returns -EFAULT before dispatch. --------- Co-authored-by: StonkGuy <68372320+StonkGuy@users.noreply.github.com> Co-authored-by: StonkGuy <StonkGuy@users.noreply.github.com>
1561 lines
65 KiB
C
1561 lines
65 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).
|
|
//
|
|
// execve() and posix_spawn(): rootfs programs through ld.so with the hook, scripts through their
|
|
// interpreter, Android programs with Android's environment.
|
|
|
|
#ifndef DDNATV_HOST_TEST
|
|
|
|
// Runs before every exec, mostly in a child a shell has just forked: the copies write only the
|
|
// string (ddnatv_copy_cstr), not the whole PATH_MAX buffer, since each page written there is a
|
|
// copy-on-write fault.
|
|
static int follow_link(const char *path, char *target, size_t size) {
|
|
ssize_t len = readlink(path, target, size - 1);
|
|
if (len < 0) return 0;
|
|
target[len] = '\0';
|
|
// proot's link2symlink leaves hard links as ".l2s.*" files that programs must not see by name
|
|
const char *base = strrchr(target, '/');
|
|
return strncmp(base ? base + 1 : target, ".l2s.", 5) != 0;
|
|
}
|
|
|
|
static void resolve_symlinks(const char *path, char *out, size_t out_size, int depth) {
|
|
if (!path || !out || out_size == 0) return;
|
|
ddnatv_copy_cstr(out, out_size, path);
|
|
if (depth > 8) return;
|
|
char link_target[PATH_MAX];
|
|
char next_path[PATH_MAX];
|
|
if (g_ddnatv_root_len > 0 && strncmp(path, g_ddnatv_root, g_ddnatv_root_len) == 0 && path[g_ddnatv_root_len] == '/') {
|
|
char done[PATH_MAX];
|
|
char todo[PATH_MAX];
|
|
size_t used = ddnatv_append(done, sizeof(done), 0, g_ddnatv_root, g_ddnatv_root_len);
|
|
ddnatv_copy_cstr(todo, sizeof(todo), path + g_ddnatv_root_len);
|
|
int links = 0;
|
|
char *rest = todo;
|
|
while (*rest) {
|
|
while (*rest == '/') rest++;
|
|
if (!*rest) break;
|
|
char *end = strchr(rest, '/');
|
|
size_t n = end ? (size_t)(end - rest) : strlen(rest);
|
|
if (n == 1 && rest[0] == '.') {
|
|
rest += n;
|
|
continue;
|
|
}
|
|
if (n == 2 && rest[0] == '.' && rest[1] == '.') {
|
|
char *slash = strrchr(done + g_ddnatv_root_len, '/');
|
|
if (slash) used = (size_t)(slash - done);
|
|
done[used] = '\0';
|
|
rest += n;
|
|
continue;
|
|
}
|
|
size_t before = used;
|
|
used = ddnatv_append(done, sizeof(done), used, "/", 1);
|
|
used = ddnatv_append(done, sizeof(done), used, rest, n);
|
|
rest += n;
|
|
if (used >= sizeof(done) - 1) return;
|
|
if (!follow_link(done, link_target, sizeof(link_target))) {
|
|
struct stat st;
|
|
if (*rest && (syscall(SYS_newfstatat, AT_FDCWD, done, &st, 0) != 0 || !S_ISDIR(st.st_mode))) return;
|
|
continue;
|
|
}
|
|
if (++links > 40) return;
|
|
size_t m = ddnatv_append(next_path, sizeof(next_path), 0, link_target, strlen(link_target));
|
|
m = ddnatv_append(next_path, sizeof(next_path), m, rest, strlen(rest));
|
|
if (m >= sizeof(next_path) - 1) return;
|
|
if (link_target[0] == '/') {
|
|
char rw_buf[PATH_MAX];
|
|
resolve_symlinks(rewrite_path(next_path, rw_buf, sizeof(rw_buf)), out, out_size, depth + 1);
|
|
return;
|
|
}
|
|
used = before;
|
|
done[used] = '\0';
|
|
ddnatv_copy_cstr(todo, sizeof(todo), next_path);
|
|
rest = todo;
|
|
}
|
|
if (used > g_ddnatv_root_len) ddnatv_copy_cstr(out, out_size, done);
|
|
return;
|
|
}
|
|
if (!follow_link(path, link_target, sizeof(link_target))) return;
|
|
if (link_target[0] == '/') {
|
|
char rw_buf[PATH_MAX];
|
|
const char *rewritten = rewrite_path(link_target, rw_buf, sizeof(rw_buf));
|
|
ddnatv_copy_cstr(next_path, sizeof(next_path), rewritten);
|
|
} else {
|
|
const char *slash = strrchr(path, '/');
|
|
if (slash) {
|
|
size_t dir_len = (size_t)(slash - path);
|
|
if (dir_len > sizeof(next_path) - 1) dir_len = sizeof(next_path) - 1;
|
|
memcpy(next_path, path, dir_len);
|
|
next_path[dir_len] = '\0';
|
|
size_t n = ddnatv_append(next_path, sizeof(next_path), dir_len, "/", 1);
|
|
ddnatv_append(next_path, sizeof(next_path), n, link_target, strlen(link_target));
|
|
} else {
|
|
ddnatv_copy_cstr(next_path, sizeof(next_path), link_target);
|
|
}
|
|
}
|
|
resolve_symlinks(next_path, out, out_size, depth + 1);
|
|
}
|
|
|
|
static char **ensure_hook_in_envp(char *const envp[], const char *real_exe, const char *lib_path) {
|
|
return prepare_ddnatv_env(envp, real_exe, lib_path);
|
|
}
|
|
|
|
// The file whose header decides how to start `target`: the symlink-resolved ELF (so ld.so and
|
|
// /proc/self/exe see the real program, as with the kernel), else `target` itself (scripts,
|
|
// links to ld.so). `probe` describes the returned file.
|
|
static const char *select_exec_target(const char *target, char *resolved, size_t resolved_size, struct exec_probe *probe) {
|
|
resolve_symlinks(target, resolved, resolved_size, 0);
|
|
probe_exec_file(resolved, probe);
|
|
if (probe->is_elf && !is_ld_linux(resolved)) return resolved;
|
|
if (strcmp(resolved, target) != 0) probe_exec_file(target, probe);
|
|
return target;
|
|
}
|
|
|
|
// The library children get with --preload: the one this process runs from, so that a program
|
|
// always starts with the same build as its parent, else the first of usr/lib and lib that exists;
|
|
// NULL if neither does.
|
|
// The path dladdr() finds is kept (it does not change): set once, read by every later exec, and
|
|
// set before a fork by prepare_exec_in_parent() so that the children only read it.
|
|
static char g_hook_library[PATH_MAX];
|
|
static int g_hook_library_known = 0;
|
|
|
|
static const char *ddnatv_hook_library(char *buf, size_t bufsz) {
|
|
static const char usr_lib[] = "/usr/lib/libddnatv-hook.so";
|
|
static const char lib[] = "/lib/libddnatv-hook.so";
|
|
if (__atomic_load_n(&g_hook_library_known, __ATOMIC_ACQUIRE)) return g_hook_library;
|
|
Dl_info info;
|
|
if (dladdr((void *)ddnatv_hook_library, &info) && info.dli_fname && info.dli_fname[0] == '/' &&
|
|
strlen(info.dli_fname) < sizeof(g_hook_library)) {
|
|
// loaded from there, so it exists
|
|
ddnatv_copy_cstr(g_hook_library, sizeof(g_hook_library), info.dli_fname);
|
|
__atomic_store_n(&g_hook_library_known, 1, __ATOMIC_RELEASE);
|
|
return g_hook_library;
|
|
}
|
|
size_t n = ddnatv_append(buf, bufsz, 0, g_ddnatv_root, g_ddnatv_root_len);
|
|
ddnatv_append(buf, bufsz, n, usr_lib, sizeof(usr_lib) - 1);
|
|
if (access(buf, F_OK) == 0) return buf;
|
|
n = ddnatv_append(buf, bufsz, 0, g_ddnatv_root, g_ddnatv_root_len);
|
|
ddnatv_append(buf, bufsz, n, lib, sizeof(lib) - 1);
|
|
return access(buf, F_OK) == 0 ? buf : NULL;
|
|
}
|
|
|
|
// ld.so does not need the exec bit on the program it loads, but other tools look at it: set
|
|
// it as the old access(X_OK)/chmod() pair did, using the mode the probe already has.
|
|
static void ensure_exec_bit(const char *path, mode_t mode) {
|
|
if (S_ISDIR(mode) || (mode & 0111) != 0) return;
|
|
if (strstr(path, "/bin/") || strstr(path, "/sbin/")) return;
|
|
chmod(path, 0755);
|
|
}
|
|
|
|
// Rootfs path of a "#!" interpreter; a missing /bin/sh falls back to Android's shell.
|
|
static const char *shebang_interpreter(const char *interp, char *buf, size_t bufsz) {
|
|
const char *rewritten = rewrite_path(interp, buf, bufsz);
|
|
if (strcmp(interp, "/bin/sh") == 0 && access(rewritten, F_OK) != 0 && access("/system/bin/sh", X_OK) == 0) {
|
|
return "/system/bin/sh";
|
|
}
|
|
return rewritten;
|
|
}
|
|
|
|
static const char *exec_prog_name(const char *target) {
|
|
const char *slash = strrchr(target, '/');
|
|
return slash ? slash + 1 : target;
|
|
}
|
|
|
|
// Hook execve
|
|
typedef int (*orig_execve_f_type)(const char *filename, char *const argv[], char *const envp[]);
|
|
|
|
// glibc's execve(), looked up once (also by prepare_exec_in_parent() before a fork)
|
|
static orig_execve_f_type g_orig_execve = NULL;
|
|
|
|
static orig_execve_f_type real_execve(void) {
|
|
orig_execve_f_type f = __atomic_load_n(&g_orig_execve, __ATOMIC_RELAXED);
|
|
if (!f) {
|
|
f = (orig_execve_f_type)dlsym(RTLD_NEXT, "execve");
|
|
__atomic_store_n(&g_orig_execve, f, __ATOMIC_RELAXED);
|
|
}
|
|
return f;
|
|
}
|
|
|
|
// prepare_exec_in_parent() rehearses an exec in the parent: everything up to the execve() itself,
|
|
// which this then skips. Only in the thread that rehearses: another thread's exec at that moment
|
|
// is a real one.
|
|
static int g_exec_rehearsal = 0;
|
|
static pthread_t g_exec_rehearsal_thread;
|
|
|
|
static int in_exec_rehearsal(void) {
|
|
return __atomic_load_n(&g_exec_rehearsal, __ATOMIC_ACQUIRE) &&
|
|
pthread_equal(pthread_self(), g_exec_rehearsal_thread);
|
|
}
|
|
|
|
// Android's own programs, and the app's extracted libraries, may still be executed directly.
|
|
static int exec_directly(const char *path) {
|
|
static const char *const prefixes[] = {"/system/", "/vendor/", "/apex/", "/product/", "/odm/", "/system_ext/", "/data/app/"};
|
|
if (g_exec_loader[0] == '\0' || !path || path[0] != '/' || strcmp(path, g_exec_loader) == 0) return 1;
|
|
for (size_t i = 0; i < sizeof(prefixes) / sizeof(prefixes[0]); i++)
|
|
if (strncmp(path, prefixes[i], strlen(prefixes[i])) == 0) return 1;
|
|
return 0;
|
|
}
|
|
|
|
// ENOENT when the program names a dynamic linker that is not there (a glibc program's
|
|
// "/lib/ld-linux-aarch64.so.1" on Android), as the kernel answers: callers try another way.
|
|
static int exec_interp_missing(int fd) {
|
|
Elf64_Ehdr eh;
|
|
if (syscall(SYS_pread64, fd, &eh, sizeof(eh), 0) != (long)sizeof(eh) || eh.e_ident[EI_CLASS] != ELFCLASS64 ||
|
|
eh.e_machine != EM_AARCH64 || (eh.e_type != ET_EXEC && eh.e_type != ET_DYN) ||
|
|
eh.e_phentsize != sizeof(Elf64_Phdr) || eh.e_phnum == 0 || eh.e_phnum > 64)
|
|
return ENOEXEC;
|
|
for (int i = 0; i < eh.e_phnum; i++) {
|
|
Elf64_Phdr ph;
|
|
if (syscall(SYS_pread64, fd, &ph, sizeof(ph), (long)(eh.e_phoff + (Elf64_Off)i * sizeof(ph))) != (long)sizeof(ph))
|
|
return ENOEXEC;
|
|
if (ph.p_type != PT_INTERP) continue;
|
|
char interp[PATH_MAX];
|
|
if (ph.p_filesz == 0 || ph.p_filesz >= sizeof(interp) ||
|
|
syscall(SYS_pread64, fd, interp, ph.p_filesz, (long)ph.p_offset) != (long)ph.p_filesz)
|
|
return ENOEXEC;
|
|
interp[ph.p_filesz] = 0;
|
|
int ifd = (int)call_orig_syscall(SYS_openat, AT_FDCWD, (unsigned long)interp, O_RDONLY | O_CLOEXEC | O_NONBLOCK, 0, 0, 0);
|
|
if (ifd < 0) return errno;
|
|
syscall(SYS_close, ifd);
|
|
return 0;
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
// The errors execve() itself would give for [path], which the loader cannot report once it runs:
|
|
// a shell walking $PATH moves on at ENOENT and EACCES, and runs a file without "#!" as a script at
|
|
// ENOEXEC.
|
|
static int exec_preflight(const char *path) {
|
|
int fd = (int)call_orig_syscall(SYS_openat, AT_FDCWD, (unsigned long)path, O_RDONLY | O_CLOEXEC | O_NONBLOCK, 0, 0, 0);
|
|
if (fd < 0) return errno;
|
|
struct stat st;
|
|
int err = 0;
|
|
unsigned char magic[4];
|
|
if (syscall(SYS_fstat, fd, &st) != 0) err = errno;
|
|
else if (!S_ISREG(st.st_mode)) err = EACCES;
|
|
else if (syscall(SYS_faccessat, AT_FDCWD, path, X_OK, 0) != 0) err = EACCES;
|
|
else if (syscall(SYS_read, fd, magic, 2) == 2 && magic[0] == '#' && magic[1] == '!') err = -1;
|
|
else if (syscall(SYS_pread64, fd, magic, sizeof(magic), 0) != (long)sizeof(magic) ||
|
|
magic[0] != 0x7f || magic[1] != 'E' || magic[2] != 'L' || magic[3] != 'F') err = ENOEXEC;
|
|
else err = exec_interp_missing(fd);
|
|
syscall(SYS_close, fd);
|
|
return err;
|
|
}
|
|
|
|
// "libddexec.so <path> <argv...>"; NULL when [path] is executed directly, as a "#!" script the
|
|
// kernel hands to its interpreter is. *err is set when the exec would fail.
|
|
static char **loader_argv(const char *path, char *const argv[], int *err) {
|
|
*err = 0;
|
|
if (exec_directly(path)) return NULL;
|
|
int preflight = exec_preflight(path);
|
|
if (preflight == -1) return NULL;
|
|
*err = preflight;
|
|
if (*err) return NULL;
|
|
int argc = 0;
|
|
while (argv && argv[argc]) argc++;
|
|
char **out = (char **)malloc(sizeof(char *) * (size_t)(argc + 4));
|
|
if (!out) {
|
|
*err = ENOMEM;
|
|
return NULL;
|
|
}
|
|
out[0] = g_exec_loader;
|
|
out[1] = (char *)path;
|
|
int n = 2;
|
|
if (argc == 0) out[n++] = (char *)path;
|
|
for (int i = 0; i < argc; i++) out[n++] = argv[i];
|
|
out[n] = NULL;
|
|
return out;
|
|
}
|
|
|
|
static int run_execve(orig_execve_f_type f, const char *path, char *const argv[], char *const envp[]) {
|
|
if (in_exec_rehearsal()) {
|
|
errno = 0;
|
|
return 0;
|
|
}
|
|
int err;
|
|
char **via = loader_argv(path, argv, &err);
|
|
if (err) {
|
|
errno = err;
|
|
return -1;
|
|
}
|
|
if (!via) return f(path, argv, envp);
|
|
int ret = f(g_exec_loader, via, envp);
|
|
int saved_errno = errno;
|
|
free(via);
|
|
errno = saved_errno;
|
|
return ret;
|
|
}
|
|
|
|
// ldconfig does nothing in The native userland (its cache is for paths that ld.so opens without the hook), but the
|
|
// exec code reads /etc/ld.so.conf(.d) again when /etc/ld.so.cache changes: "sudo ldconfig" after an
|
|
// edit of a .conf file marks it changed, as the real ldconfig would by writing it. A cache asked
|
|
// for with -C is made (empty): Flatpak mounts the one it generates over /etc/ld.so.cache.
|
|
static void ldconfig_mark_cache(char *const argv[]) {
|
|
if (g_ddnatv_root[0] == '\0') return;
|
|
char path[PATH_MAX];
|
|
const char *cache = NULL;
|
|
for (int i = 1; argv && argv[i]; i++) {
|
|
if (strcmp(argv[i], "-C") == 0 && argv[i + 1]) cache = argv[++i];
|
|
else if (strncmp(argv[i], "-C", 2) == 0 && argv[i][2] != '\0') cache = argv[i] + 2;
|
|
}
|
|
const char *target = path;
|
|
if (cache) {
|
|
target = rewrite_path_in_root(cache, path, sizeof(path));
|
|
} else {
|
|
size_t n = ddnatv_append(path, sizeof(path), 0, g_ddnatv_root, g_ddnatv_root_len);
|
|
ddnatv_append(path, sizeof(path), n, "/etc/ld.so.cache", 16);
|
|
}
|
|
int fd = (int)syscall(SYS_openat, AT_FDCWD, target, O_WRONLY | O_CREAT | O_CLOEXEC, 0644);
|
|
if (fd < 0) return;
|
|
syscall(SYS_utimensat, fd, NULL, NULL, 0);
|
|
syscall(SYS_close, fd);
|
|
}
|
|
|
|
static int is_ldconfig_name(const char *name) {
|
|
return strcmp(name, "ldconfig") == 0 || strcmp(name, "ldconfig.real") == 0;
|
|
}
|
|
|
|
struct ldso_direct {
|
|
char prog[PATH_MAX];
|
|
char lib_path[PATH_MAX * 6];
|
|
};
|
|
|
|
// ld.so started directly (ldd, "ld.so --list PROGRAM", "ld.so PROGRAM"): the program it loads
|
|
// gets the --library-path a start of its own gets, or ldd reports its libraries as not found,
|
|
// and its path mapped into the rootfs, since ld.so opens it without the hook
|
|
static char **ldso_direct_argv(char *const argv[], char *const envp[], struct ldso_direct *buf, int *err) {
|
|
*err = 0;
|
|
int caller_lib_path = 0;
|
|
int pi = ldso_program_index(argv, &caller_lib_path);
|
|
if (pi <= 0) return NULL;
|
|
int argc = 0;
|
|
while (argv[argc]) argc++;
|
|
const char *prog = argv[pi];
|
|
if (caller_lib_path) {
|
|
// the caller's own --library-path stays as it is; only the program is mapped (when it is
|
|
// in the rootfs: a caller can also name a file by its real path)
|
|
if (prog[0] == '/') {
|
|
const char *mapped = rewrite_path(prog, buf->prog, sizeof(buf->prog));
|
|
int fd = mapped != prog ? (int)syscall(SYS_openat, AT_FDCWD, mapped, O_PATH | O_CLOEXEC) : -1;
|
|
if (fd >= 0) {
|
|
syscall(SYS_close, fd);
|
|
prog = mapped;
|
|
}
|
|
}
|
|
char **out = (char **)malloc(sizeof(char *) * (size_t)(argc + 1));
|
|
if (!out) {
|
|
*err = ENOMEM;
|
|
return NULL;
|
|
}
|
|
for (int i = 0; i <= argc; i++) out[i] = argv[i];
|
|
out[pi] = (char *)prog;
|
|
return out;
|
|
}
|
|
if (prog[0] == '/') prog = rewrite_path(prog, buf->prog, sizeof(buf->prog));
|
|
struct exec_probe prog_probe;
|
|
probe_exec_file(prog, &prog_probe);
|
|
build_ld_library_path(envp, prog_probe.runpath, prog_probe.runpath_is_rpath,
|
|
prog[0] == '/' ? prog : NULL, buf->lib_path, sizeof(buf->lib_path));
|
|
char **out = (char **)malloc(sizeof(char *) * (size_t)(argc + 3));
|
|
if (!out) {
|
|
*err = ENOMEM;
|
|
return NULL;
|
|
}
|
|
out[0] = argv[0];
|
|
out[1] = (char *)"--library-path";
|
|
out[2] = buf->lib_path;
|
|
for (int i = 1; i <= argc; i++) out[i + 2] = argv[i];
|
|
out[pi + 2] = (char *)prog; // ld.so opens it itself: "ldd /usr/bin/adb" as well
|
|
return out;
|
|
}
|
|
|
|
static int ddnatv_execve(const char *filename, char *const argv[], char *const envp[], int depth) {
|
|
orig_execve_f_type orig_execve = real_execve();
|
|
if (!orig_execve) {
|
|
errno = ENOSYS;
|
|
return -1;
|
|
}
|
|
if (is_proc_self_exe(filename) && g_real_exe[0] != '\0') filename = g_real_exe;
|
|
if (depth == 0 && !in_exec_rehearsal()) ddh_try(filename, argv, envp);
|
|
|
|
// Scripts get the path exactly as the caller wrote it ("./x.sh" stays "./x.sh" in $0),
|
|
// like the kernel would pass it; routing below uses the absolute form.
|
|
const char *caller_path = filename;
|
|
char abs_buf[PATH_MAX];
|
|
filename = absolutize_exec_path(filename, abs_buf, sizeof(abs_buf));
|
|
|
|
char buf[PATH_MAX];
|
|
const char *target = rewrite_path(filename, buf, sizeof(buf));
|
|
|
|
init_ddnatv_hook();
|
|
|
|
const char *f_base = (filename != NULL) ? strrchr(filename, '/') : NULL;
|
|
f_base = (f_base != NULL) ? f_base + 1 : (filename != NULL ? filename : "");
|
|
|
|
const char *prog_name = strrchr(target, '/');
|
|
prog_name = (prog_name != NULL) ? prog_name + 1 : target;
|
|
|
|
// Wine's preloader is a static program that opens the program and the dynamic linker it loads with
|
|
// system calls of its own, which no hook can map, to reserve address ranges before the linker runs.
|
|
// The program is started without it: its libc and ntdll reserve what Wine needs themselves.
|
|
if ((strcmp(prog_name, "wine-preloader") == 0 || strcmp(prog_name, "wine64-preloader") == 0) &&
|
|
argv && argv[0] && argv[1] && depth < DDNATV_MAX_SHEBANG_DEPTH) {
|
|
return ddnatv_execve(argv[1], argv + 1, envp, depth + 1);
|
|
}
|
|
|
|
// Intercept utilities that fail or cause issues in unprivileged Android environment
|
|
if (strcmp(f_base, "ldconfig") == 0 ||
|
|
strcmp(f_base, "ldconfig.real") == 0 ||
|
|
strcmp(f_base, "systemd-machine-id-setup") == 0 ||
|
|
strcmp(f_base, "systemd-sysusers") == 0 ||
|
|
strcmp(f_base, "systemd-tmpfiles") == 0 ||
|
|
strcmp(f_base, "start-stop-daemon") == 0 ||
|
|
strcmp(f_base, "mandb") == 0 ||
|
|
strcmp(f_base, "mandb.real") == 0 ||
|
|
strcmp(f_base, "update-mime-database") == 0 ||
|
|
strcmp(f_base, "update-desktop-database") == 0 ||
|
|
strcmp(f_base, "install-info") == 0 ||
|
|
strcmp(f_base, "install-sgmlcatalog") == 0 ||
|
|
strcmp(prog_name, "ldconfig") == 0 ||
|
|
strcmp(prog_name, "ldconfig.real") == 0 ||
|
|
strcmp(prog_name, "systemd-machine-id-setup") == 0 ||
|
|
strcmp(prog_name, "systemd-sysusers") == 0 ||
|
|
strcmp(prog_name, "systemd-tmpfiles") == 0 ||
|
|
strcmp(prog_name, "start-stop-daemon") == 0 ||
|
|
strcmp(prog_name, "mandb") == 0 ||
|
|
strcmp(prog_name, "mandb.real") == 0 ||
|
|
strcmp(prog_name, "update-mime-database") == 0 ||
|
|
strcmp(prog_name, "update-desktop-database") == 0 ||
|
|
strcmp(prog_name, "install-info") == 0 ||
|
|
strcmp(prog_name, "install-sgmlcatalog") == 0) {
|
|
if (is_ldconfig_name(f_base) || is_ldconfig_name(prog_name)) ldconfig_mark_cache(argv);
|
|
_exit(0);
|
|
}
|
|
if (strcmp(f_base, "mountpoint") == 0 || strcmp(prog_name, "mountpoint") == 0) {
|
|
int is_virtual_fs = 0;
|
|
for (int i = 1; argv && argv[i]; i++) {
|
|
if (strcmp(argv[i], "/proc") == 0 || strcmp(argv[i], "/proc/") == 0 ||
|
|
strcmp(argv[i], "/sys") == 0 || strcmp(argv[i], "/sys/") == 0 ||
|
|
strcmp(argv[i], "/dev") == 0 || strcmp(argv[i], "/dev/") == 0 ||
|
|
strcmp(argv[i], "/dev/pts") == 0) {
|
|
is_virtual_fs = 1;
|
|
break;
|
|
}
|
|
}
|
|
if (is_virtual_fs) {
|
|
_exit(0);
|
|
}
|
|
}
|
|
if (strcmp(f_base, "policy-rc.d") == 0 || strcmp(prog_name, "policy-rc.d") == 0) {
|
|
_exit(101);
|
|
}
|
|
|
|
// A static program inside the rootfs, to be made safe to start (prepare_static_program)
|
|
const char *static_elf = NULL;
|
|
char resolved_target[PATH_MAX];
|
|
|
|
// Only intercept binaries/scripts within DDNATV_ROOT
|
|
if ((g_ddnatv_root[0] != '\0' && strncmp(target, g_ddnatv_root, g_ddnatv_root_len) == 0) || is_mapped_guest_path(filename) ||
|
|
is_bound_guest_program(target)) {
|
|
struct exec_probe probe;
|
|
const char *elf_target = select_exec_target(target, resolved_target, sizeof(resolved_target), &probe);
|
|
if (probe.is_elf && !probe.is_dynamic) static_elf = elf_target;
|
|
// A Go program built for Android asks for Android's linker, so it is started like the dynamic
|
|
// ones, but it makes its own system calls: it gets the code of the static Go programs (#42)
|
|
if (probe.is_dynamic) prepare_static_program_ex(elf_target, 1);
|
|
|
|
// 1. Transparently route dynamically linked glibc ELF binaries through ld.so
|
|
// Note: Statically linked binaries (PT_INTERP absent, e.g. Meta Muse Code) must execute directly!
|
|
if (probe.is_dynamic) {
|
|
char ld_so[PATH_MAX];
|
|
ld_so[0] = '\0';
|
|
if (find_dynamic_linker_for_machine(g_ddnatv_root, probe.e_machine, ld_so, sizeof(ld_so)) && strcmp(elf_target, ld_so) != 0) {
|
|
ensure_exec_bit(elf_target, probe.mode);
|
|
|
|
if (!in_exec_rehearsal()) ddnatv_copy_cstr(g_real_exe, sizeof(g_real_exe), elf_target);
|
|
|
|
char hook_buf[PATH_MAX];
|
|
const char *hook_so = ddnatv_hook_library(hook_buf, sizeof(hook_buf));
|
|
char ld_lib_path[PATH_MAX * 6];
|
|
build_ld_library_path(envp, probe.runpath, probe.runpath_is_rpath, elf_target, ld_lib_path, sizeof(ld_lib_path));
|
|
char **new_argv = build_ldso_argv(ld_so, hook_so, ld_lib_path, elf_target, exec_prog_name(target), argv);
|
|
if (!new_argv) {
|
|
errno = ENOMEM;
|
|
return -1;
|
|
}
|
|
char **new_env = ensure_hook_in_envp(envp, elf_target, ld_lib_path);
|
|
int ret = run_execve(orig_execve, ld_so, new_argv, new_env);
|
|
if (errno == EACCES && chmod(ld_so, 0755) == 0) {
|
|
// ld.so without its exec bit (an unusual restore): fix it once and retry
|
|
ret = run_execve(orig_execve, ld_so, new_argv, new_env);
|
|
}
|
|
int saved_errno = errno;
|
|
free(new_argv);
|
|
free_modified_env(new_env, envp);
|
|
errno = saved_errno;
|
|
return ret;
|
|
}
|
|
}
|
|
|
|
if (probe.is_elf && !probe.is_dynamic && is_ld_linux(elf_target)) {
|
|
struct ldso_direct direct;
|
|
int err;
|
|
char **new_argv = ldso_direct_argv(argv, envp, &direct, &err);
|
|
if (err) {
|
|
errno = err;
|
|
return -1;
|
|
}
|
|
if (new_argv) {
|
|
prepare_static_program(static_elf); // ld.so is a static program itself
|
|
char **ddnatv_env = prepare_ddnatv_env(envp, target, NULL);
|
|
int ret = run_execve(orig_execve, target, new_argv, ddnatv_env);
|
|
int saved_errno = errno;
|
|
free_modified_env(ddnatv_env, envp);
|
|
free(new_argv);
|
|
errno = saved_errno;
|
|
return ret;
|
|
}
|
|
}
|
|
|
|
// 2. Handle scripts with shebang lines (e.g., #!/bin/sh, #!/usr/bin/perl)
|
|
if (!probe.is_elf && probe.n >= 2 && probe.hdr[0] == '#' && probe.hdr[1] == '!') {
|
|
char *interp;
|
|
char *interp_arg;
|
|
parse_shebang(probe.hdr, &interp, &interp_arg);
|
|
char interp_buf[PATH_MAX];
|
|
const char *rewritten_interp = shebang_interpreter(interp, interp_buf, sizeof(interp_buf));
|
|
const char *script = (caller_path && caller_path[0] != '/') ? caller_path : target;
|
|
char **new_argv = build_script_argv(rewritten_interp, interp_arg, script, argv);
|
|
if (!new_argv) {
|
|
errno = ENOMEM;
|
|
return -1;
|
|
}
|
|
int ret;
|
|
if (is_host_interpreter(interp, rewritten_interp)) {
|
|
char **sys_env = clean_env_for_system(envp);
|
|
ret = run_execve(orig_execve, rewritten_interp, new_argv, sys_env);
|
|
int saved_errno = errno;
|
|
free_modified_env(sys_env, envp);
|
|
errno = saved_errno;
|
|
} else if (depth >= DDNATV_MAX_SHEBANG_DEPTH) {
|
|
errno = ELOOP;
|
|
ret = -1;
|
|
} else {
|
|
// The interpreter's exec prepares the environment, as posix_spawn's does: done here
|
|
// too, it dropped DDNATV_BECOME before the interpreter could take it (sudo SCRIPT)
|
|
ret = ddnatv_execve(rewritten_interp, new_argv, envp, depth + 1);
|
|
}
|
|
free(new_argv);
|
|
return ret;
|
|
}
|
|
} else {
|
|
// Any binary outside DDNATV_ROOT is an Android host binary (e.g. /system/bin/su, /sbin/su, /data/adb/...)
|
|
char **sys_env = clean_env_for_system(envp);
|
|
int ret = run_execve(orig_execve, target, argv, sys_env);
|
|
int saved_errno = errno;
|
|
free_modified_env(sys_env, envp);
|
|
errno = saved_errno;
|
|
return ret;
|
|
}
|
|
|
|
if (static_elf) prepare_static_program(static_elf);
|
|
char **ddnatv_env = prepare_ddnatv_env(envp, target, NULL);
|
|
int ret = run_execve(orig_execve, target, argv, ddnatv_env);
|
|
int saved_errno = errno;
|
|
free_modified_env(ddnatv_env, envp);
|
|
errno = saved_errno;
|
|
return ret;
|
|
}
|
|
|
|
int execve(const char *filename, char *const argv[], char *const envp[]) {
|
|
return ddnatv_execve(filename, argv, envp, 0);
|
|
}
|
|
|
|
// ---- fork() ---------------------------------------------------------------------------------
|
|
// A shell (and make, dpkg, perl, ...) starts a program with fork() and then execve() in the child.
|
|
// What the exec code above needs for the first time in a process (glibc's execve, fstat and readlink
|
|
// behind the hooks, the rootfs' ld.so, the path of this library) it found in the child, where every
|
|
// page it writes is a copy of the parent's: some 40 copy-on-write faults before each program even
|
|
// started, where a shell's child without the hook has fewer than ten. Now the parent finds them at
|
|
// its first fork(), and the children inherit them and only read them. At its eighth fork() the
|
|
// parent also rehearses an exec (everything but the execve() itself), which binds the calls the
|
|
// exec code makes and touches the code it runs. That costs about as much as it saves in four
|
|
// children, so only a process that keeps forking (a shell running a loop or a long script, make,
|
|
// dpkg) does it; one that forks a few times (sh -c with a pipe) does not pay for it.
|
|
#define DDNATV_FORKS_BEFORE_REHEARSAL 8
|
|
static int g_exec_prepared = 0; // 1 after the first fork(), 2 after the rehearsal
|
|
static pthread_mutex_t g_exec_prepare_lock = PTHREAD_MUTEX_INITIALIZER;
|
|
|
|
static void rehearse_exec(void) {
|
|
static const char rehearsal_target[] = "/usr/bin/true";
|
|
char target_buf[PATH_MAX];
|
|
const char *target = rewrite_path(rehearsal_target, target_buf, sizeof(target_buf));
|
|
struct exec_probe probe;
|
|
// A dynamic program only: it takes the one way through ddnatv_execve() that ends in run_execve()
|
|
probe_exec_file(target, &probe);
|
|
if (!probe.is_elf || !probe.is_dynamic) return;
|
|
extern char **environ;
|
|
char *rehearsal_argv[] = { (char *)"true", NULL };
|
|
g_exec_rehearsal_thread = pthread_self();
|
|
__atomic_store_n(&g_exec_rehearsal, 1, __ATOMIC_RELEASE);
|
|
ddnatv_execve(rehearsal_target, rehearsal_argv, environ, 0);
|
|
__atomic_store_n(&g_exec_rehearsal, 0, __ATOMIC_RELEASE);
|
|
}
|
|
|
|
static void prepare_exec_in_parent(int level) {
|
|
// One thread prepares (two rehearsing at once would take each other for the other's thread).
|
|
// Not waiting for the lock: a signal handler that forks while its thread is preparing would wait
|
|
// for itself; a busy lock leaves the preparation to a later fork().
|
|
if (pthread_mutex_trylock(&g_exec_prepare_lock) != 0) return;
|
|
int done = __atomic_load_n(&g_exec_prepared, __ATOMIC_ACQUIRE);
|
|
if (done >= level) {
|
|
pthread_mutex_unlock(&g_exec_prepare_lock);
|
|
return;
|
|
}
|
|
int saved_errno = errno;
|
|
init_ddnatv_hook();
|
|
real_execve();
|
|
if (g_ddnatv_root[0] != '\0') {
|
|
if (done < 1) {
|
|
char ld_so[PATH_MAX];
|
|
#if defined(__aarch64__)
|
|
uint16_t machine = 183;
|
|
#elif defined(__arm__)
|
|
uint16_t machine = 40;
|
|
#elif defined(__x86_64__)
|
|
uint16_t machine = 62;
|
|
#else
|
|
uint16_t machine = 0;
|
|
#endif
|
|
if (machine && find_dynamic_linker_for_machine(g_ddnatv_root, machine, ld_so, sizeof(ld_so))) {
|
|
// readlink(), open(), read() and close() behind the hooks, as the probe calls them
|
|
char resolved[PATH_MAX];
|
|
struct exec_probe probe;
|
|
resolve_symlinks(ld_so, resolved, sizeof(resolved), 0);
|
|
probe_exec_file(ld_so, &probe);
|
|
}
|
|
char hook_buf[PATH_MAX];
|
|
ddnatv_hook_library(hook_buf, sizeof(hook_buf));
|
|
struct stat st;
|
|
probe_fstat(-1, &st); // looks fstat() up; -1 only fails with EBADF
|
|
char conf[PATH_MAX * 2];
|
|
ldconf_dirs(conf, sizeof(conf)); // ld.so.conf read here, so the children only compare times
|
|
}
|
|
if (level >= 2) rehearse_exec();
|
|
}
|
|
__atomic_store_n(&g_exec_prepared, level, __ATOMIC_RELEASE);
|
|
pthread_mutex_unlock(&g_exec_prepare_lock);
|
|
errno = saved_errno;
|
|
}
|
|
|
|
pid_t fork(void) {
|
|
static pid_t (*orig_fork)(void) = NULL;
|
|
if (!orig_fork) orig_fork = (pid_t (*)(void))dlsym(RTLD_NEXT, "fork");
|
|
if (!orig_fork) {
|
|
errno = ENOSYS;
|
|
return -1;
|
|
}
|
|
int done = __atomic_load_n(&g_exec_prepared, __ATOMIC_ACQUIRE);
|
|
if (done < 2) {
|
|
static int forks = 0;
|
|
int n = __atomic_add_fetch(&forks, 1, __ATOMIC_RELAXED);
|
|
if (n == 1 || n >= DDNATV_FORKS_BEFORE_REHEARSAL) prepare_exec_in_parent(n >= DDNATV_FORKS_BEFORE_REHEARSAL ? 2 : 1);
|
|
}
|
|
ddh_prepare();
|
|
pid_t forker = (pid_t)syscall(SYS_gettid);
|
|
pid_t forking = (pid_t)syscall(SYS_getpid);
|
|
pid_t pid = orig_fork();
|
|
if (pid == 0) {
|
|
kept_forked();
|
|
kept_close_forked();
|
|
ddh_drop_worker_binder();
|
|
ddh_forked(forker);
|
|
ddh_record_parent((pid_t)syscall(SYS_getpid), forking);
|
|
} else if (pid > 0) {
|
|
ddh_child_created(pid, 1);
|
|
}
|
|
// A child forked from a signal handler that interrupted a rehearsal is not rehearsing: its
|
|
// execve() is a real one (only read in the usual case, so no page is copied for it)
|
|
if (pid == 0 && __atomic_load_n(&g_exec_rehearsal, __ATOMIC_RELAXED)) __atomic_store_n(&g_exec_rehearsal, 0, __ATOMIC_RELAXED);
|
|
return pid;
|
|
}
|
|
|
|
extern char **environ;
|
|
|
|
int execv(const char *path, char *const argv[]) {
|
|
return execve(path, argv, environ);
|
|
}
|
|
|
|
int execl(const char *path, const char *arg0, ...) {
|
|
va_list args;
|
|
va_start(args, arg0);
|
|
int count = (arg0 != NULL) ? 1 : 0;
|
|
if (arg0 != NULL) {
|
|
while (va_arg(args, const char *) != NULL) {
|
|
count++;
|
|
}
|
|
}
|
|
va_end(args);
|
|
|
|
char **argv = (char **)calloc(count + 1, sizeof(char *));
|
|
if (!argv) {
|
|
errno = ENOMEM;
|
|
return -1;
|
|
}
|
|
if (count > 0) {
|
|
argv[0] = (char *)arg0;
|
|
va_start(args, arg0);
|
|
for (int i = 1; i < count; i++) {
|
|
argv[i] = va_arg(args, char *);
|
|
}
|
|
va_end(args);
|
|
}
|
|
argv[count] = NULL;
|
|
int ret = execv(path, argv);
|
|
free(argv);
|
|
return ret;
|
|
}
|
|
|
|
int execlp(const char *file, const char *arg0, ...) {
|
|
va_list args;
|
|
va_start(args, arg0);
|
|
int count = (arg0 != NULL) ? 1 : 0;
|
|
if (arg0 != NULL) {
|
|
while (va_arg(args, const char *) != NULL) {
|
|
count++;
|
|
}
|
|
}
|
|
va_end(args);
|
|
|
|
char **argv = (char **)calloc(count + 1, sizeof(char *));
|
|
if (!argv) {
|
|
errno = ENOMEM;
|
|
return -1;
|
|
}
|
|
if (count > 0) {
|
|
argv[0] = (char *)arg0;
|
|
va_start(args, arg0);
|
|
for (int i = 1; i < count; i++) {
|
|
argv[i] = va_arg(args, char *);
|
|
}
|
|
va_end(args);
|
|
}
|
|
argv[count] = NULL;
|
|
int ret = execvp(file, argv);
|
|
free(argv);
|
|
return ret;
|
|
}
|
|
|
|
int execle(const char *path, const char *arg0, ...) {
|
|
va_list args;
|
|
va_start(args, arg0);
|
|
int count = (arg0 != NULL) ? 1 : 0;
|
|
if (arg0 != NULL) {
|
|
while (va_arg(args, const char *) != NULL) {
|
|
count++;
|
|
}
|
|
}
|
|
char *const *envp = va_arg(args, char *const *);
|
|
va_end(args);
|
|
|
|
char **argv = (char **)calloc(count + 1, sizeof(char *));
|
|
if (!argv) {
|
|
errno = ENOMEM;
|
|
return -1;
|
|
}
|
|
if (count > 0) {
|
|
argv[0] = (char *)arg0;
|
|
va_start(args, arg0);
|
|
for (int i = 1; i < count; i++) {
|
|
argv[i] = va_arg(args, char *);
|
|
}
|
|
va_end(args);
|
|
}
|
|
argv[count] = NULL;
|
|
int ret = execve(path, argv, (char *const *)envp);
|
|
free(argv);
|
|
return ret;
|
|
}
|
|
|
|
static int exec_or_script(const char *path, char *const argv[], char *const envp[]) {
|
|
execve(path, argv, envp);
|
|
if (errno != ENOEXEC) return -1;
|
|
int argc = 0;
|
|
while (argv && argv[argc]) argc++;
|
|
char **script = (char **)malloc(sizeof(char *) * (size_t)(argc + 3));
|
|
if (!script) {
|
|
errno = ENOMEM;
|
|
return -1;
|
|
}
|
|
script[0] = (char *)"/bin/sh";
|
|
script[1] = (char *)path;
|
|
int n = 2;
|
|
for (int i = 1; i < argc; i++) script[n++] = argv[i];
|
|
script[n] = NULL;
|
|
execve(script[0], script, envp);
|
|
int saved_errno = errno;
|
|
free(script);
|
|
errno = saved_errno;
|
|
return -1;
|
|
}
|
|
|
|
static int exec_search_dir(const char *dir, size_t len, const char *file, char *const argv[], char *const envp[], int *denied) {
|
|
char candidate[PATH_MAX];
|
|
int n = len ? snprintf(candidate, sizeof(candidate), "%.*s/%s", (int)len, dir, file)
|
|
: snprintf(candidate, sizeof(candidate), "%s", file);
|
|
if (n < 0 || n >= (int)sizeof(candidate)) {
|
|
errno = ENAMETOOLONG;
|
|
return 0;
|
|
}
|
|
exec_or_script(candidate, argv, envp);
|
|
switch (errno) {
|
|
case EACCES:
|
|
*denied = 1;
|
|
return 0;
|
|
case ENOENT: case ENOTDIR: case ESTALE: case ENODEV: case ETIMEDOUT: case ENAMETOOLONG:
|
|
return 0;
|
|
default:
|
|
return 1;
|
|
}
|
|
}
|
|
|
|
static int exec_search(const char *file, char *const argv[], char *const envp[], const char *path_env) {
|
|
if (!file || !*file) {
|
|
errno = ENOENT;
|
|
return -1;
|
|
}
|
|
if (strchr(file, '/')) return exec_or_script(file, argv, envp);
|
|
if (!path_env) path_env = "/usr/bin:/bin";
|
|
int denied = 0;
|
|
for (const char *p = path_env;; ) {
|
|
const char *end = strchrnul(p, ':');
|
|
if (exec_search_dir(p, (size_t)(end - p), file, argv, envp, &denied)) return -1;
|
|
if (!*end) break;
|
|
p = end + 1;
|
|
}
|
|
static const char *const standard_paths[] = {"/usr/bin", "/bin", "/usr/sbin", "/sbin", "/usr/local/bin"};
|
|
for (size_t i = 0; i < sizeof(standard_paths) / sizeof(standard_paths[0]); i++)
|
|
if (exec_search_dir(standard_paths[i], strlen(standard_paths[i]), file, argv, envp, &denied)) return -1;
|
|
errno = denied ? EACCES : ENOENT;
|
|
return -1;
|
|
}
|
|
|
|
int execvp(const char *file, char *const argv[]) {
|
|
return exec_search(file, argv, environ, getenv("PATH"));
|
|
}
|
|
|
|
int execvpe(const char *file, char *const argv[], char *const envp[]) {
|
|
const char *path_env = NULL;
|
|
for (char *const *ep = envp; ep && *ep; ep++) {
|
|
if (strncmp(*ep, "PATH=", 5) == 0) {
|
|
path_env = *ep + 5;
|
|
break;
|
|
}
|
|
}
|
|
return exec_search(file, argv, envp, path_env ? path_env : getenv("PATH"));
|
|
}
|
|
|
|
typedef int (*orig_posix_spawn_f_type)(pid_t *, const char *, const posix_spawn_file_actions_t *,
|
|
const posix_spawnattr_t *, char *const [], char *const []);
|
|
|
|
static orig_posix_spawn_f_type real_posix_spawn(void) {
|
|
static orig_posix_spawn_f_type orig_posix_spawn = NULL;
|
|
if (!orig_posix_spawn) orig_posix_spawn = (orig_posix_spawn_f_type)dlsym(RTLD_NEXT, "posix_spawn");
|
|
return orig_posix_spawn;
|
|
}
|
|
|
|
static int run_spawn(orig_posix_spawn_f_type f, pid_t *pid, const char *path, const posix_spawn_file_actions_t *file_actions,
|
|
const posix_spawnattr_t *attrp, char *const argv[], char *const envp[]) {
|
|
int err;
|
|
char **via = loader_argv(path, argv, &err);
|
|
if (err) return err;
|
|
if (!via) return f(pid, path, file_actions, attrp, argv, envp);
|
|
int ret = f(pid, g_exec_loader, file_actions, attrp, via, envp);
|
|
free(via);
|
|
return ret;
|
|
}
|
|
|
|
static int ddnatv_posix_spawn(pid_t *pid, const char *path,
|
|
const posix_spawn_file_actions_t *file_actions,
|
|
const posix_spawnattr_t *attrp,
|
|
char *const argv[], char *const envp[], int depth);
|
|
|
|
// A rootfs script: start its interpreter with the same file actions and attributes. Handing the
|
|
// script to the kernel resolves "#!/bin/sh" to Android's own shell, which crashed on the glibc
|
|
// hook in LD_PRELOAD (and "#!/usr/bin/env" etc. used to fall back to fork() + execve(), which
|
|
// dropped the file actions).
|
|
static int spawn_script(pid_t *pid, const char *script, struct exec_probe *probe,
|
|
const posix_spawn_file_actions_t *file_actions, const posix_spawnattr_t *attrp,
|
|
char *const argv[], char *const envp[], int depth) {
|
|
char *interp;
|
|
char *interp_arg;
|
|
parse_shebang(probe->hdr, &interp, &interp_arg);
|
|
char interp_buf[PATH_MAX];
|
|
const char *rewritten_interp = shebang_interpreter(interp, interp_buf, sizeof(interp_buf));
|
|
char **new_argv = build_script_argv(rewritten_interp, interp_arg, script, argv);
|
|
if (!new_argv) return ENOMEM;
|
|
int ret;
|
|
if (is_host_interpreter(interp, rewritten_interp)) {
|
|
orig_posix_spawn_f_type orig_posix_spawn = real_posix_spawn();
|
|
char **sys_env = clean_env_for_system(envp);
|
|
ret = orig_posix_spawn ? orig_posix_spawn(pid, rewritten_interp, file_actions, attrp, new_argv, sys_env) : ENOSYS;
|
|
free_modified_env(sys_env, envp);
|
|
} else {
|
|
ret = ddnatv_posix_spawn(pid, rewritten_interp, file_actions, attrp, new_argv, envp, depth + 1);
|
|
}
|
|
free(new_argv);
|
|
return ret;
|
|
}
|
|
|
|
static int ddnatv_posix_spawn(pid_t *pid, const char *path,
|
|
const posix_spawn_file_actions_t *file_actions,
|
|
const posix_spawnattr_t *attrp,
|
|
char *const argv[], char *const envp[], int depth) {
|
|
orig_posix_spawn_f_type orig_posix_spawn = real_posix_spawn();
|
|
|
|
const char *caller_path = path;
|
|
char abs_buf[PATH_MAX];
|
|
path = absolutize_exec_path(path, abs_buf, sizeof(abs_buf));
|
|
|
|
char buf[PATH_MAX];
|
|
const char *target = rewrite_path(path, buf, sizeof(buf));
|
|
|
|
init_ddnatv_hook();
|
|
|
|
const char *f_base = (path != NULL) ? strrchr(path, '/') : NULL;
|
|
f_base = (f_base != NULL) ? f_base + 1 : (path != NULL ? path : "");
|
|
|
|
const char *prog_name = exec_prog_name(target);
|
|
|
|
if (strcmp(f_base, "ldconfig") == 0 ||
|
|
strcmp(f_base, "ldconfig.real") == 0 ||
|
|
strcmp(f_base, "systemd-machine-id-setup") == 0 ||
|
|
strcmp(f_base, "systemd-sysusers") == 0 ||
|
|
strcmp(f_base, "systemd-tmpfiles") == 0 ||
|
|
strcmp(f_base, "start-stop-daemon") == 0 ||
|
|
strcmp(prog_name, "ldconfig") == 0 ||
|
|
strcmp(prog_name, "ldconfig.real") == 0 ||
|
|
strcmp(prog_name, "systemd-machine-id-setup") == 0 ||
|
|
strcmp(prog_name, "systemd-sysusers") == 0 ||
|
|
strcmp(prog_name, "systemd-tmpfiles") == 0 ||
|
|
strcmp(prog_name, "start-stop-daemon") == 0) {
|
|
pid_t child = fork();
|
|
if (child == 0) {
|
|
if (is_ldconfig_name(f_base) || is_ldconfig_name(prog_name)) ldconfig_mark_cache(argv);
|
|
_exit(0);
|
|
} else if (child > 0) {
|
|
if (pid) *pid = child;
|
|
return 0;
|
|
}
|
|
return errno;
|
|
}
|
|
if (strcmp(f_base, "mountpoint") == 0 || strcmp(prog_name, "mountpoint") == 0) {
|
|
int is_virtual_fs = 0;
|
|
for (int i = 1; argv && argv[i]; i++) {
|
|
if (strcmp(argv[i], "/proc") == 0 || strcmp(argv[i], "/proc/") == 0 ||
|
|
strcmp(argv[i], "/sys") == 0 || strcmp(argv[i], "/sys/") == 0 ||
|
|
strcmp(argv[i], "/dev") == 0 || strcmp(argv[i], "/dev/") == 0 ||
|
|
strcmp(argv[i], "/dev/pts") == 0) {
|
|
is_virtual_fs = 1;
|
|
break;
|
|
}
|
|
}
|
|
if (is_virtual_fs) {
|
|
pid_t child = fork();
|
|
if (child == 0) {
|
|
_exit(0);
|
|
} else if (child > 0) {
|
|
if (pid) *pid = child;
|
|
return 0;
|
|
}
|
|
return errno;
|
|
}
|
|
}
|
|
if (strcmp(f_base, "policy-rc.d") == 0 || strcmp(prog_name, "policy-rc.d") == 0) {
|
|
pid_t child = fork();
|
|
if (child == 0) {
|
|
_exit(101);
|
|
} else if (child > 0) {
|
|
if (pid) *pid = child;
|
|
return 0;
|
|
}
|
|
return errno;
|
|
}
|
|
|
|
char *const *orig_ep = envp ? envp : environ;
|
|
int in_root = (g_ddnatv_root[0] != '\0' && strncmp(target, g_ddnatv_root, g_ddnatv_root_len) == 0) || is_mapped_guest_path(path) ||
|
|
is_bound_guest_program(target);
|
|
|
|
struct exec_probe probe;
|
|
char resolved_target[PATH_MAX];
|
|
const char *elf_target = target;
|
|
if (in_root) {
|
|
elf_target = select_exec_target(target, resolved_target, sizeof(resolved_target), &probe);
|
|
if (!probe.is_elf && probe.n >= 2 && probe.hdr[0] == '#' && probe.hdr[1] == '!') {
|
|
// Like the kernel, give up after a few nested "#!" interpreters.
|
|
if (depth >= DDNATV_MAX_SHEBANG_DEPTH) return ELOOP;
|
|
const char *script = (caller_path && caller_path[0] != '/') ? caller_path : target;
|
|
return spawn_script(pid, script, &probe, file_actions, attrp, argv, orig_ep, depth);
|
|
}
|
|
} else {
|
|
probe.hdr[0] = '\0';
|
|
probe.n = -1;
|
|
probe.is_elf = 0;
|
|
probe.is_dynamic = 0;
|
|
probe.android_interp = 0;
|
|
probe.e_machine = 0;
|
|
probe.mode = 0;
|
|
probe.runpath[0] = '\0';
|
|
probe.runpath_is_rpath = 0;
|
|
}
|
|
|
|
char ld_so[PATH_MAX];
|
|
ld_so[0] = '\0';
|
|
int has_ld_so = probe.is_dynamic ? find_dynamic_linker_for_machine(g_ddnatv_root, probe.e_machine, ld_so, sizeof(ld_so)) : 0;
|
|
|
|
// Android programs get Android's environment, as execve() gives them: the glibc hook in
|
|
// LD_PRELOAD crashes them.
|
|
int via_ld_so = has_ld_so && strcmp(elf_target, ld_so) != 0;
|
|
char ld_lib_path[PATH_MAX * 6];
|
|
ld_lib_path[0] = '\0';
|
|
if (via_ld_so)
|
|
build_ld_library_path(orig_ep, probe.runpath, probe.runpath_is_rpath, elf_target, ld_lib_path, sizeof(ld_lib_path));
|
|
char **new_envp = in_root ? ensure_hook_in_envp(orig_ep, elf_target, via_ld_so ? ld_lib_path : NULL)
|
|
: clean_env_for_system(orig_ep);
|
|
|
|
int ret = -1;
|
|
if (via_ld_so) {
|
|
ensure_exec_bit(elf_target, probe.mode);
|
|
prepare_static_program_ex(elf_target, 1); // a Go program built for Android (#42)
|
|
|
|
char hook_buf[PATH_MAX];
|
|
const char *hook_so = ddnatv_hook_library(hook_buf, sizeof(hook_buf));
|
|
char **new_argv = build_ldso_argv(ld_so, hook_so, ld_lib_path, elf_target, prog_name, argv);
|
|
if (!new_argv) {
|
|
ret = ENOMEM;
|
|
} else {
|
|
if (orig_posix_spawn) {
|
|
ret = run_spawn(orig_posix_spawn, pid, ld_so, file_actions, attrp, new_argv, new_envp);
|
|
if (ret == EACCES && chmod(ld_so, 0755) == 0) {
|
|
// ld.so without its exec bit (an unusual restore): fix it once and retry
|
|
ret = run_spawn(orig_posix_spawn, pid, ld_so, file_actions, attrp, new_argv, new_envp);
|
|
}
|
|
}
|
|
free(new_argv);
|
|
}
|
|
} else {
|
|
if (in_root && probe.is_elf && !probe.is_dynamic) prepare_static_program(elf_target);
|
|
char **spawn_argv = (char **)argv;
|
|
int err = 0;
|
|
struct ldso_direct direct;
|
|
if (in_root && probe.is_elf && !probe.is_dynamic && is_ld_linux(elf_target)) {
|
|
char **direct_argv = ldso_direct_argv(argv, orig_ep, &direct, &err);
|
|
if (direct_argv) spawn_argv = direct_argv;
|
|
}
|
|
if (err) {
|
|
ret = err;
|
|
} else if (orig_posix_spawn) {
|
|
ret = run_spawn(orig_posix_spawn, pid, target, file_actions, attrp, spawn_argv, new_envp);
|
|
}
|
|
if (spawn_argv != argv) free(spawn_argv);
|
|
}
|
|
|
|
if (!orig_posix_spawn) {
|
|
pid_t child = fork();
|
|
if (child < 0) {
|
|
free_modified_env(new_envp, orig_ep);
|
|
return errno;
|
|
} else if (child == 0) {
|
|
execve(target, argv, new_envp);
|
|
_exit(127);
|
|
} else {
|
|
if (pid) *pid = child;
|
|
free_modified_env(new_envp, orig_ep);
|
|
return 0;
|
|
}
|
|
}
|
|
free_modified_env(new_envp, orig_ep);
|
|
return ret;
|
|
}
|
|
|
|
static int apply_closefrom(posix_spawn_file_actions_t *actions);
|
|
|
|
// glibc's file actions (posix/spawn_int.h, unchanged since 2.35)
|
|
struct ddh_spawn_action {
|
|
enum { DDH_DO_CLOSE, DDH_DO_DUP2, DDH_DO_OPEN, DDH_DO_CHDIR, DDH_DO_FCHDIR, DDH_DO_CLOSEFROM, DDH_DO_TCSETPGRP } tag;
|
|
union {
|
|
struct { int fd; } close_action;
|
|
struct { int fd; int newfd; } dup2_action;
|
|
struct { int fd; char *path; int oflag; mode_t mode; } open_action;
|
|
struct { char *path; } chdir_action;
|
|
struct { int fd; } fchdir_action;
|
|
struct { int from; } closefrom_action;
|
|
struct { int fd; } setpgrp_action;
|
|
} action;
|
|
};
|
|
|
|
#ifndef POSIX_SPAWN_SETSID
|
|
#define POSIX_SPAWN_SETSID 0x80
|
|
#endif
|
|
|
|
static int ddh_spawn_errno(long ret) {
|
|
return ret < 0 ? errno : 0;
|
|
}
|
|
|
|
static int ddh_spawn_close_part(unsigned int first, unsigned int last, void *unused) {
|
|
(void)unused;
|
|
return (int)call_orig_syscall(SYS_close_range, first, last, 0, 0, 0, 0);
|
|
}
|
|
|
|
// What glibc's spawn child does before its exec (posix/spawni.c), as an errno. Its fd and
|
|
// directory work is done with system calls, not the hook's wrappers: those take locks that another
|
|
// thread of the parent may have held at fork() (Steam has many threads).
|
|
static int ddh_spawn_child_setup(const posix_spawn_file_actions_t *fa, const posix_spawnattr_t *attr) {
|
|
short flags = 0;
|
|
if (attr) posix_spawnattr_getflags(attr, &flags);
|
|
if (flags & POSIX_SPAWN_SETSIGDEF) {
|
|
sigset_t def;
|
|
posix_spawnattr_getsigdefault(attr, &def);
|
|
for (int sig = 1; sig < _NSIG; sig++) {
|
|
if (sigismember(&def, sig) == 1) signal(sig, SIG_DFL);
|
|
}
|
|
}
|
|
if ((flags & POSIX_SPAWN_SETSID) && setsid() < 0) return errno;
|
|
if (flags & POSIX_SPAWN_SETPGROUP) {
|
|
pid_t group = 0;
|
|
posix_spawnattr_getpgroup(attr, &group);
|
|
if (setpgid(0, group) != 0) return errno;
|
|
}
|
|
if (flags & (POSIX_SPAWN_SETSCHEDULER | POSIX_SPAWN_SETSCHEDPARAM)) {
|
|
struct sched_param param;
|
|
posix_spawnattr_getschedparam(attr, ¶m);
|
|
int policy = 0;
|
|
posix_spawnattr_getschedpolicy(attr, &policy);
|
|
int r = (flags & POSIX_SPAWN_SETSCHEDULER) ? sched_setscheduler(0, policy, ¶m) : sched_setparam(0, ¶m);
|
|
if (r == -1) return errno;
|
|
}
|
|
const struct ddh_spawn_action *a = fa ? (const struct ddh_spawn_action *)fa->__actions : NULL;
|
|
char path[PATH_MAX];
|
|
int err;
|
|
for (int i = 0; a && i < fa->__used; i++) {
|
|
switch (a[i].tag) {
|
|
case DDH_DO_CLOSE:
|
|
// the handoff table and the worker's binder stay open (kept fds)
|
|
if (!is_kept_fd(a[i].action.close_action.fd))
|
|
call_orig_syscall(SYS_close, (unsigned long)a[i].action.close_action.fd, 0, 0, 0, 0, 0);
|
|
break;
|
|
case DDH_DO_OPEN: {
|
|
const char *real = rewrite_path(a[i].action.open_action.path, path, sizeof(path));
|
|
// as glibc: the target goes first, so a full fd table still has room for the open
|
|
if (!is_kept_fd(a[i].action.open_action.fd))
|
|
call_orig_syscall(SYS_close, (unsigned long)a[i].action.open_action.fd, 0, 0, 0, 0, 0);
|
|
long fd = call_orig_syscall(SYS_openat, (unsigned long)AT_FDCWD, (unsigned long)real,
|
|
(unsigned long)a[i].action.open_action.oflag, a[i].action.open_action.mode, 0, 0);
|
|
if (fd < 0) return errno;
|
|
if (fd != a[i].action.open_action.fd) {
|
|
if ((err = ddh_spawn_errno(call_orig_syscall(SYS_dup3, (unsigned long)fd, (unsigned long)a[i].action.open_action.fd, 0, 0, 0, 0))))
|
|
return err;
|
|
call_orig_syscall(SYS_close, (unsigned long)fd, 0, 0, 0, 0, 0);
|
|
}
|
|
break;
|
|
}
|
|
case DDH_DO_DUP2: {
|
|
int from = a[i].action.dup2_action.fd, to = a[i].action.dup2_action.newfd;
|
|
if (from == to) {
|
|
long fdflags = call_orig_syscall(SYS_fcntl, (unsigned long)from, F_GETFD, 0, 0, 0, 0);
|
|
if (fdflags < 0) return errno;
|
|
if ((err = ddh_spawn_errno(call_orig_syscall(SYS_fcntl, (unsigned long)from, F_SETFD, (unsigned long)(fdflags & ~FD_CLOEXEC), 0, 0, 0))))
|
|
return err;
|
|
} else if ((err = ddh_spawn_errno(call_orig_syscall(SYS_dup3, (unsigned long)from, (unsigned long)to, 0, 0, 0, 0)))) {
|
|
return err;
|
|
}
|
|
break;
|
|
}
|
|
case DDH_DO_CHDIR: {
|
|
const char *real = rewrite_path_follow(a[i].action.chdir_action.path, path, sizeof(path));
|
|
if ((err = ddh_spawn_errno(call_orig_syscall(SYS_chdir, (unsigned long)real, 0, 0, 0, 0, 0)))) return err;
|
|
break;
|
|
}
|
|
case DDH_DO_FCHDIR:
|
|
if ((err = ddh_spawn_errno(call_orig_syscall(SYS_fchdir, (unsigned long)a[i].action.fchdir_action.fd, 0, 0, 0, 0, 0))))
|
|
return err;
|
|
break;
|
|
case DDH_DO_CLOSEFROM:
|
|
for_each_range_without((unsigned int)a[i].action.closefrom_action.from, ~0U, g_kept_fds, g_kept_fd_count,
|
|
ddh_spawn_close_part, NULL);
|
|
break;
|
|
case DDH_DO_TCSETPGRP:
|
|
if (tcsetpgrp(a[i].action.setpgrp_action.fd, getpgrp()) != 0) return errno;
|
|
break;
|
|
}
|
|
}
|
|
if (flags & POSIX_SPAWN_SETSIGMASK) {
|
|
sigset_t mask;
|
|
posix_spawnattr_getsigmask(attr, &mask);
|
|
sigprocmask(SIG_SETMASK, &mask, NULL);
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
// posix_spawn() as fork() and execve(), so that ddh_try() sees the exec. -1 when it cannot be.
|
|
static int ddh_spawn_forked(pid_t *pid, const char *path, const posix_spawn_file_actions_t *fa,
|
|
const posix_spawnattr_t *attr, char *const argv[], char *const envp[]) {
|
|
if (fa) {
|
|
const struct ddh_spawn_action *a = (const struct ddh_spawn_action *)fa->__actions;
|
|
// A terminal action stays with glibc, which blocks signals around the file actions: here a
|
|
// SIGTTOU could stop the child at tcsetpgrp() with the parent waiting on its report.
|
|
for (int i = 0; i < fa->__used; i++) {
|
|
if ((unsigned)a[i].tag >= DDH_DO_TCSETPGRP) return -1;
|
|
}
|
|
}
|
|
// A scheduling policy or priority would apply to this child, not to the worker that runs the program
|
|
short spawn_flags = 0;
|
|
if (attr && posix_spawnattr_getflags(attr, &spawn_flags) == 0 &&
|
|
(spawn_flags & (POSIX_SPAWN_SETSCHEDULER | POSIX_SPAWN_SETSCHEDPARAM)))
|
|
return -1;
|
|
// Not cancelled while the child is being started (its report is read, and its failure reaped):
|
|
// the pid would be lost with the child still running, and the report's fd left open.
|
|
int cancel = PTHREAD_CANCEL_ENABLE;
|
|
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cancel);
|
|
int report[2];
|
|
if (pipe2(report, O_CLOEXEC) != 0) {
|
|
pthread_setcancelstate(cancel, NULL);
|
|
return -1;
|
|
}
|
|
// Every signal blocked from the fork to the exec, as glibc's posix_spawn() does: a signal to the
|
|
// group during a file action (an open of a FIFO that blocks) would otherwise run the caller's
|
|
// handler, or end the child, before the program is started. The child gets back the caller's mask,
|
|
// or the one the attributes ask for, just before its exec.
|
|
sigset_t all, caller;
|
|
sigfillset(&all);
|
|
pthread_sigmask(SIG_SETMASK, &all, &caller);
|
|
pid_t child = fork();
|
|
if (child < 0) {
|
|
int err = errno;
|
|
pthread_sigmask(SIG_SETMASK, &caller, NULL);
|
|
close(report[0]);
|
|
close(report[1]);
|
|
pthread_setcancelstate(cancel, NULL);
|
|
return err;
|
|
}
|
|
if (child > 0) pthread_sigmask(SIG_SETMASK, &caller, NULL);
|
|
if (child == 0) {
|
|
call_orig_syscall(SYS_close, (unsigned long)report[0], 0, 0, 0, 0, 0);
|
|
// Out of the file actions' way: high, and one of the fds they leave open (closefrom(3) is common)
|
|
int to_parent = (int)call_orig_syscall(SYS_fcntl, (unsigned long)report[1], F_DUPFD_CLOEXEC, 1000, 0, 0, 0);
|
|
if (to_parent >= 0) {
|
|
call_orig_syscall(SYS_close, (unsigned long)report[1], 0, 0, 0, 0, 0);
|
|
ddh_keep(to_parent);
|
|
} else {
|
|
to_parent = report[1];
|
|
}
|
|
int err = ddh_spawn_child_setup(fa, attr);
|
|
if (!err) {
|
|
// A signal still pending when the mask is restored must not run a handler copied from the
|
|
// caller: caught signals go back to their default, ignored ones stay ignored (exec keeps
|
|
// them), and SIGSYS keeps the hook's handler.
|
|
for (int sig = 1; sig < _NSIG; sig++) {
|
|
struct sigaction old;
|
|
if (sig == SIGSYS || sig == SIGKILL || sig == SIGSTOP) continue;
|
|
if (sigaction(sig, NULL, &old) != 0) continue;
|
|
if (old.sa_handler == SIG_IGN || old.sa_handler == SIG_DFL) continue;
|
|
struct sigaction def = {0};
|
|
def.sa_handler = SIG_DFL;
|
|
sigaction(sig, &def, NULL);
|
|
}
|
|
short flags = 0;
|
|
if (attr) posix_spawnattr_getflags(attr, &flags);
|
|
if (!(flags & POSIX_SPAWN_SETSIGMASK)) sigprocmask(SIG_SETMASK, &caller, NULL);
|
|
execve(path, argv, envp);
|
|
err = errno;
|
|
}
|
|
syscall(SYS_write, to_parent, &err, sizeof(err));
|
|
_exit(127);
|
|
}
|
|
close(report[1]);
|
|
int err = 0;
|
|
ssize_t n;
|
|
do n = read(report[0], &err, sizeof(err));
|
|
while (n < 0 && errno == EINTR);
|
|
close(report[0]);
|
|
if (n == (ssize_t)sizeof(err)) {
|
|
while (waitpid(child, NULL, 0) < 0 && errno == EINTR) {
|
|
}
|
|
pthread_setcancelstate(cancel, NULL);
|
|
return err;
|
|
}
|
|
if (pid) *pid = child;
|
|
pthread_setcancelstate(cancel, NULL);
|
|
return 0;
|
|
}
|
|
|
|
int posix_spawn(pid_t *pid, const char *path,
|
|
const posix_spawn_file_actions_t *file_actions,
|
|
const posix_spawnattr_t *attrp,
|
|
char *const argv[], char *const envp[]) {
|
|
if (file_actions) {
|
|
int bad = apply_closefrom((posix_spawn_file_actions_t *)file_actions);
|
|
if (bad) return bad;
|
|
}
|
|
posix_spawnattr_t sanitized;
|
|
const posix_spawnattr_t *attr = spawn_attr_for_android(attrp, &sanitized);
|
|
if (ddh_spawn_wanted(path, argv, envp ? envp : environ)) {
|
|
int ret = ddh_spawn_forked(pid, path, file_actions, attr, argv, envp ? envp : environ);
|
|
if (ret != -1) return ret;
|
|
}
|
|
pid_t child = 0;
|
|
int ret = ddnatv_posix_spawn(&child, path, file_actions, attr, argv, envp, 0);
|
|
if (ret == 0) {
|
|
ddh_child_created(child, 0);
|
|
if (pid) *pid = child;
|
|
}
|
|
return ret;
|
|
}
|
|
|
|
int posix_spawnp(pid_t *pid, const char *file,
|
|
const posix_spawn_file_actions_t *file_actions,
|
|
const posix_spawnattr_t *attrp,
|
|
char *const argv[], char *const envp[]) {
|
|
if (!file || !*file) {
|
|
return ENOENT;
|
|
}
|
|
if (strchr(file, '/')) {
|
|
return posix_spawn(pid, file, file_actions, attrp, argv, envp);
|
|
}
|
|
const char *path_env = NULL;
|
|
if (envp) {
|
|
for (char *const *ep = envp; *ep; ep++) {
|
|
if (strncmp(*ep, "PATH=", 5) == 0) {
|
|
path_env = *ep + 5;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
if (!path_env) path_env = getenv("PATH");
|
|
if (!path_env) path_env = "/usr/bin:/bin";
|
|
char path_copy[4096];
|
|
strncpy(path_copy, path_env, sizeof(path_copy) - 1);
|
|
path_copy[sizeof(path_copy) - 1] = '\0';
|
|
char *saveptr = NULL;
|
|
char *token = strtok_r(path_copy, ":", &saveptr);
|
|
while (token) {
|
|
char candidate[PATH_MAX];
|
|
snprintf(candidate, sizeof(candidate), "%s/%s", token, file);
|
|
if (access(candidate, F_OK) == 0) {
|
|
return posix_spawn(pid, candidate, file_actions, attrp, argv, envp);
|
|
}
|
|
token = strtok_r(NULL, ":", &saveptr);
|
|
}
|
|
const char *standard_paths[] = {"/usr/bin", "/bin", "/usr/sbin", "/sbin", "/usr/local/bin", NULL};
|
|
for (int i = 0; standard_paths[i] != NULL; i++) {
|
|
char candidate[PATH_MAX];
|
|
snprintf(candidate, sizeof(candidate), "%s/%s", standard_paths[i], file);
|
|
if (access(candidate, F_OK) == 0) {
|
|
return posix_spawn(pid, candidate, file_actions, attrp, argv, envp);
|
|
}
|
|
}
|
|
// If not found in PATH or standard paths, return ENOENT without spawning zombie
|
|
return ENOENT;
|
|
}
|
|
|
|
// ---- system(), popen() and pclose() ---------------------------------------------------------
|
|
// glibc starts the shell of system() and popen() from inside the C library (its own posix_spawn and
|
|
// execve), where the hook's execve() is not called: the kernel ran the machine's /bin/sh, which on
|
|
// Android is the system's own shell, and that one failed to link against Ubuntu's libraries
|
|
// ("CANNOT LINK EXECUTABLE sh: ...libc.so has bad ELF magic", #49). They start Ubuntu's /bin/sh here.
|
|
|
|
extern char **environ;
|
|
|
|
static pid_t start_shell(const char *command, int child_fd, int target_fd, const sigset_t *mask,
|
|
const struct sigaction *intr, const struct sigaction *quit, int close_popen_streams);
|
|
|
|
// While system() waits, SIGINT and SIGQUIT are ignored; with several threads in system() at once, the
|
|
// first one in saves the dispositions and the last one out puts them back (as glibc does)
|
|
static pthread_mutex_t g_system_lock = PTHREAD_MUTEX_INITIALIZER;
|
|
static int g_system_waiting;
|
|
static struct sigaction g_system_intr, g_system_quit;
|
|
|
|
// system(3) as POSIX describes it: SIGINT and SIGQUIT ignored and SIGCHLD blocked while it waits
|
|
int system(const char *command) {
|
|
if (!command) return access("/bin/sh", X_OK) == 0; // whether there is a shell (Ubuntu's)
|
|
pthread_mutex_lock(&g_system_lock);
|
|
if (g_system_waiting++ == 0) {
|
|
struct sigaction ignore;
|
|
memset(&ignore, 0, sizeof(ignore));
|
|
ignore.sa_handler = SIG_IGN;
|
|
sigemptyset(&ignore.sa_mask);
|
|
sigaction(SIGINT, &ignore, &g_system_intr);
|
|
sigaction(SIGQUIT, &ignore, &g_system_quit);
|
|
}
|
|
struct sigaction intr = g_system_intr, quit = g_system_quit;
|
|
pthread_mutex_unlock(&g_system_lock);
|
|
sigset_t block, old;
|
|
sigemptyset(&block);
|
|
sigaddset(&block, SIGCHLD);
|
|
sigprocmask(SIG_BLOCK, &block, &old);
|
|
|
|
int status = -1;
|
|
pid_t pid = start_shell(command, -1, -1, &old, &intr, &quit, 0);
|
|
if (pid < 0) status = 127 << 8; // as glibc's system() when the shell could not be started
|
|
if (pid > 0) {
|
|
while (waitpid(pid, &status, 0) < 0) {
|
|
if (errno != EINTR) {
|
|
status = -1;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
int saved = errno;
|
|
pthread_mutex_lock(&g_system_lock);
|
|
if (--g_system_waiting == 0) {
|
|
sigaction(SIGINT, &g_system_intr, NULL);
|
|
sigaction(SIGQUIT, &g_system_quit, NULL);
|
|
}
|
|
pthread_mutex_unlock(&g_system_lock);
|
|
sigprocmask(SIG_SETMASK, &old, NULL);
|
|
errno = saved;
|
|
return status;
|
|
}
|
|
|
|
// The streams popen() made, with their shells: pclose() waits for the one of its stream
|
|
struct ddnatv_popen {
|
|
FILE *fp;
|
|
pid_t pid;
|
|
struct ddnatv_popen *next;
|
|
};
|
|
static struct ddnatv_popen *g_popen_streams;
|
|
static pthread_mutex_t g_popen_lock = PTHREAD_MUTEX_INITIALIZER;
|
|
|
|
static pid_t start_shell(const char *command, int child_fd, int target_fd, const sigset_t *mask,
|
|
const struct sigaction *intr, const struct sigaction *quit, int close_popen_streams) {
|
|
// Through posix_spawn(), as glibc does: its child only makes system calls. A forked child running
|
|
// the exec code here would take locks that another thread of a multithreaded caller may have held
|
|
// at fork(), and wait for them forever (Steam's popen()s did, and its main loop stalled).
|
|
posix_spawn_file_actions_t actions;
|
|
posix_spawnattr_t attr;
|
|
if (posix_spawn_file_actions_init(&actions) != 0) return -1;
|
|
if (posix_spawnattr_init(&attr) != 0) {
|
|
posix_spawn_file_actions_destroy(&actions);
|
|
return -1;
|
|
}
|
|
int err = 0;
|
|
if (child_fd >= 0) {
|
|
// dup2 onto itself clears FD_CLOEXEC in the child (glibc 2.29 and later)
|
|
err = posix_spawn_file_actions_adddup2(&actions, child_fd, target_fd);
|
|
}
|
|
// POSIX: the streams of earlier popen() calls are not open in the new shell
|
|
for (struct ddnatv_popen *p = g_popen_streams; !err && close_popen_streams && p; p = p->next) {
|
|
int fd = fileno(p->fp);
|
|
if (fd >= 0 && fd != target_fd) err = posix_spawn_file_actions_addclose(&actions, fd);
|
|
}
|
|
short flags = 0;
|
|
if (!err && mask) {
|
|
posix_spawnattr_setsigmask(&attr, mask);
|
|
flags |= POSIX_SPAWN_SETSIGMASK;
|
|
}
|
|
// SIGINT and SIGQUIT as they were before system() ignored them: an exec keeps an ignored signal
|
|
// ignored and puts a handled one back to the default
|
|
sigset_t defaults;
|
|
sigemptyset(&defaults);
|
|
if (intr && intr->sa_handler != SIG_IGN) sigaddset(&defaults, SIGINT);
|
|
if (quit && quit->sa_handler != SIG_IGN) sigaddset(&defaults, SIGQUIT);
|
|
if (!err && (intr || quit)) {
|
|
posix_spawnattr_setsigdefault(&attr, &defaults);
|
|
flags |= POSIX_SPAWN_SETSIGDEF;
|
|
}
|
|
if (!err) err = posix_spawnattr_setflags(&attr, flags);
|
|
pid_t pid = -1;
|
|
char *const argv[] = { (char *)"sh", (char *)"-c", (char *)command, NULL };
|
|
if (!err) err = posix_spawn(&pid, "/bin/sh", &actions, &attr, argv, environ);
|
|
posix_spawn_file_actions_destroy(&actions);
|
|
posix_spawnattr_destroy(&attr);
|
|
if (err) {
|
|
errno = err;
|
|
return -1;
|
|
}
|
|
return pid;
|
|
}
|
|
|
|
FILE *popen(const char *command, const char *type) {
|
|
if (!command || !type || (type[0] != 'r' && type[0] != 'w')) {
|
|
errno = EINVAL;
|
|
return NULL;
|
|
}
|
|
int reading = type[0] == 'r';
|
|
int keep_on_exec = strchr(type, 'e') == NULL;
|
|
int fds[2];
|
|
if (pipe2(fds, O_CLOEXEC) != 0) return NULL;
|
|
int parent_end = reading ? fds[0] : fds[1];
|
|
int child_end = reading ? fds[1] : fds[0];
|
|
struct ddnatv_popen *entry = (struct ddnatv_popen *)malloc(sizeof(*entry));
|
|
if (!entry) {
|
|
close(fds[0]);
|
|
close(fds[1]);
|
|
errno = ENOMEM;
|
|
return NULL;
|
|
}
|
|
pthread_mutex_lock(&g_popen_lock);
|
|
pid_t pid = start_shell(command, child_end, reading ? STDOUT_FILENO : STDIN_FILENO, NULL, NULL, NULL, 1);
|
|
int saved = errno;
|
|
close(child_end);
|
|
FILE *fp = NULL;
|
|
if (pid > 0) {
|
|
if (keep_on_exec) fcntl(parent_end, F_SETFD, 0);
|
|
fp = fdopen(parent_end, reading ? "r" : "w");
|
|
saved = errno;
|
|
}
|
|
if (!fp) {
|
|
close(parent_end);
|
|
pthread_mutex_unlock(&g_popen_lock);
|
|
free(entry);
|
|
if (pid > 0) {
|
|
// A shell nobody will read or write: it is not left to run (or waited for while it does)
|
|
kill(pid, SIGKILL);
|
|
while (waitpid(pid, NULL, 0) < 0 && errno == EINTR) {}
|
|
}
|
|
errno = saved;
|
|
return NULL;
|
|
}
|
|
entry->fp = fp;
|
|
entry->pid = pid;
|
|
entry->next = g_popen_streams;
|
|
g_popen_streams = entry;
|
|
pthread_mutex_unlock(&g_popen_lock);
|
|
return fp;
|
|
}
|
|
|
|
int pclose(FILE *stream) {
|
|
struct ddnatv_popen *found = NULL;
|
|
pthread_mutex_lock(&g_popen_lock);
|
|
for (struct ddnatv_popen **p = &g_popen_streams; *p; p = &(*p)->next) {
|
|
if ((*p)->fp == stream) {
|
|
found = *p;
|
|
*p = found->next;
|
|
break;
|
|
}
|
|
}
|
|
// Closed before the lock is let go: a popen() in between would fork a shell that keeps this pipe open,
|
|
// and the shell of this stream would wait for its end of it
|
|
if (found) fclose(stream);
|
|
pthread_mutex_unlock(&g_popen_lock);
|
|
if (!found) {
|
|
// Not one of ours: glibc's own
|
|
static int (*orig_pclose)(FILE *) = NULL;
|
|
if (!orig_pclose) orig_pclose = (int (*)(FILE *))dlsym(RTLD_NEXT, "pclose");
|
|
if (!orig_pclose) {
|
|
errno = ECHILD;
|
|
return -1;
|
|
}
|
|
return orig_pclose(stream);
|
|
}
|
|
pid_t pid = found->pid;
|
|
free(found);
|
|
int status = -1;
|
|
pid_t r;
|
|
do {
|
|
r = waitpid(pid, &status, 0);
|
|
} while (r < 0 && errno == EINTR);
|
|
return r < 0 ? -1 : status;
|
|
}
|
|
|
|
#endif /* !DDNATV_HOST_TEST */
|