diff --git a/kernel/kernel_core/fork.rs b/kernel/kernel_core/fork.rs index 6c875a9..88688b1 100644 --- a/kernel/kernel_core/fork.rs +++ b/kernel/kernel_core/fork.rs @@ -768,6 +768,8 @@ fn fork_prepare_child_state( // are preserved even before any custom signal handler is installed. child.sigactions.copy_from(&parent.sigactions); child.blocked = parent.blocked; + // N2.6a: POSIX/Linux fork(2) inherits the parent's alternate signal stack. + child.sigaltstack = parent.sigaltstack; // 克隆能力表(尊重 CLOFORK 标志) // diff --git a/kernel/kernel_core/process.rs b/kernel/kernel_core/process.rs index 6d5bd81..38a59f7 100644 --- a/kernel/kernel_core/process.rs +++ b/kernel/kernel_core/process.rs @@ -2784,6 +2784,10 @@ pub struct ThreadGroup { /// G7: process-directed pending signals (one bit per signal), visible to /// every member. Members claim a bit into their own set before delivery. shared_pending: AtomicU64, + /// N2.6a: bounded FIFO queue of process-directed signal payloads (RT signals + /// 32..=64 queue multiple instances; standard signals store at most one). + /// Leaf lock ordered after PCB lock; IRQ paths use `try_lock()` only. + shared_rt_sigqueue: Mutex, /// G8: members that have not begun exiting. Each task leaves exactly once /// (`Process.group_live`); the task that takes it to zero is the group's /// last live member and runs the process-wide exit work (namespace-init @@ -2821,6 +2825,7 @@ impl ThreadGroup { members: AtomicUsize::new(1), parent_notified: AtomicBool::new(false), shared_pending: AtomicU64::new(0), + shared_rt_sigqueue: Mutex::new(crate::signal::RtSigQueue::new()), live: AtomicUsize::new(1), child_events: AtomicU64::new(0), child_waiters: AtomicUsize::new(0), @@ -2877,6 +2882,82 @@ impl ThreadGroup { self.shared_pending.fetch_and(!bit, Ordering::AcqRel) & bit != 0 } + /// N2.6a: enqueue a process-directed signal with optional `SigInfo` payload. + /// Real-time signals (`32..=64`) queue FIFO up to `MAX_QUEUED_RT_SIGNALS`; + /// standard signals store a single coalesced payload if not already pending. + pub(crate) fn queue_shared_info( + &self, + signal: crate::signal::Signal, + info: Option, + fail_on_full: bool, + ) -> Result<(), crate::signal::SignalError> { + let mut q = self.shared_rt_sigqueue.lock(); + if let Some(si) = info { + if signal.is_realtime() { + if q.push(si).is_err() && fail_on_full { + return Err(crate::signal::SignalError::QueueFull); + } + } else if (self.shared_pending.load(Ordering::Acquire) & signal.bit()) == 0 + && !q.has_signal(signal) + { + let _ = q.push(si); + } + } + self.shared_pending.fetch_or(signal.bit(), Ordering::AcqRel); + Ok(()) + } + + /// N2.6a: claim one instance of `signal` (and its oldest queued `SigInfo`, + /// if any) from the group set. Keeps the bit set in `shared_pending` if + /// additional RT instances remain queued. + pub(crate) fn claim_shared_with_info( + &self, + signal: crate::signal::Signal, + ) -> Option> { + let mut q = self.shared_rt_sigqueue.lock(); + if (self.shared_pending.load(Ordering::Acquire) & signal.bit()) == 0 { + return None; + } + let info = q.pop(signal); + if !q.has_signal(signal) { + self.shared_pending + .fetch_and(!signal.bit(), Ordering::AcqRel); + } + Some(info) + } + + /// N2.6a: IRQ-safe non-blocking variant of [`claim_shared_with_info`]. + pub(crate) fn try_claim_shared_with_info_irq( + &self, + signal: crate::signal::Signal, + ) -> Option> { + let mut q = self.shared_rt_sigqueue.try_lock()?; + if (self.shared_pending.load(Ordering::Acquire) & signal.bit()) == 0 { + return None; + } + let info = q.pop(signal); + if !q.has_signal(signal) { + self.shared_pending + .fetch_and(!signal.bit(), Ordering::AcqRel); + } + Some(info) + } + + /// N2.6a: discard all queued instances of `signal` from the group set. + pub(crate) fn discard_shared_signal(&self, signal: crate::signal::Signal) { + let mut q = self.shared_rt_sigqueue.lock(); + q.remove_all(signal); + self.shared_pending + .fetch_and(!signal.bit(), Ordering::AcqRel); + } + + /// N2.6a: return claimed group entries matching `mask` back to the group. + pub(crate) fn return_shared_entries(&self, mask: u64, src: &mut crate::signal::RtSigQueue) { + let mut q = self.shared_rt_sigqueue.lock(); + src.drain_mask_into(mask, &mut q); + self.shared_pending.fetch_or(mask, Ordering::AcqRel); + } + /// Tasks of this group currently in PROCESS_TABLE. pub fn members(&self) -> usize { self.members.load(Ordering::Acquire) @@ -3048,6 +3129,14 @@ pub struct Process { /// `saved_blocked`. pub poll_restore_blocked: Option, + /// N2.6a: per-task alternate signal stack (`sigaltstack(2)`). Inherited on + /// `fork`, disabled on `clone(CLONE_VM)` (without `CLONE_VFORK`) and `execve`. + pub sigaltstack: crate::signal::SigAltStack, + + /// N2.6a: bounded FIFO queue of per-task / claimed pending signal payloads. + /// Born empty; not inherited on fork/clone; preserved across execve. + pub rt_sigqueue: crate::signal::RtSigQueue, + /// 进程优先级(静态优先级) pub priority: Priority, @@ -4019,6 +4108,8 @@ impl Process { saved_frame_owner: _, in_signal_handler: _, poll_restore_blocked: _, + sigaltstack: _, + rt_sigqueue: _, priority: _, dynamic_priority: _, base_dynamic_priority: _, @@ -4127,6 +4218,9 @@ impl Process { addr_of_mut!((*dst).in_signal_handler).write(false); // M0-6 poll/select: no pending ppoll/pselect6 sigmask restore at birth. addr_of_mut!((*dst).poll_restore_blocked).write(None); + // N2.6a: alternate signal stack disabled and RT queue empty at birth. + addr_of_mut!((*dst).sigaltstack).write(crate::signal::SigAltStack::disabled()); + addr_of_mut!((*dst).rt_sigqueue).write(crate::signal::RtSigQueue::new()); addr_of_mut!((*dst).priority).write(priority); addr_of_mut!((*dst).dynamic_priority).write(priority); addr_of_mut!((*dst).base_dynamic_priority).write(priority); // E.4 PI: starts same as dynamic_priority @@ -4961,7 +5055,10 @@ impl Process { if self.pending_signals.is_pending(signal) { return true; } - if self.thread_group.claim_shared(signal.bit()) { + if let Some(info) = self.thread_group.claim_shared_with_info(signal) { + if let Some(si) = info { + let _ = self.rt_sigqueue.push(si); + } self.pending_signals.set(signal); self.group_claimed |= signal.bit(); return true; @@ -4969,11 +5066,36 @@ impl Process { false } + /// N2.6a: IRQ-safe non-blocking variant of [`claim_pending`]. + pub(crate) fn try_claim_pending_irq(&mut self, signal: crate::signal::Signal) -> bool { + if self.pending_signals.is_pending(signal) { + return true; + } + if let Some(info) = self.thread_group.try_claim_shared_with_info_irq(signal) { + if let Some(si) = info { + let _ = self.rt_sigqueue.push_no_alloc(si); + } + self.pending_signals.set(signal); + self.group_claimed |= signal.bit(); + return true; + } + false + } + + /// N2.6a: peek the oldest queued `SigInfo` for `signal` in this task's own + /// queue (synthesizing default `SI_USER` metadata if none was queued). + pub(crate) fn peek_own_siginfo(&self, signal: crate::signal::Signal) -> crate::signal::SigInfo { + self.rt_sigqueue + .peek(signal) + .unwrap_or_else(|| crate::signal::SigInfo::default_for(signal)) + } + /// GAP-5 G7: drop `signal` from this task's own set and its group's set. pub(crate) fn discard_pending(&mut self, signal: crate::signal::Signal) { + self.rt_sigqueue.remove_all(signal); self.pending_signals.clear(signal); self.group_claimed &= !signal.bit(); - self.thread_group.discard_shared(signal.bit()); + self.thread_group.discard_shared_signal(signal); } /// GAP-5 G7: the pending set that interrupts this task's waits: its own @@ -4982,11 +5104,40 @@ impl Process { self.pending_signals.bits() | (self.thread_group.shared_pending() & self.shared_chosen) } - /// GAP-5 G7: this task delivered or consumed `signal`; it is no longer - /// pending here and no longer a claimed group signal to hand back. - pub(crate) fn consume_own_pending(&mut self, signal: crate::signal::Signal) { - self.pending_signals.clear(signal); - self.group_claimed &= !signal.bit(); + /// GAP-5 G7 + N2.6a: this task delivered or consumed ONE instance of `signal`. + /// Returns its `SigInfo`. If additional queued instances of `signal` remain + /// in `rt_sigqueue` (RT signals 32..=64), keeps the pending bit set for the + /// next delivery in FIFO order. + pub(crate) fn consume_own_pending( + &mut self, + signal: crate::signal::Signal, + ) -> crate::signal::SigInfo { + let info = self + .rt_sigqueue + .pop(signal) + .unwrap_or_else(|| crate::signal::SigInfo::default_for(signal)); + if !self.rt_sigqueue.has_signal(signal) { + self.pending_signals.clear(signal); + self.group_claimed &= !signal.bit(); + } + info + } + + /// N2.6a: atomically dequeue one pending signal matching `mask` (regardless + /// of whether it is currently blocked) for `rt_sigtimedwait(2)`. + pub(crate) fn take_pending_for_sigwait( + &mut self, + mask: u64, + ) -> Option<(crate::signal::Signal, crate::signal::SigInfo)> { + let mut candidates = self.pending_bits() & mask; + while let Some(sig) = crate::signal::select_lowest_deliverable(candidates) { + candidates &= !sig.bit(); + if self.claim_pending(sig) { + let info = self.consume_own_pending(sig); + return Some((sig, info)); + } + } + None } /// GAP-5 G7 (review D3, Linux `recalc_sigpending` with @@ -5026,7 +5177,8 @@ impl Process { if back != 0 { self.pending_signals .replace_bits(self.pending_signals.bits() & !back); - self.thread_group.queue_shared(back); + self.thread_group + .return_shared_entries(back, &mut self.rt_sigqueue); } back } diff --git a/kernel/kernel_core/signal.rs b/kernel/kernel_core/signal.rs index de43f48..c1347a5 100644 --- a/kernel/kernel_core/signal.rs +++ b/kernel/kernel_core/signal.rs @@ -125,6 +125,11 @@ impl Signal { pub const SIGTTIN: Signal = Signal(21); // Background read from tty pub const SIGTTOU: Signal = Signal(22); // Background write to tty + /// First real-time signal number (Linux x86_64 `SIGRTMIN`). + pub const SIGRTMIN: u8 = 32; + /// Last real-time signal number (Linux x86_64 `SIGRTMAX`). + pub const SIGRTMAX: u8 = 64; + /// Create signal from raw signal number pub fn from_raw(raw: i32) -> Result { if raw <= 0 || raw > MAX_SIGNAL as i32 { @@ -177,6 +182,452 @@ impl Signal { pub fn is_uncatchable(self) -> bool { self == Signal::SIGKILL || self == Signal::SIGSTOP } + + /// Check if this is a POSIX real-time queued signal (32..=64). + #[inline] + pub fn is_realtime(self) -> bool { + self.0 >= Self::SIGRTMIN + } +} + +// ============================================================================ +// N2.6a: Real-time signal metadata (`SigInfo`), bounded FIFO queue, and +// alternate signal stack (`SigAltStack`) +// ============================================================================ + +/// Linux x86_64 `siginfo_t.si_code` values (`uapi/asm-generic/siginfo.h`). +pub const SI_USER: i32 = 0; +pub const SI_QUEUE: i32 = -1; +pub const SI_TIMER: i32 = -2; +pub const SI_TKILL: i32 = -6; +pub const SI_KERNEL: i32 = 0x80; + +/// Linux x86_64 `stack_t.ss_flags` values (`uapi/asm-generic/signal.h`). +pub const SS_ONSTACK: u32 = 1; +pub const SS_DISABLE: u32 = 2; +pub const SS_AUTODISARM: u32 = 1 << 31; +/// Minimum alternate signal stack size (Linux x86_64 `MINSIGSTKSZ`). +pub const MINSIGSTKSZ: usize = 2048; + +/// Bounded per-task and per-group real-time signal queue capacity +/// (matches POSIX `_POSIX_SIGQUEUE_MAX = 32`, zero heap allocation on delivery). +pub const MAX_QUEUED_RT_SIGNALS: usize = 32; + +/// Compact kernel representation of a signal's `siginfo_t` payload. +/// `signo == 0` marks an empty slot in [`RtSigQueue`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct SigInfo { + pub signo: i32, + pub errno: i32, + pub code: i32, + pub pid: i32, + pub uid: u32, + pub value: u64, +} + +impl SigInfo { + /// Empty sentinel slot. + pub const EMPTY: Self = Self { + signo: 0, + errno: 0, + code: 0, + pid: 0, + uid: 0, + value: 0, + }; + + /// Minimal `SI_USER` metadata for a signal with no explicitly queued payload. + #[inline] + pub const fn default_for(signal: Signal) -> Self { + Self { + signo: signal.0 as i32, + errno: 0, + code: SI_USER, + pid: 0, + uid: 0, + value: 0, + } + } + + /// Minimal `SI_USER` metadata for a raw signal number. + #[inline] + pub const fn default_for_raw(signum: u32) -> Self { + Self { + signo: signum as i32, + errno: 0, + code: SI_USER, + pid: 0, + uid: 0, + value: 0, + } + } + + /// Construct metadata for a `kill`/`tkill`/`tgkill` or kernel-originated signal. + #[inline] + pub const fn from_sender(signal: Signal, code: i32, pid: i32, uid: u32) -> Self { + Self { + signo: signal.0 as i32, + errno: 0, + code, + pid, + uid, + value: 0, + } + } + + /// Serialize into a 128-byte Linux x86_64 `siginfo_t` wire buffer. + /// Zero-fills the entire buffer so no kernel stack residue can leak. + pub fn write_wire_bytes(&self, out: &mut [u8; 128]) { + out.fill(0); + out[0..4].copy_from_slice(&self.signo.to_ne_bytes()); + out[4..8].copy_from_slice(&self.errno.to_ne_bytes()); + out[8..12].copy_from_slice(&self.code.to_ne_bytes()); + // Bytes 12..16: 4-byte alignment pad before `_sifields` on x86_64. + out[16..20].copy_from_slice(&self.pid.to_ne_bytes()); + out[20..24].copy_from_slice(&self.uid.to_ne_bytes()); + out[24..32].copy_from_slice(&self.value.to_ne_bytes()); + } + + /// Parse a user-supplied 128-byte `siginfo_t` wire buffer for + /// `rt_sigqueueinfo` / `rt_tgsigqueueinfo`, overriding `si_signo` with `sig`. + pub fn from_wire_bytes(sig: i32, bytes: &[u8; 128]) -> Self { + let rd_i32 = + |o: usize| i32::from_ne_bytes([bytes[o], bytes[o + 1], bytes[o + 2], bytes[o + 3]]); + let rd_u32 = + |o: usize| u32::from_ne_bytes([bytes[o], bytes[o + 1], bytes[o + 2], bytes[o + 3]]); + let rd_u64 = |o: usize| { + u64::from_ne_bytes([ + bytes[o], + bytes[o + 1], + bytes[o + 2], + bytes[o + 3], + bytes[o + 4], + bytes[o + 5], + bytes[o + 6], + bytes[o + 7], + ]) + }; + Self { + signo: sig, + errno: rd_i32(4), + code: rd_i32(8), + pid: rd_i32(16), + uid: rd_u32(20), + value: rd_u64(24), + } + } +} + +const RT_SIGQUEUE_OVERFLOW_CAP: usize = MAX_QUEUED_RT_SIGNALS - 1; + +/// Lazy overflow storage for queued signals beyond the 1 inline slot. +/// Allocated fallibly via `Box::try_new` only when a process actually queues +/// 2..=32 simultaneous signals, keeping `Process` and `ThreadGroup` compact. +#[derive(Debug, Clone)] +struct RtSigQueueOverflow { + entries: [SigInfo; RT_SIGQUEUE_OVERFLOW_CAP], + len: usize, +} + +impl RtSigQueueOverflow { + const fn new() -> Self { + Self { + entries: [SigInfo::EMPTY; RT_SIGQUEUE_OVERFLOW_CAP], + len: 0, + } + } +} + +/// Compact bounded FIFO queue of pending signal payloads (40 bytes inline). +/// +/// Stores the first pending payload inline (zero heap allocation for normal +/// single-signal delivery and IRQ claims) and lazily allocates a bounded +/// fallible overflow slab (`Box::try_new`) only when 2..=[`MAX_QUEUED_RT_SIGNALS`] +/// signals are simultaneously queued. +#[derive(Debug)] +pub struct RtSigQueue { + first: SigInfo, + overflow: Option>, +} + +const _: () = assert!( + core::mem::size_of::() <= 48, + "RtSigQueue must stay compact inside Process/ThreadGroup to preserve PCB heap admission budgets" +); + +impl RtSigQueue { + pub const fn new() -> Self { + Self { + first: SigInfo::EMPTY, + overflow: None, + } + } + + #[inline] + pub fn len(&self) -> usize { + if self.first.signo == 0 { + 0 + } else { + 1 + self.overflow.as_ref().map_or(0, |o| o.len) + } + } + + #[inline] + pub const fn is_empty(&self) -> bool { + self.first.signo == 0 + } + + /// Append `info` in FIFO order. Returns `Err(())` if the bounded queue is + /// full or if fallible overflow allocation fails (OOM). + pub fn push(&mut self, info: SigInfo) -> Result<(), ()> { + if self.first.signo == 0 { + self.first = info; + return Ok(()); + } + if self.overflow.is_none() { + let slab = alloc::boxed::Box::try_new(RtSigQueueOverflow::new()).map_err(|_| ())?; + self.overflow = Some(slab); + } + let ov = self.overflow.as_mut().unwrap(); + if ov.len >= RT_SIGQUEUE_OVERFLOW_CAP { + return Err(()); + } + ov.entries[ov.len] = info; + ov.len += 1; + Ok(()) + } + + /// Append `info` in FIFO order without allocating (IRQ-safe: uses the inline + /// slot or an already-allocated overflow slab, returning `Err(())` otherwise). + pub fn push_no_alloc(&mut self, info: SigInfo) -> Result<(), ()> { + if self.first.signo == 0 { + self.first = info; + return Ok(()); + } + let Some(ov) = self.overflow.as_mut() else { + return Err(()); + }; + if ov.len >= RT_SIGQUEUE_OVERFLOW_CAP { + return Err(()); + } + ov.entries[ov.len] = info; + ov.len += 1; + Ok(()) + } + + /// Return the oldest queued payload for `signal` without removing it. + pub fn peek(&self, signal: Signal) -> Option { + let target = signal.as_i32(); + if self.first.signo == 0 { + return None; + } + if self.first.signo == target { + return Some(self.first); + } + self.overflow + .as_ref()? + .entries + .iter() + .take(self.overflow.as_ref()?.len) + .copied() + .find(|e| e.signo == target) + } + + /// Remove and return the oldest queued payload for `signal`, preserving FIFO + /// order of all remaining entries. + pub fn pop(&mut self, signal: Signal) -> Option { + let target = signal.as_i32(); + if self.first.signo == 0 { + return None; + } + if self.first.signo == target { + let item = self.first; + if let Some(ov) = self.overflow.as_mut() { + if ov.len > 0 { + self.first = ov.entries[0]; + let mut i = 0usize; + while i + 1 < ov.len { + ov.entries[i] = ov.entries[i + 1]; + i += 1; + } + ov.len -= 1; + ov.entries[ov.len] = SigInfo::EMPTY; + return Some(item); + } + } + self.first = SigInfo::EMPTY; + return Some(item); + } + let ov = self.overflow.as_mut()?; + let pos = ov.entries[..ov.len] + .iter() + .position(|e| e.signo == target)?; + let item = ov.entries[pos]; + let mut i = pos; + while i + 1 < ov.len { + ov.entries[i] = ov.entries[i + 1]; + i += 1; + } + ov.len -= 1; + ov.entries[ov.len] = SigInfo::EMPTY; + Some(item) + } + + /// True if at least one entry for `signal` remains queued. + pub fn has_signal(&self, signal: Signal) -> bool { + let target = signal.as_i32(); + if self.first.signo == 0 { + return false; + } + if self.first.signo == target { + return true; + } + self.overflow + .as_ref() + .is_some_and(|ov| ov.entries[..ov.len].iter().any(|e| e.signo == target)) + } + + /// Remove all queued entries for `signal`. + pub fn remove_all(&mut self, signal: Signal) { + let target = signal.as_i32(); + if self.first.signo == 0 { + return; + } + if let Some(ov) = self.overflow.as_mut() { + let mut write = 0usize; + for read in 0..ov.len { + if ov.entries[read].signo != target { + ov.entries[write] = ov.entries[read]; + write += 1; + } + } + for i in write..ov.len { + ov.entries[i] = SigInfo::EMPTY; + } + ov.len = write; + } + if self.first.signo == target { + if let Some(ov) = self.overflow.as_mut() { + if ov.len > 0 { + self.first = ov.entries[0]; + let mut i = 0usize; + while i + 1 < ov.len { + ov.entries[i] = ov.entries[i + 1]; + i += 1; + } + ov.len -= 1; + ov.entries[ov.len] = SigInfo::EMPTY; + } else { + self.first = SigInfo::EMPTY; + } + } else { + self.first = SigInfo::EMPTY; + } + } + if self.overflow.as_ref().is_some_and(|ov| ov.len == 0) { + self.overflow = None; + } + } + + /// Move every entry whose signal bit is set in `mask` into `dst` (best-effort + /// if `dst` is full, preserving bitmap visibility via returned mask). + pub fn drain_mask_into(&mut self, mask: u64, dst: &mut RtSigQueue) { + if mask == 0 || self.first.signo == 0 { + return; + } + let matches_mask = + |entry: SigInfo| Signal::from_raw(entry.signo).is_ok_and(|s| (mask & s.bit()) != 0); + let first_matched = matches_mask(self.first); + if first_matched { + let _ = dst.push(self.first); + self.first = SigInfo::EMPTY; + } + if let Some(ov) = self.overflow.as_mut() { + let mut write = 0usize; + for read in 0..ov.len { + let entry = ov.entries[read]; + if matches_mask(entry) { + let _ = dst.push(entry); + } else if self.first.signo == 0 { + self.first = entry; + } else { + ov.entries[write] = entry; + write += 1; + } + } + for i in write..ov.len { + ov.entries[i] = SigInfo::EMPTY; + } + ov.len = write; + } + if self.overflow.as_ref().is_some_and(|ov| ov.len == 0) { + self.overflow = None; + } + } + + pub fn clear(&mut self) { + self.first = SigInfo::EMPTY; + self.overflow = None; + } +} + +impl Default for RtSigQueue { + fn default() -> Self { + Self::new() + } +} + +/// Per-task alternate signal stack configuration (`sigaltstack(2)`). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct SigAltStack { + pub sp: u64, + pub size: u64, + /// `SS_DISABLE` when disabled, `0` (or `SS_AUTODISARM`) when enabled. + pub flags: u32, +} + +impl SigAltStack { + pub const fn disabled() -> Self { + Self { + sp: 0, + size: 0, + flags: SS_DISABLE, + } + } + + #[inline] + pub const fn is_enabled(self) -> bool { + (self.flags & SS_DISABLE) == 0 && self.size >= MINSIGSTKSZ as u64 && self.sp != 0 + } + + /// True if `rsp` currently lies inside the active alternate signal stack. + /// Matches Linux `on_sig_stack(sp)`: `sp > ss_sp && sp - ss_sp <= ss_size`. + #[inline] + pub const fn on_stack(self, rsp: u64) -> bool { + self.is_enabled() && rsp > self.sp && rsp.saturating_sub(self.sp) <= self.size + } + + /// Exclusive top VA of the alternate signal stack (`sp + size`). + #[inline] + pub const fn top(self) -> Option { + if self.is_enabled() { + self.sp.checked_add(self.size) + } else { + None + } + } + + /// Format `(ss_sp, ss_flags, ss_size)` for `old_ss` or `ucontext.uc_stack`. + #[inline] + pub const fn as_stack_t_fields(self, current_rsp: u64) -> (u64, u32, u64) { + if !self.is_enabled() { + (0, SS_DISABLE, 0) + } else if self.on_stack(current_rsp) { + (self.sp, SS_ONSTACK, self.size) + } else { + (self.sp, 0, self.size) + } + } } /// Pending signals bitmap (supports signals 1-64) @@ -882,6 +1333,8 @@ pub enum SignalError { PermissionDenied, /// A credential writer has closed reader admission; caller may retry. CredentialBusy, + /// Bounded real-time signal queue is full (`EAGAIN`). + QueueFull, } impl From for SyscallError { @@ -891,6 +1344,7 @@ impl From for SyscallError { SignalError::NoSuchProcess => SyscallError::ESRCH, SignalError::PermissionDenied => SyscallError::EPERM, SignalError::CredentialBusy => SyscallError::EAGAIN, + SignalError::QueueFull => SyscallError::EAGAIN, } } } @@ -944,7 +1398,17 @@ pub fn default_action(signal: Signal) -> SignalAction { pub fn send_signal(pid: ProcessId, signal: Signal) -> Result { // GAP-5 slice 4 G7: kill() is process-directed; a thread group picks the // member that will take it. Single-task processes are unaffected. - send_process_signal(pid, signal, true) + send_process_signal(pid, signal, true, None, false) +} + +/// N2.6a: process-directed `rt_sigqueueinfo(2)` with explicit `SigInfo` payload. +/// Fails with `SignalError::QueueFull` (`EAGAIN`) if the bounded RT queue is full. +pub fn send_signal_queueinfo( + pid: ProcessId, + signal: Signal, + info: SigInfo, +) -> Result { + send_process_signal(pid, signal, true, Some(info), true) } /// GAP-5 G7 (review D3): the member is chosen without its lock, so it can @@ -954,12 +1418,21 @@ fn send_process_signal( pid: ProcessId, signal: Signal, enforce_permissions: bool, + info: Option, + fail_on_queue_full: bool, ) -> Result { const ATTEMPTS: usize = 4; let mut last = Err(SignalError::NoSuchProcess); for _ in 0..ATTEMPTS { let target = process::select_process_directed_target(pid, signal.bit()); - last = send_signal_inner(target, signal, enforce_permissions, SignalScope::Process); + last = send_signal_inner( + target, + signal, + enforce_permissions, + SignalScope::Process, + info, + fail_on_queue_full, + ); if last != Err(SignalError::NoSuchProcess) || target == pid { return last; } @@ -971,7 +1444,17 @@ fn send_process_signal( /// `tid`, with the same POSIX permission checks as `send_signal`. Fatal and /// job-control defaults still act on the whole group. pub fn send_signal_thread(tid: ProcessId, signal: Signal) -> Result { - send_signal_inner(tid, signal, true, SignalScope::Thread) + send_signal_inner(tid, signal, true, SignalScope::Thread, None, false) +} + +/// N2.6a: thread-directed `rt_tgsigqueueinfo(2)` with explicit `SigInfo` payload. +/// Fails with `SignalError::QueueFull` (`EAGAIN`) if the bounded RT queue is full. +pub fn send_signal_tgsigqueueinfo( + tid: ProcessId, + signal: Signal, + info: SigInfo, +) -> Result { + send_signal_inner(tid, signal, true, SignalScope::Thread, Some(info), true) } /// R115-2 FIX: Kernel-authoritative signal delivery — bypasses POSIX permission checks. @@ -983,7 +1466,7 @@ pub fn send_signal_thread(tid: ProcessId, signal: Signal) -> Result Result { - send_process_signal(pid, signal, false) + send_process_signal(pid, signal, false, None, false) } /// GAP-5 G7: where a generated signal is queued. @@ -1139,6 +1622,8 @@ fn send_signal_inner( signal: Signal, enforce_permissions: bool, scope: SignalScope, + explicit_info: Option, + fail_on_queue_full: bool, ) -> Result { // 注意:我们需要调用调度器的 resume_stopped,它在 sched crate 中 // 由于循环依赖的限制,我们通过回调机制实现 @@ -1148,6 +1633,10 @@ fn send_signal_inner( // Previously, we fetched the process twice: once for permission check, once for signal. let process_arc = process::get_process(pid).ok_or(SignalError::NoSuchProcess)?; + // Synthesize `SigInfo` when the caller did not supply an explicit one (e.g. + // `kill`, `tkill`, `tgkill`, or kernel-originated signal). + let mut synthesized_sender: Option<(i32, u32)> = None; + // 【安全修复 Z-9】POSIX 权限检查(深度防御) // 使用 UID/EUID 而非仅父子关系 // R115-2 FIX: Only enforce permission checks on user-facing paths. @@ -1161,6 +1650,14 @@ fn send_signal_inner( // signal authority. Kernel-internal callers use `send_signal_kernel` // and intentionally bypass this branch. let sender_pid = require_signal_sender_pid(process::current_pid())?; + if explicit_info.is_none() { + if let Some(sender_arc) = process::get_process(sender_pid) { + let s = sender_arc.lock(); + let uid = s.try_credentials_read().map_or(0, |c| c.uid); + let visible_pid = s.ns_tgid.max(s.tgid); + synthesized_sender = Some((visible_pid as i32, uid)); + } + } let has_dac_permission = user_signal_dac_allowed(&process_arc)?; let mut namespace_init_supervisor = false; // GAP-5 (review D1): init is a process; name the target's and the @@ -1258,16 +1755,46 @@ fn send_signal_inner( } // Queue the signal (always — delivery/clear decisions follow). - // GAP-5 G7: process-directed signals go to the group's shared set, so - // they survive the exit of the member chosen to be woken. + // GAP-5 G7 + N2.6a: process-directed signals go to the group's shared + // set/queue, so they survive the exit of the member chosen to be woken. + let siginfo = match explicit_info { + Some(mut si) => { + si.signo = signal.as_i32(); + Some(si) + } + None => { + if enforce_permissions { + let (spid, suid) = synthesized_sender.unwrap_or((0, 0)); + let code = match scope { + SignalScope::Process => SI_USER, + SignalScope::Thread => SI_TKILL, + }; + Some(SigInfo::from_sender(signal, code, spid, suid)) + } else { + Some(SigInfo::from_sender(signal, SI_KERNEL, 0, 0)) + } + } + }; match scope { SignalScope::Process => { - proc.thread_group.queue_shared(signal.bit()); + proc.thread_group + .queue_shared_info(signal, siginfo, fail_on_queue_full)?; // This member was chosen for it: its waits now abort for it // (unless it cannot take it; see the retarget below). proc.shared_chosen |= signal.bit(); } SignalScope::Thread => { + if let Some(si) = siginfo { + if signal.is_realtime() { + if proc.rt_sigqueue.push(si).is_err() && fail_on_queue_full { + return Err(SignalError::QueueFull); + } + } else if !proc.pending_signals.is_pending(signal) + && !proc.rt_sigqueue.has_signal(signal) + { + let _ = proc.rt_sigqueue.push(si); + } + } proc.pending_signals.set(signal); // A thread-directed instance is this task's own, not a // claimed group signal to hand back. diff --git a/kernel/kernel_core/signal_frame.rs b/kernel/kernel_core/signal_frame.rs index ad48033..e88f878 100644 --- a/kernel/kernel_core/signal_frame.rs +++ b/kernel/kernel_core/signal_frame.rs @@ -45,9 +45,13 @@ pub const SIGFRAME_SIZE: usize = FRAME_SIZE as usize; const OFF_PRETCODE: u64 = 0; const OFF_UC: u64 = 8; const OFF_UC_FLAGS: u64 = OFF_UC; // +0 +const OFF_UC_STACK_SP: u64 = OFF_UC + 16; // ss_sp within uc_stack const OFF_UC_STACK_FLAGS: u64 = OFF_UC + 24; // ss_flags within uc_stack (SS_DISABLE) +const OFF_UC_STACK_SIZE: u64 = OFF_UC + 32; // ss_size within uc_stack /// sigcontext (uc_mcontext) starts 40 bytes into the ucontext. const OFF_MCONTEXT: u64 = OFF_UC + 40; // 48 +/// uc_sigmask (8-byte kernel sigset_t) sits immediately after the 256-byte sigcontext. +const OFF_UC_SIGMASK: u64 = OFF_MCONTEXT + 256; // 304 (OFF_UC + 296) const OFF_SIGINFO: u64 = OFF_UC + UC_SIZE; // 312 const OFF_FPSTATE: u64 = OFF_SIGINFO + SIGINFO_SIZE; // 440 @@ -78,9 +82,10 @@ const MC_FPSTATE_PTR: u64 = OFF_MCONTEXT + 184; const SI_SIGNO: u64 = OFF_SIGINFO; // +0 const SI_ERRNO: u64 = OFF_SIGINFO + 4; const SI_CODE: u64 = OFF_SIGINFO + 8; -/// SI_USER — a user `kill()`/`raise()` source. The minimal slice-1 siginfo carries -/// no sender pid/uid/addr (the `PendingSignals` u64 bitmap holds none); a documented -/// M0 divergence (real `siginfo` is SLICE 4). +const SI_PID: u64 = OFF_SIGINFO + 16; +const SI_UID: u64 = OFF_SIGINFO + 20; +const SI_VALUE: u64 = OFF_SIGINFO + 24; +/// SI_USER — default `si_code` for user `kill()`/`raise()` signals. const SI_USER: u32 = 0; /// The red zone skipped below the interrupted RSP (SysV AMD64 §3.2.2). @@ -163,8 +168,19 @@ pub struct SigframeLayout { /// VMA and must never mutate main-stack accounting. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum SigframeStack { - Main { floor: u64 }, - Mmap { floor: u64 }, + Main { + floor: u64, + }, + Mmap { + floor: u64, + }, + /// N2.6a: explicit `sigaltstack(2)` range `[floor, top)`. Backed by any + /// writable user memory (mmap, brk heap, `.bss`, or main stack); page-table + /// writability is enforced by faultable `copy_to_user`. + AltStack { + floor: u64, + on_main_stack: bool, + }, Unlocatable, } @@ -175,7 +191,7 @@ impl SigframeStack { #[inline] pub const fn layout_floor(self, rsp: u64) -> u64 { match self { - Self::Main { floor } | Self::Mmap { floor } => floor, + Self::Main { floor } | Self::Mmap { floor } | Self::AltStack { floor, .. } => floor, Self::Unlocatable => rsp, } } @@ -185,7 +201,11 @@ impl SigframeStack { /// consult or update the main stack's committed-floor watermark. #[inline] pub const fn needs_main_stack_backing(self, frame_base: u64, eager_floor: u64) -> bool { - matches!(self, Self::Main { .. }) && frame_base < eager_floor + match self { + Self::Main { .. } => frame_base < eager_floor, + Self::AltStack { on_main_stack, .. } => on_main_stack && frame_base < eager_floor, + Self::Mmap { .. } | Self::Unlocatable => false, + } } } @@ -207,10 +227,26 @@ pub fn compute_sigframe_layout( interrupted_rsp: u64, stack_floor: u64, ) -> Result { - // Skip the 128-byte red zone below the interrupted RSP. - let top = interrupted_rsp - .checked_sub(RED_ZONE) - .ok_or(SyscallError::EFAULT)?; + compute_sigframe_layout_with_redzone(interrupted_rsp, stack_floor, true) +} + +/// Compute the sigframe layout with optional red-zone skipping. +/// +/// Switching onto a fresh alternate signal stack (`SA_ONSTACK`) passes +/// `skip_red_zone = false` so `MINSIGSTKSZ` (2048 B) is not needlessly reduced +/// by 128 bytes above the top of the alternate stack. +pub fn compute_sigframe_layout_with_redzone( + target_rsp: u64, + stack_floor: u64, + skip_red_zone: bool, +) -> Result { + let top = if skip_red_zone { + target_rsp + .checked_sub(RED_ZONE) + .ok_or(SyscallError::EFAULT)? + } else { + target_rsp + }; // Place the frame so frame_base ≡ 8 (mod 16): align the candidate down to 16 // then drop 8. fpstate (frame_base + 440) is then 16-aligned for fxrstor64. let candidate = top.checked_sub(FRAME_SIZE).ok_or(SyscallError::E2BIG)?; @@ -271,6 +307,34 @@ pub fn assemble_sigframe( handler: u64, restorer: u64, out: &mut [u8; SIGFRAME_SIZE], +) -> Result<(), SyscallError> { + let info = crate::signal::SigInfo::default_for_raw(signum); + assemble_sigframe_full( + layout, + ctx, + fpstate, + &info, + (0, crate::signal::SS_DISABLE, 0), + 0, + handler, + restorer, + out, + ) +} + +/// Full N2.6a `rt_sigframe` builder carrying queued `siginfo_t` metadata, +/// `uc_stack` (`sigaltstack`), and `uc_sigmask`. +#[allow(clippy::too_many_arguments)] +pub fn assemble_sigframe_full( + layout: &SigframeLayout, + ctx: &SavedUserContext, + fpstate: &[u8; FXSAVE_SIZE], + siginfo: &crate::signal::SigInfo, + uc_stack: (u64, u32, u64), + uc_sigmask: u64, + handler: u64, + restorer: u64, + out: &mut [u8; SIGFRAME_SIZE], ) -> Result<(), SyscallError> { // Overflow gate BEFORE any write: a corrupt layout can never diverge the // initialized region from the caller's fixed-size usercopy. Unreachable in @@ -284,9 +348,11 @@ pub fn assemble_sigframe( // pretcode = SA_RESTORER (the handler `ret`s here, which issues rt_sigreturn). put_u64(&mut buf, OFF_PRETCODE, restorer); - // ucontext: uc_flags = 0, uc_link = 0, uc_stack = {0, SS_DISABLE(2), 0}. + // ucontext: uc_flags = 0, uc_link = 0, uc_stack = {ss_sp, ss_flags, ss_size}. put_u64(&mut buf, OFF_UC_FLAGS, 0); - put_u32(&mut buf, OFF_UC_STACK_FLAGS, 2 /* SS_DISABLE */); + put_u64(&mut buf, OFF_UC_STACK_SP, uc_stack.0); + put_u32(&mut buf, OFF_UC_STACK_FLAGS, uc_stack.1); + put_u64(&mut buf, OFF_UC_STACK_SIZE, uc_stack.2); // sigcontext (uc_mcontext): the interrupted user register state. put_u64(&mut buf, MC_R8, ctx.r8); @@ -302,18 +368,23 @@ pub fn assemble_sigframe( put_u64(&mut buf, MC_RBP, ctx.rbp); put_u64(&mut buf, MC_RBX, ctx.rbx); put_u64(&mut buf, MC_RDX, ctx.rdx); - put_u64(&mut buf, MC_RAX, ctx.rax); // the FINAL syscall result — restored on return. + put_u64(&mut buf, MC_RAX, ctx.rax); // the FINAL syscall result (or restarted syscall nr). put_u64(&mut buf, MC_RCX, ctx.rcx); put_u64(&mut buf, MC_RSP, ctx.rsp); put_u64(&mut buf, MC_RIP, ctx.rip); put_u64(&mut buf, MC_EFLAGS, ctx.rflags); // uc_mcontext.fpstate pointer is ABI shape only; rt_sigreturn re-derives the VA. put_u64(&mut buf, MC_FPSTATE_PTR, layout.fpstate_va); - - // siginfo: minimal (si_signo, si_errno=0, si_code=SI_USER); rest zero. - put_u32(&mut buf, SI_SIGNO, signum); - put_u32(&mut buf, SI_ERRNO, 0); - put_u32(&mut buf, SI_CODE, SI_USER as u32); + // uc_sigmask (informative for handler; rt_sigreturn restores PCB saved_blocked). + put_u64(&mut buf, OFF_UC_SIGMASK, uc_sigmask); + + // siginfo (128-byte Linux x86_64 siginfo_t layout). + put_u32(&mut buf, SI_SIGNO, siginfo.signo as u32); + put_u32(&mut buf, SI_ERRNO, siginfo.errno as u32); + put_u32(&mut buf, SI_CODE, siginfo.code as u32); + put_u32(&mut buf, SI_PID, siginfo.pid as u32); + put_u32(&mut buf, SI_UID, siginfo.uid); + put_u64(&mut buf, SI_VALUE, siginfo.value); // fpstate: the 512-byte FXSAVE image. let o = OFF_FPSTATE as usize; diff --git a/kernel/kernel_core/syscall/abi.rs b/kernel/kernel_core/syscall/abi.rs index 8e51fb2..968d63b 100644 --- a/kernel/kernel_core/syscall/abi.rs +++ b/kernel/kernel_core/syscall/abi.rs @@ -177,6 +177,26 @@ const _: [(); 24] = [(); core::mem::size_of::()]; pub const LINUX_DIRENT64_NAME_OFFSET: usize = core::mem::offset_of!(LinuxDirent64, d_type) + 1; const _: [(); 19] = [(); LINUX_DIRENT64_NAME_OFFSET]; +// ============================================================================ +// Signal Stack ABI (Linux x86_64 stack_t, N2.6a) +// ============================================================================ + +/// Linux x86_64 `stack_t` wire layout for `sigaltstack(2)` (24 bytes, explicit padding). +#[repr(C)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(super) struct StackT { + pub(super) ss_sp: u64, + pub(super) ss_flags: i32, + pub(super) _pad: i32, + pub(super) ss_size: usize, +} + +const _: [(); 24] = [(); core::mem::size_of::()]; +const _: [(); 8] = [(); core::mem::align_of::()]; +const _: [(); 0] = [(); core::mem::offset_of!(StackT, ss_sp)]; +const _: [(); 8] = [(); core::mem::offset_of!(StackT, ss_flags)]; +const _: [(); 16] = [(); core::mem::offset_of!(StackT, ss_size)]; + // ============================================================================ // Socket ABI (Linux x86_64) // ============================================================================ diff --git a/kernel/kernel_core/syscall/exec.rs b/kernel/kernel_core/syscall/exec.rs index 27720fa..786634a 100644 --- a/kernel/kernel_core/syscall/exec.rs +++ b/kernel/kernel_core/syscall/exec.rs @@ -1197,6 +1197,8 @@ pub(super) fn exec_from_bytes( // M0-6 poll/select: a live ppoll/pselect6 mask stash cannot survive the // address-space replacement (the syscall that set it is being replaced). proc.poll_restore_blocked = None; + // N2.6a: POSIX/Linux execve(2) disables any established alternate signal stack. + proc.sigaltstack = crate::signal::SigAltStack::disabled(); // Robust-list registration is address-space-local. Clear the old // image's pointer before publishing the replacement so exit cleanup // cannot dereference stale or newly-reused virtual memory. diff --git a/kernel/kernel_core/syscall/mod.rs b/kernel/kernel_core/syscall/mod.rs index 9185841..95969e6 100644 --- a/kernel/kernel_core/syscall/mod.rs +++ b/kernel/kernel_core/syscall/mod.rs @@ -696,6 +696,20 @@ pub fn syscall_dispatcher( arg3 as usize, ), Sc::RtSigreturn => sys_rt_sigreturn(), + // N2.6a: Extended POSIX/Linux RT signal syscalls + alternate signal stack. + Sc::RtSigpending => sys_rt_sigpending(arg0 as *mut u8, arg1 as usize), + Sc::RtSigtimedwait => sys_rt_sigtimedwait( + arg0 as *const u8, + arg1 as *mut u8, + arg2 as *const u8, + arg3 as usize, + ), + Sc::RtSigqueueinfo => sys_rt_sigqueueinfo(arg0 as i32, arg1 as i32, arg2 as *const u8), + Sc::RtSigsuspend => sys_rt_sigsuspend(arg0 as *const u8, arg1 as usize), + Sc::Sigaltstack => sys_sigaltstack(arg0 as *const u8, arg1 as *mut u8), + Sc::RtTgsigqueueinfo => { + sys_rt_tgsigqueueinfo(arg0 as i32, arg1 as i32, arg2 as i32, arg3 as *const u8) + } // F.1: Namespace unshare Sc::Unshare => sys_unshare(arg0 as u64), // F.1: setns for mount namespace @@ -1032,7 +1046,11 @@ fn finish_syscall( audit_syscall_exit(syscall_num, args, timestamp, lsm_ctx, &result); } let voluntary_yield = dispatched && syscall_num == 24 && result.is_ok(); - finish_syscall_tail(result, voluntary_yield, entry_proc) + let restart_nr = (dispatched + && matches!(result, Err(SyscallError::EINTR)) + && is_restartable_syscall(syscall_num, args)) + .then_some(syscall_num); + finish_syscall_tail(result, voluntary_yield, restart_nr, entry_proc) } /// Audit record and LSM exit hook for a dispatched call. @@ -1088,6 +1106,7 @@ fn audit_syscall_exit( fn finish_syscall_tail( mut result: SyscallResult, mut voluntary_yield: bool, + restart_nr: Option, entry_proc: Option, ) -> i64 { // Compute the syscall's return value (→ RAX). Captured here because signal @@ -1150,10 +1169,10 @@ fn finish_syscall_tail( let handoff_proc = handoff_arc.lock(); maybe_deliver_signal_phase1(pid, &handoff_arc, handoff_proc) }; - finish_signal_tail_step(pid, ret_val, handoff_arc, step); + finish_signal_tail_step(pid, ret_val, None, handoff_arc, step); } } - other => finish_signal_tail_step(pid, ret_val, proc_arc, other), + other => finish_signal_tail_step(pid, ret_val, restart_nr, proc_arc, other), } } } else { diff --git a/kernel/kernel_core/syscall/proc.rs b/kernel/kernel_core/syscall/proc.rs index 2886d7c..50dc8a5 100644 --- a/kernel/kernel_core/syscall/proc.rs +++ b/kernel/kernel_core/syscall/proc.rs @@ -1366,6 +1366,9 @@ pub(super) fn sys_clone( None }; child.blocked = parent_blocked; + // N2.6a: Linux clone(2) disables sigaltstack when CLONE_VM is set + // (without CLONE_VFORK), which matches born-clean `SigAltStack::disabled()`. + child.sigaltstack = crate::signal::SigAltStack::disabled(); // RF180-1 FIX: publish the snapshotted sandbox state only while holding // parent -> child in canonical order and only if the committed seccomp diff --git a/kernel/kernel_core/syscall/signal.rs b/kernel/kernel_core/syscall/signal.rs index 97ae5cb..df3d6f7 100644 --- a/kernel/kernel_core/syscall/signal.rs +++ b/kernel/kernel_core/syscall/signal.rs @@ -37,7 +37,7 @@ pub(super) enum KillTarget { } pub(super) fn sys_kill(pid: ProcessId, sig: i32) -> SyscallResult { - kill_common(pid, sig, KillTarget::Process) + kill_common(pid, sig, KillTarget::Process, None) } /// tkill(2). musl's raise() uses it with the caller's own tid. @@ -45,7 +45,7 @@ pub(super) fn sys_tkill(tid: i32, sig: i32) -> SyscallResult { if tid <= 0 { return Err(SyscallError::EINVAL); } - kill_common(tid as ProcessId, sig, KillTarget::Thread) + kill_common(tid as ProcessId, sig, KillTarget::Thread, None) } /// tgkill(2). @@ -57,14 +57,61 @@ pub(super) fn sys_tgkill(tgid: i32, tid: i32, sig: i32) -> SyscallResult { tid as ProcessId, sig, KillTarget::ThreadInGroup(tgid as ProcessId), + None, + ) +} + +/// rt_sigqueueinfo(2) — queue a signal + siginfo_t payload to a thread group (129). +pub(super) fn sys_rt_sigqueueinfo(tgid: i32, sig: i32, uinfo: *const u8) -> SyscallResult { + if uinfo.is_null() { + return Err(SyscallError::EFAULT); + } + let mut raw = [0u8; 128]; + copy_from_user(&mut raw, uinfo)?; + if tgid <= 0 { + return Err(SyscallError::EINVAL); + } + let info = crate::signal::SigInfo::from_wire_bytes(sig, &raw); + kill_common(tgid as ProcessId, sig, KillTarget::Process, Some(info)) +} + +/// rt_tgsigqueueinfo(2) — queue a signal + siginfo_t payload to a specific thread (297). +pub(super) fn sys_rt_tgsigqueueinfo( + tgid: i32, + tid: i32, + sig: i32, + uinfo: *const u8, +) -> SyscallResult { + if uinfo.is_null() { + return Err(SyscallError::EFAULT); + } + let mut raw = [0u8; 128]; + copy_from_user(&mut raw, uinfo)?; + if tgid <= 0 || tid <= 0 { + return Err(SyscallError::EINVAL); + } + let info = crate::signal::SigInfo::from_wire_bytes(sig, &raw); + kill_common( + tid as ProcessId, + sig, + KillTarget::ThreadInGroup(tgid as ProcessId), + Some(info), ) } -/// Shared authorization and delivery for kill, tkill and tgkill. Every check -/// below (namespace translation, init protection, POSIX/user-namespace -/// permission, LSM) applies to all three; only the final delivery differs. -pub(super) fn kill_common(pid: ProcessId, sig: i32, mode: KillTarget) -> SyscallResult { - use crate::signal::{send_signal, send_signal_thread, signal_name, Signal}; +/// Shared authorization and delivery for kill, tkill, tgkill, rt_sigqueueinfo, +/// and rt_tgsigqueueinfo. Every check below (namespace translation, init +/// protection, POSIX/user-namespace permission, LSM) applies uniformly. +pub(super) fn kill_common( + pid: ProcessId, + sig: i32, + mode: KillTarget, + explicit_info: Option, +) -> SyscallResult { + use crate::signal::{ + send_signal, send_signal_queueinfo, send_signal_tgsigqueueinfo, send_signal_thread, + signal_name, Signal, + }; let self_global_pid = current_pid().ok_or(SyscallError::ESRCH)?; @@ -173,6 +220,14 @@ pub(super) fn kill_common(pid: ProcessId, sig: i32, mode: KillTarget) -> Syscall return Err(SyscallError::EPERM); } + // Linux rt_sigqueueinfo(2) / rt_tgsigqueueinfo(2) anti-spoofing rule: + // a caller may not send si_code >= 0 or SI_TKILL to another process. + if let Some(info) = explicit_info { + if self_tgid != target_tgid && (info.code >= 0 || info.code == crate::signal::SI_TKILL) { + return Err(SyscallError::EPERM); + } + } + // R161-2 FIX + R162-1-1 FIX: Invoke LSM hook_signal_send BEFORE sig==0 // check so MAC policy can deny process existence probes across security // domains (matching Linux SELinux/AppArmor behavior). @@ -198,11 +253,17 @@ pub(super) fn kill_common(pid: ProcessId, sig: i32, mode: KillTarget) -> Syscall let signal = Signal::from_raw(sig)?; // 发送信号 (using global PID) - let _action = match mode { - KillTarget::Process => send_signal(target_global_pid, signal)?, - KillTarget::Thread | KillTarget::ThreadInGroup(_) => { + let _action = match (mode, explicit_info) { + (KillTarget::Process, None) => send_signal(target_global_pid, signal)?, + (KillTarget::Process, Some(info)) => { + send_signal_queueinfo(target_global_pid, signal, info)? + } + (KillTarget::Thread | KillTarget::ThreadInGroup(_), None) => { send_signal_thread(target_global_pid, signal)? } + (KillTarget::Thread | KillTarget::ThreadInGroup(_), Some(info)) => { + send_signal_tgsigqueueinfo(target_global_pid, signal, info)? + } }; // R101-2 FIX: Gate signal dispatch debug print behind debug_assertions. @@ -419,6 +480,370 @@ pub(super) fn sys_rt_sigaction( Ok(0) } +// ============================================================================ +// N2.6a: Extended POSIX / Linux RT signal syscalls +// (`rt_sigpending`, `rt_sigsuspend`, `rt_sigtimedwait`, `sigaltstack`, `SA_RESTART`) +// ============================================================================ + +/// sys_rt_sigpending - examine pending signals for the calling thread/process (127). +pub(super) fn sys_rt_sigpending(set: *mut u8, sigsetsize: usize) -> SyscallResult { + if sigsetsize != LINUX_KERNEL_SIGSET_SIZE { + return Err(SyscallError::EINVAL); + } + if set.is_null() { + return Err(SyscallError::EFAULT); + } + verify_user_memory(set as *const u8, LINUX_KERNEL_SIGSET_SIZE, true)?; + + let pid = current_pid().ok_or(SyscallError::ESRCH)?; + let proc_arc = get_process(pid).ok_or(SyscallError::ESRCH)?; + let pending = proc_arc.lock().pending_bits(); + copy_to_user(set, &pending.to_ne_bytes())?; + Ok(0) +} + +/// sys_rt_sigsuspend - atomically replace the signal mask and wait for a signal (130). +/// +/// Reuses the `poll_restore_blocked` (TIF_RESTORE_SIGMASK) contract: the temporary +/// mask stays active across the syscall-return safe point so the interrupting +/// handler is delivered under it while `saved_blocked` records the caller's +/// original mask (restored by `rt_sigreturn`). Always returns `EINTR` and is +/// never restarted by `SA_RESTART`. +pub(super) fn sys_rt_sigsuspend(unewset: *const u8, sigsetsize: usize) -> SyscallResult { + if sigsetsize != LINUX_KERNEL_SIGSET_SIZE { + return Err(SyscallError::EINVAL); + } + if unewset.is_null() { + return Err(SyscallError::EFAULT); + } + let mut b = [0u8; LINUX_KERNEL_SIGSET_SIZE]; + copy_from_user(&mut b, unewset)?; + let temp_mask = u64::from_ne_bytes(b); + + let pid = current_pid().ok_or(SyscallError::ESRCH)?; + let proc_arc = get_process(pid).ok_or(SyscallError::ESRCH)?; + + let (old_mask, retarget) = { + let mut p = proc_arc.lock(); + let old = p.blocked; + p.blocked = crate::signal::apply_sigprocmask(old, SIG_SETMASK, temp_mask); + let retarget = p + .recalc_shared_signals(true) + .then(|| Arc::clone(&p.thread_group)); + (old, retarget) + }; + if let Some(group) = retarget { + crate::process::retarget_shared_signals(pid, &group); + } + + loop { + if wait_should_abort(pid) || crate::signal::has_deliverable_signal(pid) { + break; + } + crate::reschedule_if_needed(); + debug_assert!( + x86_64::instructions::interrupts::are_enabled(), + "rt_sigsuspend wait loop must hlt with IRQs enabled" + ); + unsafe { + core::arch::asm!("hlt", options(nomem, nostack, preserves_flags)); + } + } + + let retarget_after = { + let mut p = proc_arc.lock(); + if crate::signal::has_deliverable_signal_locked(&p) { + p.poll_restore_blocked = Some(old_mask); + None + } else { + p.blocked = old_mask & !crate::signal::uncatchable_mask(); + p.recalc_shared_signals(false) + .then(|| Arc::clone(&p.thread_group)) + } + }; + if let Some(group) = retarget_after { + crate::process::retarget_shared_signals(pid, &group); + } + + Err(SyscallError::EINTR) +} + +/// sys_rt_sigtimedwait - synchronously wait for and consume a queued signal (128). +/// +/// Consumes any pending signal matching `*uthese` (even if blocked), writes its +/// 128-byte `siginfo_t` to `uinfo` when non-null, and returns the signal number. +/// Never restarted by `SA_RESTART`. +pub(super) fn sys_rt_sigtimedwait( + uthese: *const u8, + uinfo: *mut u8, + uts: *const u8, + sigsetsize: usize, +) -> SyscallResult { + if sigsetsize != LINUX_KERNEL_SIGSET_SIZE { + return Err(SyscallError::EINVAL); + } + if uthese.is_null() { + return Err(SyscallError::EFAULT); + } + let mut mask_bytes = [0u8; LINUX_KERNEL_SIGSET_SIZE]; + copy_from_user(&mut mask_bytes, uthese)?; + // Linux do_sigtimedwait strips SIGKILL and SIGSTOP from the wait set. + let these = u64::from_ne_bytes(mask_bytes) & !crate::signal::uncatchable_mask(); + + if !uinfo.is_null() { + verify_user_memory(uinfo as *const u8, 128, true)?; + } + + const NS_PER_MS: u64 = 1_000_000; + let timeout_ms: Option = if !uts.is_null() { + let mut ts = TimeSpec::default(); + // lint-repr-c-copy: allow (no-padding: TimeSpec {i64,i64} = 16 bytes; user→kernel) + let ts_bytes = unsafe { + core::slice::from_raw_parts_mut( + &mut ts as *mut TimeSpec as *mut u8, + core::mem::size_of::(), + ) + }; + crate::usercopy::copy_from_user_safe(ts_bytes, uts).map_err(|_| SyscallError::EFAULT)?; + if ts.tv_sec < 0 || ts.tv_nsec < 0 || ts.tv_nsec >= 1_000_000_000 { + return Err(SyscallError::EINVAL); + } + let total_ns = (ts.tv_sec as u64) + .saturating_mul(1_000_000_000) + .saturating_add(ts.tv_nsec as u64); + let ms = if total_ns == 0 { + 0 + } else { + (total_ns / NS_PER_MS) + .saturating_add(if total_ns % NS_PER_MS != 0 { 1 } else { 0 }) + .max(1) + }; + Some(ms) + } else { + None + }; + + let pid = current_pid().ok_or(SyscallError::ESRCH)?; + let proc_arc = get_process(pid).ok_or(SyscallError::ESRCH)?; + let start = crate::time::get_ticks(); + + loop { + let outcome = { + let mut proc = proc_arc.lock(); + if let Some((sig, info)) = proc.take_pending_for_sigwait(these) { + Ok(Some((sig, info))) + } else { + let actions = proc.sigactions.lock(); + let other_deliverable = crate::signal::select_for_delivery( + proc.wait_pending_bits() & !these & !crate::signal::uncatchable_mask(), + proc.blocked, + proc.in_signal_handler, + &actions, + crate::signal::DeliveryMode::AnyActionable, + ) + .is_some(); + if other_deliverable { + Err(SyscallError::EINTR) + } else { + Ok(None) + } + } + }; + + match outcome { + Ok(Some((sig, info))) => { + if !uinfo.is_null() { + let mut wire = [0u8; 128]; + info.write_wire_bytes(&mut wire); + copy_to_user(uinfo, &wire)?; + } + return Ok(sig.as_u8() as usize); + } + Err(e) => return Err(e), + Ok(None) => {} + } + + if wait_should_abort(pid) { + return Err(SyscallError::EINTR); + } + + match timeout_ms { + Some(0) => return Err(SyscallError::EAGAIN), + Some(t) if crate::time::get_ticks().saturating_sub(start) >= t => { + return Err(SyscallError::EAGAIN); + } + _ => {} + } + + crate::reschedule_if_needed(); + debug_assert!( + x86_64::instructions::interrupts::are_enabled(), + "rt_sigtimedwait wait loop must hlt with IRQs enabled" + ); + unsafe { + core::arch::asm!("hlt", options(nomem, nostack, preserves_flags)); + } + } +} + +/// Pure validator/updater for `sigaltstack(2)` (unit-testable without a live PCB). +pub(super) fn apply_sigaltstack_update( + current: crate::signal::SigAltStack, + user_rsp: u64, + new_req: Option, +) -> Result<(crate::signal::SigAltStack, StackT), SyscallError> { + use crate::signal::{SigAltStack, MINSIGSTKSZ, SS_DISABLE}; + + let on_stack = current.on_stack(user_rsp); + let (old_sp, old_flags, old_size) = current.as_stack_t_fields(user_rsp); + let old_stack = StackT { + ss_sp: old_sp, + ss_flags: old_flags as i32, + _pad: 0, + ss_size: old_size as usize, + }; + + let next = match new_req { + None => current, + Some(req) => { + if on_stack { + return Err(SyscallError::EPERM); + } + if req.ss_flags != 0 && req.ss_flags != SS_DISABLE as i32 { + return Err(SyscallError::EINVAL); + } + if req.ss_flags == SS_DISABLE as i32 { + SigAltStack::disabled() + } else { + if req.ss_size < MINSIGSTKSZ { + return Err(SyscallError::ENOMEM); + } + let end = req + .ss_sp + .checked_add(req.ss_size as u64) + .ok_or(SyscallError::EINVAL)?; + if req.ss_sp == 0 + || !crate::signal_frame::is_canonical_user_addr(req.ss_sp) + || !crate::signal_frame::is_canonical_user_addr(end - 1) + { + return Err(SyscallError::EINVAL); + } + SigAltStack { + sp: req.ss_sp, + size: req.ss_size as u64, + flags: 0, + } + } + } + }; + + Ok((next, old_stack)) +} + +/// sys_sigaltstack - set and/or get alternate signal stack context (131). +pub(super) fn sys_sigaltstack(ss: *const u8, old_ss: *mut u8) -> SyscallResult { + let new_req: Option = if !ss.is_null() { + let mut req = StackT::default(); + // lint-repr-c-copy: allow (StackT is 24-byte #[repr(C)] with explicit _pad; user→kernel) + let bytes = unsafe { + core::slice::from_raw_parts_mut( + &mut req as *mut StackT as *mut u8, + core::mem::size_of::(), + ) + }; + copy_from_user(bytes, ss)?; + Some(req) + } else { + None + }; + + if !old_ss.is_null() { + verify_user_memory(old_ss as *const u8, core::mem::size_of::(), true)?; + } + + let pid = current_pid().ok_or(SyscallError::ESRCH)?; + let proc_arc = get_process(pid).ok_or(SyscallError::ESRCH)?; + let user_rsp = with_current_syscall_frame(|f| f.rsp).unwrap_or(0); + + let old_stack = { + let mut proc = proc_arc.lock(); + let (next, old_stack) = apply_sigaltstack_update(proc.sigaltstack, user_rsp, new_req)?; + proc.sigaltstack = next; + old_stack + }; + + if !old_ss.is_null() { + // lint-repr-c-copy: allow (StackT is 24-byte #[repr(C)] with explicit _pad; kernel→user) + let bytes = unsafe { + core::slice::from_raw_parts( + &old_stack as *const StackT as *const u8, + core::mem::size_of::(), + ) + }; + copy_to_user(old_ss, bytes)?; + } + Ok(0) +} + +/// Pure Linux `signal(7)` restartability predicate for `SA_RESTART`. +/// +/// Only blocking I/O, wait, socket accept/send/recv, and timeout-less +/// `FUTEX_WAIT`/`FUTEX_WAIT_BITSET` restart when returning `EINTR` into an +/// `SA_RESTART` handler. Time-bounded waits (`nanosleep`, `poll`, `ppoll`, +/// `select`, `pselect6`, `rt_sigsuspend`, `rt_sigtimedwait`) and `connect` +/// NEVER restart. +#[inline] +pub(super) fn is_restartable_syscall(syscall_num: u64, args: &[u64; 6]) -> bool { + use seccomp::syscall_table as st; + match syscall_num { + st::SYS_READ + | st::SYS_WRITE + | st::SYS_READV + | st::SYS_WRITEV + | st::SYS_WAIT4 + | st::SYS_WAITID + | st::SYS_ACCEPT + | st::SYS_ACCEPT4 + | st::SYS_SENDTO + | st::SYS_RECVFROM + | st::SYS_SENDMSG + | st::SYS_RECVMSG => true, + st::SYS_FUTEX => { + let op = (args[1] as u32) & 0x7f; + let timeout_ptr = args[3]; + // FUTEX_WAIT (0) or FUTEX_WAIT_BITSET (9) with NULL timeout only. + (op == 0 || op == 9) && timeout_ptr == 0 + } + _ => false, + } +} + +/// Choose the target stack top, red-zone policy, and `SigframeStack` provenance +/// for signal delivery, honoring `SA_ONSTACK` + `sigaltstack(2)`. +#[inline] +pub(super) fn choose_altstack_target( + interrupted_rsp: u64, + sa_flags: u64, + altstack: crate::signal::SigAltStack, +) -> Option<(u64, bool, crate::signal_frame::SigframeStack)> { + if (sa_flags & crate::signal::SA_ONSTACK) == 0 || !altstack.is_enabled() { + return None; + } + let on_main = main_sigframe_stack(altstack.sp).is_some(); + let stack = crate::signal_frame::SigframeStack::AltStack { + floor: altstack.sp, + on_main_stack: on_main, + }; + if altstack.on_stack(interrupted_rsp) { + // Already running on the alternate signal stack: continue downward from + // the current RSP within the same altstack bounds (keep red zone). + Some((interrupted_rsp, true, stack)) + } else { + // Switch onto the top of the alternate signal stack (no red zone above top). + altstack.top().map(|top| (top, false, stack)) + } +} + /// sys_rt_sigreturn - restore the interrupted context after a handler returns (15). /// /// M0 item 5 (sub-slice 1a). SROP-DEFENDED: validates the restored RIP/RSP (canonical, @@ -799,11 +1224,14 @@ pub(super) enum SignalTailStep { /// Handler frame delivery (Phase 2/3) outside the PCB lock. Handler { sig: crate::signal::Signal, + siginfo: crate::signal::SigInfo, + altstack: crate::signal::SigAltStack, handler: u64, restorer: u64, sa_mask: u64, sa_flags: u64, old_blocked: u64, + uc_sigmask: u64, delivered_action: crate::signal::SigAction, }, } @@ -914,13 +1342,19 @@ pub(super) fn maybe_deliver_signal_phase1<'a>( // former `bit` local was folded into select_lowest_deliverable). let delivered_action = actions[(sig.as_u8() - 1) as usize]; let restorer = delivered_action.restorer; + let siginfo = proc.peek_own_siginfo(sig); + let altstack = proc.sigaltstack; + let uc_sigmask = proc.poll_restore_blocked.unwrap_or(proc.blocked); SignalTailStep::Handler { sig, + siginfo, + altstack, handler, restorer, sa_mask: mask, sa_flags: flags, old_blocked: proc.blocked, + uc_sigmask, delivered_action, } } @@ -944,10 +1378,22 @@ pub(super) fn maybe_deliver_signal_phase1<'a>( pub(super) fn finish_signal_tail_step( pid: ProcessId, result: i64, + restart_nr: Option, proc_arc: crate::process::ProcessArc, step: SignalTailStep, ) { - let (sig, handler, restorer, sa_mask, sa_flags, old_blocked, delivered_action) = match step { + let ( + sig, + siginfo, + altstack, + handler, + restorer, + sa_mask, + sa_flags, + old_blocked, + uc_sigmask, + delivered_action, + ) = match step { SignalTailStep::Done | SignalTailStep::ExecHandoff => return, SignalTailStep::Exit(exit_code) => { drop(proc_arc); @@ -970,19 +1416,25 @@ pub(super) fn finish_signal_tail_step( } SignalTailStep::Handler { sig, + siginfo, + altstack, handler, restorer, sa_mask, sa_flags, old_blocked, + uc_sigmask, delivered_action, } => ( sig, + siginfo, + altstack, handler, restorer, sa_mask, sa_flags, old_blocked, + uc_sigmask, delivered_action, ), }; @@ -991,9 +1443,22 @@ pub(super) fn finish_signal_tail_step( // D1RES-R1): snapshot the interrupted context + FXSAVE, build the sigframe, copy // it to the user stack. let snap = with_current_syscall_frame_mut(pid, |frame, fx| { + // N2.6a SA_RESTART: if a restartable syscall returned EINTR and this + // handler has SA_RESTART set, rewind RIP by the 2-byte `syscall` (0f 05) + // instruction and save the original syscall number into RAX so + // `rt_sigreturn` transparently re-executes the syscall with intact args. + let should_restart = restart_nr + .filter(|_| (sa_flags & crate::signal::SA_RESTART) != 0) + .filter(|_| { + frame.rcx >= 2 && crate::signal_frame::is_canonical_user_addr(frame.rcx - 2) + }); + let (saved_rax, saved_rip) = match should_restart { + Some(nr) => (nr, frame.rcx - 2), + None => (result as u64, frame.rcx), + }; // The SYSCALL path saved user RIP into RCX and user RFLAGS into R11. let ctx = crate::signal_frame::SavedUserContext { - rax: result as u64, + rax: saved_rax, rbx: frame.rbx, rcx: frame.rcx, rdx: frame.rdx, @@ -1009,7 +1474,7 @@ pub(super) fn finish_signal_tail_step( r13: frame.r13, r14: frame.r14, r15: frame.r15, - rip: frame.rcx, // user RIP + rip: saved_rip, // user RIP (or rewound `syscall` for SA_RESTART) rflags: frame.r11, // user RFLAGS }; let mut fxcopy = [0u8; 512]; @@ -1027,35 +1492,45 @@ pub(super) fn finish_signal_tail_step( }; crate::signal_frame::sanitize_fxsave_for_export(&mut fxcopy); - // RF178-34 FIX: carry stack provenance through layout and backing. This - // prevents a low mmap-backed thread stack from entering main-stack growth. - let stack = match main_sigframe_stack(ctx.rsp) { - Some(main) => main, - None => { - let proc = proc_arc.lock(); - let mm = proc.mm.lock(); - locate_sigframe_vma(ctx.rsp, &mm.mmap_regions) + // N2.6a SA_ONSTACK + RF178-34 FIX: honor sigaltstack when SA_ONSTACK is set; + // otherwise carry normal stack provenance through layout and backing. + let (target_rsp, skip_red_zone, stack) = + if let Some(alt) = choose_altstack_target(ctx.rsp, sa_flags, altstack) { + alt + } else { + let s = match main_sigframe_stack(ctx.rsp) { + Some(main) => main, + None => { + let proc = proc_arc.lock(); + let mm = proc.mm.lock(); + locate_sigframe_vma(ctx.rsp, &mm.mmap_regions) + } + }; + (ctx.rsp, true, s) + }; + let layout = match crate::signal_frame::compute_sigframe_layout_with_redzone( + target_rsp, + stack.layout_floor(target_rsp), + skip_red_zone, + ) { + Ok(l) => l, + // No room for the frame on the user stack: fatal SIGSEGV (Linux force_sigsegv). + // GAP-5 review: no PCB reference may outlive the abandoned stack. + Err(_) => { + drop(proc_arc); + crate::process::terminate_group_self_and_halt(pid, 139) } }; - let layout = - match crate::signal_frame::compute_sigframe_layout(ctx.rsp, stack.layout_floor(ctx.rsp)) { - Ok(l) => l, - // No room for the frame on the user stack: fatal SIGSEGV (Linux force_sigsegv). - // GAP-5 review: no PCB reference may outlive the abandoned stack. - Err(_) => { - drop(proc_arc); - crate::process::terminate_group_self_and_halt(pid, 139) - } - }; // D1RES-R1: heap-free staging — assembled in place into a kernel-stack buffer - // (assemble_sigframe zero-fills it; the zero fill is load-bearing). Removes the - // former fallible heap alloc + its OOM-kill-on-delivery leg from this path. + // (assemble_sigframe_full zero-fills it; the zero fill is load-bearing). let mut buf = [0u8; crate::signal_frame::SIGFRAME_SIZE]; - if crate::signal_frame::assemble_sigframe( + if crate::signal_frame::assemble_sigframe_full( &layout, &ctx, &fxcopy, - sig.as_u8() as u32, + &siginfo, + altstack.as_stack_t_fields(ctx.rsp), + uc_sigmask, handler, restorer, &mut buf, @@ -1314,7 +1789,7 @@ pub fn try_deliver_signal_on_irq_return( // again at commit below. A concurrent state change therefore causes a // fail-closed defer; it can never redirect a stale handler or overwrite a // newer signal mask. - let (sig, sa, old_blocked, generation, stack, mm) = { + let (sig, siginfo, altstack, sa, old_blocked, generation, target_rsp, skip_red_zone, stack, mm) = { // RF178-35 FIX: fatal exit dominates handler delivery. This closes the // race after the timer's initial pending-exit transaction. if proc_guard @@ -1364,19 +1839,32 @@ pub fn try_deliver_signal_on_irq_return( if !sa.is_handler() { return None; } - // GAP-5 G7: take a group-wide signal into this task's own set before - // the frame is built; another member that already took it delivers it. - if !proc_guard.claim_pending(sig) { + // GAP-5 G7 + N2.6a: IRQ-safe non-blocking claim of a group-wide signal. + if !proc_guard.try_claim_pending_irq(sig) { return None; } - - let stack = resolve_sigframe_stack_irq(interrupted_rsp, &proc_guard); + let siginfo = proc_guard.peek_own_siginfo(sig); + let altstack = proc_guard.sigaltstack; + let (target_rsp, skip_red_zone, stack) = + if let Some(alt) = choose_altstack_target(interrupted_rsp, sa.flags, altstack) { + alt + } else { + ( + interrupted_rsp, + true, + resolve_sigframe_stack_irq(interrupted_rsp, &proc_guard), + ) + }; let mm = Arc::clone(&proc_guard.mm); ( sig, + siginfo, + altstack, sa, proc_guard.blocked, proc_guard.generation, + target_rsp, + skip_red_zone, stack, mm, ) @@ -1422,10 +1910,11 @@ pub fn try_deliver_signal_on_irq_return( } }; - // Compute the layout. - let layout = match crate::signal_frame::compute_sigframe_layout( - interrupted_rsp, - stack.layout_floor(interrupted_rsp), + // Compute the layout (honoring SA_ONSTACK + sigaltstack when active). + let layout = match crate::signal_frame::compute_sigframe_layout_with_redzone( + target_rsp, + stack.layout_floor(target_rsp), + skip_red_zone, ) { Ok(l) => l, Err(_) => return None, // Layout computation failed — defer. @@ -1436,11 +1925,13 @@ pub fn try_deliver_signal_on_irq_return( // alloc performed while HOLDING the proc_arc try_lock guard (FIX A graph), // restoring the no-alloc-under-spinlock rule on this path. let mut frame_bytes = [0u8; crate::signal_frame::SIGFRAME_SIZE]; - if crate::signal_frame::assemble_sigframe( + if crate::signal_frame::assemble_sigframe_full( &layout, &interrupted_ctx, fpu_state, - sig.as_u8() as u32, + &siginfo, + altstack.as_stack_t_fields(interrupted_rsp), + old_blocked, handler, restorer, &mut frame_bytes, @@ -1507,7 +1998,13 @@ pub fn try_deliver_signal_on_irq_return( } }; let index = (sig.as_u8() - 1) as usize; - let stack_still_matches = resolve_sigframe_stack_irq(interrupted_rsp, &proc) == stack; + let stack_still_matches = if let Some((_, _, alt_s)) = + choose_altstack_target(interrupted_rsp, sa_flags, proc.sigaltstack) + { + proc.sigaltstack == altstack && alt_s == stack + } else { + proc.sigaltstack == altstack && resolve_sigframe_stack_irq(interrupted_rsp, &proc) == stack + }; // GAP-5: hold the table (try-locked; IRQ context) across the recheck and // the SA_RESETHAND commit so a sibling's rt_sigaction cannot interleave. let sigactions = Arc::clone(&proc.sigactions); @@ -1562,3 +2059,401 @@ pub fn try_deliver_signal_on_irq_return( // Return the redirect target: (handler RIP, frame_base RSP, sanitized RFLAGS). Some((handler, frame_base, new_rflags)) } + +#[cfg(test)] +mod n2_6a_signal_tests { + use super::*; + use crate::signal::{ + RtSigQueue, SigAltStack, SigInfo, Signal, MAX_QUEUED_RT_SIGNALS, MINSIGSTKSZ, SA_ONSTACK, + SI_QUEUE, SI_USER, SS_DISABLE, SS_ONSTACK, + }; + + #[test] + fn n2_6a_rt_sigqueue_fifo_and_bounded_capacity() { + let sig34 = Signal::from_raw(34).unwrap(); + let sig35 = Signal::from_raw(35).unwrap(); + assert!(sig34.is_realtime()); + assert!(!Signal::SIGUSR1.is_realtime()); + + let mut q = RtSigQueue::new(); + for i in 0..MAX_QUEUED_RT_SIGNALS { + let sig = if i % 2 == 0 { sig34 } else { sig35 }; + let info = SigInfo { + signo: sig.as_i32(), + errno: 0, + code: SI_QUEUE, + pid: 42, + uid: 1000, + value: i as u64, + }; + assert!(q.push(info).is_ok(), "slot {i} must fit"); + } + // Bounded capacity: next push fails with Err(()) -> EAGAIN. + assert!(q.push(SigInfo::default_for(sig34)).is_err()); + + // Popping sig34 drains all even values in strict FIFO order without + // disturbing sig35 entries. + for expected in (0..MAX_QUEUED_RT_SIGNALS).step_by(2) { + assert_eq!(q.peek(sig34).map(|s| s.value), Some(expected as u64)); + let popped = q.pop(sig34).expect("sig34 entry"); + assert_eq!(popped.value, expected as u64); + assert_eq!(popped.code, SI_QUEUE); + } + assert!(!q.has_signal(sig34)); + assert!(q.has_signal(sig35)); + + // remove_all clears all remaining sig35 entries. + q.remove_all(sig35); + assert!(q.is_empty()); + } + + #[test] + fn n2_6a_siginfo_wire_roundtrip_and_zero_padding() { + let info = SigInfo { + signo: 36, + errno: 7, + code: SI_QUEUE, + pid: 1234, + uid: 5678, + value: 0xDEAD_BEEF_CAFE_BABE, + }; + let mut wire = [0xA5u8; 128]; + info.write_wire_bytes(&mut wire); + assert_eq!(&wire[12..16], &[0, 0, 0, 0], "x86_64 pad0 must be zero"); + assert!(wire[32..].iter().all(|&b| b == 0), "tail must be zero"); + + let parsed = SigInfo::from_wire_bytes(36, &wire); + assert_eq!(parsed, info); + // signo argument overrides wire si_signo (Linux rt_sigqueueinfo contract). + let overridden = SigInfo::from_wire_bytes(40, &wire); + assert_eq!(overridden.signo, 40); + assert_eq!(overridden.value, info.value); + } + + #[test] + fn n2_6a_sigaltstack_validation_and_on_stack_eperm() { + let mut cur = SigAltStack::disabled(); + let main_rsp = 0x7FFF_0000u64; + + // Query disabled state. + let (next, old) = apply_sigaltstack_update(cur, main_rsp, None).unwrap(); + assert_eq!(next, cur); + assert_eq!(old.ss_flags, SS_DISABLE as i32); + assert_eq!(old.ss_sp, 0); + assert_eq!(old.ss_size, 0); + + // Reject too-small stack (< MINSIGSTKSZ) with ENOMEM. + assert_eq!( + apply_sigaltstack_update( + cur, + main_rsp, + Some(StackT { + ss_sp: 0x20_0000, + ss_flags: 0, + _pad: 0, + ss_size: MINSIGSTKSZ - 1, + }) + ), + Err(SyscallError::ENOMEM) + ); + + // Reject SS_ONSTACK as an input flag with EINVAL. + assert_eq!( + apply_sigaltstack_update( + cur, + main_rsp, + Some(StackT { + ss_sp: 0x20_0000, + ss_flags: SS_ONSTACK as i32, + _pad: 0, + ss_size: MINSIGSTKSZ, + }) + ), + Err(SyscallError::EINVAL) + ); + + // Reject kernel/non-canonical address with EINVAL. + assert_eq!( + apply_sigaltstack_update( + cur, + main_rsp, + Some(StackT { + ss_sp: 0xFFFF_8000_0000_0000, + ss_flags: 0, + _pad: 0, + ss_size: MINSIGSTKSZ, + }) + ), + Err(SyscallError::EINVAL) + ); + + // Install valid alternate stack. + let (installed, _) = apply_sigaltstack_update( + cur, + main_rsp, + Some(StackT { + ss_sp: 0x30_0000, + ss_flags: 0, + _pad: 0, + ss_size: MINSIGSTKSZ * 2, + }), + ) + .unwrap(); + cur = installed; + assert!(cur.is_enabled()); + assert!(!cur.on_stack(main_rsp)); + + // While executing inside the altstack, query reports SS_ONSTACK and + // any modification fails with EPERM. + let alt_rsp = 0x30_0000 + MINSIGSTKSZ as u64; + assert!(cur.on_stack(alt_rsp)); + let (_, queried) = apply_sigaltstack_update(cur, alt_rsp, None).unwrap(); + assert_eq!(queried.ss_flags, SS_ONSTACK as i32); + assert_eq!(queried.ss_sp, 0x30_0000); + assert_eq!( + apply_sigaltstack_update( + cur, + alt_rsp, + Some(StackT { + ss_sp: 0, + ss_flags: SS_DISABLE as i32, + _pad: 0, + ss_size: 0, + }) + ), + Err(SyscallError::EPERM) + ); + + // Off-stack disable succeeds and returns prior active stack. + let (disabled, prev) = apply_sigaltstack_update( + cur, + main_rsp, + Some(StackT { + ss_sp: 0, + ss_flags: SS_DISABLE as i32, + _pad: 0, + ss_size: 0, + }), + ) + .unwrap(); + assert!(!disabled.is_enabled()); + assert_eq!(prev.ss_sp, 0x30_0000); + assert_eq!(prev.ss_flags, 0); + } + + #[test] + fn n2_6a_sa_onstack_layout_and_sigframe_full_fields() { + let alt = SigAltStack { + sp: 0x50_0000, + size: MINSIGSTKSZ as u64, + flags: 0, + }; + let main_rsp = 0x7FFF_1000u64; + + // Without SA_ONSTACK, altstack is not selected. + assert!(choose_altstack_target(main_rsp, 0, alt).is_none()); + + // With SA_ONSTACK from main stack, switches to altstack top without red zone. + let (target_rsp, skip_rz, stack) = + choose_altstack_target(main_rsp, SA_ONSTACK, alt).expect("altstack selected"); + assert_eq!(target_rsp, 0x50_0000 + MINSIGSTKSZ as u64); + assert!(!skip_rz); + assert_eq!(stack.layout_floor(target_rsp), 0x50_0000); + + let layout = crate::signal_frame::compute_sigframe_layout_with_redzone( + target_rsp, + stack.layout_floor(target_rsp), + skip_rz, + ) + .expect("MINSIGSTKSZ altstack must fit full sigframe"); + assert_eq!(layout.frame_base & 0xF, 8); + assert!(layout.frame_base >= alt.sp); + assert!(layout.frame_base + crate::signal_frame::SIGFRAME_SIZE as u64 <= target_rsp); + + // Already running on altstack keeps current RSP and red zone. + let nested_rsp = alt.sp + 1600; + let (nested_top, nested_rz, _) = + choose_altstack_target(nested_rsp, SA_ONSTACK, alt).expect("nested altstack"); + assert_eq!(nested_top, nested_rsp); + assert!(nested_rz); + + // Full sigframe assembly writes siginfo + uc_stack + uc_sigmask accurately. + let mut ctx = crate::signal_frame::SavedUserContext::default(); + ctx.rip = 0x40_1000; + ctx.rsp = main_rsp; + ctx.rflags = 0x202; + let fx = [0u8; crate::signal_frame::FXSAVE_SIZE]; + let info = SigInfo { + signo: 35, + errno: 0, + code: SI_QUEUE, + pid: 77, + uid: 1000, + value: 0x1122_3344_5566_7788, + }; + let mut buf = [0u8; crate::signal_frame::SIGFRAME_SIZE]; + crate::signal_frame::assemble_sigframe_full( + &layout, + &ctx, + &fx, + &info, + alt.as_stack_t_fields(main_rsp), + 0x0000_0000_0000_0200, + 0x40_2000, + 0x40_3000, + &mut buf, + ) + .expect("assemble full sigframe"); + // uc_stack at uc+16 (frame+24): ss_sp, ss_flags, ss_size + assert_eq!( + u64::from_ne_bytes(buf[24..32].try_into().unwrap()), + 0x50_0000 + ); + assert_eq!(u32::from_ne_bytes(buf[32..36].try_into().unwrap()), 0); + assert_eq!( + u64::from_ne_bytes(buf[40..48].try_into().unwrap()), + MINSIGSTKSZ as u64 + ); + // uc_sigmask at frame+304 + assert_eq!( + u64::from_ne_bytes(buf[304..312].try_into().unwrap()), + 0x0200 + ); + // siginfo at frame+312 + assert_eq!(i32::from_ne_bytes(buf[312..316].try_into().unwrap()), 35); + assert_eq!( + i32::from_ne_bytes(buf[320..324].try_into().unwrap()), + SI_QUEUE + ); + assert_eq!(i32::from_ne_bytes(buf[328..332].try_into().unwrap()), 77); + assert_eq!(u32::from_ne_bytes(buf[332..336].try_into().unwrap()), 1000); + assert_eq!( + u64::from_ne_bytes(buf[336..344].try_into().unwrap()), + 0x1122_3344_5566_7788 + ); + } + + #[test] + fn n2_6a_sa_restart_syscall_classification() { + use seccomp::syscall_table as st; + let z = [0u64; 6]; + for nr in [ + st::SYS_READ, + st::SYS_WRITE, + st::SYS_READV, + st::SYS_WRITEV, + st::SYS_WAIT4, + st::SYS_WAITID, + st::SYS_ACCEPT, + st::SYS_ACCEPT4, + st::SYS_SENDTO, + st::SYS_RECVFROM, + st::SYS_SENDMSG, + st::SYS_RECVMSG, + ] { + assert!( + is_restartable_syscall(nr, &z), + "syscall {nr} must be restartable under SA_RESTART" + ); + } + // FUTEX_WAIT / FUTEX_WAIT_BITSET with NULL timeout are restartable; with + // non-null timeout or FUTEX_WAKE are not. + assert!(is_restartable_syscall(st::SYS_FUTEX, &[0, 0, 0, 0, 0, 0])); + assert!(is_restartable_syscall(st::SYS_FUTEX, &[0, 128, 0, 0, 0, 0])); // PRIVATE|WAIT + assert!(is_restartable_syscall(st::SYS_FUTEX, &[0, 9, 0, 0, 0, 0])); + assert!(!is_restartable_syscall( + st::SYS_FUTEX, + &[0, 0, 0, 0x1000, 0, 0] + )); + assert!(!is_restartable_syscall(st::SYS_FUTEX, &[0, 1, 0, 0, 0, 0])); // WAKE + + // Never-restartable syscalls per Linux signal(7). + for nr in [ + st::SYS_NANOSLEEP, + st::SYS_POLL, + st::SYS_PPOLL, + st::SYS_SELECT, + st::SYS_PSELECT6, + st::SYS_RT_SIGSUSPEND, + st::SYS_RT_SIGTIMEDWAIT, + st::SYS_CONNECT, + ] { + assert!( + !is_restartable_syscall(nr, &z), + "syscall {nr} must NEVER restart under SA_RESTART" + ); + } + } + + #[test] + fn n2_6a_process_group_rt_queue_and_sigwait_fifo() { + let proc_arc = Arc::new(crate::owner_lock::OwnerCpuMutex::new( + crate::process::Process::new(901, 1, alloc::string::String::from("rt-test"), 10), + )); + let sig34 = Signal::from_raw(34).unwrap(); + let sigusr1 = Signal::SIGUSR1; + + { + let p = proc_arc.lock(); + for val in [100u64, 200, 300] { + p.thread_group + .queue_shared_info( + sig34, + Some(SigInfo { + signo: 34, + errno: 0, + code: SI_QUEUE, + pid: 11, + uid: 0, + value: val, + }), + true, + ) + .expect("queue rt signal"); + } + // Standard signal coalesces to first payload. + p.thread_group + .queue_shared_info( + sigusr1, + Some(SigInfo::from_sender(sigusr1, SI_USER, 11, 0)), + false, + ) + .unwrap(); + p.thread_group + .queue_shared_info( + sigusr1, + Some(SigInfo::from_sender(sigusr1, SI_USER, 99, 0)), + false, + ) + .unwrap(); + } + + // Dequeue all 3 RT instances in FIFO order via take_pending_for_sigwait. + let mut p = proc_arc.lock(); + let (s1, i1) = p.take_pending_for_sigwait(sig34.bit()).expect("1st rt"); + assert_eq!((s1, i1.value), (sig34, 100)); + assert_ne!( + p.pending_bits() & sig34.bit(), + 0, + "2 instances still remain" + ); + + let (s2, i2) = p.take_pending_for_sigwait(sig34.bit()).expect("2nd rt"); + assert_eq!((s2, i2.value), (sig34, 200)); + assert_ne!( + p.pending_bits() & sig34.bit(), + 0, + "1 instance still remains" + ); + + let (s3, i3) = p.take_pending_for_sigwait(sig34.bit()).expect("3rd rt"); + assert_eq!((s3, i3.value), (sig34, 300)); + assert_eq!(p.pending_bits() & sig34.bit(), 0, "queue drained"); + assert!(p.take_pending_for_sigwait(sig34.bit()).is_none()); + + // Standard signal delivers once with first sender pid (11). + let (su, iu) = p.take_pending_for_sigwait(sigusr1.bit()).expect("usr1"); + assert_eq!((su, iu.pid), (sigusr1, 11)); + assert!(p.take_pending_for_sigwait(sigusr1.bit()).is_none()); + } +} diff --git a/kernel/seccomp/syscall_table.rs b/kernel/seccomp/syscall_table.rs index b9358fe..aaad86b 100644 --- a/kernel/seccomp/syscall_table.rs +++ b/kernel/seccomp/syscall_table.rs @@ -333,6 +333,12 @@ define_syscall_table! { (107, SYS_GETEUID, Geteuid, "geteuid", strict: false, drop_proc: false, status: Dispatched, pledge: PledgePolicy::Promises(P_STDIO), reason: ""), (108, SYS_GETEGID, Getegid, "getegid", strict: false, drop_proc: false, status: Dispatched, pledge: PledgePolicy::Promises(P_STDIO), reason: ""), (110, SYS_GETPPID, Getppid, "getppid", strict: false, drop_proc: false, status: Dispatched, pledge: PledgePolicy::Promises(P_STDIO), reason: ""), + // Extended RT signals & alternate signal stack (N2.6a) + (127, SYS_RT_SIGPENDING, RtSigpending, "rt_sigpending", strict: false, drop_proc: false, status: Dispatched, pledge: PledgePolicy::Unpledged, reason: ""), + (128, SYS_RT_SIGTIMEDWAIT, RtSigtimedwait, "rt_sigtimedwait", strict: false, drop_proc: false, status: Dispatched, pledge: PledgePolicy::Unpledged, reason: ""), + (129, SYS_RT_SIGQUEUEINFO, RtSigqueueinfo, "rt_sigqueueinfo", strict: false, drop_proc: true, status: Dispatched, pledge: PledgePolicy::Unpledged, reason: ""), + (130, SYS_RT_SIGSUSPEND, RtSigsuspend, "rt_sigsuspend", strict: false, drop_proc: false, status: Dispatched, pledge: PledgePolicy::Unpledged, reason: ""), + (131, SYS_SIGALTSTACK, Sigaltstack, "sigaltstack", strict: false, drop_proc: false, status: Dispatched, pledge: PledgePolicy::Unpledged, reason: ""), // Root/prctl/arch/rlimit/sync (155, SYS_PIVOT_ROOT, PivotRoot, "pivot_root", strict: false, drop_proc: false, status: Dispatched, pledge: PledgePolicy::Unpledged, reason: ""), (157, SYS_PRCTL, Prctl, "prctl", strict: false, drop_proc: false, status: Dispatched, pledge: PledgePolicy::Unpledged, reason: ""), @@ -365,6 +371,7 @@ define_syscall_table! { (288, SYS_ACCEPT4, Accept4, "accept4", strict: false, drop_proc: false, status: Dispatched, pledge: PledgePolicy::Unpledged, reason: ""), (292, SYS_DUP3, Dup3, "dup3", strict: false, drop_proc: false, status: Dispatched, pledge: PledgePolicy::Unpledged, reason: ""), (293, SYS_PIPE2, Pipe2, "pipe2", strict: false, drop_proc: false, status: Dispatched, pledge: PledgePolicy::Unpledged, reason: ""), + (297, SYS_RT_TGSIGQUEUEINFO, RtTgsigqueueinfo, "rt_tgsigqueueinfo", strict: false, drop_proc: true, status: Dispatched, pledge: PledgePolicy::Unpledged, reason: ""), (302, SYS_PRLIMIT64, Prlimit64, "prlimit64", strict: false, drop_proc: false, status: Dispatched, pledge: PledgePolicy::Promises(P_RLIMIT), reason: ""), (308, SYS_SETNS, Setns, "setns", strict: false, drop_proc: false, status: Dispatched, pledge: PledgePolicy::Unpledged, reason: ""), (316, SYS_RENAMEAT2, Renameat2, "renameat2", strict: false, drop_proc: false, status: Dispatched, pledge: PledgePolicy::PrivateNeverPledged, reason: ""), diff --git a/scripts/tools/abi_layout_oracle.py b/scripts/tools/abi_layout_oracle.py index 2077172..975286c 100644 --- a/scripts/tools/abi_layout_oracle.py +++ b/scripts/tools/abi_layout_oracle.py @@ -409,6 +409,14 @@ def _sub_sizeof(m): fields=[("handler", 0, 8), ("flags", 8, 8), ("restorer", 16, 8), ("mask", 24, 8)], size=32, ), + "StackT": dict( + src="syscall_abi", layer=LINUX_UAPI, + cite="uapi/asm-generic/signal.h stack_t (x86-64, 24B)", + fields=[("ss_sp", 0, 8), ("ss_flags", 8, 4), ("_pad", 12, 4), + ("ss_size", 16, 8)], size=24, + c_type="stack_t", c_include="signal.h", + c_fields=[("ss_sp", 0), ("ss_flags", 8), ("ss_size", 16)], + ), "VfsStat": dict( # D2-ABI-STAT-LAYOUT RESOLVED (2026-07-24): converted from the former # 112-byte private layout to the Linux x86-64 struct stat wire layout. @@ -563,6 +571,7 @@ def emit_c(reference): lines.append("#include ") lines.append("#include ") lines.append("#include ") + lines.append("#include ") lines.append("#if defined(__has_include)") lines.append("# if __has_include()") lines.append("# include ") diff --git a/scripts/tools/hosted_subcrate_tests.sh b/scripts/tools/hosted_subcrate_tests.sh index 51c12cd..3a1e0e5 100755 --- a/scripts/tools/hosted_subcrate_tests.sh +++ b/scripts/tools/hosted_subcrate_tests.sh @@ -246,7 +246,7 @@ run_suite cgroup-access 1 0 \ # Includes the C3 aligned TID store and concurrent word tests, the C3 # work-stealing hint with its model, and P2 wake-affine / placement / voluntary-yield policy tests. -run_suite kernel-core 221 0 \ +run_suite kernel-core 227 0 \ --manifest-path kernel/kernel_core/Cargo.toml \ --target x86_64-unknown-linux-gnu \ --features host_harness \ @@ -292,7 +292,7 @@ run_suite security-wxorx 6 14 \ --features mm/host_harness,cpu_local/host_harness \ --lib --locked -- wxorx::tests -run_suite mitigation-mappings 5 221 \ +run_suite mitigation-mappings 5 227 \ --manifest-path kernel/kernel_core/Cargo.toml \ --target x86_64-unknown-linux-gnu \ --features host_harness,mitigation_probe \