//! Retained, boot-owned process identity metadata for the native product. //! //! This owner does not hold ELF images, exception frames, address spaces, ASIDs, //! physical pages, or scheduler tasks. A metadata transition never proves EL0 //! execution and never authorizes releasing any of those resources. The D3 //! execution owner must retain and retire them independently. use turkos_kernel::process::{Error, PROCESS_CAPACITY, ProcessTable}; pub(super) use turkos_kernel::process::{ProcessId as Id, State}; use core::sync::atomic::{Ordering, compiler_fence}; pub(super) const CAPACITY: usize = PROCESS_CAPACITY; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) struct Snapshot { pub init: Id, pub boot_id: u64, /// Occupied identities which have not exited. Exited identities are kept /// separately until their actual parent waits and reaps their metadata. pub live: u64, pub exited: u64, pub current: Option, pub execs: u64, pub spawns: u64, pub waits: u64, pub exits: u64, pub reaps: u64, pub stale_rejections: u64, } #[derive(Clone, Copy, PartialEq, Eq)] struct Record { id: Option, parent: Option, image_generation: u64, waiting_for: Option, } impl Record { const EMPTY: Self = Self { id: None, parent: None, image_generation: 0, waiting_for: None, }; } #[derive(Clone, PartialEq, Eq)] struct Owner { table: ProcessTable, records: [Record; CAPACITY], last_reaped: [Option; CAPACITY], boot_id: u64, init: Option, current: Option, execs: u64, spawns: u64, waits: u64, exits: u64, reaps: u64, stale_rejections: u64, shutting_down: bool, shutdown_retired: u64, } impl Owner { const fn new() -> Self { Self { table: ProcessTable::new(), records: [Record::EMPTY; CAPACITY], last_reaped: [None; CAPACITY], boot_id: 0, init: None, current: None, execs: 0, spawns: 0, waits: 0, exits: 0, reaps: 0, stale_rejections: 0, shutting_down: false, shutdown_retired: 0, } } fn checked_state(&mut self, id: Id) -> Result { match self.table.state(id) { Ok(state) if self.records[id.slot as usize].id == Some(id) => Ok(state), Ok(_) => Err("process-owner-record-mismatch"), Err(Error::StaleId) => { self.stale_rejections = self.stale_rejections.saturating_add(1); Err("process-owner-stale-id") } Err(error) => Err(tag(error)), } } fn require_current(&mut self, id: Id) -> Result<(), &'static str> { if self.shutting_down { return Err("process-owner-shutting-down"); } if self.checked_state(id)? != State::Running || self.current != Some(id) { return Err("process-owner-current-mismatch"); } Ok(()) } fn initialize(&mut self, boot_id: u64) -> Result { if self.shutting_down { return Err("process-owner-shutting-down"); } if boot_id == 0 { return Err("process-owner-zero-boot-id"); } if self.boot_id != 0 { if self.boot_id != boot_id { return Err("process-owner-boot-mismatch"); } // Idempotent access never recreates PID1 or clears retained state. return self.snapshot(); } let init = self.table.create().map_err(tag)?; if init.slot != 0 { return Err("process-owner-init-slot"); } self.records[0] = Record { id: Some(init), ..Record::EMPTY }; self.init = Some(init); self.boot_id = boot_id; self.snapshot() } fn snapshot(&mut self) -> Result { let init = self.init.ok_or("process-owner-uninitialized")?; if self.boot_id == 0 || self.records[init.slot as usize].parent.is_some() { return Err("process-owner-init-owner"); } if matches!(self.checked_state(init)?, State::Exited(_)) { return Err("process-owner-init-exited"); } let mut live = 0; let mut exited = 0; let mut running = None; for index in 0..CAPACITY { let Some(id) = self.records[index].id else { continue; }; match self.checked_state(id)? { State::Exited(_) => exited += 1, State::Running => { if running.replace(id).is_some() { return Err("process-owner-multiple-current"); } live += 1; } _ => live += 1, } } if self.current != running { return Err("process-owner-current-mismatch"); } Ok(Snapshot { init, boot_id: self.boot_id, live, exited, current: self.current, execs: self.execs, spawns: self.spawns, waits: self.waits, exits: self.exits, reaps: self.reaps, stale_rejections: self.stale_rejections, }) } fn start(&mut self, id: Id) -> Result<(), &'static str> { if self.shutting_down { return Err("process-owner-shutting-down"); } if self.checked_state(id)? != State::Ready || self.current.is_some() { return Err("process-owner-not-ready"); } self.table.run(id).map_err(tag)?; self.current = Some(id); Ok(()) } fn yield_ready(&mut self, id: Id) -> Result<(), &'static str> { self.require_current(id)?; self.table.yield_ready(id).map_err(tag)?; self.current = None; Ok(()) } fn spawn(&mut self, parent: Id) -> Result { self.require_current(parent)?; let spawns = next(self.spawns)?; let child = self.table.create().map_err(tag)?; self.records[child.slot as usize] = Record { id: Some(child), parent: Some(parent), ..Record::EMPTY }; self.spawns = spawns; Ok(child) } fn exec(&mut self, id: Id) -> Result { self.require_current(id)?; let generation = next(self.records[id.slot as usize].image_generation)?; let execs = next(self.execs)?; self.records[id.slot as usize].image_generation = generation; self.execs = execs; Ok(generation) } fn child_id(&mut self, parent: Id, token: u64) -> Result, &'static str> { self.require_current(parent)?; let child = self.records.iter().find_map(|record| { let id = record.id?; (pid(id) == token && record.parent == Some(parent)).then_some(id) }); if let Some(id) = child { // Exited children remain valid wait targets until their parent // reaps them. Never resolve a token using the slot number alone. self.checked_state(id)?; Ok(Some(id)) } else { // Count an actual rejected public child lookup, including a token // for another parent's process. No caller can increment this // evidence without performing the bounded ownership lookup. self.stale_rejections = self.stale_rejections.saturating_add(1); Ok(None) } } fn wait(&mut self, parent: Id, child: Id) -> Result, &'static str> { self.require_current(parent)?; let child_state = self.checked_state(child)?; if self.records[child.slot as usize].parent != Some(parent) { return Err("process-owner-not-child"); } let waits = next(self.waits)?; if let State::Exited(code) = child_state { let reaps = next(self.reaps)?; if self.table.reap(child).map_err(tag)? != code { return Err("process-owner-reap-code"); } self.records[child.slot as usize] = Record::EMPTY; self.last_reaped[child.slot as usize] = Some(child); self.waits = waits; self.reaps = reaps; return Ok(Some(code)); } if child_state == State::Running { return Err("process-owner-child-already-current"); } self.table.wait(parent).map_err(tag)?; self.records[parent.slot as usize].waiting_for = Some(child); self.current = None; self.waits = waits; Ok(None) } fn exit(&mut self, id: Id, code: i32) -> Result<(), &'static str> { self.require_current(id)?; if self.init == Some(id) { return Err("process-owner-init-must-survive"); } // The bounded product path has no orphan adoption service. Refuse to // lose any descendant's parent identity, including unreaped zombies. if self.records.iter().any(|entry| entry.parent == Some(id)) { return Err("process-owner-unreaped-children"); } let parent = self.records[id.slot as usize] .parent .ok_or("process-owner-parent-missing")?; let parent_state = self.checked_state(parent)?; if matches!(parent_state, State::Exited(_)) { return Err("process-owner-parent-exited"); } let wake = parent_state == State::Waiting && self.records[parent.slot as usize].waiting_for == Some(id); let exits = next(self.exits)?; self.table.exit(id, code).map_err(tag)?; self.current = None; if wake { self.table.wake(parent).map_err(tag)?; self.records[parent.slot as usize].waiting_for = None; } self.exits = exits; Ok(()) } fn interrupt_wait(&mut self, parent: Id, child: Id) -> Result<(), &'static str> { // A supervisor service event may interrupt a blocked wait. It never // reports an exit, reaps an identity, or changes the child's state. if self.current.is_some() || self.checked_state(parent)? != State::Waiting || self.records[parent.slot as usize].waiting_for != Some(child) || self.checked_state(child)? != State::Ready || self.records[child.slot as usize].parent != Some(parent) { return Err("process-owner-wait-interrupt-target"); } self.table.wake(parent).map_err(tag)?; self.records[parent.slot as usize].waiting_for = None; Ok(()) } fn shutdown_begin(&mut self) -> Result<(u64, u64), &'static str> { if self.shutting_down || self.current.is_some() || self.boot_id == 0 { return Err("process-owner-shutdown-context"); } let snap = self.snapshot()?; if snap.exited != 0 || snap.live != 2 { return Err("process-owner-shutdown-live"); } for slot in 0..CAPACITY { if let Some(id) = self.records[slot].id { if self.checked_state(id)? != State::Ready { return Err("process-owner-shutdown-not-ready"); } } } self.shutting_down = true; Ok((self.boot_id, snap.live)) } fn shutdown_retire(&mut self, id: Id) -> Result<(), &'static str> { if !self.shutting_down || self.current.is_some() || self.checked_state(id)? != State::Ready || self.records.iter().any(|entry| entry.parent == Some(id)) { return Err("process-owner-shutdown-order"); } // This is explicit kernel cancellation after execution storage was // retired, not a userspace exit or parent wait receipt. The normal // exit path still forbids PID1 exit. No callback can run here. self.table.run(id).map_err(tag)?; self.table.exit(id, -125).map_err(tag)?; if self.table.reap(id).map_err(tag)? != -125 { return Err("process-owner-shutdown-code"); } self.records[id.slot as usize] = Record::EMPTY; self.last_reaped[id.slot as usize] = Some(id); self.shutdown_retired = next(self.shutdown_retired)?; Ok(()) } fn reject_stale_wake( &mut self, caller: Id, old: Id, replacement: Id, ) -> Result<(), &'static str> { self.require_current(caller)?; if old.slot != replacement.slot || replacement.generation <= old.generation || usize::from(old.slot) >= CAPACITY || self.last_reaped[old.slot as usize] != Some(old) || self.checked_state(replacement)? != State::Ready { return Err("process-owner-stale-wake-binding"); } let before = self.table.clone(); if self.table.wake(old) != Err(Error::StaleId) || self.table != before { return Err("process-owner-stale-wake-was-not-refused"); } self.stale_rejections = next(self.stale_rejections)?; Ok(()) } fn shutdown_state(&self) -> (u64, u64, u64, bool) { let live = self .records .iter() .filter(|entry| entry.id.is_some()) .count() as u64; ( self.boot_id, self.shutdown_retired, live, self.shutting_down && self.current.is_none() && live == 0 && self.shutdown_retired == 2, ) } } fn next(value: u64) -> Result { value .checked_add(1) .ok_or("process-owner-counter-exhausted") } fn tag(error: Error) -> &'static str { match error { Error::Capacity => "process-owner-capacity", Error::GenerationExhausted => "process-owner-generation-exhausted", Error::StaleId => "process-owner-stale-id", Error::Transition => "process-owner-transition", Error::AlreadyRunning => "process-owner-already-running", } } // This is a boot-CPU reentry guard, never an inter-CPU lock. In particular it // must not issue exclusive accesses: native guest mappings need not support // exclusive byte loads. All other CPUs are rejected before touching this flag. static mut BUSY: bool = false; static mut OWNER: Owner = Owner::new(); #[cfg(target_os = "none")] static mut RANK_WINDOWS: [u64; 4] = [0; 4]; #[unsafe(no_mangle)] pub static mut OS_PRODUCT_D5_PROC_RANK: [u64; 64] = [0; 64]; struct Access; impl Drop for Access { fn drop(&mut self) { // Finish all metadata accesses before permitting synchronous reentry. // This fence is compiler-only and emits no exclusive/atomic accesses. compiler_fence(Ordering::SeqCst); // SAFETY: Access exists only while the boot CPU owns the flag with // every asynchronous exception class masked. No reference is retained. unsafe { core::ptr::write_volatile(core::ptr::addr_of_mut!(BUSY), false) }; } } fn require_boot_cpu() -> Result<(), &'static str> { #[cfg(target_arch = "aarch64")] { let cpu: u64; let el: u64; let daif: u64; // SAFETY: this runtime is an EL1-only native product module. These // observations neither change masks nor grant any hardware ownership. unsafe { core::arch::asm!( "mrs {cpu}, MPIDR_EL1", "mrs {el}, CurrentEL", "mrs {daif}, DAIF", cpu = out(reg) cpu, el = out(reg) el, daif = out(reg) daif, options(nomem, nostack, preserves_flags) ); } if el != 4 || daif & 0x3c0 != 0x3c0 { return Err("process-owner-masked-boot-cpu-required"); } #[cfg(target_os = "none")] if super::d5_smp::service_mode_active() { // The normal path remains a boot-CPU owner. Explicit D5 mode // transfers its sole ownership under the real global lease. super::d5_smp::authorize_service_cpu()?; } else if cpu & 0x0000_00ff_00ff_ffff != 0 { return Err("process-owner-masked-boot-cpu-required"); } #[cfg(not(target_os = "none"))] if cpu & 0x0000_00ff_00ff_ffff != 0 { return Err("process-owner-masked-boot-cpu-required"); } Ok(()) } #[cfg(not(target_arch = "aarch64"))] Err("process-owner-native-el1-required") } fn access(f: impl FnOnce(&mut Owner) -> Result) -> Result { access_with_probe(f, false) } fn access_with_probe( f: impl FnOnce(&mut Owner) -> Result, probe: bool, ) -> Result { require_boot_cpu()?; // SAFETY: the CPU/mask check precedes every access to this single-CPU // flag. Masking D/A/I/F prevents asynchronous entry between the check and // store; a synchronous exception here occurs before OWNER is borrowed. unsafe { if core::ptr::read_volatile(core::ptr::addr_of!(BUSY)) { return Err("process-owner-reentrant-access"); } core::ptr::write_volatile(core::ptr::addr_of_mut!(BUSY), true); } // Do not let the compiler move metadata access before publishing reentry // protection. The fence has no hardware atomic instruction requirement. compiler_fence(Ordering::SeqCst); let _access = Access; #[cfg(target_os = "none")] let _rank = super::d5_smp::enter_rank(20)?; // SAFETY: only the fully masked boot CPU may enter. BUSY rejects synchronous // reentry before another mutable reference can be created. No reference // escapes this private function; the closure cannot unmask exceptions or // switch CPUs, and secondary CPUs always fail before reading BUSY. let owner = unsafe { &mut *core::ptr::addr_of_mut!(OWNER) }; #[cfg(target_os = "none")] if probe && super::d5_smp::service_mode_active() { let (cpu, window, _) = super::d5_smp::service_window()?; if cpu >= 4 { return Err("process-owner-rank-cpu"); } let previous = unsafe { core::ptr::read_volatile( core::ptr::addr_of!(RANK_WINDOWS) .cast::() .add(cpu as usize), ) }; if previous != window { let before = owner.clone(); super::d5_smp::probe_rank_refusals()?; if *owner != before { return Err("process-owner-rank-refusal-mutated-authority"); } let record = unsafe { core::ptr::addr_of_mut!(OS_PRODUCT_D5_PROC_RANK) .cast::() .add(cpu as usize * 16) }; let count = unsafe { core::ptr::read_volatile(record.add(4)) } .checked_add(1) .ok_or("process-owner-rank-count")?; for (index, value) in [ (0, 0x50524f4352414e4b), (1, 1), (2, cpu), (3, window), (4, count), (5, 1), (6, 1), (7, owner.boot_id), (8, owner.spawns), (9, owner.execs), (10, owner.waits), (11, owner.exits), (12, owner.reaps), (13, owner.stale_rejections), ] { unsafe { core::ptr::write_volatile(record.add(index), value); } } unsafe { core::ptr::write_volatile( core::ptr::addr_of_mut!(RANK_WINDOWS) .cast::() .add(cpu as usize), window, ); } } } f(owner) } pub(super) fn probe_rank_invariance() -> Result<(), &'static str> { access_with_probe(|_| Ok(()), true) } /// Public process tokens use the table-wide monotonic generation, so a reaped /// process and its replacement never share a userspace wait token. The bounded /// slot remains an internal index; execution owners must retain the complete Id. pub(super) const fn pid(id: Id) -> u64 { id.generation } /// Creates a retained Ready PID1 without allocating frames or executing ELF. pub(super) fn initialize(boot_id: u64) -> Result { access(|owner| owner.initialize(boot_id)) } pub(super) fn snapshot() -> Result { access(Owner::snapshot) } /// Bounded source-owner metadata, including actual blocked-wait identities. /// ProcessTable's private generation counter is covered by the exact cloned /// authority comparison in the rank probe, never inferred from this export. pub(super) fn ownership_inventory(out: &mut [u64; 64]) -> Result<(), &'static str> { access(|owner| { out.fill(0); out[..11].copy_from_slice(&[ owner.boot_id, owner.current.map(pid).unwrap_or(0), owner.init.map(pid).unwrap_or(0), owner.spawns, owner.execs, owner.waits, owner.exits, owner.reaps, owner.stale_rejections, u64::from(owner.shutting_down), owner.shutdown_retired, ]); for slot in 0..CAPACITY { out[11 + slot] = owner.last_reaped[slot].map(pid).unwrap_or(0); let record = owner.records[slot]; let Some(id) = record.id else { continue; }; let state = owner.table.state(id).map_err(tag)?; let (state, code) = match state { State::Ready => (1, 0), State::Running => (2, 0), State::Waiting => (3, 0), State::Exited(code) => (4, code as i64 as u64), }; let at = 16 + slot * 12; out[at..at + 12].copy_from_slice(&[ 1, u64::from(id.slot), id.generation, u64::from(record.parent.is_some()), record.parent.map(|p| u64::from(p.slot)).unwrap_or(0), record.parent.map(|p| p.generation).unwrap_or(0), record.image_generation, u64::from(record.waiting_for.is_some()), record.waiting_for.map(|p| u64::from(p.slot)).unwrap_or(0), record.waiting_for.map(|p| p.generation).unwrap_or(0), state, code, ]); } Ok(()) }) } pub(super) fn state(id: Id) -> Result { access(|owner| owner.checked_state(id)) } pub(super) fn parent(id: Id) -> Result, &'static str> { access(|owner| { owner.checked_state(id)?; Ok(owner.records[id.slot as usize].parent) }) } pub(super) fn wait_target(id: Id) -> Result, &'static str> { access(|owner| { owner.checked_state(id)?; Ok(owner.records[id.slot as usize].waiting_for) }) } pub(super) fn image_generation(id: Id) -> Result { access(|owner| { owner.checked_state(id)?; Ok(owner.records[id.slot as usize].image_generation) }) } pub(super) fn start(id: Id) -> Result<(), &'static str> { access(|owner| owner.start(id)) } pub(super) fn yield_ready(id: Id) -> Result<(), &'static str> { access(|owner| owner.yield_ready(id)) } pub(super) fn spawn(parent: Id) -> Result { access(|owner| owner.spawn(parent)) } /// Advances an image's metadata generation without changing its process Id. /// The caller must separately prove the ELF image was validated and installed. pub(super) fn exec(id: Id) -> Result { access(|owner| owner.exec(id)) } /// Resolves a public wait token only for the current process's retained child. /// Unknown, reaped, and foreign tokens return None and record their rejection. pub(super) fn child_id(parent: Id, token: u64) -> Result, &'static str> { access(|owner| owner.child_id(parent, token)) } /// Waits for an actual child, or reaps only its exited identity metadata. /// This function never releases an ELF space, ASID, frame, or task resource. pub(super) fn wait(parent: Id, child: Id) -> Result, &'static str> { access(|owner| owner.wait(parent, child)) } /// Records a child exit and makes its waiting parent Ready. The parent's /// execution owner must separately resume its saved frame/address space. pub(super) fn exit(id: Id, code: i32) -> Result<(), &'static str> { access(|owner| owner.exit(id, code)) } /// Makes a blocked parent Ready for an actual interrupted-wait return. The /// execution owner must supply EINTR in the parent's saved syscall result. /// Both the child and the wait/exit/reap counters retain their actual history. pub(super) fn interrupt_wait(parent: Id, child: Id) -> Result<(), &'static str> { access(|owner| owner.interrupt_wait(parent, child)) } pub(super) fn shutdown_begin() -> Result<(u64, u64), &'static str> { access(Owner::shutdown_begin) } pub(super) fn shutdown_retire(id: Id) -> Result<(), &'static str> { access(|owner| owner.shutdown_retire(id)) } pub(super) fn shutdown_state() -> Result<(u64, u64, u64, bool), &'static str> { access(|owner| Ok(owner.shutdown_state())) } /// Observes an actually retired identity without incrementing the rejected /// user-lookup counter. This is an execution receipt check, not a wait lookup. pub(super) fn retired(id: Id) -> Result { access(|owner| { Ok(usize::from(id.slot) < CAPACITY && owner.records[id.slot as usize].id != Some(id) && owner.table.state(id) == Err(Error::StaleId)) }) } pub(super) fn retired_reused(old: Id, replacement: Id) -> Result { access(|owner| { Ok(usize::from(old.slot) < CAPACITY && old.slot == replacement.slot && replacement.generation > old.generation && owner.last_reaped[old.slot as usize] == Some(old) && owner.records[replacement.slot as usize].id == Some(replacement) && owner.table.state(old) == Err(Error::StaleId) && owner.table.state(replacement) == Ok(State::Ready)) }) } pub(super) fn reject_stale_wake(caller: Id, old: Id, replacement: Id) -> Result<(), &'static str> { access(|owner| owner.reject_stale_wake(caller, old, replacement)) } #[cfg(test)] mod tests { use super::*; #[test] fn actual_stale_wait_and_wake_preserve_reused_ready_child_authority() { let mut owner = Owner::new(); let init = owner.initialize(771).unwrap().init; owner.start(init).unwrap(); let old = owner.spawn(init).unwrap(); owner.wait(init, old).unwrap(); owner.start(old).unwrap(); owner.exit(old, 0).unwrap(); owner.start(init).unwrap(); assert_eq!(owner.wait(init, old), Ok(Some(0))); let replacement = owner.spawn(init).unwrap(); assert_eq!(old.slot, replacement.slot); assert_eq!(owner.last_reaped[old.slot as usize], Some(old)); let before = owner.clone(); assert_eq!(owner.wait(init, old), Err("process-owner-stale-id")); owner.reject_stale_wake(init, old, replacement).unwrap(); let mut expected = before.clone(); expected.stale_rejections += 2; assert!(owner == expected); assert_eq!(owner.table.state(replacement), Ok(State::Ready)); let unknown = Id { slot: old.slot, generation: old.generation - 1, }; assert_eq!( owner.reject_stale_wake(init, unknown, replacement), Err("process-owner-stale-wake-binding") ); assert!(owner == expected); } #[test] fn init_survives_child_fault_wait_reap_and_recycled_generation() { let mut owner = Owner::new(); let init = owner.initialize(77).unwrap().init; assert_eq!(pid(init), 1); owner.start(init).unwrap(); assert_eq!(owner.exec(init), Ok(1)); let shell = owner.spawn(init).unwrap(); assert_eq!(owner.wait(init, shell), Ok(None)); owner.start(shell).unwrap(); owner.exec(shell).unwrap(); let child = owner.spawn(shell).unwrap(); assert_eq!(owner.wait(shell, child), Ok(None)); owner.start(child).unwrap(); assert_eq!(owner.exec(child), Ok(1)); assert_eq!(owner.exec(child), Ok(2)); assert_eq!(owner.current, Some(child)); owner.exit(child, -11).unwrap(); assert_eq!(owner.checked_state(init), Ok(State::Waiting)); assert_eq!(owner.checked_state(shell), Ok(State::Ready)); owner.start(shell).unwrap(); assert_eq!(owner.wait(shell, child), Ok(Some(-11))); let replacement = owner.spawn(shell).unwrap(); assert_eq!(replacement.slot, child.slot); assert!(replacement.generation > child.generation); assert_ne!(pid(replacement), pid(child)); assert_eq!( owner.child_id(shell, pid(replacement)), Ok(Some(replacement)) ); assert_eq!(owner.child_id(shell, pid(child)), Ok(None)); assert_eq!(owner.checked_state(child), Err("process-owner-stale-id")); assert_eq!(owner.exit(child, 0), Err("process-owner-stale-id")); owner.yield_ready(shell).unwrap(); let snapshot = owner.snapshot().unwrap(); assert_eq!(snapshot.init, init); assert_eq!(snapshot.current, None); assert_eq!(snapshot.live, 3); assert_eq!(snapshot.exited, 0); assert_eq!(snapshot.reaps, 1); assert_eq!(snapshot.stale_rejections, 3); } #[test] fn wrong_parent_wait_and_pid1_exit_do_not_mutate_lifecycle() { let mut owner = Owner::new(); let init = owner.initialize(88).unwrap().init; owner.start(init).unwrap(); let shell = owner.spawn(init).unwrap(); let sibling = owner.spawn(init).unwrap(); assert_eq!(owner.exit(init, 0), Err("process-owner-init-must-survive")); owner.wait(init, shell).unwrap(); owner.start(shell).unwrap(); let before = owner.snapshot().unwrap(); assert_eq!(owner.wait(shell, sibling), Err("process-owner-not-child")); assert_eq!(owner.snapshot(), Ok(before)); assert_eq!(owner.child_id(shell, pid(sibling)), Ok(None)); assert_eq!(owner.stale_rejections, before.stale_rejections + 1); let child = owner.spawn(shell).unwrap(); assert_eq!(owner.exit(shell, 0), Err("process-owner-unreaped-children")); assert_eq!(owner.checked_state(shell), Ok(State::Running)); assert_eq!(owner.checked_state(child), Ok(State::Ready)); } #[test] fn repeated_initialization_preserves_owner_and_rejects_boot_replacement() { let mut owner = Owner::new(); assert_eq!(owner.initialize(0), Err("process-owner-zero-boot-id")); let before = owner.initialize(99).unwrap(); assert_eq!(owner.initialize(99), Ok(before)); assert_eq!(owner.initialize(100), Err("process-owner-boot-mismatch")); assert_eq!(owner.snapshot(), Ok(before)); owner.start(before.init).unwrap(); let child = owner.spawn(before.init).unwrap(); let running = owner.snapshot().unwrap(); assert_eq!(owner.initialize(99), Ok(running)); assert_eq!(owner.records[child.slot as usize].parent, Some(before.init)); } #[test] fn interrupted_live_child_wait_retains_both_identities_and_exit_history() { let mut owner = Owner::new(); let init = owner.initialize(123).unwrap().init; owner.start(init).unwrap(); let shell = owner.spawn(init).unwrap(); owner.wait(init, shell).unwrap(); let before = owner.snapshot().unwrap(); owner.interrupt_wait(init, shell).unwrap(); let after = owner.snapshot().unwrap(); assert_eq!(owner.checked_state(init), Ok(State::Ready)); assert_eq!(owner.checked_state(shell), Ok(State::Ready)); assert_eq!(after.live, 2); assert_eq!(after.exited, 0); assert_eq!(after.waits, before.waits); assert_eq!(after.exits, before.exits); assert_eq!(after.reaps, before.reaps); assert_eq!(owner.records[init.slot as usize].waiting_for, None); assert_eq!(owner.records[shell.slot as usize].parent, Some(init)); assert_eq!( owner.interrupt_wait(init, shell), Err("process-owner-wait-interrupt-target") ); owner.start(init).unwrap(); assert_eq!(owner.wait(init, shell), Ok(None)); } #[test] fn shutdown_requires_quiescence_and_cancels_child_before_init_without_wait_receipts() { let mut owner = Owner::new(); let init = owner.initialize(515).unwrap().init; owner.start(init).unwrap(); let shell = owner.spawn(init).unwrap(); assert_eq!( owner.shutdown_begin(), Err("process-owner-shutdown-context") ); owner.yield_ready(init).unwrap(); let before = owner.snapshot().unwrap(); assert_eq!(owner.shutdown_begin(), Ok((515, 2))); assert_eq!( owner.shutdown_retire(init), Err("process-owner-shutdown-order") ); assert_eq!(owner.start(shell), Err("process-owner-shutting-down")); owner.shutdown_retire(shell).unwrap(); assert_eq!(owner.shutdown_state(), (515, 1, 1, false)); owner.shutdown_retire(init).unwrap(); assert_eq!(owner.shutdown_state(), (515, 2, 0, true)); assert_eq!(owner.initialize(515), Err("process-owner-shutting-down")); assert_eq!( (owner.waits, owner.exits, owner.reaps), (before.waits, before.exits, before.reaps) ); } }