Skip to main content

coreshift_core/spawn/
mod.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/
4
5//! Process spawning and lifecycle management.
6//!
7//! This module exposes explicit Linux/Android process primitives. Callers must
8//! provide the exact argument vector and choose the spawn backend. Core does not
9//! infer shell/root behavior, select backends from platform properties, or
10//! silently switch between backends.
11
12use std::ffi::CString;
13use std::mem::MaybeUninit;
14use std::os::unix::io::RawFd;
15use std::ptr;
16use std::time::{Duration, Instant};
17
18use crate::CoreError;
19use crate::error::{posix_ret, syscall_ret};
20use crate::fd::Fd;
21use crate::signal::SignalRuntime;
22use libc::{
23    O_CLOEXEC, O_NONBLOCK, WEXITSTATUS, WIFEXITED, WIFSIGNALED, WTERMSIG, c_char, pid_t, pipe2,
24    waitpid,
25};
26
27unsafe extern "C" {
28    pub(crate) static mut environ: *mut *mut libc::c_char;
29}
30
31pub(crate) const POSIX_SPAWN_SETPGROUP: i32 = 2;
32pub(crate) const POSIX_SPAWN_SETSIGDEF: i32 = 4;
33pub(crate) const POSIX_SPAWN_SETSIGMASK: i32 = 8;
34
35unsafe extern "C" {
36    pub(crate) fn posix_spawn(
37        pid: *mut libc::pid_t,
38        path: *const libc::c_char,
39        file_actions: *const libc::posix_spawn_file_actions_t,
40        attrp: *const libc::posix_spawnattr_t,
41        argv: *const *mut libc::c_char,
42        envp: *const *mut libc::c_char,
43    ) -> libc::c_int;
44
45    pub(crate) fn posix_spawn_file_actions_addclose(
46        file_actions: *mut libc::posix_spawn_file_actions_t,
47        fd: libc::c_int,
48    ) -> libc::c_int;
49
50    pub(crate) fn posix_spawn_file_actions_adddup2(
51        file_actions: *mut libc::posix_spawn_file_actions_t,
52        fd: libc::c_int,
53        newfd: libc::c_int,
54    ) -> libc::c_int;
55
56    pub(crate) fn posix_spawn_file_actions_destroy(
57        file_actions: *mut libc::posix_spawn_file_actions_t,
58    ) -> libc::c_int;
59
60    pub(crate) fn posix_spawn_file_actions_init(
61        file_actions: *mut libc::posix_spawn_file_actions_t,
62    ) -> libc::c_int;
63
64    pub(crate) fn posix_spawnattr_destroy(attr: *mut libc::posix_spawnattr_t) -> libc::c_int;
65
66    pub(crate) fn posix_spawnattr_init(attr: *mut libc::posix_spawnattr_t) -> libc::c_int;
67
68    pub(crate) fn posix_spawnattr_setflags(
69        attr: *mut libc::posix_spawnattr_t,
70        flags: libc::c_short,
71    ) -> libc::c_int;
72
73    pub(crate) fn posix_spawnattr_setpgroup(
74        attr: *mut libc::posix_spawnattr_t,
75        pgroup: libc::pid_t,
76    ) -> libc::c_int;
77
78    pub(crate) fn posix_spawnattr_setsigdefault(
79        attr: *mut libc::posix_spawnattr_t,
80        sigdefault: *const libc::sigset_t,
81    ) -> libc::c_int;
82
83    pub(crate) fn posix_spawnattr_setsigmask(
84        attr: *mut libc::posix_spawnattr_t,
85        sigmask: *const libc::sigset_t,
86    ) -> libc::c_int;
87}
88
89/// Policy for handling process cancellation or timeouts.
90#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
91pub enum CancelPolicy {
92    /// Do nothing on cancellation; let the process run to completion.
93    #[default]
94    None,
95    /// Send SIGTERM, then SIGKILL after a grace period.
96    Graceful,
97    /// Send SIGKILL immediately.
98    Kill,
99}
100
101/// Process group and session configuration.
102#[derive(Debug, Clone, Copy, Default)]
103pub struct ProcessGroup {
104    /// Join an existing process group leader.
105    pub leader: Option<pid_t>,
106    /// Create a new session (`setsid`).
107    pub isolated: bool,
108}
109
110impl ProcessGroup {
111    /// Create a new process group configuration.
112    pub fn new(leader: Option<pid_t>, isolated: bool) -> Self {
113        Self { leader, isolated }
114    }
115}
116
117#[inline(always)]
118fn errno() -> i32 {
119    std::io::Error::last_os_error().raw_os_error().unwrap_or(0)
120}
121
122/// Creates a pipe with O_CLOEXEC | O_NONBLOCK flags.
123/// Invariants: FDs returned are strictly non-negative and will close automatically on drop.
124#[inline(always)]
125fn make_pipe() -> Result<(Fd, Fd), CoreError> {
126    let mut fds = [0; 2];
127    let r = unsafe { pipe2(fds.as_mut_ptr(), O_CLOEXEC | O_NONBLOCK) };
128    syscall_ret(r, "pipe2")?;
129    Ok((Fd::new(fds[0], "pipe2")?, Fd::new(fds[1], "pipe2")?))
130}
131
132fn make_cloexec_pipe() -> Result<(RawFd, RawFd), CoreError> {
133    let mut fds = [0; 2];
134    let r = unsafe { pipe2(fds.as_mut_ptr(), O_CLOEXEC) };
135    syscall_ret(r, "pipe2")?;
136    Ok((fds[0], fds[1]))
137}
138
139#[repr(u8)]
140#[derive(Clone, Copy)]
141enum ChildSetupOp {
142    DupStdin = 1,
143    DupStdout = 2,
144    DupStderr = 3,
145    Setsid = 4,
146    Chdir = 5,
147    Setpgid = 6,
148    SignalMask = 7,
149    Execve = 8,
150}
151
152impl ChildSetupOp {
153    fn as_str(self) -> &'static str {
154        match self {
155            Self::DupStdin => "fork child dup2 stdin",
156            Self::DupStdout => "fork child dup2 stdout",
157            Self::DupStderr => "fork child dup2 stderr",
158            Self::Setsid => "fork child setsid",
159            Self::Chdir => "fork child chdir",
160            Self::Setpgid => "fork child setpgid",
161            Self::SignalMask => "fork child signal setup",
162            Self::Execve => "fork child execve",
163        }
164    }
165
166    fn from_u8(value: u8) -> Self {
167        match value {
168            1 => Self::DupStdin,
169            2 => Self::DupStdout,
170            3 => Self::DupStderr,
171            4 => Self::Setsid,
172            5 => Self::Chdir,
173            6 => Self::Setpgid,
174            7 => Self::SignalMask,
175            _ => Self::Execve,
176        }
177    }
178}
179
180unsafe fn report_child_setup_error(fd: RawFd, op: ChildSetupOp, code: i32) -> ! {
181    let mut msg = [0u8; 5];
182    msg[..4].copy_from_slice(&code.to_ne_bytes());
183    msg[4] = op as u8;
184    let mut written = 0;
185    while written < msg.len() {
186        let n = unsafe {
187            libc::write(
188                fd,
189                msg[written..].as_ptr().cast::<libc::c_void>(),
190                msg.len() - written,
191            )
192        };
193        if n <= 0 {
194            break;
195        }
196        written += n as usize;
197    }
198    unsafe {
199        libc::_exit(127);
200    }
201}
202
203fn read_child_setup_error(fd: RawFd) -> Result<Option<CoreError>, CoreError> {
204    let mut msg = [0u8; 5];
205    let mut read_len = 0;
206    loop {
207        let n = unsafe {
208            libc::read(
209                fd,
210                msg[read_len..].as_mut_ptr().cast::<libc::c_void>(),
211                msg.len() - read_len,
212            )
213        };
214        if n == 0 {
215            return Ok(None);
216        }
217        if n < 0 {
218            let code = errno();
219            if code == libc::EINTR {
220                continue;
221            }
222            return Err(CoreError::sys(code, "read fork child setup error"));
223        }
224        read_len += n as usize;
225        if read_len == msg.len() {
226            let code = i32::from_ne_bytes([msg[0], msg[1], msg[2], msg[3]]);
227            return Ok(Some(CoreError::sys(
228                code,
229                ChildSetupOp::from_u8(msg[4]).as_str(),
230            )));
231        }
232    }
233}
234
235struct Pipes {
236    stdin_r: Option<Fd>,
237    stdin_w: Option<Fd>,
238    stdout_r: Option<Fd>,
239    stdout_w: Option<Fd>,
240    stderr_r: Option<Fd>,
241    stderr_w: Option<Fd>,
242}
243
244impl Pipes {
245    fn new(in_buf: Option<&[u8]>, out: bool, err: bool) -> Result<Self, CoreError> {
246        let (stdin_r, stdin_w) = if in_buf.is_some() {
247            let (r, w) = make_pipe()?;
248            (Some(r), Some(w))
249        } else {
250            (None, None)
251        };
252
253        let (stdout_r, stdout_w) = if out {
254            let (r, w) = make_pipe()?;
255            (Some(r), Some(w))
256        } else {
257            (None, None)
258        };
259
260        let (stderr_r, stderr_w) = if err {
261            let (r, w) = make_pipe()?;
262            (Some(r), Some(w))
263        } else {
264            (None, None)
265        };
266
267        Ok(Self {
268            stdin_r,
269            stdin_w,
270            stdout_r,
271            stdout_w,
272            stderr_r,
273            stderr_w,
274        })
275    }
276
277    #[inline(always)]
278    fn close_all(&mut self) {
279        self.stdin_r.take();
280        self.stdin_w.take();
281        self.stdout_r.take();
282        self.stdout_w.take();
283        self.stderr_r.take();
284        self.stderr_w.take();
285    }
286}
287
288/// Represents the termination status of a process.
289#[derive(Debug, PartialEq, Eq)]
290pub enum ExitStatus {
291    /// Process exited normally with the specified code.
292    Exited(i32),
293    /// Process was terminated by a signal.
294    Signaled(i32),
295}
296
297/// Explicit process spawning backend.
298#[derive(Debug, Clone, Copy, PartialEq, Eq)]
299pub enum SpawnBackend {
300    /// Force the use of `posix_spawn`.
301    PosixSpawn,
302    /// Force the use of `fork`/`exec`.
303    ///
304    /// The fork backend supports explicit [`SpawnFdPolicy`] handling before
305    /// `execve`.
306    Fork,
307}
308
309/// Explicit file-descriptor inheritance policy for spawned children.
310#[derive(Debug, Clone, PartialEq, Eq, Default)]
311pub enum SpawnFdPolicy {
312    /// Inherit descriptors according to their existing `FD_CLOEXEC` flags.
313    #[default]
314    CloexecOnly,
315    /// For the fork backend, close every descriptor >= 3 before `execve`,
316    /// except Core-required pipe descriptors.
317    CloseFrom3,
318    /// For the fork backend, close every descriptor >= 3 before `execve`,
319    /// except Core-required pipe descriptors and the listed descriptors.
320    ///
321    /// Core does not close allowlisted descriptors, but their existing
322    /// `FD_CLOEXEC` state still applies. Callers that want an allowlisted
323    /// descriptor to survive `execve` must clear `FD_CLOEXEC` before spawning.
324    Allowlist(Vec<RawFd>),
325}
326
327/// Owned argument vector storage for spawn internals.
328#[derive(Clone)]
329enum ExecArgv {
330    /// Dynamically allocated C-compatible strings.
331    Dynamic(Vec<CString>),
332}
333
334/// Validated execution context for process spawning.
335#[derive(Clone)]
336struct ExecContext {
337    argv: ExecArgv,
338    envp: Option<Vec<CString>>,
339    cwd: Option<CString>,
340}
341
342impl ExecContext {
343    /// Build a validated execution context for process spawn.
344    fn new(
345        argv: Vec<String>,
346        env: Option<Vec<String>>,
347        cwd: Option<String>,
348    ) -> Result<Self, CoreError> {
349        if argv.is_empty() {
350            return Err(CoreError::sys(libc::EINVAL, "exec argv empty"));
351        }
352
353        let c_argv: Vec<CString> = argv
354            .into_iter()
355            .map(|s| {
356                CString::new(s).map_err(|_| CoreError::sys(libc::EINVAL, "exec argv contains nul"))
357            })
358            .collect::<Result<_, _>>()?;
359
360        let c_envp = match env {
361            Some(vars) => Some(
362                vars.into_iter()
363                    .map(|s| {
364                        CString::new(s)
365                            .map_err(|_| CoreError::sys(libc::EINVAL, "exec env contains nul"))
366                    })
367                    .collect::<Result<Vec<_>, _>>()?,
368            ),
369            None => None,
370        };
371
372        let c_cwd = match cwd {
373            Some(c) => Some(
374                CString::new(c)
375                    .map_err(|_| CoreError::sys(libc::EINVAL, "exec cwd contains nul"))?,
376            ),
377            None => None,
378        };
379
380        Ok(Self {
381            argv: ExecArgv::Dynamic(c_argv),
382            envp: c_envp,
383            cwd: c_cwd,
384        })
385    }
386
387    /// Return a vector of pointers to the argument strings.
388    fn get_argv_ptrs(&self) -> Vec<*mut libc::c_char> {
389        let mut ptrs = Vec::new();
390        match &self.argv {
391            ExecArgv::Dynamic(v) => {
392                for s in v {
393                    ptrs.push(s.as_ptr() as *mut libc::c_char);
394                }
395            }
396        }
397        ptrs.push(ptr::null_mut());
398        ptrs
399    }
400
401    /// Return a vector of pointers to the environment strings.
402    fn get_envp_ptrs(&self) -> Option<Vec<*mut libc::c_char>> {
403        self.envp.as_ref().map(|envp| {
404            let mut ptrs = Vec::new();
405            for s in envp {
406                ptrs.push(s.as_ptr() as *mut libc::c_char);
407            }
408            ptrs.push(ptr::null_mut());
409            ptrs
410        })
411    }
412}
413
414#[inline(always)]
415fn decode_status(status: i32) -> ExitStatus {
416    if WIFEXITED(status) {
417        ExitStatus::Exited(WEXITSTATUS(status))
418    } else if WIFSIGNALED(status) {
419        ExitStatus::Signaled(WTERMSIG(status))
420    } else {
421        ExitStatus::Exited(-1)
422    }
423}
424
425/// A handle to a spawned process.
426///
427/// ### Fork Safety
428/// The process handle contains a PID. After a `fork`, the child process will
429/// have a copy of this PID, but it refers to the same original process.
430/// Calling `wait` or `kill` from the child may lead to confusing results
431/// if multiple processes are managing the same PID.
432pub struct Process {
433    pid: pid_t,
434}
435
436impl Process {
437    /// Create a handle for an existing PID.
438    pub fn new(pid: pid_t) -> Self {
439        Self { pid }
440    }
441
442    /// Return the process ID.
443    pub fn pid(&self) -> pid_t {
444        self.pid
445    }
446
447    /// Perform a non-blocking wait for process termination.
448    ///
449    /// ### Errors
450    /// - `ECHILD`: The process does not exist or is not a child of the caller.
451    /// - `EINTR`: The call was interrupted by a signal (handled internally).
452    pub fn wait_step(&self) -> Result<Option<ExitStatus>, CoreError> {
453        loop {
454            let mut status = 0;
455            let r = unsafe { waitpid(self.pid, &mut status, libc::WNOHANG) };
456            if r == 0 {
457                return Ok(None);
458            }
459            if r < 0 {
460                let e = errno();
461                if e == libc::EINTR {
462                    continue;
463                }
464                return Err(CoreError::sys(e, "waitpid_step"));
465            }
466            return Ok(Some(decode_status(status)));
467        }
468    }
469
470    /// Block until the process terminates.
471    ///
472    /// ### Errors
473    /// - `ECHILD`: The process does not exist or is not a child of the caller.
474    pub fn wait_blocking(&self) -> Result<ExitStatus, CoreError> {
475        loop {
476            let mut status = 0;
477            let r = unsafe { waitpid(self.pid, &mut status, 0) };
478            if r < 0 {
479                let e = errno();
480                if e == libc::EINTR {
481                    continue;
482                }
483                return Err(CoreError::sys(e, "waitpid_blocking"));
484            }
485            return Ok(decode_status(status));
486        }
487    }
488
489    /// Send a signal to the process.
490    ///
491    /// ### Errors
492    /// - `EINVAL`: Invalid signal number.
493    /// - `EPERM`: The caller does not have permission to send the signal.
494    /// - `ESRCH`: The process does not exist.
495    pub fn kill(&self, sig: i32) -> Result<(), CoreError> {
496        let r = unsafe { libc::kill(self.pid, sig) };
497        if r < 0 {
498            let e = errno();
499            if e == libc::ESRCH {
500                return Ok(());
501            }
502            syscall_ret(-1, "kill")?;
503        }
504        Ok(())
505    }
506
507    /// Signal the process group whose id equals [`Self::pid`] — valid only
508    /// when the process is its own group/session leader. For a child placed
509    /// into a custom leader's group use [`Self::kill_group`].
510    ///
511    /// ### Errors
512    /// Same as [`Self::kill`].
513    pub fn kill_pgroup(&self, sig: i32) -> Result<(), CoreError> {
514        self.kill_group(self.pid, sig)
515    }
516
517    /// Send a signal to an explicit process group.
518    ///
519    /// The pgid must be the child's actual group (its own pid after `setsid`,
520    /// or the configured leader's id after `setpgid`), never guessed from the
521    /// pid.
522    ///
523    /// ### Errors
524    /// Same as [`Self::kill`].
525    pub fn kill_group(&self, pgid: pid_t, sig: i32) -> Result<(), CoreError> {
526        let r = unsafe { libc::kill(-pgid, sig) };
527        if r < 0 {
528            let e = errno();
529            if e == libc::ESRCH {
530                return Ok(());
531            }
532            syscall_ret(-1, "kill_group")?;
533        }
534        Ok(())
535    }
536}
537
538/// Configuration options for spawning a new process.
539#[derive(Clone)]
540pub struct SpawnOptions {
541    ctx: ExecContext,
542    stdin: Option<Box<[u8]>>,
543    capture_stdout: bool,
544    capture_stderr: bool,
545    wait: bool,
546    pgroup: ProcessGroup,
547    max_output: usize,
548    timeout_ms: Option<u32>,
549    kill_grace_ms: u32,
550    cancel: CancelPolicy,
551    backend: SpawnBackend,
552    fd_policy: SpawnFdPolicy,
553    early_exit: Option<fn(&[u8]) -> bool>,
554}
555
556impl SpawnOptions {
557    /// Create a new builder for process spawning.
558    pub fn builder(argv: Vec<String>, backend: SpawnBackend) -> SpawnOptionsBuilder {
559        SpawnOptionsBuilder::new(argv, backend)
560    }
561
562    /// Execute the process according to the options and block until completion.
563    pub fn run(self) -> Result<Output, CoreError> {
564        spawn(self)
565    }
566}
567
568/// Builder for [`SpawnOptions`].
569#[derive(Clone)]
570pub struct SpawnOptionsBuilder {
571    argv: Vec<String>,
572    env: Option<Vec<String>>,
573    cwd: Option<String>,
574    stdin: Option<Box<[u8]>>,
575    capture_stdout: bool,
576    capture_stderr: bool,
577    wait: bool,
578    pgroup: ProcessGroup,
579    max_output: usize,
580    timeout_ms: Option<u32>,
581    kill_grace_ms: u32,
582    cancel: CancelPolicy,
583    backend: SpawnBackend,
584    fd_policy: SpawnFdPolicy,
585    early_exit: Option<fn(&[u8]) -> bool>,
586}
587
588impl SpawnOptionsBuilder {
589    /// Create a new builder with the specified argument vector.
590    pub fn new(argv: Vec<String>, backend: SpawnBackend) -> Self {
591        Self {
592            argv,
593            env: None,
594            cwd: None,
595            stdin: None,
596            capture_stdout: false,
597            capture_stderr: false,
598            wait: true,
599            pgroup: ProcessGroup::default(),
600            max_output: 1024 * 1024,
601            timeout_ms: None,
602            kill_grace_ms: 2000,
603            cancel: CancelPolicy::Kill,
604            backend,
605            fd_policy: SpawnFdPolicy::default(),
606            early_exit: None,
607        }
608    }
609
610    /// Set environment variables.
611    pub fn env(mut self, env: Vec<String>) -> Self {
612        self.env = Some(env);
613        self
614    }
615
616    /// Set the working directory.
617    pub fn cwd(mut self, cwd: String) -> Self {
618        self.cwd = Some(cwd);
619        self
620    }
621
622    /// Provide data to be written to the child's stdin.
623    pub fn stdin(mut self, data: impl Into<Box<[u8]>>) -> Self {
624        self.stdin = Some(data.into());
625        self
626    }
627
628    /// Enable stdout capture.
629    pub fn capture_stdout(mut self) -> Self {
630        self.capture_stdout = true;
631        self
632    }
633
634    /// Enable stderr capture.
635    pub fn capture_stderr(mut self) -> Self {
636        self.capture_stderr = true;
637        self
638    }
639
640    /// Set whether to wait for the process to terminate (default: true).
641    pub fn wait(mut self, wait: bool) -> Self {
642        self.wait = wait;
643        self
644    }
645
646    /// Set process group and isolation policy.
647    pub fn pgroup(mut self, pgroup: ProcessGroup) -> Self {
648        self.pgroup = pgroup;
649        self
650    }
651
652    /// Set the combined stdout+stderr output buffer size (default: 1MB).
653    ///
654    /// If captured output exceeds this limit, spawn drains the child pipes to
655    /// completion and returns `EOVERFLOW`.
656    pub fn max_output(mut self, max: usize) -> Self {
657        self.max_output = max;
658        self
659    }
660
661    /// Set the execution timeout in milliseconds.
662    pub fn timeout_ms(mut self, ms: u32) -> Self {
663        self.timeout_ms = Some(ms);
664        self
665    }
666
667    /// Set the grace period before SIGKILL (default: 2s).
668    pub fn kill_grace_ms(mut self, ms: u32) -> Self {
669        self.kill_grace_ms = ms;
670        self
671    }
672
673    /// Set the cancellation policy (default: Kill).
674    pub fn cancel(mut self, policy: CancelPolicy) -> Self {
675        self.cancel = policy;
676        self
677    }
678
679    /// Set the child file-descriptor inheritance policy.
680    pub fn fd_policy(mut self, policy: SpawnFdPolicy) -> Self {
681        self.fd_policy = policy;
682        self
683    }
684
685    /// Set an early exit callback.
686    pub fn early_exit(mut self, callback: fn(&[u8]) -> bool) -> Self {
687        self.early_exit = Some(callback);
688        self
689    }
690
691    /// Build the spawn options.
692    pub fn build(self) -> Result<SpawnOptions, CoreError> {
693        let ctx = ExecContext::new(self.argv, self.env, self.cwd)?;
694        Ok(SpawnOptions {
695            ctx,
696            stdin: self.stdin,
697            capture_stdout: self.capture_stdout,
698            capture_stderr: self.capture_stderr,
699            wait: self.wait,
700            pgroup: self.pgroup,
701            max_output: self.max_output,
702            timeout_ms: self.timeout_ms,
703            kill_grace_ms: self.kill_grace_ms,
704            cancel: self.cancel,
705            backend: self.backend,
706            fd_policy: self.fd_policy,
707            early_exit: self.early_exit,
708        })
709    }
710}
711
712/// The result of a process execution.
713#[derive(Debug)]
714pub struct Output {
715    /// The PID of the finished process.
716    pub pid: pid_t,
717    /// Final exit status (None if `wait=false`).
718    pub status: Option<ExitStatus>,
719    /// Captured stdout buffer.
720    pub stdout: Vec<u8>,
721    /// Captured stderr buffer.
722    pub stderr: Vec<u8>,
723    /// Whether the process timed out.
724    pub timed_out: bool,
725    /// Whether stdout drain stopped because the early-exit callback matched.
726    pub stdout_early_exited: bool,
727}
728
729fn validate_backend(opts: &SpawnOptions) -> Result<(), CoreError> {
730    validate_fd_policy(&opts.fd_policy)?;
731    match opts.backend {
732        SpawnBackend::PosixSpawn => {
733            if opts.ctx.cwd.is_some() {
734                return Err(CoreError::sys(libc::EINVAL, "posix_spawn cwd unsupported"));
735            }
736            if opts.pgroup.isolated {
737                return Err(CoreError::sys(
738                    libc::EINVAL,
739                    "posix_spawn setsid unsupported",
740                ));
741            }
742            if opts.fd_policy != SpawnFdPolicy::CloexecOnly {
743                return Err(CoreError::sys(
744                    libc::EINVAL,
745                    "posix_spawn fd policy unsupported",
746                ));
747            }
748            Ok(())
749        }
750        SpawnBackend::Fork => Ok(()),
751    }
752}
753
754fn validate_fd_policy(policy: &SpawnFdPolicy) -> Result<(), CoreError> {
755    if let SpawnFdPolicy::Allowlist(fds) = policy {
756        let mut seen = Vec::with_capacity(fds.len());
757        for &fd in fds {
758            if fd < 0 {
759                return Err(CoreError::sys(libc::EINVAL, "spawn fd allowlist invalid"));
760            }
761            let flags = unsafe { libc::fcntl(fd, libc::F_GETFD) };
762            if flags < 0 {
763                return Err(CoreError::sys(errno(), "spawn fd allowlist fcntl(F_GETFD)"));
764            }
765            if seen.contains(&fd) {
766                return Err(CoreError::sys(libc::EINVAL, "spawn fd allowlist duplicate"));
767            }
768            seen.push(fd);
769        }
770    }
771    Ok(())
772}
773
774use crate::io::DrainState;
775
776/// Specialized drain state for process spawning.
777pub type SpawnDrain = DrainState<fn(&[u8]) -> bool>;
778
779/// A process that is currently running and being monitored.
780///
781/// ### Fork Safety
782/// This handle contains both a PID and owned file descriptors for process I/O.
783/// Upon `fork`, the descriptors are inherited. Standard `O_CLOEXEC` behavior
784/// applies after `exec`.
785pub struct RunningProcess {
786    /// Handle to the process.
787    pub process: Process,
788    drain: SpawnDrain,
789}
790
791/// Full process lifecycle driven by a caller-owned reactor.
792///
793/// `ManagedProcess` preserves the blocking [`spawn`] semantics while allowing
794/// an application reactor to stay responsive: Core owns timeout/cancellation
795/// escalation, process-group signaling, pipe draining, overflow reporting, and
796/// `waitpid` reaping; the caller only routes readiness events and polls on
797/// [`Self::next_deadline`].
798pub struct ManagedProcess {
799    running: Option<RunningProcess>,
800    timeout_at: Option<Instant>,
801    kill_grace: Duration,
802    cancel: CancelPolicy,
803    pgroup: ProcessGroup,
804    cancel_at: Option<Instant>,
805    kill_state: KillState,
806    status: Option<ExitStatus>,
807    timed_out: bool,
808}
809
810impl RunningProcess {
811    /// Register active stdio pipe descriptors with a reactor.
812    ///
813    /// Call this once after [`spawn_start`] when the process was started with
814    /// captured output or stdin data. The assigned tokens are kept internally
815    /// and later matched by [`Self::handle_reactor_event`].
816    pub fn register_with_reactor(&mut self, reactor: &mut Reactor) -> Result<(), CoreError> {
817        self.drain.register_with_reactor(reactor)
818    }
819
820    /// Apply one reactor readiness event to this process' stdio drain state.
821    ///
822    /// Events for unrelated tokens are ignored. Callers remain responsible for
823    /// waiting on [`Self::process`] and driving the reactor until [`Self::io_done`]
824    /// returns true.
825    pub fn handle_reactor_event(
826        &mut self,
827        reactor: &mut Reactor,
828        event: &crate::fd::Event,
829    ) -> Result<(), CoreError> {
830        if self.drain.stdout_matches(event.token) {
831            if event.readable || event.hangup {
832                self.drain.handle_stdout_ready(reactor)?;
833            } else if event.error {
834                self.drain.drop_stdout(reactor)?;
835            }
836        } else if self.drain.stderr_matches(event.token) {
837            if event.readable || event.hangup {
838                self.drain.handle_stderr_ready(reactor)?;
839            } else if event.error {
840                self.drain.drop_stderr(reactor)?;
841            }
842        } else if self.drain.stdin_matches(event.token) {
843            if event.writable {
844                self.drain.handle_stdin_writable(reactor)?;
845            } else if event.error || event.hangup {
846                self.drain.drop_stdin(reactor)?;
847            }
848        }
849        Ok(())
850    }
851
852    /// Return whether all managed stdio pipes have been drained or closed.
853    pub fn io_done(&self) -> bool {
854        self.drain.is_done()
855    }
856
857    /// Consume the running process handle and return captured stdout/stderr buffers.
858    pub fn into_output_parts(self) -> (Vec<u8>, Vec<u8>) {
859        self.drain.into_parts()
860    }
861}
862
863impl ManagedProcess {
864    /// Return the child PID.
865    pub fn pid(&self) -> pid_t {
866        self.running
867            .as_ref()
868            .expect("managed process already completed")
869            .process
870            .pid()
871    }
872
873    /// Register active child I/O descriptors with the caller's reactor.
874    pub fn register_with_reactor(&mut self, reactor: &mut Reactor) -> Result<(), CoreError> {
875        self.running
876            .as_mut()
877            .ok_or_else(|| CoreError::sys(libc::EINVAL, "managed process completed"))?
878            .register_with_reactor(reactor)
879    }
880
881    /// Route one reactor event to the child's I/O drain state.
882    pub fn handle_reactor_event(
883        &mut self,
884        reactor: &mut Reactor,
885        event: &crate::fd::Event,
886    ) -> Result<(), CoreError> {
887        self.running
888            .as_mut()
889            .ok_or_else(|| CoreError::sys(libc::EINVAL, "managed process completed"))?
890            .handle_reactor_event(reactor, event)
891    }
892
893    /// Request cancellation using the daemon-owned policy from
894    /// [`SpawnOptionsBuilder::cancel`]. Repeated requests are idempotent.
895    pub fn request_cancel(&mut self) {
896        self.cancel_at.get_or_insert_with(Instant::now);
897    }
898
899    /// Earliest time at which [`Self::poll_completion`] should run again.
900    ///
901    /// A bounded reap tick is returned while the child is live, and exact
902    /// timeout / TERM-to-KILL deadlines take precedence. `None` means the
903    /// completion was already consumed.
904    pub fn next_deadline(&self) -> Option<Instant> {
905        self.running.as_ref()?;
906        let now = Instant::now();
907        let mut next = now + Duration::from_millis(100);
908        if !self.timed_out
909            && let Some(timeout_at) = self.timeout_at
910            && timeout_at < next
911        {
912            next = timeout_at;
913        }
914        if self.kill_state == KillState::TermSent
915            && let Some(cancel_at) = self.cancel_at
916        {
917            let kill_at = cancel_at + self.kill_grace;
918            if kill_at < next {
919                next = kill_at;
920            }
921        }
922        Some(next)
923    }
924
925    /// Advance timeout/cancellation, reap state, and completion.
926    ///
927    /// Returns `Ok(None)` while work remains, the normal [`Output`] once the
928    /// child is reaped and its pipes are drained, or `EOVERFLOW` when the
929    /// configured combined output limit was exceeded.
930    pub fn poll_completion(&mut self, reactor: &mut Reactor) -> Result<Option<Output>, CoreError> {
931        let now = Instant::now();
932        if !self.timed_out
933            && let Some(timeout_at) = self.timeout_at
934            && now >= timeout_at
935        {
936            self.timed_out = true;
937            self.cancel_at.get_or_insert(timeout_at);
938        }
939
940        self.advance_cancel(now)?;
941
942        let running = self
943            .running
944            .as_ref()
945            .ok_or_else(|| CoreError::sys(libc::EINVAL, "managed process completed"))?;
946        if self.status.is_none() {
947            self.status = running.process.wait_step()?;
948        }
949
950        let io_done = running.io_done();
951        if self.status.is_some() && (io_done || self.cancel_at.is_some()) {
952            return self.finish(reactor, !io_done).map(Some);
953        }
954        Ok(None)
955    }
956
957    fn advance_cancel(&mut self, now: Instant) -> Result<(), CoreError> {
958        let Some(cancel_at) = self.cancel_at else {
959            return Ok(());
960        };
961        let running = self
962            .running
963            .as_ref()
964            .ok_or_else(|| CoreError::sys(libc::EINVAL, "managed process completed"))?;
965        let process = &running.process;
966        let pid = process.pid();
967        let pgid = effective_pgid(pid, self.pgroup);
968        let target_is_group = self.pgroup.isolated || self.pgroup.leader.is_some();
969        match self.kill_state {
970            KillState::None => match self.cancel {
971                CancelPolicy::None => {}
972                CancelPolicy::Graceful => {
973                    let result = signal_process(process, target_is_group, pgid, libc::SIGTERM);
974                    self.kill_state = if result.is_ok() {
975                        KillState::TermSent
976                    } else {
977                        KillState::KillSent
978                    };
979                }
980                CancelPolicy::Kill => {
981                    let _ = signal_process(process, target_is_group, pgid, libc::SIGKILL);
982                    self.kill_state = KillState::KillSent;
983                }
984            },
985            KillState::TermSent if now >= cancel_at + self.kill_grace => {
986                let _ = signal_process(process, target_is_group, pgid, libc::SIGKILL);
987                self.kill_state = KillState::KillSent;
988            }
989            _ => {}
990        }
991        Ok(())
992    }
993
994    fn finish(&mut self, reactor: &mut Reactor, force_close: bool) -> Result<Output, CoreError> {
995        let mut running = self
996            .running
997            .take()
998            .ok_or_else(|| CoreError::sys(libc::EINVAL, "managed process completed"))?;
999        for slot in running.drain.take_all_slots() {
1000            if force_close {
1001                let _ = reactor.del(&slot.fd);
1002            } else {
1003                reactor.del(&slot.fd)?;
1004            }
1005        }
1006        let pid = running.process.pid();
1007        let (stdout, stderr, output_limit_exceeded, stdout_early_exited) =
1008            running.drain.into_parts_with_state();
1009        if output_limit_exceeded {
1010            return Err(CoreError::sys(libc::EOVERFLOW, "spawn output limit"));
1011        }
1012        Ok(Output {
1013            pid,
1014            status: self.status.take(),
1015            stdout,
1016            stderr,
1017            timed_out: self.timed_out,
1018            stdout_early_exited,
1019        })
1020    }
1021}
1022
1023fn effective_pgid(pid: pid_t, pgroup: ProcessGroup) -> pid_t {
1024    match pgroup.leader {
1025        Some(0) | None => pid,
1026        Some(leader) => leader,
1027    }
1028}
1029
1030fn signal_process(
1031    process: &Process,
1032    target_is_group: bool,
1033    pgid: pid_t,
1034    signal: i32,
1035) -> Result<(), CoreError> {
1036    if target_is_group {
1037        process.kill_group(pgid, signal)
1038    } else {
1039        process.kill(signal)
1040    }
1041}
1042
1043use crate::reactor::Reactor;
1044
1045/// Start spawning a process and return a monitor handle.
1046///
1047/// This initializes the pipes and starts the process, but does not block. Use
1048/// [`RunningProcess::register_with_reactor`],
1049/// [`RunningProcess::handle_reactor_event`], [`RunningProcess::io_done`], and
1050/// [`RunningProcess::into_output_parts`] to drive captured stdio without
1051/// exposing internal drain state.
1052///
1053/// ### Errors
1054/// - `EACCES`: Permission denied for the executable.
1055/// - `EINVAL`: Invalid spawn options (e.g. background capture without wait).
1056/// - `EMFILE`: Process limit on open file descriptors hit.
1057/// - `ENOENT`: The executable was not found.
1058/// - `ENOMEM`: Insufficient memory to spawn the process.
1059pub fn spawn_start(opts: SpawnOptions) -> Result<RunningProcess, CoreError> {
1060    if !opts.wait && (opts.stdin.is_some() || opts.capture_stdout || opts.capture_stderr) {
1061        return Err(CoreError::sys(
1062            libc::EINVAL,
1063            "background I/O capture not supported (wait must be true)",
1064        ));
1065    }
1066
1067    validate_backend(&opts)?;
1068
1069    let (pid, drain) = match opts.backend {
1070        SpawnBackend::PosixSpawn => spawn_posix_internal(opts)?,
1071        SpawnBackend::Fork => spawn_fork_internal(opts)?,
1072    };
1073
1074    Ok(RunningProcess {
1075        process: Process::new(pid),
1076        drain,
1077    })
1078}
1079
1080/// Start a process whose complete lifecycle is driven by a caller-owned
1081/// reactor.
1082pub fn spawn_managed(opts: SpawnOptions) -> Result<ManagedProcess, CoreError> {
1083    if !opts.wait {
1084        return Err(CoreError::sys(
1085            libc::EINVAL,
1086            "managed process requires wait=true",
1087        ));
1088    }
1089    let timeout_at = opts
1090        .timeout_ms
1091        .map(|ms| Instant::now() + Duration::from_millis(ms as u64));
1092    let kill_grace = Duration::from_millis(opts.kill_grace_ms as u64);
1093    let cancel = opts.cancel;
1094    let pgroup = opts.pgroup;
1095    let running = spawn_start(opts)?;
1096    Ok(ManagedProcess {
1097        running: Some(running),
1098        timeout_at,
1099        kill_grace,
1100        cancel,
1101        pgroup,
1102        cancel_at: None,
1103        kill_state: KillState::None,
1104        status: None,
1105        timed_out: false,
1106    })
1107}
1108
1109/// Spawn a process and block until completion or timeout.
1110///
1111/// This is the primary high-level interface for process execution. It handles
1112/// the full lifecycle, including I/O multiplexing and signal management.
1113///
1114/// ### Errors
1115/// Returns the same errors as [`spawn_start`], plus any I/O or reactor errors
1116/// encountered during the wait loop.
1117pub fn spawn(opts: SpawnOptions) -> Result<Output, CoreError> {
1118    let wait = opts.wait;
1119    let timeout_ms = opts.timeout_ms;
1120    let kill_grace_ms = opts.kill_grace_ms;
1121    let cancel = opts.cancel;
1122    let pgroup = opts.pgroup;
1123
1124    let mut reactor = Reactor::new()?;
1125    let running = spawn_start(opts)?;
1126
1127    let pid = running.process.pid();
1128    let mut drain = running.drain;
1129
1130    drain.register_with_reactor(&mut reactor)?;
1131
1132    if !wait {
1133        let (stdout, stderr) = drain.into_parts();
1134        return Ok(Output {
1135            pid,
1136            status: None,
1137            stdout,
1138            stderr,
1139            timed_out: false,
1140            stdout_early_exited: false,
1141        });
1142    }
1143
1144    wait_loop(
1145        pid,
1146        drain,
1147        reactor,
1148        timeout_ms,
1149        kill_grace_ms,
1150        cancel,
1151        pgroup,
1152    )
1153}
1154
1155fn spawn_posix_internal(opts: SpawnOptions) -> Result<(pid_t, SpawnDrain), CoreError> {
1156    let mut pipes = Pipes::new(
1157        opts.stdin.as_deref(),
1158        opts.capture_stdout,
1159        opts.capture_stderr,
1160    )?;
1161
1162    let exe_ptr = match &opts.ctx.argv {
1163        ExecArgv::Dynamic(v) => v[0].as_ptr(),
1164    };
1165
1166    let argv = opts.ctx.get_argv_ptrs();
1167    let envp = opts.ctx.get_envp_ptrs();
1168
1169    let actions = MaybeUninit::zeroed();
1170    let mut actions = unsafe { actions.assume_init() };
1171    if let Err(e) = posix_ret(
1172        unsafe { posix_spawn_file_actions_init(&mut actions) },
1173        "file_actions_init",
1174    ) {
1175        pipes.close_all();
1176        return Err(e);
1177    }
1178
1179    struct Actions(*mut libc::posix_spawn_file_actions_t);
1180    impl Drop for Actions {
1181        fn drop(&mut self) {
1182            unsafe {
1183                posix_spawn_file_actions_destroy(self.0);
1184            }
1185        }
1186    }
1187    let _guard = Actions(&mut actions);
1188
1189    if let (Some(r), Some(w)) = (&pipes.stdin_r, &pipes.stdin_w) {
1190        if let Err(e) = posix_ret(
1191            unsafe { posix_spawn_file_actions_adddup2(&mut actions, r.raw(), 0) },
1192            "dup2 stdin",
1193        ) {
1194            pipes.close_all();
1195            return Err(e);
1196        }
1197        if let Err(e) = posix_ret(
1198            unsafe { posix_spawn_file_actions_addclose(&mut actions, r.raw()) },
1199            "close stdin pipe",
1200        ) {
1201            pipes.close_all();
1202            return Err(e);
1203        }
1204        if let Err(e) = posix_ret(
1205            unsafe { posix_spawn_file_actions_addclose(&mut actions, w.raw()) },
1206            "close stdin write pipe",
1207        ) {
1208            pipes.close_all();
1209            return Err(e);
1210        }
1211    }
1212
1213    if let (Some(r), Some(w)) = (&pipes.stdout_r, &pipes.stdout_w) {
1214        if let Err(e) = posix_ret(
1215            unsafe { posix_spawn_file_actions_adddup2(&mut actions, w.raw(), 1) },
1216            "dup2 stdout",
1217        ) {
1218            pipes.close_all();
1219            return Err(e);
1220        }
1221        if let Err(e) = posix_ret(
1222            unsafe { posix_spawn_file_actions_addclose(&mut actions, w.raw()) },
1223            "close stdout pipe",
1224        ) {
1225            pipes.close_all();
1226            return Err(e);
1227        }
1228        if let Err(e) = posix_ret(
1229            unsafe { posix_spawn_file_actions_addclose(&mut actions, r.raw()) },
1230            "close stdout read pipe",
1231        ) {
1232            pipes.close_all();
1233            return Err(e);
1234        }
1235    }
1236
1237    if let (Some(r), Some(w)) = (&pipes.stderr_r, &pipes.stderr_w) {
1238        if let Err(e) = posix_ret(
1239            unsafe { posix_spawn_file_actions_adddup2(&mut actions, w.raw(), 2) },
1240            "dup2 stderr",
1241        ) {
1242            pipes.close_all();
1243            return Err(e);
1244        }
1245        if let Err(e) = posix_ret(
1246            unsafe { posix_spawn_file_actions_addclose(&mut actions, w.raw()) },
1247            "close stderr pipe",
1248        ) {
1249            pipes.close_all();
1250            return Err(e);
1251        }
1252        if let Err(e) = posix_ret(
1253            unsafe { posix_spawn_file_actions_addclose(&mut actions, r.raw()) },
1254            "close stderr read pipe",
1255        ) {
1256            pipes.close_all();
1257            return Err(e);
1258        }
1259    }
1260
1261    let attr = MaybeUninit::zeroed();
1262    let mut attr = unsafe { attr.assume_init() };
1263    if let Err(e) = posix_ret(unsafe { posix_spawnattr_init(&mut attr) }, "attr_init") {
1264        pipes.close_all();
1265        return Err(e);
1266    }
1267
1268    struct Attr(*mut libc::posix_spawnattr_t);
1269    impl Drop for Attr {
1270        fn drop(&mut self) {
1271            unsafe {
1272                posix_spawnattr_destroy(self.0);
1273            }
1274        }
1275    }
1276    let _attr = Attr(&mut attr);
1277
1278    let mut flags = 0;
1279
1280    if let Some(pg) = opts.pgroup.leader {
1281        flags |= POSIX_SPAWN_SETPGROUP;
1282        if let Err(e) = posix_ret(
1283            unsafe { posix_spawnattr_setpgroup(&mut attr, pg) },
1284            "setpgroup",
1285        ) {
1286            pipes.close_all();
1287            return Err(e);
1288        }
1289    }
1290
1291    flags |= POSIX_SPAWN_SETSIGMASK | POSIX_SPAWN_SETSIGDEF;
1292
1293    if let Err(e) = posix_ret(
1294        unsafe { posix_spawnattr_setflags(&mut attr, flags as _) },
1295        "setflags",
1296    ) {
1297        pipes.close_all();
1298        return Err(e);
1299    }
1300
1301    let empty_mask = SignalRuntime::empty_set();
1302    let def = SignalRuntime::set_with(&[libc::SIGPIPE])?;
1303
1304    if let Err(e) = posix_ret(
1305        unsafe { posix_spawnattr_setsigmask(&mut attr, &empty_mask) },
1306        "setsigmask",
1307    ) {
1308        pipes.close_all();
1309        return Err(e);
1310    }
1311    if let Err(e) = posix_ret(
1312        unsafe { posix_spawnattr_setsigdefault(&mut attr, &def) },
1313        "setsigdefault",
1314    ) {
1315        pipes.close_all();
1316        return Err(e);
1317    }
1318
1319    let mut pid: pid_t = 0;
1320
1321    let envp_ptr = envp.as_ref().map_or_else(
1322        || unsafe { environ as *const *mut c_char },
1323        |e: &Vec<*mut c_char>| e.as_ptr(),
1324    );
1325
1326    if let Err(e) = posix_ret(
1327        unsafe { posix_spawn(&mut pid, exe_ptr, &actions, &attr, argv.as_ptr(), envp_ptr) },
1328        "posix_spawn",
1329    ) {
1330        pipes.close_all();
1331        return Err(e);
1332    }
1333
1334    drop(pipes.stdin_r.take());
1335    drop(pipes.stdout_w.take());
1336    drop(pipes.stderr_w.take());
1337
1338    let drain = crate::io::DrainState::new(
1339        pipes.stdin_w.take().filter(|_| opts.stdin.is_some()),
1340        opts.stdin,
1341        pipes.stdout_r.take(),
1342        pipes.stderr_r.take(),
1343        opts.max_output,
1344        opts.early_exit,
1345    )?;
1346
1347    Ok((pid, drain))
1348}
1349
1350fn collect_required_pipe_fds(pipes: &Pipes) -> Vec<RawFd> {
1351    let mut fds = Vec::new();
1352    if let Some(fd) = &pipes.stdin_r {
1353        fds.push(fd.raw());
1354    }
1355    if let Some(fd) = &pipes.stdin_w {
1356        fds.push(fd.raw());
1357    }
1358    if let Some(fd) = &pipes.stdout_r {
1359        fds.push(fd.raw());
1360    }
1361    if let Some(fd) = &pipes.stdout_w {
1362        fds.push(fd.raw());
1363    }
1364    if let Some(fd) = &pipes.stderr_r {
1365        fds.push(fd.raw());
1366    }
1367    if let Some(fd) = &pipes.stderr_w {
1368        fds.push(fd.raw());
1369    }
1370    fds
1371}
1372
1373fn collect_open_fds_for_child_policy(policy: &SpawnFdPolicy) -> Result<Vec<RawFd>, CoreError> {
1374    match policy {
1375        SpawnFdPolicy::CloexecOnly => Ok(Vec::new()),
1376        SpawnFdPolicy::CloseFrom3 | SpawnFdPolicy::Allowlist(_) => {
1377            let dir_fd = unsafe {
1378                libc::open(
1379                    c"/proc/self/fd".as_ptr(),
1380                    libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC,
1381                )
1382            };
1383            if dir_fd < 0 {
1384                return Err(CoreError::sys(errno(), "open /proc/self/fd"));
1385            }
1386
1387            let dir = unsafe { libc::fdopendir(dir_fd) };
1388            if dir.is_null() {
1389                let code = errno();
1390                unsafe {
1391                    libc::close(dir_fd);
1392                }
1393                return Err(CoreError::sys(code, "fdopendir /proc/self/fd"));
1394            }
1395
1396            let mut open_fds = Vec::new();
1397            loop {
1398                let entry = unsafe { libc::readdir(dir) };
1399                if entry.is_null() {
1400                    break;
1401                }
1402                let name = unsafe { std::ffi::CStr::from_ptr((*entry).d_name.as_ptr()) };
1403                if let Ok(s) = name.to_str()
1404                    && let Ok(fd) = s.parse::<RawFd>()
1405                    && fd != dir_fd
1406                {
1407                    open_fds.push(fd);
1408                }
1409            }
1410            unsafe {
1411                libc::closedir(dir);
1412            }
1413            Ok(open_fds)
1414        }
1415    }
1416}
1417
1418fn close_child_fds_for_policy(policy: &SpawnFdPolicy, required_fds: &[RawFd], open_fds: &[RawFd]) {
1419    match policy {
1420        SpawnFdPolicy::CloexecOnly => {}
1421        SpawnFdPolicy::CloseFrom3 | SpawnFdPolicy::Allowlist(_) => {
1422            for &fd in open_fds {
1423                if fd > 2
1424                    && !required_fds.contains(&fd)
1425                    && !matches!(policy, SpawnFdPolicy::Allowlist(allowlist) if allowlist.contains(&fd))
1426                {
1427                    unsafe {
1428                        libc::close(fd);
1429                    }
1430                }
1431            }
1432        }
1433    }
1434}
1435
1436fn spawn_fork_internal(opts: SpawnOptions) -> Result<(pid_t, SpawnDrain), CoreError> {
1437    let mut pipes = Pipes::new(
1438        opts.stdin.as_deref(),
1439        opts.capture_stdout,
1440        opts.capture_stderr,
1441    )?;
1442
1443    let exe_ptr = match &opts.ctx.argv {
1444        ExecArgv::Dynamic(v) => v[0].as_ptr(),
1445    };
1446
1447    let argv = opts.ctx.get_argv_ptrs();
1448    let envp = opts.ctx.get_envp_ptrs();
1449    let cwd_cstr = &opts.ctx.cwd;
1450    let (child_error_r, child_error_w) = make_cloexec_pipe()?;
1451    let mut required_fds = collect_required_pipe_fds(&pipes);
1452    required_fds.push(child_error_w);
1453    let open_fds = collect_open_fds_for_child_policy(&opts.fd_policy)?;
1454
1455    let pid = unsafe { libc::fork() };
1456
1457    if pid < 0 {
1458        unsafe {
1459            libc::close(child_error_r);
1460            libc::close(child_error_w);
1461        }
1462        pipes.close_all();
1463        syscall_ret(-1, "fork")?;
1464    }
1465
1466    if pid == 0 {
1467        // Child
1468        unsafe {
1469            libc::close(child_error_r);
1470        }
1471
1472        // dup stdin
1473        if let (Some(r), Some(_)) = (&pipes.stdin_r, &pipes.stdin_w) {
1474            unsafe {
1475                if libc::dup2(r.raw(), 0) < 0 {
1476                    report_child_setup_error(child_error_w, ChildSetupOp::DupStdin, errno());
1477                }
1478            }
1479        }
1480
1481        // dup stdout
1482        if let (Some(_), Some(w)) = (&pipes.stdout_r, &pipes.stdout_w) {
1483            unsafe {
1484                if libc::dup2(w.raw(), 1) < 0 {
1485                    report_child_setup_error(child_error_w, ChildSetupOp::DupStdout, errno());
1486                }
1487            }
1488        }
1489
1490        // dup stderr
1491        if let (Some(_), Some(w)) = (&pipes.stderr_r, &pipes.stderr_w) {
1492            unsafe {
1493                if libc::dup2(w.raw(), 2) < 0 {
1494                    report_child_setup_error(child_error_w, ChildSetupOp::DupStderr, errno());
1495                }
1496            }
1497        }
1498
1499        // SAFETY: Close all pipe FDs in child before exec, except the ones duped to 0,1,2.
1500        pipes.close_all();
1501
1502        close_child_fds_for_policy(&opts.fd_policy, &required_fds, &open_fds);
1503
1504        // setsid
1505        if opts.pgroup.isolated {
1506            // SAFETY: safe to call setsid in child.
1507            unsafe {
1508                if libc::setsid() < 0 {
1509                    report_child_setup_error(child_error_w, ChildSetupOp::Setsid, errno());
1510                }
1511            }
1512        }
1513
1514        // chdir
1515        if let Some(cwd) = cwd_cstr {
1516            // SAFETY: cwd is a valid null-terminated CString.
1517            unsafe {
1518                if libc::chdir(cwd.as_ptr()) != 0 {
1519                    report_child_setup_error(child_error_w, ChildSetupOp::Chdir, errno());
1520                }
1521            }
1522        }
1523
1524        // setpgid
1525        if let Some(pg) = opts.pgroup.leader {
1526            // SAFETY: valid pgroup.
1527            unsafe {
1528                if libc::setpgid(0, pg) < 0 {
1529                    report_child_setup_error(child_error_w, ChildSetupOp::Setpgid, errno());
1530                }
1531            }
1532        }
1533
1534        let envp_ptr = envp.as_ref().map_or_else(
1535            || unsafe { environ as *const *mut c_char },
1536            |e: &Vec<*mut c_char>| e.as_ptr(),
1537        );
1538
1539        // unblock signals and reset SIGPIPE
1540        // SAFETY: valid signal mask array manipulation
1541        if let Err(err) = SignalRuntime::unblock_all() {
1542            unsafe {
1543                report_child_setup_error(
1544                    child_error_w,
1545                    ChildSetupOp::SignalMask,
1546                    err.raw_os_error().unwrap_or(libc::EIO),
1547                );
1548            }
1549        }
1550        if let Err(err) = SignalRuntime::reset_default(libc::SIGPIPE) {
1551            unsafe {
1552                report_child_setup_error(
1553                    child_error_w,
1554                    ChildSetupOp::SignalMask,
1555                    err.raw_os_error().unwrap_or(libc::EIO),
1556                );
1557            }
1558        }
1559
1560        // exec
1561        // SAFETY: exe_ptr is null-terminated. argv and envp_ptr are valid null-terminated arrays.
1562        unsafe {
1563            libc::execve(
1564                exe_ptr,
1565                argv.as_ptr() as *const *const _,
1566                envp_ptr as *const *const _,
1567            );
1568            report_child_setup_error(child_error_w, ChildSetupOp::Execve, errno());
1569        }
1570    }
1571
1572    // Parent
1573    unsafe {
1574        libc::close(child_error_w);
1575    }
1576    match read_child_setup_error(child_error_r) {
1577        Ok(Some(err)) => {
1578            unsafe {
1579                libc::close(child_error_r);
1580                let mut status = 0;
1581                let _ = libc::waitpid(pid, &mut status, 0);
1582            }
1583            pipes.close_all();
1584            return Err(err);
1585        }
1586        Ok(None) => {}
1587        Err(err) => {
1588            unsafe {
1589                libc::close(child_error_r);
1590            }
1591            pipes.close_all();
1592            return Err(err);
1593        }
1594    }
1595    unsafe {
1596        libc::close(child_error_r);
1597    }
1598    drop(pipes.stdin_r.take());
1599    drop(pipes.stdout_w.take());
1600    drop(pipes.stderr_w.take());
1601
1602    let drain = crate::io::DrainState::new(
1603        pipes.stdin_w.take().filter(|_| opts.stdin.is_some()),
1604        opts.stdin,
1605        pipes.stdout_r.take(),
1606        pipes.stderr_r.take(),
1607        opts.max_output,
1608        opts.early_exit,
1609    )?;
1610
1611    Ok((pid, drain))
1612}
1613
1614#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1615enum KillState {
1616    None,
1617    TermSent,
1618    KillSent,
1619}
1620
1621fn wait_loop(
1622    pid: pid_t,
1623    mut drain: crate::io::DrainState<fn(&[u8]) -> bool>,
1624    mut reactor: Reactor,
1625    timeout_ms: Option<u32>,
1626    kill_grace_ms: u32,
1627    cancel: CancelPolicy,
1628    pgroup: ProcessGroup,
1629) -> Result<Output, CoreError> {
1630    let process = Process::new(pid);
1631    // M8: the child's effective pgid is the configured leader when one is set
1632    // (Setpgid is applied after Setsid in the child), else its own pid. A
1633    // timeout must signal `-pgid`; `kill(-pid)` would target a different
1634    // group for a custom leader and the child would never die.
1635    let pgid = effective_pgid(pid, pgroup);
1636    let mut status_raw = process.wait_step()?;
1637    let mut state = KillState::None;
1638    let mut timed_out = false;
1639
1640    let start_time = std::time::Instant::now();
1641    let deadline = timeout_ms.map(|t| std::time::Duration::from_millis(t as u64));
1642
1643    loop {
1644        let mut poll_timeout = -1;
1645
1646        if let Some(dl) = deadline {
1647            let elapsed = start_time.elapsed();
1648            if elapsed >= dl {
1649                timed_out = true;
1650                let elapsed_over = (elapsed - dl).as_millis();
1651
1652                let target_is_group = pgroup.isolated || pgroup.leader.is_some();
1653
1654                match state {
1655                    KillState::None => {
1656                        if cancel == CancelPolicy::Graceful {
1657                            let r = if target_is_group {
1658                                process.kill_group(pgid, libc::SIGTERM)
1659                            } else {
1660                                process.kill(libc::SIGTERM)
1661                            };
1662                            if r.is_err() {
1663                                state = KillState::KillSent; // Process already gone
1664                            } else {
1665                                state = KillState::TermSent;
1666                            }
1667                        } else if cancel == CancelPolicy::Kill {
1668                            let _ = if target_is_group {
1669                                process.kill_group(pgid, libc::SIGKILL)
1670                            } else {
1671                                process.kill(libc::SIGKILL)
1672                            };
1673                            state = KillState::KillSent;
1674                        } else {
1675                            // CancelPolicy::None just times out without killing
1676                        }
1677                    }
1678                    KillState::TermSent if elapsed_over > kill_grace_ms as u128 => {
1679                        let _ = if target_is_group {
1680                            process.kill_group(pgid, libc::SIGKILL)
1681                        } else {
1682                            process.kill(libc::SIGKILL)
1683                        };
1684                        state = KillState::KillSent;
1685                    }
1686                    _ => {}
1687                }
1688                poll_timeout = 100; // Poll frequently while waiting for kill to take effect
1689            } else {
1690                let remaining = dl - elapsed;
1691                poll_timeout = remaining.as_millis().min(i32::MAX as u128) as i32;
1692            }
1693        }
1694
1695        if status_raw.is_none()
1696            && let Some(s) = process.wait_step()?
1697        {
1698            status_raw = Some(s);
1699        }
1700
1701        if drain.is_done() {
1702            let s = if status_raw.is_some() {
1703                status_raw.take()
1704            } else if deadline.is_none() {
1705                // C1: all pipes drained but the child is still alive, and no
1706                // deadline is set → block until it exits (intended semantics).
1707                Some(process.wait_blocking()?)
1708            } else {
1709                // C1: pipes drained with a deadline set → never block here; fall
1710                // through to the bounded `reactor.wait` below so the deadline
1711                // logic at the top of the loop kills and reaps. A later
1712                // `wait_step` reaps the child and we return from this branch.
1713                None
1714            };
1715
1716            if let Some(s) = s {
1717                for slot in drain.take_all_slots() {
1718                    reactor.del(&slot.fd)?;
1719                }
1720                let (stdout, stderr, output_limit_exceeded, stdout_early_exited) =
1721                    drain.into_parts_with_state();
1722                if output_limit_exceeded {
1723                    return Err(CoreError::sys(libc::EOVERFLOW, "spawn output limit"));
1724                }
1725                return Ok(Output {
1726                    pid,
1727                    status: Some(s),
1728                    stdout,
1729                    stderr,
1730                    timed_out,
1731                    stdout_early_exited,
1732                });
1733            }
1734        }
1735
1736        // N4: the deadline has elapsed and the child is reaped, but a wedged
1737        // pipe (a descendant inheriting the write end) keeps the drain from
1738        // closing. The absolute deadline is authoritative — return the partial
1739        // output instead of spinning forever.
1740        if timed_out && status_raw.is_some() {
1741            for slot in drain.take_all_slots() {
1742                let _ = reactor.del(&slot.fd);
1743            }
1744            let (stdout, stderr, _output_limit_exceeded, stdout_early_exited) =
1745                drain.into_parts_with_state();
1746            return Ok(Output {
1747                pid,
1748                status: status_raw,
1749                stdout,
1750                stderr,
1751                timed_out: true,
1752                stdout_early_exited,
1753            });
1754        }
1755
1756        let timeout = poll_timeout;
1757
1758        let mut events = Vec::new();
1759        let nevents = reactor.wait(&mut events, 64, timeout)?;
1760
1761        for ev in events.iter().take(nevents) {
1762            if drain.stdout_matches(ev.token) {
1763                if ev.readable || ev.hangup {
1764                    drain.handle_stdout_ready(&mut reactor)?;
1765                } else if ev.error {
1766                    drain.drop_stdout(&mut reactor)?;
1767                }
1768            } else if drain.stderr_matches(ev.token) {
1769                if ev.readable || ev.hangup {
1770                    drain.handle_stderr_ready(&mut reactor)?;
1771                } else if ev.error {
1772                    drain.drop_stderr(&mut reactor)?;
1773                }
1774            } else if drain.stdin_matches(ev.token) {
1775                if ev.writable {
1776                    drain.handle_stdin_writable(&mut reactor)?;
1777                } else if ev.error || ev.hangup {
1778                    drain.drop_stdin(&mut reactor)?;
1779                }
1780            }
1781        }
1782    }
1783}