Skip to main content

aft_base/
posix_spawn.rs

1//! Session-isolated pipe children without a fork of the daemon.
2//!
3//! File actions retain only stdio and the two wrapper marker descriptors. All
4//! preparation, including PATH lookup and privacy attributes, happens in the parent.
5use std::collections::BTreeMap;
6use std::ffi::{CStr, CString, OsStr, OsString};
7use std::fs::File;
8use std::io;
9use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd};
10use std::os::unix::ffi::OsStrExt;
11use std::path::Path;
12use std::process::{Command, ExitStatus};
13use std::sync::atomic::{AtomicU64, Ordering};
14use std::sync::OnceLock;
15
16#[derive(Debug)]
17enum Handle {
18    Std(std::process::Child),
19    Native {
20        pid: libc::pid_t,
21        status: Option<ExitStatus>,
22    },
23}
24
25/// Like std's Child, dropping this handle does not kill or reap a running child.
26#[derive(Debug)]
27pub struct Child {
28    handle: Handle,
29    pub stdin: Option<File>,
30    reaped: Option<ExitStatus>,
31    // The kernel may reuse the PID as soon as wait4 returns; keep the identity
32    // that was declared, rather than looking up a possibly newer child at reap.
33    agent_root: Option<subc_client_rs::AgentCommandRoot>,
34}
35impl From<std::process::Child> for Child {
36    fn from(mut child: std::process::Child) -> Self {
37        let stdin = child
38            .stdin
39            .take()
40            .map(|pipe| File::from(OwnedFd::from(pipe)));
41        Self {
42            handle: Handle::Std(child),
43            stdin,
44            reaped: None,
45            agent_root: None,
46        }
47    }
48}
49impl Child {
50    pub fn declare_agent(&mut self) {
51        self.agent_root = crate::agent_commands::started(self.id());
52    }
53    #[cfg(any(test, feature = "test-support"))]
54    pub fn kill(&mut self) -> io::Result<()> {
55        if self.reaped.is_some() {
56            return Err(io::Error::new(
57                io::ErrorKind::InvalidInput,
58                "child already reaped",
59            ));
60        }
61        match &mut self.handle {
62            Handle::Std(child) => child.kill(),
63            Handle::Native {
64                status: Some(_), ..
65            } => Err(io::Error::new(
66                io::ErrorKind::InvalidInput,
67                "child already reaped",
68            )),
69            Handle::Native { pid, .. } => {
70                if unsafe { libc::kill(*pid, libc::SIGKILL) } == 0 {
71                    Ok(())
72                } else {
73                    Err(io::Error::last_os_error())
74                }
75            }
76        }
77    }
78    pub fn id(&self) -> u32 {
79        match &self.handle {
80            Handle::Std(child) => child.id(),
81            Handle::Native { pid, .. } => *pid as u32,
82        }
83    }
84    pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
85        self.wait_inner(libc::WNOHANG)
86    }
87    pub fn wait(&mut self) -> io::Result<ExitStatus> {
88        drop(self.stdin.take());
89        self.wait_inner(0)?
90            .ok_or_else(|| io::Error::other("waitpid returned no status"))
91    }
92    fn wait_inner(&mut self, flags: libc::c_int) -> io::Result<Option<ExitStatus>> {
93        if self.reaped.is_none() {
94            self.reaped = crate::agent_commands::wait4(self.id(), flags, self.agent_root)?;
95            if let Handle::Native { status, .. } = &mut self.handle {
96                *status = self.reaped;
97            }
98        }
99        Ok(self.reaped)
100    }
101}
102
103pub struct PipeIo<'a> {
104    pub gated_stdin: bool,
105    pub stdout: &'a File,
106    pub stderr: &'a File,
107    pub exit: RawFd,
108    pub failure: RawFd,
109}
110
111type AddChdir =
112    unsafe extern "C" fn(*mut libc::posix_spawn_file_actions_t, *const libc::c_char) -> libc::c_int;
113#[cfg(not(target_os = "macos"))]
114type CloseFrom =
115    unsafe extern "C" fn(*mut libc::posix_spawn_file_actions_t, libc::c_int) -> libc::c_int;
116#[derive(Clone, Copy)]
117struct Functions {
118    chdir: AddChdir,
119    #[cfg(not(target_os = "macos"))]
120    closefrom: CloseFrom,
121}
122type SpawnBackend = Result<Functions, String>;
123static BACKEND: OnceLock<SpawnBackend> = OnceLock::new();
124static FALLBACK_SPAWNS: AtomicU64 = AtomicU64::new(0);
125
126// Resolve optional libc extensions at runtime so release binaries retain their
127// old glibc baseline instead of acquiring GLIBC_2.29/GLIBC_2.34 symbol versions.
128fn symbol(name: &CStr) -> *mut libc::c_void {
129    unsafe { libc::dlsym(libc::RTLD_DEFAULT, name.as_ptr()) }
130}
131fn discover() -> SpawnBackend {
132    if !cfg!(any(
133        target_os = "macos",
134        all(target_os = "linux", target_env = "gnu")
135    )) {
136        return Err("unsupported Unix libc".into());
137    }
138    #[cfg(target_os = "macos")]
139    let chdir = {
140        let modern = symbol(c"posix_spawn_file_actions_addchdir");
141        if modern.is_null() {
142            symbol(c"posix_spawn_file_actions_addchdir_np")
143        } else {
144            modern
145        }
146    };
147    #[cfg(not(target_os = "macos"))]
148    let chdir = symbol(c"posix_spawn_file_actions_addchdir_np");
149    if chdir.is_null() {
150        return Err("posix_spawn_file_actions_addchdir_np".into());
151    }
152    #[cfg(not(target_os = "macos"))]
153    let closefrom = symbol(c"posix_spawn_file_actions_addclosefrom_np");
154    #[cfg(not(target_os = "macos"))]
155    if closefrom.is_null() {
156        return Err("posix_spawn_file_actions_addclosefrom_np".into());
157    }
158    let functions = Functions {
159        chdir: unsafe { std::mem::transmute::<*mut libc::c_void, AddChdir>(chdir) },
160        #[cfg(not(target_os = "macos"))]
161        closefrom: unsafe { std::mem::transmute::<*mut libc::c_void, CloseFrom>(closefrom) },
162    };
163    // Older libc may export the file actions yet reject SETSID. Probe before
164    // accepting work, not by retrying a user's command after an ambiguous error.
165    let null = File::options()
166        .read(true)
167        .write(true)
168        .open("/dev/null")
169        .map_err(|error| format!("capability probe open /dev/null: {error}"))?;
170    let mut command = Command::new("/usr/bin/true");
171    command.env_clear().current_dir("/");
172    let mut child = spawn_native(
173        &command,
174        true,
175        false,
176        &PipeIo {
177            gated_stdin: false,
178            stdout: &null,
179            stderr: &null,
180            exit: null.as_raw_fd(),
181            failure: null.as_raw_fd(),
182        },
183        functions,
184    )
185    .map_err(|error| format!("POSIX_SPAWN_SETSID probe: {error}"))?;
186    if !child
187        .wait()
188        .map_err(|error| format!("POSIX_SPAWN_SETSID wait: {error}"))?
189        .success()
190    {
191        return Err("POSIX_SPAWN_SETSID probe exited unsuccessfully".into());
192    }
193    Ok(functions)
194}
195
196pub fn initialize() {
197    BACKEND.get_or_init(|| {
198        let backend = discover();
199        if let Err(reason) = &backend {
200            crate::slog_warn!("bash_spawn=fork_fallback missing_capability={reason}");
201        } else {
202            crate::slog_info!("bash_spawn=posix_spawn");
203        }
204        backend
205    });
206}
207
208#[cfg(any(test, feature = "test-support"))]
209thread_local! { pub static FORCE_FALLBACK: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; }
210fn missing_capability() -> Option<String> {
211    #[cfg(any(test, feature = "test-support"))]
212    if FORCE_FALLBACK.get() {
213        return Some("test-forced missing capability".into());
214    }
215    initialize();
216    BACKEND.get().unwrap().as_ref().err().cloned()
217}
218pub fn health() -> serde_json::Value {
219    let missing = missing_capability();
220    serde_json::json!({
221        "backend": if missing.is_some() { "fork_fallback" } else { "posix_spawn" },
222        "missing_capability": missing,
223        "fallback_spawns": FALLBACK_SPAWNS.load(Ordering::Relaxed),
224        "pty_backend": "fork",
225    })
226}
227
228/// None means the caller must use its existing pre_exec composition unchanged.
229pub fn try_spawn(
230    command: &Command,
231    cleared: bool,
232    disclaim: bool,
233    io: &PipeIo<'_>,
234) -> Option<io::Result<Child>> {
235    if missing_capability().is_some() {
236        FALLBACK_SPAWNS.fetch_add(1, Ordering::Relaxed);
237        return None;
238    }
239    Some(spawn_native(
240        command,
241        cleared,
242        disclaim,
243        io,
244        *BACKEND.get().unwrap().as_ref().unwrap(),
245    ))
246}
247
248#[cfg(any(test, feature = "test-support"))]
249#[derive(Clone, Copy)]
250enum NativeTestPlatform {
251    MacOs,
252    LinuxGnu,
253    Other,
254}
255
256#[cfg(any(test, feature = "test-support"))]
257#[derive(Debug, PartialEq, Eq)]
258enum NativeTestDecision {
259    Run,
260    Skip(String),
261    Fail(String),
262}
263
264#[cfg(any(test, feature = "test-support"))]
265fn native_test_decision(
266    platform: NativeTestPlatform,
267    glibc_version: Option<(u32, u32)>,
268    missing: Option<&str>,
269) -> NativeTestDecision {
270    match platform {
271        NativeTestPlatform::MacOs => match missing {
272            Some(reason) => NativeTestDecision::Fail(format!(
273                "macOS requires the native POSIX spawn backend, but it is unavailable: {reason}"
274            )),
275            None => NativeTestDecision::Run,
276        },
277        NativeTestPlatform::LinuxGnu => {
278            let Some(reason) = missing else {
279                return NativeTestDecision::Run;
280            };
281            let Some((capability, minimum)) = native_capability_minimum(reason) else {
282                return NativeTestDecision::Fail(format!(
283                    "glibc native POSIX spawn capability check failed unexpectedly: {reason}"
284                ));
285            };
286            let Some(version) = glibc_version else {
287                return NativeTestDecision::Fail(format!(
288                    "could not determine glibc version while checking {capability}: {reason}"
289                ));
290            };
291            if version < minimum {
292                NativeTestDecision::Skip(format!(
293                    "glibc {}.{} predates {capability} (requires {}.{}): {reason}",
294                    version.0, version.1, minimum.0, minimum.1
295                ))
296            } else {
297                NativeTestDecision::Fail(format!(
298                    "glibc {}.{} should provide {capability} (available since {}.{}), but the native backend is unavailable: {reason}",
299                    version.0, version.1, minimum.0, minimum.1
300                ))
301            }
302        }
303        NativeTestPlatform::Other => NativeTestDecision::Skip(
304            "native POSIX spawn tests require macOS or Linux with glibc".into(),
305        ),
306    }
307}
308
309#[cfg(any(test, feature = "test-support"))]
310fn native_capability_minimum(reason: &str) -> Option<(&'static str, (u32, u32))> {
311    if reason.contains("posix_spawn_file_actions_addclosefrom_np") {
312        Some(("posix_spawn_file_actions_addclosefrom_np", (2, 34)))
313    } else if reason.contains("posix_spawn_file_actions_addchdir_np") {
314        Some(("posix_spawn_file_actions_addchdir_np", (2, 29)))
315    } else if reason.contains("POSIX_SPAWN_SETSID") {
316        Some(("POSIX_SPAWN_SETSID", (2, 26)))
317    } else {
318        None
319    }
320}
321
322#[cfg(all(
323    any(test, feature = "test-support"),
324    target_os = "linux",
325    target_env = "gnu"
326))]
327fn test_glibc_version() -> Option<(u32, u32)> {
328    let version = unsafe { CStr::from_ptr(libc::gnu_get_libc_version()) }
329        .to_str()
330        .ok()?;
331    let mut components = version.split('.');
332    Some((
333        components.next()?.parse().ok()?,
334        components.next()?.parse().ok()?,
335    ))
336}
337
338#[cfg(all(
339    any(test, feature = "test-support"),
340    not(all(target_os = "linux", target_env = "gnu"))
341))]
342fn test_glibc_version() -> Option<(u32, u32)> {
343    None
344}
345
346/// Returns false only when native-only assertions do not apply on this libc.
347#[cfg(any(test, feature = "test-support"))]
348pub fn native_backend_for_tests() -> bool {
349    initialize();
350    let platform = if cfg!(target_os = "macos") {
351        NativeTestPlatform::MacOs
352    } else if cfg!(all(target_os = "linux", target_env = "gnu")) {
353        NativeTestPlatform::LinuxGnu
354    } else {
355        NativeTestPlatform::Other
356    };
357    let missing = BACKEND.get().unwrap().as_ref().err().map(String::as_str);
358    match native_test_decision(platform, test_glibc_version(), missing) {
359        NativeTestDecision::Run => true,
360        NativeTestDecision::Skip(reason) => {
361            eprintln!("skipping native-only spawn assertion: {reason}");
362            false
363        }
364        NativeTestDecision::Fail(reason) => panic!("{reason}"),
365    }
366}
367
368fn check(rc: libc::c_int) -> io::Result<()> {
369    if rc == 0 {
370        Ok(())
371    } else {
372        Err(io::Error::from_raw_os_error(rc))
373    }
374}
375fn cstring(value: &OsStr) -> io::Result<CString> {
376    CString::new(value.as_bytes()).map_err(|_| {
377        io::Error::new(
378            io::ErrorKind::InvalidInput,
379            "command or environment contains NUL",
380        )
381    })
382}
383
384fn default_search_path() -> io::Result<OsString> {
385    let length = unsafe { libc::confstr(libc::_CS_PATH, std::ptr::null_mut(), 0) };
386    if length == 0 {
387        return Err(io::Error::other(
388            "default executable search path unavailable",
389        ));
390    }
391    let mut buffer = vec![0u8; length];
392    let written =
393        unsafe { libc::confstr(libc::_CS_PATH, buffer.as_mut_ptr().cast(), buffer.len()) };
394    if written != length {
395        return Err(io::Error::other(
396            "default executable search path changed during lookup",
397        ));
398    }
399    let path = CStr::from_bytes_with_nul(&buffer)
400        .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
401    Ok(OsStr::from_bytes(path.to_bytes()).to_owned())
402}
403struct Attributes(libc::posix_spawnattr_t);
404impl Drop for Attributes {
405    fn drop(&mut self) {
406        unsafe {
407            libc::posix_spawnattr_destroy(&mut self.0);
408        }
409    }
410}
411struct Actions(libc::posix_spawn_file_actions_t);
412impl Drop for Actions {
413    fn drop(&mut self) {
414        unsafe {
415            libc::posix_spawn_file_actions_destroy(&mut self.0);
416        }
417    }
418}
419
420fn high_copy(fd: RawFd) -> io::Result<File> {
421    let copy = unsafe { libc::fcntl(fd, libc::F_DUPFD_CLOEXEC, 10) };
422    if copy < 0 {
423        Err(io::Error::last_os_error())
424    } else {
425        Ok(unsafe { File::from_raw_fd(copy) })
426    }
427}
428fn input(gated: bool) -> io::Result<(File, Option<File>)> {
429    if !gated {
430        return Ok((File::open("/dev/null")?, None));
431    }
432    // Use the same CLOEXEC pipe implementation as std::Command's piped stdin.
433    // The spawn allowlist also closes both originals in the child after dup2.
434    let (read, write) = std::io::pipe()?;
435    Ok((
436        File::from(OwnedFd::from(read)),
437        Some(File::from(OwnedFd::from(write))),
438    ))
439}
440
441fn spawn_native(
442    command: &Command,
443    cleared: bool,
444    disclaim: bool,
445    io: &PipeIo<'_>,
446    functions: Functions,
447) -> io::Result<Child> {
448    let mut environment = if cleared {
449        BTreeMap::new()
450    } else {
451        std::env::vars_os().collect::<BTreeMap<_, _>>()
452    };
453    for (key, value) in command.get_envs() {
454        if let Some(value) = value {
455            environment.insert(key.to_owned(), value.to_owned());
456        } else {
457            environment.remove(key);
458        }
459    }
460    let cwd = command
461        .get_current_dir()
462        .map(Path::to_owned)
463        .map(Ok)
464        .unwrap_or_else(std::env::current_dir)?;
465    let cwd = if cwd.is_absolute() {
466        cwd
467    } else {
468        std::env::current_dir()?.join(cwd)
469    };
470    let program = command.get_program();
471    // Resolve only after applying the complete child environment; posix_spawnp
472    // would instead search the daemon's PATH. Preserve the requested argv[0].
473    let path = if Path::new(program).is_absolute() {
474        Path::new(program).to_owned()
475    } else {
476        // execvp searches the system default only when PATH is absent. An
477        // explicitly empty PATH still searches cwd, without exporting a default.
478        let search_path = environment
479            .get(OsStr::new("PATH"))
480            .cloned()
481            .map(Ok)
482            .unwrap_or_else(default_search_path)?;
483        if search_path.is_empty() {
484            cwd.join(program)
485        } else {
486            which::which_in(program, Some(search_path), &cwd)
487                .map_err(|error| io::Error::new(io::ErrorKind::NotFound, error))?
488        }
489    };
490    let path = cstring(path.as_os_str())?;
491    let cwd = cstring(cwd.as_os_str())?;
492    let argv_storage = std::iter::once(program)
493        .chain(command.get_args())
494        .map(cstring)
495        .collect::<io::Result<Vec<_>>>()?;
496    let env_storage = environment
497        .into_iter()
498        .map(|(key, value)| {
499            let mut entry = OsString::from(key);
500            entry.push("=");
501            entry.push(value);
502            cstring(&entry)
503        })
504        .collect::<io::Result<Vec<_>>>()?;
505    let pointers = |values: &[CString]| {
506        values
507            .iter()
508            .map(|value| value.as_ptr().cast_mut())
509            .chain(std::iter::once(std::ptr::null_mut()))
510            .collect::<Vec<_>>()
511    };
512    let argv = pointers(&argv_storage);
513    let env = pointers(&env_storage);
514    unsafe {
515        let mut attr = std::mem::zeroed();
516        check(libc::posix_spawnattr_init(&mut attr))?;
517        let mut attr = Attributes(attr);
518        // Darwin's sys/spawn.h exposes SETSID even though libc does not name it.
519        #[cfg(target_os = "macos")]
520        const POSIX_SPAWN_SETSID: libc::c_int = 0x0400;
521        #[cfg(target_os = "macos")]
522        let flags =
523            POSIX_SPAWN_SETSID | libc::POSIX_SPAWN_CLOEXEC_DEFAULT | libc::POSIX_SPAWN_SETSIGDEF;
524        #[cfg(target_os = "linux")]
525        let flags = libc::POSIX_SPAWN_SETSID | libc::POSIX_SPAWN_SETSIGDEF;
526        #[cfg(not(any(target_os = "linux", target_os = "macos")))]
527        let flags = libc::POSIX_SPAWN_SETSIGDEF;
528        let flags = flags | libc::POSIX_SPAWN_SETSIGMASK;
529        check(libc::posix_spawnattr_setflags(&mut attr.0, flags as i16))?;
530        let mut defaults = std::mem::zeroed();
531        libc::sigemptyset(&mut defaults);
532        libc::sigaddset(&mut defaults, libc::SIGPIPE);
533        check(libc::posix_spawnattr_setsigdefault(&mut attr.0, &defaults))?;
534        // Match std::Command: signal-handling threads may block signals that
535        // must remain deliverable to children, so start with an empty mask.
536        let mut mask = std::mem::zeroed();
537        check(libc::sigemptyset(&mut mask))?;
538        check(libc::posix_spawnattr_setsigmask(&mut attr.0, &mask))?;
539        crate::privacy_spawn::apply_spawn_attribute(&mut attr.0, disclaim)?;
540        let mut actions = std::mem::zeroed();
541        check(libc::posix_spawn_file_actions_init(&mut actions))?;
542        let mut actions = Actions(actions);
543        let (stdin, parent_stdin) = input(io.gated_stdin)?;
544        // Copy every source above the targets before constructing actions: even
545        // when the daemon has closed stdio, no dup2 can overwrite another source.
546        let sources = [
547            stdin.as_raw_fd(),
548            io.stdout.as_raw_fd(),
549            io.stderr.as_raw_fd(),
550            io.exit,
551            io.failure,
552        ]
553        .into_iter()
554        .map(high_copy)
555        .collect::<io::Result<Vec<_>>>()?;
556        for (target, source) in sources.iter().enumerate() {
557            check(libc::posix_spawn_file_actions_adddup2(
558                &mut actions.0,
559                source.as_raw_fd(),
560                target as RawFd,
561            ))?;
562        }
563        check((functions.chdir)(&mut actions.0, cwd.as_ptr()))?;
564        #[cfg(not(target_os = "macos"))]
565        check((functions.closefrom)(&mut actions.0, 5))?;
566        let mut pid = 0;
567        check(libc::posix_spawn(
568            &mut pid,
569            path.as_ptr(),
570            &actions.0,
571            &attr.0,
572            argv.as_ptr(),
573            env.as_ptr(),
574        ))?;
575        Ok(Child {
576            handle: Handle::Native { pid, status: None },
577            stdin: parent_stdin,
578            reaped: None,
579            agent_root: None,
580        })
581    }
582}
583
584#[cfg(test)]
585mod tests {
586    use super::*;
587    use std::io::Write;
588
589    fn spawn(command: &Command, root: &Path, gated: bool) -> (Child, [File; 4]) {
590        assert!(
591            native_backend_for_tests(),
592            "native spawn helper called when native-only tests should be skipped"
593        );
594        let files =
595            ["out", "err", "exit", "failure"].map(|name| File::create(root.join(name)).unwrap());
596        let child = try_spawn(
597            command,
598            true,
599            false,
600            &PipeIo {
601                gated_stdin: gated,
602                stdout: &files[0],
603                stderr: &files[1],
604                exit: files[2].as_raw_fd(),
605                failure: files[3].as_raw_fd(),
606            },
607        )
608        .unwrap_or_else(|| panic!("modern libc required for native tests: {}", health()))
609        .unwrap();
610        (child, files)
611    }
612
613    #[test]
614    fn native_test_policy_skips_only_versioned_glibc_capability_gaps() {
615        assert!(matches!(
616            native_test_decision(
617                NativeTestPlatform::LinuxGnu,
618                Some((2, 33)),
619                Some("posix_spawn_file_actions_addclosefrom_np")
620            ),
621            NativeTestDecision::Skip(_)
622        ));
623        assert!(matches!(
624            native_test_decision(
625                NativeTestPlatform::LinuxGnu,
626                Some((2, 34)),
627                Some("posix_spawn_file_actions_addclosefrom_np")
628            ),
629            NativeTestDecision::Fail(_)
630        ));
631        assert!(matches!(
632            native_test_decision(NativeTestPlatform::MacOs, None, None),
633            NativeTestDecision::Run
634        ));
635        assert!(matches!(
636            native_test_decision(
637                NativeTestPlatform::MacOs,
638                None,
639                Some("posix_spawn_file_actions_addchdir_np")
640            ),
641            NativeTestDecision::Fail(_)
642        ));
643    }
644
645    #[test]
646    fn native_spawn_cwd_env_arg0_markers_and_stdin() {
647        if !native_backend_for_tests() {
648            return;
649        }
650        let dir = tempfile::tempdir().unwrap();
651        let script = dir.path().join("shell");
652        std::os::unix::fs::symlink("/bin/sh", &script).unwrap();
653        let mut command = Command::new("shell");
654        command.current_dir(dir.path()).env_clear().env("PATH", dir.path()).env("TOKEN", "child-value")
655            .args(["-c", "read release; printf '%s:%s:%s:%s' \"$0\" \"$TOKEN\" \"$PWD\" \"$release\"; printf exit >&3; printf fail >&4", "requested-zero"]);
656        let (mut child, _files) = spawn(&command, dir.path(), true);
657        let pid = child.id() as i32;
658        assert_eq!(unsafe { libc::getsid(pid) }, pid);
659        assert_eq!(unsafe { libc::getpgid(pid) }, pid);
660        assert!(child.try_wait().unwrap().is_none());
661        child
662            .stdin
663            .take()
664            .unwrap()
665            .write_all(b"released\n")
666            .unwrap();
667        assert!(child.wait().unwrap().success());
668        assert_eq!(child.try_wait().unwrap().unwrap().code(), Some(0));
669        assert!(
670            child.kill().is_err(),
671            "never signal a pid once it has been reaped"
672        );
673        // The child's shell derives $PWD from the physical working folder, so
674        // compare against the canonical path (/private/var on macOS, not /var).
675        assert_eq!(
676            std::fs::read_to_string(dir.path().join("out")).unwrap(),
677            format!(
678                "requested-zero:child-value:{}:released",
679                dir.path().canonicalize().unwrap().display()
680            )
681        );
682        assert_eq!(std::fs::read(dir.path().join("exit")).unwrap(), b"exit");
683        assert_eq!(std::fs::read(dir.path().join("failure")).unwrap(), b"fail");
684    }
685
686    #[test]
687    fn native_spawn_signal_mask_probe_child() {
688        if std::env::var_os("AFT_NATIVE_SIGNAL_MASK_PROBE").is_none() {
689            return;
690        }
691        let mut mask = unsafe { std::mem::zeroed::<libc::sigset_t>() };
692        assert_eq!(
693            unsafe { libc::pthread_sigmask(libc::SIG_SETMASK, std::ptr::null(), &mut mask) },
694            0
695        );
696        let blocked = (1..=64)
697            .filter(|signal| unsafe { libc::sigismember(&mask, *signal) } == 1)
698            .collect::<Vec<_>>();
699        println!("child blocked signals: {blocked:?}");
700        assert!(
701            blocked.is_empty(),
702            "child inherited blocked signals: {blocked:?}"
703        );
704    }
705
706    #[test]
707    fn native_spawn_clears_spawning_thread_signal_mask() {
708        if !native_backend_for_tests() {
709            return;
710        }
711        struct RestoreMask(libc::sigset_t);
712        impl Drop for RestoreMask {
713            fn drop(&mut self) {
714                assert_eq!(
715                    unsafe {
716                        libc::pthread_sigmask(libc::SIG_SETMASK, &self.0, std::ptr::null_mut())
717                    },
718                    0
719                );
720            }
721        }
722        initialize();
723        assert_eq!(health()["backend"], "posix_spawn");
724        let dir = tempfile::tempdir().unwrap();
725        let mut command = Command::new(std::env::current_exe().unwrap());
726        command
727            .current_dir(dir.path())
728            .env_clear()
729            .env("AFT_NATIVE_SIGNAL_MASK_PROBE", "1")
730            .args([
731                "--exact",
732                "posix_spawn::tests::native_spawn_signal_mask_probe_child",
733                "--nocapture",
734            ]);
735        let (mut child, _files) = {
736            let mut blocked = unsafe { std::mem::zeroed::<libc::sigset_t>() };
737            let mut previous = unsafe { std::mem::zeroed::<libc::sigset_t>() };
738            unsafe {
739                assert_eq!(libc::sigemptyset(&mut blocked), 0);
740                assert_eq!(libc::sigaddset(&mut blocked, libc::SIGTERM), 0);
741                assert_eq!(libc::sigaddset(&mut blocked, libc::SIGINT), 0);
742                assert_eq!(
743                    libc::pthread_sigmask(libc::SIG_BLOCK, &blocked, &mut previous),
744                    0
745                );
746            }
747            let _restore = RestoreMask(previous);
748            let mut observed = unsafe { std::mem::zeroed::<libc::sigset_t>() };
749            assert_eq!(
750                unsafe {
751                    libc::pthread_sigmask(libc::SIG_SETMASK, std::ptr::null(), &mut observed)
752                },
753                0
754            );
755            assert_eq!(unsafe { libc::sigismember(&observed, libc::SIGTERM) }, 1);
756            assert_eq!(unsafe { libc::sigismember(&observed, libc::SIGINT) }, 1);
757            spawn(&command, dir.path(), false)
758        };
759        let status = child.wait().unwrap();
760        let output = std::fs::read_to_string(dir.path().join("out")).unwrap();
761        assert!(
762            status.success(),
763            "{} {}",
764            output,
765            std::fs::read_to_string(dir.path().join("err")).unwrap()
766        );
767        assert!(
768            output.contains("child blocked signals: []"),
769            "probe did not report an empty mask: {output}"
770        );
771    }
772
773    #[test]
774    fn native_spawn_absent_path_uses_default_search_but_empty_path_uses_cwd() {
775        if !native_backend_for_tests() {
776            return;
777        }
778        let dir = tempfile::tempdir().unwrap();
779        let shadow = dir.path().join("env");
780        crate::executable_cache::write_executable(&shadow, b"#!/bin/sh\nprintf cwd-shadow")
781            .unwrap();
782        for (path, expected) in [
783            (None, "NATIVE_TOKEN=default-search\n"),
784            (Some(""), "cwd-shadow"),
785        ] {
786            let mut command = Command::new("env");
787            command
788                .current_dir(dir.path())
789                .env_clear()
790                .env("NATIVE_TOKEN", "default-search");
791            if let Some(path) = path {
792                command.env("PATH", path);
793            }
794            let (mut child, _files) = spawn(&command, dir.path(), false);
795            assert!(child.wait().unwrap().success());
796            assert_eq!(
797                std::fs::read_to_string(dir.path().join("out")).unwrap(),
798                expected,
799                "PATH={path:?}"
800            );
801        }
802    }
803
804    #[test]
805    fn native_spawn_reports_exec_errors() {
806        if !native_backend_for_tests() {
807            return;
808        }
809        use std::os::unix::fs::PermissionsExt;
810        let dir = tempfile::tempdir().unwrap();
811        let not_executable = dir.path().join("not-executable");
812        std::fs::write(&not_executable, b"#!/bin/sh\n").unwrap();
813        std::fs::set_permissions(&not_executable, std::fs::Permissions::from_mode(0o644)).unwrap();
814        for (program, errno) in [
815            (dir.path().join("absent"), libc::ENOENT),
816            (not_executable, libc::EACCES),
817        ] {
818            let mut command = Command::new(program);
819            command.current_dir(dir.path());
820            let file = File::create(dir.path().join("out")).unwrap();
821            let error = try_spawn(
822                &command,
823                true,
824                false,
825                &PipeIo {
826                    gated_stdin: false,
827                    stdout: &file,
828                    stderr: &file,
829                    exit: file.as_raw_fd(),
830                    failure: file.as_raw_fd(),
831                },
832            )
833            .unwrap()
834            .unwrap_err();
835            assert_eq!(error.raw_os_error(), Some(errno));
836        }
837    }
838
839    #[test]
840    fn native_spawn_fd_probe_child() {
841        let Some(fd) = std::env::var_os("AFT_NATIVE_FD_PROBE") else {
842            return;
843        };
844        let fd = fd.to_str().unwrap().parse::<i32>().unwrap();
845        assert_eq!(
846            unsafe { libc::fcntl(fd, libc::F_GETFD) },
847            -1,
848            "daemon fd leaked into child"
849        );
850        assert_eq!(io::Error::last_os_error().raw_os_error(), Some(libc::EBADF));
851        assert_ne!(
852            unsafe { libc::fcntl(3, libc::F_GETFD) },
853            -1,
854            "exit marker missing"
855        );
856        assert_ne!(
857            unsafe { libc::fcntl(4, libc::F_GETFD) },
858            -1,
859            "failure marker missing"
860        );
861    }
862
863    #[test]
864    fn native_spawn_closes_non_cloexec_daemon_fd() {
865        if !native_backend_for_tests() {
866            return;
867        }
868        let dir = tempfile::tempdir().unwrap();
869        let file = File::create(dir.path().join("secret")).unwrap();
870        let raw = unsafe { libc::fcntl(file.as_raw_fd(), libc::F_DUPFD, 200) };
871        assert!(raw >= 200);
872        let _held = unsafe { File::from_raw_fd(raw) };
873        assert_eq!(
874            unsafe { libc::fcntl(raw, libc::F_GETFD) } & libc::FD_CLOEXEC,
875            0
876        );
877        let mut command = Command::new(std::env::current_exe().unwrap());
878        command
879            .current_dir(dir.path())
880            .env_clear()
881            .env("AFT_NATIVE_FD_PROBE", raw.to_string())
882            .args([
883                "--exact",
884                "posix_spawn::tests::native_spawn_fd_probe_child",
885                "--nocapture",
886            ]);
887        let (mut child, _files) = spawn(&command, dir.path(), false);
888        assert!(
889            child.wait().unwrap().success(),
890            "{}",
891            std::fs::read_to_string(dir.path().join("out")).unwrap()
892        );
893    }
894}