diff --git a/Cargo.lock b/Cargo.lock index 3c3a80f8b..3532803f6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1472,8 +1472,10 @@ dependencies = [ name = "fspy_elf_loader" version = "0.1.0" dependencies = [ + "allocator-api2", "elf", "fspy_nostd", + "fspy_nostd_alloc", "linux-raw-sys 0.12.1", "syscalls", "tempfile", @@ -1485,6 +1487,7 @@ version = "0.0.0" dependencies = [ "fspy_elf_loader", "fspy_nostd", + "syscalls", ] [[package]] diff --git a/crates/fspy_elf_loader/Cargo.toml b/crates/fspy_elf_loader/Cargo.toml index 692fb4bd1..c76eea038 100644 --- a/crates/fspy_elf_loader/Cargo.toml +++ b/crates/fspy_elf_loader/Cargo.toml @@ -9,9 +9,18 @@ publish.workspace = true rust-version.workspace = true [target.'cfg(any(target_os = "linux", target_os = "none"))'.dependencies] +allocator-api2 = { workspace = true } elf = { workspace = true } fspy_nostd = { workspace = true } -linux-raw-sys = { workspace = true, features = ["auxvec", "general", "no_std", "prctl"] } +fspy_nostd_alloc = { workspace = true } +linux-raw-sys = { workspace = true, features = [ + "auxvec", + "errno", + "general", + "no_std", + "prctl", + "ptrace", +] } syscalls = { workspace = true } [target.'cfg(target_os = "linux")'.dev-dependencies] diff --git a/crates/fspy_elf_loader/README.md b/crates/fspy_elf_loader/README.md index c18fa8c57..667c87b78 100644 --- a/crates/fspy_elf_loader/README.md +++ b/crates/fspy_elf_loader/README.md @@ -50,9 +50,14 @@ reserved ranges. - Startup stack: contiguous argv/envp strings, rebuilt auxv, copied `AT_RANDOM` / platform strings, inherited scalars and resident vDSO. - Naked enter stubs: install SP, clear dirty GPRs, jump (no return address). +- `SIGSYS` signal, `/proc/*/exe`, and custom `SyscallInterceptor` virtualization + with a private pooled `SIGSYS` stack, virtualized `rt_sigaction` / + `rt_sigprocmask` / `rt_sigpending` / masked waits / `fork` / `vfork`, and + direct user memory copies that assume valid pointers. +- Wired into `fspy` via `fspy_preload_linux` as the sole Linux tracking backend. - [`fspy_elf_loader_tests`](../fspy_elf_loader_tests/README.md): dynamic and - static PIE/`ET_EXEC` runtimes, overlap rejection, malformed images. An - ignored Node test exists (`--include-ignored` on Linux with Node on `PATH`). + static PIE/`ET_EXEC` runtimes, overlap rejection, malformed images, and + `SIGSYS` + `/proc/*/exe` virtualization coverage. ## Not a complete exec @@ -61,25 +66,19 @@ Do not try to close these in this crate unless a real target requires it: - **`brk` / `start_brk`.** The kernel's brk belongs to the high launcher mapping. It cannot be moved to a Linux-faithful image end. glibc malloc still works via mmap; leave brk alone. -- **`/proc` identity.** `/proc/self/exe` and parent-visible `/proc//exe` - still name the launcher. Parent `/proc//exe` is not a JS/Chromium - identity gate. `/proc/self/exe` is, and needs virtualization later. -- GNU properties, executable stacks, ELF32, other arches, growable stack - (fixed 8 MiB + guard), fd/signal/personality cleanup. +- **External `/proc` views.** `/proc/self/exe` and `/proc//exe` are + virtualized inside the tracked process, while external `/proc//exe` + observers still see the launcher binary. +- **Privileged / unsupported binaries.** `PR_SET_NO_NEW_PRIVS` is enabled for + seccomp (so setuid/setgid and file-capability escalations do not apply), and + ELF32 and `binfmt_misc` binaries are rejected with `ENOEXEC`. +- **Launcher path visibility across mount changes.** Every tracked `execve` + re-enters the materialized freestanding launcher binary on disk. If a tracked + process tree changes its mount namespace or root (`chroot`, `pivot_root`, or + a private `/tmp` mount hiding the materialized launcher path), subsequent + child `execve` calls fail with `ENOENT`. +- GNU properties, other arches, growable stack (fixed 8–64 MiB from + `RLIMIT_STACK` + guard), and personality cleanup. Load failures panic and terminate. `exec_elf` is for a fresh single-threaded process with no libc or TLS init. Trusted images only; this is not a sandbox. - -## Product work (elsewhere) - -fspy still spawns with `LD_PRELOAD` or `seccomp_unotify`. The loader is not -wired in. Remaining work is to make launcher + userland shebang + `exec_elf` -the only Linux spawn: - -1. Shebang and PATH above `exec_elf`, then load the resulting ELF. Scripts - never hit kernel `binfmt_script`. Nested `execve` must re-enter this path - instead of kernel-execing the child image. -2. Virtualize `/proc/self/exe` so the target sees its own path (`process.execPath` - / `fs.realpath`). The ignored Node test does not do this. -3. Drop the Linux preload/seccomp spawn split. One intercept setup in the - launcher covers dynamic glibc, musl, and static images. diff --git a/crates/fspy_elf_loader/src/lib.rs b/crates/fspy_elf_loader/src/lib.rs index e88b1838c..438f4b781 100644 --- a/crates/fspy_elf_loader/src/lib.rs +++ b/crates/fspy_elf_loader/src/lib.rs @@ -10,23 +10,151 @@ //! executable and enters its `e_entry`. `AT_BASE` is 0. Static-PIE images are //! `ET_DYN` without an interpreter; their CRT applies `RELATIVE` relocations. //! -//! We implement the mapping, stack, and entry steps after the kernel has -//! already executed our freestanding loader. We leave its mappings and signal -//! handlers in place. Calling another kernel exec here would discard them. +//! We implement the mapping, stack, `SIGSYS` virtualization, and entry steps +//! after the kernel has already executed our freestanding launcher. We leave +//! its mappings and signal handlers in place. Calling another kernel exec here +//! would discard them. #![cfg(any(target_os = "linux", target_os = "none"))] #![no_std] #[cfg(test)] extern crate std; +use core::{ptr, slice}; + +use elf::{abi, endian::LittleEndian, file::Class, segment::SegmentTable}; use fspy_nostd::{BorrowedFd, CStr, OwnedFd, Result, Thin, env::AuxEntry}; -use linux_raw_sys::{auxvec::AT_PAGESZ, prctl::PR_SET_NAME}; +use linux_raw_sys::{ + auxvec::{AT_NULL, AT_PAGESZ, AT_PHDR, AT_PHENT, AT_PHNUM}, + prctl::PR_SET_NAME, +}; use syscalls::Sysno; mod image; mod mapping; +mod sigsys; mod stack; +#[cfg(target_arch = "x86_64")] +const LAUNCHER_REGION: (usize, usize) = (0x5500_0000_0000, 0x5a00_0000_0000); +#[cfg(target_arch = "aarch64")] +const LAUNCHER_REGION: (usize, usize) = (0x0002_0000_0000, 0x0005_0000_0000); + +/// Decoded syscall invocation passed to a [`SyscallInterceptor`]. +#[derive(Clone, Copy, Debug)] +pub struct Syscall { + pub sysno: Sysno, + pub args: [usize; 6], + raw_uc_sigmask: u64, +} + +impl Syscall { + /// Returns the calling thread's virtualized signal mask prior to this + /// syscall (including the virtualized `SIGSYS` bit). + /// + /// Computed lazily because only `execve`/`execveat` interceptors typically + /// need it; avoids a `gettid` syscall on hot filesystem traps. + /// + /// Because the `SIGSYS` dispatcher masks asynchronous signals while running + /// the interceptor, an interceptor returning [`SyscallAction::Execve`] must + /// propagate or restore this mask in the new image. + #[must_use] + pub fn sigmask(&self) -> u64 { + sigsys::virtual_sigmask_from(self.raw_uc_sigmask) + } + + /// Returns `true` when executing inside a `CLONE_VM` (`vfork` / + /// `posix_spawn`) child that still shares its address space with the parent + /// process. + /// + /// Computed lazily to avoid a `getpid` syscall on hot filesystem traps. + #[must_use] + #[expect(clippy::unused_self, reason = "scopes the query to an active SIGSYS trap")] + pub fn is_shared_vm_child(&self) -> bool { + sigsys::is_shared_vm_child() + } +} + +/// Failure-cleanup callback and context pointer attached to +/// [`SyscallAction::Execve`]. +pub type ExecveCleanup = (unsafe fn(*mut core::ffi::c_void), *mut core::ffi::c_void); + +/// Action returned by a [`SyscallInterceptor`] to tell the `SIGSYS` dispatcher +/// how to complete the trapped syscall after releasing the private `SIGSYS` +/// stack. +#[derive(Clone, Copy, Debug)] +pub enum SyscallAction { + /// Replay the (possibly `/proc/*/exe`-rewritten) trapped syscall. + Replay, + /// Execute a replacement `SYS_execve(prog, argv, envp)` on the entry stack + /// after releasing the private `SIGSYS` stack and clearing the calling + /// thread's virtual `SIGSYS` mask entry. + /// + /// If `SYS_execve` fails, `cleanup` (when `Some`) is invoked with its + /// context pointer before returning `-errno` to the caller. + Execve { + prog: *const u8, + argv: *const *const u8, + envp: *const *const u8, + cleanup: Option, + }, +} + +/// Optional caller-supplied syscall interceptor invoked from the loader's +/// `SIGSYS` dispatcher. +/// +/// The listed `syscalls` are merged into the seccomp-BPF filter alongside the +/// loader's own virtualization syscalls. Signal-virtualization syscalls and +/// `/proc/*/exe` `readlink` calls are handled directly by the loader; for +/// path-following syscalls targeting `/proc/*/exe`, `handle` observes the +/// already-rewritten target executable path. +/// +/// Returning `Ok(SyscallAction::Replay)` replays the syscall; returning +/// `Ok(SyscallAction::Execve { .. })` releases the private `SIGSYS` stack +/// before executing the replacement `SYS_execve`; returning `Err(error)` +/// short-circuits the syscall and returns `-error.raw_os_error()` directly to +/// the caller. +#[derive(Clone, Copy)] +pub struct SyscallInterceptor { + pub syscalls: &'static [Sysno], + pub handle: unsafe fn(&Syscall) -> Result, +} + +/// Borrows a NUL-terminated C string directly from a trapped syscall's user +/// pointer. +/// +/// # Errors +/// +/// Returns [`fspy_nostd::Error::FAULT`] if `addr` is in the first page (such as +/// `NULL`). +/// +/// # Safety +/// +/// Any other `addr` must point to a readable NUL-terminated string valid for +/// `'a`. Like the macOS and Windows preloads, the runtime assumes the pointers +/// programs pass to syscalls are valid; a bad one crashes the process instead +/// of failing with `EFAULT`. +pub unsafe fn user_cstr<'a>(addr: usize) -> Result> { + // SAFETY: forwarded from caller contract. + unsafe { sigsys::user_cstr(addr) } +} + +/// Copies a `Copy` value from a trapped syscall's user pointer. +/// +/// # Errors +/// +/// Returns [`fspy_nostd::Error::FAULT`] if `addr` is in the first page (such as +/// `NULL`). +/// +/// # Safety +/// +/// `T` must be valid for any bit pattern, and any other `addr` must be +/// readable for `size_of::()` bytes (see [`user_cstr`]). +pub unsafe fn copy_user_value(addr: usize) -> Result { + // SAFETY: forwarded from caller contract. + unsafe { sigsys::copy_user_value(addr) } +} + /// Validates that `fd` refers to a loadable ELF64 executable (and, if present, /// a valid `PT_INTERP` dynamic interpreter) without mapping execution segments, /// mutating process state, or closing `fd`. @@ -40,61 +168,48 @@ pub fn validate_exec(fd: BorrowedFd<'_>) -> Result<()> { image::validate_exec_fd(fd, fspy_nostd::param::page_size()) } -/// Loads an ELF executable into the current process and enters it. +/// Loads an ELF executable into the current process, installs `SIGSYS` +/// virtualization (plus any optional `interceptor`), and enters it. /// /// Takes ownership of a private executable descriptor and closes it after /// mapping. Loads the executable and, when present, its `PT_INTERP`. Sets the /// process name (`PR_SET_NAME`) to the basename of `execfn`, sizes the new -/// stack from `RLIMIT_STACK` (clamped to `[8 MiB, 64 MiB]`), builds an initial -/// stack, and transfers control to the interpreter, or to the executable when -/// there is no interpreter. +/// stack from `RLIMIT_STACK` (clamped to `[8 MiB, 64 MiB]`), installs the +/// `SIGSYS` + `/proc/*/exe` + seccomp-BPF runtime, builds the initial stack, +/// and transfers control to the interpreter (or directly to the executable when +/// there is no interpreter). /// /// `execfn` is the original execution name used for `AT_EXECFN` and /// `PR_SET_NAME`; it need not match `argv[0]`. Arguments and environment /// entries are copied to the new stack. `inherited_auxv` borrows entries from -/// the loader's original kernel stack, excluding `AT_NULL`. Its `AT_PAGESZ` -/// supplies the page size used for mapping. Image-specific entries are -/// replaced, reusable entries are preserved, and referenced data is copied -/// where needed. The resulting vector ends with `AT_NULL`. -/// -/// Path resolution, shebang handling, and execution-policy checks belong to -/// the caller. This function does not perform kernel exec cleanup: installed -/// signal handlers and their resident code and state must remain usable. -/// Loading failures terminate the process; they cannot return to the program -/// that executed the loader. -/// -/// Currently supports native little-endian ELF64 executables on `AArch64` and -/// x86-64. Both PIE (`ET_DYN`) and fixed-address -/// (`ET_EXEC`) images are supported, with or without `PT_INTERP`. -/// Fixed-address images must not overlap any existing process mappings. -/// Existing loader mappings, the old stack, and kernel process metadata -/// (including `/proc` identity and `brk`) are retained. This does not emulate -/// a complete exec. Processor-specific GNU properties are not applied. +/// the launcher's original kernel stack, excluding `AT_NULL`. /// /// # Safety /// -/// Call only from a fresh, single-threaded loader process. The executable and -/// interpreter must be trusted to run with the process's current privileges. -/// Their backing files must remain unchanged throughout loading. The loader -/// must not have initialized libc or thread-local runtime state. -/// Auxiliary entries must describe this process; any referenced memory must -/// remain readable and unchanged until copied or retained for the target. -/// The caller must permit execution to abandon its stack without running -/// destructors. Any retained handlers, mappings, or other process state must -/// remain valid while the target runs. +/// Call only from a fresh, single-threaded freestanding launcher process linked +/// with this crate's `link_args` metadata (`--no-pie` at the high fixed base +/// address). The executable and interpreter must be trusted to run with the +/// process's current privileges. Their backing files must remain unchanged +/// throughout loading. The launcher must not have initialized libc or +/// thread-local runtime state. Auxiliary entries must describe this process; +/// any referenced memory must remain readable and unchanged until copied or +/// retained for the target. The caller must permit execution to abandon its +/// stack without running destructors. Any installed `interceptor.handle` must +/// be async-signal-safe and live inside the launcher's `PF_X` code segment. /// /// # Panics /// -/// Panics when `AT_PAGESZ` is missing or invalid, loading detects an unsupported -/// or malformed image, runs out of stack capacity, or fails to map or open a -/// file. The freestanding panic handler must terminate the process. Faults -/// after entering the interpreter or executable are not converted into panics. +/// Panics when the launcher image violates its high fixed-address `PF_X` +/// invariants, `AT_PAGESZ` is missing or invalid, loading detects an +/// unsupported or malformed image, runs out of stack capacity, fails to map or +/// open a file, or fails to install the `SIGSYS`/seccomp runtime. pub unsafe fn exec_elf<'a>( elf_file: OwnedFd, execfn: CStr<'a, Thin>, argv: impl Iterator>, envp: impl Iterator>, inherited_auxv: &[AuxEntry], + interceptor: Option, ) -> ! { let page_size = inherited_auxv .iter() @@ -103,6 +218,18 @@ pub unsafe fn exec_elf<'a>( .value; assert!(page_size.is_power_of_two(), "invalid AT_PAGESZ"); + // Verify the launcher's own fixed-address ELF layout and locate its `PF_X` + // `PT_LOAD` range `[code_start, code_end)` for seccomp IP allowlisting. + // SAFETY: caller supplies the kernel auxiliary vector for this process. + let code_range = unsafe { locate_launcher_code_range(inherited_auxv) }; + if let Some(ref ic) = interceptor { + let handle_addr = (ic.handle as *const ()).addr() as u64; + assert!( + code_range.0 <= handle_addr && handle_addr < code_range.1, + "SyscallInterceptor::handle outside launcher PF_X range" + ); + } + let executable = image::File::open(elf_file.as_fd()).expect("invalid ELF executable"); let executable_layout = executable.validate_segments(page_size).expect("invalid ELF executable segments"); @@ -145,6 +272,18 @@ pub unsafe fn exec_elf<'a>( // Match kernel execve's `/proc/self/comm` basename update. set_process_name(execfn); + // Install SIGSYS + /proc/*/exe + seccomp virtualization while `elf_file` + // is still open so `/proc/self/fd/` resolves the canonical target path. + let min_sigstksz = inherited_auxv + .iter() + .find(|entry| entry.key == 51) // AT_MINSIGSTKSZ + .map_or(0, |entry| entry.value); + // SAFETY: fresh single-threaded launcher with validated resident `code_range`. + unsafe { + sigsys::install(code_range, elf_file.as_fd(), execfn, min_sigstksz, page_size, interceptor) + } + .expect("cannot install SIGSYS virtualization runtime"); + // With PT_INTERP, the interpreter runs first even though AT_ENTRY points // at the executable. It uses that value to hand off after linking. // Without PT_INTERP, AT_BASE is 0 and the executable's e_entry starts. @@ -166,6 +305,90 @@ pub unsafe fn exec_elf<'a>( unsafe { enter(entry, stack) } } +/// Parses `inherited_auxv` (`AT_PHDR`, `AT_PHENT`, `AT_PHNUM`) to locate and +/// validate the launcher's own `PF_X` `PT_LOAD` range `[code_start, code_end)`. +/// +/// # Safety +/// +/// `inherited_auxv` must be the live kernel auxiliary vector for the current +/// process. +unsafe fn locate_launcher_code_range(inherited_auxv: &[AuxEntry]) -> (u64, u64) { + let mut phdr_addr = None; + let mut phent = None; + let mut phnum = None; + for entry in inherited_auxv { + let Ok(key) = u32::try_from(entry.key) else { + continue; + }; + match key { + AT_NULL => break, + AT_PHDR => phdr_addr = Some(entry.value), + AT_PHENT => phent = Some(entry.value), + AT_PHNUM => phnum = Some(entry.value), + _ => {} + } + } + + let phdr_addr = phdr_addr.expect("missing AT_PHDR"); + let phent = phent.expect("missing AT_PHENT"); + let phnum = phnum.expect("missing AT_PHNUM"); + assert_eq!(phent, image::PHDR_SIZE, "unexpected launcher AT_PHENT"); + assert!(phnum > 0, "empty launcher AT_PHNUM"); + + let (region_base, region_limit) = LAUNCHER_REGION; + assert!( + phdr_addr >= region_base && phdr_addr < region_limit, + "launcher AT_PHDR outside expected high fixed region" + ); + let table_len = phnum.checked_mul(phent).expect("launcher program-header table overflow"); + // SAFETY: `AT_PHDR` points to `AT_PHNUM` contiguous `Elf64_Phdr` entries + // mapped into this process by the kernel. + let raw_phdrs = + unsafe { slice::from_raw_parts(ptr::with_exposed_provenance::(phdr_addr), table_len) }; + let segments = SegmentTable::new(LittleEndian, Class::ELF64, raw_phdrs); + + let mut code_range: Option<(usize, usize)> = None; + for seg in segments.iter() { + assert!( + !matches!(seg.p_type, abi::PT_INTERP | abi::PT_DYNAMIC | abi::PT_TLS), + "launcher must not contain PT_INTERP, PT_DYNAMIC, or PT_TLS" + ); + if seg.p_type == abi::PT_PHDR { + assert_eq!( + usize::try_from(seg.p_vaddr).ok(), + Some(phdr_addr), + "launcher must be loaded without relocation bias" + ); + } + if seg.p_type == abi::PT_LOAD && seg.p_memsz != 0 { + let start = usize::try_from(seg.p_vaddr).expect("launcher PT_LOAD vaddr overflow"); + let memsz = usize::try_from(seg.p_memsz).expect("launcher PT_LOAD memsz overflow"); + let end = start.checked_add(memsz).expect("launcher PT_LOAD end overflow"); + assert!( + start >= region_base && end <= region_limit, + "launcher PT_LOAD outside expected high fixed region" + ); + if (seg.p_flags & abi::PF_X) != 0 { + assert!(code_range.is_none(), "launcher must have a single executable PT_LOAD"); + code_range = Some((start, end)); + } + } + } + + let (code_start, code_end) = code_range.expect("launcher missing executable PT_LOAD"); + let enter_addr = (enter as *const ()).addr(); + let handler_addr = sigsys::handler_addr(); + assert!( + code_start <= enter_addr && enter_addr < code_end, + "exec_elf entry stub outside launcher PF_X range" + ); + assert!( + code_start <= handler_addr && handler_addr < code_end, + "SIGSYS handler outside launcher PF_X range" + ); + (code_start as u64, code_end as u64) +} + /// Sets `/proc/self/comm` via `prctl(PR_SET_NAME)` to the basename of `execfn` /// truncated to 15 bytes + NUL. fn set_process_name(execfn: CStr<'_, Thin>) { diff --git a/crates/fspy_elf_loader/src/sigsys/arch.rs b/crates/fspy_elf_loader/src/sigsys/arch.rs new file mode 100644 index 000000000..7b7be0118 --- /dev/null +++ b/crates/fspy_elf_loader/src/sigsys/arch.rs @@ -0,0 +1,1164 @@ +//! Architecture-specific Linux ABI primitives for `SIGSYS` interception. +//! +//! Provides: +//! - The freestanding `rt_sigreturn` restorer trampoline (`SA_RESTORER`). +//! - Kernel `ucontext_t` / `sigaction` layouts and register accessors for +//! x86-64 and `AArch64`. +//! - Raw 6-argument syscall replay and signal/PID helpers executed directly +//! from the launcher's allowlisted `PF_X` code range. + +use core::ffi::c_void; + +use linux_raw_sys::general::{SIGKILL, SIGSTOP, SIGSYS}; +use syscalls::Sysno; + +/// Bitmask for `SIGSYS` (signal 31) in a 64-bit Linux kernel `sigset_t`. +pub const SIGSYS_BIT: u64 = 1_u64 << (SIGSYS - 1); + +/// Unblockable signals stripped by the Linux kernel from `sa_mask` and +/// signal masks (`SIGKILL` and `SIGSTOP`). +pub const UNBLOCKABLE_MASK: u64 = (1_u64 << (SIGKILL - 1)) | (1_u64 << (SIGSTOP - 1)); + +/// Mask installed on our `SIGSYS` `sigaction.sa_mask` so asynchronous signals +/// cannot preempt the dispatcher while it runs on a private pooled stack or +/// modifies virtualized signal state. +pub const HANDLER_BLOCK_MASK: u64 = !(SIGSYS_BIT | UNBLOCKABLE_MASK); + +/// Size of the Linux kernel `sigset_t` on 64-bit architectures (8 bytes = 64 signals). +pub const KERNEL_SIGSET_SIZE: usize = core::mem::size_of::(); + +/// Native seccomp audit architecture constant (`seccomp_data.arch`). +#[cfg(target_arch = "x86_64")] +pub const AUDIT_ARCH_NATIVE: u32 = linux_raw_sys::ptrace::AUDIT_ARCH_X86_64; + +/// Native seccomp audit architecture constant (`seccomp_data.arch`). +#[cfg(target_arch = "aarch64")] +pub const AUDIT_ARCH_NATIVE: u32 = linux_raw_sys::ptrace::AUDIT_ARCH_AARCH64; + +/// Linux kernel `struct sigaction` layout used by `rt_sigaction` on both +/// x86-64 and `AArch64`. +#[expect(clippy::struct_field_names, reason = "matches Linux UAPI struct sigaction field names")] +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +#[repr(C)] +pub struct KernelSigaction { + pub sa_handler: usize, + pub sa_flags: usize, + pub sa_restorer: usize, + pub sa_mask: u64, +} + +const _: () = { + use core::mem::{offset_of, size_of}; + + use linux_raw_sys::general::siginfo; + assert!(size_of::() == 32); + assert!(offset_of!(KernelSigaction, sa_handler) == 0); + assert!(offset_of!(KernelSigaction, sa_flags) == 8); + assert!(offset_of!(KernelSigaction, sa_restorer) == 16); + assert!(offset_of!(KernelSigaction, sa_mask) == 24); + // `sigsys_trampoline` reads `si_errno` at +4 and `si_code` at +8 directly. + assert!(offset_of!(siginfo, __bindgen_anon_1.__bindgen_anon_1.si_signo) == 0); + assert!(offset_of!(siginfo, __bindgen_anon_1.__bindgen_anon_1.si_errno) == 4); + assert!(offset_of!(siginfo, __bindgen_anon_1.__bindgen_anon_1.si_code) == 8); +}; + +/// Decoded syscall invocation captured from a `SIGSYS` `ucontext_t`. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[repr(C)] +pub struct SyscallInvocation { + pub nr: usize, + pub args: [usize; 6], +} + +const _: () = { + use core::mem::{offset_of, size_of}; + assert!(size_of::() == 56); + assert!(offset_of!(SyscallInvocation, nr) == 0); + assert!(offset_of!(SyscallInvocation, args) == 8); +}; + +/// Linux `stack_t` (`struct sigaltstack`) inside `ucontext_t`. +#[repr(C)] +pub struct StackT { + pub ss_sp: *mut c_void, + pub ss_flags: i32, + pub _pad: i32, + pub ss_size: usize, +} + +#[cfg(target_arch = "x86_64")] +mod imp { + use core::{arch::naked_asm, ffi::c_void, mem::size_of, ptr}; + + use linux_raw_sys::{ + errno::ENOMEM, + general::{SIG_SETMASK, SYS_SECCOMP}, + }; + use syscalls::Sysno; + + use super::{StackT, SyscallInvocation}; + use crate::sigsys::filter::TRAP_TAG; + + pub const REG_R8: usize = 0; + pub const REG_R9: usize = 1; + pub const REG_R10: usize = 2; + pub const REG_RDI: usize = 8; + pub const REG_RSI: usize = 9; + pub const REG_RDX: usize = 12; + pub const REG_RAX: usize = 13; + pub const REG_RSP: usize = 15; + pub const REG_RIP: usize = 16; + + #[repr(C)] + pub struct Mcontext { + pub gregs: [u64; 23], + pub fpregs: *mut c_void, + pub _reserved: [u64; 8], + } + + #[expect(clippy::struct_field_names, reason = "matches Linux UAPI struct ucontext field names")] + #[repr(C)] + pub struct Ucontext { + pub uc_flags: u64, + pub uc_link: *mut Self, + pub uc_stack: StackT, + pub uc_mcontext: Mcontext, + pub uc_sigmask: u64, + } + + const UC_STACK_OFFSET: usize = 16; + const UC_GREGS_OFFSET: usize = 40; + const UC_FPREGS_OFFSET: usize = UC_GREGS_OFFSET + 23 * 8; + const UC_SIGMASK_OFFSET: usize = 296; + const UC_NR_OFFSET: usize = UC_GREGS_OFFSET + REG_RAX * 8; + + const _: () = { + use core::mem::offset_of; + assert!(offset_of!(Ucontext, uc_flags) == 0); + assert!(offset_of!(Ucontext, uc_link) == 8); + assert!(offset_of!(Ucontext, uc_stack) == UC_STACK_OFFSET); + assert!(offset_of!(Ucontext, uc_mcontext) == UC_GREGS_OFFSET); + assert!( + offset_of!(Ucontext, uc_mcontext) + offset_of!(Mcontext, fpregs) == UC_FPREGS_OFFSET + ); + assert!(offset_of!(Ucontext, uc_sigmask) == UC_SIGMASK_OFFSET); + assert!(UC_NR_OFFSET == offset_of!(Ucontext, uc_mcontext) + REG_RAX * 8); + }; + + #[unsafe(naked)] + pub unsafe extern "C" fn sigsys_trampoline() { + // Entry from kernel `SA_SIGINFO` delivery: + // rdi = signum, rsi = *mut siginfo, rdx = *mut Ucontext, + // [rsp] = sigreturn_trampoline (rsp % 16 == 8). + // + // Performs foreign-SIGSYS and masked-wait checks with ZERO stack bytes, + // then allocates only an 88-byte frame (80-byte `Phase2Packet` + align) + // on the entry stack and switches immediately to a private 64 KiB stack + // before running Rust Phase 1. Kernel `rt_sigreturn` restores all GPRs + // from `ucontext`, so `rbx`/`r12`/`r13` need not be saved. + naked_asm!( + "test rsi, rsi", + "jz 2f", + "cmp dword ptr [rsi + 8], {sys_seccomp}", + "jne 2f", + "cmp dword ptr [rsi + 4], {trap_tag}", + "jne 2f", + "test rdx, rdx", + "jz 3f", + "mov rax, [rdx + {uc_nr_off}]", + "cmp rax, {nr_rt_sigsuspend}", + "je 4f", + "cmp rax, {nr_ppoll}", + "je 4f", + "cmp rax, {nr_pselect6}", + "je 4f", + "cmp rax, {nr_epoll_pwait}", + "je 4f", + "cmp rax, {nr_epoll_pwait2}", + "je 4f", + // Entry stack frame: 88 bytes (`rsp % 16 == 0` before `call`). + "sub rsp, 88", + "mov rbx, rdx", + "mov r13, rsp", + // Lock-free pop from `STACK_POOL` with ZERO extra entry-stack bytes. + "lea r8, [rip + {stack_pool}]", + "mov ecx, {pool_slots}", + "10:", + "cmp qword ptr [r8], 0", + "je 11f", + "xor eax, eax", + "xchg [r8], rax", + "test rax, rax", + "jnz 12f", + "11:", + "add r8, 8", + "dec ecx", + "jnz 10b", + "call {alloc_stack}", + "12:", + "mov r12, rax", + "test r12, r12", + "jz 6f", + // Switch RSP to private 64 KiB stack (`r12 - 16`, 16-byte aligned). + "lea rsp, [r12 - 16]", + "mov [rsp], r13", + "mov rdi, rbx", + "mov rsi, r13", + "call {handle_phase1}", + "mov rsp, r13", + // Lock-free push back to `STACK_POOL` with ZERO extra entry-stack bytes. + "lea r8, [rip + {stack_pool}]", + "mov ecx, {pool_slots}", + "13:", + "cmp qword ptr [r8], 0", + "jne 14f", + "xor eax, eax", + "lock cmpxchg [r8], r12", + "je 7f", + "14:", + "add r8, 8", + "dec ecx", + "jnz 13b", + "mov rdi, r12", + "call {free_stack}", + "jmp 7f", + "6:", + // OOM fallback: run Phase 1 on current stack. + "mov rdi, rbx", + "mov rsi, r13", + "call {handle_phase1}", + "7:", + "mov rdx, [r13 + 72]", + "test rdx, rdx", + "jz 5f", + "mov rdi, rbx", + "mov rsi, r13", + "call {finish_phase2}", + "5:", + "add rsp, 88", + "3:", + "ret", + "4:", + "mov rdi, rdx", + "jmp {masked_wait}", + "2:", + "jmp {foreign_sigsys}", + sys_seccomp = const SYS_SECCOMP.cast_signed(), + trap_tag = const TRAP_TAG as i32, + uc_nr_off = const UC_NR_OFFSET, + nr_rt_sigsuspend = const Sysno::rt_sigsuspend as usize, + nr_ppoll = const Sysno::ppoll as usize, + nr_pselect6 = const Sysno::pselect6 as usize, + nr_epoll_pwait = const Sysno::epoll_pwait as usize, + nr_epoll_pwait2 = const Sysno::epoll_pwait2 as usize, + pool_slots = const crate::sigsys::stack_pool::STACK_POOL_SLOTS, + stack_pool = sym crate::sigsys::stack_pool::STACK_POOL, + alloc_stack = sym crate::sigsys::stack_pool::alloc_stack_raw, + free_stack = sym crate::sigsys::stack_pool::free_stack_raw, + handle_phase1 = sym crate::sigsys::sigsys_phase1, + finish_phase2 = sym crate::sigsys::sigsys_phase2, + masked_wait = sym crate::sigsys::sigsys_masked_wait, + foreign_sigsys = sym crate::sigsys::sigsys_foreign, + ); + } + + #[unsafe(naked)] + pub unsafe extern "C" fn sigreturn_trampoline() -> ! { + naked_asm!( + "mov rax, {nr}", + "syscall", + "ud2", + nr = const Sysno::rt_sigreturn as usize, + ); + } + + #[unsafe(naked)] + pub unsafe extern "C" fn call_on_stack( + stack_top: usize, + arg: *mut c_void, + entry: extern "C" fn(*mut c_void), + ) { + naked_asm!( + "lea r11, [rdi - 16]", + "mov [r11], rsp", + "mov rsp, r11", + "mov rdi, rsi", + "call rdx", + "mov rsp, [rsp]", + "ret", + ); + } + + #[unsafe(naked)] + unsafe extern "C" fn replay_unmasked_raw( + inv: *const SyscallInvocation, + orig_mask: *const u64, + blocked_mask: *const u64, + ) -> isize { + // rdi = inv, rsi = orig_mask, rdx = blocked_mask. + // Linux x86-64 `syscall` preserves rbx and r12..r15. + naked_asm!( + "push rbx", + "push r12", + "push r13", + "mov rbx, rdi", + "mov r12, rdx", + // Unmask `orig_mask` for the duration of the replayed syscall. + "mov eax, {nr_rt_sigprocmask}", + "mov edi, {sig_setmask}", + "xor edx, edx", + "mov r10d, 8", + "syscall", + // Replay the trapped syscall directly from `inv`. + "mov rax, [rbx + 0]", + "mov rdi, [rbx + 8]", + "mov rsi, [rbx + 16]", + "mov rdx, [rbx + 24]", + "mov r10, [rbx + 32]", + "mov r8, [rbx + 40]", + "mov r9, [rbx + 48]", + "syscall", + "mov r13, rax", + // Re-block maskable signals before returning to Rust. + "mov eax, {nr_rt_sigprocmask}", + "mov edi, {sig_setmask}", + "mov rsi, r12", + "xor edx, edx", + "mov r10d, 8", + "syscall", + "mov rax, r13", + "pop r13", + "pop r12", + "pop rbx", + "ret", + sig_setmask = const SIG_SETMASK as usize, + nr_rt_sigprocmask = const Sysno::rt_sigprocmask as usize, + ); + } + + unsafe extern "C" { + static __fspy_elf_loader_masked_wait_ret_pc: u8; + } + + #[unsafe(naked)] + unsafe extern "C" fn replay_masked_wait_raw(inv: *const SyscallInvocation) -> isize { + // rdi = inv. + naked_asm!( + "mov rax, [rdi + 0]", + "mov rsi, [rdi + 16]", + "mov rdx, [rdi + 24]", + "mov r10, [rdi + 32]", + "mov r8, [rdi + 40]", + "mov r9, [rdi + 48]", + "mov rdi, [rdi + 8]", + "syscall", + ".globl __fspy_elf_loader_masked_wait_ret_pc", + ".hidden __fspy_elf_loader_masked_wait_ret_pc", + "__fspy_elf_loader_masked_wait_ret_pc:", + "ret", + ); + } + + #[inline] + pub fn masked_wait_return_pc() -> usize { + (&raw const __fspy_elf_loader_masked_wait_ret_pc).addr() + } + + #[inline] + pub unsafe fn replay_masked_wait(inv: &SyscallInvocation, _ucontext: &Ucontext) -> isize { + // SAFETY: forwarded from caller contract. + unsafe { replay_masked_wait_raw(inv) } + } + + /// Builds a private child `ucontext` in the upper half of `altstack_top` + /// so the `vfork`/`posix_spawn` child can install its `sigaltstack` and + /// return via `SYS_rt_sigreturn` (preserving all GPRs, FPU/AVX/AMX state, + /// and `eflags`). + /// + /// Returns the `rsp` value (`&child_uc`) to pass to `SYS_clone` and + /// `SYS_rt_sigreturn`, or `None` if `altstack_size` is too small. + pub unsafe fn prepare_vfork_child_sigframe( + ucontext: *const Ucontext, + altstack_top: usize, + altstack_size: usize, + orig_child_stack: usize, + child_sigmask: u64, + ) -> Option { + let half = (altstack_size / 2) & !4095; + if half < 4096 || altstack_size.saturating_sub(half) < size_of::() + 64 { + return None; + } + let altstack_base = altstack_top - altstack_size; + // Leave 16 bytes above `altstack_base + half` so `rt_sigreturn`'s + // `access_ok(rsp - 8, ...)` stays strictly inside the upper half. + let child_uc_addr = altstack_base + half + 16; + let child_uc_ptr = ptr::with_exposed_provenance_mut::(child_uc_addr); + // SAFETY: `ucontext` points to the live kernel `Ucontext` and + // `child_uc_ptr` owns `size_of::()` writable bytes. + unsafe { + ptr::copy_nonoverlapping(ucontext, child_uc_ptr, 1); + let child_uc = &mut *child_uc_ptr; + child_uc.uc_mcontext.gregs[REG_RAX] = 0; + if orig_child_stack != 0 { + child_uc.uc_mcontext.gregs[REG_RSP] = orig_child_stack as u64; + } + child_uc.uc_sigmask = child_sigmask; + child_uc.uc_stack = StackT { + ss_sp: ptr::with_exposed_provenance_mut(altstack_base), + ss_flags: 0, + _pad: 0, + ss_size: half, + }; + } + Some(child_uc_addr) + } + + /// Replays `clone(CLONE_VM | CLONE_VFORK, non_null_stack, ...)` starting + /// the child on `child_sigreturn_sp` (`&child_uc`), where the child + /// installs its pooled `sigaltstack` and returns via `SYS_rt_sigreturn` + /// (restoring all GPRs, FPU/AVX/AMX state, `eflags`, and `sigmask`). + /// Processes running with a CET shadow stack are not supported here. + #[unsafe(naked)] + pub unsafe extern "C" fn replay_vfork_with_altstack( + inv: *const SyscallInvocation, + child_sigreturn_sp: usize, + altstack_size: usize, + save_top: usize, + ) -> isize { + naked_asm!( + "push rbp; push rbx; push r12", + "mov rbp, rsp; mov r12, rdi; mov r8, rsi; xor ebx, ebx", + "test rcx, rcx; jz 3f", + "mov rax, [r12 + 16]; sub rax, rbp; jbe 3f", + "mov r10, rdx; shr r10, 1; sub r10, 128; cmp rax, r10; ja 9f", + "mov rbx, rax", + "mov r11, rcx; sub r11, rbx; sub r11, 64; and r11, -64", + "mov r9, rbp; and r9, 63; or r11, r9", + "mov rsp, r11", + "cld; mov rsi, rbp; mov rdi, r11; mov rcx, rbx; rep movsb", + "mov rax, [r8 + {uc_fpregs_off}]", + "cmp rax, rbp; jb 3f; cmp rax, [r12 + 16]; jae 3f", + "sub rax, rbp; add rax, r11; mov [r8 + {uc_fpregs_off}], rax", + "3:", + "mov rax, [r12 + 0]; mov rdi, [r12 + 8]; mov rsi, r8", + "mov rdx, [r12 + 24]; mov r10, [r12 + 32]; mov r8, [r12 + 40]", + "syscall", + "test rax, rax; jz 1f", + "test rbx, rbx; jz 4f", + "cld; mov rsi, rsp; mov rdi, rbp; mov rcx, rbx; rep movsb; mov rsp, rbp", + "4:", + "pop r12; pop rbx; pop rbp; ret", + "9:", + "mov rax, {neg_enomem}; jmp 4b", + "1:", + "mov eax, {nr_sigaltstack}; lea rdi, [rsp + {uc_stack_off}]; xor esi, esi; syscall", + "mov eax, {nr_rt_sigreturn}; syscall; ud2", + neg_enomem = const -(ENOMEM as i64), + uc_stack_off = const UC_STACK_OFFSET, + uc_fpregs_off = const UC_FPREGS_OFFSET, + nr_sigaltstack = const Sysno::sigaltstack as usize, + nr_rt_sigreturn = const Sysno::rt_sigreturn as usize, + ); + } + + #[inline] + pub unsafe fn replay_unmasked( + inv: &SyscallInvocation, + orig_mask: u64, + blocked_mask: u64, + _ucontext: &Ucontext, + ) -> isize { + // SAFETY: forwarded from caller contract; stack locals stay live for the call. + unsafe { replay_unmasked_raw(inv, &raw const orig_mask, &raw const blocked_mask) } + } + + #[expect(clippy::cast_possible_truncation, reason = "64-bit Linux native registers")] + pub const fn decode_syscall(ucontext: &Ucontext) -> SyscallInvocation { + let gregs = &ucontext.uc_mcontext.gregs; + SyscallInvocation { + nr: gregs[REG_RAX] as usize, + args: [ + gregs[REG_RDI] as usize, + gregs[REG_RSI] as usize, + gregs[REG_RDX] as usize, + gregs[REG_R10] as usize, + gregs[REG_R8] as usize, + gregs[REG_R9] as usize, + ], + } + } + + pub const fn set_syscall_result(ucontext: &mut Ucontext, result: isize) { + ucontext.uc_mcontext.gregs[REG_RAX] = result.cast_unsigned() as u64; + } + + #[expect(clippy::cast_possible_truncation, reason = "64-bit x86-64 usize == u64")] + pub const fn ucontext_sp(ucontext: &Ucontext) -> usize { + ucontext.uc_mcontext.gregs[REG_RSP] as usize + } + + #[expect(clippy::cast_possible_truncation, reason = "64-bit x86-64 usize == u64")] + pub const fn ucontext_pc(ucontext: &Ucontext) -> usize { + ucontext.uc_mcontext.gregs[REG_RIP] as usize + } + + pub const fn set_ucontext_sp(ucontext: &mut Ucontext, sp: usize) { + ucontext.uc_mcontext.gregs[REG_RSP] = sp as u64; + } + + pub const fn uc_sigmask_mut(ucontext: &mut Ucontext) -> &mut u64 { + &mut ucontext.uc_sigmask + } + + /// Invokes a target-registered `SIGSYS` handler on x86-64. + pub unsafe fn invoke_user_sigsys_handler( + handler_addr: usize, + is_siginfo: bool, + signum: i32, + info: *mut linux_raw_sys::general::siginfo, + ucontext: *mut Ucontext, + ) { + if is_siginfo { + // SAFETY: `handler_addr` was registered by the target as an `SA_SIGINFO` handler. + let handler: unsafe extern "C" fn( + i32, + *mut linux_raw_sys::general::siginfo, + *mut c_void, + ) = unsafe { core::mem::transmute(handler_addr) }; + // SAFETY: Invoking target's registered `SIGSYS` handler. + unsafe { handler(signum, info, ucontext.cast()) }; + } else { + // SAFETY: `handler_addr` was registered by the target as a 1-arg handler. + let handler: unsafe extern "C" fn(i32) = unsafe { core::mem::transmute(handler_addr) }; + // SAFETY: Invoking target's registered `SIGSYS` handler. + unsafe { handler(signum) }; + } + } +} + +#[cfg(target_arch = "aarch64")] +mod imp { + use core::{arch::naked_asm, ffi::c_void, ptr}; + + use linux_raw_sys::{ + errno::ENOMEM, + general::{SIG_SETMASK, SYS_SECCOMP}, + }; + use syscalls::Sysno; + + use super::{StackT, SyscallInvocation}; + use crate::sigsys::filter::TRAP_TAG; + + /// Linux `AArch64` `struct sigcontext` prefix (16-byte aligned due to + /// `__reserved` carrying `__attribute__((__aligned__(16)))`). + #[repr(C, align(16))] + pub struct Sigcontext { + pub fault_address: u64, + pub regs: [u64; 31], + pub sp: u64, + pub pc: u64, + pub pstate: u64, + } + + #[repr(C)] + pub struct Ucontext { + pub uc_flags: u64, + pub uc_link: *mut Self, + pub uc_stack: StackT, + pub uc_sigmask: u64, + /// Kernel pads `uc_sigmask` to glibc's 1024-bit `sigset_t` (128 bytes). + pub _sigmask_pad: [u8; 128 - 8], + pub uc_mcontext: Sigcontext, + } + + /// Size of `struct siginfo` preceding `ucontext` in `AArch64` `rt_sigframe`. + const RT_SIGFRAME_UC_OFFSET: usize = 128; + /// Offset of `uc.uc_stack` from `rt_sigframe` start (`128 + 16`). + const RT_SIGFRAME_UC_STACK_OFFSET: usize = RT_SIGFRAME_UC_OFFSET + 16; + /// Offset of `uc_mcontext.__reserved[4096]` from `Ucontext` start (`176 + 288`). + const UC_RESERVED_OFFSET: usize = 176 + 288; + /// Full kernel `struct ucontext` size including `sigcontext.__reserved[4096]`. + const UC_FULL_BYTES: usize = UC_RESERVED_OFFSET + 4096; + + const UC_NR_OFFSET: usize = 176 + 8 + 8 * 8; + + const _: () = { + use core::mem::offset_of; + assert!(offset_of!(Ucontext, uc_flags) == 0); + assert!(offset_of!(Ucontext, uc_link) == 8); + assert!(offset_of!(Ucontext, uc_stack) == 16); + assert!(offset_of!(Ucontext, uc_sigmask) == 40); + assert!(offset_of!(Ucontext, uc_mcontext) == 176); + assert!(offset_of!(Sigcontext, fault_address) == 0); + assert!(offset_of!(Sigcontext, regs) == 8); + assert!(offset_of!(Sigcontext, sp) == 256); + assert!(offset_of!(Sigcontext, pc) == 264); + assert!(offset_of!(Sigcontext, pstate) == 272); + assert!( + UC_NR_OFFSET + == offset_of!(Ucontext, uc_mcontext) + offset_of!(Sigcontext, regs) + 8 * 8 + ); + assert!( + RT_SIGFRAME_UC_STACK_OFFSET == RT_SIGFRAME_UC_OFFSET + offset_of!(Ucontext, uc_stack) + ); + }; + + #[unsafe(naked)] + pub unsafe extern "C" fn sigsys_trampoline() { + // Entry: x0=signum, x1=*mut siginfo, x2=*mut Ucontext, x30=rt_sigreturn. + // Uses 0 stack bytes for foreign/masked-wait dispatch and only a 96-byte + // frame (80B Phase2Packet + x30) around the lock-free `STACK_POOL` swap, + // fitting comfortably inside AArch64 musl's 5 KiB `posix_spawn` stack. + naked_asm!( + "cbz x1, 2f", + "ldr w9, [x1, #8]", + "cmp w9, #{sys_seccomp}", + "b.ne 2f", + "ldr w9, [x1, #4]", + "movz w10, #{trap_tag}", + "cmp w9, w10", + "b.ne 2f", + "cbz x2, 3f", + "ldr x9, [x2, #{uc_nr_off}]", + "cmp x9, #{nr_rt_sigsuspend}; b.eq 4f", + "cmp x9, #{nr_ppoll}; b.eq 4f", + "cmp x9, #{nr_pselect6}; b.eq 4f", + "cmp x9, #{nr_epoll_pwait}; b.eq 4f", + "cmp x9, #{nr_epoll_pwait2}; b.eq 4f", + "sub sp, sp, #96", + "str x30, [sp, #80]", + "mov x19, x2", + "mov x21, sp", + "adrp x9, {stack_pool}", + "add x9, x9, :lo12:{stack_pool}", + "mov x10, #{pool_slots}", + "10:", + "ldaxr x20, [x9]", + "cbz x20, 11f", + "stlxr w11, xzr, [x9]", + "cbnz w11, 10b", + "b 12f", + "11:", + "clrex", + "add x9, x9, #8", + "subs x10, x10, #1", + "b.ne 10b", + "bl {alloc_stack}", + "mov x20, x0", + "12:", + "cbz x20, 6f", + "sub x10, x20, #16", + "str x21, [x10]", + "mov sp, x10", + "mov x0, x19", + "mov x1, x21", + "bl {handle_phase1}", + "mov sp, x21", + "adrp x9, {stack_pool}", + "add x9, x9, :lo12:{stack_pool}", + "mov x10, #{pool_slots}", + "13:", + "ldaxr x11, [x9]", + "cbnz x11, 14f", + "stlxr w12, x20, [x9]", + "cbnz w12, 13b", + "b 7f", + "14:", + "clrex", + "add x9, x9, #8", + "subs x10, x10, #1", + "b.ne 13b", + "mov x0, x20", + "bl {free_stack}", + "b 7f", + "6:", + "mov x0, x19", + "mov x1, x21", + "bl {handle_phase1}", + "7:", + "ldr x2, [x21, #72]", + "cbz x2, 5f", + "mov x0, x19", + "mov x1, x21", + "bl {finish_phase2}", + "5:", + "ldr x30, [sp, #80]", + "add sp, sp, #96", + "3:", + "ret", + "4:", + "mov x0, x2", + "b {masked_wait}", + "2:", + "b {foreign_sigsys}", + sys_seccomp = const SYS_SECCOMP.cast_signed(), + trap_tag = const TRAP_TAG as u32, + uc_nr_off = const UC_NR_OFFSET, + nr_rt_sigsuspend = const Sysno::rt_sigsuspend as usize, + nr_ppoll = const Sysno::ppoll as usize, + nr_pselect6 = const Sysno::pselect6 as usize, + nr_epoll_pwait = const Sysno::epoll_pwait as usize, + nr_epoll_pwait2 = const Sysno::epoll_pwait2 as usize, + pool_slots = const crate::sigsys::stack_pool::STACK_POOL_SLOTS, + stack_pool = sym crate::sigsys::stack_pool::STACK_POOL, + alloc_stack = sym crate::sigsys::stack_pool::alloc_stack_raw, + free_stack = sym crate::sigsys::stack_pool::free_stack_raw, + handle_phase1 = sym crate::sigsys::sigsys_phase1, + finish_phase2 = sym crate::sigsys::sigsys_phase2, + masked_wait = sym crate::sigsys::sigsys_masked_wait, + foreign_sigsys = sym crate::sigsys::sigsys_foreign, + ); + } + + #[unsafe(naked)] + pub unsafe extern "C" fn sigreturn_trampoline() -> ! { + naked_asm!( + "mov x8, #{nr}", + "svc #0", + "brk #0", + nr = const Sysno::rt_sigreturn as usize, + ); + } + + #[unsafe(naked)] + pub unsafe extern "C" fn call_on_stack( + stack_top: usize, + arg: *mut c_void, + entry: extern "C" fn(*mut c_void), + ) { + naked_asm!( + "mov x9, sp", + "sub x10, x0, #16", + "stp x9, x30, [x10]", + "mov sp, x10", + "mov x0, x1", + "blr x2", + "ldp x9, x30, [sp]", + "mov sp, x9", + "ret", + ); + } + + unsafe extern "C" { + static __fspy_elf_loader_masked_wait_ret_pc: u8; + } + + #[unsafe(naked)] + unsafe extern "C" fn replay_with_x28_raw( + inv: *const SyscallInvocation, + target_x28: u64, + ) -> isize { + // Restore the target's `x28` (Go's `g` register on `CGO_ENABLED=0` + // AArch64) across a blocking syscall that temporarily unmasks signals, + // so any signal handler (e.g. Go's `SIGURG`) observes a valid `x28`. + naked_asm!( + "sub sp, sp, #16", + "str x28, [sp]", + "mov x28, x1", + "mov x9, x0", + "ldr x8, [x9, #0]", + "ldp x0, x1, [x9, #8]", + "ldp x2, x3, [x9, #24]", + "ldp x4, x5, [x9, #40]", + "svc #0", + ".globl __fspy_elf_loader_masked_wait_ret_pc", + ".hidden __fspy_elf_loader_masked_wait_ret_pc", + "__fspy_elf_loader_masked_wait_ret_pc:", + "ldr x28, [sp]", + "add sp, sp, #16", + "ret", + ); + } + + #[inline] + pub fn masked_wait_return_pc() -> usize { + (&raw const __fspy_elf_loader_masked_wait_ret_pc).addr() + } + + #[unsafe(naked)] + unsafe extern "C" fn replay_unmasked_raw( + inv: *const SyscallInvocation, + orig_mask: *const u64, + blocked_mask: *const u64, + target_x28: u64, + ) -> isize { + // x0 = inv, x1 = orig_mask, x2 = blocked_mask, x3 = target_x28. + // Set `x28 = target_x28` BEFORE unmasking signals and re-block signals + // BEFORE restoring caller `x28` so Rust code never runs unmasked. + naked_asm!( + "stp x19, x20, [sp, #-32]!", + "stp x21, x28, [sp, #16]", + "mov x19, x0", + "mov x20, x2", + "mov x28, x3", + // Unmask `orig_mask`. + "mov x0, #{sig_setmask}", + "mov x2, #0", + "mov x3, #8", + "mov x8, #{nr_rt_sigprocmask}", + "svc #0", + // Replay the trapped syscall from `inv`. + "ldr x8, [x19, #0]", + "ldp x0, x1, [x19, #8]", + "ldp x2, x3, [x19, #24]", + "ldp x4, x5, [x19, #40]", + "svc #0", + "mov x21, x0", + // Re-block maskable signals before restoring caller `x28`. + "mov x0, #{sig_setmask}", + "mov x1, x20", + "mov x2, #0", + "mov x3, #8", + "mov x8, #{nr_rt_sigprocmask}", + "svc #0", + "mov x0, x21", + "ldp x21, x28, [sp, #16]", + "ldp x19, x20, [sp], #32", + "ret", + sig_setmask = const SIG_SETMASK as usize, + nr_rt_sigprocmask = const Sysno::rt_sigprocmask as usize, + ); + } + + /// Builds a private child `rt_sigframe` (including `sigcontext.__reserved`) + /// in the upper half of `altstack_top` so the `vfork`/`posix_spawn` child + /// can install its `sigaltstack` and return via `SYS_rt_sigreturn` + /// (preserving `x16`, `pstate`, FP/SIMD state, and ARM64 BTI compliance + /// via `eret`). Frames with an `EXTRA_MAGIC` record past `__reserved` + /// (live Scalable Matrix Extension `ZA` state) are not supported here. + /// + /// Returns the `sp` value (`&child_rt_sigframe`) to pass to `SYS_clone` + /// and `SYS_rt_sigreturn`, or `None` if `altstack_size` is too small. + pub unsafe fn prepare_vfork_child_sigframe( + ucontext: *const Ucontext, + altstack_top: usize, + altstack_size: usize, + orig_child_stack: usize, + child_sigmask: u64, + ) -> Option { + let half = (altstack_size / 2) & !4095; + let upper = altstack_size.saturating_sub(half); + let max_uc_bytes = upper.checked_sub(RT_SIGFRAME_UC_OFFSET)?; + if half < 4096 || max_uc_bytes < UC_FULL_BYTES { + return None; + } + let altstack_base = altstack_top - altstack_size; + let child_frame_addr = altstack_base + half; + let child_uc_addr = child_frame_addr + RT_SIGFRAME_UC_OFFSET; + let dst_uc = ptr::with_exposed_provenance_mut::(child_uc_addr); + // SAFETY: `ucontext` is the raw kernel `AArch64` `ucontext` pointer + // (`UC_FULL_BYTES` = 4560 bytes including `__reserved[4096]`), and + // `dst_uc` owns `max_uc_bytes >= UC_FULL_BYTES` writable bytes. + unsafe { + ptr::copy_nonoverlapping(ucontext.cast::(), dst_uc, UC_FULL_BYTES); + let child_uc = &mut *ptr::with_exposed_provenance_mut::(child_uc_addr); + child_uc.uc_mcontext.regs[0] = 0; + if orig_child_stack != 0 { + child_uc.uc_mcontext.sp = orig_child_stack as u64; + } + child_uc.uc_sigmask = child_sigmask; + child_uc.uc_stack = StackT { + ss_sp: ptr::with_exposed_provenance_mut(altstack_base), + ss_flags: 0, + _pad: 0, + ss_size: half, + }; + } + Some(child_frame_addr) + } + + /// Replays `clone(CLONE_VM | CLONE_VFORK, non_null_stack, ...)` starting + /// the child on `child_sigreturn_sp` (`&child_rt_sigframe`), where the + /// child installs its pooled `sigaltstack` and returns via + /// `SYS_rt_sigreturn` (preserving `x16`, FP/SIMD, and ARM64 BTI + /// compliance via `eret`). Processes running with an Arm Guarded Control + /// Stack (GCS) are not supported here. + #[unsafe(naked)] + pub unsafe extern "C" fn replay_vfork_with_altstack( + inv: *const SyscallInvocation, + child_sigreturn_sp: usize, + altstack_size: usize, + save_top: usize, + ) -> isize { + naked_asm!( + "stp x19, x20, [sp, #-48]!; stp x21, x22, [sp, #16]; str x30, [sp, #32]", + "mov x19, sp; ldr x20, [x0, #16]; mov x21, #0; mov x22, x3", + "cbz x22, 3f", + "subs x9, x20, x19; b.ls 3f", + "lsr x15, x2, #1; sub x15, x15, #128; cmp x9, x15; b.hi 11f", + "mov x21, x9; sub x10, x22, x21; and x10, x10, #-16; mov sp, x10", + "mov x11, x19; mov x12, x10; mov x13, x21", + "5: cmp x13, #8; b.lo 6f; ldr x14, [x11], #8; str x14, [x12], #8; sub x13, x13, #8; b 5b", + "6: cbz x13, 3f; ldrb w14, [x11], #1; strb w14, [x12], #1; sub x13, x13, #1; b 6b", + "3:", + "mov x9, x0; mov x10, x1", + "ldr x8, [x9, #0]; ldr x0, [x9, #8]; mov x1, x10", + "ldr x2, [x9, #24]; ldr x3, [x9, #32]; ldr x4, [x9, #40]", + "svc #0", + "cbz x0, 1f", + "cbz x21, 4f", + "mov x11, sp; mov x12, x19; mov x13, x21", + "8: cmp x13, #8; b.lo 9f; ldr x14, [x11], #8; str x14, [x12], #8; sub x13, x13, #8; b 8b", + "9: cbz x13, 10f; ldrb w14, [x11], #1; strb w14, [x12], #1; sub x13, x13, #1; b 9b", + "10: mov sp, x19", + "4:", + "ldr x30, [sp, #32]; ldp x21, x22, [sp, #16]; ldp x19, x20, [sp], #48; ret", + "11:", + "mov x0, #{neg_enomem}; b 4b", + "1:", + "add x0, sp, #{uc_stack_from_frame}; mov x1, #0; mov x8, #{nr_sigaltstack}; svc #0", + "mov x8, #{nr_rt_sigreturn}; svc #0; brk #0", + neg_enomem = const -(ENOMEM as i64), + uc_stack_from_frame = const RT_SIGFRAME_UC_STACK_OFFSET, + nr_sigaltstack = const Sysno::sigaltstack as usize, + nr_rt_sigreturn = const Sysno::rt_sigreturn as usize, + ); + } + + #[unsafe(naked)] + unsafe extern "C" fn call_handler_with_x28_raw( + handler_addr: usize, + signum: i32, + info: *mut c_void, + ucontext: *mut c_void, + target_x28: u64, + ) { + // Restore the target's `x28` (Go's `g` register on AArch64) across the + // target's own `SIGSYS` handler invocation. + naked_asm!( + "stp x28, x30, [sp, #-16]!", + "mov x9, x0", + "mov x0, x1", + "mov x1, x2", + "mov x2, x3", + "mov x28, x4", + "blr x9", + "ldp x28, x30, [sp], #16", + "ret", + ); + } + + /// Invokes a target-registered `SIGSYS` handler on `AArch64` with the + /// target's `x28` restored from `ucontext`. + pub unsafe fn invoke_user_sigsys_handler( + handler_addr: usize, + _is_siginfo: bool, + signum: i32, + info: *mut linux_raw_sys::general::siginfo, + ucontext: *mut Ucontext, + ) { + let target_x28 = if ucontext.is_null() { + 0 + } else { + // SAFETY: Kernel-provided `ucontext` is readable. + unsafe { (*ucontext).uc_mcontext.regs[28] } + }; + // SAFETY: `handler_addr` was registered by the target as a signal handler. + unsafe { + call_handler_with_x28_raw( + handler_addr, + signum, + info.cast(), + ucontext.cast(), + target_x28, + ); + } + } + + #[inline] + pub unsafe fn replay_masked_wait(inv: &SyscallInvocation, ucontext: &Ucontext) -> isize { + // SAFETY: forwarded from caller contract. + unsafe { replay_with_x28_raw(inv, ucontext.uc_mcontext.regs[28]) } + } + + #[inline] + pub unsafe fn replay_unmasked( + inv: &SyscallInvocation, + orig_mask: u64, + blocked_mask: u64, + ucontext: &Ucontext, + ) -> isize { + // SAFETY: forwarded from caller contract; stack locals stay live for the call. + unsafe { + replay_unmasked_raw( + inv, + &raw const orig_mask, + &raw const blocked_mask, + ucontext.uc_mcontext.regs[28], + ) + } + } + + #[expect(clippy::cast_possible_truncation, reason = "64-bit Linux native registers")] + pub const fn decode_syscall(ucontext: &Ucontext) -> SyscallInvocation { + let regs = &ucontext.uc_mcontext.regs; + SyscallInvocation { + nr: regs[8] as usize, + args: [ + regs[0] as usize, + regs[1] as usize, + regs[2] as usize, + regs[3] as usize, + regs[4] as usize, + regs[5] as usize, + ], + } + } + + pub const fn set_syscall_result(ucontext: &mut Ucontext, result: isize) { + ucontext.uc_mcontext.regs[0] = result.cast_unsigned() as u64; + } + + #[expect(clippy::cast_possible_truncation, reason = "64-bit AArch64 usize == u64")] + pub const fn ucontext_sp(ucontext: &Ucontext) -> usize { + ucontext.uc_mcontext.sp as usize + } + + #[expect(clippy::cast_possible_truncation, reason = "64-bit AArch64 usize == u64")] + pub const fn ucontext_pc(ucontext: &Ucontext) -> usize { + ucontext.uc_mcontext.pc as usize + } + + pub const fn set_ucontext_sp(ucontext: &mut Ucontext, sp: usize) { + ucontext.uc_mcontext.sp = sp as u64; + } + + pub const fn uc_sigmask_mut(ucontext: &mut Ucontext) -> &mut u64 { + &mut ucontext.uc_sigmask + } +} + +pub use imp::{ + Ucontext, call_on_stack, decode_syscall, invoke_user_sigsys_handler, masked_wait_return_pc, + prepare_vfork_child_sigframe, replay_masked_wait, replay_unmasked, replay_vfork_with_altstack, + set_syscall_result, set_ucontext_sp, sigreturn_trampoline, sigsys_trampoline, uc_sigmask_mut, + ucontext_pc, ucontext_sp, +}; + +/// Executes a raw 6-argument Linux syscall from within the launcher's +/// allowlisted `PF_X` code range. +/// +/// Returns the raw kernel return value (non-negative result or `-errno`). +/// +/// # Safety +/// +/// The caller must uphold the kernel ABI contract for syscall `nr` and its +/// six arguments. +#[inline] +pub unsafe fn syscall6( + nr: usize, + a0: usize, + a1: usize, + a2: usize, + a3: usize, + a4: usize, + a5: usize, +) -> isize { + // SAFETY: forwarded from caller contract. + unsafe { syscalls::raw::syscall6(nr, a0, a1, a2, a3, a4, a5) }.cast_signed() +} + +/// Replays a decoded syscall invocation directly to the kernel. +/// +/// # Safety +/// +/// The caller must uphold the kernel ABI contract for `invocation`. +#[inline] +pub unsafe fn replay(invocation: SyscallInvocation) -> isize { + // SAFETY: forwarded from caller contract. + unsafe { + syscall6( + invocation.nr, + invocation.args[0], + invocation.args[1], + invocation.args[2], + invocation.args[3], + invocation.args[4], + invocation.args[5], + ) + } +} + +/// Extracts a 32-bit signed integer argument from a 64-bit syscall register. +#[inline] +#[must_use] +#[expect( + clippy::cast_possible_truncation, + clippy::cast_possible_wrap, + reason = "Linux 32-bit signed syscall arguments live in the low 32 bits of a 64-bit register" +)] +pub const fn arg_i32(value: usize) -> i32 { + value as i32 +} + +/// Converts a positive Linux `errno` constant into its negated raw syscall +/// return value (`-errno`). +#[inline] +#[must_use] +pub const fn neg_errno(errno: u32) -> isize { + -(errno.cast_signed() as isize) +} + +/// Calls `getpid()` directly. +#[inline] +#[must_use] +#[expect(clippy::cast_possible_truncation, reason = "Linux pid_t is i32")] +pub fn getpid() -> i32 { + // SAFETY: `getpid` takes no arguments and cannot fail. + unsafe { syscalls::raw::syscall0(Sysno::getpid as usize).cast_signed() as i32 } +} + +/// Calls `gettid()` directly. +#[inline] +#[must_use] +#[expect(clippy::cast_possible_truncation, reason = "Linux pid_t is i32")] +pub fn gettid() -> i32 { + // SAFETY: `gettid` takes no arguments and cannot fail. + unsafe { syscalls::raw::syscall0(Sysno::gettid as usize).cast_signed() as i32 } +} + +/// Calls `rt_sigaction` directly. +/// +/// # Safety +/// +/// `act` and `oldact` must be null or point to valid [`KernelSigaction`] storage. +#[inline] +pub unsafe fn rt_sigaction( + signum: i32, + act: *const KernelSigaction, + oldact: *mut KernelSigaction, +) -> isize { + // SAFETY: caller upholds pointer validity. + unsafe { + syscall6( + Sysno::rt_sigaction as usize, + signum.cast_unsigned() as usize, + act.addr(), + oldact.addr(), + KERNEL_SIGSET_SIZE, + 0, + 0, + ) + } +} + +/// Calls `rt_sigprocmask` directly. +/// +/// # Safety +/// +/// `set` and `oldset` must be null or point to valid `u64` storage. +#[inline] +pub unsafe fn rt_sigprocmask(how: u32, set: *const u64, oldset: *mut u64) -> isize { + // SAFETY: caller upholds pointer validity. + unsafe { + syscall6( + Sysno::rt_sigprocmask as usize, + how as usize, + set.addr(), + oldset.addr(), + KERNEL_SIGSET_SIZE, + 0, + 0, + ) + } +} diff --git a/crates/fspy_elf_loader/src/sigsys/filter.rs b/crates/fspy_elf_loader/src/sigsys/filter.rs new file mode 100644 index 000000000..bed42ed69 --- /dev/null +++ b/crates/fspy_elf_loader/src/sigsys/filter.rs @@ -0,0 +1,838 @@ +//! Seccomp-BPF filter construction, fingerprint probing, and installation. +//! +//! The installed filter executes in optimal order: +//! 1. Allows syscalls whose `seccomp_data.arch` does not match the native 64-bit +//! architecture. +//! 2. Answers the idempotency probe +//! `getpid(PROBE_MAGIC, fingerprint)` with `SECCOMP_RET_ERRNO | EOWNERDEAD` +//! **before** the `PF_X` IP allowlist so recursive `execve`s of the same +//! launcher detect an already-installed identical filter and avoid filter +//! stacking. +//! 3. Returns `SECCOMP_RET_ERRNO | ENOSYS` for `clone3` (so callers like +//! glibc's `posix_spawn`, which pass `CLONE_CLEAR_SIGHAND` to reset all +//! signal handlers including `SIGSYS`, fall back cleanly to `clone(2)`) and +//! for `io_uring_setup` (so runtimes fall back to standard syscalls instead +//! of bypassing `/proc/*/exe` virtualization and caller interceptors via +//! `io_uring` rings). +//! 4. Conditionally traps: +//! - `ppoll` / `pselect6` / `epoll_pwait` / `epoll_pwait2` **only** when the +//! temporary sigmask pointer argument is non-null (avoiding `SIGSYS` traps +//! on hot event-loop waits like Go's netpoller and glibc `poll`/`epoll_wait`). +//! - `clone` when `(flags & CLONE_VM) == 0` (every new-address-space fork, +//! with either NULL or non-NULL `child_stack`, so the child updates process +//! ownership, resets locks, and inherits virtualized `SIGSYS` blocking), or +//! when `(flags & (CLONE_VM | CLONE_VFORK)) == (CLONE_VM | CLONE_VFORK)` +//! with `child_stack != 0` (so `posix_spawn` / `vfork` children with small +//! caller stacks receive a pooled `sigaltstack` before trapping). Regular +//! threads (`CLONE_VM` without `CLONE_VFORK`) and shared-stack `vfork` +//! (`child_stack == 0`) never trap. +//! 5. Allows any syscall number not in the merged trapped syscall set without +//! ever inspecting `instruction_pointer`. +//! 6. Allows trapped syscalls whose `instruction_pointer` lies inside the +//! launcher's `PF_X` `PT_LOAD` range `[code_start, code_end)`. +//! 7. Traps all remaining matched syscalls with `SECCOMP_RET_TRAP | TRAP_TAG`. + +use core::mem::offset_of; + +use fspy_nostd::{Error, Result}; +use linux_raw_sys::{ + errno::{ENOSYS, EOWNERDEAD}, + general::{CLONE_VFORK, CLONE_VM}, + prctl::PR_SET_NO_NEW_PRIVS, + ptrace::{ + BPF_ABS, BPF_JEQ, BPF_JGE, BPF_JGT, BPF_JMP, BPF_JSET, BPF_K, BPF_LD, BPF_RET, BPF_W, + SECCOMP_RET_ALLOW, SECCOMP_RET_DATA, SECCOMP_RET_ERRNO, SECCOMP_RET_TRAP, + SECCOMP_SET_MODE_FILTER, seccomp_data, sock_filter, sock_fprog, + }, +}; +use syscalls::Sysno; + +use super::arch::{AUDIT_ARCH_NATIVE, neg_errno, syscall6}; + +#[expect(clippy::cast_possible_truncation, reason = "cBPF opcodes fit in u16")] +const LD_W_ABS: u16 = (BPF_LD | BPF_W | BPF_ABS) as u16; +#[expect(clippy::cast_possible_truncation, reason = "cBPF opcodes fit in u16")] +const JMP_JEQ_K: u16 = (BPF_JMP | BPF_JEQ | BPF_K) as u16; +#[expect(clippy::cast_possible_truncation, reason = "cBPF opcodes fit in u16")] +const JMP_JGE_K: u16 = (BPF_JMP | BPF_JGE | BPF_K) as u16; +#[expect(clippy::cast_possible_truncation, reason = "cBPF opcodes fit in u16")] +const JMP_JGT_K: u16 = (BPF_JMP | BPF_JGT | BPF_K) as u16; +#[expect(clippy::cast_possible_truncation, reason = "cBPF opcodes fit in u16")] +const JMP_JSET_K: u16 = (BPF_JMP | BPF_JSET | BPF_K) as u16; +#[expect(clippy::cast_possible_truncation, reason = "cBPF opcodes fit in u16")] +const RET_K: u16 = (BPF_RET | BPF_K) as u16; + +#[expect(clippy::cast_possible_truncation, reason = "seccomp_data is 64 bytes")] +const OFF_NR: u32 = offset_of!(seccomp_data, nr) as u32; +#[expect(clippy::cast_possible_truncation, reason = "seccomp_data is 64 bytes")] +const OFF_ARCH: u32 = offset_of!(seccomp_data, arch) as u32; +// Little-endian 64-bit fields: low 32 bits first, high 32 bits second. +#[expect(clippy::cast_possible_truncation, reason = "seccomp_data is 64 bytes")] +const OFF_IP_LO: u32 = offset_of!(seccomp_data, instruction_pointer) as u32; +const OFF_IP_HI: u32 = OFF_IP_LO + 4; +#[expect(clippy::cast_possible_truncation, reason = "seccomp_data is 64 bytes")] +const OFF_ARG0_LO: u32 = offset_of!(seccomp_data, args) as u32; +const OFF_ARG0_HI: u32 = OFF_ARG0_LO + 4; +const OFF_ARG1_LO: u32 = OFF_ARG0_LO + 8; +const OFF_ARG1_HI: u32 = OFF_ARG1_LO + 4; +const OFF_ARG3_LO: u32 = OFF_ARG0_LO + 24; +const OFF_ARG3_HI: u32 = OFF_ARG3_LO + 4; +const OFF_ARG4_LO: u32 = OFF_ARG0_LO + 32; +const OFF_ARG4_HI: u32 = OFF_ARG4_LO + 4; +const OFF_ARG5_LO: u32 = OFF_ARG0_LO + 40; +const OFF_ARG5_HI: u32 = OFF_ARG5_LO + 4; + +/// Magic `args[0]` sentinel for the `getpid(PROBE_MAGIC, fingerprint)` probe. +pub const PROBE_MAGIC: u64 = 0x6673_7079_5f73_6563; + +/// Non-zero 16-bit tag delivered in `siginfo->si_errno` for our own +/// `SECCOMP_RET_TRAP` deliveries so target-installed seccomp filters (which +/// carry a different `si_errno`, typically `0`) can be forwarded untouched. +pub const TRAP_TAG: u16 = 0x5350; + +/// Seccomp return action emitted for syscalls trapped by this loader. +pub const SECCOMP_RET_TAGGED_TRAP: u32 = SECCOMP_RET_TRAP | (TRAP_TAG as u32 & SECCOMP_RET_DATA); + +/// Seccomp return action emitted when the `getpid` idempotency probe matches. +pub const SECCOMP_RET_PROBE: u32 = SECCOMP_RET_ERRNO | (EOWNERDEAD & SECCOMP_RET_DATA); + +/// Seccomp return action emitted for `clone3` and `io_uring_setup` so runtimes +/// fall back to `clone(2)` and standard filesystem syscalls. +pub const SECCOMP_RET_ENOSYS: u32 = SECCOMP_RET_ERRNO | (ENOSYS & SECCOMP_RET_DATA); + +/// Maximum number of unique unconditionally trapped syscalls (loader base + +/// interceptor). +pub const MAX_TRAPPED_SYSCALLS: usize = 64; + +/// Maximum instruction count emitted by [`build_filter`]. +const MAX_BPF_INSNS: usize = 192; + +/// Loader-owned syscalls trapped unconditionally on x86-64 for `SIGSYS`, +/// `fork`, and `/proc/*/exe` virtualization. +/// +/// Masked waits (`ppoll`, `pselect6`, `epoll_pwait`, `epoll_pwait2`) and +/// `clone` are handled by conditional BPF gates in [`build_filter`] so hot +/// `NULL`-sigmask waits, regular threads, and shared-stack `vfork` never trap. +#[cfg(target_arch = "x86_64")] +pub const BASE_TRAPPED_SYSCALLS: &[u32] = &[ + // Signal & fork virtualization + Sysno::rt_sigaction as u32, + Sysno::rt_sigprocmask as u32, + Sysno::rt_sigpending as u32, + Sysno::rt_sigsuspend as u32, + Sysno::fork as u32, + // /proc/self/exe virtualization + Sysno::readlink as u32, + Sysno::readlinkat as u32, + Sysno::open as u32, + Sysno::openat as u32, + Sysno::openat2 as u32, + // `lstat` never follows `/proc/self/exe`, so it needs no rewrite. + Sysno::stat as u32, + Sysno::newfstatat as u32, + Sysno::statx as u32, + Sysno::access as u32, + Sysno::faccessat as u32, + Sysno::faccessat2 as u32, +]; + +/// Loader-owned syscalls trapped unconditionally on `AArch64` for `SIGSYS` and +/// `/proc/*/exe` virtualization. +#[cfg(target_arch = "aarch64")] +pub const BASE_TRAPPED_SYSCALLS: &[u32] = &[ + // Signal virtualization + Sysno::rt_sigaction as u32, + Sysno::rt_sigprocmask as u32, + Sysno::rt_sigpending as u32, + Sysno::rt_sigsuspend as u32, + // /proc/self/exe virtualization + Sysno::readlinkat as u32, + Sysno::openat as u32, + Sysno::openat2 as u32, + Sysno::fstatat as u32, + Sysno::statx as u32, + Sysno::faccessat as u32, + Sysno::faccessat2 as u32, +]; + +/// Fixed-capacity cBPF program buffer requiring no heap allocation. +pub struct FilterProgram { + insns: [sock_filter; MAX_BPF_INSNS], + len: usize, +} + +impl FilterProgram { + const fn new() -> Self { + Self { insns: [sock_filter { code: 0, jt: 0, jf: 0, k: 0 }; MAX_BPF_INSNS], len: 0 } + } + + const fn push(&mut self, code: u16, jt: u8, jf: u8, k: u32) -> usize { + assert!(self.len < MAX_BPF_INSNS, "seccomp BPF filter exceeded static capacity"); + let idx = self.len; + self.insns[idx] = sock_filter { code, jt, jf, k }; + self.len += 1; + idx + } + + #[expect(clippy::cast_possible_truncation, reason = "verified <= u8::MAX before cast")] + const fn patch_jt(&mut self, jump_idx: usize, target_idx: usize) { + assert!(target_idx > jump_idx, "BPF forward jump must target a later instruction"); + let delta = target_idx - jump_idx - 1; + assert!(delta <= u8::MAX as usize, "BPF jt offset overflow"); + self.insns[jump_idx].jt = delta as u8; + } + + #[expect(clippy::cast_possible_truncation, reason = "verified <= u8::MAX before cast")] + const fn patch_jf(&mut self, jump_idx: usize, target_idx: usize) { + assert!(target_idx > jump_idx, "BPF forward jump must target a later instruction"); + let delta = target_idx - jump_idx - 1; + assert!(delta <= u8::MAX as usize, "BPF jf offset overflow"); + self.insns[jump_idx].jf = delta as u8; + } + + #[cfg(test)] + #[must_use] + pub fn as_slice(&self) -> &[sock_filter] { + &self.insns[..self.len] + } +} + +/// Merges `BASE_TRAPPED_SYSCALLS` with `extra`, returning a sorted, +/// deduplicated array and its populated length. +/// +/// # Errors +/// +/// Returns [`Error::INVAL`] if the merged set exceeds [`MAX_TRAPPED_SYSCALLS`]. +pub fn collect_trapped_syscalls(extra: &[Sysno]) -> Result<([u32; MAX_TRAPPED_SYSCALLS], usize)> { + let mut out = [0_u32; MAX_TRAPPED_SYSCALLS]; + let mut len = 0_usize; + + let mut insert = |nr: u32| -> Result<()> { + let mut pos = 0_usize; + while pos < len { + if out[pos] == nr { + return Ok(()); + } + if out[pos] > nr { + break; + } + pos += 1; + } + if len >= MAX_TRAPPED_SYSCALLS { + return Err(Error::INVAL); + } + let mut i = len; + while i > pos { + out[i] = out[i - 1]; + i -= 1; + } + out[pos] = nr; + len += 1; + Ok(()) + }; + + for &nr in BASE_TRAPPED_SYSCALLS { + insert(nr)?; + } + for &sysno in extra { + insert(sysno as u32)?; + } + + Ok((out, len)) +} + +/// Computes a 64-bit FNV-1a fingerprint over `(code_start, code_end, +/// sorted_trapped_syscalls)`. +#[must_use] +pub const fn compute_fingerprint( + code_start: u64, + code_end: u64, + sorted_trapped_syscalls: &[u32], +) -> u64 { + const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; + const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; + + const fn mix_bytes(mut hash: u64, bytes: &[u8]) -> u64 { + let mut i = 0; + while i < bytes.len() { + hash ^= bytes[i] as u64; + hash = hash.wrapping_mul(FNV_PRIME); + i += 1; + } + hash + } + + let mut hash = FNV_OFFSET_BASIS; + hash = mix_bytes(hash, &code_start.to_le_bytes()); + hash = mix_bytes(hash, &code_end.to_le_bytes()); + let mut i = 0; + while i < sorted_trapped_syscalls.len() { + hash = mix_bytes(hash, &sorted_trapped_syscalls[i].to_le_bytes()); + i += 1; + } + hash +} + +/// Builds the cBPF seccomp filter for `arch`, half-open launcher `PF_X` code +/// range `[code_start, code_end)`, idempotency `fingerprint`, and +/// `trapped_syscalls`. +#[must_use] +#[expect( + clippy::cast_possible_truncation, + clippy::too_many_lines, + reason = "BPF constants/offsets fit in u8/u32 and keeping program assembly in one const fn preserves symbolic jump patching" +)] +pub const fn build_filter( + arch: u32, + code_start: u64, + code_end: u64, + fingerprint: u64, + trapped_syscalls: &[u32], +) -> FilterProgram { + assert!(code_start < code_end, "invalid launcher PF_X code range"); + assert!( + trapped_syscalls.len() <= MAX_TRAPPED_SYSCALLS, + "too many trapped syscalls for cBPF filter" + ); + + let mut prog = FilterProgram::new(); + + // 1. Native architecture gate: allow foreign/compat architectures untouched. + prog.push(LD_W_ABS, 0, 0, OFF_ARCH); + prog.push(JMP_JEQ_K, 1, 0, arch); + prog.push(RET_K, 0, 0, SECCOMP_RET_ALLOW); + + // 2. Idempotency probe (runs BEFORE the PF_X IP allowlist): + // `getpid(PROBE_MAGIC, fingerprint)` -> `SECCOMP_RET_ERRNO | EOWNERDEAD`. + let magic_lo = PROBE_MAGIC as u32; + let magic_hi = (PROBE_MAGIC >> 32) as u32; + let fp_lo = fingerprint as u32; + let fp_hi = (fingerprint >> 32) as u32; + + prog.push(LD_W_ABS, 0, 0, OFF_NR); + prog.push(JMP_JEQ_K, 0, 9, Sysno::getpid as u32); + prog.push(LD_W_ABS, 0, 0, OFF_ARG0_LO); + prog.push(JMP_JEQ_K, 0, 7, magic_lo); + prog.push(LD_W_ABS, 0, 0, OFF_ARG0_HI); + prog.push(JMP_JEQ_K, 0, 5, magic_hi); + prog.push(LD_W_ABS, 0, 0, OFF_ARG1_LO); + prog.push(JMP_JEQ_K, 0, 3, fp_lo); + prog.push(LD_W_ABS, 0, 0, OFF_ARG1_HI); + prog.push(JMP_JEQ_K, 0, 1, fp_hi); + prog.push(RET_K, 0, 0, SECCOMP_RET_PROBE); + + // 3. Reject `clone3` and `io_uring_setup` with `ENOSYS`: + // - `clone3` callers using `CLONE_CLEAR_SIGHAND` would reset our + // `SIGSYS` handler to `SIG_DFL` in the child while keeping the + // seccomp filter active; `ENOSYS` makes glibc fall back to `clone(2)`. + // - `io_uring` operations bypass seccomp syscall traps entirely, so + // rejecting `io_uring_setup` ensures runtimes fall back to standard + // syscalls where `/proc/*/exe` virtualization and caller interceptors + // observe them. + prog.push(LD_W_ABS, 0, 0, OFF_NR); + prog.push(JMP_JEQ_K, 1, 0, Sysno::clone3 as u32); + prog.push(JMP_JEQ_K, 0, 1, Sysno::io_uring_setup as u32); + prog.push(RET_K, 0, 0, SECCOMP_RET_ENOSYS); + + // Collect indices of jumps that must target `ip_check_idx`. + let mut on_true_to_ip = [0_usize; MAX_TRAPPED_SYSCALLS + 16]; + let mut true_to_ip_count = 0_usize; + let mut on_false_to_ip = [0_usize; 16]; + let mut false_to_ip_count = 0_usize; + + // 4a. Conditional `clone` gate: + // - Always trap new-address-space `clone` where `(args[0] & CLONE_VM) == 0` + // (regardless of whether `child_stack` is NULL or non-NULL) so + // `on_fork_child` refreshes `OWNER_PID`, drops parent TID slots, and + // clears `ACTION_LOCK` in every forked process. + // - Also trap `CLONE_VM | CLONE_VFORK` ONLY when `child_stack != 0` + // (separate child stack such as musl's 5 KiB `posix_spawn` stack, + // where AArch64 or AVX-512/AMX `rt_sigframe`s would overflow, or + // glibc AArch64 `vfork()` passing `child_stack == parent_sp`). + // Shared-stack `vfork` (`child_stack == 0`) MUST NOT be trapped so + // our `SIGSYS` frame is never placed below the parent's active SP. + // - Regular threads (`CLONE_VM` without `CLONE_VFORK`) allow directly. + // A holds `nr`. + let j_not_clone = prog.push(JMP_JEQ_K, 0, 0, Sysno::clone as u32); + prog.push(LD_W_ABS, 0, 0, OFF_ARG0_LO); + let j_not_clone_vm = prog.push(JMP_JSET_K, 0, 0, CLONE_VM); + on_false_to_ip[false_to_ip_count] = j_not_clone_vm; + false_to_ip_count += 1; + // `CLONE_VM` is set; only trap if `CLONE_VFORK` is also set AND `child_stack != 0`. + prog.push(JMP_JSET_K, 1, 0, CLONE_VFORK); + prog.push(RET_K, 0, 0, SECCOMP_RET_ALLOW); + prog.push(LD_W_ABS, 0, 0, OFF_ARG1_LO); + let j_stack_lo_nz = prog.push(JMP_JEQ_K, 0, 0, 0); + on_false_to_ip[false_to_ip_count] = j_stack_lo_nz; + false_to_ip_count += 1; + prog.push(LD_W_ABS, 0, 0, OFF_ARG1_HI); + let j_stack_hi_nz = prog.push(JMP_JEQ_K, 0, 0, 0); + on_false_to_ip[false_to_ip_count] = j_stack_hi_nz; + false_to_ip_count += 1; + prog.push(RET_K, 0, 0, SECCOMP_RET_ALLOW); + let after_clone = prog.len; + prog.patch_jf(j_not_clone, after_clone); + + // 4b. Conditional masked-wait gates: trap `ppoll`, `pselect6`, + // `epoll_pwait`, and `epoll_pwait2` ONLY when the sigmask pointer + // argument is non-null. + // Note: `A` still holds `nr` on entry because we jumped here on `nr != clone`. + let masked_waits: [(u32, u32, u32); 4] = [ + (Sysno::ppoll as u32, OFF_ARG3_LO, OFF_ARG3_HI), + (Sysno::pselect6 as u32, OFF_ARG5_LO, OFF_ARG5_HI), + (Sysno::epoll_pwait as u32, OFF_ARG4_LO, OFF_ARG4_HI), + (Sysno::epoll_pwait2 as u32, OFF_ARG4_LO, OFF_ARG4_HI), + ]; + let mut mw_i = 0; + while mw_i < masked_waits.len() { + let (nr, arg_lo, arg_hi) = masked_waits[mw_i]; + let j_not_mw = prog.push(JMP_JEQ_K, 0, 0, nr); + prog.push(LD_W_ABS, 0, 0, arg_lo); + let j_lo_nz = prog.push(JMP_JEQ_K, 0, 0, 0); + on_false_to_ip[false_to_ip_count] = j_lo_nz; + false_to_ip_count += 1; + prog.push(LD_W_ABS, 0, 0, arg_hi); + let j_hi_nz = prog.push(JMP_JEQ_K, 0, 0, 0); + on_false_to_ip[false_to_ip_count] = j_hi_nz; + false_to_ip_count += 1; + prog.push(RET_K, 0, 0, SECCOMP_RET_ALLOW); + let next_mw = prog.len; + prog.patch_jf(j_not_mw, next_mw); + mw_i += 1; + } + + // 4c. Unconditional trapped-syscall dispatch: `A` still holds `nr`. + let count = trapped_syscalls.len(); + let mut i = 0; + while i < count { + let j = prog.push(JMP_JEQ_K, 0, 0, trapped_syscalls[i]); + on_true_to_ip[true_to_ip_count] = j; + true_to_ip_count += 1; + i += 1; + } + prog.push(RET_K, 0, 0, SECCOMP_RET_ALLOW); + + // 5. Launcher `PF_X` IP range check: allow if `code_start <= ip < code_end`, + // i.e. `code_start <= ip <= code_end - 1`, else `SECCOMP_RET_TAGGED_TRAP`. + let ip_check_idx = prog.push(LD_W_ABS, 0, 0, OFF_IP_HI); + + // Patch all deferred jumps to `ip_check_idx`. + let mut k = 0; + while k < true_to_ip_count { + prog.patch_jt(on_true_to_ip[k], ip_check_idx); + k += 1; + } + let mut k = 0; + while k < false_to_ip_count { + prog.patch_jf(on_false_to_ip[k], ip_check_idx); + k += 1; + } + + let end_inclusive = code_end - 1; + let start_lo = code_start as u32; + let start_hi = (code_start >> 32) as u32; + let end_lo = end_inclusive as u32; + let end_hi = (end_inclusive >> 32) as u32; + + if start_hi == end_hi { + prog.push(JMP_JEQ_K, 0, 4, start_hi); + prog.push(LD_W_ABS, 0, 0, OFF_IP_LO); + prog.push(JMP_JGE_K, 0, 2, start_lo); + } else { + prog.push(JMP_JGE_K, 0, 8, start_hi); + prog.push(JMP_JGT_K, 7, 0, end_hi); + prog.push(JMP_JEQ_K, 0, 2, start_hi); + prog.push(LD_W_ABS, 0, 0, OFF_IP_LO); + prog.push(JMP_JGE_K, 3, 4, start_lo); + prog.push(JMP_JEQ_K, 0, 2, end_hi); + prog.push(LD_W_ABS, 0, 0, OFF_IP_LO); + } + prog.push(JMP_JGT_K, 1, 0, end_lo); + prog.push(RET_K, 0, 0, SECCOMP_RET_ALLOW); + prog.push(RET_K, 0, 0, SECCOMP_RET_TAGGED_TRAP); + + prog +} + +/// Probes whether an identical seccomp filter with `fingerprint` is already +/// installed on the current process. +#[expect(clippy::cast_possible_truncation, reason = "64-bit Linux native pointer/word size")] +fn probe_installed_filter(fingerprint: u64) -> bool { + // SAFETY: `getpid` ignores extra arguments when no matching filter is + // installed; a matching filter returns `-EOWNERDEAD` directly. + let rc = unsafe { + syscalls::raw::syscall2(Sysno::getpid as usize, PROBE_MAGIC as usize, fingerprint as usize) + } + .cast_signed(); + rc == neg_errno(EOWNERDEAD) +} + +/// Installs the seccomp-BPF filter unless an identical filter (matching +/// `code_start`, `code_end`, and the merged trapped syscall set) is already +/// active on the process. +/// +/// # Errors +/// +/// Returns [`Error::INVAL`] if the syscall set exceeds capacity, or the kernel +/// error if `prctl` or `seccomp` fails. +pub fn install_seccomp_filter(code_start: u64, code_end: u64, extra: &[Sysno]) -> Result<()> { + let (syscalls_buf, count) = collect_trapped_syscalls(extra)?; + let trapped = &syscalls_buf[..count]; + let fingerprint = compute_fingerprint(code_start, code_end, trapped); + + if probe_installed_filter(fingerprint) { + return Ok(()); + } + + // SAFETY: `PR_SET_NO_NEW_PRIVS` takes integer arguments only and enables + // unprivileged seccomp filter installation. + let rc = + unsafe { syscall6(Sysno::prctl as usize, PR_SET_NO_NEW_PRIVS as usize, 1, 0, 0, 0, 0) }; + check_syscall_result(rc)?; + + let mut filter = build_filter(AUDIT_ARCH_NATIVE, code_start, code_end, fingerprint, trapped); + let len = u16::try_from(filter.len).map_err(|_| Error::INVAL)?; + let prog = sock_fprog { len, filter: filter.insns.as_mut_ptr() }; + + // SAFETY: `prog` points to `len` initialized `sock_filter` instructions for + // the duration of the `seccomp` syscall. + let rc = unsafe { + syscall6( + Sysno::seccomp as usize, + SECCOMP_SET_MODE_FILTER as usize, + 0, + core::ptr::from_ref(&prog).addr(), + 0, + 0, + 0, + ) + }; + check_syscall_result(rc) +} + +#[expect(clippy::cast_possible_truncation, reason = "Linux errno values fit in i32")] +const fn check_syscall_result(rc: isize) -> Result<()> { + if rc < 0 { Err(Error::from_raw_os_error((-rc) as i32)) } else { Ok(()) } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn eval_bpf(prog: &[sock_filter], data: &seccomp_data) -> u32 { + // SAFETY: `seccomp_data` is a plain `#[repr(C)]` struct of integer fields. + let bytes = unsafe { + core::slice::from_raw_parts( + core::ptr::from_ref(data).cast::(), + core::mem::size_of::(), + ) + }; + let mut pc = 0_usize; + let mut acc = 0_u32; + loop { + let insn = prog[pc]; + pc += 1; + match insn.code { + LD_W_ABS => { + let off = insn.k as usize; + acc = u32::from_ne_bytes(bytes[off..off + 4].try_into().unwrap()); + } + JMP_JEQ_K => pc += usize::from(if acc == insn.k { insn.jt } else { insn.jf }), + JMP_JGE_K => pc += usize::from(if acc >= insn.k { insn.jt } else { insn.jf }), + JMP_JGT_K => pc += usize::from(if acc > insn.k { insn.jt } else { insn.jf }), + JMP_JSET_K => { + pc += usize::from(if (acc & insn.k) != 0 { insn.jt } else { insn.jf }); + } + RET_K => return insn.k, + other => panic!("unexpected BPF opcode: {other:#x}"), + } + } + } + + fn make_data(arch: u32, ip: u64, nr: u32, args: [u64; 6]) -> seccomp_data { + seccomp_data { nr: nr.cast_signed(), arch, instruction_pointer: ip, args } + } + + #[test] + fn filter_allows_pf_x_range_and_traps_listed_syscalls_same_hi() { + let code_start = 0x5500_0000_1000_u64; + let code_end = 0x5500_0000_9000_u64; + let (buf, count) = collect_trapped_syscalls(&[]).unwrap(); + let trapped = &buf[..count]; + let fp = compute_fingerprint(code_start, code_end, trapped); + let prog = build_filter(AUDIT_ARCH_NATIVE, code_start, code_end, fp, trapped); + let insns = prog.as_slice(); + + // Foreign arch is always allowed (even for matching probe or trapped syscall). + assert_eq!( + eval_bpf(insns, &make_data(AUDIT_ARCH_NATIVE ^ 1, 0x1000, trapped[0], [0; 6])), + SECCOMP_RET_ALLOW + ); + assert_eq!( + eval_bpf( + insns, + &make_data( + AUDIT_ARCH_NATIVE ^ 1, + code_start + 8, + Sysno::getpid as u32, + [PROBE_MAGIC, fp, 0, 0, 0, 0], + ), + ), + SECCOMP_RET_ALLOW + ); + + // Inside half-open `[code_start, code_end)` is allowed even for trapped syscalls. + for ip in [code_start, code_start + 1, code_end - 1] { + for &nr in trapped { + assert_eq!( + eval_bpf(insns, &make_data(AUDIT_ARCH_NATIVE, ip, nr, [0; 6])), + SECCOMP_RET_ALLOW, + "expected ALLOW inside PF_X for ip={ip:#x} nr={nr}" + ); + } + } + + // `clone3` and `io_uring_setup` always return `SECCOMP_RET_ENOSYS` on the native arch. + for nr in [Sysno::clone3 as u32, Sysno::io_uring_setup as u32] { + for ip in [0, code_start, code_end, 0x0000_7fff_0000_0000] { + assert_eq!( + eval_bpf(insns, &make_data(AUDIT_ARCH_NATIVE, ip, nr, [0; 6])), + SECCOMP_RET_ENOSYS, + "expected ENOSYS for nr={nr} at ip={ip:#x}" + ); + } + } + + // Outside `[code_start, code_end)` (including `code_end` itself!) is trapped with `TRAP_TAG`. + for ip in [0, code_start - 1, code_end, code_end + 1, 0x0000_7fff_0000_0000, u64::MAX] { + for &nr in trapped { + assert_eq!( + eval_bpf(insns, &make_data(AUDIT_ARCH_NATIVE, ip, nr, [0; 6])), + SECCOMP_RET_TAGGED_TRAP, + "expected tagged TRAP outside PF_X for ip={ip:#x} nr={nr}" + ); + } + // Untrapped hot syscalls are always allowed. + for nr in [ + Sysno::write as u32, + Sysno::read as u32, + Sysno::exit_group as u32, + Sysno::rt_sigreturn as u32, + Sysno::mmap as u32, + ] { + assert_eq!( + eval_bpf(insns, &make_data(AUDIT_ARCH_NATIVE, ip, nr, [0; 6])), + SECCOMP_RET_ALLOW, + "expected ALLOW for untrapped ip={ip:#x} nr={nr}" + ); + } + } + } + + #[test] + fn conditional_gates_filter_clone_vm() { + let code_start = 0x5500_0000_1000_u64; + let code_end = 0x5500_0000_9000_u64; + let (buf, count) = collect_trapped_syscalls(&[]).unwrap(); + let trapped = &buf[..count]; + let fp = compute_fingerprint(code_start, code_end, trapped); + let prog = build_filter(AUDIT_ARCH_NATIVE, code_start, code_end, fp, trapped); + let insns = prog.as_slice(); + let user_ip = 0x0000_7fff_0000_1000; + let launcher_ip = code_start + 0x10; + + let eval_clone = |ip: u64, flags: u64, stack: u64| { + eval_bpf( + insns, + &make_data(AUDIT_ARCH_NATIVE, ip, Sysno::clone as u32, [flags, stack, 0, 0, 0, 0]), + ) + }; + + // `clone`: allow regular threads (`CLONE_VM` without `CLONE_VFORK`); + // trap ALL new-address-space clones (`(flags & CLONE_VM) == 0`, whether + // `child_stack` is NULL or non-NULL) outside PF_X. + assert_eq!(eval_clone(user_ip, u64::from(CLONE_VM), 0), SECCOMP_RET_ALLOW); + assert_eq!(eval_clone(user_ip, u64::from(CLONE_VM), 0x7fff_0000_0000), SECCOMP_RET_ALLOW); + assert_eq!(eval_clone(user_ip, 0x11, 0), SECCOMP_RET_TAGGED_TRAP); + assert_eq!(eval_clone(user_ip, 0x11, 0x7fff_0000_0000), SECCOMP_RET_TAGGED_TRAP); + assert_eq!(eval_clone(user_ip, 0x11, 0x1_0000_0000), SECCOMP_RET_TAGGED_TRAP); + assert_eq!(eval_clone(launcher_ip, 0x11, 0), SECCOMP_RET_ALLOW); + let vfork_flags = u64::from(CLONE_VM | CLONE_VFORK | 0x11); + // Shared-stack `vfork` (`child_stack == 0`) MUST allow directly so our + // SIGSYS frame never sits below the shared parent SP. + assert_eq!(eval_clone(user_ip, vfork_flags, 0), SECCOMP_RET_ALLOW); + // Separate-stack `vfork`/`posix_spawn` (`child_stack != 0`, low or high + // 32 bits) MUST trap outside PF_X so the child gets a safe sigaltstack. + for stack_ptr in [0x0000_0000_0000_8000_u64, 0x0000_7fff_0000_0000_u64] { + assert_eq!(eval_clone(user_ip, vfork_flags, stack_ptr), SECCOMP_RET_TAGGED_TRAP); + assert_eq!(eval_clone(launcher_ip, vfork_flags, stack_ptr), SECCOMP_RET_ALLOW); + } + } + + #[test] + fn conditional_gates_filter_null_masked_waits() { + let code_start = 0x5500_0000_1000_u64; + let code_end = 0x5500_0000_9000_u64; + let (buf, count) = collect_trapped_syscalls(&[]).unwrap(); + let trapped = &buf[..count]; + let fp = compute_fingerprint(code_start, code_end, trapped); + let prog = build_filter(AUDIT_ARCH_NATIVE, code_start, code_end, fp, trapped); + let insns = prog.as_slice(); + let user_ip = 0x0000_7fff_0000_1000; + let launcher_ip = code_start + 0x10; + + // Masked waits: NULL sigmask allows directly; non-null (low or high 32-bit) traps outside PF_X. + for (nr, mask_idx) in [ + (Sysno::ppoll as u32, 3_usize), + (Sysno::pselect6 as u32, 5_usize), + (Sysno::epoll_pwait as u32, 4_usize), + (Sysno::epoll_pwait2 as u32, 4_usize), + ] { + assert_eq!( + eval_bpf(insns, &make_data(AUDIT_ARCH_NATIVE, user_ip, nr, [0; 6])), + SECCOMP_RET_ALLOW, + "NULL mask must allow directly for nr={nr}" + ); + for mask_ptr in + [0x0000_0000_0000_1234_u64, 0x0000_7fff_0000_0000_u64, 0x0000_7fff_1234_5678_u64] + { + let mut args = [0_u64; 6]; + args[mask_idx] = mask_ptr; + assert_eq!( + eval_bpf(insns, &make_data(AUDIT_ARCH_NATIVE, user_ip, nr, args)), + SECCOMP_RET_TAGGED_TRAP, + "non-null mask {mask_ptr:#x} must trap outside PF_X for nr={nr}" + ); + assert_eq!( + eval_bpf(insns, &make_data(AUDIT_ARCH_NATIVE, launcher_ip, nr, args)), + SECCOMP_RET_ALLOW, + "non-null mask inside PF_X must allow for nr={nr}" + ); + } + } + } + + #[test] + fn getpid_probe_matches_before_pf_x_check_and_ignores_mismatches() { + let code_start = 0x0002_0000_1000_u64; + let code_end = 0x0002_0000_8000_u64; + let (buf, count) = collect_trapped_syscalls(&[]).unwrap(); + let trapped = &buf[..count]; + let fp = compute_fingerprint(code_start, code_end, trapped); + let prog = build_filter(AUDIT_ARCH_NATIVE, code_start, code_end, fp, trapped); + let insns = prog.as_slice(); + + for ip in [code_start + 0x20, 0x7fff_0000_0000] { + assert_eq!( + eval_bpf( + insns, + &make_data( + AUDIT_ARCH_NATIVE, + ip, + Sysno::getpid as u32, + [PROBE_MAGIC, fp, 0, 0, 0, 0], + ), + ), + SECCOMP_RET_PROBE + ); + } + + for args in [ + [0, 0, 0, 0, 0, 0], + [PROBE_MAGIC ^ 1, fp, 0, 0, 0, 0], + [PROBE_MAGIC ^ (1 << 32), fp, 0, 0, 0, 0], + [PROBE_MAGIC, fp ^ 1, 0, 0, 0, 0], + [PROBE_MAGIC, fp ^ (1 << 32), 0, 0, 0, 0], + ] { + assert_eq!( + eval_bpf( + insns, + &make_data(AUDIT_ARCH_NATIVE, code_start + 0x20, Sysno::getpid as u32, args), + ), + SECCOMP_RET_ALLOW + ); + } + + let (buf2, count2) = collect_trapped_syscalls(&[Sysno::getpid]).unwrap(); + let trapped2 = &buf2[..count2]; + let fp2 = compute_fingerprint(code_start, code_end, trapped2); + let prog2 = build_filter(AUDIT_ARCH_NATIVE, code_start, code_end, fp2, trapped2); + let insns2 = prog2.as_slice(); + assert_eq!( + eval_bpf( + insns2, + &make_data( + AUDIT_ARCH_NATIVE, + code_start + 0x20, + Sysno::getpid as u32, + [PROBE_MAGIC, fp2, 0, 0, 0, 0], + ), + ), + SECCOMP_RET_PROBE + ); + assert_eq!( + eval_bpf(insns2, &make_data(AUDIT_ARCH_NATIVE, 0x1000, Sysno::getpid as u32, [0; 6])), + SECCOMP_RET_TAGGED_TRAP + ); + assert_eq!( + eval_bpf( + insns2, + &make_data(AUDIT_ARCH_NATIVE, code_start + 0x20, Sysno::getpid as u32, [0; 6]), + ), + SECCOMP_RET_ALLOW + ); + } + + #[test] + fn filter_handles_pf_x_crossing_4gib_boundary() { + let code_start = 0x0000_0001_ffff_fffe_u64; + let code_end = 0x0000_0003_0000_0003_u64; + let trapped = &[Sysno::openat as u32]; + let fp = compute_fingerprint(code_start, code_end, trapped); + let prog = build_filter(AUDIT_ARCH_NATIVE, code_start, code_end, fp, trapped); + let insns = prog.as_slice(); + + for ip in [ + code_start, + 0x0000_0001_ffff_ffff, + 0x0000_0002_0000_0000, + 0x0000_0002_8000_0000, + 0x0000_0003_0000_0000, + code_end - 1, + ] { + assert_eq!( + eval_bpf(insns, &make_data(AUDIT_ARCH_NATIVE, ip, trapped[0], [0; 6])), + SECCOMP_RET_ALLOW, + "expected ALLOW for ip={ip:#x}" + ); + } + + for ip in [0, 0x0000_0000_ffff_ffff, code_start - 1, code_end, 0x0000_0004_0000_0000] { + assert_eq!( + eval_bpf(insns, &make_data(AUDIT_ARCH_NATIVE, ip, trapped[0], [0; 6])), + SECCOMP_RET_TAGGED_TRAP, + "expected tagged TRAP for ip={ip:#x}" + ); + } + } + + #[test] + fn collect_deduplicates_sorts_and_fingerprints_deterministically() { + let (a, len_a) = + collect_trapped_syscalls(&[Sysno::execve, Sysno::openat, Sysno::execveat]).unwrap(); + let (b, len_b) = + collect_trapped_syscalls(&[Sysno::execveat, Sysno::execve, Sysno::execve]).unwrap(); + assert_eq!(len_a, len_b); + assert_eq!(&a[..len_a], &b[..len_b]); + assert!(a[..len_a].windows(2).all(|w| w[0] < w[1])); + + let fp1 = compute_fingerprint(0x2_0000_1000, 0x2_0000_5000, &a[..len_a]); + let fp2 = compute_fingerprint(0x2_0000_1000, 0x2_0000_5000, &b[..len_b]); + let fp_diff_range = compute_fingerprint(0x2_0000_1000, 0x2_0000_6000, &a[..len_a]); + let (c, len_c) = collect_trapped_syscalls(&[]).unwrap(); + let fp_diff_syscalls = compute_fingerprint(0x2_0000_1000, 0x2_0000_5000, &c[..len_c]); + assert_eq!(fp1, fp2); + assert_ne!(fp1, fp_diff_range); + assert_ne!(fp1, fp_diff_syscalls); + } +} diff --git a/crates/fspy_elf_loader/src/sigsys/mod.rs b/crates/fspy_elf_loader/src/sigsys/mod.rs new file mode 100644 index 000000000..a7f6d4990 --- /dev/null +++ b/crates/fspy_elf_loader/src/sigsys/mod.rs @@ -0,0 +1,681 @@ +//! Freestanding `SIGSYS` signal, `/proc/self/exe`, and custom syscall +//! interception runtime. + +mod arch; +mod filter; +mod proc_exe; +mod signal; +mod stack_pool; +mod usermem; + +use core::{ + cell::UnsafeCell, + ffi::c_void, + mem::size_of, + ptr, + sync::atomic::{AtomicBool, Ordering}, +}; + +use fspy_nostd::{BorrowedFd, CStr, Error, Result, Thin}; +#[cfg(target_arch = "x86_64")] +use linux_raw_sys::general::AT_FDCWD; +use linux_raw_sys::general::{ + O_NONBLOCK, O_PATH, SA_NODEFER, SA_ONSTACK, SA_RESTORER, SA_SIGINFO, SIG_UNBLOCK, SIGSYS, + SS_DISABLE, open_how, siginfo, +}; +use syscalls::Sysno; + +use self::arch::{ + HANDLER_BLOCK_MASK, KernelSigaction, SIGSYS_BIT, SyscallInvocation, UNBLOCKABLE_MASK, Ucontext, + arg_i32, decode_syscall, replay, replay_unmasked, rt_sigaction, rt_sigprocmask, + set_syscall_result, set_ucontext_sp, sigreturn_trampoline, sigsys_trampoline, syscall6, + uc_sigmask_mut, ucontext_sp, +}; +use crate::{Syscall, SyscallAction, SyscallInterceptor}; + +struct SyncCell(UnsafeCell); + +// SAFETY: Written once during single-threaded `install` before arming seccomp +// and published with `INTERCEPTOR_INSTALLED` Release/Acquire ordering. +unsafe impl Sync for SyncCell {} + +static INSTALLED: AtomicBool = AtomicBool::new(false); +static INTERCEPTOR_INSTALLED: AtomicBool = AtomicBool::new(false); +static INTERCEPTOR: SyncCell> = SyncCell(UnsafeCell::new(None)); + +/// Returns the runtime address of [`sigsys_trampoline`] for startup `PF_X` +/// bounds verification. +#[must_use] +pub fn handler_addr() -> usize { + (sigsys_trampoline as *const ()).addr() +} + +/// Borrows a user C string directly from `addr`. +/// +/// # Safety +/// +/// See [`usermem::user_cstr`]. +pub unsafe fn user_cstr<'a>(addr: usize) -> Result> { + // SAFETY: forwarded from caller contract. + unsafe { usermem::user_cstr(addr) } +} + +/// Copies a user `Copy` value. +/// +/// # Safety +/// +/// `T` must be valid for any bit pattern, and `addr` must satisfy +/// [`usermem::read_user`]. +pub unsafe fn copy_user_value(addr: usize) -> Result { + // SAFETY: forwarded from caller contract. + unsafe { usermem::read_user(addr) } +} + +/// Computes the calling thread's virtualized signal mask from `ucontext.uc_sigmask`. +pub fn virtual_sigmask_from(raw_uc_sigmask: u64) -> u64 { + signal::virtual_sigmask_from(raw_uc_sigmask) +} + +/// Returns `true` when executing inside a `CLONE_VM` child sharing its parent's +/// address space. +pub fn is_shared_vm_child() -> bool { + signal::is_shared_vm_child() +} + +/// Installs the `SIGSYS` runtime, `/proc/self/exe` virtualization, and +/// optional [`SyscallInterceptor`] for an open executable descriptor. +/// +/// # Errors +/// +/// Returns an error if the runtime is already installed, the executable path +/// cannot be stored, `SIGSYS` setup fails, or seccomp filter installation +/// fails. +/// +/// # Safety +/// +/// Must be called once in a fresh single-threaded process before entering the +/// target executable. `code_range` must be the launcher's own `PF_X` `PT_LOAD` +/// range `[code_start, code_end)` that remains mapped for the lifetime of the +/// process. +pub unsafe fn install( + code_range: (u64, u64), + fd: BorrowedFd<'_>, + fallback_path: CStr<'_, Thin>, + min_sigstksz: usize, + page_size: usize, + interceptor: Option, +) -> Result<()> { + if INSTALLED.swap(true, Ordering::AcqRel) { + return Err(Error::INVAL); + } + + // Prime cached page size and private SIGSYS stack pool (honoring + // `AT_MINSIGSTKSZ`) before arming seccomp. + let _ = fspy_nostd::param::page_size(); + stack_pool::init_and_warm(min_sigstksz, page_size); + + let bump = fspy_nostd_alloc::pooled_bump(); + let exe_path = match proc_exe::resolve_exe_path_for_fd(&bump, fd, fallback_path) { + Ok(path) => path, + Err(err) => { + INSTALLED.store(false, Ordering::Release); + return Err(err); + } + }; + if let Err(err) = proc_exe::init(&exe_path) { + INSTALLED.store(false, Ordering::Release); + return Err(err); + } + + // Publish the interceptor before arming seccomp / entering target. + // SAFETY: Single-threaded initialization prior to `SECCOMP_SET_MODE_FILTER`. + unsafe { *INTERCEPTOR.0.get() = interceptor }; + INTERCEPTOR_INSTALLED.store(interceptor.is_some(), Ordering::Release); + + // Install our freestanding `SIGSYS` naked trampoline before arming seccomp, + // preserving any inherited `SIGSYS` disposition (e.g. `SIG_IGN`) in the + // virtualized table. + // + // `sa_mask` blocks all maskable signals except `SIGSYS` while the handler + // runs so asynchronous signals (such as Go's `SIGURG` preemption) cannot + // interrupt us while `SP` is switched onto `stack_pool` or observe + // non-target register state. + let our_action = KernelSigaction { + sa_handler: handler_addr(), + sa_flags: (SA_SIGINFO | SA_RESTORER | SA_NODEFER | SA_ONSTACK) as usize, + sa_restorer: (sigreturn_trampoline as *const ()).addr(), + sa_mask: HANDLER_BLOCK_MASK, + }; + let mut prev_action = KernelSigaction::default(); + // SAFETY: `our_action` and `prev_action` are valid stack-local structs. + let rc = + unsafe { rt_sigaction(SIGSYS.cast_signed(), &raw const our_action, &raw mut prev_action) }; + if rc < 0 { + INTERCEPTOR_INSTALLED.store(false, Ordering::Release); + INSTALLED.store(false, Ordering::Release); + #[expect(clippy::cast_possible_truncation, reason = "Linux errno fits in i32")] + return Err(Error::from_raw_os_error((-rc) as i32)); + } + + // Ensure `SIGSYS` is unblocked in the kernel mask before arming seccomp, + // while recording if the parent had passed `SIGSYS` blocked. + let sigsys_mask = SIGSYS_BIT; + let mut prev_mask: u64 = 0; + // SAFETY: `sigsys_mask` and `prev_mask` are valid stack-local `u64`s. + let rc = unsafe { rt_sigprocmask(SIG_UNBLOCK, &raw const sigsys_mask, &raw mut prev_mask) }; + if rc < 0 { + // SAFETY: Best-effort restore of previous `SIGSYS` disposition on failure. + let _ = + unsafe { rt_sigaction(SIGSYS.cast_signed(), &raw const prev_action, ptr::null_mut()) }; + INTERCEPTOR_INSTALLED.store(false, Ordering::Release); + INSTALLED.store(false, Ordering::Release); + #[expect(clippy::cast_possible_truncation, reason = "Linux errno fits in i32")] + return Err(Error::from_raw_os_error((-rc) as i32)); + } + + signal::init(prev_action, (prev_mask & SIGSYS_BIT) != 0); + + let extra_syscalls = interceptor.map_or(&[][..], |i| i.syscalls); + if let Err(err) = filter::install_seccomp_filter(code_range.0, code_range.1, extra_syscalls) { + // SAFETY: Best-effort restore of previous `SIGSYS` disposition on failure. + let _ = + unsafe { rt_sigaction(SIGSYS.cast_signed(), &raw const prev_action, ptr::null_mut()) }; + INTERCEPTOR_INSTALLED.store(false, Ordering::Release); + INSTALLED.store(false, Ordering::Release); + return Err(err); + } + + Ok(()) +} + +/// Entry target from [`sigsys_trampoline`] for non-seccomp and foreign-seccomp +/// `SIGSYS` deliveries. +pub unsafe extern "C" fn sigsys_foreign(signum: i32, info: *mut siginfo, ucontext: *mut Ucontext) { + // SAFETY: Kernel-supplied signal frame pointers from `sigsys_trampoline`. + unsafe { signal::forward_non_seccomp_sigsys(signum, info, ucontext) }; +} + +const PHASE2_NONE: usize = 0; +const PHASE2_DELIVER_PENDING_SIGSYS: usize = 1; +const PHASE2_REPLAY: usize = 2; +const PHASE2_REPLAY_UNMASKED: usize = 3; +const PHASE2_FORK_REPLAY: usize = 4; +const PHASE2_EXECVE: usize = 5; +const PHASE2_VFORK_ALTSTACK: usize = 6; + +/// Compact 80-byte Phase 1 -> Phase 2 handoff packet allocated on the entry +/// stack by [`sigsys_trampoline`]. +#[repr(C)] +pub struct Phase2Packet { + inv: SyscallInvocation, + /// `orig_mask` (`ReplayUnmasked`), `parent_blocked` (`ForkReplay`), or + /// `cleanup_fn` address (`Execve`). + aux0: usize, + /// `cleanup_ctx` address (`Execve`). + aux1: usize, + /// One of `PHASE2_*`; offset 72 is checked directly by `sigsys_trampoline`. + kind: usize, +} + +const _: () = { + assert!(size_of::() == 80); + assert!(core::mem::offset_of!(Phase2Packet, kind) == 72); +}; + +/// Entry target from [`sigsys_trampoline`] for masked-wait syscalls, running +/// directly on the entry stack so any `SA_ONSTACK` signal sees +/// `on_sig_stack(SP) == true`. +pub unsafe extern "C" fn sigsys_masked_wait(ucontext_ptr: *mut Ucontext) { + // SAFETY: `sigsys_trampoline` checked `ucontext_ptr` is non-null. + let ucontext = unsafe { &mut *ucontext_ptr }; + let inv = decode_syscall(ucontext); + let result = match Sysno::new(inv.nr) { + // SAFETY: Each helper matches the corresponding Linux syscall ABI. + Some(Sysno::rt_sigsuspend) => unsafe { + signal::handle_masked_wait(inv, ucontext, 0, 1, false) + }, + // SAFETY: Matches Linux `ppoll` ABI. + Some(Sysno::ppoll) => unsafe { signal::handle_masked_wait(inv, ucontext, 3, 4, true) }, + // SAFETY: Matches Linux `pselect6` ABI. + Some(Sysno::pselect6) => unsafe { signal::handle_pselect6(inv, ucontext) }, + // SAFETY: Matches Linux `epoll_pwait` / `epoll_pwait2` ABI. + Some(Sysno::epoll_pwait | Sysno::epoll_pwait2) => unsafe { + signal::handle_masked_wait(inv, ucontext, 4, 5, true) + }, + // SAFETY: Unreachable; replay directly. + _ => unsafe { replay(inv) }, + }; + set_syscall_result(ucontext, result); + *uc_sigmask_mut(ucontext) &= !SIGSYS_BIT; +} + +/// Phase 1 entry called by [`sigsys_trampoline`] on a private 64 KiB stack +/// while maskable asynchronous signals are blocked by `our_action.sa_mask`. +pub unsafe extern "C" fn sigsys_phase1(ucontext_ptr: *mut Ucontext, packet_ptr: *mut Phase2Packet) { + // SAFETY: `sigsys_trampoline` guarantees both pointers are valid and writable. + let ucontext = unsafe { &mut *ucontext_ptr }; + // SAFETY: `packet_ptr` points to the 80-byte slot on the entry stack. + let packet = unsafe { &mut *packet_ptr }; + let inv = decode_syscall(ucontext); + // SAFETY: Dispatches Phase 1 on the private stack. + unsafe { dispatch_phase1(inv, ucontext, packet) }; +} + +/// Phase 2 entry called by [`sigsys_trampoline`] back on the entry stack AFTER +/// the private 64 KiB stack has been released, only when `packet.kind != 0`. +#[inline(never)] +pub unsafe extern "C" fn sigsys_phase2( + ucontext_ptr: *mut Ucontext, + packet_ptr: *const Phase2Packet, + kind: usize, +) { + // SAFETY: `packet_ptr` points to the populated `Phase2Packet` on the entry stack. + let packet = unsafe { &*packet_ptr }; + let result = match kind { + PHASE2_DELIVER_PENDING_SIGSYS => { + // SAFETY: Delivering pending `SIGSYS` on entry stack after unmasking. + unsafe { signal::deliver_pending_sigsys(&mut *ucontext_ptr) }; + return; + } + PHASE2_REPLAY => { + // SAFETY: Replays non-blocking syscall directly from `&packet.inv` + // without copying `SyscallInvocation` onto the entry stack. + unsafe { + syscall6( + packet.inv.nr, + packet.inv.args[0], + packet.inv.args[1], + packet.inv.args[2], + packet.inv.args[3], + packet.inv.args[4], + packet.inv.args[5], + ) + } + } + PHASE2_REPLAY_UNMASKED => { + // SAFETY: Replays blocking syscall with caller's mask restored. + unsafe { + replay_unmasked(&packet.inv, packet.aux0 as u64, HANDLER_BLOCK_MASK, &*ucontext_ptr) + } + } + PHASE2_FORK_REPLAY => { + // SAFETY: Replays `fork`/`clone` (new `mm`) and updates child state on `rc == 0`. + unsafe { finish_fork_replay(&mut *ucontext_ptr, &packet.inv, packet.aux0 != 0) } + } + PHASE2_EXECVE => { + // SAFETY: Runs replacement `SYS_execve` after releasing `stack_pool`. + unsafe { finish_execve(packet) } + } + PHASE2_VFORK_ALTSTACK => { + // SAFETY: Passes raw `ucontext_ptr` so full kernel `rt_sigframe` + // copies preserve provenance past the Rust `Ucontext` prefix. + unsafe { finish_vfork_altstack(ucontext_ptr.cast_const(), packet) } + } + _ => return, + }; + + // SAFETY: `sigsys_trampoline` guarantees `ucontext_ptr` is valid and writable. + let ucontext = unsafe { &mut *ucontext_ptr }; + set_syscall_result(ucontext, result); + *uc_sigmask_mut(ucontext) &= !SIGSYS_BIT; +} + +#[inline(never)] +unsafe fn finish_vfork_altstack(ucontext_ptr: *const Ucontext, packet: &Phase2Packet) -> isize { + let Some(altstack_top) = stack_pool::acquire_stack() else { + return arch::neg_errno(linux_raw_sys::errno::ENOMEM); + }; + let orig_child_stack = packet.inv.args[1]; + let uc_addr = ucontext_ptr.addr(); + let child_sigmask = packet.aux0 as u64; + let altstack_size = stack_pool::stack_size(); + // SAFETY: `ucontext_ptr` is the live kernel signal frame and `altstack_top` + // owns `altstack_size` writable bytes below it exclusively until `clone` + // returns in the parent. + let Some(child_sigreturn_sp) = (unsafe { + arch::prepare_vfork_child_sigframe( + ucontext_ptr, + altstack_top, + altstack_size, + orig_child_stack, + child_sigmask, + ) + }) else { + stack_pool::release_stack(altstack_top); + return arch::neg_errno(linux_raw_sys::errno::ENOMEM); + }; + // SAFETY: `ucontext_ptr` is a valid kernel `Ucontext`. + let ucontext = unsafe { &*ucontext_ptr }; + let uc_sp = ucontext_sp(ucontext); + // If our live `SIGSYS` frame sits on a separate user `sigaltstack` that + // does not contain `orig_child_stack`, the child cannot overwrite it. + let on_separate_altstack = { + let ss_base = ucontext.uc_stack.ss_sp.addr(); + let ss_len = ucontext.uc_stack.ss_size; + let ss_enabled = (ucontext.uc_stack.ss_flags & SS_DISABLE.cast_signed()) == 0 && ss_len > 0; + let ss_end = ss_base.saturating_add(ss_len); + ss_enabled + && uc_addr >= ss_base + && uc_addr < ss_end + && !(orig_child_stack > ss_base && orig_child_stack <= ss_end) + }; + // When `orig_child_stack` sits directly above our live `SIGSYS` frame + // (e.g. glibc `AArch64` `vfork()` passing `child_stack = parent_sp`), + // acquire a second pooled stack to preserve and restore the parent's frame. + let save_top = + if !on_separate_altstack && orig_child_stack <= uc_sp && uc_addr < orig_child_stack { + let Some(top) = stack_pool::acquire_stack() else { + stack_pool::release_stack(altstack_top); + return arch::neg_errno(linux_raw_sys::errno::ENOMEM); + }; + top + } else { + 0 + }; + // SAFETY: `packet.inv` holds the trapped `clone(CLONE_VM | CLONE_VFORK, + // non_null_stack)` arguments; `child_sigreturn_sp` points to our prepared + // `rt_sigframe` inside `altstack_top`, and optional `save_top` owns + // `altstack_size` writable bytes until `clone` returns in the parent. + let rc = unsafe { + arch::replay_vfork_with_altstack( + &raw const packet.inv, + child_sigreturn_sp, + altstack_size, + save_top, + ) + }; + if save_top != 0 { + stack_pool::release_stack(save_top); + } + stack_pool::release_stack(altstack_top); + rc +} + +#[inline(never)] +unsafe fn finish_fork_replay( + ucontext: &mut Ucontext, + inv: &SyscallInvocation, + parent_blocked: bool, +) -> isize { + // For `clone` without `CLONE_VM` that supplied a custom `child_stack != 0`, + // replay with `child_stack = 0` so the child starts on a private COW copy + // of our entry stack, runs `on_fork_child`, and then has `ucontext` SP set + // to `orig_child_stack` so `rt_sigreturn` atomically switches to the + // caller's requested child stack with every register and TLS intact. + let orig_child_stack = if inv.nr == Sysno::clone as usize { inv.args[1] } else { 0 }; + let mut replay_inv = *inv; + if orig_child_stack != 0 { + replay_inv.args[1] = 0; + } + // SAFETY: Replays `fork` / `clone` without `CLONE_VM`. + let rc = unsafe { replay(replay_inv) }; + if rc == 0 { + signal::on_fork_child(parent_blocked); + if orig_child_stack != 0 { + set_ucontext_sp(ucontext, orig_child_stack); + } + } + rc +} + +#[inline(never)] +unsafe fn finish_execve(packet: &Phase2Packet) -> isize { + // Clear our TID slot before `SYS_execve` so a successful `vfork` / + // `posix_spawn` exec leaves ZERO entries in the parent's `TID_SLOTS` table + // (and `stack_pool` has already been released above!). + let saved_tid = signal::take_current_tid_entry(); + // SAFETY: `packet.inv` holds `SYS_execve(prog, argv, envp)` pointers valid in + // caller-owned scratch storage until `cleanup` runs on failure. + let rc = unsafe { + syscall6( + Sysno::execve as usize, + packet.inv.args[0], + packet.inv.args[1], + packet.inv.args[2], + 0, + 0, + 0, + ) + }; + // `SYS_execve` failed: restore TID entry and release scratch/fd. + signal::restore_current_tid_entry(saved_tid); + if packet.aux0 != 0 { + // SAFETY: `aux0` was stored from `SyscallAction::Execve`'s cleanup fn pointer. + let cleanup_fn: unsafe fn(*mut c_void) = + unsafe { core::mem::transmute::(packet.aux0) }; + let mut cb = CleanupContext { + cleanup_fn, + cleanup_ctx: ptr::with_exposed_provenance_mut(packet.aux1), + }; + // SAFETY: Run interceptor cleanup on the private stack so complex + // destructors never overflow a tight `vfork` stack. + unsafe { + stack_pool::run_on_private_stack((&raw mut cb).cast(), run_cleanup_on_stack); + } + } + rc +} + +struct CleanupContext { + cleanup_fn: unsafe fn(*mut c_void), + cleanup_ctx: *mut c_void, +} + +extern "C" fn run_cleanup_on_stack(raw: *mut c_void) { + // SAFETY: `finish_execve` passes a valid `*mut CleanupContext`. + let cb = unsafe { &*(raw.cast::()) }; + // SAFETY: Invokes the interceptor's failure cleanup callback once. + unsafe { (cb.cleanup_fn)(cb.cleanup_ctx) }; +} + +#[inline] +const fn finish_in_phase1(ucontext: &mut Ucontext, packet: &mut Phase2Packet, rc: isize) { + set_syscall_result(ucontext, rc); + *uc_sigmask_mut(ucontext) &= !SIGSYS_BIT; + packet.kind = PHASE2_NONE; +} + +/// Runs Phase 1 of trapped-syscall dispatch on the private `SIGSYS` stack while +/// maskable signals are blocked, either completing the syscall in `ucontext` +/// (`PHASE2_NONE`) or populating `packet` for Phase 2 on the entry stack. +/// +/// # Safety +/// +/// `inv` must be decoded from the live `SECCOMP_RET_TRAP` `ucontext`. +#[expect( + clippy::too_many_lines, + reason = "Phase 1 dispatch keeps signal, /proc/self/exe, interceptor, and replay stages in a single linear pipeline" +)] +unsafe fn dispatch_phase1( + mut inv: SyscallInvocation, + ucontext: &mut Ucontext, + packet: &mut Phase2Packet, +) { + let Some(sysno) = Sysno::new(inv.nr) else { + packet.inv = inv; + packet.kind = PHASE2_REPLAY; + return; + }; + + // 1. Signal and fork virtualization (not forwarded to `interceptor`). + // SAFETY: Arguments match the corresponding Linux syscall ABIs. + unsafe { + match sysno { + Sysno::rt_sigaction => { + finish_in_phase1(ucontext, packet, signal::handle_rt_sigaction(inv)); + return; + } + Sysno::rt_sigprocmask => { + match signal::handle_rt_sigprocmask(inv, ucontext) { + signal::SigprocmaskOutcome::Done(rc) => { + finish_in_phase1(ucontext, packet, rc); + } + signal::SigprocmaskOutcome::DeliverPendingSigsys(rc) => { + set_syscall_result(ucontext, rc); + *uc_sigmask_mut(ucontext) &= !SIGSYS_BIT; + packet.kind = PHASE2_DELIVER_PENDING_SIGSYS; + } + } + return; + } + Sysno::rt_sigpending => { + finish_in_phase1(ucontext, packet, signal::handle_rt_sigpending(inv)); + return; + } + Sysno::clone => { + const CLONE_VM_VFORK: usize = 0x0000_0100 | 0x0000_4000; + if (inv.args[0] & CLONE_VM_VFORK) == CLONE_VM_VFORK && inv.args[1] != 0 { + let child_mask = ucontext.uc_sigmask & !(SIGSYS_BIT | UNBLOCKABLE_MASK); + packet.inv = inv; + #[expect( + clippy::cast_possible_truncation, + reason = "64-bit Linux usize == u64" + )] + { + packet.aux0 = child_mask as usize; + } + packet.kind = PHASE2_VFORK_ALTSTACK; + return; + } + packet.inv = inv; + packet.aux0 = usize::from(signal::is_current_tid_blocked()); + packet.kind = PHASE2_FORK_REPLAY; + return; + } + #[cfg(target_arch = "x86_64")] + Sysno::fork => { + packet.inv = inv; + packet.aux0 = usize::from(signal::is_current_tid_blocked()); + packet.kind = PHASE2_FORK_REPLAY; + return; + } + _ => {} + } + } + + // 2. `readlink`/`readlinkat` matching `/proc/*/exe` -> handled directly. + // SAFETY: Arguments match the corresponding Linux readlink syscall ABI. + unsafe { + match sysno { + Sysno::readlinkat => { + if let Some(rc) = proc_exe::try_handle_readlink( + arg_i32(inv.args[0]), + inv.args[1], + inv.args[2], + inv.args[3], + ) { + finish_in_phase1(ucontext, packet, rc); + return; + } + } + #[cfg(target_arch = "x86_64")] + Sysno::readlink => { + if let Some(rc) = + proc_exe::try_handle_readlink(AT_FDCWD, inv.args[0], inv.args[1], inv.args[2]) + { + finish_in_phase1(ucontext, packet, rc); + return; + } + } + _ => {} + } + } + + // 3. Path-following syscalls -> rewrite `/proc/*/exe` in place in `inv`, + // retaining any already-read `open_how` for the unmasked-replay check. + // SAFETY: Arguments come from the trapped syscall for `sysno`. + let prefetched_open_how = unsafe { proc_exe::rewrite_path_arg(&mut inv, sysno) }; + + // 4. Optional caller interceptor (sees `/proc/*/exe`-rewritten `inv`, with + // lazy access to virtualized `sigmask` and `is_shared_vm_child`). + if INTERCEPTOR_INSTALLED.load(Ordering::Acquire) { + // SAFETY: `INTERCEPTOR` was written once before `Release` store. + if let Some(interceptor) = unsafe { *INTERCEPTOR.0.get() } + && interceptor.syscalls.contains(&sysno) + { + let call = Syscall { sysno, args: inv.args, raw_uc_sigmask: ucontext.uc_sigmask }; + // SAFETY: `call` holds the live (and rewritten) trapped arguments. + match unsafe { (interceptor.handle)(&call) } { + Ok(SyscallAction::Replay) => {} + Ok(SyscallAction::Execve { prog, argv, envp, cleanup }) => { + packet.inv = SyscallInvocation { + nr: Sysno::execve as usize, + args: [prog.addr(), argv.addr(), envp.addr(), 0, 0, 0], + }; + if let Some((cleanup_fn, cleanup_ctx)) = cleanup { + packet.aux0 = (cleanup_fn as *const ()).addr(); + packet.aux1 = cleanup_ctx.addr(); + } else { + packet.aux0 = 0; + packet.aux1 = 0; + } + packet.kind = PHASE2_EXECVE; + return; + } + Err(err) => { + finish_in_phase1(ucontext, packet, -(err.raw_os_error() as isize)); + return; + } + } + } + } + + // 5. Return to the entry stack to replay the (possibly rewritten) syscall. + // Unmask signals for potentially blocking `open*` (e.g. FIFO without + // `O_NONBLOCK`) and directly-replayed `execve`/`execveat`, unless all + // maskable signals were already blocked by the caller. + packet.inv = inv; + // SAFETY: Inspects `openat2`'s `open_how` safely via `usermem` if not already prefetched. + if unsafe { needs_unmasked_replay(sysno, &inv, prefetched_open_how) } { + let orig_mask = ucontext.uc_sigmask & !(SIGSYS_BIT | UNBLOCKABLE_MASK); + if orig_mask != HANDLER_BLOCK_MASK { + #[expect(clippy::cast_possible_truncation, reason = "64-bit Linux usize == u64")] + { + packet.aux0 = orig_mask as usize; + } + packet.kind = PHASE2_REPLAY_UNMASKED; + return; + } + } + packet.kind = PHASE2_REPLAY; +} + +/// Returns `true` if replaying `sysno` on the entry stack should temporarily +/// restore the caller's signal mask (`open`/`openat`/`openat2` without +/// `O_NONBLOCK`/`O_PATH`, or `execve`/`execveat`). +/// +/// # Safety +/// +/// `inv` must contain the arguments from a trapped `sysno` syscall. +#[expect(clippy::cast_possible_truncation, reason = "Linux open flags live in low 32 bits")] +unsafe fn needs_unmasked_replay( + sysno: Sysno, + inv: &SyscallInvocation, + prefetched_open_how: Option, +) -> bool { + const NON_BLOCKING_FLAGS: u32 = O_NONBLOCK | O_PATH; + match sysno { + #[cfg(target_arch = "x86_64")] + Sysno::open => ((inv.args[1] as u32) & NON_BLOCKING_FLAGS) == 0, + Sysno::openat => ((inv.args[2] as u32) & NON_BLOCKING_FLAGS) == 0, + Sysno::openat2 => { + let how = if let Some(how) = prefetched_open_how { + how + } else { + let how_ptr = inv.args[2]; + let size = inv.args[3]; + if how_ptr == 0 || size < size_of::() { + return false; + } + // SAFETY: `open_how` is a plain `#[repr(C)]` struct of `u64` fields. + let Ok(how) = (unsafe { usermem::read_user::(how_ptr) }) else { + return false; + }; + how + }; + (how.flags & u64::from(NON_BLOCKING_FLAGS)) == 0 + } + Sysno::execve | Sysno::execveat => true, + _ => false, + } +} diff --git a/crates/fspy_elf_loader/src/sigsys/proc_exe.rs b/crates/fspy_elf_loader/src/sigsys/proc_exe.rs new file mode 100644 index 000000000..a959fe0c9 --- /dev/null +++ b/crates/fspy_elf_loader/src/sigsys/proc_exe.rs @@ -0,0 +1,590 @@ +//! `/proc/self/exe` virtualization for the `SIGSYS` dispatcher. +//! +//! Because the kernel execs the freestanding launcher instead of the target +//! ELF, `/proc/self/exe`, `/proc/thread-self/exe`, `/proc//exe`, and +//! `/proc//task//exe` all resolve to the launcher binary. +//! +//! This module handles: +//! - `readlink` / `readlinkat`: returns the target executable's path without a +//! trailing NUL, matching Linux truncation and `bufsiz <= 0` (`-EINVAL`) +//! semantics. +//! - Path-following syscalls (`open`, `openat`, `openat2`, `stat`, +//! `newfstatat`/`fstatat`, `statx`, `access`, `faccessat`, `faccessat2`, +//! `execve`, `execveat`): rewrites matching paths (including relative lookups +//! via a `/proc/...` `dirfd` or `cwd`) in place in [`SyscallInvocation`] to +//! the permanent target executable path, honoring `O_NOFOLLOW`, +//! `AT_SYMLINK_NOFOLLOW`, and `openat2` resolve flags. + +use core::{ + mem::size_of, + ptr, + sync::atomic::{AtomicPtr, AtomicUsize, Ordering}, +}; + +use allocator_api2::{alloc::Allocator, vec::Vec}; +use fspy_nostd::{ + BorrowedFd, CStr, CWD, Error, Result, Thin, + fs::{AccessFlags, faccessat}, +}; +use linux_raw_sys::{ + errno::{EFAULT, EINVAL}, + general::{ + AT_FDCWD, AT_SYMLINK_NOFOLLOW, O_NOFOLLOW, RESOLVE_BENEATH, RESOLVE_IN_ROOT, + RESOLVE_NO_MAGICLINKS, RESOLVE_NO_SYMLINKS, RESOLVE_NO_XDEV, open_how, + }, +}; +use syscalls::Sysno; + +use super::{ + arch::{SyscallInvocation, arg_i32, getpid, gettid, neg_errno}, + usermem, +}; + +/// Permanently retained pointer to the NUL-terminated target executable path. +static EXE_PTR: AtomicPtr = AtomicPtr::new(ptr::null_mut()); +/// Byte length of the target executable path, excluding its terminating NUL. +static EXE_LEN: AtomicUsize = AtomicUsize::new(0); + +/// Stores the target executable path in permanent page-backed storage. +/// +/// Must be called once during `sigsys::install` before entering the target. +/// +/// # Errors +/// +/// Returns [`Error::INVAL`] if `exe_path` is empty or contains an interior NUL, +/// or [`Error::NOMEM`] if storage allocation fails. +pub fn init(exe_path: &[u8]) -> Result<()> { + if exe_path.is_empty() || exe_path.contains(&0) { + return Err(Error::INVAL); + } + let bump = fspy_nostd_alloc::page_bump(); + let mut owned = Vec::new_in(&bump); + owned.try_reserve_exact(exe_path.len() + 1).map_err(|_| Error::NOMEM)?; + owned.extend_from_slice(exe_path); + owned.push(0); + let ptr = owned.as_mut_ptr(); + // Retain the permanent mapping for the lifetime of the process. + core::mem::forget(owned); + core::mem::forget(bump); + EXE_PTR.store(ptr, Ordering::Release); + EXE_LEN.store(exe_path.len(), Ordering::Release); + Ok(()) +} + +/// Resolves the canonical path of an already-opened executable `fd` via +/// [`fspy_nostd_alloc::fs::fd_path`], falling back to `fallback` (made absolute +/// with `getcwd` if relative) when `/proc` is unavailable. +/// +/// # Errors +/// +/// Returns [`Error::NOMEM`] if temporary allocation fails. +pub fn resolve_exe_path_for_fd( + alloc: A, + fd: BorrowedFd<'_>, + fallback: CStr<'_, Thin>, +) -> Result> { + if let Ok(Some(resolved)) = fspy_nostd_alloc::fs::fd_path(alloc, fd) + && resolved.as_units().starts_with(b"/") + { + return Ok(resolved.into_units()); + } + + let fallback_bytes = fallback.count().as_units(); + if fallback_bytes.starts_with(b"/") { + let mut out = Vec::new_in(alloc); + out.try_reserve_exact(fallback_bytes.len()).map_err(|_| Error::NOMEM)?; + out.extend_from_slice(fallback_bytes); + return Ok(out); + } + + if let Ok(cwd) = fspy_nostd_alloc::fs::getcwd(alloc) { + let cwd_bytes = cwd.as_units(); + let mut joined = Vec::new_in(alloc); + let needed = cwd_bytes.len() + 1 + fallback_bytes.len(); + joined.try_reserve_exact(needed).map_err(|_| Error::NOMEM)?; + joined.extend_from_slice(cwd_bytes); + if !cwd_bytes.ends_with(b"/") { + joined.push(b'/'); + } + joined.extend_from_slice(fallback_bytes); + let mut normalized = Vec::new_in(alloc); + if normalize_abs_path(&joined, &mut normalized) { + return Ok(normalized); + } + } + + let mut out = Vec::new_in(alloc); + out.try_reserve_exact(fallback_bytes.len()).map_err(|_| Error::NOMEM)?; + out.extend_from_slice(fallback_bytes); + Ok(out) +} + +fn target_exe() -> Option<(*const u8, usize)> { + let len = EXE_LEN.load(Ordering::Acquire); + if len == 0 { + return None; + } + let ptr = EXE_PTR.load(Ordering::Acquire); + if ptr.is_null() { + return None; + } + Some((ptr.cast_const(), len)) +} + +/// Handles `readlink(path, buf, bufsiz)` (x86-64) and +/// `readlinkat(dirfd, path, buf, bufsiz)` (both arches) when `(dirfd, path_ptr)` +/// targets `/proc/*/exe`. +/// +/// Returns `None` when the path does not match `/proc/*/exe` so the dispatcher +/// can invoke any registered [`crate::SyscallInterceptor`] and replay the call. +/// +/// # Safety +/// +/// Arguments must come from a trapped `readlink` or `readlinkat` syscall. +pub unsafe fn try_handle_readlink( + dirfd: i32, + path_ptr: usize, + buf_ptr: usize, + bufsiz_raw: usize, +) -> Option { + let (exe_ptr, exe_len) = target_exe()?; + // SAFETY: Inspects user path pointer up to `PATH_MAX` bytes. + if !unsafe { is_proc_self_exe(dirfd, path_ptr) } { + return None; + } + + // Linux `do_readlinkat` takes `int bufsiz` and rejects `<= 0` with `-EINVAL`. + let bufsiz = arg_i32(bufsiz_raw); + if bufsiz <= 0 { + return Some(neg_errno(EINVAL)); + } + if buf_ptr == 0 { + return Some(neg_errno(EFAULT)); + } + + let copy_len = exe_len.min(bufsiz.cast_unsigned() as usize); + // SAFETY: `exe_ptr` is permanently retained and readable for `exe_len` bytes. + let src = unsafe { core::slice::from_raw_parts(exe_ptr, copy_len) }; + // SAFETY: user pointer from the trapped syscall (see `usermem`). + if unsafe { usermem::write_user_bytes(buf_ptr, src) }.is_err() { + return Some(neg_errno(EFAULT)); + } + Some(copy_len.cast_signed()) +} + +/// Rewrites `/proc/*/exe` path arguments in `inv` in place to the permanent +/// target executable path for path-following syscalls, returning any +/// already-read `open_how` value for `openat2`. +/// +/// # Safety +/// +/// `inv` must contain the arguments from a trapped syscall matching `sysno`. +pub unsafe fn rewrite_path_arg(inv: &mut SyscallInvocation, sysno: Sysno) -> Option { + let (exe_ptr, _) = target_exe()?; + + // SAFETY: All helpers inspect user pointers according to the kernel ABI for + // `sysno` and only replace arguments with the permanent `exe_ptr` / `AT_FDCWD`. + unsafe { + match sysno { + Sysno::openat => { + rewrite_open(inv, exe_ptr, Some(0), 1, 2); + None + } + Sysno::openat2 => rewrite_openat2(inv, exe_ptr), + #[cfg(target_arch = "x86_64")] + Sysno::open => { + rewrite_open(inv, exe_ptr, None, 0, 1); + None + } + #[cfg(target_arch = "x86_64")] + Sysno::newfstatat => { + rewrite_at_follow(inv, exe_ptr, Some(0), 1, Some(3)); + None + } + #[cfg(target_arch = "aarch64")] + Sysno::fstatat => { + rewrite_at_follow(inv, exe_ptr, Some(0), 1, Some(3)); + None + } + Sysno::statx => { + rewrite_at_follow(inv, exe_ptr, Some(0), 1, Some(2)); + None + } + Sysno::faccessat => { + rewrite_at_follow(inv, exe_ptr, Some(0), 1, None); + None + } + Sysno::faccessat2 => { + rewrite_at_follow(inv, exe_ptr, Some(0), 1, Some(3)); + None + } + #[cfg(target_arch = "x86_64")] + Sysno::stat | Sysno::access => { + rewrite_at_follow(inv, exe_ptr, None, 0, None); + None + } + Sysno::execve => { + rewrite_at_follow(inv, exe_ptr, None, 0, None); + None + } + Sysno::execveat => { + rewrite_at_follow(inv, exe_ptr, Some(0), 1, Some(4)); + None + } + _ => None, + } + } +} + +#[expect(clippy::cast_possible_truncation, reason = "Linux open flags are u32")] +unsafe fn rewrite_open( + inv: &mut SyscallInvocation, + exe_ptr: *const u8, + dirfd_idx: Option, + path_idx: usize, + flags_idx: usize, +) { + let flags = inv.args[flags_idx] as u32; + // Preserve symlink semantics for `O_NOFOLLOW` (fails with ELOOP, or opens + // the symlink itself with `O_PATH | O_NOFOLLOW`). + if (flags & O_NOFOLLOW) != 0 { + return; + } + let dirfd = dirfd_idx.map_or(AT_FDCWD, |idx| arg_i32(inv.args[idx])); + let path_ptr = inv.args[path_idx]; + // SAFETY: `path_ptr` is the trapped syscall's path argument. + if !unsafe { is_proc_self_exe(dirfd, path_ptr) } { + return; + } + if let Some(idx) = dirfd_idx { + inv.args[idx] = AT_FDCWD.cast_unsigned() as usize; + } + inv.args[path_idx] = exe_ptr.addr(); +} + +unsafe fn rewrite_openat2(inv: &mut SyscallInvocation, exe_ptr: *const u8) -> Option { + let dirfd = arg_i32(inv.args[0]); + let path_ptr = inv.args[1]; + let how_ptr = inv.args[2]; + let size = inv.args[3]; + + if how_ptr == 0 || size < size_of::() { + return None; + } + // SAFETY: `open_how` is a plain `#[repr(C)]` struct of `u64` fields. + let how = unsafe { usermem::read_user::(how_ptr) }.ok()?; + let restricted_resolve = u64::from( + RESOLVE_NO_SYMLINKS + | RESOLVE_NO_MAGICLINKS + | RESOLVE_BENEATH + | RESOLVE_IN_ROOT + | RESOLVE_NO_XDEV, + ); + if (how.flags & u64::from(O_NOFOLLOW)) != 0 || (how.resolve & restricted_resolve) != 0 { + return Some(how); + } + // SAFETY: `path_ptr` is the trapped syscall's path argument. + if unsafe { is_proc_self_exe(dirfd, path_ptr) } { + inv.args[0] = AT_FDCWD.cast_unsigned() as usize; + inv.args[1] = exe_ptr.addr(); + } + Some(how) +} + +#[expect(clippy::cast_possible_truncation, reason = "Linux dirfd/flags are 32-bit")] +unsafe fn rewrite_at_follow( + inv: &mut SyscallInvocation, + exe_ptr: *const u8, + dirfd_idx: Option, + path_idx: usize, + flags_idx: Option, +) { + if let Some(idx) = flags_idx + && ((inv.args[idx] as u32) & AT_SYMLINK_NOFOLLOW) != 0 + { + // Do not rewrite no-follow queries: `/proc/self/exe` must remain a + // symlink (`S_IFLNK`) so `lstat` and `realpath` follow it via `readlink`. + return; + } + let dirfd = dirfd_idx.map_or(AT_FDCWD, |idx| arg_i32(inv.args[idx])); + let path_ptr = inv.args[path_idx]; + // SAFETY: `path_ptr` is the trapped syscall's path argument. + if !unsafe { is_proc_self_exe(dirfd, path_ptr) } { + return; + } + if let Some(idx) = dirfd_idx { + inv.args[idx] = AT_FDCWD.cast_unsigned() as usize; + } + inv.args[path_idx] = exe_ptr.addr(); +} + +/// Checks whether `(dirfd, path_ptr)` refers to the current process's +/// `/proc/.../exe` magic symlink. +/// +/// # Safety +/// +/// `path_ptr` must be null, in the first page, or point to a readable +/// NUL-terminated user string. +unsafe fn is_proc_self_exe(dirfd: i32, path_ptr: usize) -> bool { + // SAFETY: forwarded from the caller contract. + let Ok(cstr) = (unsafe { usermem::user_cstr(path_ptr) }) else { + return false; + }; + let raw = cstr.count().as_units(); + // Fast rejection for 99.99% of paths: any path naming `/proc/.../exe` + // (without a trailing `/`, which is ENOTDIR on a regular-file symlink) + // must end with the component `exe`. + if !ends_with_exe_component(raw) { + return false; + } + + let pid = getpid(); + let tid = gettid(); + + if raw.starts_with(b"/") { + // Fast path for exact canonical forms without allocating. + return if !raw.contains(&b'.') && !raw.windows(2).any(|w| w == b"//") { + match_normalized_proc_exe(raw, pid, tid, task_dir_exists) + } else { + let bump = fspy_nostd_alloc::pooled_bump(); + let mut normalized = Vec::new_in(&bump); + normalize_abs_path(raw, &mut normalized) + && match_normalized_proc_exe(&normalized, pid, tid, task_dir_exists) + }; + } + + // Relative path ending in `exe`: resolve `dirfd` (or `cwd` for `AT_FDCWD`, + // which is `-100` on Linux and yields `Some(CWD)` from `try_borrow_raw`) + // via `fspy_nostd_alloc::fs::fd_path` using a pooled bump arena so stack + // usage stays tiny. + // SAFETY: `dirfd` comes from the trapped syscall; `-1` yields `None`, and + // any invalid fd cleanly returns `Ok(None)` from `fd_path`. + let Some(borrowed_dirfd) = (unsafe { BorrowedFd::try_borrow_raw(dirfd) }) else { + return false; + }; + let bump = fspy_nostd_alloc::pooled_bump(); + let Ok(Some(base)) = fspy_nostd_alloc::fs::fd_path(&bump, borrowed_dirfd) else { + return false; + }; + let base_bytes = base.as_units(); + if !base_bytes.starts_with(b"/") { + return false; + } + + let mut joined = Vec::new_in(&bump); + if joined.try_reserve_exact(base_bytes.len() + 1 + raw.len()).is_err() { + return false; + } + joined.extend_from_slice(base_bytes); + joined.push(b'/'); + joined.extend_from_slice(raw); + + let mut normalized = Vec::new_in(&bump); + normalize_abs_path(&joined, &mut normalized) + && match_normalized_proc_exe(&normalized, pid, tid, task_dir_exists) +} + +fn ends_with_exe_component(path: &[u8]) -> bool { + path == b"exe" || path.ends_with(b"/exe") +} + +/// Lexically normalizes an absolute path (`path` starts with `b'/'`), resolving +/// redundant slashes, `.`, and `..`. +fn normalize_abs_path(path: &[u8], out: &mut Vec) -> bool { + if !path.starts_with(b"/") { + return false; + } + out.clear(); + if out.try_reserve(path.len().max(1)).is_err() { + return false; + } + for segment in path.split(|&b| b == b'/') { + match segment { + b"" | b"." => {} + b".." => { + while let Some(byte) = out.pop() { + if byte == b'/' { + break; + } + } + } + seg => { + out.push(b'/'); + out.extend_from_slice(seg); + } + } + } + if out.is_empty() { + out.push(b'/'); + } + true +} + +/// Matches a lexically normalized absolute path against: +/// - `/proc/self/exe` +/// - `/proc/thread-self/exe` +/// - `/proc//exe` +/// - `/proc//task//exe` +fn match_normalized_proc_exe( + norm: &[u8], + pid: i32, + tid: i32, + task_exists: impl FnOnce(i32, i32) -> bool, +) -> bool { + let Some(rest) = norm.strip_prefix(b"/proc/") else { + return false; + }; + let Some(prefix) = rest.strip_suffix(b"/exe") else { + return false; + }; + if prefix == b"self" || prefix == b"thread-self" { + return true; + } + if let Some(id) = parse_positive_i32(prefix) { + return id == pid || id == tid || task_exists(pid, id); + } + // Check `/task/` + let Some(slash) = prefix.iter().position(|&b| b == b'/') else { + return false; + }; + let (proc_id, after_proc) = prefix.split_at(slash); + let Some(task_tid_bytes) = after_proc.strip_prefix(b"/task/") else { + return false; + }; + let proc_matches = proc_id == b"self" || parse_positive_i32(proc_id) == Some(pid); + if !proc_matches { + return false; + } + let Some(task_tid) = parse_positive_i32(task_tid_bytes) else { + return false; + }; + task_tid == pid || task_tid == tid || task_exists(pid, task_tid) +} + +fn parse_positive_i32(bytes: &[u8]) -> Option { + if bytes.is_empty() || bytes[0] == b'0' { + return None; + } + let mut value = 0_i32; + for &b in bytes { + if !b.is_ascii_digit() { + return None; + } + value = value.checked_mul(10)?.checked_add(i32::from(b - b'0'))?; + } + (value > 0).then_some(value) +} + +fn write_u32_decimal(mut value: u32, buf: &mut [u8], start: usize) -> Option { + let mut digits = [0_u8; 10]; + let mut count = 0; + loop { + digits[count] = b'0' + (value % 10) as u8; + count += 1; + value /= 10; + if value == 0 { + break; + } + } + if start + count > buf.len() { + return None; + } + for i in 0..count { + buf[start + i] = digits[count - 1 - i]; + } + Some(start + count) +} + +fn task_dir_exists(pid: i32, task_tid: i32) -> bool { + if pid <= 0 || task_tid <= 0 { + return false; + } + let mut buf = [0_u8; 64]; + let prefix = b"/proc/"; + let mut pos = prefix.len(); + buf[..pos].copy_from_slice(prefix); + let Some(next) = write_u32_decimal(pid.cast_unsigned(), &mut buf, pos) else { + return false; + }; + pos = next; + let middle = b"/task/"; + if pos + middle.len() >= buf.len() { + return false; + } + buf[pos..pos + middle.len()].copy_from_slice(middle); + pos += middle.len(); + let Some(next) = write_u32_decimal(task_tid.cast_unsigned(), &mut buf, pos) else { + return false; + }; + pos = next; + if pos >= buf.len() { + return false; + } + buf[pos] = 0; + + let Some(path) = CStr::from_units_with_nul(&buf[..=pos]) else { + return false; + }; + faccessat(CWD, path, AccessFlags::empty()).is_ok() +} + +#[cfg(test)] +mod tests { + use allocator_api2::alloc::Global; + + use super::*; + + fn normalize(input: &[u8]) -> std::vec::Vec { + let mut out = Vec::new_in(Global); + assert!(normalize_abs_path(input, &mut out)); + out.as_slice().to_vec() + } + + #[test] + fn normalizes_slashes_dot_and_dotdot() { + assert_eq!(normalize(b"/proc/self/exe"), b"/proc/self/exe"); + assert_eq!(normalize(b"//proc///self/./exe"), b"/proc/self/exe"); + assert_eq!(normalize(b"/proc/123/../self/exe"), b"/proc/self/exe"); + assert_eq!(normalize(b"/proc/self/task/99/../../exe"), b"/proc/self/exe"); + assert_eq!(normalize(b"/../../../proc/self/exe"), b"/proc/self/exe"); + assert_eq!(normalize(b"/"), b"/"); + } + + #[test] + fn matches_expected_proc_exe_variants() { + let pid = 1000; + let tid = 1005; + let sibling_tid = 1009; + let exists = |p: i32, t: i32| p == pid && t == sibling_tid; + + assert!(match_normalized_proc_exe(b"/proc/self/exe", pid, tid, exists)); + assert!(match_normalized_proc_exe(b"/proc/thread-self/exe", pid, tid, exists)); + assert!(match_normalized_proc_exe(b"/proc/1000/exe", pid, tid, exists)); + assert!(match_normalized_proc_exe(b"/proc/1005/exe", pid, tid, exists)); + assert!(match_normalized_proc_exe(b"/proc/1009/exe", pid, tid, exists)); + assert!(match_normalized_proc_exe(b"/proc/1000/task/1000/exe", pid, tid, exists)); + assert!(match_normalized_proc_exe(b"/proc/1000/task/1005/exe", pid, tid, exists)); + assert!(match_normalized_proc_exe(b"/proc/1000/task/1009/exe", pid, tid, exists)); + assert!(match_normalized_proc_exe(b"/proc/self/task/1009/exe", pid, tid, exists)); + + // Non-matching paths. + assert!(!match_normalized_proc_exe(b"/proc/1/exe", pid, tid, exists)); + assert!(!match_normalized_proc_exe(b"/proc/01000/exe", pid, tid, exists)); + assert!(!match_normalized_proc_exe(b"/proc/1000/task/9999/exe", pid, tid, exists)); + assert!(!match_normalized_proc_exe(b"/proc/9999/task/1005/exe", pid, tid, exists)); + assert!(!match_normalized_proc_exe(b"/proc/self/cmdline", pid, tid, exists)); + assert!(!match_normalized_proc_exe(b"/tmp/proc/self/exe", pid, tid, exists)); + assert!(!match_normalized_proc_exe(b"/proc/self/exe/extra", pid, tid, exists)); + } + + #[test] + fn fast_exe_suffix_filter() { + assert!(ends_with_exe_component(b"exe")); + assert!(ends_with_exe_component(b"/proc/self/exe")); + assert!(ends_with_exe_component(b"./exe")); + assert!(!ends_with_exe_component(b"")); + assert!(!ends_with_exe_component(b"/proc/self/exe/")); + assert!(!ends_with_exe_component(b"/usr/bin/myexe")); + assert!(!ends_with_exe_component(b"/etc/ld.so.cache")); + } +} diff --git a/crates/fspy_elf_loader/src/sigsys/signal.rs b/crates/fspy_elf_loader/src/sigsys/signal.rs new file mode 100644 index 000000000..badd71406 --- /dev/null +++ b/crates/fspy_elf_loader/src/sigsys/signal.rs @@ -0,0 +1,1332 @@ +//! `SIGSYS` signal disposition, signal-mask, pending-signal, and fork/vfork +//! virtualization. +//! +//! Seccomp `SECCOMP_RET_TRAP` requires the kernel's `SIGSYS` disposition to +//! stay pointing at our dispatcher and `SIGSYS` to stay unblocked in every +//! thread's kernel signal mask (blocking `SIGSYS` causes the kernel to kill the +//! process when a trapped syscall executes). +//! +//! This module virtualizes `SIGSYS` across: +//! - `rt_sigaction`: stores a process-wide virtualized `SIGSYS` action without +//! modifying the kernel's `SIGSYS` disposition, strips `SIGSYS` from +//! `sa_mask` of other signals while preserving it on read-back, ignores +//! writes from `CLONE_VM` (`vfork`/`posix_spawn`) children so they cannot +//! corrupt the parent's signal table, and forwards non-seccomp or foreign +//! `SIGSYS` deliveries to the virtualized disposition. +//! - `rt_sigprocmask` & `rt_sigpending`: updates `ucontext.uc_sigmask` directly +//! so `rt_sigreturn` commits non-`SIGSYS` bits atomically, tracks per-TID +//! virtual `SIGSYS` blocked and pending state in a lock-free `(pid, tid)` +//! table with automatic dead-TID reaping, and defers/delivers non-seccomp +//! `SIGSYS` when blocked/unblocked. +//! - Masked-wait syscalls (`rt_sigsuspend`, `ppoll`, `pselect6`, +//! `epoll_pwait`, `epoll_pwait2`): strips `SIGSYS` from temporary kernel wait +//! masks while honoring `SIGSYS` blocking/unblocking in virtualized state. +//! - True `fork()` (`fork` / `clone` without `CLONE_VM`): updates process +//! ownership, resets `ACTION_LOCK`, drops parent sibling TIDs, and inherits +//! the calling thread's virtual `SIGSYS` blocked bit. + +use core::{ + cell::UnsafeCell, + mem::MaybeUninit, + ptr, + sync::atomic::{AtomicI32, AtomicU32, AtomicU64, AtomicUsize, Ordering}, +}; + +use fspy_nostd::{Error, Result}; +use linux_raw_sys::{ + errno::{EFAULT, EINTR, EINVAL, ENOMEM, ESRCH}, + general::{ + CLOCK_MONOTONIC, P_PID, SA_NODEFER, SA_RESETHAND, SA_SIGINFO, SIG_BLOCK, SIG_SETMASK, + SIG_UNBLOCK, SIGSYS, SYS_SECCOMP, WEXITED, WNOHANG, WNOWAIT, siginfo, timespec, + }, +}; +use syscalls::Sysno; + +use super::{ + arch::{ + KERNEL_SIGSET_SIZE, KernelSigaction, SIGSYS_BIT, SyscallInvocation, UNBLOCKABLE_MASK, + Ucontext, arg_i32, getpid, gettid, invoke_user_sigsys_handler, masked_wait_return_pc, + neg_errno, replay, replay_masked_wait, rt_sigaction, rt_sigprocmask, syscall6, + uc_sigmask_mut, ucontext_pc, + }, + usermem, +}; + +const SIG_DFL_RAW: usize = 0; +const SIG_IGN_RAW: usize = 1; +const SIGSYS_I32: i32 = SIGSYS.cast_signed(); + +/// Capacity of the lock-free `(pid, tid)` virtual `SIGSYS` state table +/// (16 KiB BSS; dead TIDs are automatically reaped on pressure). +const MAX_TID_SLOTS: usize = 2048; + +/// Capacity of the lock-free pending `siginfo` side table (8 KiB BSS). +const MAX_PENDING_INFOS: usize = 64; + +const KEY_BITS: u32 = 30; +const KEY_PART_MASK: u64 = (1_u64 << KEY_BITS) - 1; +const KEY_MASK: u64 = (1_u64 << (KEY_BITS * 2)) - 1; +const BIT_BLOCKED: u64 = 1_u64 << 60; +const BIT_PENDING: u64 = 1_u64 << 61; +const INFO_LOCK_BIT: u64 = 1_u64 << 63; + +struct SyncCell(UnsafeCell); + +// SAFETY: Access is serialized by `ACTION_LOCK` (for `USER_SIGSYS_ACTION`) or +// per-slot `INFO_LOCK_BIT` (for `PENDING_INFOS`). +unsafe impl Sync for SyncCell {} + +/// Owning PID of this address space (set in `init` and refreshed in `fork` +/// children). Any thread observing `getpid() != OWNER_PID` is executing inside +/// a `CLONE_VM` (`vfork` / `posix_spawn`) child sharing the parent's memory. +static OWNER_PID: AtomicI32 = AtomicI32::new(0); + +/// Owner `(pid, tid)` key holding `USER_SIGSYS_ACTION` (`0` = unlocked). +/// Storing the owner key lets waiters verify liveness via `tgkill`/`kill` and +/// reclaim the lock ONLY if the previous owner provably died (e.g. a +/// `CLONE_VM` child killed by `SIGKILL`), without ever racing a live holder. +static ACTION_LOCK: AtomicU64 = AtomicU64::new(0); +static USER_SIGSYS_ACTION: SyncCell = SyncCell(UnsafeCell::new(KernelSigaction { + sa_handler: SIG_DFL_RAW, + sa_flags: 0, + sa_restorer: 0, + sa_mask: 0, +})); + +/// Bit `sig - 1` records whether the target included `SIGSYS` in `sa_mask` +/// when installing a handler for signal `sig` (`1..=64`, `sig != SIGSYS`). +static SA_MASK_HAS_SIGSYS: AtomicU64 = AtomicU64::new(0); + +/// Lock-free per-TID virtual `SIGSYS` state: +/// - `0` => empty slot +/// - bits `0..30`: Linux TID +/// - bits `30..60`: Linux PID +/// - bit `60`: `BIT_BLOCKED` +/// - bit `61`: `BIT_PENDING` +static TID_SLOTS: [AtomicU64; MAX_TID_SLOTS] = [const { AtomicU64::new(0) }; MAX_TID_SLOTS]; +static OCCUPIED_SLOTS: AtomicUsize = AtomicUsize::new(0); + +struct PendingInfoSlot { + key: AtomicU64, + info: SyncCell>, +} + +static PENDING_INFOS: [PendingInfoSlot; MAX_PENDING_INFOS] = [const { + PendingInfoSlot { + key: AtomicU64::new(0), + info: SyncCell(UnsafeCell::new(MaybeUninit::uninit())), + } +}; MAX_PENDING_INFOS]; + +/// Per-slot monotonic counter incremented whenever a non-seccomp `SIGSYS` is +/// deferred on that `(pid, tid)` slot, allowing masked waits on one thread to +/// detect spurious `-EINTR` without false retries caused by deferred `SIGSYS` +/// arriving on other threads. +static TID_DEFERRED_SEQ: [AtomicU32; MAX_TID_SLOTS] = [const { AtomicU32::new(0) }; MAX_TID_SLOTS]; + +/// Bounded spin budget for `INFO_LOCK_BIT` so a `CLONE_VM` child killed while +/// updating a pending `siginfo` slot cannot hang another thread forever. +const MAX_INFO_LOCK_SPINS: usize = 1_000_000; + +/// Outcome of `handle_rt_sigprocmask`. +pub enum SigprocmaskOutcome { + Done(isize), + DeliverPendingSigsys(isize), +} + +/// `pselect6` argument 6 points to this two-word structure. +#[derive(Clone, Copy)] +#[repr(C)] +struct PselectSigmask { + ss: *const u64, + ss_len: usize, +} + +/// Initializes virtualized `SIGSYS` state from the process's pre-install +/// kernel `SIGSYS` action and inherited signal mask. +pub fn init(inherited_action: KernelSigaction, inherited_sigsys_blocked: bool) { + let pid = getpid(); + OWNER_PID.store(pid, Ordering::Release); + ACTION_LOCK.store(0, Ordering::Release); + with_action_lock(|slot| { + *slot = inherited_action; + }); + SA_MASK_HAS_SIGSYS.store(0, Ordering::Release); + clear_all_tid_slots(); + if inherited_sigsys_blocked { + let _ = set_tid_blocked(pid, gettid(), true); + } +} + +/// Returns `true` when the calling thread belongs to a `CLONE_VM` child +/// (`vfork` / `posix_spawn`) sharing its parent's address space. +#[inline] +#[must_use] +pub fn is_shared_vm_child() -> bool { + let owner = OWNER_PID.load(Ordering::Acquire); + owner > 0 && getpid() != owner +} + +/// Resets process-owned state in a freshly `fork()`'d child (separate COW +/// address space), dropping parent sibling TIDs, releasing any spinlock held +/// by a sibling thread at `fork()` time, and inheriting the calling thread's +/// virtual `SIGSYS` blocked state. +pub fn on_fork_child(parent_blocked: bool) { + let pid = getpid(); + OWNER_PID.store(pid, Ordering::Release); + ACTION_LOCK.store(0, Ordering::Release); + clear_all_tid_slots(); + if parent_blocked { + let _ = set_tid_blocked(pid, gettid(), true); + } +} + +/// Captures and removes the current thread's `TID_SLOTS` entry prior to +/// `SYS_execve` (so `vfork` / `posix_spawn` children do not leak a TID slot in +/// the parent's address space). Returns the previous entry flags to pass to +/// [`restore_current_tid_entry`] if `SYS_execve` fails. +pub fn take_current_tid_entry() -> Option<(u64, Option)> { + if OCCUPIED_SLOTS.load(Ordering::Acquire) == 0 { + return None; + } + let key = make_key(getpid(), gettid())?; + let prev_flags = update_tid_flags(key, 0, BIT_BLOCKED | BIT_PENDING).ok()?; + if prev_flags == 0 { + return None; + } + let info = if (prev_flags & BIT_PENDING) != 0 { take_pending_info(key) } else { None }; + Some((prev_flags, info)) +} + +/// Restores a TID entry removed by [`take_current_tid_entry`] after a failed +/// `SYS_execve`. +pub fn restore_current_tid_entry(saved: Option<(u64, Option)>) { + let Some((flags, info)) = saved else { + return; + }; + let Some(key) = make_key(getpid(), gettid()) else { + return; + }; + if let Some(info) = info { + store_pending_info(key, info); + } + let _ = update_tid_flags(key, flags, 0); +} + +fn with_action_lock(f: impl FnOnce(&mut KernelSigaction) -> R) -> R { + // Block ALL maskable signals (including `SIGSYS`) across the brief + // critical section so an async non-seccomp `SIGSYS` (`tgkill`/`kill`) + // cannot re-enter `with_action_lock` on the same thread and self-deadlock. + // The closure performs only in-memory copies; contention wait-loop syscalls + // (`waitid`/`kill`/`tgkill`/`sched_yield`) run from our allowlisted `PF_X` + // range (note: a target-installed seccomp filter trapping those syscalls + // during contention would see `SIGSYS` blocked briefly). + let block_all = !UNBLOCKABLE_MASK; + let mut saved: u64 = 0; + // SAFETY: `block_all` and `saved` are valid stack-local `u64` values. + let masked = unsafe { rt_sigprocmask(SIG_SETMASK, &raw const block_all, &raw mut saved) } == 0; + let my_pid = getpid(); + let my_key = make_key(my_pid, gettid()).unwrap_or(1); + let mut spins = 0_usize; + loop { + match ACTION_LOCK.compare_exchange_weak(0, my_key, Ordering::Acquire, Ordering::Relaxed) { + Ok(_) => break, + Err(owner) => { + spins += 1; + if spins.trailing_zeros() >= 10 { + // Check whether the lock holder is provably dead (including + // an unreaped zombie `CLONE_VM` child killed by `SIGKILL`). + // Never steal from a live preempted thread. + if owner != 0 + && owner != my_key + && !is_tid_alive(my_pid, slot_pid(owner), slot_tid(owner)) + && ACTION_LOCK + .compare_exchange(owner, my_key, Ordering::AcqRel, Ordering::Relaxed) + .is_ok() + { + break; + } + // SAFETY: `sched_yield` takes no arguments and is async-signal-safe. + let _ = unsafe { syscall6(Sysno::sched_yield as usize, 0, 0, 0, 0, 0, 0) }; + } else { + core::hint::spin_loop(); + } + } + } + } + // SAFETY: Exclusively serialized by `ACTION_LOCK` (`my_key`). + let result = unsafe { f(&mut *USER_SIGSYS_ACTION.0.get()) }; + ACTION_LOCK.store(0, Ordering::Release); + if masked { + // SAFETY: `saved` is a valid stack-local `u64`. + let _ = unsafe { rt_sigprocmask(SIG_SETMASK, &raw const saved, ptr::null_mut()) }; + } + result +} + +/// Combines the thread's kernel signal mask from `ucontext.uc_sigmask` with +/// the virtualized `SIGSYS` blocked bit for the current thread. +#[must_use] +pub fn virtual_sigmask_from(kernel_mask: u64) -> u64 { + let base = kernel_mask & !UNBLOCKABLE_MASK; + if is_current_tid_blocked() { base | SIGSYS_BIT } else { base & !SIGSYS_BIT } +} + +const fn make_key(pid: i32, tid: i32) -> Option { + if pid <= 0 || tid <= 0 { + return None; + } + let p = pid.cast_unsigned() as u64; + let t = tid.cast_unsigned() as u64; + if p > KEY_PART_MASK || t > KEY_PART_MASK { + return None; + } + Some((p << KEY_BITS) | t) +} + +const fn slot_pid(val: u64) -> i32 { + ((val >> KEY_BITS) & KEY_PART_MASK) as i32 +} + +const fn slot_tid(val: u64) -> i32 { + (val & KEY_PART_MASK) as i32 +} + +fn clear_all_tid_slots() { + for (slot, seq) in TID_SLOTS.iter().zip(TID_DEFERRED_SEQ.iter()) { + slot.store(0, Ordering::Relaxed); + seq.store(0, Ordering::Relaxed); + } + for slot in &PENDING_INFOS { + slot.key.store(0, Ordering::Relaxed); + } + OCCUPIED_SLOTS.store(0, Ordering::Release); +} + +fn find_tid_slot_index(pid: i32, tid: i32) -> Option { + if OCCUPIED_SLOTS.load(Ordering::Acquire) == 0 { + return None; + } + let key = make_key(pid, tid)?; + for (idx, slot) in TID_SLOTS.iter().enumerate() { + let val = slot.load(Ordering::Acquire); + if val != 0 && (val & KEY_MASK) == key { + return Some(idx); + } + } + None +} + +fn read_tid_deferred_seq(pid: i32, tid: i32) -> u32 { + find_tid_slot_index(pid, tid).map_or(0, |idx| TID_DEFERRED_SEQ[idx].load(Ordering::Acquire)) +} + +fn bump_tid_deferred_seq(pid: i32, tid: i32) { + if let Some(idx) = find_tid_slot_index(pid, tid) { + TID_DEFERRED_SEQ[idx].fetch_add(1, Ordering::Release); + } +} + +fn lookup_tid_flags(pid: i32, tid: i32) -> u64 { + if OCCUPIED_SLOTS.load(Ordering::Acquire) == 0 { + return 0; + } + let Some(key) = make_key(pid, tid) else { + return 0; + }; + for slot in &TID_SLOTS { + let val = slot.load(Ordering::Acquire); + if val != 0 && (val & KEY_MASK) == key { + return val & (BIT_BLOCKED | BIT_PENDING); + } + } + 0 +} + +#[must_use] +pub fn is_current_tid_blocked() -> bool { + if OCCUPIED_SLOTS.load(Ordering::Acquire) == 0 { + return false; + } + (lookup_tid_flags(getpid(), gettid()) & BIT_BLOCKED) != 0 +} + +fn is_current_tid_pending() -> bool { + if OCCUPIED_SLOTS.load(Ordering::Acquire) == 0 { + return false; + } + (lookup_tid_flags(getpid(), gettid()) & BIT_PENDING) != 0 +} + +fn is_tid_alive(my_pid: i32, slot_p: i32, slot_t: i32) -> bool { + if slot_p == my_pid { + // `tgkill(pid, tid, 0)` probes thread liveness in our thread group. + // SAFETY: signal 0 performs only existence validation. + let rc = unsafe { + syscall6( + Sysno::tgkill as usize, + my_pid.cast_unsigned() as usize, + slot_t.cast_unsigned() as usize, + 0, + 0, + 0, + 0, + ) + }; + rc != neg_errno(ESRCH) + } else { + // First detect an unreaped zombie child without reaping it (`WNOWAIT`), + // since `kill(pid, 0)` still returns `0` for zombies. + // SAFETY: zero-initialized `siginfo` is valid writable storage for `waitid`. + let mut info: siginfo = unsafe { core::mem::zeroed() }; + // SAFETY: `waitid(P_PID, slot_p, &info, WEXITED | WNOHANG | WNOWAIT)` + // never blocks and never consumes the child's wait status. + let wrc = unsafe { + syscall6( + Sysno::waitid as usize, + P_PID as usize, + slot_p.cast_unsigned() as usize, + (&raw mut info).addr(), + (WEXITED | WNOHANG | WNOWAIT) as usize, + 0, + 0, + ) + }; + if wrc == 0 { + // SAFETY: `waitid(WEXITED)` populates `_sigchld._pid` when a child has exited. + let exited_pid = + unsafe { info.__bindgen_anon_1.__bindgen_anon_1._sifields._sigchld._pid }; + if exited_pid == slot_p { + return false; + } + } + // `kill(pid, 0)` probes whether a `vfork`/other process still exists. + // SAFETY: signal 0 performs only existence validation. + let rc = unsafe { + syscall6(Sysno::kill as usize, slot_p.cast_unsigned() as usize, 0, 0, 0, 0, 0) + }; + rc != neg_errno(ESRCH) + } +} + +fn reap_dead_tids(my_pid: i32) { + for slot in &TID_SLOTS { + let val = slot.load(Ordering::Acquire); + if val == 0 { + continue; + } + let p = slot_pid(val); + let t = slot_tid(val); + if !is_tid_alive(my_pid, p, t) + && slot.compare_exchange(val, 0, Ordering::AcqRel, Ordering::Relaxed).is_ok() + { + OCCUPIED_SLOTS.fetch_sub(1, Ordering::Release); + let _ = take_pending_info(val & KEY_MASK); + } + } +} + +/// Atomically sets `set_bits` and clears `clear_bits` on the `(pid, tid)` +/// slot, returning the previous flags (`BIT_BLOCKED | BIT_PENDING`). +fn update_tid_flags(key: u64, set_bits: u64, clear_bits: u64) -> Result { + // 1. Update an existing entry for `key` if present. + if OCCUPIED_SLOTS.load(Ordering::Acquire) != 0 { + for slot in &TID_SLOTS { + loop { + let val = slot.load(Ordering::Acquire); + if val == 0 || (val & KEY_MASK) != key { + break; + } + let old_flags = val & (BIT_BLOCKED | BIT_PENDING); + let new_flags = (old_flags | set_bits) & !clear_bits; + if new_flags == old_flags { + return Ok(old_flags); + } + let new_val = if new_flags == 0 { 0 } else { key | new_flags }; + if slot + .compare_exchange_weak(val, new_val, Ordering::AcqRel, Ordering::Relaxed) + .is_ok() + { + if new_val == 0 { + OCCUPIED_SLOTS.fetch_sub(1, Ordering::Release); + } + return Ok(old_flags); + } + } + } + } + + let new_flags = set_bits & !clear_bits; + if new_flags == 0 { + return Ok(0); + } + + // 2. Insert a new slot; if the table is under pressure or full, reap dead + // TIDs (e.g. exited pthreads that blocked signals on teardown). + if OCCUPIED_SLOTS.load(Ordering::Acquire) >= MAX_TID_SLOTS / 2 { + reap_dead_tids(slot_pid(key)); + } + + for attempt in 0..2 { + for slot in &TID_SLOTS { + if slot.load(Ordering::Relaxed) == 0 + && slot + .compare_exchange(0, key | new_flags, Ordering::AcqRel, Ordering::Relaxed) + .is_ok() + { + OCCUPIED_SLOTS.fetch_add(1, Ordering::Release); + return Ok(0); + } + } + if attempt == 0 { + reap_dead_tids(slot_pid(key)); + } + } + + Err(Error::NOMEM) +} + +fn set_tid_blocked(pid: i32, tid: i32, blocked: bool) -> Result<()> { + let key = make_key(pid, tid).ok_or(Error::INVAL)?; + if blocked { + update_tid_flags(key, BIT_BLOCKED, 0)?; + } else { + update_tid_flags(key, 0, BIT_BLOCKED)?; + } + Ok(()) +} + +const fn synthetic_sigsys_info() -> siginfo { + // SAFETY: zero-initialized `siginfo` is a valid C struct; populate `si_signo`. + let mut info: siginfo = unsafe { core::mem::zeroed() }; + info.__bindgen_anon_1.__bindgen_anon_1.si_signo = SIGSYS_I32; + info.__bindgen_anon_1.__bindgen_anon_1.si_code = -6; // SI_TKILL + info +} + +fn store_pending_info(key: u64, info: siginfo) { + // Pass 0: update an existing slot for `key`. + // Pass 1: claim an empty slot. + // Pass 2: reclaim any slot (including one abandoned with `INFO_LOCK_BIT`) + // whose owner thread is provably dead via `tgkill`/`kill` (`-ESRCH`). + let my_pid = slot_pid(key); + for pass in 0..3 { + for slot in &PENDING_INFOS { + let cur = slot.key.load(Ordering::Acquire); + let can_claim = match pass { + 0 => cur == key, + 1 => cur == 0, + _ => { + let owner = cur & KEY_MASK; + owner != 0 + && owner != key + && !is_tid_alive(my_pid, slot_pid(owner), slot_tid(owner)) + } + }; + if can_claim + && slot + .key + .compare_exchange(cur, key | INFO_LOCK_BIT, Ordering::AcqRel, Ordering::Relaxed) + .is_ok() + { + // SAFETY: `INFO_LOCK_BIT` grants exclusive write access to `slot.info`. + unsafe { (*slot.info.0.get()).write(info) }; + slot.key.store(key, Ordering::Release); + return; + } + } + } +} + +fn take_pending_info(key: u64) -> Option { + // Lock with the calling (live) thread's own key so `store_pending_info` + // pass 2 never mistakes a live `reap_dead_tids` take for an abandoned dead slot. + let lock_val = make_key(getpid(), gettid()).unwrap_or(key) | INFO_LOCK_BIT; + for slot in &PENDING_INFOS { + let mut spins = 0_usize; + loop { + let cur = slot.key.load(Ordering::Acquire); + if cur == (key | INFO_LOCK_BIT) { + spins += 1; + if spins >= MAX_INFO_LOCK_SPINS { + // Never clear a live thread's lock bit (which would race + // an in-progress write); fall back to `synthetic_sigsys_info`. + break; + } + core::hint::spin_loop(); + continue; + } + if cur != key { + break; + } + if slot + .key + .compare_exchange_weak(key, lock_val, Ordering::AcqRel, Ordering::Relaxed) + .is_ok() + { + // SAFETY: `slot.info` was initialized before publishing `key`. + let info = unsafe { (*slot.info.0.get()).assume_init_read() }; + slot.key.store(0, Ordering::Release); + return Some(info); + } + } + } + None +} + +fn record_pending_sigsys(pid: i32, tid: i32, info: *const siginfo) { + let Some(key) = make_key(pid, tid) else { + return; + }; + let saved = if info.is_null() { + synthetic_sigsys_info() + } else { + // SAFETY: Kernel guarantees `info` is readable in `SA_SIGINFO` handler. + unsafe { *info } + }; + store_pending_info(key, saved); + let _ = update_tid_flags(key, BIT_PENDING, 0); +} + +fn take_pending_sigsys(pid: i32, tid: i32) -> Option { + if OCCUPIED_SLOTS.load(Ordering::Acquire) == 0 { + return None; + } + let key = make_key(pid, tid)?; + let prev = update_tid_flags(key, 0, BIT_PENDING).ok()?; + if (prev & BIT_PENDING) == 0 { + return None; + } + Some(take_pending_info(key).unwrap_or_else(synthetic_sigsys_info)) +} + +fn discard_pending_sigsys(pid: i32, tid: i32) { + let _ = take_pending_sigsys(pid, tid); +} + +/// Handles intercepted `rt_sigaction(signum, act, oldact, sigsetsize)`. +/// +/// # Safety +/// +/// `inv` must contain the arguments from a trapped `rt_sigaction` syscall. +pub unsafe fn handle_rt_sigaction(inv: SyscallInvocation) -> isize { + let signum = arg_i32(inv.args[0]); + let act_ptr = inv.args[1]; + let oldact_ptr = inv.args[2]; + let sigsetsize = inv.args[3]; + + if sigsetsize != KERNEL_SIGSET_SIZE { + return neg_errno(EINVAL); + } + + let shared_vm = is_shared_vm_child(); + + if signum == SIGSYS_I32 { + let new_act = if act_ptr != 0 { + // SAFETY: `KernelSigaction` is a plain `#[repr(C)]` struct of integers. + let Ok(mut act) = (unsafe { usermem::read_user::(act_ptr) }) else { + return neg_errno(EFAULT); + }; + act.sa_mask &= !UNBLOCKABLE_MASK; + Some(act) + } else { + None + }; + + // Read `prev` first and validate/write `oldact` before mutating the + // virtualized action so an unwritable `oldact` returns `-EFAULT` + // without changing signal state. + let prev = with_action_lock(|slot| *slot); + // SAFETY: user pointer from the trapped syscall (see `usermem`). + if oldact_ptr != 0 && unsafe { usermem::write_user(oldact_ptr, &prev) }.is_err() { + return neg_errno(EFAULT); + } + + if let Some(act) = new_act + && !shared_vm + { + with_action_lock(|slot| { + *slot = act; + }); + if act.sa_handler == SIG_IGN_RAW { + discard_pending_sigsys(getpid(), gettid()); + } + } + return 0; + } + + // Other signals: strip SIGSYS from `act.sa_mask` before calling the kernel, + // and restore the virtualized SIGSYS bit in `oldact.sa_mask` on read-back. + let sig_bit = + if (1..=64).contains(&signum) { Some(1_u64 << (signum - 1).cast_unsigned()) } else { None }; + + let (filtered_act, new_had_sigsys) = if act_ptr != 0 { + // SAFETY: `KernelSigaction` is a plain `#[repr(C)]` struct of integers. + let Ok(mut act) = (unsafe { usermem::read_user::(act_ptr) }) else { + return neg_errno(EFAULT); + }; + let had = (act.sa_mask & SIGSYS_BIT) != 0; + act.sa_mask &= !SIGSYS_BIT; + (Some(act), Some(had)) + } else { + (None, None) + }; + + let prev_had_sigsys = + sig_bit.is_some_and(|bit| (SA_MASK_HAS_SIGSYS.load(Ordering::Acquire) & bit) != 0); + + let kernel_act_ptr = filtered_act.as_ref().map_or(0, |a| ptr::from_ref(a).addr()); + // SAFETY: `kernel_act_ptr` is either null or points to `filtered_act`. + let rc = unsafe { + syscall6( + Sysno::rt_sigaction as usize, + inv.args[0], + kernel_act_ptr, + oldact_ptr, + sigsetsize, + 0, + 0, + ) + }; + + if rc == 0 { + if !shared_vm && let (Some(bit), Some(had)) = (sig_bit, new_had_sigsys) { + if had { + SA_MASK_HAS_SIGSYS.fetch_or(bit, Ordering::Release); + } else { + SA_MASK_HAS_SIGSYS.fetch_and(!bit, Ordering::Release); + } + } + if oldact_ptr != 0 && prev_had_sigsys { + // SAFETY: `KernelSigaction` is a plain `#[repr(C)]` struct of integers. + if let Ok(mut oldact) = unsafe { usermem::read_user::(oldact_ptr) } { + oldact.sa_mask |= SIGSYS_BIT; + // SAFETY: the kernel has just written `oldact_ptr`. + let _ = unsafe { usermem::write_user(oldact_ptr, &oldact) }; + } + } + } + + rc +} + +/// Handles intercepted `rt_sigprocmask(how, set, oldset, sigsetsize)`. +/// +/// Reads and mutates `ucontext.uc_sigmask` directly because `rt_sigreturn` +/// unconditionally installs `ucontext.uc_sigmask` as the thread's signal mask +/// when our `SIGSYS` handler returns. +/// +/// # Safety +/// +/// `inv` must contain the arguments from a trapped `rt_sigprocmask` syscall, +/// and `ucontext` must be the live writable `Ucontext` for that signal frame. +#[expect(clippy::cast_possible_truncation, reason = "Linux sigprocmask `how` is u32")] +pub unsafe fn handle_rt_sigprocmask( + inv: SyscallInvocation, + ucontext: &mut Ucontext, +) -> SigprocmaskOutcome { + let how = inv.args[0] as u32; + let set_ptr = inv.args[1]; + let oldset_ptr = inv.args[2]; + let sigsetsize = inv.args[3]; + + if sigsetsize != KERNEL_SIGSET_SIZE { + return SigprocmaskOutcome::Done(neg_errno(EINVAL)); + } + + // Invalid `how` with non-null `set`: replay directly to the kernel so + // `copy_from_user(set)` (`-EFAULT`) runs BEFORE the `how` check (`-EINVAL`), + // matching Linux kernel semantics relied upon by Abseil `AddressIsReadable` + // (`syscall(SYS_rt_sigprocmask, ~0, addr, NULL, 8)`). + if set_ptr != 0 && how != SIG_BLOCK && how != SIG_UNBLOCK && how != SIG_SETMASK { + // SAFETY: Kernel never modifies the signal mask when `how` is invalid. + return SigprocmaskOutcome::Done(unsafe { replay(inv) }); + } + + let pid = getpid(); + let tid = gettid(); + let cur_kernel_mask = *uc_sigmask_mut(ucontext) & !(SIGSYS_BIT | UNBLOCKABLE_MASK); + let was_blocked = (lookup_tid_flags(pid, tid) & BIT_BLOCKED) != 0; + + // Read `set` before writing `oldset` so `set == oldset` aliasing works and + // an unreadable `set` returns `-EFAULT` before touching `oldset`. + let raw_mask = if set_ptr != 0 { + // SAFETY: `u64` accepts any bit pattern. + let Ok(mask) = (unsafe { usermem::read_user::(set_ptr) }) else { + return SigprocmaskOutcome::Done(neg_errno(EFAULT)); + }; + Some(mask) + } else { + None + }; + + if oldset_ptr != 0 { + let old_virtual = + if was_blocked { cur_kernel_mask | SIGSYS_BIT } else { cur_kernel_mask & !SIGSYS_BIT }; + // SAFETY: user pointer from the trapped syscall (see `usermem`). + if unsafe { usermem::write_user(oldset_ptr, &old_virtual) }.is_err() { + return SigprocmaskOutcome::Done(neg_errno(EFAULT)); + } + } + + if let Some(raw_mask) = raw_mask { + let filtered_mask = raw_mask & !(SIGSYS_BIT | UNBLOCKABLE_MASK); + let has_sigsys = (raw_mask & SIGSYS_BIT) != 0; + + let new_kernel_mask = match how { + SIG_BLOCK => cur_kernel_mask | filtered_mask, + SIG_UNBLOCK => cur_kernel_mask & !filtered_mask, + SIG_SETMASK => filtered_mask, + _ => unreachable!(), + }; + let now_blocked = match how { + SIG_BLOCK => was_blocked || has_sigsys, + SIG_UNBLOCK => was_blocked && !has_sigsys, + SIG_SETMASK => has_sigsys, + _ => unreachable!(), + }; + + if now_blocked != was_blocked && set_tid_blocked(pid, tid, now_blocked).is_err() { + return SigprocmaskOutcome::Done(neg_errno(ENOMEM)); + } + *uc_sigmask_mut(ucontext) = new_kernel_mask; + + if was_blocked && !now_blocked && (lookup_tid_flags(pid, tid) & BIT_PENDING) != 0 { + return SigprocmaskOutcome::DeliverPendingSigsys(0); + } + } + + SigprocmaskOutcome::Done(0) +} + +/// Takes and delivers any deferred pending `SIGSYS` for the calling thread on +/// the entry stack. +/// +/// # Safety +/// +/// Must be called on the entry stack with a valid writable `ucontext`. +#[inline(never)] +pub unsafe fn deliver_pending_sigsys(ucontext: &mut Ucontext) { + let pid = getpid(); + let tid = gettid(); + if let Some(mut info) = take_pending_sigsys(pid, tid) { + // SAFETY: `info` is valid stack storage and `ucontext` is writable. + unsafe { deliver_sigsys_now(SIGSYS_I32, &raw mut info, ucontext) }; + } +} + +/// Handles intercepted `rt_sigpending(set, sigsetsize)`, merging any virtually +/// pending `SIGSYS` into the returned set. +/// +/// # Safety +/// +/// `inv` must contain the arguments from a trapped `rt_sigpending` syscall. +pub unsafe fn handle_rt_sigpending(inv: SyscallInvocation) -> isize { + // SAFETY: Replays `rt_sigpending` directly to the kernel. + let rc = unsafe { replay(inv) }; + if rc == 0 && inv.args[0] != 0 && inv.args[1] == KERNEL_SIGSET_SIZE && is_current_tid_pending() + { + // SAFETY: `u64` accepts any bit pattern. + if let Ok(mask) = unsafe { usermem::read_user::(inv.args[0]) } { + let updated = mask | SIGSYS_BIT; + // SAFETY: the kernel has just written `inv.args[0]`. + if unsafe { usermem::write_user(inv.args[0], &updated) }.is_err() { + return neg_errno(EFAULT); + } + } + } + rc +} + +/// Handles masked-wait syscalls where `args[mask_idx]` is a `*const u64` +/// sigset pointer and `args[size_idx]` is `sigsetsize`. +/// +/// Covers `rt_sigsuspend` (0, 1, `allow_null_mask = false`), `ppoll` (3, 4), +/// `epoll_pwait` (4, 5), and `epoll_pwait2` (4, 5). +/// +/// Must execute on the entry stack (not on `stack_pool`) so any `SA_ONSTACK` +/// signal delivered while waiting does not re-enter and clobber the active +/// `SIGSYS` frame on `sigaltstack`. +/// +/// # Safety +/// +/// `inv` must contain the arguments from the corresponding trapped syscall, and +/// `ucontext` must be the live writable signal frame for that trap. +pub unsafe fn handle_masked_wait( + mut inv: SyscallInvocation, + ucontext: &mut Ucontext, + mask_idx: usize, + size_idx: usize, + allow_null_mask: bool, +) -> isize { + let mask_ptr = inv.args[mask_idx]; + let sigsetsize = inv.args[size_idx]; + + if mask_ptr == 0 { + if !allow_null_mask { + // `rt_sigsuspend(NULL, ...)` fails immediately with `-EFAULT`. + // SAFETY: Replays the invalid invocation directly. + return unsafe { replay(inv) }; + } + let orig_mask = ucontext.uc_sigmask & !(SIGSYS_BIT | UNBLOCKABLE_MASK); + inv.args[mask_idx] = (&raw const orig_mask).addr(); + inv.args[size_idx] = KERNEL_SIGSET_SIZE; + // SAFETY: `orig_mask` remains valid on the entry stack for the syscall. + return unsafe { replay_masked_wait(&inv, ucontext) }; + } + + if sigsetsize != KERNEL_SIGSET_SIZE { + // SAFETY: Replay invalid sigsetsize to preserve exact `-EINVAL`. + return unsafe { replay(inv) }; + } + + // SAFETY: `u64` accepts any bit pattern. + let Ok(raw_mask) = (unsafe { usermem::read_user::(mask_ptr) }) else { + return neg_errno(EFAULT); + }; + + let filtered = raw_mask & !(SIGSYS_BIT | UNBLOCKABLE_MASK); + inv.args[mask_idx] = (&raw const filtered).addr(); + // SAFETY: `filtered` lives on the entry stack for the wait duration. + unsafe { run_wait_with_virtual_sigsys(inv, ucontext, (raw_mask & SIGSYS_BIT) != 0) } +} + +/// Handles `pselect6(nfds, readfds, writefds, exceptfds, timeout, sigmask_struct)`. +/// +/// Must execute on the entry stack (not on `stack_pool`). +/// +/// # Safety +/// +/// `inv` must contain the arguments from a trapped `pselect6` syscall, and +/// `ucontext` must be the live writable signal frame for that trap. +pub unsafe fn handle_pselect6(mut inv: SyscallInvocation, ucontext: &mut Ucontext) -> isize { + let orig_mask = ucontext.uc_sigmask & !(SIGSYS_BIT | UNBLOCKABLE_MASK); + let sig_ptr = inv.args[5]; + if sig_ptr == 0 { + let local_wrapper = PselectSigmask { ss: &raw const orig_mask, ss_len: KERNEL_SIGSET_SIZE }; + inv.args[5] = (&raw const local_wrapper).addr(); + // SAFETY: `local_wrapper` and `orig_mask` live on the entry stack. + return unsafe { replay_masked_wait(&inv, ucontext) }; + } + + // SAFETY: `PselectSigmask` is a plain `#[repr(C)]` struct of pointer + usize. + let Ok(wrapper) = (unsafe { usermem::read_user::(sig_ptr) }) else { + return neg_errno(EFAULT); + }; + if wrapper.ss.is_null() { + let local_wrapper = PselectSigmask { ss: &raw const orig_mask, ss_len: KERNEL_SIGSET_SIZE }; + inv.args[5] = (&raw const local_wrapper).addr(); + // SAFETY: `local_wrapper` and `orig_mask` live on the entry stack. + return unsafe { replay_masked_wait(&inv, ucontext) }; + } + if wrapper.ss_len != KERNEL_SIGSET_SIZE { + // SAFETY: Invalid sigsetsize; replay directly to return `-EINVAL`. + return unsafe { replay(inv) }; + } + + // SAFETY: `u64` accepts any bit pattern. + let Ok(raw_mask) = (unsafe { usermem::read_user::(wrapper.ss.addr()) }) else { + return neg_errno(EFAULT); + }; + let filtered = raw_mask & !(SIGSYS_BIT | UNBLOCKABLE_MASK); + let local_wrapper = PselectSigmask { ss: &raw const filtered, ss_len: KERNEL_SIGSET_SIZE }; + inv.args[5] = (&raw const local_wrapper).addr(); + // SAFETY: `local_wrapper` and `filtered` live on the entry stack for the wait. + unsafe { run_wait_with_virtual_sigsys(inv, ucontext, (raw_mask & SIGSYS_BIT) != 0) } +} + +#[inline] +fn monotonic_ns() -> Option { + let mut ts = timespec { tv_sec: 0, tv_nsec: 0 }; + // SAFETY: `ts` is valid stack storage for `clock_gettime(CLOCK_MONOTONIC)`. + let rc = unsafe { + syscall6( + Sysno::clock_gettime as usize, + CLOCK_MONOTONIC as usize, + (&raw mut ts).addr(), + 0, + 0, + 0, + 0, + ) + }; + if rc == 0 { + Some(i128::from(ts.tv_sec) * 1_000_000_000 + i128::from(ts.tv_nsec)) + } else { + None + } +} + +/// Clears `pselect6`'s non-null `readfds`/`writefds`/`exceptfds` bitsets when +/// a zero-timeout retry loop is exhausted under a continuous `SIGSYS` flood. +fn clear_pselect_fdsets(inv: &SyscallInvocation) { + // Cap at `FD_SETSIZE` (1024 bits = 128 bytes) so callers passing a large + // `nfds` (e.g. `getdtablesize()`) with a standard `fd_set` never get memory + // beyond their `fd_set` zeroed if zero-timeout retries are exhausted. + let nfds = arg_i32(inv.args[0]).min(1024); + if nfds <= 0 { + return; + } + let words = nfds.cast_unsigned().div_ceil(64) as usize; + let total_bytes = words * core::mem::size_of::(); + let zeros = [0_u8; 128]; + for fdset_ptr in [inv.args[1], inv.args[2], inv.args[3]] { + if fdset_ptr == 0 { + continue; + } + // SAFETY: user pointer from the trapped syscall (see `usermem`). + let _ = unsafe { usermem::write_user_bytes(fdset_ptr, &zeros[..total_bytes]) }; + } +} + +/// Replays a masked-wait syscall while `SIGSYS` is virtually blocked, retrying +/// if the wait returned `-EINTR` solely because a virtually-blocked non-seccomp +/// `SIGSYS` woke the kernel wait. +#[expect(clippy::cast_possible_truncation, reason = "Linux timeout fields fit in i32/i64")] +unsafe fn replay_masked_wait_deferring_sigsys( + pid: i32, + tid: i32, + mut inv: SyscallInvocation, + ucontext: &mut Ucontext, +) -> isize { + const MAX_ZERO_POLL_RETRIES: u8 = 8; + let sysno = Sysno::new(inv.nr); + // Snapshot initial relative timeout (if any) before first wait so retries + // after a deferred `SIGSYS` preserve the caller's deadline for `ppoll`, + // `pselect6`, `epoll_pwait`, and `epoll_pwait2`. + let mut local_ts = timespec { tv_sec: 0, tv_nsec: 0 }; + let mut ts_arg_idx: Option = None; + let mut orig_ts_ptr: usize = 0; + let initial_timeout_ns: Option = match sysno { + Some(Sysno::ppoll | Sysno::pselect6 | Sysno::epoll_pwait2) => { + let idx = match sysno { + Some(Sysno::ppoll) => 2, + Some(Sysno::pselect6) => 4, + _ => 3, + }; + let ts_ptr = inv.args[idx]; + if ts_ptr == 0 { + None + } else { + // SAFETY: `timespec` is a `#[repr(C)]` struct of `i64` fields. + let Ok(ts) = (unsafe { usermem::read_user::(ts_ptr) }) else { + // SAFETY: Replays invalid timeout pointer directly (`-EFAULT`). + return unsafe { replay_masked_wait(&inv, ucontext) }; + }; + if ts.tv_sec < 0 || ts.tv_nsec < 0 || ts.tv_nsec >= 1_000_000_000 { + // SAFETY: Replays invalid timeout directly (`-EINVAL`). + return unsafe { replay_masked_wait(&inv, ucontext) }; + } + local_ts = ts; + ts_arg_idx = Some(idx); + orig_ts_ptr = ts_ptr; + Some(i128::from(ts.tv_sec) * 1_000_000_000 + i128::from(ts.tv_nsec)) + } + } + Some(Sysno::epoll_pwait) => { + let ms = arg_i32(inv.args[3]); + if ms < 0 { None } else { Some(i128::from(ms) * 1_000_000) } + } + // `rt_sigsuspend` has no timeout. + _ => None, + }; + + let start_ns = initial_timeout_ns.and_then(|_| monotonic_ns()); + let mut retried = false; + let mut zero_poll_retries = 0_u8; + + loop { + if retried && let Some(idx) = ts_arg_idx { + inv.args[idx] = (&raw const local_ts).addr(); + } + let seq_before = read_tid_deferred_seq(pid, tid); + // SAFETY: `inv` points to valid entry-stack wait args (including `local_ts`). + let rc = unsafe { replay_masked_wait(&inv, ucontext) }; + if rc != neg_errno(EINTR) || read_tid_deferred_seq(pid, tid) == seq_before { + if retried && matches!(sysno, Some(Sysno::pselect6 | Sysno::ppoll)) && orig_ts_ptr != 0 + { + // SAFETY: user pointer from the trapped syscall (see `usermem`). + let _ = unsafe { usermem::write_user(orig_ts_ptr, &local_ts) }; + } + return rc; + } + retried = true; + // A virtually-blocked `SIGSYS` interrupted this thread's kernel wait; + // retry with the remaining timeout (or a bounded number of zero-timeout + // kernel polls if expired, falling back to clearing `pselect6` fd sets + // directly so a tight `SIGSYS` flood can neither livelock nor leave + // stale fd-set bits behind). + if let (Some(total_ns), Some(t0)) = (initial_timeout_ns, start_ns) { + let elapsed = monotonic_ns().map_or(total_ns, |now| now.saturating_sub(t0)); + let rem = total_ns - elapsed; + if rem <= 0 { + if zero_poll_retries >= MAX_ZERO_POLL_RETRIES { + if sysno == Some(Sysno::pselect6) { + clear_pselect_fdsets(&inv); + } + if matches!(sysno, Some(Sysno::pselect6 | Sysno::ppoll)) && orig_ts_ptr != 0 { + local_ts = timespec { tv_sec: 0, tv_nsec: 0 }; + // SAFETY: user pointer from the trapped syscall (see `usermem`). + let _ = unsafe { usermem::write_user(orig_ts_ptr, &local_ts) }; + } + return 0; + } + zero_poll_retries += 1; + match sysno { + Some(Sysno::ppoll | Sysno::pselect6 | Sysno::epoll_pwait2) => { + local_ts = timespec { tv_sec: 0, tv_nsec: 0 }; + } + Some(Sysno::epoll_pwait) => { + inv.args[3] = 0; + } + _ => {} + } + continue; + } + match sysno { + Some(Sysno::ppoll | Sysno::pselect6 | Sysno::epoll_pwait2) => { + local_ts = timespec { + tv_sec: (rem / 1_000_000_000) as i64, + tv_nsec: (rem % 1_000_000_000) as i64, + }; + } + Some(Sysno::epoll_pwait) => { + let rem_ms = + ((rem + 999_999) / 1_000_000).clamp(1, i128::from(i32::MAX)) as i32; + inv.args[3] = rem_ms.cast_unsigned() as usize; + } + _ => {} + } + } + } +} + +/// Runs a masked-wait syscall while honoring the caller's temporary `SIGSYS` +/// blocked/unblocked bit in the wait mask. +unsafe fn run_wait_with_virtual_sigsys( + inv: SyscallInvocation, + ucontext: &mut Ucontext, + wait_blocks_sigsys: bool, +) -> isize { + let pid = getpid(); + let tid = gettid(); + let was_blocked = (lookup_tid_flags(pid, tid) & BIT_BLOCKED) != 0; + + if !wait_blocks_sigsys && was_blocked { + // Wait mask temporarily unblocks `SIGSYS`. If one is already pending, + // deliver it immediately and return `-EINTR` (matching Linux `sigsuspend`). + if let Some(mut info) = take_pending_sigsys(pid, tid) { + // SAFETY: Delivering pending virtual `SIGSYS` on entry stack. + unsafe { deliver_sigsys_now(SIGSYS_I32, &raw mut info, ucontext) }; + return neg_errno(EINTR); + } + let _ = set_tid_blocked(pid, tid, false); + // SAFETY: `inv` points to valid entry-stack wait args. + let rc = unsafe { replay_masked_wait(&inv, ucontext) }; + let _ = set_tid_blocked(pid, tid, true); + return rc; + } + + if wait_blocks_sigsys && !was_blocked { + // Wait mask temporarily blocks `SIGSYS`; defer any non-seccomp `SIGSYS` + // that arrives during the wait until the wait completes. + let _ = set_tid_blocked(pid, tid, true); + // SAFETY: `inv` points to valid entry-stack wait args. + let rc = unsafe { replay_masked_wait_deferring_sigsys(pid, tid, inv, ucontext) }; + let _ = set_tid_blocked(pid, tid, false); + if let Some(mut info) = take_pending_sigsys(pid, tid) { + // SAFETY: Delivering `SIGSYS` that arrived while masked by wait. + unsafe { deliver_sigsys_now(SIGSYS_I32, &raw mut info, ucontext) }; + } + return rc; + } + + if wait_blocks_sigsys { + // SAFETY: `SIGSYS` is already blocked; retry if a deferred `SIGSYS` wakes the wait. + return unsafe { replay_masked_wait_deferring_sigsys(pid, tid, inv, ucontext) }; + } + + // SAFETY: `inv` points to valid entry-stack wait args. + unsafe { replay_masked_wait(&inv, ucontext) } +} + +/// Handles a non-seccomp or foreign-seccomp `SIGSYS` delivery, deferring +/// non-seccomp `SIGSYS` when virtually blocked on this thread and otherwise +/// forwarding it to the target's virtualized `SIGSYS` disposition. +/// +/// # Safety +/// +/// Must be called on the entry stack from the `SIGSYS` signal handler with the +/// kernel-supplied `info` and `ucontext` pointers. +pub unsafe fn forward_non_seccomp_sigsys(signum: i32, info: *mut siginfo, ucontext: *mut Ucontext) { + let is_foreign_seccomp = !info.is_null() && { + // SAFETY: Kernel guarantees `info` is valid in `SA_SIGINFO` handler. + let common = unsafe { &(*info).__bindgen_anon_1.__bindgen_anon_1 }; + common.si_code == SYS_SECCOMP.cast_signed() + }; + + if !is_foreign_seccomp && is_current_tid_blocked() { + let pid = getpid(); + let tid = gettid(); + let handler = with_action_lock(|slot| slot.sa_handler); + if handler != SIG_IGN_RAW { + record_pending_sigsys(pid, tid, info); + } + // Only mark this thread's masked wait as woken by a deferred `SIGSYS` + // when `SIGSYS` directly interrupted `replay_masked_wait`'s syscall. + // If another signal (e.g. `SIGINT`/`SIGUSR1`) was dequeued first on + // the same wake or was already executing its handler, `ucontext_pc` + // points to that user handler rather than `masked_wait_return_pc()`, + // so the wait preserves `-EINTR` instead of swallowing it. + if !ucontext.is_null() + // SAFETY: Kernel guarantees `ucontext` is readable in `SA_SIGINFO` handler. + && ucontext_pc(unsafe { &*ucontext }) == masked_wait_return_pc() + { + bump_tid_deferred_seq(pid, tid); + } + return; + } + + // SAFETY: Caller passed valid kernel signal frame pointers. + unsafe { deliver_sigsys_now(signum, info, ucontext) }; +} + +/// Delivers a `SIGSYS` immediately to the target's virtualized `SIGSYS` +/// disposition (used by both [`forward_non_seccomp_sigsys`] and deferred +/// delivery upon unblocking `SIGSYS`). +/// +/// # Safety +/// +/// Must be called on the entry stack with valid `info` and `ucontext` pointers. +pub unsafe fn deliver_sigsys_now(signum: i32, info: *mut siginfo, ucontext: *mut Ucontext) { + let user_act = with_action_lock(|slot| { + let act = *slot; + if (act.sa_flags & SA_RESETHAND as usize) != 0 { + slot.sa_handler = SIG_DFL_RAW; + } + act + }); + + match user_act.sa_handler { + SIG_IGN_RAW => {} + SIG_DFL_RAW => terminate_with_default_sigsys(), + handler_addr => { + // Our `SIGSYS` `sa_mask` blocked all maskable signals on entry; + // install the exact mask the target handler expects (`orig_mask | + // user_act.sa_mask`, with `SIGSYS` kept unblocked in the kernel). + let orig_mask = if ucontext.is_null() { + 0 + } else { + // SAFETY: Kernel-provided `ucontext` is readable. + unsafe { (*ucontext).uc_sigmask } + }; + let handler_mask = (orig_mask | user_act.sa_mask) & !(SIGSYS_BIT | UNBLOCKABLE_MASK); + // SAFETY: `handler_mask` is a valid stack-local `u64`. + let _ = + unsafe { rt_sigprocmask(SIG_SETMASK, &raw const handler_mask, ptr::null_mut()) }; + + let defer_sigsys = (user_act.sa_flags & SA_NODEFER as usize) == 0; + let pid = if defer_sigsys { getpid() } else { 0 }; + let tid = if defer_sigsys { gettid() } else { 0 }; + let prev_virtual_blocked = + defer_sigsys && (lookup_tid_flags(pid, tid) & BIT_BLOCKED) != 0; + if defer_sigsys && !prev_virtual_blocked { + let _ = set_tid_blocked(pid, tid, true); + } + + // SAFETY: `handler_addr` was registered by the target as its `SIGSYS` + // handler; `invoke_user_sigsys_handler` restores `x28` on AArch64. + unsafe { + invoke_user_sigsys_handler( + handler_addr, + (user_act.sa_flags & SA_SIGINFO as usize) != 0, + signum, + info, + ucontext, + ); + } + + if defer_sigsys && !prev_virtual_blocked { + let _ = set_tid_blocked(pid, tid, false); + } + if ucontext.is_null() { + let restore = orig_mask & !(SIGSYS_BIT | UNBLOCKABLE_MASK); + // SAFETY: `restore` is a valid stack-local `u64`. + let _ = unsafe { rt_sigprocmask(SIG_SETMASK, &raw const restore, ptr::null_mut()) }; + } else { + // Ensure returning through `rt_sigreturn` cannot re-block SIGSYS + // even if the user handler mutated `ucontext->uc_sigmask`. + // `rt_sigreturn` also restores `ucontext->uc_sigmask` atomically. + // SAFETY: Kernel-provided `ucontext` is writable. + *uc_sigmask_mut(unsafe { &mut *ucontext }) &= !SIGSYS_BIT; + } + } + } +} + +fn terminate_with_default_sigsys() -> ! { + let dfl = KernelSigaction { sa_handler: SIG_DFL_RAW, sa_flags: 0, sa_restorer: 0, sa_mask: 0 }; + // SAFETY: Restoring kernel default `SIGSYS` disposition before re-raising. + let _ = unsafe { rt_sigaction(SIGSYS_I32, &raw const dfl, ptr::null_mut()) }; + let sigsys = SIGSYS_BIT; + // SAFETY: Unblocking `SIGSYS` so `tgkill` terminates immediately. + let _ = unsafe { rt_sigprocmask(SIG_UNBLOCK, &raw const sigsys, ptr::null_mut()) }; + let pid = getpid(); + let tid = gettid(); + // SAFETY: Sends `SIGSYS` with default disposition to the current thread. + let _ = unsafe { + syscall6( + Sysno::tgkill as usize, + pid.cast_unsigned() as usize, + tid.cast_unsigned() as usize, + SIGSYS as usize, + 0, + 0, + 0, + ) + }; + loop { + // SAFETY: Fallback termination if `SIGSYS` somehow did not terminate. + let _ = + unsafe { syscall6(Sysno::exit_group as usize, 128 + SIGSYS as usize, 0, 0, 0, 0, 0) }; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn blocked_tid_table_tracks_insert_lookup_pending_and_remove() { + clear_all_tid_slots(); + let pid = getpid(); + assert_eq!(lookup_tid_flags(pid, 42), 0); + set_tid_blocked(pid, 42, true).unwrap(); + assert_eq!(lookup_tid_flags(pid, 42), BIT_BLOCKED); + assert_eq!(lookup_tid_flags(pid, 99), 0); + assert_eq!(lookup_tid_flags(pid + 1, 42), 0); + + // Duplicate insert is a no-op. + set_tid_blocked(pid, 42, true).unwrap(); + assert_eq!(OCCUPIED_SLOTS.load(Ordering::Acquire), 1); + + // Pending bit coexists with blocked bit. + record_pending_sigsys(pid, 42, ptr::null()); + assert_eq!(lookup_tid_flags(pid, 42), BIT_BLOCKED | BIT_PENDING); + let taken = take_pending_sigsys(pid, 42); + assert!(taken.is_some()); + assert_eq!(lookup_tid_flags(pid, 42), BIT_BLOCKED); + + set_tid_blocked(pid, 99, true).unwrap(); + assert_eq!(OCCUPIED_SLOTS.load(Ordering::Acquire), 2); + + set_tid_blocked(pid, 42, false).unwrap(); + assert_eq!(lookup_tid_flags(pid, 42), 0); + assert_eq!(lookup_tid_flags(pid, 99), BIT_BLOCKED); + assert_eq!(OCCUPIED_SLOTS.load(Ordering::Acquire), 1); + + set_tid_blocked(pid, 99, false).unwrap(); + assert_eq!(lookup_tid_flags(pid, 99), 0); + assert_eq!(OCCUPIED_SLOTS.load(Ordering::Acquire), 0); + } +} diff --git a/crates/fspy_elf_loader/src/sigsys/stack_pool.rs b/crates/fspy_elf_loader/src/sigsys/stack_pool.rs new file mode 100644 index 000000000..f47141721 --- /dev/null +++ b/crates/fspy_elf_loader/src/sigsys/stack_pool.rs @@ -0,0 +1,209 @@ +//! Lock-free pool of private `SIGSYS` handler stacks. +//! +//! Trapped syscalls can arrive on tiny target-owned stacks — for example musl's +//! `posix_spawn` (`char stack[1024 + PATH_MAX]` = 5 KiB, almost entirely +//! consumed by the `AArch64` kernel `rt_sigframe`) or musl Rust's 12 KiB +//! `sigaltstack`. Switching `SP` to a private 64 KiB stack before dispatching +//! our `SIGSYS` handler guarantees headroom across both debug and release builds +//! without risking stack overflow or corrupting a `vfork` parent's stack frame. + +use core::{ + ffi::c_void, + sync::atomic::{AtomicUsize, Ordering}, +}; + +use linux_raw_sys::general::{MAP_ANONYMOUS, MAP_PRIVATE, PROT_READ, PROT_WRITE}; +use syscalls::Sysno; + +use super::arch::{call_on_stack, syscall6}; + +/// Minimum size of each private `SIGSYS` handler stack (64 KiB, page-aligned on +/// 4 KiB, 16 KiB, and 64 KiB kernels). Raised dynamically via [`init_and_warm`] +/// if the kernel advertises a larger `AT_MINSIGSTKSZ` (e.g. `AArch64` SVE/SME +/// or AVX-512 / AMX hosts). +pub const MIN_SIGSYS_STACK_SIZE: usize = 64 * 1024; + +/// Number of reusable stacks retained in the lock-free cache. +/// +/// Sized for 64 concurrent trapping threads so high-core-count parallel file +/// walkers (e.g. `oxlint`, `biome`, `rspack` on 32–64-core CI runners) stay +/// inside the pool without `mmap`/`munmap` TLB shootdowns. Stacks are allocated +/// lazily on demand, so single-threaded workloads only map one stack. +pub const STACK_POOL_SLOTS: usize = 64; + +/// Active byte size of each private `SIGSYS` stack (multiple of the host page +/// size, at least [`MIN_SIGSYS_STACK_SIZE`]). +static STACK_SIZE: AtomicUsize = AtomicUsize::new(MIN_SIGSYS_STACK_SIZE); + +/// Cached `stack_top` pointers (`0` means empty slot). +/// +/// Accessed directly from [`super::arch::sigsys_trampoline`] so the common-case +/// pop/push uses zero entry-stack bytes even in unoptimized debug builds. +pub static STACK_POOL: [AtomicUsize; STACK_POOL_SLOTS] = + [const { AtomicUsize::new(0) }; STACK_POOL_SLOTS]; + +/// Configures the private `SIGSYS` stack size from `AT_MINSIGSTKSZ` and +/// `page_size`, then pre-allocates one stack during single-threaded +/// `sigsys::install` so the first trapped syscall never needs to invoke `mmap` +/// on a tiny caller stack. +pub fn init_and_warm(min_sigstksz: usize, page_size: usize) { + let page = page_size.max(4096); + // Reserve at least `2 * AT_MINSIGSTKSZ + 16 KiB` (and >= 64 KiB) so both + // Phase 1 and AArch64 `vfork` `sigaltstack` (`stack_size - 64`) always + // satisfy kernel `MINSIGSTKSZ` with ample headroom. + let needed = + min_sigstksz.saturating_mul(2).saturating_add(16 * 1024).max(MIN_SIGSYS_STACK_SIZE); + let aligned = needed.checked_add(page - 1).map_or(MIN_SIGSYS_STACK_SIZE, |n| n & !(page - 1)); + STACK_SIZE.store(aligned.max(MIN_SIGSYS_STACK_SIZE), Ordering::Release); + if let Some(top) = alloc_stack() { + release(top); + } +} + +/// Returns the active byte size of each private `SIGSYS` stack. +#[inline] +#[must_use] +pub fn stack_size() -> usize { + STACK_SIZE.load(Ordering::Acquire) +} + +/// Executes `entry(ctx)` on a private 64 KiB stack, restoring the caller's +/// stack before returning. +/// +/// Falls back to running on the current stack only if `mmap` fails (OOM). +/// +/// # Safety +/// +/// `ctx` must satisfy the safety contract expected by `entry`, and maskable +/// asynchronous signals must remain blocked for the duration of `entry` so an +/// `SA_ONSTACK` signal cannot observe `SP` outside the thread's `sigaltstack`. +pub unsafe fn run_on_private_stack(ctx: *mut c_void, entry: extern "C" fn(*mut c_void)) { + let Some(stack_top) = acquire() else { + entry(ctx); + return; + }; + // SAFETY: `stack_top` is page-aligned (therefore 16-byte aligned) and owns + // `SIGSYS_STACK_SIZE` writable bytes below it exclusively until `release`. + unsafe { call_on_stack(stack_top, ctx, entry) }; + release(stack_top); +} + +/// Cold-path allocator called by [`super::arch::sigsys_trampoline`] when all +/// [`STACK_POOL`] slots are empty. Returns `0` on OOM. +#[inline(never)] +pub extern "C" fn alloc_stack_raw() -> usize { + alloc_stack().unwrap_or(0) +} + +/// Cold-path deallocator called by [`super::arch::sigsys_trampoline`] when all +/// [`STACK_POOL`] slots are full. +#[inline(never)] +pub extern "C" fn free_stack_raw(stack_top: usize) { + if stack_top != 0 { + free_stack(stack_top); + } +} + +/// Acquires a private `SIGSYS` stack top from [`STACK_POOL`] (or `mmap` on miss). +pub fn acquire_stack() -> Option { + acquire() +} + +/// Returns a private `SIGSYS` stack top to [`STACK_POOL`] (or `munmap` if full). +pub fn release_stack(stack_top: usize) { + release(stack_top); +} + +fn acquire() -> Option { + for slot in &STACK_POOL { + let top = slot.swap(0, Ordering::AcqRel); + if top != 0 { + return Some(top); + } + } + alloc_stack() +} + +fn release(stack_top: usize) { + for slot in &STACK_POOL { + if slot.load(Ordering::Relaxed) == 0 + && slot.compare_exchange(0, stack_top, Ordering::Release, Ordering::Relaxed).is_ok() + { + return; + } + } + free_stack(stack_top); +} + +#[inline(never)] +fn alloc_stack() -> Option { + let size = stack_size(); + // SAFETY: anonymous private `mmap` of `size` bytes. + let rc = unsafe { + syscall6( + Sysno::mmap as usize, + 0, + size, + (PROT_READ | PROT_WRITE) as usize, + (MAP_PRIVATE | MAP_ANONYMOUS) as usize, + (-1_isize).cast_unsigned(), + 0, + ) + }; + if rc <= 0 { + return None; + } + let Some(top) = rc.cast_unsigned().checked_add(size) else { + // SAFETY: release mapping if address arithmetic ever overflowed. + let _ = unsafe { syscall6(Sysno::munmap as usize, rc.cast_unsigned(), size, 0, 0, 0, 0) }; + return None; + }; + Some(top) +} + +#[inline(never)] +fn free_stack(stack_top: usize) { + let size = stack_size(); + let base = stack_top - size; + // SAFETY: `base..stack_top` was mapped by `alloc_stack` and is no longer in use. + let _ = unsafe { syscall6(Sysno::munmap as usize, base, size, 0, 0, 0, 0) }; +} + +#[cfg(test)] +mod tests { + use core::sync::atomic::AtomicUsize; + + use super::*; + + static OBSERVED_SP: AtomicUsize = AtomicUsize::new(0); + static OBSERVED_ARG: AtomicUsize = AtomicUsize::new(0); + + extern "C" fn record_stack_and_arg(arg: *mut c_void) { + let local = 0usize; + OBSERVED_SP.store(core::ptr::from_ref(&local).addr(), Ordering::Release); + OBSERVED_ARG.store(arg.addr(), Ordering::Release); + } + + #[test] + fn acquires_reuses_and_switches_to_private_stack() { + let size = stack_size(); + let top = acquire().expect("mmap private stack"); + assert_eq!(top % 16, 0); + let sentinel = core::ptr::without_provenance_mut::(0x1234_5678); + // SAFETY: `top` is a freshly acquired private stack and `record_stack_and_arg` + // never dereferences `sentinel`. + unsafe { call_on_stack(top, sentinel, record_stack_and_arg) }; + let sp = OBSERVED_SP.load(Ordering::Acquire); + assert!( + (top - size..top).contains(&sp), + "expected sp {sp:#x} inside [{:#x}, {top:#x})", + top - size + ); + assert_eq!(OBSERVED_ARG.load(Ordering::Acquire), 0x1234_5678); + + release(top); + let reused = acquire().expect("re-acquire cached stack"); + assert_eq!(reused, top); + release(reused); + } +} diff --git a/crates/fspy_elf_loader/src/sigsys/usermem.rs b/crates/fspy_elf_loader/src/sigsys/usermem.rs new file mode 100644 index 000000000..2fda67386 --- /dev/null +++ b/crates/fspy_elf_loader/src/sigsys/usermem.rs @@ -0,0 +1,95 @@ +//! User memory copies for the `SIGSYS` dispatcher. +//! +//! Pointers passed to trapped syscalls are assumed to be valid, as the macOS +//! and Windows preloads assume for the calls they interpose, and are read and +//! written directly. Only addresses in the first page (`NULL` and small +//! integers) are rejected with `EFAULT` without being touched. +//! +//! Any other bad pointer crashes the process where the kernel would return +//! `EFAULT`, because `HANDLER_BLOCK_MASK` blocks `SIGSEGV` and `SIGBUS` while +//! the handler runs. No known program passes one to the syscalls handled +//! here; the one known address-probe idiom, Abseil's +//! `rt_sigprocmask(~0, addr, NULL, 8)`, is passed straight to the kernel +//! without reading `addr`. Copying through `process_vm_readv` instead would +//! cost two syscalls per copy and trip target filters that trap it, such as +//! Chromium's sandbox. + +use core::{mem::size_of, ptr, slice}; + +use fspy_nostd::{CStr, Error, Result, Thin}; + +/// Minimum valid user-space address (page 0 is never mapped on Linux). +const MIN_USER_ADDR: usize = 4096; + +#[inline] +fn check_range(addr: usize, len: usize) -> Result<()> { + if len == 0 { + return Ok(()); + } + if addr < MIN_USER_ADDR { + return Err(Error::FAULT); + } + addr.checked_add(len).ok_or(Error::FAULT)?; + Ok(()) +} + +/// Copies a `Copy` value of type `T` from user address `addr`, returning +/// [`Error::FAULT`] if `addr` is in the first page. +/// +/// # Safety +/// +/// `T` must be valid for any bit pattern (e.g. integers or `#[repr(C)]` kernel +/// UAPI structs of integers/raw pointers), and `addr` must be null, in the +/// first page, or readable for `size_of::()` bytes. +pub unsafe fn read_user(addr: usize) -> Result { + check_range(addr, size_of::())?; + // SAFETY: the caller guarantees `addr..addr + size_of::()` is readable. + Ok(unsafe { ptr::with_exposed_provenance::(addr).read_unaligned() }) +} + +/// Copies a `Copy` value of type `T` to user address `addr`, returning +/// [`Error::FAULT`] if `addr` is in the first page. +/// +/// # Safety +/// +/// `addr` must be null, in the first page, or writable for +/// `size_of::()` bytes. +pub unsafe fn write_user(addr: usize, value: &T) -> Result<()> { + // SAFETY: `value` is a valid initialized `T` of `size_of::()` bytes. + let bytes = unsafe { slice::from_raw_parts(ptr::from_ref(value).cast::(), size_of::()) }; + // SAFETY: forwarded from the caller contract. + unsafe { write_user_bytes(addr, bytes) } +} + +/// Copies `src` bytes to user address `addr`, returning [`Error::FAULT`] if +/// `addr` is in the first page. +/// +/// # Safety +/// +/// `addr` must be null, in the first page, or writable for `src.len()` +/// bytes that do not overlap `src`. +pub unsafe fn write_user_bytes(addr: usize, src: &[u8]) -> Result<()> { + check_range(addr, src.len())?; + // SAFETY: the caller guarantees `addr..addr + src.len()` is writable and + // disjoint from `src`. + unsafe { + ptr::copy_nonoverlapping(src.as_ptr(), ptr::with_exposed_provenance_mut(addr), src.len()); + } + Ok(()) +} + +/// Borrows a NUL-terminated C string directly from user address `addr`, +/// returning [`Error::FAULT`] if `addr` is in the first page (such as `NULL`). +/// +/// # Safety +/// +/// Any other `addr` must point to a readable NUL-terminated C string that +/// remains valid and unmodified for `'a`. +pub unsafe fn user_cstr<'a>(addr: usize) -> Result> { + if addr < MIN_USER_ADDR { + return Err(Error::FAULT); + } + // SAFETY: caller guarantees `addr` points to a readable NUL-terminated C + // string valid for `'a`. + Ok(unsafe { CStr::::from_ptr(ptr::with_exposed_provenance(addr)) }) +} diff --git a/crates/fspy_elf_loader_test_launcher/Cargo.toml b/crates/fspy_elf_loader_test_launcher/Cargo.toml index eadaf1072..3c74becc8 100644 --- a/crates/fspy_elf_loader_test_launcher/Cargo.toml +++ b/crates/fspy_elf_loader_test_launcher/Cargo.toml @@ -10,6 +10,7 @@ rust-version.workspace = true [target.'cfg(target_os = "none")'.dependencies] fspy_elf_loader = { path = "../fspy_elf_loader" } fspy_nostd = { workspace = true } +syscalls = { workspace = true } [[bin]] name = "fspy_elf_loader_test_launcher" diff --git a/crates/fspy_elf_loader_test_launcher/src/main.rs b/crates/fspy_elf_loader_test_launcher/src/main.rs index 29cde1486..87a52e269 100644 --- a/crates/fspy_elf_loader_test_launcher/src/main.rs +++ b/crates/fspy_elf_loader_test_launcher/src/main.rs @@ -6,31 +6,115 @@ const fn main() {} #[cfg(target_os = "none")] mod freestanding { + use fspy_elf_loader::{Syscall, SyscallAction, SyscallInterceptor}; use fspy_nostd::{ - CWD, + CWD, Error, Result, fs::{Mode, OFlags, openat}, }; + use syscalls::Sysno; fspy_nostd::main!(run); fspy_nostd::no_global_alloc!(); + const INTERCEPTOR_SHORT_CIRCUIT_ARG: usize = 0xdead_beef; + const INTERCEPTOR_REWRITE_PROBE_MODE: usize = 0x7777; + const INTERCEPTOR_EXEC_PROBE_ARGV: usize = 0x5555_1234; + + static TEST_INTERCEPTOR: SyscallInterceptor = SyscallInterceptor { + syscalls: &[Sysno::getegid, Sysno::faccessat, Sysno::execve, Sysno::execveat], + handle: test_handle, + }; + + /// Test interceptor exercising: + /// - `getegid(0xdead_beef)` -> short-circuits with `Err(Error::ACCES)` + /// - `getegid(_)` -> replays normally (`Ok(SyscallAction::Replay)`) + /// - `faccessat(_, path, 0x7777)` -> checks `/proc/self/exe` was rewritten + /// to an absolute non-`/proc/` path, returning `Err(Error::LOOP)` on + /// match or `Err(Error::NOENT)` on mismatch + /// - `execve(path, 0x5555_1234, _)` / `execveat(dirfd, path, 0x5555_1234, _, _)` + /// -> checks `/proc/self/exe` was rewritten to an absolute non-`/proc/` + /// path (and `dirfd == AT_FDCWD` for `execveat`) + unsafe fn test_handle(call: &Syscall) -> Result { + let check_rewritten_path = |path_ptr: usize| -> Result { + // SAFETY: `path_ptr` is the trapped syscall's path argument. + let Ok(cstr) = (unsafe { fspy_elf_loader::user_cstr(path_ptr) }) else { + return Err(Error::NOENT); + }; + let path = cstr.count().as_units(); + if path.starts_with(b"/") && !path.starts_with(b"/proc/") { + Err(Error::LOOP) + } else { + Err(Error::NOENT) + } + }; + + match call.sysno { + Sysno::getegid => { + if call.args[0] == INTERCEPTOR_SHORT_CIRCUIT_ARG { + return Err(Error::ACCES); + } + Ok(SyscallAction::Replay) + } + Sysno::faccessat => { + if call.args[2] == INTERCEPTOR_REWRITE_PROBE_MODE { + return check_rewritten_path(call.args[1]); + } + Ok(SyscallAction::Replay) + } + Sysno::execve => { + if call.args[1] == INTERCEPTOR_EXEC_PROBE_ARGV { + return check_rewritten_path(call.args[0]); + } + Ok(SyscallAction::Replay) + } + Sysno::execveat => { + if call.args[2] == INTERCEPTOR_EXEC_PROBE_ARGV { + #[expect( + clippy::cast_possible_truncation, + clippy::cast_possible_wrap, + reason = "Linux dirfd lives in low 32 bits" + )] + let dirfd = call.args[0] as i32; + if dirfd != CWD.as_raw_fd() { + return Err(Error::NOENT); + } + return check_rewritten_path(call.args[1]); + } + Ok(SyscallAction::Replay) + } + _ => Ok(SyscallAction::Replay), + } + } + // The kernel enters with argc, argv, envp, and auxv on the initial stack. // Consume those views before exec_elf replaces the stack. #[expect(clippy::needless_pass_by_value, reason = "signature required by main!")] fn run(stack: fspy_nostd::env::InitialStack<'_>) -> ! { - // Invocation: launcher ELF_PATH TARGET_ARGV0 [TARGET_ARGS...]. + // Invocation: launcher [--test-interceptor] ELF_PATH TARGET_ARGV0 [TARGET_ARGS...]. // The kernel supplied this stack for the launcher; exec_elf will build - // another one for the target, with the first two arguments removed. + // another one for the target, with the launcher arguments removed. let mut args = stack.args().iter().copied(); let _launcher = args.next().expect("missing launcher argv[0]"); - let path = args.next().expect("missing target path"); + let first = args.next().expect("missing target path"); + let (interceptor, path) = if first.count().as_units() == b"--test-interceptor" { + (Some(TEST_INTERCEPTOR), args.next().expect("missing target path")) + } else { + (None, first) + }; let file = openat(CWD, path, OFlags::RDONLY | OFlags::CLOEXEC, Mode::empty()) .expect("cannot open target"); // SAFETY: this is a fresh single-threaded freestanding process. The // parent selects a trusted fixture and kernel auxv references stay // valid until copied. There is no runtime requiring stack cleanup. unsafe { - fspy_elf_loader::exec_elf(file, path, args, stack.envs().iter().copied(), stack.auxv()) + fspy_elf_loader::exec_elf( + file, + path, + args, + stack.envs().iter().copied(), + stack.auxv(), + interceptor, + ) } } } diff --git a/crates/fspy_elf_loader_tests/build.rs b/crates/fspy_elf_loader_tests/build.rs index 994ad4197..0c2571dd7 100644 --- a/crates/fspy_elf_loader_tests/build.rs +++ b/crates/fspy_elf_loader_tests/build.rs @@ -9,6 +9,7 @@ fn main() { return; } println!("cargo::rerun-if-changed=fixtures/runtime.c"); + println!("cargo::rerun-if-changed=fixtures/virtualization.c"); println!("cargo::rerun-if-env-changed=CC"); let compiler = resolve_compiler(); @@ -17,8 +18,11 @@ fn main() { .is_some_and(|path| path.rsplit('/').next().is_some_and(|name| name.starts_with("zigcc-"))); let out = env::var_os("OUT_DIR").unwrap(); - let mut source = env::var_os("CARGO_MANIFEST_DIR").unwrap(); + let manifest_dir = env::var_os("CARGO_MANIFEST_DIR").unwrap(); + let mut source = manifest_dir.clone(); source.push("/fixtures/runtime.c"); + let mut virt_source = manifest_dir; + virt_source.push("/fixtures/virtualization.c"); // Compile the single C runtime fixture across all four ELF64 cells with // explicit PIE/non-PIE flags so GCC, Clang, and zig cc emit identical shapes. @@ -53,6 +57,24 @@ fn main() { } println!("cargo::rustc-env={env_name}={}", dest.to_str().unwrap()); } + + for (env_name, file_name, flags, is_static) in [ + ("FIXTURE_VIRT_DYN_PIE", "/fixture_virt_dyn_pie", &["-fPIE", "-pie"][..], false), + ( + "FIXTURE_VIRT_STATIC_EXEC", + "/fixture_virt_static_exec", + &["-fno-pie", "-static"][..], + true, + ), + ] { + let dest = join_out(&out, file_name); + if is_static && let Some(musl_target) = musl_target { + compile_zig_musl(musl_target, &virt_source, &dest, flags); + } else { + run_compile(Command::new(&compiler), &virt_source, &dest, flags); + } + println!("cargo::rustc-env={env_name}={}", dest.to_str().unwrap()); + } } fn resolve_compiler() -> OsString { diff --git a/crates/fspy_elf_loader_tests/fixtures/virtualization.c b/crates/fspy_elf_loader_tests/fixtures/virtualization.c new file mode 100644 index 000000000..d346e827f --- /dev/null +++ b/crates/fspy_elf_loader_tests/fixtures/virtualization.c @@ -0,0 +1,2669 @@ +/* Integration test fixture exercising freestanding SIGSYS virtualization, + * /proc/self/exe virtualization, PR_SET_NAME, RLIMIT_STACK, SyscallInterceptor, + * recursive re-exec without seccomp filter stacking, and target-installed + * SECCOMP_RET_TRAP forwarding under fspy_elf_loader. + * + * Subcommands (passed in argv[1]): + * sigaction - overwrite SIGSYS (SIG_IGN, custom, SA_SIGINFO, + * SA_RESETHAND, SIG_DFL), read oldact, verify sa_mask + * stripping and round-trip on SIGUSR1, and forward + * non-seccomp SIGSYS. + * sigsys-default-death - set SIGSYS to SIG_DFL and raise(SIGSYS); must die + * with signal SIGSYS. + * sigmask-single - sigprocmask (BLOCK/UNBLOCK/SETMASK/query), + * sigsuspend, ppoll, pselect, epoll_pwait, and + * epoll_pwait2 with SIGSYS in blocked masks. + * sigmask-threads - multi-threaded pthread_sigmask isolation, mask + * inheritance across pthread_create, concurrent + * masked waits, and /proc//task//exe. + * proc-exe - /proc/self/exe, /proc/thread-self/exe, + * /proc//exe, /proc//task//exe, + * /proc/self/task//exe, normalized paths, + * dirfd/cwd relative lookups, readlink/readlinkat + * edge cases, open/openat/openat2, stat/lstat/ + * fstatat/statx, access/faccessat/faccessat2, and + * non-matching path pass-through. + * comm - verifies /proc/self/comm matches EXPECTED_COMM. + * deep-stack - consumes >10 MiB of call stack to test RLIMIT_STACK. + * interceptor - exercises SyscallInterceptor replay, -errno + * short-circuit, and /proc/self/exe rewrite visibility + * across faccessat, execve, and execveat. + * recursive-exec - re-execs the launcher into self and asserts + * /proc/self/status Seccomp_filters count stays + * constant across recursive execs. + * nested-seccomp - installs target's own SIGSYS handler and + * SECCOMP_RET_TRAP filter (data=0) trapping getuid, + * verifying forwarding while loader traps keep working. + */ + +#define _GNU_SOURCE + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +extern char **environ; + +#ifndef AT_SYMLINK_NOFOLLOW +#define AT_SYMLINK_NOFOLLOW 0x100 +#endif + +#ifndef PR_SET_NO_NEW_PRIVS +#define PR_SET_NO_NEW_PRIVS 38 +#endif + +#ifndef SYS_SECCOMP +#define SYS_SECCOMP 1 +#endif + +struct raw_sock_filter { + uint16_t code; + uint8_t jt; + uint8_t jf; + uint32_t k; +}; + +struct raw_sock_fprog { + uint16_t len; + struct raw_sock_filter *filter; +}; + +struct raw_open_how { + uint64_t flags; + uint64_t mode; + uint64_t resolve; +}; + +struct raw_statx_timestamp { + int64_t tv_sec; + uint32_t tv_nsec; + int32_t __reserved; +}; + +struct raw_statx { + uint32_t stx_mask; + uint32_t stx_blksize; + uint64_t stx_attributes; + uint32_t stx_nlink; + uint32_t stx_uid; + uint32_t stx_gid; + uint16_t stx_mode; + uint16_t __spare0[1]; + uint64_t stx_ino; + uint64_t stx_size; + uint64_t stx_blocks; + uint64_t stx_attributes_mask; + struct raw_statx_timestamp stx_atime; + struct raw_statx_timestamp stx_btime; + struct raw_statx_timestamp stx_ctime; + struct raw_statx_timestamp stx_mtime; + uint32_t stx_rdev_major; + uint32_t stx_rdev_minor; + uint32_t stx_dev_major; + uint32_t stx_dev_minor; + uint64_t stx_mnt_id; + uint32_t stx_dio_mem_align; + uint32_t stx_dio_offset_align; + uint64_t __spare3[12]; +}; + +static void write_all(int fd, const char *buf, size_t len) { + while (len > 0) { + ssize_t n = write(fd, buf, len); + if (n <= 0) { + return; + } + buf += n; + len -= (size_t)n; + } +} + +static void fail(const char *msg) { + char buf[256]; + int n = snprintf(buf, sizeof buf, "FAIL: %s (errno=%d)\n", msg, errno); + if (n > 0) { + write_all(STDERR_FILENO, buf, (size_t)n); + } + _exit(2); +} + +static pid_t current_tid(void) { + return (pid_t)syscall(SYS_gettid); +} + +static const char *expected_exe_path(void) { + const char *p = getenv("EXPECTED_EXE"); + if (p == NULL || p[0] != '/') { + fail("missing EXPECTED_EXE"); + } + return p; +} + +static void assert_readlink_matches_expected(const char *path, const char *expected) { + char buf[PATH_MAX]; + ssize_t n = readlink(path, buf, sizeof buf - 1); + if (n < 0) { + fail(path); + } + buf[n] = '\0'; + if (strcmp(buf, expected) != 0) { + char msg[256]; + snprintf(msg, sizeof msg, "readlink mismatch for %s: got %s", path, buf); + fail(msg); + } +} + +/* ---- sigaction subcommand ---- */ + +static volatile sig_atomic_t g_sigsys_plain_count = 0; +static volatile sig_atomic_t g_sigsys_info_count = 0; +static volatile sig_atomic_t g_sigsys_info_code = 0; +static volatile sig_atomic_t g_sigusr1_count = 0; +static volatile sig_atomic_t g_handler_readlink_ok = 0; +static const char *g_expected_exe = NULL; + +static void check_readlink_in_handler(void) { + char buf[PATH_MAX]; + ssize_t n = readlink("/proc/self/exe", buf, sizeof buf - 1); + if (n > 0 && (size_t)n == strlen(g_expected_exe) && memcmp(buf, g_expected_exe, (size_t)n) == 0) { + g_handler_readlink_ok = 1; + } +} + +static void sigsys_plain_handler(int sig) { + if (sig == SIGSYS) { + g_sigsys_plain_count++; + check_readlink_in_handler(); + } +} + +static void sigsys_info_handler(int sig, siginfo_t *info, void *ucontext) { + (void)ucontext; + if (sig == SIGSYS) { + g_sigsys_info_count++; + g_sigsys_info_code = info != NULL ? info->si_code : -1; + check_readlink_in_handler(); + } +} + +static void sigusr1_handler(int sig) { + if (sig == SIGUSR1) { + g_sigusr1_count++; + /* Execute an intercepted syscall while SIGUSR1's sa_mask requested + * SIGSYS blocked (sigfillset). Must not die! */ + check_readlink_in_handler(); + } +} + +static int run_sigaction_test(void) { + struct sigaction act; + struct sigaction old; + g_expected_exe = expected_exe_path(); + + /* 1. Overwrite SIGSYS with SIG_IGN; oldact must be SIG_DFL. */ + memset(&act, 0, sizeof act); + act.sa_handler = SIG_IGN; + if (sigaction(SIGSYS, &act, &old) != 0) { + fail("sigaction SIG_IGN"); + } + if (old.sa_handler != SIG_DFL) { + fail("initial oldact was not SIG_DFL"); + } + /* Non-seccomp SIGSYS is now ignored, and intercepted syscalls still work. */ + if (raise(SIGSYS) != 0) { + fail("raise SIGSYS under SIG_IGN"); + } + assert_readlink_matches_expected("/proc/self/exe", g_expected_exe); + + /* 2. Install plain custom SIGSYS handler; oldact must be SIG_IGN. */ + memset(&act, 0, sizeof act); + act.sa_handler = sigsys_plain_handler; + sigemptyset(&act.sa_mask); + sigaddset(&act.sa_mask, SIGUSR2); + if (sigaction(SIGSYS, &act, &old) != 0) { + fail("sigaction plain custom"); + } + if (old.sa_handler != SIG_IGN) { + fail("oldact after SIG_IGN mismatch"); + } + g_handler_readlink_ok = 0; + if (raise(SIGSYS) != 0) { + fail("raise SIGSYS plain"); + } + if (g_sigsys_plain_count != 1 || !g_handler_readlink_ok) { + fail("plain SIGSYS handler did not run cleanly"); + } + assert_readlink_matches_expected("/proc/self/exe", g_expected_exe); + + /* 3. Install SA_SIGINFO | SA_RESETHAND handler; oldact must be plain handler. */ + memset(&act, 0, sizeof act); + act.sa_sigaction = sigsys_info_handler; + act.sa_flags = SA_SIGINFO | SA_RESETHAND; + sigemptyset(&act.sa_mask); + if (sigaction(SIGSYS, &act, &old) != 0) { + fail("sigaction SA_SIGINFO"); + } + if (old.sa_handler != sigsys_plain_handler) { + fail("oldact after plain handler mismatch"); + } + if (!sigismember(&old.sa_mask, SIGUSR2)) { + fail("oldact sa_mask did not preserve SIGUSR2"); + } + g_handler_readlink_ok = 0; + if (raise(SIGSYS) != 0) { + fail("raise SIGSYS info"); + } + if (g_sigsys_info_count != 1 || g_sigsys_info_code == SYS_SECCOMP || !g_handler_readlink_ok) { + fail("SA_SIGINFO SIGSYS handler did not run cleanly"); + } + + /* Because SA_RESETHAND was set, querying SIGSYS must now report SIG_DFL, + * while intercepted syscalls still keep working. */ + memset(&old, 0, sizeof old); + if (sigaction(SIGSYS, NULL, &old) != 0) { + fail("sigaction query after SA_RESETHAND"); + } + if (old.sa_handler != SIG_DFL) { + fail("SA_RESETHAND did not reset virtualized SIGSYS to SIG_DFL"); + } + assert_readlink_matches_expected("/proc/self/exe", g_expected_exe); + + /* 4. Explicitly set SIG_DFL and verify intercepted syscalls still work. */ + memset(&act, 0, sizeof act); + act.sa_handler = SIG_DFL; + if (sigaction(SIGSYS, &act, &old) != 0) { + fail("sigaction SIG_DFL"); + } + if (old.sa_handler != SIG_DFL) { + fail("oldact before explicit SIG_DFL mismatch"); + } + assert_readlink_matches_expected("/proc/self/exe", g_expected_exe); + + /* 5. Install SIGUSR1 with sigfillset(&sa_mask) (includes SIGSYS). + * Inside SIGUSR1 handler, execute intercepted syscall; also verify oldact + * round-trips SIGSYS in sa_mask. */ + memset(&act, 0, sizeof act); + act.sa_handler = sigusr1_handler; + sigfillset(&act.sa_mask); + if (sigaction(SIGUSR1, &act, NULL) != 0) { + fail("sigaction SIGUSR1"); + } + g_handler_readlink_ok = 0; + if (raise(SIGUSR1) != 0) { + fail("raise SIGUSR1"); + } + if (g_sigusr1_count != 1 || !g_handler_readlink_ok) { + fail("SIGUSR1 handler failed with SIGSYS in sa_mask"); + } + memset(&old, 0, sizeof old); + if (sigaction(SIGUSR1, NULL, &old) != 0) { + fail("sigaction query SIGUSR1"); + } + if (!sigismember(&old.sa_mask, SIGSYS)) { + fail("SIGUSR1 oldact.sa_mask lost SIGSYS"); + } + + write_all(STDOUT_FILENO, "sigaction-ok\n", 13); + return 0; +} + +static int run_sigsys_default_death(void) { + /* Suppress core dumps so the expected SIGSYS death finishes immediately. */ + struct rlimit zero = {0, 0}; + (void)setrlimit(RLIMIT_CORE, &zero); + + struct sigaction act; + memset(&act, 0, sizeof act); + act.sa_handler = SIG_DFL; + if (sigaction(SIGSYS, &act, NULL) != 0) { + fail("sigaction SIG_DFL"); + } + raise(SIGSYS); + fail("raise(SIGSYS) with SIG_DFL returned"); + return 1; +} + +/* ---- sigmask-single subcommand ---- */ + +struct signal_sender_arg { + pthread_t target; + int ready_fd; +}; + +static void *send_sigusr1_thread(void *raw) { + struct signal_sender_arg *arg = (struct signal_sender_arg *)raw; + char ch = 0; + if (read(arg->ready_fd, &ch, 1) != 1) { + fail("sender read"); + } + for (int i = 0; i < 200; i++) { + if (g_sigusr1_count > 0) { + break; + } + pthread_kill(arg->target, SIGUSR1); + struct timespec ts = {0, 2 * 1000 * 1000}; + nanosleep(&ts, NULL); + } + return NULL; +} + +static int run_sigmask_single_test(void) { + sigset_t set, old, cur, full; + g_expected_exe = expected_exe_path(); + + /* 1. sigprocmask BLOCK / query / UNBLOCK / SETMASK */ + sigemptyset(&set); + sigaddset(&set, SIGSYS); + if (sigprocmask(SIG_BLOCK, &set, &old) != 0) { + fail("sigprocmask SIG_BLOCK"); + } + if (sigismember(&old, SIGSYS) != 0) { + fail("SIGSYS initially blocked"); + } + assert_readlink_matches_expected("/proc/self/exe", g_expected_exe); + + sigemptyset(&cur); + if (sigprocmask(SIG_SETMASK, NULL, &cur) != 0) { + fail("sigprocmask query after BLOCK"); + } + if (sigismember(&cur, SIGSYS) != 1) { + fail("SIGSYS not reported blocked after SIG_BLOCK"); + } + + if (sigprocmask(SIG_UNBLOCK, &set, &old) != 0) { + fail("sigprocmask SIG_UNBLOCK"); + } + if (sigismember(&old, SIGSYS) != 1) { + fail("oldset did not report SIGSYS before UNBLOCK"); + } + if (sigprocmask(SIG_SETMASK, NULL, &cur) != 0) { + fail("sigprocmask query after UNBLOCK"); + } + if (sigismember(&cur, SIGSYS) != 0) { + fail("SIGSYS still reported blocked after UNBLOCK"); + } + + sigfillset(&full); + if (sigprocmask(SIG_SETMASK, &full, &old) != 0) { + fail("sigprocmask SIG_SETMASK full"); + } + assert_readlink_matches_expected("/proc/self/exe", g_expected_exe); + if (sigprocmask(SIG_SETMASK, NULL, &cur) != 0) { + fail("sigprocmask query after SETMASK full"); + } + if (sigismember(&cur, SIGSYS) != 1) { + fail("SIGSYS not reported blocked after SETMASK full"); + } + sigemptyset(&set); + if (sigprocmask(SIG_SETMASK, &set, &old) != 0) { + fail("sigprocmask clear"); + } + if (sigismember(&old, SIGSYS) != 1) { + fail("oldset lost SIGSYS before clear"); + } + + /* 1b. Non-SIGSYS signals blocked via sigprocmask must persist after + * rt_sigreturn and actually defer delivery until unblocked; also verify + * set == oldset aliasing. */ + { + struct sigaction sa_u1; + memset(&sa_u1, 0, sizeof sa_u1); + sa_u1.sa_handler = sigusr1_handler; + sigemptyset(&sa_u1.sa_mask); + if (sigaction(SIGUSR1, &sa_u1, NULL) != 0) { + fail("sigaction SIGUSR1 for persist test"); + } + g_sigusr1_count = 0; + + sigemptyset(&set); + sigaddset(&set, SIGUSR1); + if (sigprocmask(SIG_BLOCK, &set, NULL) != 0) { + fail("sigprocmask block SIGUSR1"); + } + sigemptyset(&cur); + if (sigprocmask(SIG_SETMASK, NULL, &cur) != 0 || sigismember(&cur, SIGUSR1) != 1) { + fail("SIGUSR1 block did not persist after rt_sigreturn"); + } + if (raise(SIGUSR1) != 0) { + fail("raise blocked SIGUSR1"); + } + if (g_sigusr1_count != 0) { + fail("SIGUSR1 was delivered while blocked"); + } + + /* Aliasing: set == oldset when adding SIGUSR2 must return old mask + * (SIGUSR1 set, SIGUSR2 clear) while leaving both blocked. */ + sigset_t alias; + sigemptyset(&alias); + sigaddset(&alias, SIGUSR2); + if (sigprocmask(SIG_BLOCK, &alias, &alias) != 0) { + fail("sigprocmask aliasing block"); + } + if (sigismember(&alias, SIGUSR1) != 1 || sigismember(&alias, SIGUSR2) != 0) { + fail("sigprocmask aliasing returned wrong oldset"); + } + sigemptyset(&cur); + if (sigprocmask(SIG_SETMASK, NULL, &cur) != 0 + || sigismember(&cur, SIGUSR1) != 1 + || sigismember(&cur, SIGUSR2) != 1) { + fail("sigprocmask aliasing did not apply new mask"); + } + + sigemptyset(&set); + sigaddset(&set, SIGUSR1); + sigaddset(&set, SIGUSR2); + if (sigprocmask(SIG_UNBLOCK, &set, NULL) != 0) { + fail("sigprocmask unblock SIGUSR1+SIGUSR2"); + } + if (g_sigusr1_count != 1) { + fail("pending SIGUSR1 was not delivered upon unblock"); + } + } + + /* 2. sigsuspend with SIGSYS in wait mask, interrupted by SIGUSR1 whose + * handler runs an intercepted syscall. */ + struct sigaction sa; + memset(&sa, 0, sizeof sa); + sa.sa_handler = sigusr1_handler; + sigfillset(&sa.sa_mask); + if (sigaction(SIGUSR1, &sa, NULL) != 0) { + fail("sigaction SIGUSR1 for sigsuspend"); + } + sigemptyset(&set); + sigaddset(&set, SIGUSR1); + if (sigprocmask(SIG_BLOCK, &set, NULL) != 0) { + fail("block SIGUSR1"); + } + + int ready_pipe[2]; + if (pipe(ready_pipe) != 0) { + fail("pipe for sigsuspend"); + } + g_sigusr1_count = 0; + g_handler_readlink_ok = 0; + struct signal_sender_arg sarg = {pthread_self(), ready_pipe[0]}; + pthread_t sender; + if (pthread_create(&sender, NULL, send_sigusr1_thread, &sarg) != 0) { + fail("pthread_create sender"); + } + char go = 'g'; + if (write(ready_pipe[1], &go, 1) != 1) { + fail("write go"); + } + sigset_t suspend_mask; + sigfillset(&suspend_mask); + sigdelset(&suspend_mask, SIGUSR1); + errno = 0; + if (sigsuspend(&suspend_mask) != -1 || errno != EINTR) { + fail("sigsuspend did not return EINTR"); + } + pthread_join(sender, NULL); + close(ready_pipe[0]); + close(ready_pipe[1]); + if (g_sigusr1_count == 0 || !g_handler_readlink_ok) { + fail("SIGUSR1 handler failed during sigsuspend"); + } + sigemptyset(&set); + if (sigprocmask(SIG_SETMASK, &set, NULL) != 0) { + fail("unblock after sigsuspend"); + } + + /* 3. ppoll with sigfillset (contains SIGSYS) on ready pipe + timeout */ + int pfd[2]; + if (pipe(pfd) != 0) { + fail("pipe for ppoll"); + } + if (write(pfd[1], "x", 1) != 1) { + fail("write pipe"); + } + struct pollfd poll_fd = {.fd = pfd[0], .events = POLLIN, .revents = 0}; + struct timespec tmo = {0, 10 * 1000 * 1000}; + sigfillset(&full); + if (ppoll(&poll_fd, 1, &tmo, &full) != 1 || (poll_fd.revents & POLLIN) == 0) { + fail("ppoll ready with full sigmask"); + } + assert_readlink_matches_expected("/proc/self/exe", g_expected_exe); + + /* 4. pselect (pselect6) with sigfillset (contains SIGSYS) */ + fd_set rfds; + FD_ZERO(&rfds); + FD_SET(pfd[0], &rfds); + if (pselect(pfd[0] + 1, &rfds, NULL, NULL, &tmo, &full) != 1 || !FD_ISSET(pfd[0], &rfds)) { + fail("pselect with full sigmask"); + } + assert_readlink_matches_expected("/proc/self/exe", g_expected_exe); + + /* 5. epoll_pwait (and epoll_pwait2 if supported) with sigfillset */ + int epfd = epoll_create1(EPOLL_CLOEXEC); + if (epfd < 0) { + fail("epoll_create1"); + } + struct epoll_event ev; + ev.events = EPOLLIN; + ev.data.fd = pfd[0]; + if (epoll_ctl(epfd, EPOLL_CTL_ADD, pfd[0], &ev) != 0) { + fail("epoll_ctl"); + } + struct epoll_event out_ev; + if (epoll_pwait(epfd, &out_ev, 1, 100, &full) != 1 || out_ev.data.fd != pfd[0]) { + fail("epoll_pwait with full sigmask"); + } +#ifdef SYS_epoll_pwait2 + { + uint64_t raw_full = ~UINT64_C(0); + long rc = syscall(SYS_epoll_pwait2, epfd, &out_ev, 1, &tmo, &raw_full, sizeof raw_full); + if (rc == -1 && errno == ENOSYS) { + /* Older kernel without epoll_pwait2; skip cleanly. */ + } else if (rc != 1 || out_ev.data.fd != pfd[0]) { + fail("epoll_pwait2 with full sigmask"); + } + } +#endif + assert_readlink_matches_expected("/proc/self/exe", g_expected_exe); + + close(epfd); + close(pfd[0]); + close(pfd[1]); + write_all(STDOUT_FILENO, "sigmask-single-ok\n", 18); + return 0; +} + +/* ---- sigmask-threads subcommand ---- */ + +struct worker_arg { + int id; + int block_sigsys; + pthread_barrier_t *barrier; +}; + +static void *child_inherits_mask_fn(void *unused) { + (void)unused; + sigset_t cur; + sigemptyset(&cur); + if (pthread_sigmask(SIG_SETMASK, NULL, &cur) != 0) { + fail("child query mask"); + } + if (sigismember(&cur, SIGSYS) != 1) { + fail("child thread did not inherit blocked SIGSYS"); + } + assert_readlink_matches_expected("/proc/self/exe", g_expected_exe); + + sigset_t only; + sigemptyset(&only); + sigaddset(&only, SIGSYS); + if (pthread_sigmask(SIG_UNBLOCK, &only, NULL) != 0) { + fail("child unblock SIGSYS"); + } + if (pthread_sigmask(SIG_SETMASK, NULL, &cur) != 0 || sigismember(&cur, SIGSYS) != 0) { + fail("child SIGSYS still blocked after unblock"); + } + return NULL; +} + +static void *worker_thread_fn(void *raw) { + struct worker_arg *arg = (struct worker_arg *)raw; + sigset_t set, cur, full; + char path[128]; + + if (arg->block_sigsys) { + sigemptyset(&set); + sigaddset(&set, SIGSYS); + if (pthread_sigmask(SIG_BLOCK, &set, NULL) != 0) { + fail("worker pthread_sigmask block"); + } + } + + pthread_barrier_wait(arg->barrier); + + sigemptyset(&cur); + if (pthread_sigmask(SIG_SETMASK, NULL, &cur) != 0) { + fail("worker query mask"); + } + if (sigismember(&cur, SIGSYS) != arg->block_sigsys) { + fail("worker SIGSYS virtualized mask isolation broken"); + } + + assert_readlink_matches_expected("/proc/self/exe", g_expected_exe); + assert_readlink_matches_expected("/proc/thread-self/exe", g_expected_exe); + snprintf(path, sizeof path, "/proc/%d/task/%d/exe", (int)getpid(), (int)current_tid()); + assert_readlink_matches_expected(path, g_expected_exe); + + sigfillset(&full); + struct timespec zero = {0, 0}; + if (ppoll(NULL, 0, &zero, &full) != 0) { + fail("worker ppoll"); + } + + if (arg->block_sigsys && arg->id == 0) { + pthread_t child; + if (pthread_create(&child, NULL, child_inherits_mask_fn, NULL) != 0) { + fail("grandchild pthread_create"); + } + pthread_join(child, NULL); + if (pthread_sigmask(SIG_SETMASK, NULL, &cur) != 0 || sigismember(&cur, SIGSYS) != 1) { + fail("parent lost blocked SIGSYS after child unblocked"); + } + } + + pthread_barrier_wait(arg->barrier); + + if (arg->block_sigsys) { + sigemptyset(&set); + sigaddset(&set, SIGSYS); + if (pthread_sigmask(SIG_UNBLOCK, &set, NULL) != 0) { + fail("worker unblock"); + } + } + return NULL; +} + +static int run_sigmask_threads_test(void) { + enum { NUM_WORKERS = 4 }; + pthread_t threads[NUM_WORKERS]; + struct worker_arg args[NUM_WORKERS]; + pthread_barrier_t barrier; + + g_expected_exe = expected_exe_path(); + if (pthread_barrier_init(&barrier, NULL, NUM_WORKERS) != 0) { + fail("pthread_barrier_init"); + } + for (int i = 0; i < NUM_WORKERS; i++) { + args[i].id = i; + args[i].block_sigsys = (i % 2 == 0) ? 1 : 0; + args[i].barrier = &barrier; + if (pthread_create(&threads[i], NULL, worker_thread_fn, &args[i]) != 0) { + fail("pthread_create worker"); + } + } + for (int i = 0; i < NUM_WORKERS; i++) { + if (pthread_join(threads[i], NULL) != 0) { + fail("pthread_join worker"); + } + } + pthread_barrier_destroy(&barrier); + + sigset_t cur; + if (pthread_sigmask(SIG_SETMASK, NULL, &cur) != 0 || sigismember(&cur, SIGSYS) != 0) { + fail("main thread SIGSYS mask polluted"); + } + + write_all(STDOUT_FILENO, "sigmask-threads-ok\n", 19); + return 0; +} + +/* ---- proc-exe subcommand ---- */ + +struct sibling_tid_arg { + pid_t tid; + pthread_barrier_t *barrier; +}; + +static void *sibling_tid_fn(void *raw) { + struct sibling_tid_arg *arg = (struct sibling_tid_arg *)raw; + arg->tid = current_tid(); + pthread_barrier_wait(arg->barrier); + pthread_barrier_wait(arg->barrier); + return NULL; +} + +static void assert_open_matches_file(int fd, const struct stat *expected_st, const unsigned char expected_hdr[64]) { + if (fd < 0) { + fail("open proc exe failed"); + } + struct stat st; + if (fstat(fd, &st) != 0) { + fail("fstat opened proc exe"); + } + if (st.st_dev != expected_st->st_dev || st.st_ino != expected_st->st_ino || st.st_size != expected_st->st_size) { + fail("opened proc exe stat mismatch"); + } + unsigned char hdr[64]; + ssize_t n = read(fd, hdr, sizeof hdr); + if (n != (ssize_t)sizeof hdr || memcmp(hdr, expected_hdr, sizeof hdr) != 0) { + fail("opened proc exe bytes mismatch"); + } + close(fd); +} + +static int run_proc_exe_test(void) { + const char *expected = expected_exe_path(); + size_t expected_len = strlen(expected); + pid_t pid = getpid(); + pid_t tid = current_tid(); + + struct stat expected_st; + if (stat(expected, &expected_st) != 0) { + fail("stat EXPECTED_EXE"); + } + unsigned char expected_hdr[64]; + { + int efd = open(expected, O_RDONLY | O_CLOEXEC); + if (efd < 0 || read(efd, expected_hdr, sizeof expected_hdr) != (ssize_t)sizeof expected_hdr) { + fail("read EXPECTED_EXE header"); + } + close(efd); + } + + /* 1. Absolute path variants (including sibling thread TID) */ + pthread_barrier_t barrier; + pthread_barrier_init(&barrier, NULL, 2); + struct sibling_tid_arg sarg = {0, &barrier}; + pthread_t sib; + if (pthread_create(&sib, NULL, sibling_tid_fn, &sarg) != 0) { + fail("pthread_create sibling"); + } + pthread_barrier_wait(&barrier); + + char pid_exe[128]; + char task_self_exe[128]; + char task_sib_exe[128]; + char self_task_sib_exe[128]; + snprintf(pid_exe, sizeof pid_exe, "/proc/%d/exe", (int)pid); + snprintf(task_self_exe, sizeof task_self_exe, "/proc/%d/task/%d/exe", (int)pid, (int)tid); + snprintf(task_sib_exe, sizeof task_sib_exe, "/proc/%d/task/%d/exe", (int)pid, (int)sarg.tid); + snprintf(self_task_sib_exe, sizeof self_task_sib_exe, "/proc/self/task/%d/exe", (int)sarg.tid); + + const char *variants[] = { + "/proc/self/exe", + "/proc/thread-self/exe", + pid_exe, + task_self_exe, + task_sib_exe, + self_task_sib_exe, + "//proc///self/./exe", + "/proc/self/../self/exe", + }; + + for (size_t i = 0; i < sizeof variants / sizeof variants[0]; i++) { + const char *p = variants[i]; + assert_readlink_matches_expected(p, expected); + + assert_open_matches_file(openat(AT_FDCWD, p, O_RDONLY | O_CLOEXEC), &expected_st, expected_hdr); +#ifdef SYS_open + assert_open_matches_file((int)syscall(SYS_open, p, O_RDONLY | O_CLOEXEC, 0), &expected_st, expected_hdr); +#endif +#ifdef SYS_openat2 + { + struct raw_open_how how = {O_RDONLY | O_CLOEXEC, 0, 0}; + long fd = syscall(SYS_openat2, AT_FDCWD, p, &how, sizeof how); + if (fd < 0 && errno == ENOSYS) { + /* Older kernel; skip cleanly. */ + } else { + assert_open_matches_file((int)fd, &expected_st, expected_hdr); + } + } +#endif + + struct stat st; + if (stat(p, &st) != 0 || !S_ISREG(st.st_mode) || st.st_ino != expected_st.st_ino || st.st_size != expected_st.st_size) { + fail("stat follow mismatch"); + } + if (fstatat(AT_FDCWD, p, &st, 0) != 0 || st.st_ino != expected_st.st_ino) { + fail("fstatat follow mismatch"); + } + + struct stat lst; + if (lstat(p, &lst) != 0 || !S_ISLNK(lst.st_mode)) { + fail("lstat did not report S_IFLNK"); + } + if (fstatat(AT_FDCWD, p, &lst, AT_SYMLINK_NOFOLLOW) != 0 || !S_ISLNK(lst.st_mode)) { + fail("fstatat NOFOLLOW did not report S_IFLNK"); + } + +#ifdef SYS_statx + { + struct raw_statx stx; + memset(&stx, 0, sizeof stx); + if (syscall(SYS_statx, AT_FDCWD, p, 0, 0x7ffU, &stx) != 0) { + fail("statx follow"); + } + if (!S_ISREG(stx.stx_mode) || stx.stx_ino != expected_st.st_ino || stx.stx_size != (uint64_t)expected_st.st_size) { + fail("statx follow mismatch"); + } + memset(&stx, 0, sizeof stx); + if (syscall(SYS_statx, AT_FDCWD, p, AT_SYMLINK_NOFOLLOW, 0x7ffU, &stx) != 0) { + fail("statx nofollow"); + } + if (!S_ISLNK(stx.stx_mode)) { + fail("statx nofollow did not report S_IFLNK"); + } + } +#endif + + if (access(p, R_OK | X_OK) != 0) { + fail("access"); + } + if (faccessat(AT_FDCWD, p, R_OK, 0) != 0) { + fail("faccessat"); + } +#ifdef SYS_faccessat2 + { + long rc = syscall(SYS_faccessat2, AT_FDCWD, p, R_OK, 0); + if (rc != 0 && errno != ENOSYS) { + fail("faccessat2"); + } + } +#endif + } + + pthread_barrier_wait(&barrier); + pthread_join(sib, NULL); + pthread_barrier_destroy(&barrier); + + /* 2. readlink / readlinkat edge cases: no NUL, truncation, bufsiz <= 0 */ + { + unsigned char buf[PATH_MAX]; + memset(buf, 0xAA, sizeof buf); + ssize_t n = readlinkat(AT_FDCWD, "/proc/self/exe", (char *)buf, sizeof buf); + if (n != (ssize_t)expected_len) { + fail("readlinkat full length"); + } + if (memcmp(buf, expected, expected_len) != 0 || buf[expected_len] != 0xAA) { + fail("readlinkat content or NUL overwrite"); + } + + memset(buf, 0xBB, 16); + n = readlinkat(AT_FDCWD, "/proc/self/exe", (char *)buf, 5); + if (n != 5 || memcmp(buf, expected, 5) != 0 || buf[5] != 0xBB) { + fail("readlinkat truncation to 5"); + } + + memset(buf, 0xCC, 16); + n = readlinkat(AT_FDCWD, "/proc/self/exe", (char *)buf, 1); + if (n != 1 || buf[0] != (unsigned char)expected[0] || buf[1] != 0xCC) { + fail("readlinkat truncation to 1"); + } + + errno = 0; + if (syscall(SYS_readlinkat, AT_FDCWD, "/proc/self/exe", buf, 0) != -1 || errno != EINVAL) { + fail("readlinkat bufsiz=0 did not return EINVAL"); + } + errno = 0; + if (syscall(SYS_readlinkat, AT_FDCWD, "/proc/self/exe", buf, -1) != -1 || errno != EINVAL) { + fail("readlinkat bufsiz=-1 did not return EINVAL"); + } +#ifdef SYS_readlink + memset(buf, 0xDD, 16); + n = (ssize_t)syscall(SYS_readlink, "/proc/self/exe", buf, 4); + if (n != 4 || memcmp(buf, expected, 4) != 0 || buf[4] != 0xDD) { + fail("SYS_readlink truncation"); + } + errno = 0; + if (syscall(SYS_readlink, "/proc/self/exe", buf, 0) != -1 || errno != EINVAL) { + fail("SYS_readlink bufsiz=0"); + } +#endif + } + + /* 3. openat with O_NOFOLLOW must preserve ELOOP on the symlink */ + errno = 0; + if (openat(AT_FDCWD, "/proc/self/exe", O_RDONLY | O_NOFOLLOW) != -1 || errno != ELOOP) { + fail("openat O_NOFOLLOW did not return ELOOP"); + } + + /* 4. Relative lookups via dirfd (/proc/self, /proc, /proc/) */ + { + int d_self = open("/proc/self", O_RDONLY | O_DIRECTORY | O_CLOEXEC); + int d_proc = open("/proc", O_RDONLY | O_DIRECTORY | O_CLOEXEC); + char pid_dir[64]; + snprintf(pid_dir, sizeof pid_dir, "/proc/%d", (int)pid); + int d_pid = open(pid_dir, O_RDONLY | O_DIRECTORY | O_CLOEXEC); + if (d_self < 0 || d_proc < 0 || d_pid < 0) { + fail("open proc dirfds"); + } + + char buf[PATH_MAX]; + ssize_t n = readlinkat(d_self, "exe", buf, sizeof buf - 1); + if (n < 0 || (buf[n] = '\0', strcmp(buf, expected) != 0)) { + fail("readlinkat(d_self, exe)"); + } + n = readlinkat(d_proc, "self/exe", buf, sizeof buf - 1); + if (n < 0 || (buf[n] = '\0', strcmp(buf, expected) != 0)) { + fail("readlinkat(d_proc, self/exe)"); + } + n = readlinkat(d_pid, "exe", buf, sizeof buf - 1); + if (n < 0 || (buf[n] = '\0', strcmp(buf, expected) != 0)) { + fail("readlinkat(d_pid, exe)"); + } + + assert_open_matches_file(openat(d_self, "exe", O_RDONLY | O_CLOEXEC), &expected_st, expected_hdr); + struct stat st; + if (fstatat(d_self, "exe", &st, 0) != 0 || st.st_ino != expected_st.st_ino) { + fail("fstatat(d_self, exe)"); + } + if (faccessat(d_self, "exe", R_OK, 0) != 0) { + fail("faccessat(d_self, exe)"); + } + + close(d_self); + close(d_proc); + close(d_pid); + } + + /* 5. Relative lookups via cwd = /proc/self */ + { + char saved_cwd[PATH_MAX]; + if (getcwd(saved_cwd, sizeof saved_cwd) == NULL) { + fail("getcwd"); + } + if (chdir("/proc/self") != 0) { + fail("chdir /proc/self"); + } + assert_readlink_matches_expected("exe", expected); + assert_open_matches_file(open("exe", O_RDONLY | O_CLOEXEC), &expected_st, expected_hdr); + struct stat st; + if (stat("exe", &st) != 0 || st.st_ino != expected_st.st_ino) { + fail("stat cwd exe"); + } + if (chdir(saved_cwd) != 0) { + fail("restore cwd"); + } + } + + /* 6. realpath("/proc/self/exe") matches expected canonical path */ + { + char resolved[PATH_MAX]; + if (realpath("/proc/self/exe", resolved) == NULL || strcmp(resolved, expected) != 0) { + fail("realpath(/proc/self/exe)"); + } + } + + /* 7. Unrelated file/symlink named `exe` must NOT be virtualized */ + { + const char *other_exe = getenv("OTHER_EXE_LINK"); + if (other_exe != NULL) { + char buf[PATH_MAX]; + ssize_t n = readlink(other_exe, buf, sizeof buf - 1); + if (n < 0 || (buf[n] = '\0', strcmp(buf, "/dev/null") != 0)) { + fail("unrelated exe symlink was wrongly virtualized"); + } + } + } + + write_all(STDOUT_FILENO, "proc-exe-ok\n", 12); + return 0; +} + +/* ---- comm subcommand (PR_SET_NAME) ---- */ + +static int run_comm_test(void) { + const char *expected = getenv("EXPECTED_COMM"); + if (expected == NULL) { + fail("missing EXPECTED_COMM"); + } + int fd = open("/proc/self/comm", O_RDONLY | O_CLOEXEC); + if (fd < 0) { + fail("open /proc/self/comm"); + } + char buf[64]; + ssize_t n = read(fd, buf, sizeof buf - 1); + close(fd); + if (n <= 0) { + fail("read /proc/self/comm"); + } + while (n > 0 && buf[n - 1] == '\n') { + n--; + } + buf[n] = '\0'; + if (strcmp(buf, expected) != 0) { + char msg[256]; + snprintf(msg, sizeof msg, "/proc/self/comm mismatch: got '%s', expected '%s'", buf, expected); + fail(msg); + } + write_all(STDOUT_FILENO, "comm-ok\n", 8); + return 0; +} + +/* ---- deep-stack subcommand (RLIMIT_STACK > 8 MiB) ---- */ + +__attribute__((noinline)) +static uint64_t touch_deep_stack(int depth) { + volatile unsigned char frame[65536]; + frame[0] = (unsigned char)(depth & 0xff); + frame[sizeof frame - 1] = (unsigned char)((depth * 7) & 0xff); + uint64_t acc = (uint64_t)frame[0] + (uint64_t)frame[sizeof frame - 1]; + if (depth > 1) { + acc += touch_deep_stack(depth - 1); + } + return acc; +} + +static int run_deep_stack_test(void) { + /* 160 frames * 64 KiB = 10 MiB (> default 8 MiB fixed stack, fits in 16 MiB). */ + uint64_t sum = touch_deep_stack(160); + if (sum == 0) { + fail("unexpected zero deep-stack checksum"); + } + write_all(STDOUT_FILENO, "deep-stack-ok\n", 14); + return 0; +} + +/* ---- interceptor subcommand ---- */ + +static int run_interceptor_test(void) { + const char *expected = expected_exe_path(); + assert_readlink_matches_expected("/proc/self/exe", expected); + + /* 1. Ok(()) replays custom trapped syscall `getegid`. */ + gid_t egid_normal = (gid_t)syscall(SYS_getegid, 0UL); + if (egid_normal != getegid()) { + fail("intercepted getegid replay mismatch"); + } + + /* 2. Err(ACCES) short-circuits with -EACCES without replaying. */ + errno = 0; + if (syscall(SYS_getegid, 0xdeadbeefUL) != -1 || errno != EACCES) { + fail("intercepted getegid short-circuit did not return EACCES"); + } + + /* 3. /proc/self/exe rewrite is visible to interceptor on faccessat. */ + errno = 0; + if (syscall(SYS_faccessat, AT_FDCWD, "/proc/self/exe", 0x7777UL) != -1 || errno != ELOOP) { + fail("interceptor did not observe rewritten /proc/self/exe on faccessat"); + } + if (syscall(SYS_faccessat, AT_FDCWD, "/proc/self/exe", R_OK) != 0) { + fail("normal faccessat(/proc/self/exe) failed under interceptor"); + } + + /* 4. /proc/self/exe rewrite is visible to interceptor on execve & execveat. */ + errno = 0; + if (syscall(SYS_execve, "/proc/self/exe", (void *)0x55551234UL, NULL) != -1 || errno != ELOOP) { + fail("interceptor did not observe rewritten /proc/self/exe on execve"); + } + errno = 0; + if (syscall(SYS_execveat, AT_FDCWD, "/proc/self/exe", (void *)0x55551234UL, NULL, 0) != -1 || errno != ELOOP) { + fail("interceptor did not observe rewritten /proc/self/exe on execveat"); + } + int d_self = open("/proc/self", O_RDONLY | O_DIRECTORY | O_CLOEXEC); + if (d_self < 0) { + fail("open /proc/self for execveat"); + } + errno = 0; + if (syscall(SYS_execveat, d_self, "exe", (void *)0x55551234UL, NULL, 0) != -1 || errno != ELOOP) { + close(d_self); + fail("interceptor did not observe rewritten dirfd /proc/self/exe on execveat"); + } + close(d_self); + + write_all(STDOUT_FILENO, "interceptor-ok\n", 15); + return 0; +} + +/* ---- recursive-exec subcommand (no seccomp filter stacking) ---- */ + +static int read_seccomp_filter_count(void) { + int fd = open("/proc/self/status", O_RDONLY | O_CLOEXEC); + if (fd < 0) { + fail("open /proc/self/status"); + } + char buf[8192]; + ssize_t n = read(fd, buf, sizeof buf - 1); + close(fd); + if (n <= 0) { + fail("read /proc/self/status"); + } + buf[n] = '\0'; + const char *needle = "Seccomp_filters:\t"; + const char *p = strstr(buf, needle); + if (p == NULL) { + fail("Seccomp_filters field missing in /proc/self/status"); + } + return atoi(p + strlen(needle)); +} + +static int run_recursive_exec_test(void) { + const char *expected = expected_exe_path(); + const char *stage = getenv("RECURSIVE_STAGE"); + if (stage == NULL) { + fail("missing RECURSIVE_STAGE"); + } + int count = read_seccomp_filter_count(); + if (count < 1) { + fail("expected at least 1 seccomp filter"); + } + assert_readlink_matches_expected("/proc/self/exe", expected); + + if (strcmp(stage, "1") == 0) { + const char *launcher = getenv("LAUNCHER_PATH"); + if (launcher == NULL) { + fail("missing LAUNCHER_PATH"); + } + char count_str[32]; + snprintf(count_str, sizeof count_str, "%d", count); + setenv("PARENT_SECCOMP_FILTERS", count_str, 1); + setenv("RECURSIVE_STAGE", "2", 1); + + /* Block SIGUSR2 before execv; child must inherit it blocked. */ + sigset_t block_u2; + sigemptyset(&block_u2); + sigaddset(&block_u2, SIGUSR2); + if (sigprocmask(SIG_BLOCK, &block_u2, NULL) != 0) { + fail("recursive exec block SIGUSR2"); + } + + const char *use_interceptor = getenv("USE_INTERCEPTOR"); + if (use_interceptor != NULL && strcmp(use_interceptor, "1") == 0) { + char *argv_next[] = { + (char *)launcher, + (char *)"--test-interceptor", + (char *)expected, + (char *)"recursive-stage-2", + (char *)"recursive-exec", + NULL, + }; + execv(launcher, argv_next); + } else { + char *argv_next[] = { + (char *)launcher, + (char *)expected, + (char *)"recursive-stage-2", + (char *)"recursive-exec", + NULL, + }; + execv(launcher, argv_next); + } + fail("recursive execv launcher failed"); + } + + const char *parent_str = getenv("PARENT_SECCOMP_FILTERS"); + if (parent_str == NULL) { + fail("missing PARENT_SECCOMP_FILTERS"); + } + int parent_count = atoi(parent_str); + if (count != parent_count) { + char msg[128]; + snprintf(msg, sizeof msg, "seccomp filter stacked: parent=%d child=%d", parent_count, count); + fail(msg); + } + + sigset_t inherited; + sigemptyset(&inherited); + if (sigprocmask(SIG_SETMASK, NULL, &inherited) != 0 || sigismember(&inherited, SIGUSR2) != 1) { + fail("recursive exec did not preserve blocked SIGUSR2"); + } + + write_all(STDOUT_FILENO, "recursive-exec-ok\n", 18); + return 0; +} + +/* ---- nested-seccomp subcommand (target's own SECCOMP_RET_TRAP filter) ---- */ + +static volatile sig_atomic_t g_nested_trap_count = 0; +static volatile sig_atomic_t g_nested_trap_errno = -1; +static volatile sig_atomic_t g_nested_trap_readlink_ok = 0; + +static void nested_seccomp_sigsys_handler(int sig, siginfo_t *info, void *raw_ucontext) { + if (sig != SIGSYS || info == NULL || raw_ucontext == NULL) { + return; + } + if (info->si_code != SYS_SECCOMP) { + return; + } + g_nested_trap_count++; + g_nested_trap_errno = info->si_errno; + + /* Loader's own tagged SECCOMP_RET_TRAP must still work even inside the + * target's forwarded SIGSYS handler! */ + char buf[PATH_MAX]; + ssize_t n = readlink("/proc/self/exe", buf, sizeof buf - 1); + if (n > 0 && (size_t)n == strlen(g_expected_exe) && memcmp(buf, g_expected_exe, (size_t)n) == 0) { + g_nested_trap_readlink_ok = 1; + } + + ucontext_t *uc = (ucontext_t *)raw_ucontext; +#if defined(__x86_64__) + uc->uc_mcontext.gregs[REG_RAX] = 4242; +#elif defined(__aarch64__) + uc->uc_mcontext.regs[0] = 4242; +#else +#error "unsupported architecture" +#endif +} + +static int run_nested_seccomp_test(void) { + g_expected_exe = expected_exe_path(); + + struct sigaction sa; + memset(&sa, 0, sizeof sa); + sa.sa_sigaction = nested_seccomp_sigsys_handler; + sa.sa_flags = SA_SIGINFO; + sigemptyset(&sa.sa_mask); + if (sigaction(SIGSYS, &sa, NULL) != 0) { + fail("nested sigaction(SIGSYS)"); + } + + if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0) { + fail("nested prctl(PR_SET_NO_NEW_PRIVS)"); + } + + /* BPF filter: if nr == SYS_getuid -> SECCOMP_RET_TRAP (data=0), else ALLOW. */ + struct raw_sock_filter insns[] = { + {0x20, 0, 0, 0}, /* LD_W_ABS offsetof(seccomp_data, nr) */ + {0x15, 0, 1, (uint32_t)SYS_getuid}, /* JEQ SYS_getuid -> +0 else +1 */ + {0x06, 0, 0, 0x00030000U}, /* RET SECCOMP_RET_TRAP | 0 */ + {0x06, 0, 0, 0x7fff0000U}, /* RET SECCOMP_RET_ALLOW */ + }; + struct raw_sock_fprog prog = { + .len = (uint16_t)(sizeof insns / sizeof insns[0]), + .filter = insns, + }; + if (syscall(SYS_seccomp, 1 /* SECCOMP_SET_MODE_FILTER */, 0, &prog) != 0) { + fail("nested seccomp(SECCOMP_SET_MODE_FILTER)"); + } + + long uid = syscall(SYS_getuid); + if (uid != 4242) { + char msg[128]; + snprintf(msg, sizeof msg, "nested seccomp getuid returned %ld instead of 4242", uid); + fail(msg); + } + if (g_nested_trap_count != 1 || g_nested_trap_errno != 0 || !g_nested_trap_readlink_ok) { + fail("nested seccomp handler state mismatch"); + } + + /* Loader's own /proc/self/exe traps must continue working afterward. */ + assert_readlink_matches_expected("/proc/self/exe", g_expected_exe); + + write_all(STDOUT_FILENO, "nested-seccomp-ok\n", 18); + return 0; +} + +/* ---- posix-spawn subcommand (clone3 CLONE_CLEAR_SIGHAND fallback) ---- */ + +static int run_posix_spawn_test(void) { + posix_spawnattr_t attr; + if (posix_spawnattr_init(&attr) != 0) { + fail("posix_spawnattr_init"); + } + sigset_t full; + sigfillset(&full); + if (posix_spawnattr_setflags(&attr, POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK) != 0) { + fail("posix_spawnattr_setflags"); + } + if (posix_spawnattr_setsigdefault(&attr, &full) != 0) { + fail("posix_spawnattr_setsigdefault"); + } + if (posix_spawnattr_setsigmask(&attr, &full) != 0) { + fail("posix_spawnattr_setsigmask"); + } + + /* 1. Failed exec in posix_spawn must propagate ENOENT instead of killing + * the vfork child with SIGSYS (which leaves glibc's shared errno 0). */ + { + char *argv_missing[] = {(char *)"/nonexistent_fspy_posix_spawn_probe", NULL}; + pid_t missing_pid = -1; + int missing_rc = posix_spawn( + &missing_pid, + "/nonexistent_fspy_posix_spawn_probe", + NULL, + &attr, + argv_missing, + environ + ); + if (missing_rc != ENOENT) { + char msg[128]; + snprintf(msg, sizeof msg, "posix_spawn missing expected ENOENT, got %d", missing_rc); + fail(msg); + } + } + + /* 2. Successful posix_spawn through the launcher (or direct kernel exec). */ + const char *launcher = getenv("LAUNCHER_PATH"); + pid_t pid = -1; + int rc; + if (launcher != NULL && launcher[0] != '\0') { + char *argv_child[] = {(char *)launcher, (char *)"/bin/true", (char *)"true", NULL}; + rc = posix_spawn(&pid, launcher, NULL, &attr, argv_child, environ); + } else { + char *argv_child[] = {(char *)"/bin/true", NULL}; + rc = posix_spawn(&pid, "/bin/true", NULL, &attr, argv_child, environ); + } + posix_spawnattr_destroy(&attr); + if (rc != 0) { + errno = rc; + fail("posix_spawn /bin/true"); + } + + int status = 0; + if (waitpid(pid, &status, 0) != pid) { + fail("waitpid posix_spawn child"); + } + if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) { + char msg[128]; + snprintf(msg, sizeof msg, "posix_spawn child exited abnormally: status=0x%x", status); + fail(msg); + } + + write_all(STDOUT_FILENO, "posix-spawn-ok\n", 15); + return 0; +} + +static int run_clone3_enosys_test(void) { +#ifdef SYS_clone3 + uint64_t args[11]; + memset(args, 0, sizeof args); + /* CLONE_CLEAR_SIGHAND = 0x100000000ULL */ + args[0] = UINT64_C(0x100000000); + errno = 0; + long rc = syscall(SYS_clone3, args, sizeof args); + if (rc != -1 || errno != ENOSYS) { + char msg[128]; + snprintf(msg, sizeof msg, "clone3 expected -1/ENOSYS, got rc=%ld errno=%d", rc, errno); + fail(msg); + } +#endif + write_all(STDOUT_FILENO, "clone3-enosys-ok\n", 17); + return 0; +} + +/* ---- sigaltstack-storm subcommand (Go-style SA_ONSTACK SIGURG stress) ---- */ + +static volatile sig_atomic_t g_storm_stop = 0; +static volatile sig_atomic_t g_storm_sig_count = 0; + +static void storm_sigusr1_handler(int sig) { + if (sig == SIGUSR1) { + g_storm_sig_count++; + } +} + +struct storm_arg { + pthread_t target; +}; + +static void *storm_sender_thread(void *raw) { + struct storm_arg *arg = (struct storm_arg *)raw; + while (!g_storm_stop) { + pthread_kill(arg->target, SIGUSR1); + struct timespec ts = {0, 50 * 1000}; /* 50 us */ + nanosleep(&ts, NULL); + } + return NULL; +} + +static int run_sigaltstack_storm_test(void) { + const char *expected = expected_exe_path(); + static unsigned char alt_stack_mem[64 * 1024]; + stack_t ss; + ss.ss_sp = alt_stack_mem; + ss.ss_size = sizeof alt_stack_mem; + ss.ss_flags = 0; + if (sigaltstack(&ss, NULL) != 0) { + fail("sigaltstack"); + } + + struct sigaction sa; + memset(&sa, 0, sizeof sa); + sa.sa_handler = storm_sigusr1_handler; + sa.sa_flags = SA_ONSTACK | SA_RESTART; + sigemptyset(&sa.sa_mask); + if (sigaction(SIGUSR1, &sa, NULL) != 0) { + fail("sigaction SIGUSR1 storm"); + } + + g_storm_stop = 0; + g_storm_sig_count = 0; + struct storm_arg sarg = {pthread_self()}; + pthread_t sender; + if (pthread_create(&sender, NULL, storm_sender_thread, &sarg) != 0) { + fail("pthread_create storm sender"); + } + + for (int i = 0; i < 3000; i++) { + int fd = openat(AT_FDCWD, "/dev/null", O_RDONLY | O_CLOEXEC); + if (fd < 0) { + fail("storm openat /dev/null"); + } + close(fd); + + struct stat st; + if (fstatat(AT_FDCWD, "/dev/null", &st, 0) != 0) { + fail("storm fstatat /dev/null"); + } + + assert_readlink_matches_expected("/proc/self/exe", expected); + + struct timespec zero = {0, 0}; + if (ppoll(NULL, 0, &zero, NULL) < 0 && errno != EINTR) { + fail("storm ppoll(NULL)"); + } + + sigset_t u2; + sigemptyset(&u2); + sigaddset(&u2, SIGUSR2); + if (sigprocmask(SIG_BLOCK, &u2, NULL) != 0) { + fail("storm sigprocmask block"); + } + if (sigprocmask(SIG_UNBLOCK, &u2, NULL) != 0) { + fail("storm sigprocmask unblock"); + } + } + + g_storm_stop = 1; + pthread_join(sender, NULL); + if (g_storm_sig_count == 0) { + fail("storm received zero SIGUSR1 signals"); + } + + write_all(STDOUT_FILENO, "sigaltstack-storm-ok\n", 21); + return 0; +} + +/* ---- fifo-open-eintr subcommand (blocking open interrupted by signal) ---- */ + +static volatile sig_atomic_t g_fifo_done = 0; +static volatile sig_atomic_t g_fifo_sig_count = 0; + +static void fifo_sigusr1_handler(int sig) { + if (sig == SIGUSR1) { + g_fifo_sig_count++; + } +} + +static void *fifo_sender_thread(void *raw) { + struct storm_arg *arg = (struct storm_arg *)raw; + for (int i = 0; i < 400 && !g_fifo_done; i++) { + struct timespec ts = {0, 5 * 1000 * 1000}; /* 5 ms */ + nanosleep(&ts, NULL); + if (!g_fifo_done) { + pthread_kill(arg->target, SIGUSR1); + } + } + return NULL; +} + +static int run_fifo_open_eintr_test(void) { + const char *fifo_path = getenv("FIFO_PATH"); + if (fifo_path == NULL || fifo_path[0] == '\0') { + fail("missing FIFO_PATH"); + } + if (mkfifo(fifo_path, 0600) != 0) { + fail("mkfifo"); + } + + struct sigaction sa; + memset(&sa, 0, sizeof sa); + sa.sa_handler = fifo_sigusr1_handler; + sa.sa_flags = 0; /* no SA_RESTART: blocking open must fail with EINTR */ + sigemptyset(&sa.sa_mask); + if (sigaction(SIGUSR1, &sa, NULL) != 0) { + fail("sigaction SIGUSR1 fifo"); + } + + g_fifo_done = 0; + g_fifo_sig_count = 0; + struct storm_arg sarg = {pthread_self()}; + pthread_t sender; + if (pthread_create(&sender, NULL, fifo_sender_thread, &sarg) != 0) { + fail("pthread_create fifo sender"); + } + + errno = 0; + int fd = open(fifo_path, O_RDONLY); + int open_err = errno; + g_fifo_done = 1; + pthread_join(sender, NULL); + if (fd >= 0) { + close(fd); + } + unlink(fifo_path); + + if (fd != -1 || open_err != EINTR || g_fifo_sig_count == 0) { + char msg[128]; + snprintf(msg, sizeof msg, "blocking open(fifo) expected -1/EINTR, got fd=%d errno=%d sigs=%d", + fd, open_err, (int)g_fifo_sig_count); + fail(msg); + } + + write_all(STDOUT_FILENO, "fifo-open-eintr-ok\n", 19); + return 0; +} + +/* ---- blocked-sigsys-pending subcommand ---- */ + +static int run_blocked_sigsys_pending_test(void) { + const char *expected = expected_exe_path(); + g_expected_exe = expected; + + struct sigaction act; + memset(&act, 0, sizeof act); + act.sa_handler = sigsys_plain_handler; + sigemptyset(&act.sa_mask); + if (sigaction(SIGSYS, &act, NULL) != 0) { + fail("sigaction SIGSYS plain"); + } + + sigset_t set, pending; + sigemptyset(&set); + sigaddset(&set, SIGSYS); + if (sigprocmask(SIG_BLOCK, &set, NULL) != 0) { + fail("block SIGSYS"); + } + + g_sigsys_plain_count = 0; + g_handler_readlink_ok = 0; + if (raise(SIGSYS) != 0) { + fail("raise blocked SIGSYS"); + } + if (g_sigsys_plain_count != 0) { + fail("blocked SIGSYS was delivered immediately"); + } + + sigemptyset(&pending); + if (sigpending(&pending) != 0 || sigismember(&pending, SIGSYS) != 1) { + fail("sigpending did not report blocked SIGSYS"); + } + + /* Intercepted syscalls must keep working while SIGSYS is virtually blocked+pending. */ + assert_readlink_matches_expected("/proc/self/exe", expected); + + /* Unblocking SIGSYS delivers the deferred signal once. */ + if (sigprocmask(SIG_UNBLOCK, &set, NULL) != 0) { + fail("unblock SIGSYS"); + } + if (g_sigsys_plain_count != 1 || !g_handler_readlink_ok) { + fail("pending SIGSYS was not delivered on unblock"); + } + sigemptyset(&pending); + if (sigpending(&pending) != 0 || sigismember(&pending, SIGSYS) != 0) { + fail("SIGSYS still pending after delivery"); + } + + /* SIG_DFL while blocked must NOT kill until unblocked; switching to SIG_IGN + * before unblocking discards it safely. */ + act.sa_handler = SIG_DFL; + if (sigaction(SIGSYS, &act, NULL) != 0) { + fail("sigaction SIGSYS SIG_DFL"); + } + if (sigprocmask(SIG_BLOCK, &set, NULL) != 0) { + fail("re-block SIGSYS"); + } + if (raise(SIGSYS) != 0) { + fail("raise blocked SIGSYS with SIG_DFL"); + } + sigemptyset(&pending); + if (sigpending(&pending) != 0 || sigismember(&pending, SIGSYS) != 1) { + fail("sigpending missing SIG_DFL blocked SIGSYS"); + } + act.sa_handler = SIG_IGN; + if (sigaction(SIGSYS, &act, NULL) != 0) { + fail("sigaction SIGSYS SIG_IGN"); + } + if (sigprocmask(SIG_UNBLOCK, &set, NULL) != 0) { + fail("unblock ignored SIGSYS"); + } + assert_readlink_matches_expected("/proc/self/exe", expected); + + write_all(STDOUT_FILENO, "blocked-sigsys-pending-ok\n", 26); + return 0; +} + +/* ---- wait-mask-sigsys subcommand ---- */ + +static void *send_sigsys_delayed_thread(void *raw) { + struct storm_arg *arg = (struct storm_arg *)raw; + struct timespec ts = {0, 10 * 1000 * 1000}; /* 10 ms */ + nanosleep(&ts, NULL); + pthread_kill(arg->target, SIGSYS); + return NULL; +} + +static int run_wait_mask_sigsys_test(void) { + g_expected_exe = expected_exe_path(); + struct sigaction act; + memset(&act, 0, sizeof act); + act.sa_handler = sigsys_plain_handler; + sigemptyset(&act.sa_mask); + if (sigaction(SIGSYS, &act, NULL) != 0) { + fail("sigaction SIGSYS wait-mask"); + } + + /* 1. Block SIGSYS, raise it, call ppoll with SIGSYS still in wait mask + * (must stay deferred), then call sigsuspend with empty wait mask + * (must deliver pending SIGSYS and return EINTR while keeping SIGSYS + * blocked afterward). */ + sigset_t only_sigsys, empty, cur; + sigemptyset(&only_sigsys); + sigaddset(&only_sigsys, SIGSYS); + sigemptyset(&empty); + + if (sigprocmask(SIG_BLOCK, &only_sigsys, NULL) != 0) { + fail("block SIGSYS wait-mask"); + } + g_sigsys_plain_count = 0; + if (raise(SIGSYS) != 0) { + fail("raise SIGSYS wait-mask"); + } + struct timespec short_tmo = {0, 5 * 1000 * 1000}; + if (ppoll(NULL, 0, &short_tmo, &only_sigsys) != 0) { + fail("ppoll with SIGSYS blocked should time out"); + } + if (g_sigsys_plain_count != 0) { + fail("ppoll delivered SIGSYS despite SIGSYS in wait mask"); + } + + errno = 0; + if (sigsuspend(&empty) != -1 || errno != EINTR) { + fail("sigsuspend(&empty) did not return EINTR for pending SIGSYS"); + } + if (g_sigsys_plain_count != 1) { + fail("sigsuspend(&empty) did not deliver pending SIGSYS"); + } + sigemptyset(&cur); + if (sigprocmask(SIG_SETMASK, NULL, &cur) != 0 || sigismember(&cur, SIGSYS) != 1) { + fail("sigsuspend did not preserve blocked SIGSYS mask"); + } + if (sigprocmask(SIG_UNBLOCK, &only_sigsys, NULL) != 0) { + fail("unblock SIGSYS after sigsuspend"); + } + + /* 2. With SIGSYS unblocked, enter ppoll(&only_sigsys) while a helper sends + * SIGSYS; SIGSYS must NOT interrupt ppoll and must be delivered once + * ppoll restores the unblocked mask. */ + g_sigsys_plain_count = 0; + struct storm_arg sarg = {pthread_self()}; + pthread_t sender; + if (pthread_create(&sender, NULL, send_sigsys_delayed_thread, &sarg) != 0) { + fail("pthread_create sigsys sender"); + } + struct timespec wait_tmo = {0, 40 * 1000 * 1000}; /* 40 ms */ + int rc = ppoll(NULL, 0, &wait_tmo, &only_sigsys); + pthread_join(sender, NULL); + if (rc != 0) { + fail("ppoll(&only_sigsys) was interrupted by masked SIGSYS"); + } + if (g_sigsys_plain_count != 1) { + fail("SIGSYS deferred during ppoll was not delivered on return"); + } + + write_all(STDOUT_FILENO, "wait-mask-sigsys-ok\n", 20); + return 0; +} + +/* ---- tid-churn subcommand ---- */ + +static void *churn_thread_fn(void *unused) { + (void)unused; + /* Block SIGSYS before exiting (just like glibc's thread-exit path). */ + sigset_t set; + sigemptyset(&set); + sigaddset(&set, SIGSYS); + if (pthread_sigmask(SIG_BLOCK, &set, NULL) != 0) { + fail("churn thread block SIGSYS"); + } + return NULL; +} + +static void *post_churn_check_fn(void *unused) { + (void)unused; + sigset_t set, cur; + sigemptyset(&set); + sigaddset(&set, SIGSYS); + if (pthread_sigmask(SIG_BLOCK, &set, NULL) != 0) { + fail("post-churn block SIGSYS"); + } + sigemptyset(&cur); + if (pthread_sigmask(SIG_SETMASK, NULL, &cur) != 0 || sigismember(&cur, SIGSYS) != 1) { + fail("post-churn SIGSYS not recorded blocked (reaping failed)"); + } + if (pthread_sigmask(SIG_UNBLOCK, &set, NULL) != 0) { + fail("post-churn unblock SIGSYS"); + } + return NULL; +} + +static int run_tid_churn_test(void) { + /* Exceed MAX_TID_SLOTS (2048) to force dead-TID reaping. */ + pthread_attr_t attr; + if (pthread_attr_init(&attr) != 0) { + fail("pthread_attr_init"); + } + (void)pthread_attr_setstacksize(&attr, 64 * 1024); + for (int i = 0; i < 2200; i++) { + pthread_t t; + if (pthread_create(&t, &attr, churn_thread_fn, NULL) != 0) { + fail("pthread_create churn"); + } + if (pthread_join(t, NULL) != 0) { + fail("pthread_join churn"); + } + } + pthread_t check; + if (pthread_create(&check, &attr, post_churn_check_fn, NULL) != 0) { + fail("pthread_create post-churn"); + } + if (pthread_join(check, NULL) != 0) { + fail("pthread_join post-churn"); + } + pthread_attr_destroy(&attr); + + write_all(STDOUT_FILENO, "tid-churn-ok\n", 13); + return 0; +} + +/* ---- fork-sigmask-and-lock subcommand ---- */ + +static volatile sig_atomic_t g_hammer_stop = 0; + +static void *sigaction_hammer_thread(void *unused) { + (void)unused; + struct sigaction act, old; + memset(&act, 0, sizeof act); + act.sa_handler = SIG_IGN; + while (!g_hammer_stop) { + (void)sigaction(SIGSYS, &act, &old); + act.sa_handler = (act.sa_handler == SIG_IGN) ? sigsys_plain_handler : SIG_IGN; + } + return NULL; +} + +static int run_fork_sigmask_and_lock_test(void) { + const char *expected = expected_exe_path(); + g_expected_exe = expected; + + sigset_t set; + sigemptyset(&set); + sigaddset(&set, SIGSYS); + sigaddset(&set, SIGUSR2); + if (sigprocmask(SIG_BLOCK, &set, NULL) != 0) { + fail("parent block SIGSYS+SIGUSR2"); + } + + g_hammer_stop = 0; + pthread_t hammer; + if (pthread_create(&hammer, NULL, sigaction_hammer_thread, NULL) != 0) { + fail("pthread_create hammer"); + } + + for (int i = 0; i < 20; i++) { + pid_t pid = fork(); + if (pid < 0) { + fail("fork"); + } + if (pid == 0) { + /* Must not deadlock on ACTION_LOCK even if hammer held it during fork. */ + struct sigaction old; + memset(&old, 0, sizeof old); + if (sigaction(SIGSYS, NULL, &old) != 0) { + _exit(10); + } + sigset_t cur; + sigemptyset(&cur); + if (sigprocmask(SIG_SETMASK, NULL, &cur) != 0 + || sigismember(&cur, SIGSYS) != 1 + || sigismember(&cur, SIGUSR2) != 1) { + _exit(11); + } + char buf[PATH_MAX]; + ssize_t n = readlink("/proc/self/exe", buf, sizeof buf - 1); + if (n < 0) { + _exit(12); + } + buf[n] = '\0'; + if (strcmp(buf, expected) != 0) { + _exit(13); + } + _exit(0); + } + int status = 0; + if (waitpid(pid, &status, 0) != pid || !WIFEXITED(status) || WEXITSTATUS(status) != 0) { + fail("fork child failed"); + } + } + + g_hammer_stop = 1; + pthread_join(hammer, NULL); + if (sigprocmask(SIG_UNBLOCK, &set, NULL) != 0) { + fail("parent unblock"); + } + + write_all(STDOUT_FILENO, "fork-sigmask-and-lock-ok\n", 25); + return 0; +} + +/* ---- vfork-parent-isolation subcommand ---- */ + +static int run_vfork_parent_isolation_test(void) { + g_expected_exe = expected_exe_path(); + struct sigaction act, old; + memset(&act, 0, sizeof act); + act.sa_handler = sigsys_plain_handler; + sigemptyset(&act.sa_mask); + if (sigaction(SIGSYS, &act, NULL) != 0) { + fail("parent sigaction SIGSYS"); + } + + posix_spawnattr_t attr; + if (posix_spawnattr_init(&attr) != 0) { + fail("posix_spawnattr_init"); + } + sigset_t full; + sigfillset(&full); + if (posix_spawnattr_setflags(&attr, POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK) != 0 + || posix_spawnattr_setsigdefault(&attr, &full) != 0 + || posix_spawnattr_setsigmask(&attr, &full) != 0) { + fail("posix_spawnattr set flags/masks"); + } + + const char *launcher = getenv("LAUNCHER_PATH"); + char *direct_argv[] = {"true", NULL}; + char *loaded_argv[] = {(char *)launcher, "/bin/true", "true", NULL}; + const char *spawn_prog = (launcher != NULL && launcher[0] != '\0') ? launcher : "/bin/true"; + char **spawn_argv = (launcher != NULL && launcher[0] != '\0') ? loaded_argv : direct_argv; + + pid_t pid = -1; + int rc = posix_spawn(&pid, spawn_prog, NULL, &attr, spawn_argv, environ); + posix_spawnattr_destroy(&attr); + if (rc != 0) { + errno = rc; + fail("posix_spawn /bin/true"); + } + int status = 0; + if (waitpid(pid, &status, 0) != pid || !WIFEXITED(status) || WEXITSTATUS(status) != 0) { + fail("waitpid /bin/true"); + } + + /* Parent's virtual SIGSYS handler and sigmask must remain intact! */ + memset(&old, 0, sizeof old); + if (sigaction(SIGSYS, NULL, &old) != 0 || old.sa_handler != sigsys_plain_handler) { + fail("CLONE_VM child clobbered parent virtual SIGSYS handler"); + } + sigset_t cur; + sigemptyset(&cur); + if (sigprocmask(SIG_SETMASK, NULL, &cur) != 0 || sigismember(&cur, SIGSYS) != 0) { + fail("CLONE_VM child clobbered parent virtual SIGSYS mask"); + } + g_sigsys_plain_count = 0; + if (raise(SIGSYS) != 0 || g_sigsys_plain_count != 1) { + fail("parent custom SIGSYS handler failed after posix_spawn"); + } + + write_all(STDOUT_FILENO, "vfork-parent-isolation-ok\n", 26); + return 0; +} + +/* ---- tiny-vfork-stack subcommand (5 KiB stack above PROT_NONE guard) ---- */ + +static int tiny_vfork_child_fn(void *arg) { + const char *expected = (const char *)arg; + uint64_t mask = 0; + if (syscall(SYS_rt_sigprocmask, SIG_SETMASK, NULL, &mask, sizeof mask) != 0) { + _exit(20); + } + long fd = syscall(SYS_openat, AT_FDCWD, "/dev/null", O_RDONLY | O_CLOEXEC, 0); + if (fd < 0) { + _exit(21); + } + syscall(SYS_close, fd); + + char buf[256]; + long n = syscall(SYS_readlinkat, AT_FDCWD, "/proc/self/exe", buf, sizeof buf - 1); + if (n <= 0) { + _exit(22); + } + buf[n] = '\0'; + if (strcmp(buf, expected) != 0) { + _exit(23); + } + _exit(42); +} + +static int run_tiny_vfork_stack_test(void) { + const char *expected = expected_exe_path(); + long page = sysconf(_SC_PAGESIZE); + if (page <= 0) { + page = 4096; + } + /* Allocate guard page + 2 usable pages, but place child SP only 5120 bytes + * above the PROT_NONE guard page (matching AArch64 musl posix_spawn). */ + size_t total = (size_t)page * 3; + unsigned char *mem = mmap(NULL, total, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + if (mem == MAP_FAILED) { + fail("mmap tiny stack"); + } + if (mprotect(mem, (size_t)page, PROT_NONE) != 0) { + fail("mprotect guard page"); + } + unsigned char *stack_top = mem + (size_t)page + 5120; + /* Align down to 16 bytes for ABI compliance. */ + stack_top = (unsigned char *)((uintptr_t)stack_top & ~(uintptr_t)15); + + pid_t pid = clone(tiny_vfork_child_fn, stack_top, CLONE_VM | CLONE_VFORK | SIGCHLD, (void *)expected); + if (pid < 0) { + fail("clone tiny vfork stack"); + } + int status = 0; + if (waitpid(pid, &status, 0) != pid || !WIFEXITED(status) || WEXITSTATUS(status) != 42) { + fail("tiny vfork stack child failed or overflowed guard page"); + } + munmap(mem, total); + + write_all(STDOUT_FILENO, "tiny-vfork-stack-ok\n", 20); + return 0; +} + +/* ---- abseil-address-probe subcommand (Abseil AddressIsReadable) ---- */ + +static int run_abseil_address_probe_test(void) { + /* Abseil AddressIsReadable: how = ~0, set = probe_addr. The kernel copies + * set first (EFAULT) and checks how second (EINVAL), and the loader must + * pass the probe to the kernel without reading the address itself. */ + const uintptr_t bad_low = 1; + const uintptr_t bad_high = 0xdeadbeef0000ULL; + errno = 0; + if (syscall(SYS_rt_sigprocmask, ~0L, bad_low, 0, 8) != -1 || errno != EFAULT) { + fail("Abseil rt_sigprocmask(~0, bad_low) did not return EFAULT"); + } + errno = 0; + if (syscall(SYS_rt_sigprocmask, ~0L, bad_high, 0, 8) != -1 || errno != EFAULT) { + fail("Abseil rt_sigprocmask(~0, bad_high) did not return EFAULT"); + } + uint64_t valid_set = 0; + errno = 0; + if (syscall(SYS_rt_sigprocmask, ~0L, &valid_set, 0, 8) != -1 || errno != EINVAL) { + fail("Abseil rt_sigprocmask(~0, valid) did not return EINVAL"); + } + + write_all(STDOUT_FILENO, "abseil-address-probe-ok\n", 24); + return 0; +} + +/* ---- vfork-shared-stack-deep subcommand (Opus M1 regression test) ---- */ + +__attribute__((noinline)) static void touch_deep_vfork_stack(const char *expected) { + volatile unsigned char buf[16384]; + for (size_t i = 0; i < sizeof buf; i += 64) { + buf[i] = (unsigned char)(i ^ 0xa5); + } + int fd = openat(AT_FDCWD, "/dev/null", O_RDONLY | O_CLOEXEC); + if (fd >= 0) { + close(fd); + } + char linkbuf[PATH_MAX]; + ssize_t n = readlink("/proc/self/exe", linkbuf, sizeof linkbuf - 1); + if (n <= 0 || (size_t)n != strlen(expected) || memcmp(linkbuf, expected, (size_t)n) != 0) { + _exit(44); + } + if (buf[0] != 0xa5 || buf[16320] != (unsigned char)(16320 ^ 0xa5)) { + _exit(45); + } +} + +__attribute__((noinline)) static long raw_shared_stack_vfork_and_check(const char *expected) { + /* Keep known callee-saved FP/SIMD sentinels live across raw + * `clone(CLONE_VM | CLONE_VFORK | SIGCHLD, NULL, ...)`. On AArch64, if our + * SIGSYS frame sat below the parent's SP, the child's 16 KiB frame would + * overwrite saved `d8..d15` / GPRs in the parent's `ucontext`. */ + double s0 = 1.25; + double s1 = 2.5; + double s2 = 3.75; + double s3 = 4.125; + double s4 = 5.625; + double s5 = 6.875; + double s6 = 7.375; + double s7 = 8.9375; +#if defined(__aarch64__) + __asm__ volatile("" + : "+w"(s0), "+w"(s1), "+w"(s2), "+w"(s3), "+w"(s4), "+w"(s5), "+w"(s6), + "+w"(s7)); +#elif defined(__x86_64__) + __asm__ volatile("" + : "+x"(s0), "+x"(s1), "+x"(s2), "+x"(s3), "+x"(s4), "+x"(s5), "+x"(s6), + "+x"(s7)); +#endif + + /* `vfork()` uses `clone(CLONE_VM | CLONE_VFORK | SIGCHLD, NULL, ...)` on + * AArch64 (and `vfork` on x86-64) while preserving the return address off + * the shared stack. */ + pid_t pid = vfork(); + if (pid == 0) { + touch_deep_vfork_stack(expected); + _exit(0); + } + if (pid < 0) { + return -1; + } + + int status = 0; + if (waitpid((pid_t)pid, &status, 0) != (pid_t)pid || !WIFEXITED(status) || + WEXITSTATUS(status) != 0) { + fail("vfork-shared-stack-deep child failed"); + } + + if (s0 != 1.25 || s1 != 2.5 || s2 != 3.75 || s3 != 4.125 || s4 != 5.625 || s5 != 6.875 || + s6 != 7.375 || s7 != 8.9375) { + fail("parent FP/SIMD callee-saved registers were corrupted by shared-stack vfork child"); + } + return 0; +} + +static int run_vfork_shared_stack_deep_test(void) { + const char *expected = expected_exe_path(); + for (int i = 0; i < 8; i++) { + if (raw_shared_stack_vfork_and_check(expected) != 0) { + fail("raw_shared_stack_vfork_and_check failed"); + } + } + write_all(STDOUT_FILENO, "vfork-shared-stack-deep-ok\n", 27); + return 0; +} + +/* ---- clone-custom-stack-new-mm subcommand (Grok M2 regression test) ---- */ + +static int clone_custom_stack_child_fn(void *arg) { + const char *expected = (const char *)arg; + struct sigaction act, old; + memset(&act, 0, sizeof act); + memset(&old, 0, sizeof old); + act.sa_handler = sigsys_plain_handler; + sigemptyset(&act.sa_mask); + if (sigaction(SIGSYS, &act, NULL) != 0) { + _exit(50); + } + if (sigaction(SIGSYS, NULL, &old) != 0 || old.sa_handler != sigsys_plain_handler) { + _exit(51); + } + sigset_t s; + sigemptyset(&s); + sigaddset(&s, SIGSYS); + if (sigprocmask(SIG_BLOCK, &s, NULL) != 0 || sigprocmask(SIG_UNBLOCK, &s, NULL) != 0) { + _exit(52); + } + char linkbuf[PATH_MAX]; + ssize_t n = readlink("/proc/self/exe", linkbuf, sizeof linkbuf - 1); + if (n <= 0 || (size_t)n != strlen(expected) || memcmp(linkbuf, expected, (size_t)n) != 0) { + _exit(53); + } + return 0; +} + +static int run_clone_custom_stack_new_mm_test(void) { + const char *expected = expected_exe_path(); + size_t stack_sz = 64 * 1024; + unsigned char *stack_mem = + mmap(NULL, stack_sz, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + if (stack_mem == MAP_FAILED) { + fail("mmap custom clone stack"); + } + void *child_sp = (void *)(((uintptr_t)(stack_mem + stack_sz)) & ~(uintptr_t)15); + + /* `clone(fn, child_sp, SIGCHLD, ...)` creates a new address space + * (`CLONE_VM == 0`) with a non-NULL child stack. `on_fork_child` MUST still + * run so `OWNER_PID` updates and child `sigaction(SIGSYS)` / + * `rt_sigprocmask` work normally. */ + int pid = clone(clone_custom_stack_child_fn, child_sp, SIGCHLD, (void *)expected); + if (pid < 0) { + fail("clone(SIGCHLD, child_sp) failed"); + } + + int status = 0; + if (waitpid((pid_t)pid, &status, 0) != (pid_t)pid || !WIFEXITED(status) || + WEXITSTATUS(status) != 0) { + char msg[128]; + snprintf(msg, sizeof msg, "clone-custom-stack-new-mm child failed with status=%d", status); + fail(msg); + } + munmap(stack_mem, stack_sz); + write_all(STDOUT_FILENO, "clone-custom-stack-new-mm-ok\n", 29); + return 0; +} + +/* ---- pselect-timeout-deferred-sigsys subcommand (Grok M1 regression test) ---- */ + +struct pselect_sender_arg { + pid_t pid; + pid_t tid; +}; + +static void *pselect_sigsys_sender(void *raw) { + struct pselect_sender_arg *arg = (struct pselect_sender_arg *)raw; + struct timespec delay = {0, 40 * 1000 * 1000}; /* 40 ms */ + nanosleep(&delay, NULL); + syscall(SYS_tgkill, arg->pid, arg->tid, SIGSYS); + return NULL; +} + +static long long monotonic_ms(void) { + struct timespec ts; + if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) { + fail("clock_gettime"); + } + return (long long)ts.tv_sec * 1000LL + (long long)(ts.tv_nsec / 1000000L); +} + +static int run_pselect_timeout_deferred_sigsys_test(void) { + struct sigaction sa; + memset(&sa, 0, sizeof sa); + sa.sa_handler = sigsys_plain_handler; + sigemptyset(&sa.sa_mask); + if (sigaction(SIGSYS, &sa, NULL) != 0) { + fail("sigaction SIGSYS pselect"); + } + g_sigsys_plain_count = 0; + g_expected_exe = expected_exe_path(); + + sigset_t mask; + sigemptyset(&mask); + sigaddset(&mask, SIGSYS); + + struct pselect_sender_arg sarg = {getpid(), (pid_t)syscall(SYS_gettid)}; + pthread_t sender; + if (pthread_create(&sender, NULL, pselect_sigsys_sender, &sarg) != 0) { + fail("pthread_create pselect sender"); + } + + struct timespec ts = {0, 180 * 1000 * 1000}; /* 180 ms */ + long long t0 = monotonic_ms(); + int rc = pselect(0, NULL, NULL, NULL, &ts, &mask); + long long elapsed = monotonic_ms() - t0; + pthread_join(sender, NULL); + + if (rc != 0) { + char msg[128]; + snprintf(msg, sizeof msg, "pselect expected 0 on timeout, got rc=%d errno=%d", rc, errno); + fail(msg); + } + if (g_sigsys_plain_count != 1) { + fail("pselect did not deliver deferred SIGSYS upon exit"); + } + /* If pselect restarted its full 180ms timeout after the 40ms SIGSYS, it + * would take ~220ms+; fire a second check with 3 spaced SIGSYS signals? + * Check that elapsed stayed well below 2x timeout (320ms). */ + if (elapsed < 150 || elapsed > 320) { + char msg[128]; + snprintf(msg, sizeof msg, "pselect elapsed %lld ms outside [150, 320]", elapsed); + fail(msg); + } + + write_all(STDOUT_FILENO, "pselect-timeout-deferred-sigsys-ok\n", 35); + return 0; +} + +/* ---- proc-sibling-tid-exe subcommand (Grok M3 regression test) ---- */ + +struct sibling_tid_state { + volatile pid_t tid; + volatile int stop; +}; + +static void *sibling_tid_worker(void *raw) { + struct sibling_tid_state *st = (struct sibling_tid_state *)raw; + st->tid = (pid_t)syscall(SYS_gettid); + while (!st->stop) { + struct timespec ts = {0, 2 * 1000 * 1000}; + nanosleep(&ts, NULL); + } + return NULL; +} + +static int run_proc_sibling_tid_exe_test(void) { + const char *expected = expected_exe_path(); + struct sibling_tid_state st = {0, 0}; + pthread_t th; + if (pthread_create(&th, NULL, sibling_tid_worker, &st) != 0) { + fail("pthread_create sibling_tid_worker"); + } + while (st.tid == 0) { + struct timespec ts = {0, 1000 * 1000}; + nanosleep(&ts, NULL); + } + + char path[64]; + snprintf(path, sizeof path, "/proc/%d/exe", (int)st.tid); + assert_readlink_matches_expected(path, expected); + + struct stat expected_st, sibling_st; + if (stat(expected, &expected_st) != 0 || stat(path, &sibling_st) != 0) { + fail("stat /proc//exe"); + } + if (expected_st.st_dev != sibling_st.st_dev || expected_st.st_ino != sibling_st.st_ino) { + fail("stat /proc//exe did not match target executable"); + } + + st.stop = 1; + pthread_join(th, NULL); + write_all(STDOUT_FILENO, "proc-sibling-tid-exe-ok\n", 24); + return 0; +} + +/* ---- pselect-simultaneous-eintr subcommand (Grok M2 + Opus L1 regression) ---- */ + +static volatile sig_atomic_t g_eintr_usr1_hits = 0; +static volatile pid_t g_eintr_pid = 0; +static volatile pid_t g_eintr_tid = 0; + +static void pselect_eintr_usr1_handler(int sig) { + if (sig == SIGUSR1) { + g_eintr_usr1_hits++; + /* Deliver a non-seccomp SIGSYS during the real signal's wake so the + * masked wait sees both a real signal and a deferred SIGSYS. */ + syscall(SYS_tgkill, g_eintr_pid, g_eintr_tid, SIGSYS); + } +} + +static void *pselect_usr1_sender(void *raw) { + struct pselect_sender_arg *arg = (struct pselect_sender_arg *)raw; + struct timespec delay = {0, 30 * 1000 * 1000}; /* 30 ms */ + nanosleep(&delay, NULL); + syscall(SYS_tgkill, arg->pid, arg->tid, SIGUSR1); + return NULL; +} + +static atomic_int g_pselect_fdset_done = 0; + +static void *pselect_late_sigsys_sender(void *raw) { + struct pselect_sender_arg *arg = (struct pselect_sender_arg *)raw; + /* Fire SIGSYS every 3 ms until pselect returns so at least one deferred + * SIGSYS lands at or after the 20 ms timeout expiry (exercising the + * zero-timeout replay path that clears fd_sets). */ + for (int i = 0; i < 40 && !atomic_load(&g_pselect_fdset_done); i++) { + struct timespec delay = {0, 3 * 1000 * 1000}; /* 3 ms */ + nanosleep(&delay, NULL); + if (!atomic_load(&g_pselect_fdset_done)) { + syscall(SYS_tgkill, arg->pid, arg->tid, SIGSYS); + } + } + return NULL; +} + +static int run_pselect_simultaneous_eintr_test(void) { + struct sigaction sa_sys; + memset(&sa_sys, 0, sizeof sa_sys); + sa_sys.sa_handler = sigsys_plain_handler; + sigemptyset(&sa_sys.sa_mask); + if (sigaction(SIGSYS, &sa_sys, NULL) != 0) { + fail("sigaction SIGSYS simultaneous-eintr"); + } + + struct sigaction sa_u1; + memset(&sa_u1, 0, sizeof sa_u1); + sa_u1.sa_handler = pselect_eintr_usr1_handler; + sigemptyset(&sa_u1.sa_mask); + if (sigaction(SIGUSR1, &sa_u1, NULL) != 0) { + fail("sigaction SIGUSR1 simultaneous-eintr"); + } + + g_sigsys_plain_count = 0; + g_eintr_usr1_hits = 0; + g_expected_exe = expected_exe_path(); + g_eintr_pid = getpid(); + g_eintr_tid = (pid_t)syscall(SYS_gettid); + + sigset_t mask; + sigemptyset(&mask); + sigaddset(&mask, SIGSYS); + + /* Part 1: Real SIGUSR1 + deferred SIGSYS in the same pselect wake MUST + * still return -1/EINTR instead of swallowing EINTR and sleeping to timeout. */ + struct pselect_sender_arg sarg = {g_eintr_pid, g_eintr_tid}; + pthread_t sender; + if (pthread_create(&sender, NULL, pselect_usr1_sender, &sarg) != 0) { + fail("pthread_create pselect usr1 sender"); + } + + struct timespec ts = {2, 0}; /* 2 s — would clearly fail if EINTR were swallowed */ + errno = 0; + int rc = pselect(0, NULL, NULL, NULL, &ts, &mask); + int saved_errno = errno; + pthread_join(sender, NULL); + + if (rc != -1 || saved_errno != EINTR) { + char msg[128]; + snprintf( + msg, + sizeof msg, + "pselect simultaneous SIGUSR1+SIGSYS expected -1/EINTR, got rc=%d errno=%d", + rc, + saved_errno + ); + fail(msg); + } + if (g_eintr_usr1_hits != 1 || g_sigsys_plain_count != 1) { + fail("pselect simultaneous-eintr did not observe both SIGUSR1 and deferred SIGSYS"); + } + + /* Part 2: When pselect times out after a deferred SIGSYS retry, the kernel + * MUST clear non-ready fds in readfds (never returning 0 with stale bits). */ + int pfd[2]; + if (pipe(pfd) != 0) { + fail("pipe for pselect fdset clear"); + } + fd_set rfds; + FD_ZERO(&rfds); + FD_SET(pfd[0], &rfds); + g_sigsys_plain_count = 0; + atomic_store(&g_pselect_fdset_done, 0); + if (pthread_create(&sender, NULL, pselect_late_sigsys_sender, &sarg) != 0) { + fail("pthread_create pselect late sigsys sender"); + } + struct timespec short_ts = {0, 20 * 1000 * 1000}; /* 20 ms */ + rc = pselect(pfd[0] + 1, &rfds, NULL, NULL, &short_ts, &mask); + atomic_store(&g_pselect_fdset_done, 1); + int still_set = FD_ISSET(pfd[0], &rfds); + pthread_join(sender, NULL); + close(pfd[0]); + close(pfd[1]); + if (rc != 0 || still_set != 0 || g_sigsys_plain_count < 1) { + char msg[128]; + snprintf( + msg, + sizeof msg, + "pselect timeout after deferred SIGSYS failed: rc=%d fd_set=%d sigsys=%d", + rc, + still_set, + (int)g_sigsys_plain_count + ); + fail(msg); + } + + /* Part 3: Raw `SYS_ppoll` with a deferred SIGSYS must write back remaining + * time (0 on expiry) into the caller's timespec. */ + struct timespec ppoll_ts = {0, 20 * 1000 * 1000}; /* 20 ms */ + uint64_t k_mask = UINT64_C(1) << (SIGSYS - 1); + g_sigsys_plain_count = 0; + atomic_store(&g_pselect_fdset_done, 0); + if (pthread_create(&sender, NULL, pselect_late_sigsys_sender, &sarg) != 0) { + fail("pthread_create ppoll sigsys sender"); + } + long ppoll_rc = syscall(SYS_ppoll, NULL, 0UL, &ppoll_ts, &k_mask, 8UL); + atomic_store(&g_pselect_fdset_done, 1); + pthread_join(sender, NULL); + if (ppoll_rc != 0 || ppoll_ts.tv_sec != 0 || ppoll_ts.tv_nsec != 0) { + char msg[128]; + snprintf( + msg, + sizeof msg, + "raw ppoll timeout write-back failed: rc=%ld ts=%ld.%09ld", + ppoll_rc, + (long)ppoll_ts.tv_sec, + ppoll_ts.tv_nsec + ); + fail(msg); + } + + write_all(STDOUT_FILENO, "pselect-simultaneous-eintr-ok\n", 30); + return 0; +} + +/* ---- posix-spawnp-long-path subcommand (Opus M1 x86-64/AArch64 musl 5KiB stack) ---- */ + +static int run_posix_spawnp_long_path_test(void) { + /* Build a ~3.5 KiB PATH so musl's `__execvpe` allocates a large VLA on + * musl's 5 KiB `posix_spawn` child stack before calling `execve`. */ + const char *launcher = getenv("LAUNCHER_PATH"); + char launcher_dir[PATH_MAX]; + const char *launcher_base = NULL; + if (launcher != NULL && launcher[0] != '\0') { + const char *slash = strrchr(launcher, '/'); + if (slash == NULL || (size_t)(slash - launcher) >= sizeof launcher_dir) { + fail("invalid LAUNCHER_PATH"); + } + size_t dir_len = (size_t)(slash - launcher); + memcpy(launcher_dir, launcher, dir_len); + launcher_dir[dir_len] = '\0'; + launcher_base = slash + 1; + } + + char long_path[4096]; + size_t pos = 0; + while (pos + 40 < 3400) { + int n = snprintf(long_path + pos, sizeof long_path - pos, "/nonexistent-fspy-dir-%04zu:", pos); + if (n <= 0) { + fail("snprintf long_path"); + } + pos += (size_t)n; + } + if (launcher_base != NULL) { + snprintf(long_path + pos, sizeof long_path - pos, "%s:/bin:/usr/bin", launcher_dir); + } else { + snprintf(long_path + pos, sizeof long_path - pos, "/bin:/usr/bin"); + } + if (setenv("PATH", long_path, 1) != 0) { + fail("setenv PATH"); + } + + /* 1. Missing binary walks every entry of the ~3.5 KiB PATH on the child's + * stack and propagates ENOENT cleanly without overflowing the 5 KiB stack. */ + char *argv_missing[] = {(char *)"nonexistent_fspy_long_path_probe", NULL}; + for (int i = 0; i < 4; i++) { + pid_t pid = -1; + int rc = posix_spawnp(&pid, "nonexistent_fspy_long_path_probe", NULL, NULL, argv_missing, environ); + if (rc != ENOENT) { + char msg[128]; + snprintf(msg, sizeof msg, "posix_spawnp missing expected ENOENT, got %d", rc); + fail(msg); + } + } + + /* 2. Successful `posix_spawnp` resolving the last entry of the ~3.5 KiB PATH. */ + for (int i = 0; i < 4; i++) { + pid_t pid = -1; + int rc; + if (launcher_base != NULL) { + char *argv_child[] = {(char *)launcher_base, (char *)"/bin/true", (char *)"true", NULL}; + rc = posix_spawnp(&pid, launcher_base, NULL, NULL, argv_child, environ); + } else { + char *argv_child[] = {(char *)"true", NULL}; + rc = posix_spawnp(&pid, "true", NULL, NULL, argv_child, environ); + } + if (rc != 0) { + errno = rc; + fail("posix_spawnp with 3.5KiB PATH"); + } + int status = 0; + if (waitpid(pid, &status, 0) != pid || !WIFEXITED(status) || WEXITSTATUS(status) != 0) { + fail("posix_spawnp long-path child failed"); + } + } + + write_all(STDOUT_FILENO, "posix-spawnp-long-path-ok\n", 26); + return 0; +} + +/* ---- altstack-8kib-storm subcommand (Opus M4 regression test) ---- */ + +static volatile sig_atomic_t g_small_alt_hits = 0; + +static void small_alt_sigusr1_handler(int sig) { + if (sig == SIGUSR1) { + /* Perform a trapped syscall inside the SA_ONSTACK handler on a small + * realistic altstack (8 KiB on x86-64 / MINSIGSTKSZ on AArch64). */ + int fd = openat(AT_FDCWD, "/dev/null", O_RDONLY | O_CLOEXEC); + if (fd >= 0) { + close(fd); + } + g_small_alt_hits++; + } +} + +static int run_altstack_8kib_storm_test(void) { + const char *expected = expected_exe_path(); + /* Use the platform's real `SIGSTKSZ` (8 KiB on baseline x86-64, 16 KiB on + * AArch64 where a single kernel `rt_sigframe` is ~4.7 KiB and 3 nested + * frames need >= 3 * AT_MINSIGSTKSZ; musl's `sysconf(_SC_SIGSTKSZ)` does + * not scale with `AT_MINSIGSTKSZ`, so query auxv directly too). */ + long sc_sigstksz = sysconf(_SC_SIGSTKSZ); + size_t alt_sz = sc_sigstksz > 8192 ? (size_t)sc_sigstksz : 8192; + unsigned long min_sigstksz = getauxval(51 /* AT_MINSIGSTKSZ */); + size_t min_for_3_frames = (size_t)min_sigstksz * 3 + 1024; + if (min_for_3_frames > alt_sz) { + alt_sz = (min_for_3_frames + 4095) & ~(size_t)4095; + } + size_t page = (size_t)sysconf(_SC_PAGESIZE); + size_t map_sz = ((alt_sz + page - 1) & ~(page - 1)) + page; + unsigned char *mem = + mmap(NULL, map_sz, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + if (mem == MAP_FAILED) { + fail("mmap 8KiB altstack"); + } + /* Guard page at bottom of altstack to catch any overflow immediately. */ + if (mprotect(mem, page, PROT_NONE) != 0) { + fail("mprotect altstack guard"); + } + + stack_t ss; + ss.ss_sp = mem + page; + ss.ss_size = alt_sz; + ss.ss_flags = 0; + if (sigaltstack(&ss, NULL) != 0) { + fail("sigaltstack 8KiB"); + } + + struct sigaction sa; + memset(&sa, 0, sizeof sa); + sa.sa_handler = small_alt_sigusr1_handler; + sa.sa_flags = SA_ONSTACK | SA_RESTART; + sigemptyset(&sa.sa_mask); + if (sigaction(SIGUSR1, &sa, NULL) != 0) { + fail("sigaction SIGUSR1 8KiB"); + } + + g_storm_stop = 0; + g_small_alt_hits = 0; + struct storm_arg sarg = {pthread_self()}; + pthread_t sender; + if (pthread_create(&sender, NULL, storm_sender_thread, &sarg) != 0) { + fail("pthread_create 8KiB storm sender"); + } + + sigset_t empty; + sigemptyset(&empty); + for (int i = 0; i < 1500; i++) { + int fd = openat(AT_FDCWD, "/dev/null", O_RDONLY | O_CLOEXEC); + if (fd >= 0) { + close(fd); + } + assert_readlink_matches_expected("/proc/self/exe", expected); + struct timespec zero = {0, 0}; + if (ppoll(NULL, 0, &zero, &empty) < 0 && errno != EINTR) { + fail("8KiB storm ppoll"); + } + } + + g_storm_stop = 1; + pthread_join(sender, NULL); + if (g_small_alt_hits == 0) { + fail("8KiB storm received zero SIGUSR1 signals"); + } + + /* Disable altstack before unmapping it. */ + ss.ss_flags = SS_DISABLE; + sigaltstack(&ss, NULL); + munmap(mem, map_sz); + write_all(STDOUT_FILENO, "altstack-8kib-storm-ok\n", 23); + return 0; +} + +int main(int argc, char **argv) { + if (argc < 2) { + fail("missing subcommand"); + } + if (strcmp(argv[1], "sigaction") == 0) { + return run_sigaction_test(); + } + if (strcmp(argv[1], "sigsys-default-death") == 0) { + return run_sigsys_default_death(); + } + if (strcmp(argv[1], "sigmask-single") == 0) { + return run_sigmask_single_test(); + } + if (strcmp(argv[1], "sigmask-threads") == 0) { + return run_sigmask_threads_test(); + } + if (strcmp(argv[1], "proc-exe") == 0) { + return run_proc_exe_test(); + } + if (strcmp(argv[1], "comm") == 0) { + return run_comm_test(); + } + if (strcmp(argv[1], "deep-stack") == 0) { + return run_deep_stack_test(); + } + if (strcmp(argv[1], "interceptor") == 0) { + return run_interceptor_test(); + } + if (strcmp(argv[1], "recursive-exec") == 0) { + return run_recursive_exec_test(); + } + if (strcmp(argv[1], "nested-seccomp") == 0) { + return run_nested_seccomp_test(); + } + if (strcmp(argv[1], "posix-spawn") == 0) { + return run_posix_spawn_test(); + } + if (strcmp(argv[1], "clone3-enosys") == 0) { + return run_clone3_enosys_test(); + } + if (strcmp(argv[1], "sigaltstack-storm") == 0) { + return run_sigaltstack_storm_test(); + } + if (strcmp(argv[1], "fifo-open-eintr") == 0) { + return run_fifo_open_eintr_test(); + } + if (strcmp(argv[1], "blocked-sigsys-pending") == 0) { + return run_blocked_sigsys_pending_test(); + } + if (strcmp(argv[1], "wait-mask-sigsys") == 0) { + return run_wait_mask_sigsys_test(); + } + if (strcmp(argv[1], "tid-churn") == 0) { + return run_tid_churn_test(); + } + if (strcmp(argv[1], "fork-sigmask-and-lock") == 0) { + return run_fork_sigmask_and_lock_test(); + } + if (strcmp(argv[1], "vfork-parent-isolation") == 0) { + return run_vfork_parent_isolation_test(); + } + if (strcmp(argv[1], "tiny-vfork-stack") == 0) { + return run_tiny_vfork_stack_test(); + } + if (strcmp(argv[1], "abseil-address-probe") == 0) { + return run_abseil_address_probe_test(); + } + if (strcmp(argv[1], "vfork-shared-stack-deep") == 0) { + return run_vfork_shared_stack_deep_test(); + } + if (strcmp(argv[1], "clone-custom-stack-new-mm") == 0) { + return run_clone_custom_stack_new_mm_test(); + } + if (strcmp(argv[1], "pselect-timeout-deferred-sigsys") == 0) { + return run_pselect_timeout_deferred_sigsys_test(); + } + if (strcmp(argv[1], "proc-sibling-tid-exe") == 0) { + return run_proc_sibling_tid_exe_test(); + } + if (strcmp(argv[1], "altstack-8kib-storm") == 0) { + return run_altstack_8kib_storm_test(); + } + if (strcmp(argv[1], "pselect-simultaneous-eintr") == 0) { + return run_pselect_simultaneous_eintr_test(); + } + if (strcmp(argv[1], "posix-spawnp-long-path") == 0) { + return run_posix_spawnp_long_path_test(); + } + fail("unknown subcommand"); + return 1; +} diff --git a/crates/fspy_elf_loader_tests/tests/exec_elf.rs b/crates/fspy_elf_loader_tests/tests/exec_elf.rs index 141602e90..2c9357311 100644 --- a/crates/fspy_elf_loader_tests/tests/exec_elf.rs +++ b/crates/fspy_elf_loader_tests/tests/exec_elf.rs @@ -5,7 +5,11 @@ use std::{ ffi::OsStr, mem::{offset_of, size_of}, - os::unix::{ffi::OsStrExt as _, process::CommandExt as _}, + os::unix::{ + ffi::OsStrExt as _, + fs as unix_fs, + process::{CommandExt as _, ExitStatusExt as _}, + }, process::{Command, Output, Stdio}, }; @@ -16,6 +20,8 @@ const FIXTURE_DYN_PIE: &str = env!("FIXTURE_DYN_PIE"); const FIXTURE_DYN_EXEC: &str = env!("FIXTURE_DYN_EXEC"); const FIXTURE_STATIC_EXEC: &str = env!("FIXTURE_STATIC_EXEC"); const FIXTURE_STATIC_PIE: &str = env!("FIXTURE_STATIC_PIE"); +const FIXTURE_VIRT_DYN_PIE: &str = env!("FIXTURE_VIRT_DYN_PIE"); +const FIXTURE_VIRT_STATIC_EXEC: &str = env!("FIXTURE_VIRT_STATIC_EXEC"); #[test] #[timeout(10_000)] @@ -172,6 +178,450 @@ fn node_runs_javascript() { assert_eq!(loaded.stderr, direct.stderr); } +#[test] +#[ignore = "requires Node.js"] +#[timeout(10_000)] +fn node_proc_self_exe_and_exec_path_match_direct_exec() { + let mut resolve = Command::new("node"); + resolve.args(["-p", "process.execPath"]); + let resolved = output(resolve); + assert!(resolved.status.success(), "{resolved:?}"); + let node = OsStr::from_bytes(resolved.stdout.strip_suffix(b"\n").unwrap()); + let script = "const fs = require('node:fs'); console.log(JSON.stringify([process.execPath, fs.readlinkSync('/proc/self/exe'), fs.realpathSync('/proc/self/exe')]));"; + let mut direct = Command::new(node); + direct.args(["-e", script]); + let mut loaded = launcher(); + loaded.arg(node).args(["node", "-e", script]); + let direct = output(direct); + let loaded = output(loaded); + assert_eq!(direct.status.code(), Some(0), "{direct:?}"); + assert_eq!(loaded.status.code(), Some(0), "{loaded:?}"); + assert_eq!(loaded.stdout, direct.stdout); + assert_eq!(loaded.stderr, direct.stderr); +} + +#[test] +#[timeout(10_000)] +fn virtualizes_sigsys_sigaction_and_forwarding() { + for fixture in [FIXTURE_VIRT_DYN_PIE, FIXTURE_VIRT_STATIC_EXEC] { + check_virt_subcommand(fixture, "sigaction", b"sigaction-ok\n"); + } +} + +#[test] +#[timeout(10_000)] +fn non_seccomp_sigsys_with_sig_dfl_terminates_process() { + for fixture in [FIXTURE_VIRT_DYN_PIE, FIXTURE_VIRT_STATIC_EXEC] { + let mut direct = Command::new(fixture); + direct.arg("sigsys-default-death").stderr(Stdio::piped()); + let direct = output(direct); + assert_eq!(direct.status.signal(), Some(libc::SIGSYS), "kernel exec: {direct:?}"); + + let mut loaded = launcher(); + loaded.args([fixture, fixture, "sigsys-default-death"]); + let loaded = output(loaded); + assert_eq!(loaded.status.signal(), Some(libc::SIGSYS), "loader exec: {loaded:?}"); + } +} + +#[test] +#[timeout(10_000)] +fn virtualizes_sigsys_blocking_single_threaded() { + for fixture in [FIXTURE_VIRT_DYN_PIE, FIXTURE_VIRT_STATIC_EXEC] { + check_virt_subcommand(fixture, "sigmask-single", b"sigmask-single-ok\n"); + } +} + +#[test] +#[timeout(10_000)] +fn virtualizes_sigsys_blocking_multi_threaded() { + for fixture in [FIXTURE_VIRT_DYN_PIE, FIXTURE_VIRT_STATIC_EXEC] { + check_virt_subcommand(fixture, "sigmask-threads", b"sigmask-threads-ok\n"); + } +} + +#[test] +#[timeout(10_000)] +fn virtualizes_proc_self_exe_syscalls() { + let tmp = tempfile::tempdir().unwrap(); + let other_exe_link = tmp.path().join("exe"); + unix_fs::symlink("/dev/null", &other_exe_link).unwrap(); + + for (sym_name, fixture) in [ + ("sym_virt_dyn_pie", FIXTURE_VIRT_DYN_PIE), + ("sym_virt_static_exec", FIXTURE_VIRT_STATIC_EXEC), + ] { + let canonical = std::fs::canonicalize(fixture).unwrap(); + + // Direct path launch. + let mut direct = Command::new(fixture); + direct + .arg("proc-exe") + .env("EXPECTED_EXE", &canonical) + .env("OTHER_EXE_LINK", &other_exe_link) + .stderr(Stdio::piped()); + let direct = output(direct); + assert_eq!(direct.status.code(), Some(0), "kernel exec ({fixture}): {direct:?}"); + assert_eq!(direct.stdout, b"proc-exe-ok\n"); + + let mut loaded = launcher(); + loaded + .args([fixture, "custom-argv0", "proc-exe"]) + .env("EXPECTED_EXE", &canonical) + .env("OTHER_EXE_LINK", &other_exe_link); + let loaded = output(loaded); + assert_eq!(loaded.status.code(), Some(0), "loader exec ({fixture}): {loaded:?}"); + assert_eq!(loaded.stdout, direct.stdout); + assert_eq!(loaded.stderr, direct.stderr); + + // Launch via symlink: /proc/self/exe must resolve to the canonical target. + let sym_target = tmp.path().join(sym_name); + unix_fs::symlink(fixture, &sym_target).unwrap(); + let mut via_symlink = launcher(); + via_symlink + .arg(&sym_target) + .args(["sym-argv0", "proc-exe"]) + .env("EXPECTED_EXE", &canonical) + .env("OTHER_EXE_LINK", &other_exe_link); + let via_symlink = output(via_symlink); + assert_eq!( + via_symlink.status.code(), + Some(0), + "symlink loader ({fixture}): {via_symlink:?}" + ); + assert_eq!(via_symlink.stdout, b"proc-exe-ok\n"); + assert!(via_symlink.stderr.is_empty(), "{via_symlink:?}"); + } +} + +#[test] +#[timeout(10_000)] +fn sets_proc_self_comm_from_execfn_basename() { + let tmp = tempfile::tempdir().unwrap(); + // Both a short basename and a >15-byte basename (truncated to 15 bytes). + for (link_name, expected_comm) in [ + ("short_target", "short_target"), + ("very_long_executable_name_exceeding_15", "very_long_execu"), + ] { + let sym = tmp.path().join(link_name); + unix_fs::symlink(FIXTURE_VIRT_DYN_PIE, &sym).unwrap(); + + let mut loaded = launcher(); + loaded.arg(&sym).args(["different-argv0", "comm"]).env("EXPECTED_COMM", expected_comm); + let loaded = output(loaded); + assert_eq!(loaded.status.code(), Some(0), "{link_name}: {loaded:?}"); + assert_eq!(loaded.stdout, b"comm-ok\n"); + assert!(loaded.stderr.is_empty(), "{link_name}: {loaded:?}"); + } +} + +#[test] +#[timeout(10_000)] +fn respects_rlimit_stack_above_default_8_mib() { + let mut command = launcher(); + command.args([FIXTURE_VIRT_DYN_PIE, "deep-stack-argv0", "deep-stack"]); + // SAFETY: `setrlimit` is async-signal-safe and runs in the forked child + // before `execve` of the launcher. + unsafe { + command.pre_exec(|| { + let mut rlim = libc::rlimit { rlim_cur: 0, rlim_max: 0 }; + if libc::getrlimit(libc::RLIMIT_STACK, &raw mut rlim) != 0 { + return Err(std::io::Error::last_os_error()); + } + let target = 16 * 1024 * 1024; + if rlim.rlim_max != libc::RLIM_INFINITY && rlim.rlim_max < target { + rlim.rlim_cur = rlim.rlim_max; + } else { + rlim.rlim_cur = target; + } + if libc::setrlimit(libc::RLIMIT_STACK, &raw const rlim) != 0 { + return Err(std::io::Error::last_os_error()); + } + Ok(()) + }); + } + let out = output(command); + assert_eq!(out.status.code(), Some(0), "{out:?}"); + assert_eq!(out.stdout, b"deep-stack-ok\n"); + assert!(out.stderr.is_empty(), "{out:?}"); +} + +#[test] +#[timeout(10_000)] +fn syscall_interceptor_replays_short_circuits_and_observes_proc_exe_rewrite() { + for fixture in [FIXTURE_VIRT_DYN_PIE, FIXTURE_VIRT_STATIC_EXEC] { + let canonical = std::fs::canonicalize(fixture).unwrap(); + let mut loaded = launcher(); + loaded + .args(["--test-interceptor", fixture, "interceptor-argv0", "interceptor"]) + .env("EXPECTED_EXE", &canonical); + let loaded = output(loaded); + assert_eq!(loaded.status.code(), Some(0), "interceptor ({fixture}): {loaded:?}"); + assert_eq!(loaded.stdout, b"interceptor-ok\n"); + assert!(loaded.stderr.is_empty(), "interceptor ({fixture}): {loaded:?}"); + } +} + +#[test] +#[timeout(10_000)] +fn recursive_re_exec_does_not_stack_seccomp_filters() { + for use_interceptor in [false, true] { + for fixture in [FIXTURE_VIRT_DYN_PIE, FIXTURE_VIRT_STATIC_EXEC] { + let canonical = std::fs::canonicalize(fixture).unwrap(); + let mut loaded = launcher(); + if use_interceptor { + loaded.arg("--test-interceptor"); + } + loaded + .args([fixture, "recursive-stage-1", "recursive-exec"]) + .env("EXPECTED_EXE", &canonical) + .env("LAUNCHER_PATH", LAUNCHER) + .env("RECURSIVE_STAGE", "1") + .env("USE_INTERCEPTOR", if use_interceptor { "1" } else { "0" }); + let loaded = output(loaded); + assert_eq!( + loaded.status.code(), + Some(0), + "recursive ({fixture}, interceptor={use_interceptor}): {loaded:?}" + ); + assert_eq!(loaded.stdout, b"recursive-exec-ok\n"); + assert!(loaded.stderr.is_empty(), "{loaded:?}"); + } + } +} + +#[test] +#[timeout(10_000)] +fn forwards_target_installed_seccomp_ret_trap_to_target_sigsys_handler() { + for fixture in [FIXTURE_VIRT_DYN_PIE, FIXTURE_VIRT_STATIC_EXEC] { + check_virt_subcommand(fixture, "nested-seccomp", b"nested-seccomp-ok\n"); + } +} + +#[test] +#[timeout(10_000)] +fn posix_spawn_survives_clone3_clear_sighand() { + // Exercise glibc's `posix_spawn` (which tries `clone3(CLONE_CLEAR_SIGHAND)` + // and must fall back cleanly to `clone(2)` without resetting `SIGSYS`). + let mut direct = Command::new(FIXTURE_VIRT_DYN_PIE); + direct.arg("posix-spawn").env_remove("LAUNCHER_PATH").stderr(Stdio::piped()); + let direct = output(direct); + assert_eq!(direct.status.code(), Some(0), "kernel exec: {direct:?}"); + assert_eq!(direct.stdout, b"posix-spawn-ok\n"); + assert!(direct.stderr.is_empty(), "kernel exec: {direct:?}"); + + let mut loaded = launcher(); + loaded + .args([FIXTURE_VIRT_DYN_PIE, FIXTURE_VIRT_DYN_PIE, "posix-spawn"]) + .env("LAUNCHER_PATH", LAUNCHER); + let loaded = output(loaded); + assert_eq!(loaded.status.code(), Some(0), "loader exec: {loaded:?}"); + assert_eq!(loaded.stdout, direct.stdout); + assert_eq!(loaded.stderr, direct.stderr); + + // Both dynamic and static binaries observe `ENOSYS` from `clone3`. + for fixture in [FIXTURE_VIRT_DYN_PIE, FIXTURE_VIRT_STATIC_EXEC] { + let mut loaded = launcher(); + loaded.args([fixture, fixture, "clone3-enosys"]); + let loaded = output(loaded); + assert_eq!(loaded.status.code(), Some(0), "clone3-enosys ({fixture}): {loaded:?}"); + assert_eq!(loaded.stdout, b"clone3-enosys-ok\n"); + assert!(loaded.stderr.is_empty(), "clone3-enosys ({fixture}): {loaded:?}"); + } +} + +#[test] +#[timeout(10_000)] +fn survives_sa_onstack_async_signal_storm_during_trapped_syscalls() { + for fixture in [FIXTURE_VIRT_DYN_PIE, FIXTURE_VIRT_STATIC_EXEC] { + check_virt_subcommand(fixture, "sigaltstack-storm", b"sigaltstack-storm-ok\n"); + } +} + +#[test] +#[timeout(10_000)] +fn blocking_fifo_open_is_interruptible_by_signal() { + let tmp = tempfile::tempdir().unwrap(); + for (name, fixture) in + [("test_0.fifo", FIXTURE_VIRT_DYN_PIE), ("test_1.fifo", FIXTURE_VIRT_STATIC_EXEC)] + { + let fifo = tmp.path().join(name); + let mut loaded = launcher(); + loaded.args([fixture, fixture, "fifo-open-eintr"]).env("FIFO_PATH", &fifo); + let loaded = output(loaded); + assert_eq!(loaded.status.code(), Some(0), "fifo-open-eintr ({fixture}): {loaded:?}"); + assert_eq!(loaded.stdout, b"fifo-open-eintr-ok\n"); + assert!(loaded.stderr.is_empty(), "fifo-open-eintr ({fixture}): {loaded:?}"); + } +} + +#[test] +#[timeout(10_000)] +fn blocked_sigsys_stays_pending_until_unblocked() { + for fixture in [FIXTURE_VIRT_DYN_PIE, FIXTURE_VIRT_STATIC_EXEC] { + check_virt_subcommand(fixture, "blocked-sigsys-pending", b"blocked-sigsys-pending-ok\n"); + } +} + +#[test] +#[timeout(10_000)] +fn masked_wait_honors_sigsys_deferral_and_delivery() { + for fixture in [FIXTURE_VIRT_DYN_PIE, FIXTURE_VIRT_STATIC_EXEC] { + check_virt_subcommand(fixture, "wait-mask-sigsys", b"wait-mask-sigsys-ok\n"); + } +} + +#[test] +#[timeout(30_000)] +fn dead_tid_reaping_handles_churn_past_table_capacity() { + for fixture in [FIXTURE_VIRT_DYN_PIE, FIXTURE_VIRT_STATIC_EXEC] { + check_virt_subcommand(fixture, "tid-churn", b"tid-churn-ok\n"); + } +} + +#[test] +#[timeout(15_000)] +fn fork_inherits_virtual_sigmask_and_resets_action_lock() { + for fixture in [FIXTURE_VIRT_DYN_PIE, FIXTURE_VIRT_STATIC_EXEC] { + check_virt_subcommand(fixture, "fork-sigmask-and-lock", b"fork-sigmask-and-lock-ok\n"); + } +} + +#[test] +#[timeout(10_000)] +fn vfork_posix_spawn_does_not_clobber_parent_sigsys_state() { + for fixture in [FIXTURE_VIRT_DYN_PIE, FIXTURE_VIRT_STATIC_EXEC] { + let canonical = std::fs::canonicalize(fixture).unwrap(); + + let mut direct = Command::new(fixture); + direct + .arg("vfork-parent-isolation") + .env("EXPECTED_EXE", &canonical) + .env_remove("LAUNCHER_PATH") + .stderr(Stdio::piped()); + let direct = output(direct); + assert_eq!(direct.status.code(), Some(0), "kernel exec ({fixture}): {direct:?}"); + assert_eq!(direct.stdout, b"vfork-parent-isolation-ok\n"); + assert!(direct.stderr.is_empty(), "kernel exec ({fixture}): {direct:?}"); + + let mut loaded = launcher(); + loaded + .args([fixture, fixture, "vfork-parent-isolation"]) + .env("EXPECTED_EXE", &canonical) + .env("LAUNCHER_PATH", LAUNCHER); + let loaded = output(loaded); + assert_eq!(loaded.status.code(), Some(0), "loader exec ({fixture}): {loaded:?}"); + assert_eq!(loaded.stdout, direct.stdout); + assert_eq!(loaded.stderr, direct.stderr); + } +} + +#[test] +#[timeout(10_000)] +fn tiny_5kib_vfork_stack_with_guard_page_survives_trapped_syscalls() { + for fixture in [FIXTURE_VIRT_DYN_PIE, FIXTURE_VIRT_STATIC_EXEC] { + check_virt_subcommand(fixture, "tiny-vfork-stack", b"tiny-vfork-stack-ok\n"); + } +} + +#[test] +#[timeout(10_000)] +fn abseil_address_probe_reaches_the_kernel() { + for fixture in [FIXTURE_VIRT_DYN_PIE, FIXTURE_VIRT_STATIC_EXEC] { + check_virt_subcommand(fixture, "abseil-address-probe", b"abseil-address-probe-ok\n"); + } +} + +#[test] +#[timeout(15_000)] +fn vfork_shared_stack_deep_frame_preserves_parent_regs() { + for fixture in [FIXTURE_VIRT_DYN_PIE, FIXTURE_VIRT_STATIC_EXEC] { + check_virt_subcommand(fixture, "vfork-shared-stack-deep", b"vfork-shared-stack-deep-ok\n"); + } +} + +#[test] +#[timeout(10_000)] +fn clone_new_mm_with_custom_stack_updates_owner_pid() { + for fixture in [FIXTURE_VIRT_DYN_PIE, FIXTURE_VIRT_STATIC_EXEC] { + check_virt_subcommand( + fixture, + "clone-custom-stack-new-mm", + b"clone-custom-stack-new-mm-ok\n", + ); + } +} + +#[test] +#[timeout(10_000)] +fn pselect_deferred_sigsys_does_not_restart_timeout() { + for fixture in [FIXTURE_VIRT_DYN_PIE, FIXTURE_VIRT_STATIC_EXEC] { + check_virt_subcommand( + fixture, + "pselect-timeout-deferred-sigsys", + b"pselect-timeout-deferred-sigsys-ok\n", + ); + } +} + +#[test] +#[timeout(10_000)] +fn proc_sibling_tid_exe_is_virtualized() { + for fixture in [FIXTURE_VIRT_DYN_PIE, FIXTURE_VIRT_STATIC_EXEC] { + check_virt_subcommand(fixture, "proc-sibling-tid-exe", b"proc-sibling-tid-exe-ok\n"); + } +} + +#[test] +#[timeout(20_000)] +fn altstack_8kib_signal_storm_with_trapped_syscalls() { + for fixture in [FIXTURE_VIRT_DYN_PIE, FIXTURE_VIRT_STATIC_EXEC] { + check_virt_subcommand(fixture, "altstack-8kib-storm", b"altstack-8kib-storm-ok\n"); + } +} + +#[test] +#[timeout(10_000)] +fn pselect_simultaneous_eintr_and_fdset_clear() { + for fixture in [FIXTURE_VIRT_DYN_PIE, FIXTURE_VIRT_STATIC_EXEC] { + check_virt_subcommand( + fixture, + "pselect-simultaneous-eintr", + b"pselect-simultaneous-eintr-ok\n", + ); + } +} + +#[test] +#[timeout(10_000)] +fn posix_spawnp_long_path_preserves_small_child_stack() { + for fixture in [FIXTURE_VIRT_DYN_PIE, FIXTURE_VIRT_STATIC_EXEC] { + check_virt_subcommand(fixture, "posix-spawnp-long-path", b"posix-spawnp-long-path-ok\n"); + } +} + +fn check_virt_subcommand(fixture: &str, subcommand: &str, expected_stdout: &[u8]) { + let canonical = std::fs::canonicalize(fixture).unwrap(); + + let mut direct = Command::new(fixture); + direct.arg(subcommand).env("EXPECTED_EXE", &canonical).stderr(Stdio::piped()); + let direct = output(direct); + assert_eq!(direct.status.code(), Some(0), "kernel exec ({fixture} {subcommand}): {direct:?}"); + assert_eq!(direct.stdout, expected_stdout); + assert!(direct.stderr.is_empty(), "kernel exec ({fixture} {subcommand}): {direct:?}"); + + let mut loaded = launcher(); + loaded + .args([fixture, fixture, subcommand]) + .env("EXPECTED_EXE", &canonical) + .env("FSPY_LOADER_EXEC", "1") + .env("LAUNCHER_PATH", LAUNCHER); + let loaded = output(loaded); + assert_eq!(loaded.status.code(), Some(0), "loader exec ({fixture} {subcommand}): {loaded:?}"); + assert_eq!(loaded.stdout, direct.stdout); + assert_eq!(loaded.stderr, direct.stderr); +} + #[test] #[timeout(10_000)] fn rejects_malformed_images() {