From fc3196680beb783090ac9e25b25b8f04ec25968d Mon Sep 17 00:00:00 2001 From: Weidong Cui Date: Fri, 13 Nov 2026 16:01:31 -0800 Subject: [PATCH 1/3] Support kill of a vfork child's own ID A vfork child that called kill ended its parent's runner with status 127, so Go's Pdeathsig check, kill(getpid(), sig), killed the parent. Allow kill in the window for the child's own ID only: the signal goes to a new process-directed queue of the child's, under the child's dispositions, mask and init flag. Any other target would go to the broker as the parent's, with the wrong sender and targets, so it fails with a logged EINVAL. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: f5406de6-bab4-4f3b-b232-ae238032c2c2 --- .../tests/pid_namespace.c | 18 +++++ litebox_runner_linux_userland/tests/run.rs | 13 ++++ .../tests/vfork_signal_parent.c | 29 +++++++++ litebox_shim_linux/src/lib.rs | 1 + litebox_shim_linux/src/syscalls/signal/mod.rs | 65 ++++++++++++++++--- 5 files changed, 116 insertions(+), 10 deletions(-) diff --git a/litebox_runner_linux_userland/tests/pid_namespace.c b/litebox_runner_linux_userland/tests/pid_namespace.c index 580d049135..fcbad6d08a 100644 --- a/litebox_runner_linux_userland/tests/pid_namespace.c +++ b/litebox_runner_linux_userland/tests/pid_namespace.c @@ -457,6 +457,23 @@ static void vfork_makes_a_first_process(void) { CHECK(exited_with(child, 0)); } +// Runs in a vfork-style child with a new namespace, and exits with whether it could signal itself. +static int kill_own_id(void *unused) { + (void)unused; + _exit(kill(1, SIGKILL) == 0 ? 0 : 1); +} + +// A vfork-style child with a new namespace may signal itself by its own ID, 1, which is also this +// process's, and, as its namespace's first process, ignores its own `SIGKILL`. Run from the test's +// root, which is the first process of its own namespace. +static void a_vfork_first_process_ignores_its_own_sigkill(void) { + CHECK(getpid() == 1); + pid_t child = clone(kill_own_id, vfork_stack + sizeof vfork_stack, + CLONE_VM | CLONE_VFORK | CLONE_NEWPID | SIGCHLD, NULL); + CHECK(child > 1); + CHECK(exited_with(child, 0)); +} + // Without root, neither `unshare` nor `clone` creates a namespace. static int unprivileged_creates_no_namespace(void) { int code = unshare(CLONE_NEWPID) == -1 && errno == EPERM ? 0 : 1; @@ -491,6 +508,7 @@ int main(int argc, char **argv) { the_namespace_ends_with_its_first_process(); clone_parent_makes_a_sibling(); vfork_makes_a_first_process(); + a_vfork_first_process_ignores_its_own_sigkill(); printf("pid-namespace failures=%d\n", failures); return failures != 0; } diff --git a/litebox_runner_linux_userland/tests/run.rs b/litebox_runner_linux_userland/tests/run.rs index 011ca0bb25..e5596d0fed 100644 --- a/litebox_runner_linux_userland/tests/run.rs +++ b/litebox_runner_linux_userland/tests/run.rs @@ -728,6 +728,19 @@ fn vfork_child_has_its_own_signal_state() { assert_eq!(numeric_field(sigpipe_line, "code="), 70); assert_eq!(numeric_field(sigpipe_line, "sender="), sigpipe_child); + let kill_self_line = line("kill-self "); + let kill_self_child = numeric_field(kill_self_line, "child="); + assert_eq!(numeric_field(kill_self_line, "waited="), kill_self_child); + assert_eq!(numeric_field(kill_self_line, "signaled="), 1); + assert_eq!(numeric_field(kill_self_line, "signal="), libc::SIGKILL); + + // A documented difference: Linux would signal the parent, and the child would exit with 82. + let kill_other_line = line("kill-other "); + let kill_other_child = numeric_field(kill_other_line, "child="); + assert_eq!(numeric_field(kill_other_line, "waited="), kill_other_child); + assert_eq!(numeric_field(kill_other_line, "exited="), 1); + assert_eq!(numeric_field(kill_other_line, "code="), 81); + let exec_line = line("exec "); let exec_child = numeric_field(exec_line, "child="); assert_eq!(numeric_field(exec_line, "waited="), exec_child); diff --git a/litebox_runner_linux_userland/tests/vfork_signal_parent.c b/litebox_runner_linux_userland/tests/vfork_signal_parent.c index b752398faa..45cbc8ef3e 100644 --- a/litebox_runner_linux_userland/tests/vfork_signal_parent.c +++ b/litebox_runner_linux_userland/tests/vfork_signal_parent.c @@ -2,6 +2,7 @@ // Licensed under the MIT license. #define _GNU_SOURCE +#include #include #include #include @@ -137,6 +138,34 @@ int main(int argc, char **argv) { printf("sigpipe child=%d waited=%d code=%d sender=%d\n", pipe_child, waited, WEXITSTATUS(status), pipe_sender); + // A child may signal itself, and its fatal signal ends only the child. + pid_t kill_self_child = vfork(); + if (kill_self_child == 0) { + kill(getpid(), SIGKILL); + _exit(80); + } + if (kill_self_child < 0) { + perror("vfork"); + return 9; + } + waited = waitpid(kill_self_child, &status, 0); + printf("kill-self child=%d waited=%d signaled=%d signal=%d\n", kill_self_child, waited, + WIFSIGNALED(status), WTERMSIG(status)); + + // Unlike Linux, LiteBox refuses any other target in a child, whose requests go to the broker + // as its parent's. + pid_t kill_other_child = vfork(); + if (kill_other_child == 0) { + _exit(kill(getppid(), 0) == -1 && errno == EINVAL ? 81 : 82); + } + if (kill_other_child < 0) { + perror("vfork"); + return 10; + } + waited = waitpid(kill_other_child, &status, 0); + printf("kill-other child=%d waited=%d exited=%d code=%d\n", kill_other_child, waited, + WIFEXITED(status), WEXITSTATUS(status)); + // The child changes its own signal state before exec. char *child_argv[] = {argv[1], "signals", NULL}; char *child_envp[] = {NULL}; diff --git a/litebox_shim_linux/src/lib.rs b/litebox_shim_linux/src/lib.rs index 84158837d8..95306002ad 100644 --- a/litebox_shim_linux/src/lib.rs +++ b/litebox_shim_linux/src/lib.rs @@ -1040,6 +1040,7 @@ impl Task { | PrctlArg::GetNoNewPrivs | PrctlArg::SetNoNewPrivs, } + | SyscallRequest::Kill { .. } | SyscallRequest::RtSigaction { .. } | SyscallRequest::RtSigprocmask { .. } | SyscallRequest::RtSigreturn diff --git a/litebox_shim_linux/src/syscalls/signal/mod.rs b/litebox_shim_linux/src/syscalls/signal/mod.rs index 9357a9bb8c..9fdfc9d785 100644 --- a/litebox_shim_linux/src/syscalls/signal/mod.rs +++ b/litebox_shim_linux/src/syscalls/signal/mod.rs @@ -42,6 +42,9 @@ pub(crate) struct SignalState { pending: RefCell>>, /// Pending process signals (shared across all threads). shared_pending: Arc>, + /// The `vfork` child's own pending process signals, during the window, while `shared_pending` + /// keeps the suspended parent's. + vfork_child_shared_pending: RefCell>, /// Signal handlers. handlers: RefCell>>, /// Alternate signal stack. @@ -58,6 +61,7 @@ impl SignalState { Self { pending: RefCell::new(PendingSignals::new_queue(SigSet::empty())), shared_pending: PendingSignals::new_queue(SigSet::empty()), + vfork_child_shared_pending: RefCell::new(None), handlers: RefCell::new(Arc::new(SignalHandlers::new())), altstack: Cell::new(SigAltStack { sp: 0, @@ -88,6 +92,7 @@ impl SignalState { pending: RefCell::new(PendingSignals::new_queue(self.blocked())), // Share process-wide pending signals shared_pending: self.shared_pending.clone(), + vfork_child_shared_pending: RefCell::new(None), // Share handlers across tasks handlers: self.handlers.clone(), // Clear altstack @@ -197,10 +202,10 @@ impl SignalState { } /// Gives the `vfork` child a copy of the current dispositions, blocked mask, and alternate - /// stack with no pending thread signals, returning the suspended parent's state. + /// stack, and its own queues with no pending signals, returning the suspended parent's state. /// /// If `reset_handlers` is set, like `CLONE_CLEAR_SIGHAND`, the child's handled signals take - /// their default action. Process-directed pending signals stay queued for the parent. + /// their default action. The parent's process-directed pending signals stay queued for it. pub(crate) fn begin_vfork_child(&self, reset_handlers: bool) -> VforkParentSignals { let mut child_handlers = SignalHandlers::clone(&self.handlers.borrow()); if reset_handlers { @@ -208,6 +213,8 @@ impl SignalState { } let child_handlers = Arc::new(child_handlers); let child_pending = PendingSignals::new_queue(self.blocked()); + self.vfork_child_shared_pending + .replace(Some(PendingSignals::new(SigSet::empty()))); VforkParentSignals { pending: self.pending.replace(child_pending), handlers: self.handlers.replace(child_handlers), @@ -226,6 +233,7 @@ impl SignalState { } = parent; // The parent's queue restores its mask. self.pending.replace(pending); + self.vfork_child_shared_pending.replace(None); // The child cannot make the syscalls that set a temporary mask, but in case, none of its // state outlives the window. The suspended parent has no temporary mask of its own. self.saved_sigmask.set(None); @@ -1002,11 +1010,12 @@ impl Task { self.signals.pending.borrow().lock().take_next(blocked) } - /// Takes the next signal not in `blocked` that is pending for this process. + /// Takes the next signal not in `blocked` that is pending for this process: in a `vfork` + /// window, for the child. fn take_next_process_signal(&self, blocked: SigSet) -> Option<(Signal, Siginfo)> { - // Process-directed signals belong to the suspended vfork parent. - if self.vfork.borrow().is_some() { - return None; + // The parent's process-directed signals wait for the suspended parent. + if let Some(child_pending) = &mut *self.signals.vfork_child_shared_pending.borrow_mut() { + return child_pending.take_next(blocked); } self.signals.shared_pending.lock().take_next(blocked) } @@ -1134,12 +1143,17 @@ impl Task { // already have queued a signal once this lock is released. let pending = self.signals.pending.borrow(); // Differs only in a `vfork` child, which owns neither the parent's thread - // queues nor its process-directed signals. + // queues nor its process-directed signals, but has its own of each. if Arc::ptr_eq(&pending, self.thread.thread_pending_queue()) { self.process().discard_thread_signals(signal); self.signals.shared_pending.lock().discard(signal); } else { pending.lock().discard(signal); + if let Some(child_pending) = + &mut *self.signals.vfork_child_shared_pending.borrow_mut() + { + child_pending.discard(signal); + } } } } @@ -1166,6 +1180,19 @@ impl Task { pub(crate) fn sys_kill(&self, pid: i32, signal: i32) -> Result { let signal = signal_or_probe(signal)?; + // A `vfork` child's requests go to the broker as its parent's, which would signal other + // targets from the parent, so the child may signal only itself. Its ID can equal the + // parent's in a new PID namespace, so it is checked first. + if self.vfork.borrow().is_some() { + if pid != self.sys_getpid() { + log_unsupported!("kill({pid}) in a vfork child"); + return Err(Errno::EINVAL); + } + if let Some(signal) = signal { + self.send_vfork_child_shared_signal(signal, self.siginfo_from_self(signal)); + } + return Ok(0); + } // Like Linux, `kill` given the ID of any of this process's threads signals this process. if pid == self.pid || self.process().has_thread(pid) { if let Some(signal) = signal { @@ -1308,10 +1335,10 @@ impl Task { if !(thread_pending & !blocked).is_empty() { return true; } - // Process-directed signals wait for the suspended vfork parent, so they must not + // The parent's process-directed signals wait for the suspended parent, so they must not // interrupt the child: its restarted syscalls would be interrupted again forever. - if self.vfork.borrow().is_some() { - return false; + if let Some(child_pending) = &*self.signals.vfork_child_shared_pending.borrow() { + return !(child_pending.pending & !blocked).is_empty(); } let shared_pending = self.signals.shared_pending.lock().pending & !blocked; !shared_pending.is_empty() @@ -1612,6 +1639,24 @@ impl Task { self.interrupt_siblings(); } + /// Queues `signal` as a process-directed signal of the `vfork` child, unless the child ignores + /// it. Only the child's own `kill` sends one. + fn send_vfork_child_shared_signal(&self, signal: Signal, siginfo: Siginfo) { + let max_queued = self.rlimit(RlimitResource::SIGPENDING).rlim_cur; + let init = self.is_init_process(); + let handlers = self.signals.handlers.borrow(); + let inner = handlers.inner.lock(); + let blocked = self.signals.blocked_or_waited(); + if is_signal_ignored(signal, &siginfo, blocked, &inner, init) { + return; + } + // `kill` uses `SI_USER`, so its signals never fail to be made pending. + debug_assert_eq!(siginfo.code, SI_USER); + if let Some(child_pending) = &mut *self.signals.vfork_child_shared_pending.borrow_mut() { + let _ = child_pending.push(max_queued, signal, siginfo); + } + } + /// Forces a signal to be delivered on next call to `check_for_signals`. fn force_signal(&self, signal: Signal, force_exit: bool) { let siginfo = Siginfo { From daec5ba9452d9cd68aa46c02513cf05f2f95dabe Mon Sep 17 00:00:00 2001 From: Weidong Cui Date: Fri, 13 Nov 2026 16:08:50 -0800 Subject: [PATCH 2/3] Keep a vfork child's pending signals across execve A vfork child's pending signals were dropped when its new program started in a fresh runner, while Linux keeps them across execve. Carry them in the startup record and TaskParams as PendingSignalSets: the child's own process-directed queue gives the process set, its private queue the thread set, and signals that lost their siginfo stay without a sender. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: f5406de6-bab4-4f3b-b232-ae238032c2c2 --- litebox_common_linux/src/lib.rs | 3 + litebox_common_linux/src/program_startup.rs | 49 ++++++++++++++- litebox_common_linux/src/signal/mod.rs | 2 +- .../src/lib.rs | 2 + .../src/linux.rs | 3 + .../src/lib.rs | 4 ++ litebox_runner_linux_userland/src/lib.rs | 5 +- litebox_runner_linux_userland/tests/run.rs | 19 ++++++ .../tests/vfork_exec_child.c | 43 ++++++++++++- .../tests/vfork_signal_parent.c | 30 ++++++++- litebox_shim_linux/src/lib.rs | 9 ++- litebox_shim_linux/src/syscalls/process.rs | 10 ++- litebox_shim_linux/src/syscalls/signal/mod.rs | 62 +++++++++++++++++-- 13 files changed, 226 insertions(+), 15 deletions(-) diff --git a/litebox_common_linux/src/lib.rs b/litebox_common_linux/src/lib.rs index 15e2c1858f..70ec3451b1 100644 --- a/litebox_common_linux/src/lib.rs +++ b/litebox_common_linux/src/lib.rs @@ -1972,6 +1972,9 @@ pub struct TaskParams { pub blocked_signals: SigSet, /// The signals initially ignored; all other dispositions start as default. pub ignored_signals: SigSet, + /// Signals pending at start for the process, or for its main thread, as sent by the process + /// itself. + pub pending_signals: program_startup::PendingSignalSets, /// Descriptors inherited from the parent, or `None` to start with the standard streams. pub inherited_fds: Option>, /// The absolute working directory inherited from the parent, or `None` to start at `/`. diff --git a/litebox_common_linux/src/program_startup.rs b/litebox_common_linux/src/program_startup.rs index 73f89f5387..6cb884fc80 100644 --- a/litebox_common_linux/src/program_startup.rs +++ b/litebox_common_linux/src/program_startup.rs @@ -25,7 +25,7 @@ use litebox::arch::aarch64::vector::SveVectorLength; const HEADER_SIZE: usize = size_of::() + size_of::<[u32; 11]>() - + size_of::<[u64; 2]>() + + size_of::<[u64; 5]>() + size_of::() + size_of::() + if cfg!(target_arch = "aarch64") { @@ -89,6 +89,8 @@ pub struct LinuxProgramStartup { pub blocked_signals: SigSet, /// Signals whose ignored disposition survives `execve`. pub ignored_signals: SigSet, + /// Signals pending at `execve`, which survive it. + pub pending_signals: PendingSignalSets, /// File mode creation mask, with only permission bits set. pub umask: u32, /// Resource limits, which survive `execve`. @@ -115,6 +117,18 @@ pub struct LinuxProgramStartup { pub inherited_fds: Vec, } +/// Signals pending for a process that starts a program, as sent by the process itself. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct PendingSignalSets { + /// Signals pending for the process, which any of its threads may take. + pub process: SigSet, + /// Signals pending for the thread that starts the program, which becomes its main thread. + pub thread: SigSet, + /// The pending signals, of either set, whose first queued instance lost its `siginfo`, as + /// a real-time signal does once `RLIMIT_SIGPENDING` is reached, so they have no sender. + pub without_sender: SigSet, +} + /// A descriptor inherited across `execve`, as Linux keeps every descriptor not marked /// close-on-exec. /// @@ -319,6 +333,9 @@ impl LinuxProgramStartup { push_u32(&mut output, self.egid); push_u64(&mut output, self.blocked_signals.as_u64()); push_u64(&mut output, self.ignored_signals.as_u64()); + push_u64(&mut output, self.pending_signals.process.as_u64()); + push_u64(&mut output, self.pending_signals.thread.as_u64()); + push_u64(&mut output, self.pending_signals.without_sender.as_u64()); push_u32(&mut output, self.umask); output.extend_from_slice(self.resource_limits.as_bytes()); output.push(u8::from(self.no_new_privs)); @@ -382,6 +399,11 @@ impl LinuxProgramStartup { let effective_group_id = read_u32(&mut input)?; let blocked_signals = SigSet::from_u64(read_u64(&mut input)?); let ignored_signals = SigSet::from_u64(read_u64(&mut input)?); + let pending_signals = PendingSignalSets { + process: SigSet::from_u64(read_u64(&mut input)?), + thread: SigSet::from_u64(read_u64(&mut input)?), + without_sender: SigSet::from_u64(read_u64(&mut input)?), + }; let umask = read_u32(&mut input)?; let resource_limits = read_value(&mut input)?; let no_new_privs = read_bool(&mut input)?; @@ -449,6 +471,7 @@ impl LinuxProgramStartup { egid: effective_group_id, blocked_signals, ignored_signals, + pending_signals, umask, resource_limits, no_new_privs, @@ -748,6 +771,10 @@ fn validate(startup: &LinuxProgramStartup) -> Result<(), LinuxProgramStartupErro if startup.umask & !0o777 != 0 { return Err(LinuxProgramStartupError::InvalidUmask); } + let pending = &startup.pending_signals; + if !(pending.without_sender & !(pending.process | pending.thread)).is_empty() { + return Err(LinuxProgramStartupError::Malformed); + } validate_resource_limits(&startup.resource_limits) } @@ -948,6 +975,7 @@ mod tests { #[test] fn program_startup_round_trips() { + let real_time = Signal::try_from(crate::signal::SIGRTMIN).unwrap(); let startup = LinuxProgramStartup { uid: 1000, euid: 1001, @@ -955,6 +983,11 @@ mod tests { egid: 1003, blocked_signals: SigSet::empty().with(Signal::SIGUSR1), ignored_signals: SigSet::empty().with(Signal::SIGPIPE), + pending_signals: PendingSignalSets { + process: SigSet::empty().with(Signal::SIGUSR1).with(real_time), + thread: SigSet::empty().with(Signal::SIGPIPE), + without_sender: SigSet::empty().with(real_time), + }, umask: 0o027, resource_limits: resource_limits(), no_new_privs: true, @@ -1054,6 +1087,7 @@ mod tests { egid: 0, blocked_signals: SigSet::empty(), ignored_signals: SigSet::empty(), + pending_signals: PendingSignalSets::default(), umask: 0o022, resource_limits: resource_limits(), no_new_privs: false, @@ -1343,6 +1377,7 @@ mod tests { egid: 0, blocked_signals: SigSet::empty(), ignored_signals: SigSet::empty(), + pending_signals: PendingSignalSets::default(), umask: 0o022, resource_limits: resource_limits(), no_new_privs: false, @@ -1383,9 +1418,19 @@ mod tests { Err(LinuxProgramStartupError::InvalidString) ); + // Mark `SIGHUP`, which is pending in neither set, as having no sender. + let mut stray_without_sender = startup.encode().unwrap(); + let without_sender = 1 + 4 * size_of::() + 4 * size_of::(); + assert_eq!(stray_without_sender[without_sender], 0); + stray_without_sender[without_sender] = 1; + assert_eq!( + LinuxProgramStartup::decode(&stray_without_sender), + Err(LinuxProgramStartupError::Malformed) + ); + // Raise the soft limit of resource 1 above its hard limit of 1. let mut soft_above_hard = startup.encode().unwrap(); - let limits = 1 + 4 * size_of::() + 2 * size_of::() + size_of::(); + let limits = 1 + 4 * size_of::() + 5 * size_of::() + size_of::(); let soft_limit = limits + size_of::(); assert_eq!(soft_above_hard[soft_limit], 1); soft_above_hard[soft_limit] = 2; diff --git a/litebox_common_linux/src/signal/mod.rs b/litebox_common_linux/src/signal/mod.rs index a7d0af072e..68e1dd632e 100644 --- a/litebox_common_linux/src/signal/mod.rs +++ b/litebox_common_linux/src/signal/mod.rs @@ -119,7 +119,7 @@ pub enum SignalDisposition { Continue, } -#[derive(Clone, Copy, Debug, PartialEq, Eq, FromBytes, IntoBytes, Immutable)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, FromBytes, IntoBytes, Immutable)] #[repr(transparent)] pub struct SigSet(u64); diff --git a/litebox_runner_linux_on_macos_userland/src/lib.rs b/litebox_runner_linux_on_macos_userland/src/lib.rs index b066da18aa..32948a7b69 100644 --- a/litebox_runner_linux_on_macos_userland/src/lib.rs +++ b/litebox_runner_linux_on_macos_userland/src/lib.rs @@ -104,6 +104,8 @@ pub fn run(cli_args: CliArgs) -> Result { egid: 1000, blocked_signals: litebox_common_linux::signal::SigSet::empty(), ignored_signals: litebox_common_linux::signal::SigSet::empty(), + pending_signals: + litebox_common_linux::program_startup::PendingSignalSets::default(), inherited_fds: None, cwd: None, umask: None, diff --git a/litebox_runner_linux_on_vm_userland/src/linux.rs b/litebox_runner_linux_on_vm_userland/src/linux.rs index c99b9fdac4..d9b0fcbba6 100644 --- a/litebox_runner_linux_on_vm_userland/src/linux.rs +++ b/litebox_runner_linux_on_vm_userland/src/linux.rs @@ -143,6 +143,7 @@ fn serve_requests( egid: GUEST_GID, blocked_signals: litebox_common_linux::signal::SigSet::empty(), ignored_signals: litebox_common_linux::signal::SigSet::empty(), + pending_signals: litebox_common_linux::program_startup::PendingSignalSets::default(), inherited_fds: None, cwd: None, umask: None, @@ -237,6 +238,7 @@ fn run_launched( egid, blocked_signals, ignored_signals, + pending_signals, umask, resource_limits, no_new_privs, @@ -260,6 +262,7 @@ fn run_launched( egid, blocked_signals, ignored_signals, + pending_signals, inherited_fds: Some(inherited_fds), cwd: Some(cwd), umask: Some(umask), diff --git a/litebox_runner_linux_on_windows_userland/src/lib.rs b/litebox_runner_linux_on_windows_userland/src/lib.rs index 023585b4fb..21aafd7b8e 100644 --- a/litebox_runner_linux_on_windows_userland/src/lib.rs +++ b/litebox_runner_linux_on_windows_userland/src/lib.rs @@ -254,6 +254,7 @@ pub fn run(cli_args: CliArgs) -> Result<()> { egid, blocked_signals, ignored_signals, + pending_signals, umask, resource_limits, no_new_privs, @@ -273,6 +274,7 @@ pub fn run(cli_args: CliArgs) -> Result<()> { egid, blocked_signals, ignored_signals, + pending_signals, inherited_fds: Some(inherited_fds), cwd: Some(cwd), umask: Some(umask), @@ -323,6 +325,8 @@ pub fn run(cli_args: CliArgs) -> Result<()> { egid: 1000, blocked_signals: litebox_common_linux::signal::SigSet::empty(), ignored_signals: litebox_common_linux::signal::SigSet::empty(), + pending_signals: + litebox_common_linux::program_startup::PendingSignalSets::default(), inherited_fds: None, cwd: None, umask: None, diff --git a/litebox_runner_linux_userland/src/lib.rs b/litebox_runner_linux_userland/src/lib.rs index 1d715ef8bd..d8452ff9b2 100644 --- a/litebox_runner_linux_userland/src/lib.rs +++ b/litebox_runner_linux_userland/src/lib.rs @@ -15,7 +15,7 @@ use std::sync::Arc; use litebox_broker_local_userland as broker; use litebox_broker_transport_linux_userland::existing_runner::ExistingRunnerDescriptor; use litebox_common_linux::program_startup::{ - LinuxForkStartup, LinuxProcessStartup, LinuxProgramStartup, + LinuxForkStartup, LinuxProcessStartup, LinuxProgramStartup, PendingSignalSets, }; use litebox_common_linux::signal::{SigSet, Signal}; @@ -472,6 +472,7 @@ fn run_with_seccomp(cli_args: CliArgs, seccomp_scope: SeccompScope) -> Result Result Result 4) { diff --git a/litebox_runner_linux_userland/tests/vfork_signal_parent.c b/litebox_runner_linux_userland/tests/vfork_signal_parent.c index 45cbc8ef3e..3fafabcd0d 100644 --- a/litebox_runner_linux_userland/tests/vfork_signal_parent.c +++ b/litebox_runner_linux_userland/tests/vfork_signal_parent.c @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -166,9 +167,16 @@ int main(int argc, char **argv) { printf("kill-other child=%d waited=%d exited=%d code=%d\n", kill_other_child, waited, WIFEXITED(status), WEXITSTATUS(status)); - // The child changes its own signal state before exec. + // The child changes its own signal state, and leaves signals pending, before exec. char *child_argv[] = {argv[1], "signals", NULL}; char *child_envp[] = {NULL}; + int broken_pipe[2]; + struct rlimit sigpending_limit; + if (pipe(broken_pipe) != 0 || close(broken_pipe[0]) != 0 || + getrlimit(RLIMIT_SIGPENDING, &sigpending_limit) != 0) { + perror("exec setup"); + return 11; + } pid_t exec_child = vfork(); if (exec_child == 0) { // The parent's pending SIGUSR2 must not reach the child. @@ -176,6 +184,25 @@ int main(int argc, char **argv) { sigprocmask(SIG_UNBLOCK, &usr2_set, NULL) != 0) { _exit(112); } + // The signals the child sends itself are pending for its process. At the limit, a + // real-time one loses its sender. + sigset_t carried; + sigemptyset(&carried); + sigaddset(&carried, SIGUSR1); + sigaddset(&carried, SIGPIPE); + sigaddset(&carried, SIGRTMIN); + struct rlimit no_queue = {.rlim_cur = 0, .rlim_max = sigpending_limit.rlim_max}; + if (sigprocmask(SIG_BLOCK, &carried, NULL) != 0 || kill(getpid(), SIGUSR1) != 0 || + kill(getpid(), SIGPIPE) != 0 || setrlimit(RLIMIT_SIGPENDING, &no_queue) != 0 || + kill(getpid(), SIGRTMIN) != 0 || setrlimit(RLIMIT_SIGPENDING, &sigpending_limit) != 0) { + _exit(113); + } + // Ignoring SIGPIPE discards the pending one, and the broken pipe raises another for this + // thread, which, blocked, is not ignored. + if (signal(SIGPIPE, SIG_IGN) == SIG_ERR || write(broken_pipe[1], "x", 1) != -1 || + errno != EPIPE) { + _exit(114); + } execve(argv[1], child_argv, child_envp); _exit(111); } @@ -183,6 +210,7 @@ int main(int argc, char **argv) { perror("vfork"); return 5; } + close(broken_pipe[1]); waited = waitpid(exec_child, &status, 0); printf("exec child=%d waited=%d exited=%d code=%d\n", exec_child, waited, WIFEXITED(status), WEXITSTATUS(status)); diff --git a/litebox_shim_linux/src/lib.rs b/litebox_shim_linux/src/lib.rs index 95306002ad..5c006dbc35 100644 --- a/litebox_shim_linux/src/lib.rs +++ b/litebox_shim_linux/src/lib.rs @@ -510,6 +510,7 @@ impl LinuxShim { egid, blocked_signals, ignored_signals, + pending_signals, inherited_fds, cwd, umask, @@ -556,7 +557,13 @@ impl LinuxShim { Some(inherited_fds) => files.install_inherited_fds(&self.0, &inherited_fds)?, } - let signals = syscalls::signal::SignalState::inherited(blocked_signals, ignored_signals); + let signals = syscalls::signal::SignalState::inherited( + blocked_signals, + ignored_signals, + pending_signals, + pid, + uid, + ); let entrypoints = crate::LinuxShimEntrypoints { _not_send: core::marker::PhantomData, task: Task { diff --git a/litebox_shim_linux/src/syscalls/process.rs b/litebox_shim_linux/src/syscalls/process.rs index d478e2eb24..2431103ca7 100644 --- a/litebox_shim_linux/src/syscalls/process.rs +++ b/litebox_shim_linux/src/syscalls/process.rs @@ -3834,8 +3834,8 @@ impl Task { /// Starts the `vfork` child's new program in a fresh runner and resumes the parent. /// - /// The runner inherits the descriptors not marked close-on-exec. Failures before the transfer - /// return to the child, which may retry or exit. + /// The runner inherits the descriptors not marked close-on-exec and the child's pending + /// signals. Failures before the transfer return to the child, which may retry or exit. fn transfer_vfork_child( &self, path: alloc::string::String, @@ -3865,6 +3865,7 @@ impl Task { egid: self.credentials.egid, blocked_signals: self.signals.blocked(), ignored_signals: self.signals.ignored(), + pending_signals: self.signals.vfork_child_pending_signals(), umask, resource_limits, no_new_privs: self.no_new_privs(), @@ -5616,7 +5617,10 @@ mod tests { assert_eq!( SignalState::::inherited( requested, - SigSet::empty() + SigSet::empty(), + litebox_common_linux::program_startup::PendingSignalSets::default(), + 1, + 0, ) .blocked(), expected diff --git a/litebox_shim_linux/src/syscalls/signal/mod.rs b/litebox_shim_linux/src/syscalls/signal/mod.rs index 9fdfc9d785..f54d05130c 100644 --- a/litebox_shim_linux/src/syscalls/signal/mod.rs +++ b/litebox_shim_linux/src/syscalls/signal/mod.rs @@ -29,6 +29,7 @@ use litebox::{shim::Exception, sync::Mutex, utils::ReinterpretUnsignedExt as _}; use litebox_broker_protocol::process::{CpuTime, ProcessExitStatus}; use litebox_broker_protocol::signal::SignalTarget; use litebox_broker_protocol::{ProcessGroupId, ProcessId}; +use litebox_common_linux::program_startup::PendingSignalSets; use litebox_common_linux::signal::{ BUS_ADRERR, CLD_EXITED, CLD_KILLED, FPE_INTDIV, ILL_ILLOPN, MINSIGSTKSZ, NSIG, SI_KERNEL, SI_TKILL, SI_USER, SIG_DFL, SIG_IGN, SaFlags, SigAction, SigAltStack, SigSet, Siginfo, @@ -125,10 +126,17 @@ impl SignalState { self.clear_sigaltstack(); } - /// Returns the initial signal state of a process that inherits the `blocked` mask and - /// `ignored` dispositions, as a program started by `execve` in a fresh runner keeps them like - /// [`Self::reset_for_exec`]. - pub fn inherited(blocked: SigSet, ignored: SigSet) -> Self { + /// Returns the initial signal state of a process that inherits the `blocked` mask, `ignored` + /// dispositions, and `pending` signals, as a program started by `execve` in a fresh runner + /// keeps them like [`Self::reset_for_exec`]. Process `pid` of user `uid` sent itself the + /// pending signals. + pub fn inherited( + blocked: SigSet, + ignored: SigSet, + pending: PendingSignalSets, + pid: i32, + uid: u32, + ) -> Self { let mut state = Self::new_process(); state.set_signal_mask(blocked); let handlers = Arc::get_mut(state.handlers.get_mut()) @@ -142,6 +150,20 @@ impl SignalState { handler.action.sigaction = SIG_IGN; } } + let restore = |queue: &Mutex, signals: SigSet| { + let mut queue = queue.lock(); + for signal in signals { + let siginfo = if pending.without_sender.contains(signal) { + siginfo_kill(signal) + } else { + siginfo_kill_from(signal, pid, uid) + }; + // The signals were already pending, so no limit applies. + let _ = queue.push(usize::MAX, signal, siginfo); + } + }; + restore(&state.shared_pending, pending.process); + restore(&state.pending.borrow(), pending.thread); state } @@ -241,6 +263,21 @@ impl SignalState { self.altstack.set(altstack); self.last_exception.set(last_exception); } + + /// Returns the signals pending for the `vfork` child, which a program it starts keeps. + pub(crate) fn vfork_child_pending_signals(&self) -> PendingSignalSets { + let thread_pending = self.pending.borrow(); + let thread_pending = thread_pending.lock(); + let shared_pending = self.vfork_child_shared_pending.borrow(); + let shared_pending = shared_pending + .as_ref() + .expect("only a vfork child has its own process signals"); + PendingSignalSets { + process: shared_pending.pending, + thread: thread_pending.pending, + without_sender: shared_pending.without_sender() | thread_pending.without_sender(), + } + } } /// The signal state of a suspended `vfork` parent. @@ -417,6 +454,23 @@ impl PendingSignals { Some((signal, self.remove(signal))) } + /// Returns the pending signals whose first queued instance lost its `siginfo` in + /// [`Self::push`], so it has no sender. + fn without_sender(&self) -> SigSet { + let mut without_sender = SigSet::empty(); + for signal in self.pending { + let first = self + .queue + .iter() + .find(|info| info.signo == signal.as_i32()) + .expect("pending signals are queued"); + if first.code == SI_USER && first.data.pid() == 0 { + without_sender.add(signal); + } + } + without_sender + } + /// Discards every queued instance of `signal`. pub(super) fn discard(&mut self, signal: Signal) { #[cfg(test)] From 869237b90c0ba66d031b7cc64780f4fff8b25ddc Mon Sep 17 00:00:00 2001 From: Weidong Cui Date: Sun, 15 Nov 2026 13:05:29 -0800 Subject: [PATCH 3/3] Preserve queued signals across vfork exec Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 89392541-7702-4f61-8b24-b21189a90836 --- litebox_common_linux/src/lib.rs | 5 +- litebox_common_linux/src/program_startup.rs | 221 +++++++++++++----- litebox_common_linux/src/signal/mod.rs | 4 +- .../src/lib.rs | 2 +- .../src/linux.rs | 2 +- .../src/lib.rs | 2 +- litebox_runner_linux_userland/src/lib.rs | 4 +- litebox_runner_linux_userland/tests/run.rs | 2 + .../tests/vfork_exec_child.c | 13 +- .../tests/vfork_signal_parent.c | 3 +- litebox_shim_linux/src/lib.rs | 2 - litebox_shim_linux/src/syscalls/process.rs | 4 +- litebox_shim_linux/src/syscalls/signal/mod.rs | 126 ++++++---- 13 files changed, 272 insertions(+), 118 deletions(-) diff --git a/litebox_common_linux/src/lib.rs b/litebox_common_linux/src/lib.rs index 70ec3451b1..55c6ee3dfc 100644 --- a/litebox_common_linux/src/lib.rs +++ b/litebox_common_linux/src/lib.rs @@ -1972,9 +1972,8 @@ pub struct TaskParams { pub blocked_signals: SigSet, /// The signals initially ignored; all other dispositions start as default. pub ignored_signals: SigSet, - /// Signals pending at start for the process, or for its main thread, as sent by the process - /// itself. - pub pending_signals: program_startup::PendingSignalSets, + /// Queued signals pending at start for the process or its main thread, with their `siginfo`. + pub pending_signals: program_startup::PendingSignalQueues, /// Descriptors inherited from the parent, or `None` to start with the standard streams. pub inherited_fds: Option>, /// The absolute working directory inherited from the parent, or `None` to start at `/`. diff --git a/litebox_common_linux/src/program_startup.rs b/litebox_common_linux/src/program_startup.rs index 6cb884fc80..abb58e2da0 100644 --- a/litebox_common_linux/src/program_startup.rs +++ b/litebox_common_linux/src/program_startup.rs @@ -17,15 +17,15 @@ use litebox_broker_protocol::socket::SocketType; use zerocopy::{FromBytes, IntoBytes}; use crate::GuestVectorState; -use crate::signal::{NSIG, SigAction, SigAltStack, SigSet}; +use crate::signal::{NSIG, SigAction, SigAltStack, SigSet, Siginfo, Signal}; use crate::vmem::VmFlags; use crate::{PtRegs, ResourceLimitValues, TASK_COMM_LEN}; #[cfg(target_arch = "aarch64")] use litebox::arch::aarch64::vector::SveVectorLength; const HEADER_SIZE: usize = size_of::() - + size_of::<[u32; 11]>() - + size_of::<[u64; 5]>() + + size_of::<[u32; 13]>() + + size_of::<[u64; 2]>() + size_of::() + size_of::() + if cfg!(target_arch = "aarch64") { @@ -90,7 +90,7 @@ pub struct LinuxProgramStartup { /// Signals whose ignored disposition survives `execve`. pub ignored_signals: SigSet, /// Signals pending at `execve`, which survive it. - pub pending_signals: PendingSignalSets, + pub pending_signals: PendingSignalQueues, /// File mode creation mask, with only permission bits set. pub umask: u32, /// Resource limits, which survive `execve`. @@ -117,16 +117,16 @@ pub struct LinuxProgramStartup { pub inherited_fds: Vec, } -/// Signals pending for a process that starts a program, as sent by the process itself. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub struct PendingSignalSets { +/// Queued signals pending for a process that starts a program, with each instance's `siginfo`. +/// +/// Each queue keeps the order of real-time instances and contains at most one instance of each +/// standard signal. Signal numbers must be valid Linux signals. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct PendingSignalQueues { /// Signals pending for the process, which any of its threads may take. - pub process: SigSet, + pub process: Vec, /// Signals pending for the thread that starts the program, which becomes its main thread. - pub thread: SigSet, - /// The pending signals, of either set, whose first queued instance lost its `siginfo`, as - /// a real-time signal does once `RLIMIT_SIGPENDING` is reached, so they have no sender. - pub without_sender: SigSet, + pub thread: Vec, } /// A descriptor inherited across `execve`, as Linux keeps every descriptor not marked @@ -333,9 +333,6 @@ impl LinuxProgramStartup { push_u32(&mut output, self.egid); push_u64(&mut output, self.blocked_signals.as_u64()); push_u64(&mut output, self.ignored_signals.as_u64()); - push_u64(&mut output, self.pending_signals.process.as_u64()); - push_u64(&mut output, self.pending_signals.thread.as_u64()); - push_u64(&mut output, self.pending_signals.without_sender.as_u64()); push_u32(&mut output, self.umask); output.extend_from_slice(self.resource_limits.as_bytes()); output.push(u8::from(self.no_new_privs)); @@ -366,6 +363,12 @@ impl LinuxProgramStartup { u32::try_from(self.inherited_fds.len()) .map_err(|_| LinuxProgramStartupError::TooLarge)?, ); + for queue in [&self.pending_signals.process, &self.pending_signals.thread] { + push_u32( + &mut output, + u32::try_from(queue.len()).map_err(|_| LinuxProgramStartupError::TooLarge)?, + ); + } output.extend_from_slice(self.path.as_bytes()); output.extend_from_slice(self.execfn.as_bytes()); output.extend_from_slice(self.cwd.as_bytes()); @@ -377,6 +380,14 @@ impl LinuxProgramStartup { ); output.extend_from_slice(value); } + for siginfo in self + .pending_signals + .process + .iter() + .chain(&self.pending_signals.thread) + { + output.extend_from_slice(siginfo.as_bytes()); + } for inherited in &self.inherited_fds { inherited.encode(&mut output); } @@ -399,11 +410,6 @@ impl LinuxProgramStartup { let effective_group_id = read_u32(&mut input)?; let blocked_signals = SigSet::from_u64(read_u64(&mut input)?); let ignored_signals = SigSet::from_u64(read_u64(&mut input)?); - let pending_signals = PendingSignalSets { - process: SigSet::from_u64(read_u64(&mut input)?), - thread: SigSet::from_u64(read_u64(&mut input)?), - without_sender: SigSet::from_u64(read_u64(&mut input)?), - }; let umask = read_u32(&mut input)?; let resource_limits = read_value(&mut input)?; let no_new_privs = read_bool(&mut input)?; @@ -421,6 +427,10 @@ impl LinuxProgramStartup { .map_err(|_| LinuxProgramStartupError::Malformed)?; let inherited_fd_count = usize::try_from(read_u32(&mut input)?) .map_err(|_| LinuxProgramStartupError::Malformed)?; + let process_signal_count = usize::try_from(read_u32(&mut input)?) + .map_err(|_| LinuxProgramStartupError::Malformed)?; + let thread_signal_count = usize::try_from(read_u32(&mut input)?) + .map_err(|_| LinuxProgramStartupError::Malformed)?; let path_bytes = take_bytes(&mut input, path_length)?; let path = core::str::from_utf8(path_bytes) .map_err(|_| LinuxProgramStartupError::InvalidPath)? @@ -450,6 +460,10 @@ impl LinuxProgramStartup { .map_err(|_| LinuxProgramStartupError::InvalidString)?, ); } + let pending_signals = PendingSignalQueues { + process: read_signals(&mut input, process_signal_count)?, + thread: read_signals(&mut input, thread_signal_count)?, + }; if inherited_fd_count > input.len() / INHERITED_FD_HEADER_SIZE { return Err(LinuxProgramStartupError::Malformed); } @@ -771,9 +785,19 @@ fn validate(startup: &LinuxProgramStartup) -> Result<(), LinuxProgramStartupErro if startup.umask & !0o777 != 0 { return Err(LinuxProgramStartupError::InvalidUmask); } - let pending = &startup.pending_signals; - if !(pending.without_sender & !(pending.process | pending.thread)).is_empty() { - return Err(LinuxProgramStartupError::Malformed); + for queue in [ + &startup.pending_signals.process, + &startup.pending_signals.thread, + ] { + let mut seen = SigSet::empty(); + for info in queue { + let signal = + Signal::try_from(info.signo).map_err(|_| LinuxProgramStartupError::Malformed)?; + if !signal.is_rt_signal() && seen.contains(signal) { + return Err(LinuxProgramStartupError::Malformed); + } + seen.add(signal); + } } validate_resource_limits(&startup.resource_limits) } @@ -819,6 +843,19 @@ fn encoded_len(startup: &LinuxProgramStartup) -> Result MAX_PROCESS_BOOTSTRAP_SIZE as usize { return Err(LinuxProgramStartupError::TooLarge); } + for queue in [ + &startup.pending_signals.process, + &startup.pending_signals.thread, + ] { + length = queue + .len() + .checked_mul(size_of::()) + .and_then(|queue_length| length.checked_add(queue_length)) + .ok_or(LinuxProgramStartupError::TooLarge)?; + if length > MAX_PROCESS_BOOTSTRAP_SIZE as usize { + return Err(LinuxProgramStartupError::TooLarge); + } + } for value in startup.argv.iter().chain(&startup.envp) { length = length .checked_add(size_of::()) @@ -843,6 +880,21 @@ fn push_u32(output: &mut Vec, value: u32) { output.extend_from_slice(&value.to_le_bytes()); } +fn read_signals(input: &mut &[u8], count: usize) -> Result, LinuxProgramStartupError> { + let length = count + .checked_mul(size_of::()) + .ok_or(LinuxProgramStartupError::Malformed)?; + let mut bytes = take_bytes(input, length)?; + let mut signals = Vec::new(); + signals + .try_reserve_exact(count) + .map_err(|_| LinuxProgramStartupError::TooLarge)?; + for _ in 0..count { + signals.push(read_value(&mut bytes)?); + } + Ok(signals) +} + fn push_u64(output: &mut Vec, value: u64) { output.extend_from_slice(&value.to_le_bytes()); } @@ -963,7 +1015,7 @@ fn take_bytes<'a>( #[cfg(test)] mod tests { use super::*; - use crate::signal::Signal; + use crate::signal::{SI_USER, SiginfoData}; use alloc::vec; fn resource_limits() -> ResourceLimitValues { @@ -973,6 +1025,79 @@ mod tests { }) } + fn siginfo(signal: Signal, pid: i32) -> Siginfo { + Siginfo { + signo: signal.as_i32(), + errno: 0, + code: SI_USER, + #[cfg(target_pointer_width = "64")] + __pad: 0, + data: SiginfoData::new_kill(pid, 1000), + } + } + + fn program_startup() -> LinuxProgramStartup { + LinuxProgramStartup { + uid: 0, + euid: 0, + gid: 0, + egid: 0, + blocked_signals: SigSet::empty(), + ignored_signals: SigSet::empty(), + pending_signals: PendingSignalQueues::default(), + umask: 0o022, + resource_limits: resource_limits(), + no_new_privs: false, + #[cfg(target_arch = "aarch64")] + sve_vl_inherit: false, + path: "/child".into(), + execfn: "/child".into(), + cwd: "/".into(), + argv: vec![CString::new("child").unwrap()], + envp: Vec::new(), + inherited_fds: Vec::new(), + } + } + + #[test] + fn program_startup_rejects_invalid_pending_signal_queues() { + let realtime = Signal::try_from(crate::signal::SIGRTMIN).unwrap(); + let mut startup = program_startup(); + startup.argv.clear(); + startup.pending_signals.process = vec![siginfo(realtime, 7), siginfo(realtime, 8)]; + let encoded = startup.encode().unwrap(); + let first_signal = + HEADER_SIZE + startup.path.len() + startup.execfn.len() + startup.cwd.len(); + for invalid_signal in [0_i32, 65] { + let mut invalid = encoded.clone(); + invalid[first_signal..first_signal + size_of::()] + .copy_from_slice(&invalid_signal.to_ne_bytes()); + assert_eq!( + LinuxProgramStartup::decode(&invalid), + Err(LinuxProgramStartupError::Malformed) + ); + } + let mut duplicates = encoded.clone(); + for offset in [first_signal, first_signal + size_of::()] { + duplicates[offset..offset + size_of::()] + .copy_from_slice(&Signal::SIGUSR1.as_i32().to_ne_bytes()); + } + assert_eq!( + LinuxProgramStartup::decode(&duplicates), + Err(LinuxProgramStartupError::Malformed) + ); + assert_eq!( + LinuxProgramStartup::decode(&encoded[..encoded.len() - 1]), + Err(LinuxProgramStartupError::Malformed) + ); + + startup.pending_signals.process = vec![siginfo(Signal::SIGUSR1, 7); 2]; + assert_eq!(startup.encode(), Err(LinuxProgramStartupError::Malformed)); + startup.pending_signals.process = + vec![siginfo(realtime, 7); MAX_PROCESS_BOOTSTRAP_SIZE as usize / size_of::()]; + assert_eq!(startup.encode(), Err(LinuxProgramStartupError::TooLarge)); + } + #[test] fn program_startup_round_trips() { let real_time = Signal::try_from(crate::signal::SIGRTMIN).unwrap(); @@ -983,10 +1108,14 @@ mod tests { egid: 1003, blocked_signals: SigSet::empty().with(Signal::SIGUSR1), ignored_signals: SigSet::empty().with(Signal::SIGPIPE), - pending_signals: PendingSignalSets { - process: SigSet::empty().with(Signal::SIGUSR1).with(real_time), - thread: SigSet::empty().with(Signal::SIGPIPE), - without_sender: SigSet::empty().with(real_time), + pending_signals: PendingSignalQueues { + process: vec![ + siginfo(Signal::SIGUSR1, 7), + siginfo(real_time, 0), + siginfo(real_time, 7), + siginfo(real_time, 8), + ], + thread: vec![siginfo(Signal::SIGPIPE, 7), siginfo(real_time, 9)], }, umask: 0o027, resource_limits: resource_limits(), @@ -1087,7 +1216,7 @@ mod tests { egid: 0, blocked_signals: SigSet::empty(), ignored_signals: SigSet::empty(), - pending_signals: PendingSignalSets::default(), + pending_signals: PendingSignalQueues::default(), umask: 0o022, resource_limits: resource_limits(), no_new_privs: false, @@ -1370,26 +1499,7 @@ mod tests { #[test] fn program_startup_rejects_trailing_and_invalid_strings() { - let startup = LinuxProgramStartup { - uid: 0, - euid: 0, - gid: 0, - egid: 0, - blocked_signals: SigSet::empty(), - ignored_signals: SigSet::empty(), - pending_signals: PendingSignalSets::default(), - umask: 0o022, - resource_limits: resource_limits(), - no_new_privs: false, - #[cfg(target_arch = "aarch64")] - sve_vl_inherit: false, - path: "/child".into(), - execfn: "/child".into(), - cwd: "/".into(), - argv: vec![CString::new("child").unwrap()], - envp: Vec::new(), - inherited_fds: Vec::new(), - }; + let startup = program_startup(); let mut encoded = startup.encode().unwrap(); encoded.push(0); assert_eq!( @@ -1418,19 +1528,18 @@ mod tests { Err(LinuxProgramStartupError::InvalidString) ); - // Mark `SIGHUP`, which is pending in neither set, as having no sender. - let mut stray_without_sender = startup.encode().unwrap(); - let without_sender = 1 + 4 * size_of::() + 4 * size_of::(); - assert_eq!(stray_without_sender[without_sender], 0); - stray_without_sender[without_sender] = 1; + // A signal count must fit within the remaining payload. + let mut oversized_signal_count = startup.encode().unwrap(); + oversized_signal_count[HEADER_SIZE - 2 * size_of::()..HEADER_SIZE - size_of::()] + .copy_from_slice(&u32::MAX.to_le_bytes()); assert_eq!( - LinuxProgramStartup::decode(&stray_without_sender), + LinuxProgramStartup::decode(&oversized_signal_count), Err(LinuxProgramStartupError::Malformed) ); // Raise the soft limit of resource 1 above its hard limit of 1. let mut soft_above_hard = startup.encode().unwrap(); - let limits = 1 + 4 * size_of::() + 5 * size_of::() + size_of::(); + let limits = 1 + 4 * size_of::() + 2 * size_of::() + size_of::(); let soft_limit = limits + size_of::(); assert_eq!(soft_above_hard[soft_limit], 1); soft_above_hard[soft_limit] = 2; diff --git a/litebox_common_linux/src/signal/mod.rs b/litebox_common_linux/src/signal/mod.rs index 68e1dd632e..f431bc8908 100644 --- a/litebox_common_linux/src/signal/mod.rs +++ b/litebox_common_linux/src/signal/mod.rs @@ -357,7 +357,7 @@ pub struct Ucontext { } #[repr(C)] -#[derive(Clone, FromBytes, IntoBytes, Immutable)] +#[derive(Clone, Debug, PartialEq, Eq, FromBytes, IntoBytes, Immutable)] pub struct Siginfo { pub signo: i32, pub errno: i32, @@ -369,7 +369,7 @@ pub struct Siginfo { } #[repr(C, packed)] -#[derive(Clone, Copy, FromBytes, IntoBytes, Immutable)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, FromBytes, IntoBytes, Immutable)] pub struct SiginfoData { pub pad: [u32; 28], } diff --git a/litebox_runner_linux_on_macos_userland/src/lib.rs b/litebox_runner_linux_on_macos_userland/src/lib.rs index 32948a7b69..22b1f481c2 100644 --- a/litebox_runner_linux_on_macos_userland/src/lib.rs +++ b/litebox_runner_linux_on_macos_userland/src/lib.rs @@ -105,7 +105,7 @@ pub fn run(cli_args: CliArgs) -> Result { blocked_signals: litebox_common_linux::signal::SigSet::empty(), ignored_signals: litebox_common_linux::signal::SigSet::empty(), pending_signals: - litebox_common_linux::program_startup::PendingSignalSets::default(), + litebox_common_linux::program_startup::PendingSignalQueues::default(), inherited_fds: None, cwd: None, umask: None, diff --git a/litebox_runner_linux_on_vm_userland/src/linux.rs b/litebox_runner_linux_on_vm_userland/src/linux.rs index d9b0fcbba6..348bda70e9 100644 --- a/litebox_runner_linux_on_vm_userland/src/linux.rs +++ b/litebox_runner_linux_on_vm_userland/src/linux.rs @@ -143,7 +143,7 @@ fn serve_requests( egid: GUEST_GID, blocked_signals: litebox_common_linux::signal::SigSet::empty(), ignored_signals: litebox_common_linux::signal::SigSet::empty(), - pending_signals: litebox_common_linux::program_startup::PendingSignalSets::default(), + pending_signals: litebox_common_linux::program_startup::PendingSignalQueues::default(), inherited_fds: None, cwd: None, umask: None, diff --git a/litebox_runner_linux_on_windows_userland/src/lib.rs b/litebox_runner_linux_on_windows_userland/src/lib.rs index 21aafd7b8e..5bbccff120 100644 --- a/litebox_runner_linux_on_windows_userland/src/lib.rs +++ b/litebox_runner_linux_on_windows_userland/src/lib.rs @@ -326,7 +326,7 @@ pub fn run(cli_args: CliArgs) -> Result<()> { blocked_signals: litebox_common_linux::signal::SigSet::empty(), ignored_signals: litebox_common_linux::signal::SigSet::empty(), pending_signals: - litebox_common_linux::program_startup::PendingSignalSets::default(), + litebox_common_linux::program_startup::PendingSignalQueues::default(), inherited_fds: None, cwd: None, umask: None, diff --git a/litebox_runner_linux_userland/src/lib.rs b/litebox_runner_linux_userland/src/lib.rs index d8452ff9b2..f8f3fec2f0 100644 --- a/litebox_runner_linux_userland/src/lib.rs +++ b/litebox_runner_linux_userland/src/lib.rs @@ -15,7 +15,7 @@ use std::sync::Arc; use litebox_broker_local_userland as broker; use litebox_broker_transport_linux_userland::existing_runner::ExistingRunnerDescriptor; use litebox_common_linux::program_startup::{ - LinuxForkStartup, LinuxProcessStartup, LinuxProgramStartup, PendingSignalSets, + LinuxForkStartup, LinuxProcessStartup, LinuxProgramStartup, PendingSignalQueues, }; use litebox_common_linux::signal::{SigSet, Signal}; @@ -546,7 +546,7 @@ fn run_with_seccomp(cli_args: CliArgs, seccomp_scope: SeccompScope) -> Result 4) { diff --git a/litebox_runner_linux_userland/tests/vfork_signal_parent.c b/litebox_runner_linux_userland/tests/vfork_signal_parent.c index 3fafabcd0d..a14196cb70 100644 --- a/litebox_runner_linux_userland/tests/vfork_signal_parent.c +++ b/litebox_runner_linux_userland/tests/vfork_signal_parent.c @@ -194,7 +194,8 @@ int main(int argc, char **argv) { struct rlimit no_queue = {.rlim_cur = 0, .rlim_max = sigpending_limit.rlim_max}; if (sigprocmask(SIG_BLOCK, &carried, NULL) != 0 || kill(getpid(), SIGUSR1) != 0 || kill(getpid(), SIGPIPE) != 0 || setrlimit(RLIMIT_SIGPENDING, &no_queue) != 0 || - kill(getpid(), SIGRTMIN) != 0 || setrlimit(RLIMIT_SIGPENDING, &sigpending_limit) != 0) { + kill(getpid(), SIGRTMIN) != 0 || setrlimit(RLIMIT_SIGPENDING, &sigpending_limit) != 0 || + kill(getpid(), SIGRTMIN) != 0 || kill(getpid(), SIGRTMIN) != 0) { _exit(113); } // Ignoring SIGPIPE discards the pending one, and the broken pipe raises another for this diff --git a/litebox_shim_linux/src/lib.rs b/litebox_shim_linux/src/lib.rs index 5c006dbc35..8117d11543 100644 --- a/litebox_shim_linux/src/lib.rs +++ b/litebox_shim_linux/src/lib.rs @@ -561,8 +561,6 @@ impl LinuxShim { blocked_signals, ignored_signals, pending_signals, - pid, - uid, ); let entrypoints = crate::LinuxShimEntrypoints { _not_send: core::marker::PhantomData, diff --git a/litebox_shim_linux/src/syscalls/process.rs b/litebox_shim_linux/src/syscalls/process.rs index 2431103ca7..91460142f1 100644 --- a/litebox_shim_linux/src/syscalls/process.rs +++ b/litebox_shim_linux/src/syscalls/process.rs @@ -5618,9 +5618,7 @@ mod tests { SignalState::::inherited( requested, SigSet::empty(), - litebox_common_linux::program_startup::PendingSignalSets::default(), - 1, - 0, + litebox_common_linux::program_startup::PendingSignalQueues::default(), ) .blocked(), expected diff --git a/litebox_shim_linux/src/syscalls/signal/mod.rs b/litebox_shim_linux/src/syscalls/signal/mod.rs index f54d05130c..5f251ffcb2 100644 --- a/litebox_shim_linux/src/syscalls/signal/mod.rs +++ b/litebox_shim_linux/src/syscalls/signal/mod.rs @@ -29,7 +29,7 @@ use litebox::{shim::Exception, sync::Mutex, utils::ReinterpretUnsignedExt as _}; use litebox_broker_protocol::process::{CpuTime, ProcessExitStatus}; use litebox_broker_protocol::signal::SignalTarget; use litebox_broker_protocol::{ProcessGroupId, ProcessId}; -use litebox_common_linux::program_startup::PendingSignalSets; +use litebox_common_linux::program_startup::PendingSignalQueues; use litebox_common_linux::signal::{ BUS_ADRERR, CLD_EXITED, CLD_KILLED, FPE_INTDIV, ILL_ILLOPN, MINSIGSTKSZ, NSIG, SI_KERNEL, SI_TKILL, SI_USER, SIG_DFL, SIG_IGN, SaFlags, SigAction, SigAltStack, SigSet, Siginfo, @@ -128,15 +128,8 @@ impl SignalState { /// Returns the initial signal state of a process that inherits the `blocked` mask, `ignored` /// dispositions, and `pending` signals, as a program started by `execve` in a fresh runner - /// keeps them like [`Self::reset_for_exec`]. Process `pid` of user `uid` sent itself the - /// pending signals. - pub fn inherited( - blocked: SigSet, - ignored: SigSet, - pending: PendingSignalSets, - pid: i32, - uid: u32, - ) -> Self { + /// keeps them like [`Self::reset_for_exec`]. + pub fn inherited(blocked: SigSet, ignored: SigSet, pending: PendingSignalQueues) -> Self { let mut state = Self::new_process(); state.set_signal_mask(blocked); let handlers = Arc::get_mut(state.handlers.get_mut()) @@ -150,16 +143,16 @@ impl SignalState { handler.action.sigaction = SIG_IGN; } } - let restore = |queue: &Mutex, signals: SigSet| { + let restore = |queue: &Mutex, + signals: alloc::vec::Vec| { let mut queue = queue.lock(); - for signal in signals { - let siginfo = if pending.without_sender.contains(signal) { - siginfo_kill(signal) - } else { - siginfo_kill_from(signal, pid, uid) - }; + for siginfo in signals { + let signal = Signal::try_from(siginfo.signo) + .expect("startup pending signal numbers are validated"); // The signals were already pending, so no limit applies. - let _ = queue.push(usize::MAX, signal, siginfo); + queue + .push(usize::MAX, signal, siginfo) + .expect("restoring pending signals has no queue limit"); } }; restore(&state.shared_pending, pending.process); @@ -264,18 +257,17 @@ impl SignalState { self.last_exception.set(last_exception); } - /// Returns the signals pending for the `vfork` child, which a program it starts keeps. - pub(crate) fn vfork_child_pending_signals(&self) -> PendingSignalSets { + /// Returns the `vfork` child's pending signals to preserve across `execve`. + pub(crate) fn vfork_child_pending_signals(&self) -> PendingSignalQueues { let thread_pending = self.pending.borrow(); let thread_pending = thread_pending.lock(); let shared_pending = self.vfork_child_shared_pending.borrow(); let shared_pending = shared_pending .as_ref() .expect("only a vfork child has its own process signals"); - PendingSignalSets { - process: shared_pending.pending, - thread: thread_pending.pending, - without_sender: shared_pending.without_sender() | thread_pending.without_sender(), + PendingSignalQueues { + process: shared_pending.queue.iter().cloned().collect(), + thread: thread_pending.queue.iter().cloned().collect(), } } } @@ -454,23 +446,6 @@ impl PendingSignals { Some((signal, self.remove(signal))) } - /// Returns the pending signals whose first queued instance lost its `siginfo` in - /// [`Self::push`], so it has no sender. - fn without_sender(&self) -> SigSet { - let mut without_sender = SigSet::empty(); - for signal in self.pending { - let first = self - .queue - .iter() - .find(|info| info.signo == signal.as_i32()) - .expect("pending signals are queued"); - if first.code == SI_USER && first.data.pid() == 0 { - without_sender.add(signal); - } - } - without_sender - } - /// Discards every queued instance of `signal`. pub(super) fn discard(&mut self, signal: Signal) { #[cfg(test)] @@ -1234,9 +1209,9 @@ impl Task { pub(crate) fn sys_kill(&self, pid: i32, signal: i32) -> Result { let signal = signal_or_probe(signal)?; - // A `vfork` child's requests go to the broker as its parent's, which would signal other - // targets from the parent, so the child may signal only itself. Its ID can equal the - // parent's in a new PID namespace, so it is checked first. + // The shared LiteBox instance retains the parent's process identity during `vfork`, so + // the child can only signal itself locally. Check the child first: its ID can equal the + // parent's in a new PID namespace. if self.vfork.borrow().is_some() { if pid != self.sys_getpid() { log_unsupported!("kill({pid}) in a vfork child"); @@ -1893,6 +1868,69 @@ mod tests { assert_eq!(queued(), 3); } + #[test] + fn vfork_pending_signal_queues_survive_exec() { + let task = crate::syscalls::tests::init_platform(); + let realtime = Signal::try_from(litebox_common_linux::signal::SIGRTMIN).unwrap(); + let blocked = SigSet::empty().with(realtime).with(Signal::SIGUSR1); + task.signals.set_signal_mask(blocked); + let parent_info = siginfo_kill_from(Signal::SIGUSR1, 5, 1000); + task.send_signal(Signal::SIGUSR1, parent_info.clone()); + let parent = task.signals.begin_vfork_child(false); + + let child_info = siginfo_kill_from(realtime, 7, 1000); + { + let mut shared = task.signals.vfork_child_shared_pending.borrow_mut(); + let shared = shared.as_mut().unwrap(); + shared.push(0, realtime, child_info.clone()).unwrap(); + shared + .push(usize::MAX, realtime, child_info.clone()) + .unwrap(); + shared + .push(usize::MAX, realtime, child_info.clone()) + .unwrap(); + } + let mut thread_info = child_info; + thread_info.code = SI_TKILL; + task.signals + .pending + .borrow() + .lock() + .push(usize::MAX, realtime, thread_info) + .unwrap(); + + let pending = task.signals.vfork_child_pending_signals(); + assert_eq!(pending.process.len(), 3); + assert_eq!(pending.thread.len(), 1); + assert_eq!(pending.process[0].data.pid(), 0); + assert_eq!(pending.thread[0].data.pid(), 7); + let restored = SignalState::::inherited( + blocked, + SigSet::empty(), + pending.clone(), + ); + assert_eq!(restored.blocked(), blocked); + for (queue, expected) in [ + (restored.shared_pending.clone(), pending.process), + (restored.active_pending_queue(), pending.thread), + ] { + let mut queue = queue.lock(); + for info in expected { + assert_eq!(queue.take_next(SigSet::empty()), Some((realtime, info))); + } + assert!(queue.take_next(SigSet::empty()).is_none()); + } + task.signals.restore_vfork_parent(parent); + assert_eq!( + task.signals + .pending + .borrow() + .lock() + .take_next(SigSet::empty()), + Some((Signal::SIGUSR1, parent_info)) + ); + } + #[test] fn vfork_and_parent_disposition_changes_discard_separate_private_queues() { let task = crate::syscalls::tests::init_platform();