| /* | |
| * Licensed to the Apache Software Foundation (ASF) under one | |
| * or more contributor license agreements. See the NOTICE file | |
| * distributed with this work for additional information | |
| * regarding copyright ownership. The ASF licenses this file | |
| * to you under the Apache License, Version 2.0 (the | |
| * "License"); you may not use this file except in compliance | |
| * with the License. You may obtain a copy of the License at | |
| * | |
| * http://www.apache.org/licenses/LICENSE-2.0 | |
| * | |
| * Unless required by applicable law or agreed to in writing, | |
| * software distributed under the License is distributed on an | |
| * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | |
| * KIND, either express or implied. See the License for the | |
| * specific language governing permissions and limitations | |
| * under the License. | |
| */ | |
| //! Darwin's atomic close-on-exec-default and direct `posix_spawn` pipe launch. | |
| use rustix::process::Pid; | |
| use std::{ | |
| collections::BTreeMap, | |
| ffi::{CString, OsStr, OsString}, | |
| io, | |
| os::{ | |
| fd::{AsRawFd, FromRawFd, OwnedFd, RawFd}, | |
| unix::ffi::OsStrExt, | |
| }, | |
| path::Path, | |
| ptr, | |
| }; | |
| unsafe extern "C" { | |
| fn posix_spawn_file_actions_addinherit_np( | |
| actions: *mut libc::posix_spawn_file_actions_t, | |
| fd: libc::c_int, | |
| ) -> libc::c_int; | |
| fn posix_spawn_file_actions_addchdir_np( | |
| actions: *mut libc::posix_spawn_file_actions_t, | |
| path: *const libc::c_char, | |
| ) -> libc::c_int; | |
| fn posix_spawn_file_actions_addfchdir_np( | |
| actions: *mut libc::posix_spawn_file_actions_t, | |
| filedes: libc::c_int, | |
| ) -> libc::c_int; | |
| } | |
| pub(crate) struct SpawnedPipe { | |
| pub(crate) pid: Pid, | |
| pub(crate) stdin: tokio::process::ChildStdin, | |
| pub(crate) stdout: tokio::process::ChildStdout, | |
| pub(crate) stderr: tokio::process::ChildStderr, | |
| } | |
| /// Spawn a piped child directly via Darwin's `posix_spawn` without `fork()`, | |
| /// avoiding kernel `vm_map` duplication when many V8 isolates are live. | |
| pub(crate) fn spawn_piped<A: AsRef<OsStr>>( | |
| executable: &Path, | |
| args: &[A], | |
| environment: &BTreeMap<OsString, OsString>, | |
| cwd: &Path, | |
| directory: Option<RawFd>, | |
| ) -> io::Result<SpawnedPipe> { | |
| let program = string(executable.as_os_str().as_bytes())?; | |
| let argv_strings = std::iter::once(Ok(program.clone())) | |
| .chain(args.iter().map(|arg| string(arg.as_ref().as_bytes()))) | |
| .collect::<io::Result<Vec<_>>>()?; | |
| let env_strings = environment | |
| .iter() | |
| .map(|(key, value)| { | |
| let mut entry = key.clone(); | |
| entry.push("="); | |
| entry.push(value); | |
| string(entry.as_bytes()) | |
| }) | |
| .collect::<io::Result<Vec<_>>>()?; | |
| let cwd_cstr = match directory { | |
| Some(_) => None, | |
| None => Some(string(cwd.as_os_str().as_bytes())?), | |
| }; | |
| let (stdin_read, stdin_write) = create_cloexec_pipe()?; | |
| let (stdout_read, stdout_write) = create_cloexec_pipe()?; | |
| let (stderr_read, stderr_write) = create_cloexec_pipe()?; | |
| // Keep child pipe ends >= 3 so adddup2(src, 0/1/2) never collides with target | |
| // stdio slots and always marks 0/1/2 inherited even under CLOEXEC_DEFAULT. | |
| let child_stdin = move_above_stdio(stdin_read)?; | |
| let child_stdout = move_above_stdio(stdout_write)?; | |
| let child_stderr = move_above_stdio(stderr_write)?; | |
| let attributes = Attributes::new_pipe()?; | |
| let actions = Actions::new_pipe( | |
| child_stdin.as_raw_fd(), | |
| child_stdout.as_raw_fd(), | |
| child_stderr.as_raw_fd(), | |
| directory, | |
| cwd_cstr.as_deref(), | |
| )?; | |
| let argv = pointers(&argv_strings); | |
| let envp = pointers(&env_strings); | |
| let mut raw_pid: libc::pid_t = 0; | |
| // SAFETY: all C strings, pointer arrays, actions, attributes, pipe FDs, and | |
| // any pinned directory FD remain live and immutable across posix_spawn. | |
| let error = unsafe { | |
| libc::posix_spawn( | |
| &mut raw_pid, | |
| program.as_ptr(), | |
| &actions.0, | |
| &attributes.0, | |
| argv.as_ptr(), | |
| envp.as_ptr(), | |
| ) | |
| }; | |
| check(error)?; | |
| drop((child_stdin, child_stdout, child_stderr)); | |
| let pid = Pid::from_raw(raw_pid) | |
| .ok_or_else(|| io::Error::other("posix_spawn returned non-positive PID"))?; | |
| struct UnownedChild(Option<Pid>); | |
| impl Drop for UnownedChild { | |
| fn drop(&mut self) { | |
| if let Some(pid) = self.0.take() { | |
| let _ = rustix::process::kill_process_group(pid, rustix::process::Signal::KILL); | |
| crate::group::reap_orphan(pid, tokio::runtime::Handle::try_current().ok()); | |
| } | |
| } | |
| } | |
| let mut guard = UnownedChild(Some(pid)); | |
| let stdin = tokio::process::ChildStdin::from_std(std::process::ChildStdin::from(stdin_write))?; | |
| let stdout = | |
| tokio::process::ChildStdout::from_std(std::process::ChildStdout::from(stdout_read))?; | |
| let stderr = | |
| tokio::process::ChildStderr::from_std(std::process::ChildStderr::from(stderr_read))?; | |
| guard.0 = None; | |
| Ok(SpawnedPipe { | |
| pid, | |
| stdin, | |
| stdout, | |
| stderr, | |
| }) | |
| } | |
| fn create_cloexec_pipe() -> io::Result<(OwnedFd, OwnedFd)> { | |
| let mut fds = [0 as libc::c_int; 2]; | |
| // SAFETY: fds is a valid 2-element output buffer. | |
| if unsafe { libc::pipe(fds.as_mut_ptr()) } != 0 { | |
| return Err(io::Error::last_os_error()); | |
| } | |
| // SAFETY: pipe() just returned two fresh owned file descriptors. | |
| let read = unsafe { OwnedFd::from_raw_fd(fds[0]) }; | |
| let write = unsafe { OwnedFd::from_raw_fd(fds[1]) }; | |
| set_cloexec(&read)?; | |
| set_cloexec(&write)?; | |
| Ok((read, write)) | |
| } | |
| fn set_cloexec(fd: &OwnedFd) -> io::Result<()> { | |
| // SAFETY: fd is an owned open descriptor. | |
| if unsafe { libc::fcntl(fd.as_raw_fd(), libc::F_SETFD, libc::FD_CLOEXEC) } == -1 { | |
| return Err(io::Error::last_os_error()); | |
| } | |
| Ok(()) | |
| } | |
| fn move_above_stdio(fd: OwnedFd) -> io::Result<OwnedFd> { | |
| if fd.as_raw_fd() > 2 { | |
| return Ok(fd); | |
| } | |
| // SAFETY: F_DUPFD_CLOEXEC duplicates fd into the lowest slot >= 3 with CLOEXEC. | |
| let duped = unsafe { libc::fcntl(fd.as_raw_fd(), libc::F_DUPFD_CLOEXEC, 3) }; | |
| if duped == -1 { | |
| return Err(io::Error::last_os_error()); | |
| } | |
| // SAFETY: duped is a fresh owned file descriptor. | |
| Ok(unsafe { OwnedFd::from_raw_fd(duped) }) | |
| } | |
| pub(crate) fn install(command: &mut tokio::process::Command) -> io::Result<()> { | |
| let executable = command.as_std().get_program(); | |
| let program = string(executable.as_bytes())?; | |
| let args = std::iter::once(Ok(program.clone())) | |
| .chain( | |
| command | |
| .as_std() | |
| .get_args() | |
| .map(|arg| string(arg.as_bytes())), | |
| ) | |
| .collect::<io::Result<Vec<_>>>()?; | |
| // Prepared::unix always clears the environment and supplies captured values. | |
| let env = command | |
| .as_std() | |
| .get_envs() | |
| .filter_map(|(key, value)| value.map(|value| (key, value))) | |
| .map(|(key, value)| { | |
| let mut entry = key.to_os_string(); | |
| entry.push("="); | |
| entry.push(value); | |
| string(entry.as_bytes()) | |
| }) | |
| .collect::<io::Result<Vec<_>>>()?; | |
| let attributes = Attributes::new()?; | |
| let actions = Actions::new()?; | |
| let exec = Exec { | |
| program, | |
| argv: pointers(&args), | |
| envp: pointers(&env), | |
| _args: args, | |
| _env: env, | |
| attributes, | |
| actions, | |
| }; | |
| // SAFETY: every allocation and native action construction happens above in | |
| // the parent. This final callback only invokes Darwin's SETEXEC kernel path | |
| // with immutable, live C buffers. No FD snapshot, iteration, allocation or | |
| // closefrom runs after fork. Failed exec leaves Rust's error pipe intact; | |
| // successful exec atomically closes everything except the actual 0/1/2. | |
| unsafe { | |
| command.pre_exec(move || exec.replace()); | |
| } | |
| Ok(()) | |
| } | |
| fn string(bytes: &[u8]) -> io::Result<CString> { | |
| CString::new(bytes).map_err(|_| io::Error::from_raw_os_error(libc::EINVAL)) | |
| } | |
| fn pointers(strings: &[CString]) -> Vec<*mut libc::c_char> { | |
| strings | |
| .iter() | |
| .map(|value| value.as_ptr().cast_mut()) | |
| .chain(std::iter::once(ptr::null_mut())) | |
| .collect() | |
| } | |
| struct Exec { | |
| program: CString, | |
| argv: Vec<*mut libc::c_char>, | |
| envp: Vec<*mut libc::c_char>, | |
| _args: Vec<CString>, | |
| _env: Vec<CString>, | |
| attributes: Attributes, | |
| actions: Actions, | |
| } | |
| // SAFETY: pointers refer only to the immutable owned buffers/opaque native | |
| // actions in this object. It moves with Command, is never mutated by callbacks, | |
| // and is destroyed in the parent only after the spawn/exec handshake finishes. | |
| unsafe impl Send for Exec {} | |
| unsafe impl Sync for Exec {} | |
| impl Exec { | |
| fn replace(&self) -> io::Result<()> { | |
| // SAFETY: SETEXEC replaces this same child, preserving its PID/PGID and | |
| // the transport's already installed cwd, stdio and PTY setup. On error, | |
| // no successful replacement occurred; return its original errno through | |
| // std's untouched CLOEXEC error pipe, never report a fabricated spawn. | |
| let error = unsafe { | |
| libc::posix_spawn( | |
| ptr::null_mut(), | |
| self.program.as_ptr(), | |
| &self.actions.0, | |
| &self.attributes.0, | |
| self.argv.as_ptr(), | |
| self.envp.as_ptr(), | |
| ) | |
| }; | |
| Err(io::Error::from_raw_os_error(if error == 0 { | |
| libc::EIO | |
| } else { | |
| error | |
| })) | |
| } | |
| } | |
| struct Attributes(libc::posix_spawnattr_t); | |
| impl Attributes { | |
| fn new() -> io::Result<Self> { | |
| let mut value = std::mem::MaybeUninit::uninit(); | |
| // SAFETY: native init writes one attribute object, owned until destroy. | |
| unsafe { | |
| check(libc::posix_spawnattr_init(value.as_mut_ptr()))?; | |
| let mut value = Self(value.assume_init()); | |
| check(libc::posix_spawnattr_setflags( | |
| &mut value.0, | |
| (libc::POSIX_SPAWN_SETEXEC | libc::POSIX_SPAWN_CLOEXEC_DEFAULT) as _, | |
| ))?; | |
| Ok(value) | |
| } | |
| } | |
| fn new_pipe() -> io::Result<Self> { | |
| let mut value = std::mem::MaybeUninit::uninit(); | |
| // SAFETY: native init writes one attribute object, owned until destroy. | |
| // Always set POSIX_SPAWN_CLOEXEC_DEFAULT: piped launches never pass extra | |
| // descriptors past 0/1/2, and this closes the non-atomic pipe()+CLOEXEC | |
| // window under concurrent spawns. | |
| unsafe { | |
| check(libc::posix_spawnattr_init(value.as_mut_ptr()))?; | |
| let mut value = Self(value.assume_init()); | |
| let flags = libc::POSIX_SPAWN_SETPGROUP | |
| | libc::POSIX_SPAWN_SETSIGDEF | |
| | libc::POSIX_SPAWN_SETSIGMASK | |
| | libc::POSIX_SPAWN_CLOEXEC_DEFAULT; | |
| check(libc::posix_spawnattr_setflags(&mut value.0, flags as _))?; | |
| check(libc::posix_spawnattr_setpgroup(&mut value.0, 0))?; | |
| let mut sigdef = std::mem::MaybeUninit::uninit(); | |
| libc::sigemptyset(sigdef.as_mut_ptr()); | |
| let mut sigdef = sigdef.assume_init(); | |
| libc::sigaddset(&mut sigdef, libc::SIGPIPE); | |
| check(libc::posix_spawnattr_setsigdefault(&mut value.0, &sigdef))?; | |
| let mut sigmask = std::mem::MaybeUninit::uninit(); | |
| libc::sigemptyset(sigmask.as_mut_ptr()); | |
| let sigmask = sigmask.assume_init(); | |
| check(libc::posix_spawnattr_setsigmask(&mut value.0, &sigmask))?; | |
| Ok(value) | |
| } | |
| } | |
| } | |
| impl Drop for Attributes { | |
| fn drop(&mut self) { | |
| unsafe { | |
| libc::posix_spawnattr_destroy(&mut self.0); | |
| } | |
| } | |
| } | |
| struct Actions(libc::posix_spawn_file_actions_t); | |
| impl Actions { | |
| fn new() -> io::Result<Self> { | |
| let mut value = std::mem::MaybeUninit::uninit(); | |
| // SAFETY: only the transport's three actual stdio slots are retained. | |
| // No caller-supplied FD number or Root handle is an inheritance grant. | |
| unsafe { | |
| check(libc::posix_spawn_file_actions_init(value.as_mut_ptr()))?; | |
| let mut value = Self(value.assume_init()); | |
| for fd in 0..=2 { | |
| check(posix_spawn_file_actions_addinherit_np(&mut value.0, fd))?; | |
| } | |
| Ok(value) | |
| } | |
| } | |
| fn new_pipe( | |
| stdin_fd: RawFd, | |
| stdout_fd: RawFd, | |
| stderr_fd: RawFd, | |
| directory: Option<RawFd>, | |
| cwd: Option<&std::ffi::CStr>, | |
| ) -> io::Result<Self> { | |
| let mut value = std::mem::MaybeUninit::uninit(); | |
| // SAFETY: native init writes one file-actions object, owned until destroy. | |
| // Apply chdir/fchdir before dup2(0/1/2) so a dir_fd occupying 0/1/2 in a | |
| // daemon with closed stdio is never clobbered first. All pipe FDs are >= 3, | |
| // so dup2 into 0/1/2 cannot collide and inherits only 0/1/2 under | |
| // POSIX_SPAWN_CLOEXEC_DEFAULT. | |
| unsafe { | |
| check(libc::posix_spawn_file_actions_init(value.as_mut_ptr()))?; | |
| let mut value = Self(value.assume_init()); | |
| if let Some(dir_fd) = directory { | |
| check(posix_spawn_file_actions_addfchdir_np(&mut value.0, dir_fd))?; | |
| } else if let Some(cwd) = cwd { | |
| check(posix_spawn_file_actions_addchdir_np( | |
| &mut value.0, | |
| cwd.as_ptr(), | |
| ))?; | |
| } | |
| check(libc::posix_spawn_file_actions_adddup2( | |
| &mut value.0, | |
| stdin_fd, | |
| 0, | |
| ))?; | |
| check(libc::posix_spawn_file_actions_adddup2( | |
| &mut value.0, | |
| stdout_fd, | |
| 1, | |
| ))?; | |
| check(libc::posix_spawn_file_actions_adddup2( | |
| &mut value.0, | |
| stderr_fd, | |
| 2, | |
| ))?; | |
| Ok(value) | |
| } | |
| } | |
| } | |
| impl Drop for Actions { | |
| fn drop(&mut self) { | |
| unsafe { | |
| libc::posix_spawn_file_actions_destroy(&mut self.0); | |
| } | |
| } | |
| } | |
| fn check(error: libc::c_int) -> io::Result<()> { | |
| if error == 0 { | |
| Ok(()) | |
| } else { | |
| Err(io::Error::from_raw_os_error(error)) | |
| } | |
| } | |
| #[cfg(test)] | |
| mod tests { | |
| use super::*; | |
| use crate::group::Group; | |
| use tokio::{ | |
| io::{AsyncReadExt, AsyncWriteExt}, | |
| signal::unix::{SignalKind, signal}, | |
| }; | |
| #[tokio::test] | |
| async fn spawn_piped_honors_fchdir_private_stdio_pgroup_and_reaps() { | |
| let dir = tempfile::tempdir().unwrap(); | |
| let canonical = std::fs::canonicalize(dir.path()).unwrap(); | |
| let dir_file = std::fs::File::open(&canonical).unwrap(); | |
| // Open an extra inheritable (non-CLOEXEC) FD in the parent and verify | |
| // private_stdio=true atomically closes it in the child. | |
| let (extra_read, extra_write) = create_cloexec_pipe().unwrap(); | |
| // SAFETY: clearing CLOEXEC on our own test FD to prove CLOEXEC_DEFAULT closes it. | |
| assert_eq!( | |
| unsafe { libc::fcntl(extra_read.as_raw_fd(), libc::F_SETFD, 0) }, | |
| 0 | |
| ); | |
| let leaked_fd = extra_read.as_raw_fd(); | |
| let changed = signal(SignalKind::child()).unwrap(); | |
| let script = format!( | |
| "pwd; ps -o pid=,pgid= -p $$; if [ -e /dev/fd/{leaked_fd} ]; then echo LEAKED; else echo ISOLATED; fi; cat" | |
| ); | |
| let mut env = BTreeMap::new(); | |
| env.insert(OsString::from("PATH"), OsString::from("/bin:/usr/bin")); | |
| let spawned = spawn_piped( | |
| Path::new("/bin/sh"), | |
| &["-c", &script], | |
| &env, | |
| Path::new("/"), | |
| Some(dir_file.as_raw_fd()), | |
| ) | |
| .unwrap(); | |
| drop((extra_read, extra_write, dir_file)); | |
| let mut group = Group::from_pid(spawned.pid, changed); | |
| let mut stdin = spawned.stdin; | |
| let mut stdout = spawned.stdout; | |
| stdin.write_all(b"stdin-ok\n").await.unwrap(); | |
| drop(stdin); | |
| let mut out = String::new(); | |
| stdout.read_to_string(&mut out).await.unwrap(); | |
| let status = group.wait().await.unwrap(); | |
| assert!(status.success(), "child failed: {status}, out={out:?}"); | |
| let lines: Vec<&str> = out.lines().collect(); | |
| assert_eq!(lines[0], canonical.to_string_lossy()); | |
| let parts: Vec<&str> = lines[1].split_whitespace().collect(); | |
| assert_eq!(parts.len(), 2, "unexpected ps line: {:?}", lines[1]); | |
| assert_eq!(parts[0], parts[1], "child must lead its own process group"); | |
| assert_eq!(lines[2], "ISOLATED"); | |
| assert_eq!(lines[3], "stdin-ok"); | |
| } | |
| #[tokio::test] | |
| async fn spawn_piped_reports_missing_executable_and_reaps_dropped_group() { | |
| let env = BTreeMap::new(); | |
| let err = match spawn_piped( | |
| Path::new("/nonexistent/maka-missing-binary"), | |
| &[] as &[&str], | |
| &env, | |
| Path::new("/tmp"), | |
| None, | |
| ) { | |
| Ok(_) => panic!("missing executable must fail"), | |
| Err(error) => error, | |
| }; | |
| assert_eq!(err.kind(), io::ErrorKind::NotFound); | |
| let changed = signal(SignalKind::child()).unwrap(); | |
| let spawned = spawn_piped( | |
| Path::new("/bin/sleep"), | |
| &["30"], | |
| &env, | |
| Path::new("/tmp"), | |
| None, | |
| ) | |
| .unwrap(); | |
| let pid = spawned.pid; | |
| let group = Group::from_pid(pid, changed); | |
| // Dropping outside a Tokio runtime thread must still reap the child via | |
| // the Handle captured at Group::from_pid. | |
| std::thread::spawn(move || drop(group)).join().unwrap(); | |
| crate::group::wait_group_closed(pid).await.unwrap(); | |
| } | |
| } |