Use native POSIX spawning for command hooks (#47610)

## Why

Unix command hooks use a `pre_exec` callback to detach from the controlling terminal, forcing the launcher to fork. Native spawn attributes can create the detached session without that callback.

## What changed

- Route Unix hooks through `codex_utils_pty::Command` with `ProcessMode::NewSession`.
- Extend the native `posix_spawn` launcher to detached Linux sessions, retaining compatibility fallbacks for unsupported libc features and executable handling.
- Preserve the session environment snapshot, hook overrides, and restricted-variable filtering.

## Testing

Add regression coverage for launches without parent forks, terminal detachment, environment and argument handling, Linux `PATH` lookup, and executable compatibility. Cover process-group cleanup on cancellation and timeout, including descendants holding output pipes open, and preservation of background descendants after completed hooks.

GitOrigin-RevId: dbe2cf12d84aa79868cfb55ace40c7d5b5282703
This commit is contained in:
Charlie Marsh
2026-09-23 18:24:05 +00:00
committed by copyberry
parent 50fc133d05
commit 7aa6519909
11 changed files with 620 additions and 160 deletions
+8 -8
View File
@@ -11,9 +11,9 @@ use tokio::process::ChildStderr;
use tokio::process::ChildStdin;
use tokio::process::ChildStdout;
#[cfg(target_os = "macos")]
#[path = "macos_child.rs"]
pub(super) mod macos;
#[cfg(any(target_os = "macos", target_os = "linux"))]
#[path = "posix_child.rs"]
pub(super) mod posix;
#[cfg(unix)]
#[path = "child_reaper.rs"]
@@ -34,8 +34,8 @@ pub(super) enum ChildKind {
child: Option<tokio::process::Child>,
reaper: std::sync::mpsc::Sender<reaper::ChildToReap>,
},
#[cfg(target_os = "macos")]
Native(macos::NativeChild),
#[cfg(any(target_os = "macos", target_os = "linux"))]
Native(posix::NativeChild),
}
impl Child {
@@ -46,7 +46,7 @@ impl Child {
ChildKind::TokioReapOnly { child, .. } => {
child.as_ref().and_then(tokio::process::Child::id)
}
#[cfg(target_os = "macos")]
#[cfg(any(target_os = "macos", target_os = "linux"))]
ChildKind::Native(child) => child.id(),
}
}
@@ -64,7 +64,7 @@ impl Child {
.wait()
.await
}
#[cfg(target_os = "macos")]
#[cfg(any(target_os = "macos", target_os = "linux"))]
ChildKind::Native(child) => child.wait().await,
}
}
@@ -114,7 +114,7 @@ impl Child {
.kill()
.await
}
#[cfg(target_os = "macos")]
#[cfg(any(target_os = "macos", target_os = "linux"))]
ChildKind::Native(child) => child.kill().await,
}
}
+14 -5
View File
@@ -234,7 +234,7 @@ impl Command {
Ok(())
}
/// Launch with native macOS path handling and the existing compatibility fallback.
/// Launch with native platform settings and the existing compatibility fallback.
pub fn spawn(mut self) -> io::Result<Child> {
#[cfg(unix)]
self.validate()?;
@@ -242,17 +242,22 @@ impl Command {
if let ProcessMode::NewGroup = self.process_mode {
self.inner.process_group(/*pgroup*/ 0);
}
#[cfg(target_os = "macos")]
#[cfg(any(target_os = "macos", target_os = "linux"))]
{
let command = self.inner.as_std();
let program = command.get_program();
if (Path::new(program).is_relative()
#[cfg(target_os = "macos")]
let use_native = Path::new(program).is_relative()
|| self.descriptor_policy == DescriptorPolicy::Explicit
|| self.fallback == SpawnFallback::ReturnError
|| matches!(self.process_mode, ProcessMode::NewSession)
|| !self.inherited_fds.is_empty())
|| !self.inherited_fds.is_empty();
#[cfg(target_os = "linux")]
let use_native =
matches!(self.process_mode, ProcessMode::NewSession) && self.parent_pid.is_none();
if use_native
&& !program.is_empty()
&& let Some(child) = crate::child::macos::NativeChild::spawn(&self)?
&& let Some(child) = crate::child::posix::NativeChild::spawn(&self)?
{
return Ok(child);
}
@@ -331,3 +336,7 @@ mod tests;
#[cfg(all(test, target_os = "macos"))]
#[path = "macos_descriptor_tests.rs"]
mod descriptor_tests;
#[cfg(all(test, target_os = "linux"))]
#[path = "linux_child_tests.rs"]
mod linux_tests;
+3 -3
View File
@@ -5,7 +5,7 @@
//! ownership until reaped, so one live child cannot delay cleanup of another.
use std::io;
#[cfg(target_os = "macos")]
#[cfg(any(target_os = "macos", target_os = "linux"))]
use std::ptr;
use std::sync::Mutex;
use std::sync::PoisonError;
@@ -14,7 +14,7 @@ use std::time::Duration;
/// Exclusive ownership transferred by a child handle after its caller drops it.
pub(crate) enum ChildToReap {
#[cfg(target_os = "macos")]
#[cfg(any(target_os = "macos", target_os = "linux"))]
Native(libc::pid_t),
Tokio(tokio::process::Child),
}
@@ -47,7 +47,7 @@ pub(crate) fn sender() -> io::Result<mpsc::Sender<ChildToReap>> {
// Amortize scans across bursts without starving reaping when drops continue.
pending.extend(receiver.try_iter().take(REAP_BATCH_SIZE - 1));
pending.retain_mut(|child| match child {
#[cfg(target_os = "macos")]
#[cfg(any(target_os = "macos", target_os = "linux"))]
ChildToReap::Native(pid) => {
// SAFETY: Drop transferred exclusive ownership of this PID.
let result = unsafe { libc::waitpid(*pid, ptr::null_mut(), libc::WNOHANG) };
+74
View File
@@ -12,6 +12,7 @@ use tokio::io::AsyncReadExt;
use tokio::io::AsyncWriteExt;
use crate::Command;
use crate::ProcessMode;
#[tokio::test]
async fn wait_with_output_keeps_eof_pipes_open_until_exit() -> anyhow::Result<()> {
@@ -329,3 +330,76 @@ async fn preserving_descriptors_keeps_parent_record_locks() -> anyhow::Result<()
assert!(output.status.success(), "{output:?}");
Ok(())
}
#[tokio::test]
async fn detached_spawn_preserves_child_path_cwd_environment_and_arg0() -> anyhow::Result<()> {
let root = tempfile::tempdir()?;
std::fs::create_dir(root.path().join("bin"))?;
std::os::unix::fs::symlink("/bin/sh", root.path().join("bin/child-shell"))?;
let mut command = Command::new("child-shell");
command
.current_dir(root.path())
.env("PATH", "bin")
.env("MARKER", "child-value")
.arg0("custom-shell")
.args(["-c", "printf '%s|%s|' \"$0\" \"$MARKER\"; pwd; read -r line; printf '%s' \"$line\"; printf diagnostic >&2"])
.process_mode(ProcessMode::NewSession);
let mut child = command.spawn()?;
child
.stdin
.take()
.expect("piped stdin")
.write_all(b"input\n")
.await?;
assert_eq!(
child.wait_with_output().await?,
std::process::Output {
status: std::process::ExitStatus::from_raw(0),
stdout: format!(
"custom-shell|child-value|{}\ninput",
root.path().canonicalize()?.display()
)
.into_bytes(),
stderr: b"diagnostic".to_vec(),
}
);
Ok(())
}
#[tokio::test]
async fn detached_spawn_preserves_exec_errors_and_executable_text_handling() -> anyhow::Result<()> {
use std::os::unix::fs::PermissionsExt;
let root = tempfile::tempdir()?;
let program = root.path().join("script");
let mut missing = Command::new(&program);
missing.process_mode(ProcessMode::NewSession);
let error = missing.spawn().err().expect("missing executable must fail");
assert_eq!(error.kind(), std::io::ErrorKind::NotFound);
std::fs::write(&program, "printf '%s' \"$1\"")?;
std::fs::set_permissions(&program, std::fs::Permissions::from_mode(0o755))?;
// Match the existing libc behavior: glibc/macOS retry executable text through
// a shell, whereas musl returns ENOEXEC.
let mut baseline = tokio::process::Command::new(&program);
baseline.env_clear().arg("shell fallback");
// SAFETY: The legacy route only performs async-signal-safe session setup.
unsafe {
baseline.pre_exec(crate::process_group::detach_from_tty);
}
let expected = baseline.output().await;
let mut script = Command::new(&program);
script
.arg("shell fallback")
.process_mode(ProcessMode::NewSession);
let actual = match script.spawn() {
Ok(child) => child.wait_with_output().await,
Err(error) => Err(error),
};
let error_details = |error: std::io::Error| (error.kind(), error.raw_os_error());
assert_eq!(
actual.map_err(error_details),
expected.map_err(error_details)
);
Ok(())
}
@@ -0,0 +1,63 @@
//! Linux executable lookup must match the compatibility launcher's PATH semantics.
use std::os::unix::fs::PermissionsExt;
use pretty_assertions::assert_eq;
use crate::Command;
use crate::ProcessMode;
#[tokio::test]
async fn path_search_stops_at_invalid_candidates() -> anyhow::Result<()> {
let root = tempfile::tempdir()?;
std::fs::create_dir(root.path().join("bin"))?;
std::os::unix::fs::symlink("loop", root.path().join("loop"))?;
let script = root.path().join("bin/server");
std::fs::write(&script, "#!/bin/sh\nprintf later\n")?;
std::fs::set_permissions(script, std::fs::Permissions::from_mode(/*mode*/ 0o755))?;
for candidate in ["loop".to_owned(), "x".repeat(256)] {
let mut command = Command::new("server");
command
.current_dir(root.path())
.env("PATH", format!("{candidate}:bin"));
let expected = command
.inner
.spawn()
.expect_err("invalid first candidate must stop lookup");
command.process_mode(ProcessMode::NewSession);
let actual = command.spawn().err().expect("native lookup must stop too");
assert_eq!(actual.raw_os_error(), expected.raw_os_error());
}
Ok(())
}
#[tokio::test]
async fn empty_path_entries_preserve_script_argv0() -> anyhow::Result<()> {
// A sibling test can fork while the script is open for writing, retaining
// the writable descriptor and making exec fail with ETXTBSY.
if std::env::var_os("CODEX_TEST_PATH_ARGV0").is_none() {
let output = std::process::Command::new(std::env::current_exe()?)
.args([
"--exact",
"child_command::linux_tests::empty_path_entries_preserve_script_argv0",
"--nocapture",
])
.env("CODEX_TEST_PATH_ARGV0", "1")
.output()?;
assert!(output.status.success(), "{output:?}");
return Ok(());
}
let root = tempfile::tempdir()?;
let script = root.path().join("server");
std::fs::write(&script, "#!/bin/sh\nprintf '%s' \"$0\"\n")?;
std::fs::set_permissions(script, std::fs::Permissions::from_mode(/*mode*/ 0o755))?;
for path in ["", ":missing", "missing:", ".", "./"] {
let mut command = Command::new("server");
command.current_dir(root.path()).env("PATH", path);
let expected = command.inner.output().await?;
command.process_mode(ProcessMode::NewSession);
let actual = command.spawn()?.wait_with_output().await?;
assert_eq!(actual, expected);
}
Ok(())
}
+1 -1
View File
@@ -2,7 +2,7 @@
use super::*;
use crate::child::ChildKind;
use crate::child::macos::*;
use crate::child::posix::*;
use pretty_assertions::assert_eq;
use std::fs;
use std::os::fd::AsRawFd;
@@ -1,13 +1,15 @@
//! Native macOS spawning without rewriting executable paths or argv[0].
//! Native POSIX spawning without rewriting executable paths or argv[0].
//!
//! Spawn attributes and file actions implement the shared command's process-group
//! and descriptor policies. Bare commands search the child's PATH. Callers choose
//! whether incompatible executable formats and failed searches may retry through
//! Tokio. Each native child owns its PID until it has been reaped.
//! Tokio. Linux uses this for detached sessions with ambient descriptor inheritance.
//! Each native child owns its PID until it has been reaped.
use std::ffi::CString;
use std::ffi::OsStr;
use std::io;
use std::mem::MaybeUninit;
use std::os::fd::AsRawFd;
use std::os::fd::FromRawFd;
use std::os::fd::OwnedFd;
@@ -27,12 +29,15 @@ use crate::child_command::ChildDropPolicy;
use crate::child::reaper;
// Apple's spawn.h defines this extension on our minimum macOS 12, but libc
// does not expose it. A new session also creates a new process group.
#[cfg(target_os = "linux")]
use libc::POSIX_SPAWN_SETSID;
// Apple exposes this extension in spawn.h, but libc does not yet bind it.
#[cfg(target_os = "macos")]
const POSIX_SPAWN_SETSID: libc::c_int = 0x0400;
// libc does not expose this Apple extension. It is available since macOS 10.15,
// before Codex's minimum supported macOS version (12).
// Available since macOS 10.15 and in Rust's bundled musl. Older glibc needs
// runtime detection so this optimization does not raise our minimum libc version.
#[cfg(any(target_os = "macos", target_env = "musl"))]
unsafe extern "C" {
fn posix_spawn_file_actions_addchdir_np(
actions: *mut libc::posix_spawn_file_actions_t,
@@ -51,10 +56,25 @@ pub(crate) struct NativeChild {
impl NativeChild {
/// Spawn the explicit command, retaining the caller's executable spelling and argv[0].
/// Returns `Ok(None)` when native setup is unsupported or execution needs the
/// caller's compatibility fallback.
pub(crate) fn spawn(request: &crate::Command) -> io::Result<Option<crate::Child>> {
#[cfg(target_os = "linux")]
if request.descriptor_policy != crate::DescriptorPolicy::Inherit {
return Ok(None);
}
let command = request.inner.as_std();
let program = c_string(command.get_program())?;
let search_path = !program.as_bytes().contains(&b'/');
#[cfg(target_os = "linux")]
if search_path
&& !command
.get_envs()
.any(|(key, value)| key == "PATH" && value.is_some())
{
// Preserve the libc-specific default search path in the fallback.
return Ok(None);
}
let args = std::iter::once(request.arg0.as_deref().unwrap_or(command.get_program()))
.chain(command.get_args())
.map(c_string)
@@ -90,6 +110,31 @@ impl NativeChild {
ChildDropPolicy::ReapOnly => Some(reaper::sender()?),
};
#[cfg(all(target_os = "linux", target_env = "gnu"))]
let addchdir = {
// SAFETY: dlsym returns the documented function signature when present.
let symbol = unsafe {
libc::dlsym(
libc::RTLD_DEFAULT,
c"posix_spawn_file_actions_addchdir_np".as_ptr(),
)
};
if symbol.is_null() {
return Ok(None);
}
unsafe {
std::mem::transmute::<
*mut libc::c_void,
unsafe extern "C" fn(
*mut libc::posix_spawn_file_actions_t,
*const libc::c_char,
) -> libc::c_int,
>(symbol)
}
};
#[cfg(any(target_os = "macos", target_env = "musl"))]
let addchdir = posix_spawn_file_actions_addchdir_np;
// Subscribe before spawning so a child that exits immediately cannot be missed.
let sigchld = signal(SignalKind::child())?;
let (stdin_read, stdin) = match &request.stdin {
@@ -113,19 +158,20 @@ impl NativeChild {
let stdout = ChildStdout::from_std(OwnedFd::from(stdout_read).into())?;
let stderr = ChildStderr::from_std(OwnedFd::from(stderr_read).into())?;
let mut actions = FileActions(ptr::null_mut());
let mut attrs = Attributes(ptr::null_mut());
let mut actions = MaybeUninit::uninit();
// SAFETY: Successful initialization makes each object valid; RAII only
// takes ownership after that success, including if the next init fails.
cvt(unsafe { libc::posix_spawn_file_actions_init(actions.as_mut_ptr()) })?;
let mut actions = FileActions(unsafe { actions.assume_init() });
let mut attrs = MaybeUninit::uninit();
cvt(unsafe { libc::posix_spawnattr_init(attrs.as_mut_ptr()) })?;
let mut attrs = Attributes(unsafe { attrs.assume_init() });
let mut pid = 0;
// SAFETY: All C strings and pipe descriptors outlive this synchronous
// spawn. The initialized action/attribute objects are destroyed by RAII.
let result = unsafe {
cvt(libc::posix_spawn_file_actions_init(&mut actions.0))?;
cvt(libc::posix_spawnattr_init(&mut attrs.0))?;
if let Some(cwd) = &cwd {
cvt(posix_spawn_file_actions_addchdir_np(
&mut actions.0,
cwd.as_ptr(),
))?;
cvt(addchdir(&mut actions.0, cwd.as_ptr()))?;
}
for (target, source) in child_fds.iter().enumerate() {
cvt(libc::posix_spawn_file_actions_adddup2(
@@ -146,7 +192,6 @@ impl NativeChild {
}
let group_flags = match request.process_mode {
crate::ProcessMode::Inherit => 0,
crate::ProcessMode::NewSession => POSIX_SPAWN_SETSID,
crate::ProcessMode::NewGroup => {
cvt(libc::posix_spawnattr_setpgroup(
&mut attrs.0,
@@ -154,19 +199,28 @@ impl NativeChild {
))?;
libc::POSIX_SPAWN_SETPGROUP
}
crate::ProcessMode::NewSession => POSIX_SPAWN_SETSID,
};
let mut defaults = 0;
let mut defaults = std::mem::zeroed();
cvt_errno(libc::sigemptyset(&mut defaults))?;
cvt_errno(libc::sigaddset(&mut defaults, libc::SIGPIPE))?;
cvt(libc::posix_spawnattr_setsigdefault(&mut attrs.0, &defaults))?;
#[cfg(target_os = "macos")]
let descriptor_flags = match request.descriptor_policy {
crate::DescriptorPolicy::Inherit => 0,
crate::DescriptorPolicy::Explicit => libc::POSIX_SPAWN_CLOEXEC_DEFAULT,
};
cvt(libc::posix_spawnattr_setflags(
#[cfg(target_os = "linux")]
let descriptor_flags = 0;
let result = libc::posix_spawnattr_setflags(
&mut attrs.0,
(group_flags | descriptor_flags | libc::POSIX_SPAWN_SETSIGDEF) as _,
))?;
);
// Unsupported attributes fail before posix_spawn can select its fallback.
if result == libc::EINVAL && request.fallback == crate::SpawnFallback::Compatible {
return Ok(None);
}
cvt(result)?;
let mut spawn = |executable: &CString| {
libc::posix_spawn(
&mut pid,
@@ -190,12 +244,15 @@ impl NativeChild {
let mut result = libc::ENOENT;
for directory in std::env::split_paths(path) {
let mut executable = directory.into_os_string();
#[cfg(target_os = "macos")]
if executable.is_empty() {
executable.push(".");
}
// Preserve the spelling execvp would pass to a shebang
// interpreter, including empty entries and trailing slashes.
executable.push("/");
if !executable.is_empty() {
executable.push("/");
}
executable.push(command.get_program());
if executable.as_bytes().len() >= libc::PATH_MAX as usize {
return if request.fallback == crate::SpawnFallback::Compatible {
@@ -205,15 +262,13 @@ impl NativeChild {
};
}
result = spawn(&c_string(&executable)?);
if !matches!(
result,
libc::ENOENT
| libc::ENOTDIR
| libc::EACCES
| libc::ELOOP
| libc::ENAMETOOLONG
) {
break;
match result {
libc::ENOENT | libc::ENOTDIR | libc::EACCES => {}
#[cfg(target_os = "macos")]
libc::ELOOP | libc::ENAMETOOLONG => {}
#[cfg(all(target_os = "linux", target_env = "gnu"))]
libc::ESTALE | libc::ENODEV | libc::ETIMEDOUT => {}
_ => break,
}
}
result
@@ -221,7 +276,10 @@ impl NativeChild {
};
// Retain Command's shell fallback and exact PATH search errors.
if request.fallback == crate::SpawnFallback::Compatible
&& (result == libc::ENOEXEC || (search_path && result != 0))
&& (result == libc::ENOEXEC
|| (search_path && result != 0)
|| (matches!(request.process_mode, crate::ProcessMode::NewSession)
&& matches!(result, libc::EINVAL | libc::EPERM)))
{
return Ok(None);
}
@@ -380,22 +438,18 @@ struct Attributes(libc::posix_spawnattr_t);
impl Drop for FileActions {
fn drop(&mut self) {
if !self.0.is_null() {
// SAFETY: This object was initialized by posix_spawn_file_actions_init.
unsafe {
libc::posix_spawn_file_actions_destroy(&mut self.0);
}
// SAFETY: This object was initialized by posix_spawn_file_actions_init.
unsafe {
libc::posix_spawn_file_actions_destroy(&mut self.0);
}
}
}
impl Drop for Attributes {
fn drop(&mut self) {
if !self.0.is_null() {
// SAFETY: This object was initialized by posix_spawnattr_init.
unsafe {
libc::posix_spawnattr_destroy(&mut self.0);
}
// SAFETY: This object was initialized by posix_spawnattr_init.
unsafe {
libc::posix_spawnattr_destroy(&mut self.0);
}
}
}