diff --git a/litebox_common_linux/src/lib.rs b/litebox_common_linux/src/lib.rs index 15e2c1858f..55c6ee3dfc 100644 --- a/litebox_common_linux/src/lib.rs +++ b/litebox_common_linux/src/lib.rs @@ -1972,6 +1972,8 @@ pub struct TaskParams { pub blocked_signals: SigSet, /// The signals initially ignored; all other dispositions start as default. pub ignored_signals: SigSet, + /// 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 73f89f5387..abb58e2da0 100644 --- a/litebox_common_linux/src/program_startup.rs +++ b/litebox_common_linux/src/program_startup.rs @@ -17,14 +17,14 @@ 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::<[u32; 13]>() + size_of::<[u64; 2]>() + size_of::() + size_of::() @@ -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: PendingSignalQueues, /// 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, } +/// 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: Vec, + /// Signals pending for the thread that starts the program, which becomes its main thread. + pub thread: Vec, +} + /// A descriptor inherited across `execve`, as Linux keeps every descriptor not marked /// close-on-exec. /// @@ -349,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()); @@ -360,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,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)? @@ -428,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); } @@ -449,6 +485,7 @@ impl LinuxProgramStartup { egid: effective_group_id, blocked_signals, ignored_signals, + pending_signals, umask, resource_limits, no_new_privs, @@ -748,6 +785,20 @@ fn validate(startup: &LinuxProgramStartup) -> Result<(), LinuxProgramStartupErro if startup.umask & !0o777 != 0 { return Err(LinuxProgramStartupError::InvalidUmask); } + 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) } @@ -792,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::()) @@ -816,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()); } @@ -936,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 { @@ -946,8 +1025,82 @@ 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(); let startup = LinuxProgramStartup { uid: 1000, euid: 1001, @@ -955,6 +1108,15 @@ mod tests { egid: 1003, blocked_signals: SigSet::empty().with(Signal::SIGUSR1), ignored_signals: SigSet::empty().with(Signal::SIGPIPE), + 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(), no_new_privs: true, @@ -1054,6 +1216,7 @@ mod tests { egid: 0, blocked_signals: SigSet::empty(), ignored_signals: SigSet::empty(), + pending_signals: PendingSignalQueues::default(), umask: 0o022, resource_limits: resource_limits(), no_new_privs: false, @@ -1336,25 +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(), - 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!( @@ -1383,6 +1528,15 @@ mod tests { Err(LinuxProgramStartupError::InvalidString) ); + // 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(&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::() + 2 * size_of::() + size_of::(); diff --git a/litebox_common_linux/src/signal/mod.rs b/litebox_common_linux/src/signal/mod.rs index a7d0af072e..f431bc8908 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); @@ -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 b066da18aa..22b1f481c2 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::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 c99b9fdac4..348bda70e9 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::PendingSignalQueues::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..5bbccff120 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::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 1d715ef8bd..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, + LinuxForkStartup, LinuxProcessStartup, LinuxProgramStartup, PendingSignalQueues, }; use litebox_common_linux::signal::{SigSet, Signal}; @@ -472,6 +472,7 @@ fn run_with_seccomp(cli_args: CliArgs, seccomp_scope: SeccompScope) -> Result Result Result 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..28227a5992 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); @@ -743,6 +756,15 @@ fn vfork_child_has_its_own_signal_state() { assert_eq!(numeric_field(child_line, "ill_default="), 1); assert_eq!(numeric_field(child_line, "term_blocked="), 1); assert_eq!(numeric_field(child_line, "usr2_blocked="), 0); + // Like Linux, the signals pending for the child, but not the parent's, survive `execve`, each + // for the process or the thread it was pending for, and with its sender, if it had one. + assert_eq!(numeric_field(child_line, "usr1_pending="), 1); + assert_eq!(numeric_field(child_line, "term_pending="), 0); + assert_eq!(numeric_field(child_line, "usr1_from_self="), 1); + assert_eq!(numeric_field(child_line, "pipe_from_worker="), 0); + assert_eq!(numeric_field(child_line, "pipe_from_main="), 1); + assert_eq!(numeric_field(child_line, "rt_without_sender="), 1); + assert_eq!(numeric_field(child_line, "rt_from_self="), 2); } #[cfg(target_os = "linux")] @@ -1022,6 +1044,18 @@ fn clone_vfork_children_start_like_vfork_children() { assert_eq!(numeric_field(child_line, "usr2_default="), 1); assert_eq!(numeric_field(child_line, "term_blocked="), 1); assert_eq!(numeric_field(child_line, "usr2_blocked="), 0); + // The spawned child has no pending signals. + for field in [ + "usr1_pending=", + "term_pending=", + "usr1_from_self=", + "pipe_from_worker=", + "pipe_from_main=", + "rt_without_sender=", + "rt_from_self=", + ] { + assert_eq!(numeric_field(child_line, field), 0, "{field}"); + } let missing_line = line("missing "); assert_eq!(numeric_field(missing_line, "ret="), libc::ENOENT); diff --git a/litebox_runner_linux_userland/tests/vfork_exec_child.c b/litebox_runner_linux_userland/tests/vfork_exec_child.c index 23147df13e..5926aa1fb6 100644 --- a/litebox_runner_linux_userland/tests/vfork_exec_child.c +++ b/litebox_runner_linux_userland/tests/vfork_exec_child.c @@ -5,6 +5,7 @@ #include #include #include +#include #include #include #include @@ -33,6 +34,28 @@ static void on_usr1(int signal, siginfo_t *info, void *context) { usr1_uid_matches = info->si_uid == getuid(); } +// Takes `signal` if it is pending for this thread or its process, without waiting, storing its +// siginfo at `info`. +static int take_now(int signal, siginfo_t *info) { + static const struct timespec no_wait; + sigset_t set; + sigemptyset(&set); + sigaddset(&set, signal); + return sigtimedwait(&set, info, &no_wait); +} + +static int usr1_from_self; +static int pipe_from_worker; + +// Runs in a thread other than the one that started the program. +static void *take_from_worker(void *unused) { + siginfo_t info; + usr1_from_self = take_now(SIGUSR1, &info) == SIGUSR1 && info.si_code == SI_USER && + info.si_pid == getpid(); + pipe_from_worker = !(take_now(SIGPIPE, &info) == -1 && errno == EAGAIN); + return unused; +} + // Returns whether a child exiting with `code` is reaped automatically instead of being waitable. static int child_is_reaped(int code) { pid_t child = vfork(); @@ -102,12 +125,37 @@ int main(int argc, char **argv) { } if (strcmp(marker, "signals") == 0) { sigset_t blocked; + sigset_t pending; sigprocmask(SIG_BLOCK, NULL, &blocked); + sigpending(&pending); + // A signal pending for the process reaches any thread, and one pending for the thread + // that called `execve` only the main thread. + pthread_t worker; + if (pthread_create(&worker, NULL, take_from_worker, NULL) != 0 || + pthread_join(worker, NULL) != 0) { + return 6; + } + siginfo_t info; + int pipe_from_main = take_now(SIGPIPE, &info) == SIGPIPE; + int rt_without_sender = + take_now(SIGRTMIN, &info) == SIGRTMIN && info.si_code == SI_USER && info.si_pid == 0; + int rt_from_self = 0; + for (int i = 0; i < 2; i++) { + rt_from_self += take_now(SIGRTMIN, &info) == SIGRTMIN && info.si_code == SI_USER && + info.si_pid == getpid() && info.si_uid == getuid(); + } + if (take_now(SIGRTMIN, &info) != -1 || errno != EAGAIN) { + rt_from_self = -1; + } printf("child-signals pipe_ignored=%d hup_ignored=%d usr2_default=%d " - "ill_default=%d term_blocked=%d usr2_blocked=%d\n", + "ill_default=%d term_blocked=%d usr2_blocked=%d usr1_pending=%d term_pending=%d " + "usr1_from_self=%d pipe_from_worker=%d pipe_from_main=%d rt_without_sender=%d " + "rt_from_self=%d\n", disposition_is(SIGPIPE, SIG_IGN), disposition_is(SIGHUP, SIG_IGN), disposition_is(SIGUSR2, SIG_DFL), disposition_is(SIGILL, SIG_DFL), - sigismember(&blocked, SIGTERM), sigismember(&blocked, SIGUSR2)); + sigismember(&blocked, SIGTERM), sigismember(&blocked, SIGUSR2), + sigismember(&pending, SIGUSR1), sigismember(&pending, SIGTERM), usr1_from_self, + pipe_from_worker, pipe_from_main, rt_without_sender, rt_from_self); return 42; } if (strcmp(marker, "fds") == 0 && argc > 4) { diff --git a/litebox_runner_linux_userland/tests/vfork_signal_parent.c b/litebox_runner_linux_userland/tests/vfork_signal_parent.c index b752398faa..a14196cb70 100644 --- a/litebox_runner_linux_userland/tests/vfork_signal_parent.c +++ b/litebox_runner_linux_userland/tests/vfork_signal_parent.c @@ -2,9 +2,11 @@ // Licensed under the MIT license. #define _GNU_SOURCE +#include #include #include #include +#include #include #include #include @@ -137,9 +139,44 @@ int main(int argc, char **argv) { printf("sigpipe child=%d waited=%d code=%d sender=%d\n", pipe_child, waited, WEXITSTATUS(status), pipe_sender); - // The child changes its own signal state before exec. + // 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, 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. @@ -147,6 +184,26 @@ 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 || + kill(getpid(), SIGRTMIN) != 0 || kill(getpid(), SIGRTMIN) != 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); } @@ -154,6 +211,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 84158837d8..8117d11543 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,11 @@ 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, + ); let entrypoints = crate::LinuxShimEntrypoints { _not_send: core::marker::PhantomData, task: Task { @@ -1040,6 +1045,7 @@ impl Task { | PrctlArg::GetNoNewPrivs | PrctlArg::SetNoNewPrivs, } + | SyscallRequest::Kill { .. } | SyscallRequest::RtSigaction { .. } | SyscallRequest::RtSigprocmask { .. } | SyscallRequest::RtSigreturn diff --git a/litebox_shim_linux/src/syscalls/process.rs b/litebox_shim_linux/src/syscalls/process.rs index d478e2eb24..91460142f1 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,8 @@ mod tests { assert_eq!( SignalState::::inherited( requested, - SigSet::empty() + SigSet::empty(), + 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 9357a9bb8c..5f251ffcb2 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::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, @@ -42,6 +43,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 +62,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 +93,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 @@ -120,10 +126,10 @@ 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`]. + 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()) @@ -137,6 +143,20 @@ impl SignalState { handler.action.sigaction = SIG_IGN; } } + let restore = |queue: &Mutex, + signals: alloc::vec::Vec| { + let mut queue = queue.lock(); + 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. + queue + .push(usize::MAX, signal, siginfo) + .expect("restoring pending signals has no queue limit"); + } + }; + restore(&state.shared_pending, pending.process); + restore(&state.pending.borrow(), pending.thread); state } @@ -197,10 +217,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 +228,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 +248,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); @@ -233,6 +256,20 @@ impl SignalState { self.altstack.set(altstack); self.last_exception.set(last_exception); } + + /// 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"); + PendingSignalQueues { + process: shared_pending.queue.iter().cloned().collect(), + thread: thread_pending.queue.iter().cloned().collect(), + } + } } /// The signal state of a suspended `vfork` parent. @@ -1002,11 +1039,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 +1172,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 +1209,19 @@ impl Task { pub(crate) fn sys_kill(&self, pid: i32, signal: i32) -> Result { let signal = signal_or_probe(signal)?; + // 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"); + 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 +1364,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 +1668,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 { @@ -1794,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();