diff --git a/kernel/kernel_core/fork.rs b/kernel/kernel_core/fork.rs index 88688b1..e8780b9 100644 --- a/kernel/kernel_core/fork.rs +++ b/kernel/kernel_core/fork.rs @@ -770,6 +770,9 @@ fn fork_prepare_child_state( child.blocked = parent.blocked; // N2.6a: POSIX/Linux fork(2) inherits the parent's alternate signal stack. child.sigaltstack = parent.sigaltstack; + // N2.5: POSIX/Linux fork(2) inherits process group, session, and + // controlling terminal; child starts with has_execed = false. + child.thread_group.inherit_job_control(&parent.thread_group); // 克隆能力表(尊重 CLOFORK 标志) // diff --git a/kernel/kernel_core/process.rs b/kernel/kernel_core/process.rs index d7959e4..a3b3f3c 100644 --- a/kernel/kernel_core/process.rs +++ b/kernel/kernel_core/process.rs @@ -2800,6 +2800,18 @@ pub struct ThreadGroup { /// G8 (review D3): members inside a group-wide wait for children; a /// report scans for sleeping members only while this is non-zero. child_waiters: AtomicUsize, + /// N2.5: Process group ID (global leader PID; 0 only before birth binding). + pgid: AtomicUsize, + /// N2.5: Session ID (global session leader PID; 0 only before birth binding). + sid: AtomicUsize, + /// N2.5: True once this process has called `execve(2)` (POSIX `setpgid` EACCES gate). + has_execed: AtomicBool, + /// N2.5: True while this process is attached to the console controlling terminal. + has_ctty: AtomicBool, + /// N2.5: Bit-packed unreported job-control wait events: + /// bits 0..8 = unreported stop signal (non-zero => WUNTRACED/WSTOPPED pending), + /// bit 8 = unreported SIGCONT resume (1 => WCONTINUED pending). + job_wait_state: core::sync::atomic::AtomicU32, } impl ThreadGroup { @@ -2829,9 +2841,145 @@ impl ThreadGroup { live: AtomicUsize::new(1), child_events: AtomicU64::new(0), child_waiters: AtomicUsize::new(0), + pgid: AtomicUsize::new(0), + sid: AtomicUsize::new(0), + has_execed: AtomicBool::new(false), + has_ctty: AtomicBool::new(false), + job_wait_state: core::sync::atomic::AtomicU32::new(0), } } + // ── N2.5: Process group, session, ctty, and job-control wait ledger ── + + const JOB_WAIT_STOP_MASK: u32 = 0xFF; + const JOB_WAIT_CONTINUED_BIT: u32 = 1 << 8; + + /// Initialize default PGID/SID to `tgid` if not yet bound (boot/init/standalone PCB). + #[inline] + pub(crate) fn init_job_control(&self, tgid: ProcessId) { + let _ = self + .pgid + .compare_exchange(0, tgid, Ordering::AcqRel, Ordering::Acquire); + let _ = self + .sid + .compare_exchange(0, tgid, Ordering::AcqRel, Ordering::Acquire); + } + + /// POSIX `fork(2)`: inherit parent's PGID, SID, and controlling-terminal + /// attachment; child starts with `has_execed == false` and no pending wait events. + pub(crate) fn inherit_job_control(&self, parent: &ThreadGroup) { + self.pgid.store(parent.pgid(), Ordering::Release); + self.sid.store(parent.sid(), Ordering::Release); + self.has_ctty.store(parent.has_ctty(), Ordering::Release); + self.has_execed.store(false, Ordering::Release); + self.job_wait_state.store(0, Ordering::Release); + } + + #[inline] + pub fn pgid(&self) -> ProcessId { + self.pgid.load(Ordering::Acquire) + } + + #[inline] + pub fn set_pgid(&self, pgid: ProcessId) { + self.pgid.store(pgid, Ordering::Release); + } + + #[inline] + pub fn sid(&self) -> ProcessId { + self.sid.load(Ordering::Acquire) + } + + #[inline] + pub fn set_sid(&self, sid: ProcessId) { + self.sid.store(sid, Ordering::Release); + } + + #[inline] + pub fn has_execed(&self) -> bool { + self.has_execed.load(Ordering::Acquire) + } + + #[inline] + pub fn mark_execed(&self) { + self.has_execed.store(true, Ordering::Release); + } + + #[inline] + pub fn has_ctty(&self) -> bool { + self.has_ctty.load(Ordering::Acquire) + } + + #[inline] + pub fn set_has_ctty(&self, attached: bool) { + self.has_ctty.store(attached, Ordering::Release); + } + + /// Record an unreported job-control stop (cancels any stale continued flag). + #[inline] + pub fn record_stop_event(&self, stop_sig: u8) { + self.job_wait_state.store( + (stop_sig as u32) & Self::JOB_WAIT_STOP_MASK, + Ordering::Release, + ); + } + + /// Record an unreported job-control continuation (clears any stale stop flag). + #[inline] + pub fn record_continue_event(&self) { + self.job_wait_state + .store(Self::JOB_WAIT_CONTINUED_BIT, Ordering::Release); + } + + /// Peek unreported stop signal without consuming it (`WNOWAIT`). + #[inline] + pub fn peek_stop_event(&self) -> Option { + let sig = (self.job_wait_state.load(Ordering::Acquire) & Self::JOB_WAIT_STOP_MASK) as u8; + (sig != 0).then_some(sig) + } + + /// Atomically consume an unreported stop signal (returns `Some(sig)` to at most one waiter). + pub fn take_stop_event(&self) -> Option { + let mut cur = self.job_wait_state.load(Ordering::Acquire); + loop { + let sig = (cur & Self::JOB_WAIT_STOP_MASK) as u8; + if sig == 0 { + return None; + } + let next = cur & !Self::JOB_WAIT_STOP_MASK; + match self.job_wait_state.compare_exchange_weak( + cur, + next, + Ordering::AcqRel, + Ordering::Acquire, + ) { + Ok(_) => return Some(sig), + Err(actual) => cur = actual, + } + } + } + + /// Peek unreported `WCONTINUED` event without consuming it (`WNOWAIT`). + #[inline] + pub fn peek_continue_event(&self) -> bool { + (self.job_wait_state.load(Ordering::Acquire) & Self::JOB_WAIT_CONTINUED_BIT) != 0 + } + + /// Atomically consume an unreported `WCONTINUED` event. + pub fn take_continue_event(&self) -> bool { + (self + .job_wait_state + .fetch_and(!Self::JOB_WAIT_CONTINUED_BIT, Ordering::AcqRel) + & Self::JOB_WAIT_CONTINUED_BIT) + != 0 + } + + /// Clear unreported stop/continue events (called on process exit). + #[inline] + pub fn clear_job_wait_events(&self) { + self.job_wait_state.store(0, Ordering::Release); + } + /// G8 (review D3): the child-report count a group-wide wait compares /// before it sleeps. pub(crate) fn child_events(&self) -> u64 { @@ -4249,6 +4397,12 @@ impl Process { addr_of_mut!((*dst).cap_table).write(cap_table); addr_of_mut!((*dst).exit_code).write(None); + // N2.5: bind default PGID/SID to `pid` (fork overwrites with parent's PGID/SID). + thread_group.init_job_control(pid); + if pid == 1 { + thread_group.set_has_ctty(true); + console_tty_init_root_session(1); + } addr_of_mut!((*dst).thread_group).write(thread_group); addr_of_mut!((*dst).group_fatal).write(false); addr_of_mut!((*dst).group_live).write(true); @@ -13110,6 +13264,12 @@ pub fn terminate_process(pid: ProcessId, exit_code: i32) { if last_live { // N2.6b: Reclaim all interval timers and POSIX timers owned by this process. crate::time::cleanup_all_timers_for_process(tgid); + // N2.5: Clear unreported stop/continue events and release console ctty + // if the exiting process was the controlling session leader. + own_group.clear_job_wait_events(); + if tgid == own_group.sid() { + console_tty_release_session(tgid); + } if tgid == pid { handle_namespace_init_death(pid, &pid_ns_chain); } else { @@ -13365,6 +13525,194 @@ fn notify_parent_of_group_exit( } } +// ============================================================================ +// N2.5: Console Controlling Terminal State & Parent Job-Control Notification +// ============================================================================ + +/// Console controlling terminal ownership (`TIOCSCTTY`/`TIOCGPGRP`/`TIOCSPGRP`/`TIOCNOTTY`). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct ConsoleTtyState { + /// Owning session leader global PID (`None` if detached). + pub(crate) session_sid: Option, + /// Current foreground process group global PGID (`0` if none). + pub(crate) fg_pgid: ProcessId, +} + +impl ConsoleTtyState { + const fn new() -> Self { + Self { + session_sid: None, + fg_pgid: 0, + } + } +} + +static CONSOLE_TTY: Mutex = Mutex::new(ConsoleTtyState::new()); + +/// Seed PID 1's initial session as the default console controlling terminal if +/// no session owns it yet. +pub(crate) fn console_tty_init_root_session(sid: ProcessId) { + let mut tty = CONSOLE_TTY.lock(); + if tty.session_sid.is_none() { + tty.session_sid = Some(sid); + tty.fg_pgid = sid; + } +} + +/// Release the console controlling terminal when its owning session leader exits. +pub(crate) fn console_tty_release_session(sid: ProcessId) -> Option { + let mut tty = CONSOLE_TTY.lock(); + if tty.session_sid == Some(sid) { + let old_fg = tty.fg_pgid; + tty.session_sid = None; + tty.fg_pgid = 0; + return (old_fg != 0).then_some(old_fg); + } + None +} + +/// Pure `TIOCSCTTY` transition helper. +pub(crate) fn console_tty_attach( + sid: ProcessId, + pgid: ProcessId, + steal: bool, + is_privileged: bool, +) -> Result<(), crate::syscall::SyscallError> { + let mut tty = CONSOLE_TTY.lock(); + match tty.session_sid { + None => { + tty.session_sid = Some(sid); + tty.fg_pgid = pgid; + Ok(()) + } + Some(owner) if owner == sid => Ok(()), + Some(_) if steal && is_privileged => { + tty.session_sid = Some(sid); + tty.fg_pgid = pgid; + Ok(()) + } + Some(_) => Err(crate::syscall::SyscallError::EPERM), + } +} + +/// Query foreground PGID for a caller attached to the console controlling terminal. +pub(crate) fn console_tty_get_fg_pgid( + caller_sid: ProcessId, + has_ctty: bool, +) -> Result { + if !has_ctty { + return Err(crate::syscall::SyscallError::ENOTTY); + } + let tty = CONSOLE_TTY.lock(); + if tty.session_sid != Some(caller_sid) { + return Err(crate::syscall::SyscallError::ENOTTY); + } + Ok(tty.fg_pgid) +} + +/// Update foreground PGID for a caller attached to the console controlling terminal. +pub(crate) fn console_tty_set_fg_pgid( + caller_sid: ProcessId, + has_ctty: bool, + new_fg_pgid: ProcessId, +) -> Result<(), crate::syscall::SyscallError> { + if !has_ctty { + return Err(crate::syscall::SyscallError::ENOTTY); + } + let mut tty = CONSOLE_TTY.lock(); + if tty.session_sid != Some(caller_sid) { + return Err(crate::syscall::SyscallError::ENOTTY); + } + tty.fg_pgid = new_fg_pgid; + Ok(()) +} + +/// Query owning session ID for a caller attached to the console controlling terminal. +pub(crate) fn console_tty_get_sid( + caller_sid: ProcessId, + has_ctty: bool, +) -> Result { + if !has_ctty { + return Err(crate::syscall::SyscallError::ENOTTY); + } + let tty = CONSOLE_TTY.lock(); + if tty.session_sid != Some(caller_sid) { + return Err(crate::syscall::SyscallError::ENOTTY); + } + Ok(caller_sid) +} + +/// Check whether at least one live (non-zombie, non-terminated) process in +/// session `sid` currently belongs to process group `pgid`. +pub(crate) fn pgid_exists_in_session(pgid: ProcessId, sid: ProcessId) -> bool { + let table = PROCESS_TABLE.lock(); + for slot in table.iter() { + let Some(arc) = slot else { continue }; + let proc = arc.lock(); + if matches!(proc.state, ProcessState::Zombie | ProcessState::Terminated) { + continue; + } + if proc.thread_group.sid() == sid && proc.thread_group.pgid() == pgid { + return true; + } + } + false +} + +/// N2.5: Notify the parent of `child_pid` that the child stopped (`stopped == true`) +/// or continued (`stopped == false`). +/// +/// Honors `SA_NOCLDSTOP` on the parent's `SIGCHLD` disposition (suppresses the +/// `SIGCHLD` signal itself while still advancing `child_events` and waking any +/// parent blocked in `wait4`/`waitid` with `WUNTRACED`/`WCONTINUED`). +pub(crate) fn notify_parent_of_job_control_event(child_pid: ProcessId, _stopped: bool) { + let (leader_pid, parent_pid, parent_arc) = { + let table = PROCESS_TABLE.lock(); + let Some(child_arc) = table.get(child_pid).and_then(Option::as_ref) else { + return; + }; + let (tgid, ppid) = { + let child = child_arc.lock(); + (child.tgid, child.ppid) + }; + if ppid == 0 { + return; + } + let parent_arc = table.get(ppid).and_then(Option::as_ref).map(Arc::clone); + (tgid, ppid, parent_arc) + }; + + let send_sigchld = parent_arc.as_ref().is_some_and(|p| { + let sigactions = Arc::clone(&p.lock().sigactions); + let chld = sigactions.get((crate::signal::Signal::SIGCHLD.as_u8() - 1) as usize); + (chld.flags & crate::signal::SA_NOCLDSTOP) == 0 + }); + if send_sigchld { + let _ = crate::signal::send_signal_kernel(parent_pid, crate::signal::Signal::SIGCHLD); + } + + let (mut wake_parent, parent_group, single_member) = if let Some(parent) = parent_arc { + let mut parent_proc = parent.lock(); + let (woke, group, single) = notify_parent_pcb_for_child_exit( + &mut parent_proc, + leader_pid, + crate::get_ticks(), + false, + ); + (woke, Some(group), single) + } else { + (false, None, false) + }; + if let Some(group) = parent_group { + if !single_member { + wake_parent |= wake_group_child_waiters(&group, leader_pid); + } + } + if wake_parent { + let _ = crate::signal::kernel_kick_published(); + } +} + /// GAP-5 G8 (review D3): a child of a member of `group` became reportable. /// Count the report, and wake every member sleeping in a wait for any child or /// for `child_pid`. Returns whether one was woken (the caller kicks). Process diff --git a/kernel/kernel_core/signal.rs b/kernel/kernel_core/signal.rs index d93a448..14add64 100644 --- a/kernel/kernel_core/signal.rs +++ b/kernel/kernel_core/signal.rs @@ -149,13 +149,13 @@ impl Signal { /// Get raw signal number #[inline] - pub fn as_u8(self) -> u8 { + pub const fn as_u8(self) -> u8 { self.0 } /// Get signal number as i32 (for syscall compatibility) #[inline] - pub fn as_i32(self) -> i32 { + pub const fn as_i32(self) -> i32 { self.0 as i32 } @@ -1754,6 +1754,8 @@ fn send_signal_inner( // GAP-5 slice 4 G7: a stop applied here (false) or a SIGCONT (true) is // carried to the rest of the thread group after the lock is released. let mut group_job_control: Option = None; + // N2.5: notify parent of job-control stop (Some(true)) or continue (Some(false)). + let mut job_control_notify_stopped: Option = None; // GAP-5 G7 (review D3): a process-directed signal the selected member // cannot take now is offered to another member after the lock is released. let mut retarget_group: Option> = None; @@ -1906,7 +1908,9 @@ fn send_signal_inner( // RF178-35 FIX: a lock-serialized fatal publication wins over // a later stop and cannot be stranded again. if process::try_mark_job_control_stopped_locked(&mut proc) { + proc.thread_group.record_stop_event(signal.as_u8()); group_job_control = Some(false); + job_control_notify_stopped = Some(true); if process::current_pid() == Some(pid) { needs_reschedule = true; } @@ -1923,7 +1927,12 @@ fn send_signal_inner( }, } if signal.is_continue() { + let was_stopped = proc.stopped || proc.state == ProcessState::Stopped; needs_kick |= process::resume_job_control_locked(&mut proc, pid, target_generation); + if was_stopped { + proc.thread_group.record_continue_event(); + job_control_notify_stopped = Some(false); + } group_job_control = Some(true); } // GAP-5 G7 (review D3): the selection read this member's mask without @@ -1954,6 +1963,11 @@ fn send_signal_inner( needs_kick |= process::propagate_group_job_control(pid, resume); } + // N2.5: notify parent of WUNTRACED / WCONTINUED transition (respects SA_NOCLDSTOP). + if let Some(stopped) = job_control_notify_stopped { + process::notify_parent_of_job_control_event(pid, stopped); + } + // H.0.7 FIX: Cross-CPU-safe fatal signal termination. // // send_signal_inner() may target a process running on another CPU (e.g. via diff --git a/kernel/kernel_core/syscall/exec.rs b/kernel/kernel_core/syscall/exec.rs index 6712da6..2f8698a 100644 --- a/kernel/kernel_core/syscall/exec.rs +++ b/kernel/kernel_core/syscall/exec.rs @@ -1200,6 +1200,8 @@ pub(super) fn exec_from_bytes( proc.poll_restore_blocked = None; // N2.6a: POSIX/Linux execve(2) disables any established alternate signal stack. proc.sigaltstack = crate::signal::SigAltStack::disabled(); + // N2.5: Mark process as having executed a new image (POSIX setpgid EACCES rule). + proc.thread_group.mark_execed(); let exec_tgid = proc.tgid; // Robust-list registration is address-space-local. Clear the old // image's pointer before publishing the replacement so exit cleanup diff --git a/kernel/kernel_core/syscall/fs.rs b/kernel/kernel_core/syscall/fs.rs index 63e1bbc..36fd6e4 100644 --- a/kernel/kernel_core/syscall/fs.rs +++ b/kernel/kernel_core/syscall/fs.rs @@ -1590,6 +1590,12 @@ pub(super) fn sys_ioctl(fd: i32, cmd: u64, arg: u64) -> SyscallResult { const TIOCGWINSZ: u64 = 0x5413; // Get window size const TIOCSWINSZ: u64 = 0x5414; // Set window size const FIONREAD: u64 = 0x541B; // Bytes available to read + // N2.5: Controlling terminal & foreground process group job control ioctls. + const TIOCSCTTY: u64 = 0x540E; // Make controlling terminal + const TIOCGPGRP: u64 = 0x540F; // Get foreground process group + const TIOCSPGRP: u64 = 0x5410; // Set foreground process group + const TIOCNOTTY: u64 = 0x5422; // Give up controlling terminal + const TIOCGSID: u64 = 0x5429; // Get session ID of controlling terminal match cmd { TCGETS if console.is_some() => { @@ -1655,6 +1661,130 @@ pub(super) fn sys_ioctl(fd: i32, cmd: u64, arg: u64) -> SyscallResult { .map_err(|_| SyscallError::EFAULT)?; Ok(0) } + TIOCSCTTY if console.is_some() => { + let pid = current_pid().ok_or(SyscallError::ESRCH)?; + let proc_arc = get_process(pid).ok_or(SyscallError::ESRCH)?; + let (tgid, sid, pgid, has_ctty) = { + let p = proc_arc.lock(); + ( + p.tgid, + p.thread_group.sid(), + p.thread_group.pgid(), + p.thread_group.has_ctty(), + ) + }; + // Must be a session leader. + if tgid != sid { + return Err(SyscallError::EPERM); + } + let steal = arg == 1; + let privileged = + current_has_cap_rights(cap::CapRights::ADMIN) || crate::current_is_host_root(); + if has_ctty && crate::process::console_tty_get_sid(sid, true).is_ok() { + return Ok(0); + } + crate::process::console_tty_attach(sid, pgid, steal, privileged)?; + proc_arc.lock().thread_group.set_has_ctty(true); + Ok(0) + } + TIOCNOTTY if console.is_some() => { + let pid = current_pid().ok_or(SyscallError::ESRCH)?; + let proc_arc = get_process(pid).ok_or(SyscallError::ESRCH)?; + let (tgid, sid, has_ctty) = { + let p = proc_arc.lock(); + (p.tgid, p.thread_group.sid(), p.thread_group.has_ctty()) + }; + // Verify this console is indeed the caller's controlling terminal. + let _ = crate::process::console_tty_get_sid(sid, has_ctty)?; + proc_arc.lock().thread_group.set_has_ctty(false); + if tgid == sid { + if let Some(old_fg) = crate::process::console_tty_release_session(sid) { + // POSIX: notify former foreground process group with SIGHUP + SIGCONT. + let _ = send_signal_to_pgid_kernel(old_fg, crate::signal::Signal::SIGHUP); + let _ = send_signal_to_pgid_kernel(old_fg, crate::signal::Signal::SIGCONT); + } + } + Ok(0) + } + TIOCGPGRP if console.is_some() => { + if arg == 0 { + return Err(SyscallError::EFAULT); + } + let pid = current_pid().ok_or(SyscallError::ESRCH)?; + let proc_arc = get_process(pid).ok_or(SyscallError::ESRCH)?; + let (sid, has_ctty, owning_ns) = { + let p = proc_arc.lock(); + ( + p.thread_group.sid(), + p.thread_group.has_ctty(), + crate::pid_namespace::owning_namespace(&p.pid_ns_chain), + ) + }; + let fg_global = crate::process::console_tty_get_fg_pgid(sid, has_ctty)?; + let fg_view = match owning_ns { + Some(ns) => ns.lookup_ns_pid(fg_global).unwrap_or(0) as i32, + None => fg_global as i32, + }; + copy_to_user(arg as *mut u8, &fg_view.to_ne_bytes())?; + Ok(0) + } + TIOCSPGRP if console.is_some() => { + if arg == 0 { + return Err(SyscallError::EFAULT); + } + let mut raw = [0u8; 4]; + copy_from_user(&mut raw, arg as *const u8)?; + let req_pgid = i32::from_ne_bytes(raw); + if req_pgid <= 0 { + return Err(SyscallError::EINVAL); + } + let pid = current_pid().ok_or(SyscallError::ESRCH)?; + let proc_arc = get_process(pid).ok_or(SyscallError::ESRCH)?; + let (sid, has_ctty, owning_ns) = { + let p = proc_arc.lock(); + ( + p.thread_group.sid(), + p.thread_group.has_ctty(), + crate::pid_namespace::owning_namespace(&p.pid_ns_chain), + ) + }; + // Verify caller has console ctty first. + let _ = crate::process::console_tty_get_sid(sid, has_ctty)?; + let target_global_pgid = match owning_ns { + Some(ns) => { + crate::pid_namespace::resolve_pid_in_namespace(&ns, req_pgid as ProcessId) + .ok_or(SyscallError::EPERM)? + } + None => req_pgid as ProcessId, + }; + if !crate::process::pgid_exists_in_session(target_global_pgid, sid) { + return Err(SyscallError::EPERM); + } + crate::process::console_tty_set_fg_pgid(sid, has_ctty, target_global_pgid)?; + Ok(0) + } + TIOCGSID if console.is_some() => { + if arg == 0 { + return Err(SyscallError::EFAULT); + } + let pid = current_pid().ok_or(SyscallError::ESRCH)?; + let proc_arc = get_process(pid).ok_or(SyscallError::ESRCH)?; + let (sid, has_ctty, owning_ns) = { + let p = proc_arc.lock(); + ( + p.thread_group.sid(), + p.thread_group.has_ctty(), + crate::pid_namespace::owning_namespace(&p.pid_ns_chain), + ) + }; + let tty_sid = crate::process::console_tty_get_sid(sid, has_ctty)?; + let view_sid = match owning_ns { + Some(ns) => ns.lookup_ns_pid(tty_sid).unwrap_or(0) as i32, + None => tty_sid as i32, + }; + copy_to_user(arg as *mut u8, &view_sid.to_ne_bytes())?; + Ok(0) + } _ => { // For non-standard streams or unknown commands, return ENOTTY Err(SyscallError::ENOTTY) diff --git a/kernel/kernel_core/syscall/mod.rs b/kernel/kernel_core/syscall/mod.rs index a8ebdcd..a8a487a 100644 --- a/kernel/kernel_core/syscall/mod.rs +++ b/kernel/kernel_core/syscall/mod.rs @@ -669,6 +669,12 @@ pub fn syscall_dispatcher( Sc::Getpid => sys_getpid_fast(fast_ns_id), Sc::Gettid => sys_gettid_fast(fast_ns_id), Sc::Getppid => sys_getppid(), + // N2.5: Process groups & sessions. + Sc::Setpgid => sys_setpgid(arg0 as i32, arg1 as i32), + Sc::Getpgrp => sys_getpgrp(), + Sc::Setsid => sys_setsid(), + Sc::Getpgid => sys_getpgid(arg0 as i32), + Sc::Getsid => sys_getsid(arg0 as i32), Sc::Getuid => sys_getuid(), Sc::Geteuid => sys_geteuid(), Sc::Getgid => sys_getgid(), @@ -678,7 +684,7 @@ pub fn syscall_dispatcher( Sc::GetRobustList => { sys_get_robust_list(arg0 as i32, arg1 as *mut u64, arg2 as *mut u64) } - Sc::Kill => sys_kill(arg0 as ProcessId, arg1 as i32), + Sc::Kill => sys_kill(arg0 as i32, arg1 as i32), // GAP-5 slice 4 G7: thread-directed signals. Sc::Tkill => sys_tkill(arg0 as i32, arg1 as i32), Sc::Tgkill => sys_tgkill(arg0 as i32, arg1 as i32, arg2 as i32), diff --git a/kernel/kernel_core/syscall/proc.rs b/kernel/kernel_core/syscall/proc.rs index 50dc8a5..b39c245 100644 --- a/kernel/kernel_core/syscall/proc.rs +++ b/kernel/kernel_core/syscall/proc.rs @@ -1979,30 +1979,61 @@ pub(super) fn sys_wait4( if options & !(WNOHANG | WUNTRACED | WCONTINUED) != 0 { return Err(SyscallError::EINVAL); } - if pid_sel == 0 || pid_sel < -1 { - return Err(SyscallError::EINVAL); - } let target = if pid_sel > 0 { WaitTarget::Pid(pid_sel as ProcessId) - } else { + } else if pid_sel == -1 { WaitTarget::Any + } else if pid_sel == 0 { + let caller_pid = current_pid().ok_or(SyscallError::ESRCH)?; + let caller = entry_proc + .as_ref() + .cloned() + .or_else(|| get_process(caller_pid)) + .ok_or(SyscallError::ESRCH)?; + let pgid = caller.lock().thread_group.pgid(); + WaitTarget::Pgid(pgid) + } else { + // pid_sel < -1: wait for any child whose PGID equals `-pid_sel` + // (resolved in caller's PID namespace). + let local_pgid = (-pid_sel) as ProcessId; + let caller_pid = current_pid().ok_or(SyscallError::ESRCH)?; + let caller = entry_proc + .as_ref() + .cloned() + .or_else(|| get_process(caller_pid)) + .ok_or(SyscallError::ESRCH)?; + let owning_ns = crate::pid_namespace::owning_namespace(&caller.lock().pid_ns_chain); + let global_pgid = match owning_ns { + Some(ns) => crate::pid_namespace::resolve_pid_in_namespace(&ns, local_pgid) + .ok_or(SyscallError::ECHILD)?, + None => local_pgid, + }; + WaitTarget::Pgid(global_pgid) + }; + + let opts = WaitOptions { + nohang: options & WNOHANG != 0, + nowait: false, + exited: true, + stopped: options & WUNTRACED != 0, + continued: options & WCONTINUED != 0, }; // The wstatus store is the core's `publish` step: it runs at the point the - // old inline code wrote it — after a reapable zombie is chosen, before the - // child is unlinked and cleaned up — so an EFAULT leaves the zombie - // reapable and restores the parent to Ready. + // old inline code wrote it — after a child event is chosen, before the + // child is unlinked/cleaned up — so an EFAULT leaves the event reportable + // and restores the parent to Ready. let publish = |outcome: &WaitOutcome| -> Result<(), SyscallError> { if status.is_null() { return Ok(()); } - let wstatus: i32 = (outcome.exit_code & 0xff) << 8; + let wstatus: i32 = outcome.event.encode_wstatus(); copy_to_user(status as *mut u8, &wstatus.to_ne_bytes()) }; - match wait_reap_core_with_parent(target, options & WNOHANG != 0, false, publish, entry_proc)? { + match wait_reap_core_opts(target, opts, publish, entry_proc)? { Some(outcome) => Ok(outcome.view_pid), - // WNOHANG with nothing reapable. + // WNOHANG with nothing reportable. None => Ok(0), } } @@ -2018,13 +2049,56 @@ pub(super) enum WaitTarget { Any, /// Exactly this child, named in the caller's PID namespace. Pid(ProcessId), + /// Any child whose process group ID equals this global PGID + /// (`wait4(0, ..)`, `wait4(-pgid, ..)`, `waitid(P_PGID, ..)`). + Pgid(ProcessId), +} + +/// Which state transitions a wait call is willing to observe. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) struct WaitOptions { + pub(super) nohang: bool, + pub(super) nowait: bool, + pub(super) exited: bool, + pub(super) stopped: bool, + pub(super) continued: bool, +} + +/// State transition reported by `wait4` / `waitid`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum WaitEventKind { + Exited(i32), + Stopped(u8), + Continued, +} + +impl WaitEventKind { + /// Encode as Linux x86_64 `wait4` packed `wstatus`. + #[inline] + pub(super) const fn encode_wstatus(self) -> i32 { + match self { + Self::Exited(code) => (code & 0xff) << 8, + Self::Stopped(sig) => ((sig as i32) << 8) | 0x7f, + Self::Continued => 0xffff, + } + } + + /// Encode as Linux x86_64 `waitid` `(si_code, si_status)`. + #[inline] + pub(super) const fn encode_waitid_code_status(self) -> (i32, i32) { + match self { + Self::Exited(code) => (CLD_EXITED, code & 0xff), + Self::Stopped(sig) => (CLD_STOPPED, sig as i32), + Self::Continued => (CLD_CONTINUED, crate::signal::Signal::SIGCONT.as_i32()), + } + } } -/// A reaped child, described both globally and as the caller sees it. +/// A reported child event, described both globally and as the caller sees it. pub(super) struct WaitOutcome { pub(super) global_pid: ProcessId, pub(super) view_pid: ProcessId, - pub(super) exit_code: i32, + pub(super) event: WaitEventKind, } /// Resolve the wake filter before publishing Blocked. A PID selector must @@ -2057,7 +2131,7 @@ pub(super) fn prepare_child_wait_checked( mut lookup: impl FnMut(ProcessId) -> Option, ) -> Result { let wake_pid = match target { - WaitTarget::Any => Some(0), + WaitTarget::Any | WaitTarget::Pgid(_) => Some(0), WaitTarget::Pid(want) => children.iter().find_map(|&global| { let child = lookup(global)?; let child = child.lock(); @@ -2290,8 +2364,8 @@ mod selective_wait_tests { fn assert_target(&self, result: Result, SyscallError>) { let outcome = result.unwrap().expect("target must be reported"); assert_eq!( - (outcome.global_pid, outcome.view_pid, outcome.exit_code), - (self.base + 3, 4, 22) + (outcome.global_pid, outcome.view_pid, outcome.event), + (self.base + 3, 4, WaitEventKind::Exited(22)) ); let caller = self.caller.lock(); assert_eq!(caller.state, ProcessState::Ready); @@ -2565,12 +2639,37 @@ pub(super) fn wait_reap_core_with_parent( target: WaitTarget, nohang: bool, nowait: bool, + publish: W, + entry_proc: Option, +) -> Result, SyscallError> +where + W: FnMut(&WaitOutcome) -> Result<(), SyscallError>, +{ + wait_reap_core_opts( + target, + WaitOptions { + nohang, + nowait, + exited: true, + stopped: false, + continued: false, + }, + publish, + entry_proc, + ) +} + +pub(super) fn wait_reap_core_opts( + target: WaitTarget, + opts: WaitOptions, mut publish: W, entry_proc: Option, ) -> Result, SyscallError> where W: FnMut(&WaitOutcome) -> Result<(), SyscallError>, { + let nohang = opts.nohang; + let nowait = opts.nowait; let pid = current_pid().ok_or(SyscallError::ESRCH)?; let parent = entry_proc .or_else(|| get_process(pid)) @@ -2594,13 +2693,17 @@ where FastWaitCheck::MultiThread(Arc::clone(&proc.thread_group)) } else if crate::signal::should_abort_pending_block(&proc) { FastWaitCheck::AbortEintr - } else if let WaitTarget::Pid(want) = target { - let ns = crate::pid_namespace::owning_namespace(&proc.pid_ns_chain) - .unwrap_or_else(|| crate::pid_namespace::ROOT_PID_NAMESPACE.clone()); - if Arc::ptr_eq(&ns, &crate::pid_namespace::ROOT_PID_NAMESPACE) - && proc.children.contains(&want) - { - FastWaitCheck::DirectCandidate(want, ns) + } else if opts.exited { + if let WaitTarget::Pid(want) = target { + let ns = crate::pid_namespace::owning_namespace(&proc.pid_ns_chain) + .unwrap_or_else(|| crate::pid_namespace::ROOT_PID_NAMESPACE.clone()); + if Arc::ptr_eq(&ns, &crate::pid_namespace::ROOT_PID_NAMESPACE) + && proc.children.contains(&want) + { + FastWaitCheck::DirectCandidate(want, ns) + } else { + FastWaitCheck::SlowPath + } } else { FastWaitCheck::SlowPath } @@ -2610,7 +2713,7 @@ where }; match fast_check { FastWaitCheck::MultiThread(group) => { - return wait_reap_group(target, nohang, nowait, publish, pid, &parent, &group); + return wait_reap_group_opts(target, opts, publish, pid, &parent, &group); } FastWaitCheck::AbortEintr => { return Err(SyscallError::EINTR); @@ -2634,7 +2737,7 @@ where Some(WaitOutcome { global_pid: want, view_pid: want, - exit_code: child.exit_code.unwrap_or(0), + event: WaitEventKind::Exited(child.exit_code.unwrap_or(0)), }) } else { None @@ -2846,7 +2949,7 @@ where // A selected zombie whose teardown/switch-out is still in flight: the // wake was genuine, only early (wake_reaper_after_switch follows). let mut selected_zombie_pending = false; - let mut zombie_child: Option<(ProcessId, i32, ProcessId)> = None; + let mut reported_child: Option<(ProcessId, WaitEventKind, ProcessId)> = None; let mut stale_pids: vec::Vec = vec::Vec::new(); for child_pid in child_list.as_slice().iter() { @@ -2864,9 +2967,17 @@ where let Some(view_pid) = child.wait_pid_in_namespace(&parent_namespace) else { continue; }; - if let WaitTarget::Pid(want) = target { - if view_pid != want { - continue; + match target { + WaitTarget::Any => {} + WaitTarget::Pid(want) => { + if view_pid != want { + continue; + } + } + WaitTarget::Pgid(want_pgid) => { + if child.thread_group.pgid() != want_pgid { + continue; + } } } @@ -2877,7 +2988,8 @@ where // threads are auto-reaped), and a zombie leader only once it // is the last member. A lone zombie leader cannot gain // members, so this stays true through cleanup_zombie. - if child.state == ProcessState::Zombie + if opts.exited + && child.state == ProcessState::Zombie && child .teardown_done .load(core::sync::atomic::Ordering::Acquire) @@ -2888,12 +3000,45 @@ where && child.tgid == *child_pid && child.thread_group.members() == 1 { - zombie_child = Some((*child_pid, child.exit_code.unwrap_or(0), view_pid)); + reported_child = Some(( + *child_pid, + WaitEventKind::Exited(child.exit_code.unwrap_or(0)), + view_pid, + )); break; } - if child.state == ProcessState::Zombie { + if opts.exited && child.state == ProcessState::Zombie { selected_zombie_pending = true; } + // N2.5: Report WUNTRACED / WSTOPPED and WCONTINUED on live child leaders. + if !matches!(child.state, ProcessState::Zombie | ProcessState::Terminated) + && child.tgid == *child_pid + { + if opts.stopped { + let stop_sig = if nowait { + child.thread_group.peek_stop_event() + } else { + child.thread_group.take_stop_event() + }; + if let Some(sig) = stop_sig { + reported_child = + Some((*child_pid, WaitEventKind::Stopped(sig), view_pid)); + break; + } + } + if opts.continued { + let cont = if nowait { + child.thread_group.peek_continue_event() + } else { + child.thread_group.take_continue_event() + }; + if cont { + reported_child = + Some((*child_pid, WaitEventKind::Continued, view_pid)); + break; + } + } + } } None => { // 子进程已被清理但仍在父进程列表中,标记为过期 @@ -2906,66 +3051,104 @@ where } } - if let Some((child_pid, exit_code, parent_view_pid)) = zombie_child { + if let Some((child_pid, event, parent_view_pid)) = reported_child { let outcome = WaitOutcome { global_pid: child_pid, view_pid: parent_view_pid, - exit_code, + event, }; - // GAP-5 G8: the group may have gained a thread that waits too; one - // waiter claims the zombie. A loser rescans once the winner's reap - // has removed the child. - if !nowait && !crate::process::claim_wait_reap(child_pid) { - { + match event { + WaitEventKind::Stopped(sig) => { + if let Err(e) = publish(&outcome) { + if !nowait { + if let Some(c) = get_process(child_pid) { + c.lock().thread_group.record_stop_event(sig); + } + } + let mut proc = parent.lock(); + proc.enter_ready_at(crate::get_ticks()); + proc.waiting_child = None; + return Err(e); + } let mut proc = parent.lock(); + proc.waiting_child = None; proc.enter_ready_at(crate::get_ticks()); + return Ok(Some(outcome)); + } + WaitEventKind::Continued => { + if let Err(e) = publish(&outcome) { + if !nowait { + if let Some(c) = get_process(child_pid) { + c.lock().thread_group.record_continue_event(); + } + } + let mut proc = parent.lock(); + proc.enter_ready_at(crate::get_ticks()); + proc.waiting_child = None; + return Err(e); + } + let mut proc = parent.lock(); proc.waiting_child = None; + proc.enter_ready_at(crate::get_ticks()); + return Ok(Some(outcome)); } - crate::force_reschedule(); - continue; - } + WaitEventKind::Exited(exit_code) => { + // GAP-5 G8: the group may have gained a thread that waits too; one + // waiter claims the zombie. A loser rescans once the winner's reap + // has removed the child. + if !nowait && !crate::process::claim_wait_reap(child_pid) { + { + let mut proc = parent.lock(); + proc.enter_ready_at(crate::get_ticks()); + proc.waiting_child = None; + } + crate::force_reschedule(); + continue; + } - // Report to the caller before committing the reap. A failure here - // must restore Ready and leave the zombie reapable, matching Linux - // EFAULT semantics for a bad status/siginfo pointer. - if let Err(e) = publish(&outcome) { - if !nowait { - crate::process::release_wait_reap(child_pid); - } - let mut proc = parent.lock(); - proc.enter_ready_at(crate::get_ticks()); - proc.waiting_child = None; - return Err(e); - } + // Report to the caller before committing the reap. A failure here + // must restore Ready and leave the zombie reapable, matching Linux + // EFAULT semantics for a bad status/siginfo pointer. + if let Err(e) = publish(&outcome) { + if !nowait { + crate::process::release_wait_reap(child_pid); + } + let mut proc = parent.lock(); + proc.enter_ready_at(crate::get_ticks()); + proc.waiting_child = None; + return Err(e); + } - if nowait { - // WNOWAIT: leave the child linked and un-cleaned so a later - // wait can reap it. Only the parent's own wait state is undone. - let mut proc = parent.lock(); - proc.waiting_child = None; - proc.enter_ready_at(crate::get_ticks()); - return Ok(Some(outcome)); - } + if nowait { + // WNOWAIT: leave the child linked and un-cleaned so a later + // wait can reap it. Only the parent's own wait state is undone. + let mut proc = parent.lock(); + proc.waiting_child = None; + proc.enter_ready_at(crate::get_ticks()); + return Ok(Some(outcome)); + } - { - let mut proc = parent.lock(); - proc.children.retain(|&c| c != child_pid); - proc.waiting_child = None; - proc.enter_ready_at(crate::get_ticks()); - } + { + let mut proc = parent.lock(); + proc.children.retain(|&c| c != child_pid); + proc.waiting_child = None; + proc.enter_ready_at(crate::get_ticks()); + } - // 清理僵尸进程资源 - cleanup_zombie(child_pid); + // 清理僵尸进程资源 + cleanup_zombie(child_pid); - kprintln!( - "sys_wait: reaped child {} (ns_pid={}) with exit code {}", - child_pid, - parent_view_pid, - exit_code - ); - // F.1: Return namespace-local PID to parent (Linux semantics) - return Ok(Some(outcome)); + kprintln!( + "sys_wait: reaped child {} (ns_pid={}) with exit code {}", + child_pid, + parent_view_pid, + exit_code + ); + // F.1: Return namespace-local PID to parent (Linux semantics) + return Ok(Some(outcome)); + } + } } // 清理过期的子进程 PID @@ -3043,6 +3226,33 @@ pub(super) fn wait_reap_group( target: WaitTarget, nohang: bool, nowait: bool, + publish: W, + pid: ProcessId, + caller: &crate::process::ProcessArc, + group: &Arc, +) -> Result, SyscallError> +where + W: FnMut(&WaitOutcome) -> Result<(), SyscallError>, +{ + wait_reap_group_opts( + target, + WaitOptions { + nohang, + nowait, + exited: true, + stopped: false, + continued: false, + }, + publish, + pid, + caller, + group, + ) +} + +pub(super) fn wait_reap_group_opts( + target: WaitTarget, + opts: WaitOptions, mut publish: W, pid: ProcessId, caller: &crate::process::ProcessArc, @@ -3051,6 +3261,8 @@ pub(super) fn wait_reap_group( where W: FnMut(&WaitOutcome) -> Result<(), SyscallError>, { + let nohang = opts.nohang; + let nowait = opts.nowait; struct ChildWaiter<'a>(&'a crate::process::ThreadGroup); impl Drop for ChildWaiter<'_> { fn drop(&mut self) { @@ -3084,8 +3296,8 @@ where let mut grew = false; // A candidate that becomes reapable without a report: poll for it. let mut transient = false; - // (child, exit code, view pid) - let mut found: Option<(ProcessId, i32, ProcessId)> = None; + // (child, event, view pid) + let mut found: Option<(ProcessId, WaitEventKind, ProcessId)> = None; 'scan: { let table = crate::process::PROCESS_TABLE.lock(); for (slot_pid, slot) in table.iter().enumerate() { @@ -3108,46 +3320,84 @@ where let Some(view_pid) = child.wait_pid_in_namespace(&parent_namespace) else { continue; }; - if let WaitTarget::Pid(want) = target { - if view_pid != want { - continue; + match target { + WaitTarget::Any => {} + WaitTarget::Pid(want) => { + if view_pid != want { + continue; + } + wake_pid = child_pid; + } + WaitTarget::Pgid(want_pgid) => { + if child.thread_group.pgid() != want_pgid { + continue; + } } - wake_pid = child_pid; } selected_exists = true; // A zombie leader whose group is empty is reported once its // teardown is published and it has switched out for good. - let reportable = child.state == ProcessState::Zombie - && child.tgid == child_pid - && child.thread_group.members() == 1; - let reapable = reportable - && child - .teardown_done - .load(core::sync::atomic::Ordering::Acquire) - && !child.on_cpu.load(core::sync::atomic::Ordering::Acquire) - && !child - .switch_reap_pending - .load(core::sync::atomic::Ordering::Acquire); - if !reapable { - transient |= reportable; - continue; + if opts.exited && child.state == ProcessState::Zombie { + let reportable = child.tgid == child_pid && child.thread_group.members() == 1; + let reapable = reportable + && child + .teardown_done + .load(core::sync::atomic::Ordering::Acquire) + && !child.on_cpu.load(core::sync::atomic::Ordering::Acquire) + && !child + .switch_reap_pending + .load(core::sync::atomic::Ordering::Acquire); + if !reapable { + transient |= reportable; + continue; + } + if !nowait + && child + .wait_claimed + .compare_exchange( + false, + true, + core::sync::atomic::Ordering::AcqRel, + core::sync::atomic::Ordering::Acquire, + ) + .is_err() + { + transient = true; + continue; + } + found = Some(( + child_pid, + WaitEventKind::Exited(child.exit_code.unwrap_or(0)), + view_pid, + )); + break; } - if !nowait - && child - .wait_claimed - .compare_exchange( - false, - true, - core::sync::atomic::Ordering::AcqRel, - core::sync::atomic::Ordering::Acquire, - ) - .is_err() + if !matches!(child.state, ProcessState::Zombie | ProcessState::Terminated) + && child.tgid == child_pid { - transient = true; - continue; + if opts.stopped { + let stop_sig = if nowait { + child.thread_group.peek_stop_event() + } else { + child.thread_group.take_stop_event() + }; + if let Some(sig) = stop_sig { + found = Some((child_pid, WaitEventKind::Stopped(sig), view_pid)); + break; + } + } + if opts.continued { + let cont = if nowait { + child.thread_group.peek_continue_event() + } else { + child.thread_group.take_continue_event() + }; + if cont { + found = Some((child_pid, WaitEventKind::Continued, view_pid)); + break; + } + } } - found = Some((child_pid, child.exit_code.unwrap_or(0), view_pid)); - break; } } if grew { @@ -3157,37 +3407,64 @@ where #[cfg(all(test, feature = "host_harness", not(target_os = "none")))] selective_wait_tests::group_wait_phase(selective_wait_tests::GroupWaitPhase::Scanned); - if let Some((child_pid, exit_code, view_pid)) = found { + if let Some((child_pid, event, view_pid)) = found { let outcome = WaitOutcome { global_pid: child_pid, view_pid, - exit_code, + event, }; - if let Err(e) = publish(&outcome) { - if !nowait { - crate::process::release_wait_reap(child_pid); + match event { + WaitEventKind::Stopped(sig) => { + if let Err(e) = publish(&outcome) { + if !nowait { + if let Some(c) = get_process(child_pid) { + c.lock().thread_group.record_stop_event(sig); + } + } + return Err(e); + } + return Ok(Some(outcome)); } - return Err(e); - } - if nowait { - return Ok(Some(outcome)); - } - // GAP-5 G8 (review D2): the child may have been reparented since - // the scan (its parent thread exited). Unlink it from its current - // parent; reparenting runs under the same table lock. - { - let table = crate::process::PROCESS_TABLE.lock(); - let parent_pid = table - .get(child_pid) - .and_then(Option::as_ref) - .map(|child| child.lock().ppid); - if let Some(parent) = parent_pid.and_then(|p| table.get(p).and_then(Option::as_ref)) - { - parent.lock().children.retain(|&c| c != child_pid); + WaitEventKind::Continued => { + if let Err(e) = publish(&outcome) { + if !nowait { + if let Some(c) = get_process(child_pid) { + c.lock().thread_group.record_continue_event(); + } + } + return Err(e); + } + return Ok(Some(outcome)); + } + WaitEventKind::Exited(_) => { + if let Err(e) = publish(&outcome) { + if !nowait { + crate::process::release_wait_reap(child_pid); + } + return Err(e); + } + if nowait { + return Ok(Some(outcome)); + } + // GAP-5 G8 (review D2): the child may have been reparented since + // the scan (its parent thread exited). Unlink it from its current + // parent; reparenting runs under the same table lock. + { + let table = crate::process::PROCESS_TABLE.lock(); + let parent_pid = table + .get(child_pid) + .and_then(Option::as_ref) + .map(|child| child.lock().ppid); + if let Some(parent) = + parent_pid.and_then(|p| table.get(p).and_then(Option::as_ref)) + { + parent.lock().children.retain(|&c| c != child_pid); + } + } + cleanup_zombie(child_pid); + return Ok(Some(outcome)); } } - cleanup_zombie(child_pid); - return Ok(Some(outcome)); } if !selected_exists { return Err(SyscallError::ECHILD); @@ -3631,6 +3908,257 @@ pub(super) const WNOWAIT: i32 = 0x0100_0000; /// `si_code` for a child that exited normally. pub(super) const CLD_EXITED: i32 = 1; +/// `si_code` for a child that stopped (N2.5 `WUNTRACED`/`WSTOPPED`). +pub(super) const CLD_STOPPED: i32 = 5; +/// `si_code` for a stopped child that resumed via `SIGCONT` (N2.5 `WCONTINUED`). +pub(super) const CLD_CONTINUED: i32 = 6; + +// ============================================================================ +// N2.5: Process Group & Session Syscalls (`setpgid`, `getpgid`, `getpgrp`, +// `setsid`, `getsid`) +// ============================================================================ + +/// Translate a global PID/PGID/SID into the caller's PID namespace (returning +/// `0` if outside the namespace, matching Linux `pid_vnr` semantics). +#[inline] +fn translate_id_for_caller( + global_id: ProcessId, + owning_ns: &Option, +) -> ProcessId { + match owning_ns { + Some(ns) => ns.lookup_ns_pid(global_id).unwrap_or(0), + None => global_id, + } +} + +/// sys_getpgrp - get process group ID of calling process (syscall 111, N2.5). +pub(super) fn sys_getpgrp() -> SyscallResult { + sys_getpgid(0) +} + +/// sys_getpgid - get process group ID of `pid` (0 = caller) (syscall 121, N2.5). +pub(super) fn sys_getpgid(pid: i32) -> SyscallResult { + if pid < 0 { + return Err(SyscallError::ESRCH); + } + let caller = current_pid().ok_or(SyscallError::ESRCH)?; + let (caller_pgid, owning_ns) = { + let arc = get_process(caller).ok_or(SyscallError::ESRCH)?; + let p = arc.lock(); + ( + p.thread_group.pgid(), + crate::pid_namespace::owning_namespace(&p.pid_ns_chain), + ) + }; + let global_pgid = if pid == 0 { + caller_pgid + } else { + let target_global = match &owning_ns { + Some(ns) => crate::pid_namespace::resolve_pid_in_namespace(ns, pid as ProcessId) + .ok_or(SyscallError::ESRCH)?, + None => pid as ProcessId, + }; + let target = get_process(target_global).ok_or(SyscallError::ESRCH)?; + let t = target.lock(); + if matches!(t.state, ProcessState::Zombie | ProcessState::Terminated) { + return Err(SyscallError::ESRCH); + } + t.thread_group.pgid() + }; + Ok(translate_id_for_caller(global_pgid, &owning_ns)) +} + +/// sys_getsid - get session ID of `pid` (0 = caller) (syscall 124, N2.5). +pub(super) fn sys_getsid(pid: i32) -> SyscallResult { + if pid < 0 { + return Err(SyscallError::ESRCH); + } + let caller = current_pid().ok_or(SyscallError::ESRCH)?; + let (caller_sid, owning_ns) = { + let arc = get_process(caller).ok_or(SyscallError::ESRCH)?; + let p = arc.lock(); + ( + p.thread_group.sid(), + crate::pid_namespace::owning_namespace(&p.pid_ns_chain), + ) + }; + let global_sid = if pid == 0 { + caller_sid + } else { + let target_global = match &owning_ns { + Some(ns) => crate::pid_namespace::resolve_pid_in_namespace(ns, pid as ProcessId) + .ok_or(SyscallError::ESRCH)?, + None => pid as ProcessId, + }; + let target = get_process(target_global).ok_or(SyscallError::ESRCH)?; + let t = target.lock(); + if matches!(t.state, ProcessState::Zombie | ProcessState::Terminated) { + return Err(SyscallError::ESRCH); + } + t.thread_group.sid() + }; + Ok(translate_id_for_caller(global_sid, &owning_ns)) +} + +/// sys_setsid - create a new session and process group (syscall 112, N2.5). +/// +/// Fails with `EPERM` if any live process already belongs to a process group +/// whose PGID equals the caller's TGID (including the caller itself). +pub(super) fn sys_setsid() -> SyscallResult { + let caller = current_pid().ok_or(SyscallError::ESRCH)?; + let (caller_tgid, owning_ns) = { + let arc = get_process(caller).ok_or(SyscallError::ESRCH)?; + let p = arc.lock(); + ( + p.tgid, + crate::pid_namespace::owning_namespace(&p.pid_ns_chain), + ) + }; + + { + let table = crate::process::PROCESS_TABLE.lock(); + for slot in table.iter() { + let Some(arc) = slot else { continue }; + let p = arc.lock(); + if matches!(p.state, ProcessState::Zombie | ProcessState::Terminated) { + continue; + } + if p.thread_group.pgid() == caller_tgid { + return Err(SyscallError::EPERM); + } + } + let Some(caller_arc) = table.get(caller).and_then(Option::as_ref) else { + return Err(SyscallError::ESRCH); + }; + let tg = &caller_arc.lock().thread_group; + tg.set_sid(caller_tgid); + tg.set_pgid(caller_tgid); + tg.set_has_ctty(false); + } + + Ok(translate_id_for_caller(caller_tgid, &owning_ns)) +} + +/// Pure POSIX `setpgid(2)` rule check (factored for hosted unit tests). +#[allow(clippy::too_many_arguments)] +pub(super) fn validate_setpgid_rules( + caller_tgid: ProcessId, + caller_sid: ProcessId, + target_tgid: ProcessId, + target_ppid: ProcessId, + target_sid: ProcessId, + target_has_execed: bool, + new_pgid: ProcessId, + new_pgid_exists_in_session: bool, +) -> Result<(), SyscallError> { + let is_self = target_tgid == caller_tgid; + let is_child = target_ppid == caller_tgid; + if !is_self && !is_child { + return Err(SyscallError::ESRCH); + } + if is_child && target_has_execed { + return Err(SyscallError::EACCES); + } + if target_sid != caller_sid { + return Err(SyscallError::EPERM); + } + // A session leader cannot change its own process group. + if target_tgid == target_sid { + return Err(SyscallError::EPERM); + } + if new_pgid != target_tgid && !new_pgid_exists_in_session { + return Err(SyscallError::EPERM); + } + Ok(()) +} + +/// sys_setpgid - set process group ID of self or an un-exec'd child (syscall 109, N2.5). +pub(super) fn sys_setpgid(pid: i32, pgid: i32) -> SyscallResult { + if pid < 0 || pgid < 0 { + return Err(SyscallError::EINVAL); + } + let caller = current_pid().ok_or(SyscallError::ESRCH)?; + let (caller_tgid, caller_sid, owning_ns) = { + let arc = get_process(caller).ok_or(SyscallError::ESRCH)?; + let p = arc.lock(); + ( + p.tgid, + p.thread_group.sid(), + crate::pid_namespace::owning_namespace(&p.pid_ns_chain), + ) + }; + + let target_global = if pid == 0 { + caller_tgid + } else { + match &owning_ns { + Some(ns) => crate::pid_namespace::resolve_pid_in_namespace(ns, pid as ProcessId) + .ok_or(SyscallError::ESRCH)?, + None => pid as ProcessId, + } + }; + + let table = crate::process::PROCESS_TABLE.lock(); + let target_arc = table + .get(target_global) + .and_then(Option::as_ref) + .ok_or(SyscallError::ESRCH)?; + let (target_tgid, target_ppid, target_sid, target_execed, target_group) = { + let t = target_arc.lock(); + if matches!(t.state, ProcessState::Zombie | ProcessState::Terminated) { + return Err(SyscallError::ESRCH); + } + ( + t.tgid, + t.ppid, + t.thread_group.sid(), + t.thread_group.has_execed(), + Arc::clone(&t.thread_group), + ) + }; + + let new_pgid = if pgid == 0 { + target_tgid + } else { + match &owning_ns { + Some(ns) => crate::pid_namespace::resolve_pid_in_namespace(ns, pgid as ProcessId) + .ok_or(SyscallError::EPERM)?, + None => pgid as ProcessId, + } + }; + + let pgid_in_session = if new_pgid == target_tgid { + true + } else { + let mut found = false; + for slot in table.iter() { + let Some(arc) = slot else { continue }; + let p = arc.lock(); + if matches!(p.state, ProcessState::Zombie | ProcessState::Terminated) { + continue; + } + if p.thread_group.sid() == caller_sid && p.thread_group.pgid() == new_pgid { + found = true; + break; + } + } + found + }; + + validate_setpgid_rules( + caller_tgid, + caller_sid, + target_tgid, + target_ppid, + target_sid, + target_execed, + new_pgid, + pgid_in_session, + )?; + + target_group.set_pgid(new_pgid); + Ok(0) +} /// Byte offsets into the x86_64 `siginfo_t` fields `waitid` fills. /// Layout: si_signo(0) si_errno(4) si_code(8) __pad(12) then the _sigchld @@ -3670,30 +4198,43 @@ pub(super) fn waitid_validate_args( idtype: i32, id: i32, options: i32, -) -> Result { +) -> Result<(WaitTarget, WaitOptions), SyscallError> { const KNOWN: i32 = WNOHANG | WUNTRACED | WEXITED | WCONTINUED | WNOWAIT; if options & !KNOWN != 0 { return Err(SyscallError::EINVAL); } - // No stop/continue event ledger exists, so these can never be satisfied. - if options & (WUNTRACED | WCONTINUED) != 0 { - return Err(SyscallError::EINVAL); - } - if options & WEXITED == 0 { + // POSIX/Linux: at least one of WEXITED, WSTOPPED(==WUNTRACED), WCONTINUED + // must be specified in `options`. + if options & (WEXITED | WUNTRACED | WCONTINUED) == 0 { return Err(SyscallError::EINVAL); } - match idtype { - P_ALL => Ok(WaitTarget::Any), + let target = match idtype { + P_ALL => WaitTarget::Any, P_PID => { if id <= 0 { return Err(SyscallError::EINVAL); } - Ok(WaitTarget::Pid(id as ProcessId)) + WaitTarget::Pid(id as ProcessId) } - P_PGID => Err(SyscallError::EINVAL), - _ => Err(SyscallError::EINVAL), - } + P_PGID => { + if id < 0 { + return Err(SyscallError::EINVAL); + } + // id == 0 means caller's own PGID (resolved by sys_waitid before scan). + WaitTarget::Pgid(id as ProcessId) + } + _ => return Err(SyscallError::EINVAL), + }; + + let opts = WaitOptions { + nohang: options & WNOHANG != 0, + nowait: options & WNOWAIT != 0, + exited: options & WEXITED != 0, + stopped: options & WUNTRACED != 0, + continued: options & WCONTINUED != 0, + }; + Ok((target, opts)) } /// Pure `siginfo_t` encoder for `waitid`. Always returns the full 128 bytes so @@ -3724,14 +4265,34 @@ pub(super) fn sys_waitid( infop: *mut u8, options: i32, ) -> Result { - let target = waitid_validate_args(idtype, id, options)?; + let (mut target, opts) = waitid_validate_args(idtype, id, options)?; + if let WaitTarget::Pgid(local_pgid) = target { + let caller_pid = current_pid().ok_or(SyscallError::ESRCH)?; + let caller = get_process(caller_pid).ok_or(SyscallError::ESRCH)?; + let (caller_pgid, owning_ns) = { + let p = caller.lock(); + ( + p.thread_group.pgid(), + crate::pid_namespace::owning_namespace(&p.pid_ns_chain), + ) + }; + let global_pgid = if local_pgid == 0 { + caller_pgid + } else { + match owning_ns { + Some(ns) => crate::pid_namespace::resolve_pid_in_namespace(&ns, local_pgid) + .ok_or(SyscallError::ECHILD)?, + None => local_pgid, + } + }; + target = WaitTarget::Pgid(global_pgid); + } let write_siginfo = |pid: ProcessId, uid: u32, code: i32, status: i32| { copy_to_user(infop, &waitid_encode_siginfo(pid, uid, code, status)) }; - // Resolved while the zombie is still selected but before it is unlinked: - // after cleanup_zombie the PCB is gone and si_uid would be unrecoverable. + // Resolved while the child is still selected and before cleanup_zombie runs. let publish = |outcome: &WaitOutcome| -> Result<(), SyscallError> { if infop.is_null() { // Linux accepts a NULL infop and reports only via the return value. @@ -3744,17 +4305,11 @@ pub(super) fn sys_waitid( .map(|p| p.lock().shared_credentials()) .and_then(|creds| creds.try_read().map(|c| c.uid)) .unwrap_or(0); - // si_status carries the raw exit code, NOT the packed wstatus: with - // si_code == CLD_EXITED, userspace reads it directly as the exit status. - write_siginfo(outcome.view_pid, uid, CLD_EXITED, outcome.exit_code & 0xff) + let (si_code, si_status) = outcome.event.encode_waitid_code_status(); + write_siginfo(outcome.view_pid, uid, si_code, si_status) }; - match wait_reap_core( - target, - options & WNOHANG != 0, - options & WNOWAIT != 0, - publish, - )? { + match wait_reap_core_opts(target, opts, publish, None)? { Some(_) => Ok(0), None => { // WNOHANG, nothing ready: zeroed siginfo so si_pid == 0. @@ -3766,10 +4321,9 @@ pub(super) fn sys_waitid( } } -/// ST-K3-WAITID hosted oracle: executes the production `waitid(2)` argument -/// contract and `siginfo_t` encoder on the host target. The reap/unlink, -/// blocking and WNOWAIT-then-reap legs need live process state and a user -/// address space, so they run only in the guest runtime gate. +/// ST-K3-WAITID + N2.5 hosted oracle: executes the production `waitid(2)`, +/// `setpgid(2)`, `ThreadGroup` job-control ledger, and `ConsoleTty` state +/// machines on the host target. #[cfg(all(test, feature = "host_harness", not(target_os = "none")))] mod st_k3_waitid_oracle_tests { use super::*; @@ -3778,16 +4332,23 @@ mod st_k3_waitid_oracle_tests { fn waitid_selectors_resolve_or_fail_closed() { assert!(matches!( waitid_validate_args(P_ALL, 0, WEXITED), - Ok(WaitTarget::Any) + Ok((WaitTarget::Any, _)) )); assert!(matches!( waitid_validate_args(P_PID, 7, WEXITED), - Ok(WaitTarget::Pid(7)) + Ok((WaitTarget::Pid(7), _)) )); - // P_PGID has no process-group wait tracking behind it: refused, never - // silently widened to "any child". - assert_eq!( + // N2.5: P_PGID is now supported (0 = caller's PGID, >0 = explicit PGID, <0 = EINVAL). + assert!(matches!( + waitid_validate_args(P_PGID, 0, WEXITED), + Ok((WaitTarget::Pgid(0), _)) + )); + assert!(matches!( waitid_validate_args(P_PGID, 7, WEXITED), + Ok((WaitTarget::Pgid(7), _)) + )); + assert_eq!( + waitid_validate_args(P_PGID, -1, WEXITED), Err(SyscallError::EINVAL) ); for bad_id in [0, -1] { @@ -3804,26 +4365,177 @@ mod st_k3_waitid_oracle_tests { #[test] fn waitid_options_are_validated_before_any_state_change() { - // WEXITED is mandatory: a wait that can report nothing is a caller bug. + // At least one of WEXITED | WSTOPPED(WUNTRACED) | WCONTINUED is required. assert_eq!(waitid_validate_args(P_ALL, 0, 0), Err(SyscallError::EINVAL)); assert_eq!( waitid_validate_args(P_ALL, 0, WNOHANG), Err(SyscallError::EINVAL) ); - // Unsatisfiable rather than ignored: no stop/continue ledger exists, so - // honouring these would promise a notification that can never arrive. - for unsupported in [WUNTRACED, WCONTINUED] { - assert_eq!( - waitid_validate_args(P_ALL, 0, WEXITED | unsupported), - Err(SyscallError::EINVAL) - ); - } + // N2.5: WSTOPPED (WUNTRACED) and WCONTINUED are valid alone or combined. + let (_, stop_opts) = waitid_validate_args(P_ALL, 0, WUNTRACED).unwrap(); + assert!(stop_opts.stopped && !stop_opts.exited && !stop_opts.continued); + let (_, cont_opts) = waitid_validate_args(P_ALL, 0, WCONTINUED).unwrap(); + assert!(cont_opts.continued && !cont_opts.exited && !cont_opts.stopped); + let (_, all_opts) = waitid_validate_args( + P_ALL, + 0, + WEXITED | WUNTRACED | WCONTINUED | WNOHANG | WNOWAIT, + ) + .unwrap(); + assert!( + all_opts.exited + && all_opts.stopped + && all_opts.continued + && all_opts.nohang + && all_opts.nowait + ); // Unknown bits are rejected, so future flags cannot be silently dropped. assert_eq!( waitid_validate_args(P_ALL, 0, WEXITED | 1 << 20), Err(SyscallError::EINVAL) ); - assert!(waitid_validate_args(P_ALL, 0, WEXITED | WNOHANG | WNOWAIT).is_ok()); + } + + #[test] + fn n2_5_wstatus_and_waitid_job_control_encoding() { + assert_eq!(WaitEventKind::Exited(42).encode_wstatus(), 42 << 8); + assert_eq!( + WaitEventKind::Stopped(19).encode_wstatus(), + (19 << 8) | 0x7f + ); + assert_eq!(WaitEventKind::Continued.encode_wstatus(), 0xffff); + assert_eq!( + WaitEventKind::Exited(42).encode_waitid_code_status(), + (CLD_EXITED, 42) + ); + assert_eq!( + WaitEventKind::Stopped(20).encode_waitid_code_status(), + (CLD_STOPPED, 20) + ); + assert_eq!( + WaitEventKind::Continued.encode_waitid_code_status(), + (CLD_CONTINUED, 18) + ); + } + + #[test] + fn n2_5_setpgid_posix_rules() { + // Self creating its own PGID succeeds when not a session leader. + assert!(validate_setpgid_rules(10, 1, 10, 1, 1, false, 10, true).is_ok()); + // Session leader cannot change its own PGID -> EPERM. + assert_eq!( + validate_setpgid_rules(10, 10, 10, 1, 10, false, 20, true), + Err(SyscallError::EPERM) + ); + // Non-child, non-self target -> ESRCH. + assert_eq!( + validate_setpgid_rules(10, 1, 99, 2, 1, false, 99, true), + Err(SyscallError::ESRCH) + ); + // Child that already called execve -> EACCES. + assert_eq!( + validate_setpgid_rules(10, 1, 20, 10, 1, true, 20, true), + Err(SyscallError::EACCES) + ); + // Child in another session -> EPERM. + assert_eq!( + validate_setpgid_rules(10, 1, 20, 10, 20, false, 10, true), + Err(SyscallError::EPERM) + ); + // Moving into non-existent PGID in session -> EPERM. + assert_eq!( + validate_setpgid_rules(10, 1, 20, 10, 1, false, 777, false), + Err(SyscallError::EPERM) + ); + // Moving un-exec'd child into existing PGID in same session succeeds. + assert!(validate_setpgid_rules(10, 1, 20, 10, 1, false, 10, true).is_ok()); + } + + #[test] + fn n2_5_thread_group_job_wait_ledger_and_ctty_state() { + let tg = crate::process::ThreadGroup::new(); + tg.init_job_control(50); + assert_eq!( + (tg.pgid(), tg.sid(), tg.has_execed(), tg.has_ctty()), + (50, 50, false, false) + ); + + // Stop event reported once; peek preserves it for WNOWAIT. + tg.record_stop_event(19); + assert_eq!(tg.peek_stop_event(), Some(19)); + assert!(!tg.peek_continue_event()); + assert_eq!(tg.take_stop_event(), Some(19)); + assert_eq!(tg.take_stop_event(), None); + + // Continue cancels stale stop and reports once. + tg.record_stop_event(20); + tg.record_continue_event(); + assert_eq!(tg.peek_stop_event(), None); + assert!(tg.peek_continue_event()); + assert!(tg.take_continue_event()); + assert!(!tg.take_continue_event()); + + // Inheritance on fork copies pgid/sid/ctty and clears execed/wait events. + tg.set_pgid(40); + tg.set_sid(30); + tg.set_has_ctty(true); + tg.mark_execed(); + tg.record_stop_event(19); + let child_tg = crate::process::ThreadGroup::new(); + child_tg.inherit_job_control(&tg); + assert_eq!( + ( + child_tg.pgid(), + child_tg.sid(), + child_tg.has_ctty(), + child_tg.has_execed(), + child_tg.peek_stop_event() + ), + (40, 30, true, false, None) + ); + } + + #[test] + fn n2_5_console_tty_attach_fg_pgid_and_steal_rules() { + // Exercise console_tty transitions using an isolated high session ID. + let sid_a = 880_001; + let sid_b = 880_002; + let _ = crate::process::console_tty_release_session(sid_a); + let _ = crate::process::console_tty_release_session(sid_b); + + // Steal (privileged) establishes sid_a as owner with fg_pgid = sid_a. + assert!(crate::process::console_tty_attach(sid_a, sid_a, true, true).is_ok()); + assert_eq!( + crate::process::console_tty_get_fg_pgid(sid_a, true), + Ok(sid_a) + ); + assert_eq!( + crate::process::console_tty_get_fg_pgid(sid_a, false), + Err(SyscallError::ENOTTY) + ); + // Unprivileged foreign session cannot steal. + assert_eq!( + crate::process::console_tty_attach(sid_b, sid_b, true, false), + Err(SyscallError::EPERM) + ); + assert_eq!( + crate::process::console_tty_get_fg_pgid(sid_b, true), + Err(SyscallError::ENOTTY) + ); + // Foreground PGID update succeeds for owning session. + assert!(crate::process::console_tty_set_fg_pgid(sid_a, true, 880_010).is_ok()); + assert_eq!( + crate::process::console_tty_get_fg_pgid(sid_a, true), + Ok(880_010) + ); + assert_eq!( + crate::process::console_tty_release_session(sid_a), + Some(880_010) + ); + assert_eq!( + crate::process::console_tty_get_sid(sid_a, true), + Err(SyscallError::ENOTTY) + ); } #[test] diff --git a/kernel/kernel_core/syscall/signal.rs b/kernel/kernel_core/syscall/signal.rs index df3d6f7..db0c812 100644 --- a/kernel/kernel_core/syscall/signal.rs +++ b/kernel/kernel_core/syscall/signal.rs @@ -36,8 +36,138 @@ pub(super) enum KillTarget { ThreadInGroup(ProcessId), } -pub(super) fn sys_kill(pid: ProcessId, sig: i32) -> SyscallResult { - kill_common(pid, sig, KillTarget::Process, None) +pub(super) fn sys_kill(pid: i32, sig: i32) -> SyscallResult { + // Validate signal early for group/broadcast kill so invalid signals fail + // with EINVAL even if no target process exists. + if sig != 0 { + crate::signal::Signal::from_raw(sig)?; + } + if pid > 0 { + return kill_common(pid as ProcessId, sig, KillTarget::Process, None); + } + + // N2.5: POSIX process-group and broadcast kill(2): + // - pid == 0 -> every process in caller's process group + // - pid < -1 -> every process in process group `-pid` + // - pid == -1 -> every permissible process except PID 1 and caller + let self_pid = current_pid().ok_or(SyscallError::ESRCH)?; + let (self_tgid, self_pgid, owning_ns) = { + let self_proc = get_process(self_pid).ok_or(SyscallError::ESRCH)?; + let p = self_proc.lock(); + ( + p.tgid, + p.thread_group.pgid(), + crate::pid_namespace::owning_namespace(&p.pid_ns_chain), + ) + }; + + let target_pgid: Option = if pid == 0 { + Some(self_pgid) + } else if pid < -1 { + let local_pgid = (-(pid as i64)) as ProcessId; + let resolved = match &owning_ns { + Some(ns) => crate::pid_namespace::resolve_pid_in_namespace(ns, local_pgid) + .ok_or(SyscallError::ESRCH)?, + None => local_pgid, + }; + Some(resolved) + } else { + None // pid == -1 broadcast + }; + + // Snapshot matching thread-group leaders in caller's namespace without + // holding PROCESS_TABLE across kill_common. + let mut targets: Vec = Vec::new(); + { + let table = crate::process::PROCESS_TABLE.lock(); + for (slot_pid, slot) in table.iter().enumerate() { + let Some(arc) = slot else { continue }; + let p = arc.lock(); + if p.tgid != slot_pid + || matches!(p.state, ProcessState::Zombie | ProcessState::Terminated) + { + continue; + } + let matched = match target_pgid { + Some(pg) => p.thread_group.pgid() == pg, + None => p.tgid != 1 && p.tgid != self_tgid, + }; + if !matched { + continue; + } + let view_pid = match &owning_ns { + Some(ns) => match ns.lookup_ns_pid(slot_pid) { + Some(v) => v, + None => continue, + }, + None => slot_pid, + }; + if targets.try_reserve(1).is_err() { + return Err(SyscallError::ENOMEM); + } + targets.push(view_pid); + } + } + drop(owning_ns); + + if targets.is_empty() { + return Err(SyscallError::ESRCH); + } + + // Deliver to non-self members first so a fatal self-signal in the same + // process group still signals sibling processes before self-terminating. + let mut self_view: Option = None; + let mut delivered = 0usize; + let mut last_err: Option = None; + for target_view in targets { + let is_self = target_view == self_tgid + || get_process(self_pid).and_then(|p| { + crate::pid_namespace::pid_in_owning_namespace(&p.lock().pid_ns_chain) + }) == Some(target_view); + if is_self { + self_view = Some(target_view); + continue; + } + match kill_common(target_view, sig, KillTarget::Process, None) { + Ok(_) => delivered += 1, + Err(e) => last_err = Some(e), + } + } + if let Some(sv) = self_view { + match kill_common(sv, sig, KillTarget::Process, None) { + Ok(_) => delivered += 1, + Err(e) => last_err = Some(e), + } + } + + if delivered > 0 { + Ok(0) + } else { + Err(last_err.unwrap_or(SyscallError::ESRCH)) + } +} + +/// N2.5: Kernel-authoritative signal broadcast to all live processes in global `pgid` +/// (used by controlling-terminal hangup on `TIOCNOTTY`). +pub(super) fn send_signal_to_pgid_kernel(pgid: ProcessId, signal: crate::signal::Signal) { + let mut targets: Vec = Vec::new(); + { + let table = crate::process::PROCESS_TABLE.lock(); + for (slot_pid, slot) in table.iter().enumerate() { + let Some(arc) = slot else { continue }; + let p = arc.lock(); + if p.tgid == slot_pid + && !matches!(p.state, ProcessState::Zombie | ProcessState::Terminated) + && p.thread_group.pgid() == pgid + && targets.try_reserve(1).is_ok() + { + targets.push(slot_pid); + } + } + } + for tgid in targets { + let _ = crate::signal::send_signal_kernel(tgid, signal); + } } /// tkill(2). musl's raise() uses it with the caller's own tid. @@ -976,6 +1106,9 @@ pub(super) fn apply_default_at_safepoint(pid: ProcessId, sig: crate::signal::Sig } SignalAction::Stop => { stop = crate::process::try_mark_job_control_stopped_locked(&mut proc); + if stop { + proc.thread_group.record_stop_event(sig.as_u8()); + } } SignalAction::Continue | SignalAction::Ignore => {} } @@ -987,6 +1120,7 @@ pub(super) fn apply_default_at_safepoint(pid: ProcessId, sig: crate::signal::Sig if stop { // GAP-5 G7 (review D2): a stop stops the whole group, as at send time. let _ = crate::process::propagate_group_job_control(pid, false); + crate::process::notify_parent_of_job_control_event(pid, true); crate::process::wait_for_job_control_resume(pid, generation); } } diff --git a/kernel/seccomp/syscall_table.rs b/kernel/seccomp/syscall_table.rs index 900df13..e634f1f 100644 --- a/kernel/seccomp/syscall_table.rs +++ b/kernel/seccomp/syscall_table.rs @@ -336,7 +336,13 @@ define_syscall_table! { (104, SYS_GETGID, Getgid, "getgid", strict: false, drop_proc: false, status: Dispatched, pledge: PledgePolicy::Promises(P_STDIO), reason: ""), (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: ""), + // Process groups & sessions (N2.5) + (109, SYS_SETPGID, Setpgid, "setpgid", strict: false, drop_proc: false, status: Dispatched, pledge: PledgePolicy::Unpledged, reason: ""), (110, SYS_GETPPID, Getppid, "getppid", strict: false, drop_proc: false, status: Dispatched, pledge: PledgePolicy::Promises(P_STDIO), reason: ""), + (111, SYS_GETPGRP, Getpgrp, "getpgrp", strict: false, drop_proc: false, status: Dispatched, pledge: PledgePolicy::Unpledged, reason: ""), + (112, SYS_SETSID, Setsid, "setsid", strict: false, drop_proc: false, status: Dispatched, pledge: PledgePolicy::Unpledged, reason: ""), + (121, SYS_GETPGID, Getpgid, "getpgid", strict: false, drop_proc: false, status: Dispatched, pledge: PledgePolicy::Unpledged, reason: ""), + (124, SYS_GETSID, Getsid, "getsid", strict: false, drop_proc: false, status: Dispatched, pledge: PledgePolicy::Unpledged, 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: ""), diff --git a/kernel/src/syscall_test.elf b/kernel/src/syscall_test.elf index 024ba6c..92109ac 100755 Binary files a/kernel/src/syscall_test.elf and b/kernel/src/syscall_test.elf differ diff --git a/scripts/gates/boot/ring3_mm_oracle.sh b/scripts/gates/boot/ring3_mm_oracle.sh index 1a52b38..f4a53a5 100644 --- a/scripts/gates/boot/ring3_mm_oracle.sh +++ b/scripts/gates/boot/ring3_mm_oracle.sh @@ -151,6 +151,7 @@ FPU IRQ isolation: concurrent SSE XMM0-XMM7 state stays bit-exact across timer p N2.8 loopback UDP/TCP echo, getsockname/getpeername, and RST/SO_ERROR N2.8 setsockopt/getsockopt round-trip, bounds, and negative checks N2.8 sendmsg/recvmsg scatter-gather, MSG_TRUNC, EOPNOTSUPP control, and multi-iovec readv +N2.5 pgid/sid, controlling terminal ioctls, kill(-pgid), wait4/waitid stop & continue LEGS # 3. No leg reported a failure, and the suite ran to completion. diff --git a/scripts/tools/hosted_subcrate_tests.sh b/scripts/tools/hosted_subcrate_tests.sh index f47ecfa..392fcaf 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 231 0 \ +run_suite kernel-core 235 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 231 \ +run_suite mitigation-mappings 5 235 \ --manifest-path kernel/kernel_core/Cargo.toml \ --target x86_64-unknown-linux-gnu \ --features host_harness,mitigation_probe \ diff --git a/userspace/src/syscall_test.rs b/userspace/src/syscall_test.rs index 3b26700..4d933b3 100644 --- a/userspace/src/syscall_test.rs +++ b/userspace/src/syscall_test.rs @@ -381,6 +381,8 @@ pub extern "C" fn _start() -> ! { test_n2_8_loopback_udp_tcp_echo(&mut results); test_n2_8_sockopts_and_negative(&mut results); test_n2_8_sendmsg_recvmsg_and_readv(&mut results); + // N2.5: Process groups, sessions, controlling terminal ioctls, kill(-pgid), wait4/waitid job control. + test_n2_5_job_control_sessions_and_wait(&mut results); // Print summary println(""); @@ -2503,11 +2505,11 @@ fn test_waitid(results: &mut TestResult) { // needs a child. Each is a claim in §4 of the design. let mut info = SigInfo::poisoned(); let bad = [ - (P_PGID, 1, WEXITED, "P_PGID"), + (P_PGID, (-1_i32) as u64, WEXITED, "P_PGID with negative id"), (P_PID, 0, WEXITED, "P_PID with id 0"), (7, 1, WEXITED, "unknown idtype"), - (P_ALL, 0, 0, "missing WEXITED"), - (P_ALL, 0, WEXITED | WUNTRACED, "WUNTRACED"), + (P_ALL, 0, 0, "missing event flag"), + (P_ALL, 0, WNOHANG, "WNOHANG without event flag"), (P_ALL, 0, WEXITED | (1 << 20), "unknown option bit"), ]; for (idtype, id, opts, what) in bad { @@ -12660,3 +12662,307 @@ fn test_n2_8_sendmsg_recvmsg_and_readv(results: &mut TestResult) { "N2.8 sendmsg/recvmsg scatter-gather, MSG_TRUNC, EOPNOTSUPP control, and multi-iovec readv", ); } + +// =========================================================================== +// N2.5: Process Groups, Sessions, Controlling Terminal & Job Control Wait +// =========================================================================== + +const N25_SYS_IOCTL: u64 = 16; +const N25_SYS_PIPE: u64 = 22; +const N25_SYS_WAIT4: u64 = 61; +const N25_SYS_KILL: u64 = 62; +const N25_SYS_SETPGID: u64 = 109; +const N25_SYS_GETPGRP: u64 = 111; +const N25_SYS_SETSID: u64 = 112; +const N25_SYS_GETPGID: u64 = 121; +const N25_SYS_GETSID: u64 = 124; + +const N25_TIOCSCTTY: u64 = 0x540E; +const N25_TIOCGPGRP: u64 = 0x540F; +const N25_TIOCSPGRP: u64 = 0x5410; +const N25_TIOCNOTTY: u64 = 0x5422; +const N25_TIOCGSID: u64 = 0x5429; + +const N25_SIGCONT: u64 = 18; +const N25_SIGSTOP: u64 = 19; +const N25_WCONTINUED: u64 = 8; +const N25_CLD_CONTINUED: i32 = 6; +const N25_EPERM: i32 = 1; +const N25_EINTR: i32 = 4; +const N25_ENOTTY: i32 = 25; + +fn test_n2_5_job_control_sessions_and_wait(results: &mut TestResult) { + print("Testing N2.5 pgid/sid, ctty ioctls, kill(-pgid), wait4/waitid stop & continue... "); + + let my_pid = unsafe { sys_getpid() }; + let pgrp = unsafe { syscall0(N25_SYS_GETPGRP) }; + let pgid0 = unsafe { syscall1(N25_SYS_GETPGID, 0) }; + let sid0 = unsafe { syscall1(N25_SYS_GETSID, 0) }; + let setsid_leader = unsafe { syscall0(N25_SYS_SETSID) }; + if pgrp != my_pid + || pgid0 != my_pid + || sid0 != my_pid + || !is_error(setsid_leader) + || errno(setsid_leader) != N25_EPERM + { + results.fail("n2_5: initial pgid/sid or leader setsid EPERM check failed"); + return; + } + + let mut fg_pgid: i32 = 0; + let mut tty_sid: i32 = 0; + let r_gpgrp = unsafe { + syscall3( + N25_SYS_IOCTL, + 0, + N25_TIOCGPGRP, + &mut fg_pgid as *mut i32 as u64, + ) + }; + let r_gsid = unsafe { + syscall3( + N25_SYS_IOCTL, + 0, + N25_TIOCGSID, + &mut tty_sid as *mut i32 as u64, + ) + }; + if is_error(r_gpgrp) || is_error(r_gsid) || fg_pgid != my_pid as i32 || tty_sid != my_pid as i32 + { + results.fail("n2_5: initial TIOCGPGRP/TIOCGSID check failed"); + return; + } + + // Leg 1: fork child, move it into its own process group, switch fg_pgid, + // stop via kill(-pgid, SIGSTOP), observe WUNTRACED via wait4(-pgid), + // continue via kill(-pgid, SIGCONT), observe WCONTINUED via waitid(P_PGID), + // and reap exit via waitid(P_PGID, WEXITED). + let mut c2p = [0i32; 2]; + let mut p2c = [0i32; 2]; + if is_error(unsafe { syscall1(N25_SYS_PIPE, c2p.as_mut_ptr() as u64) }) + || is_error(unsafe { syscall1(N25_SYS_PIPE, p2c.as_mut_ptr() as u64) }) + { + results.fail("n2_5: pipe creation failed"); + return; + } + + let child1 = unsafe { sys_fork() }; + if is_error(child1) { + results.fail("n2_5: fork child1 failed"); + return; + } + if child1 == 0 { + unsafe { + sys_close(c2p[0] as u64); + sys_close(p2c[1] as u64); + } + let r_sp = unsafe { syscall2(N25_SYS_SETPGID, 0, 0) }; + if is_error(r_sp) { + unsafe { userspace::syscall::sys_exit(101) }; + } + let ready = [b'R']; + let _ = unsafe { syscall3(SYS_WRITE, c2p[1] as u64, ready.as_ptr() as u64, 1) }; + unsafe { sys_close(c2p[1] as u64) }; + let mut go = [0u8; 1]; + loop { + let n = unsafe { syscall3(SYS_READ, p2c[0] as u64, go.as_mut_ptr() as u64, 1) }; + if is_error(n) && errno(n) == N25_EINTR { + continue; + } + break; + } + unsafe { + sys_close(p2c[0] as u64); + userspace::syscall::sys_exit(37); + } + } + + unsafe { + sys_close(c2p[1] as u64); + sys_close(p2c[0] as u64); + } + let mut ready_byte = [0u8; 1]; + let r_ready = unsafe { syscall3(SYS_READ, c2p[0] as u64, ready_byte.as_mut_ptr() as u64, 1) }; + unsafe { sys_close(c2p[0] as u64) }; + if is_error(r_ready) || r_ready != 1 || ready_byte[0] != b'R' { + let _ = unsafe { syscall2(N25_SYS_KILL, child1, 9) }; + unsafe { sys_close(p2c[1] as u64) }; + reap_quietly(child1); + results.fail("n2_5: child1 ready handshake failed"); + return; + } + + let c1_pgid = unsafe { syscall1(N25_SYS_GETPGID, child1) }; + let c1_sid = unsafe { syscall1(N25_SYS_GETSID, child1) }; + let new_fg = child1 as i32; + let orig_fg = my_pid as i32; + let r_set_fg = unsafe { + syscall3( + N25_SYS_IOCTL, + 0, + N25_TIOCSPGRP, + &new_fg as *const i32 as u64, + ) + }; + let mut observed_fg: i32 = 0; + let r_get_fg = unsafe { + syscall3( + N25_SYS_IOCTL, + 0, + N25_TIOCGPGRP, + &mut observed_fg as *mut i32 as u64, + ) + }; + let r_restore_fg = unsafe { + syscall3( + N25_SYS_IOCTL, + 0, + N25_TIOCSPGRP, + &orig_fg as *const i32 as u64, + ) + }; + if c1_pgid != child1 + || c1_sid != my_pid + || is_error(r_set_fg) + || is_error(r_get_fg) + || observed_fg != new_fg + || is_error(r_restore_fg) + { + unsafe { sys_close(p2c[1] as u64) }; + reap_quietly(child1); + results.fail("n2_5: getpgid/getsid or TIOCSPGRP/TIOCGPGRP switch failed"); + return; + } + + let neg_c1 = (-(child1 as i64)) as u64; + let r_stop = unsafe { syscall2(N25_SYS_KILL, neg_c1, N25_SIGSTOP) }; + let mut wstatus: i32 = 0; + let r_wait_stop = unsafe { + syscall4( + N25_SYS_WAIT4, + neg_c1, + &mut wstatus as *mut i32 as u64, + WUNTRACED, + 0, + ) + }; + let expected_stop_status = ((N25_SIGSTOP as i32) << 8) | 0x7f; + + let r_cont = unsafe { syscall2(N25_SYS_KILL, neg_c1, N25_SIGCONT) }; + let mut cont_info = SigInfo::poisoned(); + let r_wait_cont = waitid(P_PGID, child1, &mut cont_info, N25_WCONTINUED); + + let go_byte = [b'G']; + let _ = unsafe { syscall3(SYS_WRITE, p2c[1] as u64, go_byte.as_ptr() as u64, 1) }; + unsafe { sys_close(p2c[1] as u64) }; + + let mut exit_info = SigInfo::poisoned(); + let r_wait_exit = waitid(P_PGID, child1, &mut exit_info, WEXITED); + + if is_error(r_stop) + || r_wait_stop != child1 + || wstatus != expected_stop_status + || is_error(r_cont) + || is_error(r_wait_cont) + || cont_info.signo() != SIGCHLD + || cont_info.code() != N25_CLD_CONTINUED + || cont_info.pid() as u64 != child1 + || cont_info.status() != N25_SIGCONT as i32 + || is_error(r_wait_exit) + || exit_info.signo() != SIGCHLD + || exit_info.code() != CLD_EXITED + || exit_info.pid() as u64 != child1 + || exit_info.status() != 37 + { + results + .fail("n2_5: kill(-pgid)/wait4(WUNTRACED)/waitid(P_PGID, WCONTINUED|WEXITED) failed"); + return; + } + + // Leg 2: setsid() detaches from inherited ctty, TIOCSCTTY(0) fails EPERM + // while another session owns it, TIOCSCTTY(1) steals, TIOCNOTTY detaches. + let child2 = unsafe { sys_fork() }; + if is_error(child2) { + results.fail("n2_5: fork child2 failed"); + return; + } + if child2 == 0 { + let c2_pid = unsafe { sys_getpid() }; + let ns = unsafe { syscall0(N25_SYS_SETSID) }; + if ns != c2_pid { + unsafe { userspace::syscall::sys_exit(11) }; + } + if unsafe { syscall0(N25_SYS_GETPGRP) } != c2_pid + || unsafe { syscall1(N25_SYS_GETSID, 0) } != c2_pid + { + unsafe { userspace::syscall::sys_exit(12) }; + } + let mut s: i32 = 0; + let r_gsid_no_ctty = + unsafe { syscall3(N25_SYS_IOCTL, 0, N25_TIOCGSID, &mut s as *mut i32 as u64) }; + if !is_error(r_gsid_no_ctty) || errno(r_gsid_no_ctty) != N25_ENOTTY { + unsafe { userspace::syscall::sys_exit(13) }; + } + let r_sctty_nosteal = unsafe { syscall3(N25_SYS_IOCTL, 0, N25_TIOCSCTTY, 0) }; + if !is_error(r_sctty_nosteal) || errno(r_sctty_nosteal) != N25_EPERM { + unsafe { userspace::syscall::sys_exit(14) }; + } + let r_sctty_steal = unsafe { syscall3(N25_SYS_IOCTL, 0, N25_TIOCSCTTY, 1) }; + if is_error(r_sctty_steal) { + unsafe { userspace::syscall::sys_exit(15) }; + } + let mut s2: i32 = 0; + let mut fg2: i32 = 0; + let r_gsid2 = + unsafe { syscall3(N25_SYS_IOCTL, 0, N25_TIOCGSID, &mut s2 as *mut i32 as u64) }; + let r_gpgrp2 = + unsafe { syscall3(N25_SYS_IOCTL, 0, N25_TIOCGPGRP, &mut fg2 as *mut i32 as u64) }; + if is_error(r_gsid2) || is_error(r_gpgrp2) || s2 != c2_pid as i32 || fg2 != c2_pid as i32 { + unsafe { userspace::syscall::sys_exit(16) }; + } + let r_notty = unsafe { syscall3(N25_SYS_IOCTL, 0, N25_TIOCNOTTY, 0) }; + if is_error(r_notty) { + unsafe { userspace::syscall::sys_exit(17) }; + } + // Session leader releasing its ctty sends SIGHUP to its foreground PGID + // (which includes child2 itself), so child2 should not reach exit(18). + unsafe { userspace::syscall::sys_exit(18) }; + } + + let mut c2_status: i32 = -1; + let r_c2 = unsafe { + syscall4( + N25_SYS_WAIT4, + child2, + &mut c2_status as *mut i32 as u64, + 0, + 0, + ) + }; + // Re-attach PID 1 to the console ctty after child2 released it with TIOCNOTTY. + let r_reattach = unsafe { syscall3(N25_SYS_IOCTL, 0, N25_TIOCSCTTY, 0) }; + let mut restored_sid: i32 = 0; + let r_check_sid = unsafe { + syscall3( + N25_SYS_IOCTL, + 0, + N25_TIOCGSID, + &mut restored_sid as *mut i32 as u64, + ) + }; + // 128 + SIGHUP(1) = 129 encoded in wait4 status as (129 << 8). + const EXPECTED_SIGHUP_STATUS: i32 = 129 << 8; + if r_c2 != child2 + || c2_status != EXPECTED_SIGHUP_STATUS + || is_error(r_reattach) + || is_error(r_check_sid) + || restored_sid != my_pid as i32 + { + results.fail("n2_5: setsid/TIOCSCTTY/TIOCNOTTY child2 leg failed"); + return; + } + + results.pass( + "N2.5 pgid/sid, controlling terminal ioctls, kill(-pgid), wait4/waitid stop & continue", + ); +}