Base: codex-main originale (prima del fork aKode)

This commit is contained in:
Andrea
2026-11-09 10:37:42 +01:00
commit 7874033c81
10166 changed files with 2728937 additions and 0 deletions

View File

@@ -0,0 +1,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "pty",
crate_name = "codex_utils_pty",
)

View File

@@ -0,0 +1,43 @@
[package]
edition.workspace = true
license.workspace = true
name = "codex-utils-pty"
version.workspace = true
[lints]
workspace = true
[dependencies]
anyhow = { workspace = true }
portable-pty = { workspace = true }
tokio = { workspace = true, features = ["io-util", "macros", "net", "process", "rt-multi-thread", "signal", "sync", "time"] }
[dev-dependencies]
codex-utils-cargo-bin = { workspace = true }
ctor = { workspace = true }
tempfile = { workspace = true }
pretty_assertions = { workspace = true }
[target.'cfg(windows)'.dependencies]
filedescriptor = "0.8.3"
lazy_static = { workspace = true }
log = { workspace = true }
shared_library = "0.1.9"
winapi = { version = "0.3.9", features = [
"handleapi",
"jobapi",
"jobapi2",
"libloaderapi",
"minwinbase",
"processthreadsapi",
"synchapi",
"winbase",
"wincon",
"winerror",
"winnt",
] }
[target.'cfg(unix)'.dependencies]
libc = { workspace = true }
[lib]
doctest = false

View File

@@ -0,0 +1,64 @@
# codex-utils-pty
Lightweight helpers for spawning interactive processes either under a PTY (pseudo terminal) or regular pipes. The public API is minimal and mirrors both backends so callers can switch based on their needs (e.g., enabling or disabling TTY).
## API surface
- `spawn_pty_process(program, args, cwd, env, arg0, size)` → `SpawnedProcess`
- `spawn_pipe_process(program, args, cwd, env, arg0)` → `SpawnedProcess`
- `spawn_pipe_process_no_stdin(program, args, cwd, env, arg0)` → `SpawnedProcess`
- `combine_output_receivers(stdout_rx, stderr_rx)` → `broadcast::Receiver<Vec<u8>>`
- `conpty_supported()` → `bool` (Windows only; always true elsewhere)
- `TerminalSize { rows, cols }` selects PTY dimensions in character cells.
- `ProcessHandle` exposes:
- `writer_sender()` → `mpsc::Sender<Vec<u8>>` (stdin)
- `resize(TerminalSize)`
- `close_stdin()`
- `has_exited()`, `exit_code()`, `terminate()`
- `SpawnedProcess` bundles `session`, `stdout_rx`, `stderr_rx`, and `exit_rx` (oneshot exit code).
## Usage examples
```rust
use std::collections::HashMap;
use std::path::Path;
use codex_utils_pty::combine_output_receivers;
use codex_utils_pty::spawn_pty_process;
use codex_utils_pty::TerminalSize;
# tokio_test::block_on(async {
let env_map: HashMap<String, String> = std::env::vars().collect();
let spawned = spawn_pty_process(
"bash",
&["-lc".into(), "echo hello".into()],
Path::new("."),
&env_map,
&None,
TerminalSize::default(),
).await?;
let writer = spawned.session.writer_sender();
writer.send(b"exit\n".to_vec()).await?;
// Collect output until the process exits.
let mut output_rx = combine_output_receivers(spawned.stdout_rx, spawned.stderr_rx);
let mut collected = Vec::new();
while let Ok(chunk) = output_rx.try_recv() {
collected.extend_from_slice(&chunk);
}
let exit_code = spawned.exit_rx.await.unwrap_or(-1);
# let _ = (collected, exit_code);
# anyhow::Ok(())
# });
```
Swap in `spawn_pipe_process` for a non-TTY subprocess; the rest of the API stays the same.
Use `spawn_pipe_process_no_stdin` to force stdin closed (commands that read stdin will see EOF immediately).
## Tests
Unit tests live in `src/lib.rs` and cover both backends (PTY Python REPL and pipe-based stdin roundtrip). Run with:
```
just test -p codex-utils-pty --no-capture
```

View File

@@ -0,0 +1,139 @@
//! Local child ownership and platform selection, independent of process transports.
//!
//! Every child exposes Tokio stdio handles. Reap-only children retain ownership until
//! reaped, including when a wait is cancelled or the async runtime shuts down.
use std::io;
use std::process::ExitStatus;
use tokio::io::AsyncReadExt;
use tokio::process::ChildStderr;
use tokio::process::ChildStdin;
use tokio::process::ChildStdout;
#[cfg(any(target_os = "macos", target_os = "linux"))]
#[path = "posix_child.rs"]
pub(super) mod posix;
#[cfg(unix)]
#[path = "child_reaper.rs"]
pub(super) mod reaper;
/// A local subprocess with owned stdio and cancellation-safe exit handling.
pub struct Child {
pub(super) inner: ChildKind,
pub stdin: Option<ChildStdin>,
pub stdout: Option<ChildStdout>,
pub stderr: Option<ChildStderr>,
}
pub(super) enum ChildKind {
Tokio(tokio::process::Child),
#[cfg(unix)]
TokioReapOnly {
child: Option<tokio::process::Child>,
reaper: std::sync::mpsc::Sender<reaper::ChildToReap>,
},
#[cfg(any(target_os = "macos", target_os = "linux"))]
Native(posix::NativeChild),
}
impl Child {
pub fn id(&self) -> Option<u32> {
match &self.inner {
ChildKind::Tokio(child) => child.id(),
#[cfg(unix)]
ChildKind::TokioReapOnly { child, .. } => {
child.as_ref().and_then(tokio::process::Child::id)
}
#[cfg(any(target_os = "macos", target_os = "linux"))]
ChildKind::Native(child) => child.id(),
}
}
/// Close retained stdin and wait without giving up ownership on cancellation.
pub async fn wait(&mut self) -> io::Result<ExitStatus> {
self.stdin.take();
match &mut self.inner {
ChildKind::Tokio(child) => child.wait().await,
#[cfg(unix)]
ChildKind::TokioReapOnly { child, .. } => {
child
.as_mut()
.ok_or_else(|| io::Error::other("child already transferred to reaper"))?
.wait()
.await
}
#[cfg(any(target_os = "macos", target_os = "linux"))]
ChildKind::Native(child) => child.wait().await,
}
}
/// Drain both output pipes while waiting, retaining the configured drop policy on cancellation.
pub async fn wait_with_output(mut self) -> io::Result<std::process::Output> {
let mut stdout = self.stdout.take();
let mut stderr = self.stderr.take();
let mut output = Vec::new();
let mut diagnostic = Vec::new();
let (status, _, _) = tokio::try_join!(
self.wait(),
async {
if let Some(stdout) = stdout.as_mut() {
stdout.read_to_end(&mut output).await?;
}
Ok::<_, io::Error>(())
},
async {
if let Some(stderr) = stderr.as_mut() {
stderr.read_to_end(&mut diagnostic).await?;
}
Ok::<_, io::Error>(())
},
)?;
// Keep the pipes open until the child exits, even after EOF, matching Tokio.
// See https://github.com/tokio-rs/tokio/issues/4309.
drop(stdout);
drop(stderr);
Ok(std::process::Output {
status,
stdout: output,
stderr: diagnostic,
})
}
/// Kill the direct child and reap it. Process-tree policy belongs to the caller.
pub async fn kill(&mut self) -> io::Result<()> {
self.stdin.take();
match &mut self.inner {
ChildKind::Tokio(child) => child.kill().await,
#[cfg(unix)]
ChildKind::TokioReapOnly { child, .. } => {
child
.as_mut()
.ok_or_else(|| io::Error::other("child already transferred to reaper"))?
.kill()
.await
}
#[cfg(any(target_os = "macos", target_os = "linux"))]
ChildKind::Native(child) => child.kill().await,
}
}
}
#[cfg(all(test, unix))]
#[path = "child_tests.rs"]
mod tests;
impl Drop for ChildKind {
fn drop(&mut self) {
#[cfg(unix)]
if let Self::TokioReapOnly { child, reaper } = self
&& let Some(child) = child.take()
&& child.id().is_some()
{
// Transfer the handle, not only its PID: Tokio must not enqueue it
// into a stopped runtime's orphan queue before our worker reaps it.
let _ = reaper.send(reaper::ChildToReap::Tokio(child));
}
}
}

View File

@@ -0,0 +1,393 @@
//! Explicit local launch settings shared by native and Tokio process creation.
//!
//! The wrapped Tokio command is private: callers cannot install callbacks or
//! change settings that the native backend cannot inspect. Children receive only
//! explicitly supplied environment variables and default to kill-on-drop. Stdio,
//! descriptor inheritance, and compatibility fallbacks are configured independently.
//! Windows children communicate over pipes and never allocate a console window.
//! Original Unix inputs retain their NUL validation even when std replaces them.
use std::ffi::OsStr;
#[cfg(unix)]
use std::ffi::OsString;
use std::io;
use std::path::Path;
use std::process::Stdio as TokioStdio;
#[cfg(windows)]
use winapi::um::winbase::CREATE_NO_WINDOW;
use crate::child::Child;
use crate::child::ChildKind;
/// Relationship between a child and its parent's session and process group.
///
/// These settings apply only on Unix; other platforms use their default behavior.
#[derive(Clone, Copy)]
pub enum ProcessMode {
/// Keep the parent's session, process group, and controlling terminal.
Inherit,
/// Create a process group led by the child, keeping the parent's session and
/// controlling terminal. This allows signaling the child's group separately.
NewGroup,
/// Create a session and process group led by the child, detaching from the
/// parent's controlling terminal.
///
/// Native spawning is an optimization; compatibility fallbacks may fork.
NewSession,
}
/// Whether Unix children inherit ambient descriptors or only explicit stdio and
/// the descriptors selected by `Command::preserve_fds`.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum DescriptorPolicy {
Inherit,
/// Exclude unrelated descriptors, allowing launch if best-effort cleanup fails.
Explicit,
}
/// Whether a native launch may use Command's executable-text and PATH fallbacks.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum SpawnFallback {
Compatible,
ReturnError,
}
/// Cleanup performed when a child handle is dropped before its exit is collected.
#[derive(Clone, Copy)]
pub(crate) enum ChildDropPolicy {
/// Kill the direct child, then reap it. This is the default.
KillAndReap,
/// Reap the child when it exits, leaving termination to the caller.
ReapOnly,
}
/// An explicit child stdin, including a socket used for bidirectional fd transfer.
pub enum ChildStdin {
Piped,
Null,
#[cfg(unix)]
File(std::os::fd::OwnedFd),
#[cfg(windows)]
File(std::os::windows::io::OwnedHandle),
}
/// A local command whose complete launch contract is known to both backends.
pub struct Command {
pub(crate) inner: tokio::process::Command,
#[cfg(unix)]
saw_nul: bool,
pub(crate) process_mode: ProcessMode,
pub(crate) descriptor_policy: DescriptorPolicy,
pub(crate) fallback: SpawnFallback,
pub(crate) stdin: ChildStdin,
pub(crate) drop_policy: ChildDropPolicy,
#[cfg(unix)]
pub(crate) inherited_fds: Vec<std::os::fd::RawFd>,
#[cfg(target_os = "linux")]
parent_pid: Option<libc::pid_t>,
#[cfg(unix)]
pub(crate) stdout_file: Option<std::os::fd::OwnedFd>,
#[cfg(unix)]
pub(crate) stderr_file: Option<std::os::fd::OwnedFd>,
#[cfg(unix)]
pub(crate) arg0: Option<OsString>,
}
impl Command {
pub fn new(program: impl AsRef<OsStr>) -> Self {
let program = program.as_ref();
let mut inner = tokio::process::Command::new(program);
inner
.env_clear()
.kill_on_drop(true)
.stdin(TokioStdio::piped())
.stdout(TokioStdio::piped())
.stderr(TokioStdio::piped());
#[cfg(windows)]
inner.creation_flags(CREATE_NO_WINDOW);
Self {
inner,
#[cfg(unix)]
saw_nul: program.as_encoded_bytes().contains(&0),
process_mode: ProcessMode::Inherit,
descriptor_policy: DescriptorPolicy::Inherit,
fallback: SpawnFallback::Compatible,
stdin: ChildStdin::Piped,
drop_policy: ChildDropPolicy::KillAndReap,
#[cfg(unix)]
inherited_fds: Vec::new(),
#[cfg(target_os = "linux")]
parent_pid: None,
#[cfg(unix)]
stdout_file: None,
#[cfg(unix)]
stderr_file: None,
#[cfg(unix)]
arg0: None,
}
}
pub fn arg(&mut self, arg: impl AsRef<OsStr>) -> &mut Self {
let arg = arg.as_ref();
#[cfg(unix)]
{
self.saw_nul |= arg.as_encoded_bytes().contains(&0);
}
self.inner.arg(arg);
self
}
pub fn args(&mut self, args: impl IntoIterator<Item = impl AsRef<OsStr>>) -> &mut Self {
for arg in args {
self.arg(arg);
}
self
}
pub fn env(&mut self, key: impl AsRef<OsStr>, value: impl AsRef<OsStr>) -> &mut Self {
self.inner.env(key, value);
self
}
pub fn envs<K, V>(&mut self, env: impl IntoIterator<Item = (K, V)>) -> &mut Self
where
K: AsRef<OsStr>,
V: AsRef<OsStr>,
{
self.inner.envs(env);
self
}
pub fn current_dir(&mut self, cwd: impl AsRef<Path>) -> &mut Self {
let cwd = cwd.as_ref();
#[cfg(unix)]
{
self.saw_nul |= cwd.as_os_str().as_encoded_bytes().contains(&0);
}
self.inner.current_dir(cwd);
self
}
pub fn process_mode(&mut self, mode: ProcessMode) -> &mut Self {
self.process_mode = mode;
self
}
/// Choose who owns termination when the child handle is dropped.
pub(crate) fn drop_policy(&mut self, policy: ChildDropPolicy) -> &mut Self {
self.drop_policy = policy;
self.inner.kill_on_drop(match policy {
ChildDropPolicy::KillAndReap => true,
ChildDropPolicy::ReapOnly => false,
});
self
}
pub fn stdin(&mut self, stdin: ChildStdin) -> &mut Self {
self.stdin = stdin;
self
}
/// Supply the child endpoint of a Windows output pipe.
#[cfg(windows)]
pub fn stdout_handle(&mut self, handle: std::os::windows::io::OwnedHandle) -> &mut Self {
self.inner.stdout(TokioStdio::from(handle));
self
}
/// Supply the child endpoint of a Windows diagnostic pipe.
#[cfg(windows)]
pub fn stderr_handle(&mut self, handle: std::os::windows::io::OwnedHandle) -> &mut Self {
self.inner.stderr(TokioStdio::from(handle));
self
}
pub fn descriptor_policy(&mut self, policy: DescriptorPolicy) -> &mut Self {
self.descriptor_policy = policy;
self
}
pub fn fallback(&mut self, fallback: SpawnFallback) -> &mut Self {
self.fallback = fallback;
self
}
/// Preserve live inheritable descriptors at their existing numbers.
/// The caller must keep them open until spawning returns. We do not duplicate
/// or close them: closing even a duplicate releases the parent's POSIX record
/// locks. Closed and CLOEXEC descriptors remain excluded.
#[cfg(unix)]
pub fn preserve_fds(&mut self, fds: &[std::os::fd::RawFd]) -> &mut Self {
self.inherited_fds = fds
.iter()
.copied()
.filter(|fd| {
// SAFETY: fcntl reports invalid descriptors without dereferencing memory.
let flags = unsafe { libc::fcntl(*fd, libc::F_GETFD) };
*fd > libc::STDERR_FILENO && flags >= 0 && flags & libc::FD_CLOEXEC == 0
})
.collect();
self
}
/// Explicit launch attachments, including CLOEXEC descriptors. The caller
/// owns them through spawn; only the child's flags are changed.
#[cfg(unix)]
pub(crate) fn inherit_fds(&mut self, fds: &[std::os::fd::RawFd]) -> &mut Self {
self.inherited_fds = fds.to_vec();
self
}
/// Keep the existing Linux pipe behavior when the spawning parent exits.
#[cfg(target_os = "linux")]
pub fn terminate_on_parent_death(&mut self) -> &mut Self {
// SAFETY: getpid has no preconditions.
self.parent_pid = Some(unsafe { libc::getpid() });
self
}
#[cfg(unix)]
pub fn arg0(&mut self, arg0: impl AsRef<OsStr>) -> &mut Self {
self.saw_nul |= arg0.as_ref().as_encoded_bytes().contains(&0);
self.inner.arg0(arg0.as_ref());
self.arg0 = Some(arg0.as_ref().to_owned());
self
}
/// Preserve Job Object assignment before the child begins executing on Windows.
#[cfg(windows)]
pub fn prepare_suspended_spawn(&mut self, job: &crate::JobObject) {
job.prepare_suspended_spawn(&mut self.inner);
}
/// Reject original inputs that std replaced with a NUL-free placeholder.
#[cfg(unix)]
pub(crate) fn validate(&self) -> io::Result<()> {
if self.saw_nul {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"nul byte found in provided data",
));
}
Ok(())
}
/// Launch with native platform settings and the existing compatibility fallback.
pub fn spawn(mut self) -> io::Result<Child> {
#[cfg(unix)]
self.validate()?;
#[cfg(unix)]
if let ProcessMode::NewGroup = self.process_mode {
self.inner.process_group(/*pgroup*/ 0);
}
#[cfg(any(target_os = "macos", target_os = "linux"))]
{
let command = self.inner.as_std();
let program = command.get_program();
#[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();
#[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::posix::NativeChild::spawn(&self)?
{
return Ok(child);
}
}
self.inner.stdin(match self.stdin {
ChildStdin::Piped => TokioStdio::piped(),
ChildStdin::Null => TokioStdio::null(),
#[cfg(unix)]
ChildStdin::File(fd) => TokioStdio::from(fd),
#[cfg(windows)]
ChildStdin::File(handle) => TokioStdio::from(handle),
});
#[cfg(unix)]
{
let new_session = matches!(self.process_mode, ProcessMode::NewSession);
let explicit_fds = self.descriptor_policy == DescriptorPolicy::Explicit;
let targets = self.inherited_fds;
#[cfg(target_os = "linux")]
let parent_pid = self.parent_pid;
#[cfg(not(target_os = "linux"))]
let parent_pid: Option<i32> = None;
if new_session || explicit_fds || !targets.is_empty() || parent_pid.is_some() {
// SAFETY: The caller keeps the selected descriptors open. Session
// and parent-death setup use system calls; Linux and macOS cleanup
// avoid allocation after fork. Other Unix targets have an
// allocation-after-fork risk documented on close_inherited_fds_except.
unsafe {
self.inner.pre_exec(move || {
if new_session {
crate::process_group::detach_from_tty()?;
}
if let Some(parent_pid) = parent_pid {
crate::process_group::set_parent_death_signal(parent_pid)?;
}
if explicit_fds {
crate::pty::close_inherited_fds_except(&targets);
}
crate::pty::make_fds_inheritable(&targets)?;
Ok(())
});
}
}
}
#[cfg(unix)]
{
if let Some(fd) = self.stdout_file {
self.inner.stdout(TokioStdio::from(fd));
}
if let Some(fd) = self.stderr_file {
self.inner.stderr(TokioStdio::from(fd));
}
}
#[cfg(unix)]
let reaper = match self.drop_policy {
ChildDropPolicy::KillAndReap => None,
ChildDropPolicy::ReapOnly => Some(crate::child::reaper::sender()?),
};
let mut child = self.inner.spawn()?;
Ok(Child {
stdin: child.stdin.take(),
stdout: child.stdout.take(),
stderr: child.stderr.take(),
inner: {
#[cfg(unix)]
{
match reaper {
Some(reaper) => ChildKind::TokioReapOnly {
child: Some(child),
reaper,
},
None => ChildKind::Tokio(child),
}
}
#[cfg(not(unix))]
ChildKind::Tokio(child)
},
})
}
}
#[cfg(all(test, unix))]
#[path = "command_validation_tests.rs"]
mod validation_tests;
#[cfg(all(test, target_os = "macos"))]
#[path = "macos_child_tests.rs"]
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;

View File

@@ -0,0 +1,68 @@
//! Runtime-independent cleanup for children whose termination is externally owned.
//!
//! Initialize the shared worker before launch so dropping a live child never
//! creates a thread or waits for its exit. Poll only transferred PIDs, retaining
//! ownership until reaped, so one live child cannot delay cleanup of another.
use std::io;
#[cfg(any(target_os = "macos", target_os = "linux"))]
use std::ptr;
use std::sync::Mutex;
use std::sync::PoisonError;
use std::sync::mpsc;
use std::time::Duration;
/// Exclusive ownership transferred by a child handle after its caller drops it.
pub(crate) enum ChildToReap {
#[cfg(any(target_os = "macos", target_os = "linux"))]
Native(libc::pid_t),
Tokio(tokio::process::Child),
}
static REAPER: Mutex<Option<mpsc::Sender<ChildToReap>>> = Mutex::new(None);
const REAP_BATCH_SIZE: usize = 64;
/// Reserve the shared reaper, returning thread creation failures before launch.
pub(crate) fn sender() -> io::Result<mpsc::Sender<ChildToReap>> {
let mut reaper = REAPER.lock().unwrap_or_else(PoisonError::into_inner);
if let Some(sender) = &*reaper {
return Ok(sender.clone());
}
let (sender, receiver) = mpsc::channel();
std::thread::Builder::new()
.name("codex-child-reaper".into())
.spawn(move || {
let mut pending = Vec::new();
loop {
if pending.is_empty() {
let Ok(pid) = receiver.recv() else { return };
pending.push(pid);
} else {
match receiver.recv_timeout(Duration::from_millis(10)) {
Ok(pid) => pending.push(pid),
Err(mpsc::RecvTimeoutError::Timeout) => {}
Err(mpsc::RecvTimeoutError::Disconnected) => return,
}
}
// 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(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) };
result == 0
|| (result == -1
&& io::Error::last_os_error().kind() == io::ErrorKind::Interrupted)
}
ChildToReap::Tokio(child) => match child.try_wait() {
Ok(None) => true,
Ok(Some(_)) => false,
Err(error) => error.kind() == io::ErrorKind::Interrupted,
},
});
}
})?;
*reaper = Some(sender.clone());
Ok(sender)
}

View File

@@ -0,0 +1,400 @@
//! Regression coverage for child descriptors, process modes, and runtime-independent reaping.
use std::future::Future;
use std::future::poll_fn;
use std::os::fd::AsRawFd;
use std::os::unix::process::ExitStatusExt;
use std::task::Poll;
use std::time::Duration;
use pretty_assertions::assert_eq;
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<()> {
let mut command = Command::new("/bin/sh");
command.args(["-c", "exec 1>&- 2>&-; read -r line"]);
let mut child = command.spawn()?;
let mut stdin = child.stdin.take().ok_or_else(|| anyhow::anyhow!("stdin"))?;
let stdout = child
.stdout
.as_mut()
.ok_or_else(|| anyhow::anyhow!("stdout"))?;
let stderr = child
.stderr
.as_mut()
.ok_or_else(|| anyhow::anyhow!("stderr"))?;
let fds = [stdout.as_raw_fd(), stderr.as_raw_fd()];
// Cache EOF readiness on both pipes while stdin keeps the child alive.
let mut byte = [0];
assert_eq!(
tokio::time::timeout(Duration::from_secs(5), stdout.read(&mut byte)).await??,
0
);
assert_eq!(
tokio::time::timeout(Duration::from_secs(5), stderr.read(&mut byte)).await??,
0
);
let output = child.wait_with_output();
tokio::pin!(output);
poll_fn(|cx| {
assert!(output.as_mut().poll(cx).is_pending());
Poll::Ready(())
})
.await;
for fd in fds {
// SAFETY: F_GETFD only inspects the descriptor; it does not modify it.
assert_ne!(
unsafe { libc::fcntl(fd, libc::F_GETFD) },
-1,
"EOF pipe closed before child exit"
);
}
stdin.write_all(b"exit\n").await?;
assert_eq!(
tokio::time::timeout(Duration::from_secs(5), output).await??,
std::process::Output {
status: std::process::ExitStatus::from_raw(0),
stdout: Vec::new(),
stderr: Vec::new(),
}
);
Ok(())
}
#[test]
fn non_killing_drop_reaps_after_runtime_shutdown() -> anyhow::Result<()> {
use crate::child_command::ChildDropPolicy;
use std::time::Duration;
if std::env::var_os("CODEX_TEST_ISOLATED_REAPER").is_none() {
// Other Tokio tests must not drain this process's global orphan queue.
let output = std::process::Command::new(std::env::current_exe()?)
.args([
"--exact",
"child::tests::non_killing_drop_reaps_after_runtime_shutdown",
"--nocapture",
])
.env("CODEX_TEST_ISOLATED_REAPER", "1")
.output()?;
assert!(
output.status.success(),
"isolated reaper test failed:\n{}\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr),
);
return Ok(());
}
for program in ["cat", "/bin/cat"] {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()?;
let mut child = runtime.block_on(async {
let mut command = crate::Command::new(program);
command.drop_policy(ChildDropPolicy::ReapOnly);
command.spawn()
})?;
let stdin = child.stdin.take();
let pid = child.id().expect("live PID");
let next = runtime.block_on(async {
let mut command = crate::Command::new(program);
command.drop_policy(ChildDropPolicy::ReapOnly);
command.spawn()
})?;
let next_pid = next.id().expect("live PID");
drop(runtime);
drop(child);
drop(next);
// The shared reaper must collect the second child while the first remains alive.
wait_until_reaped(next_pid)?;
// Keep stdin open: cat must remain alive even after its owner and runtime go away.
std::thread::sleep(Duration::from_millis(50));
let mut info = std::mem::MaybeUninit::<libc::siginfo_t>::zeroed();
// SAFETY: waitid only observes our child without reaping it, with writable storage.
assert_eq!(
unsafe {
libc::waitid(
libc::P_PID,
pid,
info.as_mut_ptr(),
libc::WEXITED | libc::WNOHANG | libc::WNOWAIT,
)
},
0
);
// SAFETY: waitid succeeded and initialized the zeroed signal information.
assert_eq!(unsafe { info.assume_init().si_pid() }, 0);
drop(stdin);
wait_until_reaped(pid)?;
}
Ok(())
}
fn wait_until_reaped(pid: u32) -> anyhow::Result<()> {
use std::io;
use std::time::Duration;
let mut info = std::mem::MaybeUninit::<libc::siginfo_t>::zeroed();
let deadline = std::time::Instant::now() + Duration::from_secs(5);
loop {
// SAFETY: WNOWAIT prevents the test from stealing the reaper's child.
if unsafe {
libc::waitid(
libc::P_PID,
pid,
info.as_mut_ptr(),
libc::WEXITED | libc::WNOHANG | libc::WNOWAIT,
)
} == -1
{
assert_eq!(
io::Error::last_os_error().raw_os_error(),
Some(libc::ECHILD)
);
break;
}
anyhow::ensure!(std::time::Instant::now() < deadline, "child was not reaped");
std::thread::sleep(Duration::from_millis(10));
}
Ok(())
}
#[tokio::test]
async fn preserved_descriptor_can_use_the_last_slot_below_the_limit() -> anyhow::Result<()> {
use std::os::fd::AsRawFd;
use std::os::fd::FromRawFd;
if std::env::var_os("CODEX_TEST_ISOLATED_FD_LIMIT").is_none() {
let output = std::process::Command::new(std::env::current_exe()?)
.args([
"--exact",
"child::tests::preserved_descriptor_can_use_the_last_slot_below_the_limit",
"--nocapture",
])
.env("CODEX_TEST_ISOLATED_FD_LIMIT", "1")
.output()?;
assert!(output.status.success(), "{output:?}");
return Ok(());
}
// Use a known, small limit without changing other tests' process-wide limit.
let mut limit = std::mem::MaybeUninit::<libc::rlimit>::uninit();
// SAFETY: getrlimit initializes writable storage.
assert_eq!(
unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, limit.as_mut_ptr()) },
0
);
// SAFETY: getrlimit succeeded.
let mut limit = unsafe { limit.assume_init() };
limit.rlim_cur = limit.rlim_cur.min(256);
// SAFETY: Only this isolated test process's soft limit is lowered.
assert_eq!(unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, &limit) }, 0);
let last = i32::try_from(limit.rlim_cur - 1)?;
let root = tempfile::tempdir()?;
let path = root.path().join("input");
std::fs::write(&path, "preserved")?;
let source = std::fs::File::open(path)?;
let fd = unsafe { libc::fcntl(source.as_raw_fd(), libc::F_DUPFD_CLOEXEC, last) };
anyhow::ensure!(fd == last, "could not reserve the last descriptor slot");
let fd = unsafe { std::os::fd::OwnedFd::from_raw_fd(fd) };
assert_eq!(unsafe { libc::fcntl(fd.as_raw_fd(), libc::F_SETFD, 0) }, 0);
let mut command = crate::Command::new("/bin/cat");
command
.arg(format!("/dev/fd/{last}"))
.stdin(crate::ChildStdin::Null)
.descriptor_policy(crate::DescriptorPolicy::Explicit)
.preserve_fds(&[last]);
let output = command.spawn()?.wait_with_output().await?;
assert!(output.status.success(), "{output:?}");
assert_eq!(output.stdout, b"preserved");
Ok(())
}
#[tokio::test]
async fn process_mode_is_preserved_by_both_backends() -> anyhow::Result<()> {
use crate::ProcessMode;
let root = tempfile::tempdir()?;
std::os::unix::fs::symlink("/bin/cat", root.path().join("server"))?;
let script = root.path().join("executable-text");
codex_utils_cargo_bin::write_executable(&script, "exec /bin/cat\n")?;
for program in ["./server", "/bin/cat", "./executable-text"] {
for mode in [
ProcessMode::Inherit,
ProcessMode::NewGroup,
ProcessMode::NewSession,
] {
let mut command = Command::new(program);
command.current_dir(root.path()).process_mode(mode);
let mut child = match command.spawn() {
Ok(child) => child,
Err(error) if program == "./executable-text" => {
// Executable-text fallback depends on both libc and std's
// spawn backend. Compare the same mode with std directly.
let mut baseline = tokio::process::Command::new(program);
baseline
.current_dir(root.path())
.env_clear()
.kill_on_drop(true);
match mode {
ProcessMode::Inherit => {}
ProcessMode::NewGroup => {
baseline.process_group(/*pgroup*/ 0);
}
ProcessMode::NewSession => {
// SAFETY: Session setup is async-signal-safe.
unsafe {
baseline.pre_exec(crate::process_group::detach_from_tty);
}
}
}
let expected = baseline
.spawn()
.expect_err("legacy spawn must also reject executable text");
assert_eq!(error.raw_os_error(), expected.raw_os_error());
continue;
}
Err(error) => return Err(error.into()),
};
let pid = child.id().expect("live PID") as libc::pid_t;
// SAFETY: These calls only inspect the current process.
let (parent_group, parent_session) = unsafe { (libc::getpgrp(), libc::getsid(0)) };
let expected = match mode {
ProcessMode::Inherit => (parent_group, parent_session),
ProcessMode::NewGroup => (pid, parent_session),
ProcessMode::NewSession => (pid, pid),
};
// SAFETY: The child is still owned and blocked on its stdin pipe.
assert_eq!(unsafe { (libc::getpgid(pid), libc::getsid(pid)) }, expected);
child.kill().await?;
}
}
Ok(())
}
#[tokio::test]
async fn preserving_descriptors_keeps_parent_record_locks() -> anyhow::Result<()> {
use std::io::Read;
if let Some(path) = std::env::var_os("CODEX_TEST_RECORD_LOCK") {
// Wait until spawn has returned and dropped the parent's command.
std::io::stdin().read_exact(&mut [0])?;
let file = std::fs::OpenOptions::new().write(true).open(path)?;
// SAFETY: A zeroed flock with these fields describes the whole file.
let mut lock: libc::flock = unsafe { std::mem::zeroed() };
lock.l_type = libc::F_WRLCK as _;
lock.l_whence = libc::SEEK_SET as _;
assert_eq!(
unsafe { libc::fcntl(file.as_raw_fd(), libc::F_SETLK, &lock) },
-1
);
assert!(matches!(
std::io::Error::last_os_error().raw_os_error(),
Some(libc::EACCES | libc::EAGAIN)
));
return Ok(());
}
let file = tempfile::NamedTempFile::new()?;
// SAFETY: The descriptor remains owned and open throughout the launch.
assert_eq!(
unsafe { libc::fcntl(file.as_raw_fd(), libc::F_SETFD, 0) },
0
);
let mut lock: libc::flock = unsafe { std::mem::zeroed() };
lock.l_type = libc::F_WRLCK as _;
lock.l_whence = libc::SEEK_SET as _;
assert_eq!(
unsafe { libc::fcntl(file.as_raw_fd(), libc::F_SETLK, &lock) },
0
);
let mut command = Command::new(std::env::current_exe()?);
command
.args([
"--exact",
"child::tests::preserving_descriptors_keeps_parent_record_locks",
"--nocapture",
])
.env("CODEX_TEST_RECORD_LOCK", file.path())
.descriptor_policy(crate::DescriptorPolicy::Explicit)
.preserve_fds(&[file.as_raw_fd()]);
let mut child = command.spawn()?;
child
.stdin
.take()
.expect("piped stdin")
.write_all(b"x")
.await?;
let output = child.wait_with_output().await?;
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<()> {
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);
codex_utils_cargo_bin::write_executable(&program, "printf '%s' \"$1\"")?;
// 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(())
}

View File

@@ -0,0 +1,126 @@
//! Invalid command inputs must fail before a child can run on either backend.
use std::io;
use pretty_assertions::assert_eq;
use crate::Command;
use crate::ProcessMode;
enum Input {
Program,
Arg,
Args,
Cwd,
Arg0,
EnvKey,
EnvValue,
}
#[tokio::test]
async fn embedded_nul_is_rejected_before_spawning() -> anyhow::Result<()> {
for mode in [ProcessMode::Inherit, ProcessMode::NewSession] {
for input in [
Input::Program,
Input::Arg,
Input::Args,
Input::Cwd,
Input::Arg0,
Input::EnvKey,
Input::EnvValue,
] {
let root = tempfile::tempdir()?;
let marker = root.path().join("ran");
let mut command = Command::new(match input {
Input::Program => "/bin/sh\0",
Input::Arg
| Input::Args
| Input::Cwd
| Input::Arg0
| Input::EnvKey
| Input::EnvValue => "/bin/sh",
});
command
.process_mode(mode)
.args(["-c", "printf ran > \"$1\"", "sh"])
.arg(&marker);
match input {
Input::Program => {}
Input::Arg => {
command.arg("bad\0arg");
}
Input::Args => {
command.args(["bad\0arg"]);
}
Input::Cwd => {
command.current_dir("bad\0cwd").current_dir(root.path());
}
Input::Arg0 => {
command.arg0("bad\0arg0").arg0("sh");
}
Input::EnvKey => {
command.env("bad\0key", "value");
}
Input::EnvValue => {
command.env("key", "bad\0value");
}
}
let error = match command.spawn() {
Err(error) => error,
Ok(child) => {
let output = child.wait_with_output().await?;
anyhow::bail!(
"invalid command ran: {output:?}, marker={}",
marker.exists()
);
}
};
assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
assert!(!marker.exists());
}
}
Ok(())
}
#[tokio::test]
async fn literal_nul_placeholder_is_a_valid_argument() -> anyhow::Result<()> {
let mut command = Command::new("/bin/echo");
command
.process_mode(ProcessMode::NewSession)
.arg("<string-with-nul>");
let output = command.spawn()?.wait_with_output().await?;
assert!(output.status.success());
assert_eq!(output.stdout, b"<string-with-nul>\n");
Ok(())
}
#[tokio::test]
async fn pipe_rejects_nul_arguments_without_side_effects() -> anyhow::Result<()> {
let root = tempfile::tempdir()?;
let marker = root.path().join("ran");
let result = crate::spawn_pipe_process(
"/usr/bin/touch",
&[
marker.to_string_lossy().into_owned(),
"bad\0arg".to_string(),
],
root.path(),
&std::collections::HashMap::new(),
/*arg0*/ &None,
&[],
)
.await;
let error = match result {
Err(error) => error,
Ok(child) => {
let _ = child.exit_rx.await;
anyhow::bail!("invalid pipe command ran, marker={}", marker.exists());
}
};
assert_eq!(
error.downcast_ref::<io::Error>().map(io::Error::kind),
Some(io::ErrorKind::InvalidInput)
);
assert!(!marker.exists());
Ok(())
}

View File

@@ -0,0 +1,70 @@
mod child;
pub use child::Child;
mod child_command;
pub use child_command::ChildStdin;
pub use child_command::Command;
pub use child_command::DescriptorPolicy;
pub use child_command::ProcessMode;
pub use child_command::SpawnFallback;
#[cfg(target_os = "linux")]
mod linux_fds;
pub mod pipe;
mod process;
pub mod process_group;
pub mod pty;
pub use pty::ChildFds;
#[cfg(test)]
mod tests;
#[cfg(unix)]
mod unix_io;
#[cfg(windows)]
mod win;
#[cfg(windows)]
mod windows_input;
pub const DEFAULT_OUTPUT_BYTES_CAP: usize = 1024 * 1024;
/// Spawn a non-interactive process using regular pipes for stdin/stdout/stderr.
pub use pipe::spawn_process as spawn_pipe_process;
/// Spawn a non-interactive process using regular pipes, but close stdin immediately.
pub use pipe::spawn_process_no_stdin as spawn_pipe_process_no_stdin;
/// Driver-backed process adapter used by integrations with their own process transport.
pub use process::ProcessDriver;
/// Handle for interacting with a spawned process (PTY or pipe).
pub use process::ProcessHandle;
/// Process signal supported by spawned-process handles.
pub use process::ProcessSignal;
/// Bundle of process handles plus split output and exit receivers returned by spawn helpers.
pub use process::SpawnedProcess;
/// Terminal size in character cells used for PTY spawn and resize operations.
pub use process::TerminalSize;
/// Combine stdout/stderr receivers into a single broadcast receiver.
pub use process::combine_output_receivers;
/// Adapt an externally-driven process into the standard spawned-process handle.
pub use process::spawn_from_driver;
/// Backwards-compatible alias for ProcessHandle.
pub type ExecCommandSession = ProcessHandle;
/// Backwards-compatible alias for SpawnedProcess.
pub type SpawnedPty = SpawnedProcess;
/// Report whether ConPTY is available on this platform (Windows only).
pub use pty::conpty_supported;
/// Spawn a process attached to a PTY for interactive use.
pub use pty::spawn_process as spawn_pty_process;
#[cfg(windows)]
pub use win::JobObject;
#[cfg(windows)]
pub use win::PsuedoCon;
#[cfg(windows)]
pub use win::conpty::RawConPty;
#[cfg(windows)]
pub use windows_input::WindowsTtyInputNormalizer;
#[cfg(target_os = "linux")]
mod spawn_helper;
#[cfg(target_os = "linux")]
mod spawn_helper_main;
#[cfg(target_os = "linux")]
pub use spawn_helper::init_spawn_helper;
#[cfg(all(test, target_os = "linux"))]
use tests::spawn_helper_tests;

View File

@@ -0,0 +1,59 @@
//! Linux executable lookup must match the compatibility launcher's PATH semantics.
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");
codex_utils_cargo_bin::write_executable(&script, "#!/bin/sh\nprintf later\n")?;
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");
codex_utils_cargo_bin::write_executable(&script, "#!/bin/sh\nprintf '%s' \"$0\"\n")?;
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(())
}

View File

@@ -0,0 +1,129 @@
//! Linux descriptor cleanup after fork, using only stack storage and syscalls.
//! Stdio and explicitly preserved FDs remain usable. CLOEXEC keeps Rust's
//! spawn-error channel alive until exec succeeds. Cleanup is best-effort:
//! failures do not prevent launch and may leave unrelated descriptors inherited.
use std::ffi::CStr;
use std::io;
use std::os::fd::RawFd;
pub(crate) fn close_inherited_fds_except(preserved_fds: &[RawFd]) {
// Mark rather than close: std::process still needs its CLOEXEC error
// pipe if exec fails. Do not alter flags on explicitly preserved FDs.
let mut first = 3_u32;
loop {
// The keep-list need not be sorted. Walking its gaps leaves each kept
// FD's flags untouched, without allocating a sorted copy after fork.
let next = preserved_fds
.iter()
.copied()
.filter_map(|fd| u32::try_from(fd).ok())
.filter(|&fd| fd >= first)
.min();
let last = next.map_or(u32::MAX, |fd| fd - 1);
if first <= last
// SAFETY: close_range has no pointers and changes only this child's FDs.
&& unsafe {
libc::syscall(
libc::SYS_close_range,
first,
last,
libc::CLOSE_RANGE_CLOEXEC,
)
} != 0
{
break;
}
match next {
Some(fd) => first = fd + 1,
None => return,
}
}
// Older kernels (or seccomp policies) may reject close_range. Read
// this child's descriptor table without libc's allocating DIR API.
// Preserve best-effort launch behavior if the fallback also fails. Logging
// here could allocate or lock after fork; writing to child stderr may block.
close_from_proc(preserved_fds);
}
fn mark_cloexec(fd: RawFd, preserved_fds: &[RawFd]) {
if fd <= libc::STDERR_FILENO || preserved_fds.contains(&fd) {
return;
}
// SAFETY: fcntl operates on the child's descriptors without allocating.
let flags = unsafe { libc::fcntl(fd, libc::F_GETFD) };
if flags == -1 {
return;
}
if flags & libc::FD_CLOEXEC == 0 {
// SAFETY: only adds CLOEXEC; existing flags and the descriptor remain intact.
unsafe { libc::fcntl(fd, libc::F_SETFD, flags | libc::FD_CLOEXEC) };
}
}
fn close_from_proc(preserved_fds: &[RawFd]) {
use std::os::fd::AsRawFd;
use std::os::fd::FromRawFd;
use std::os::fd::OwnedFd;
// Open after fork: a proc directory opened in the parent would enumerate
// the parent's changing descriptor table instead of this child's snapshot.
// SAFETY: the path is NUL-terminated and open does not allocate.
let raw = unsafe {
libc::open(
c"/proc/self/fd".as_ptr(),
libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC,
)
};
if raw == -1 {
return;
}
// SAFETY: open returned a new owned descriptor; dropping it only calls close.
let directory = unsafe { OwnedFd::from_raw_fd(raw) };
let mut buffer = [0_u8; 4096];
loop {
// SAFETY: getdents64 writes at most buffer.len() bytes into stack storage.
let count = unsafe {
libc::syscall(
libc::SYS_getdents64,
directory.as_raw_fd(),
buffer.as_mut_ptr(),
buffer.len(),
)
};
if count == -1 {
if io::Error::last_os_error().raw_os_error() == Some(libc::EINTR) {
continue;
}
return;
}
if count == 0 {
return;
}
let mut entries = &buffer[..count as usize];
// Linux getdents64 records have two 64-bit fields, a u16 record length,
// one type byte, then the NUL-terminated name (independent of libc ABI).
while !entries.is_empty() {
if entries.len() < 20 {
return;
}
let length = u16::from_ne_bytes([entries[16], entries[17]]) as usize;
if length < 20 || length > entries.len() {
return;
}
if let Ok(name) = CStr::from_bytes_until_nul(&entries[19..length])
&& let Ok(name) = name.to_str()
&& let Ok(fd) = name.parse::<RawFd>()
{
// A failure on one descriptor must not prevent cleanup of
// the remaining descriptors.
mark_cloexec(fd, preserved_fds);
}
entries = &entries[length..];
}
}
}
#[cfg(test)]
#[path = "linux_fds_tests.rs"]
mod tests;

View File

@@ -0,0 +1,246 @@
//! Child-visible descriptor inheritance, fallback compatibility, and launch errors.
use std::io;
use std::io::Write;
use std::os::fd::AsRawFd;
use std::os::fd::FromRawFd;
use std::os::fd::OwnedFd;
use std::os::unix::process::CommandExt;
use std::os::unix::process::ExitStatusExt;
use std::process::Command;
use std::process::ExitStatus;
use std::process::Output;
use std::process::Stdio;
use anyhow::Context;
use pretty_assertions::assert_eq;
// Called only from pre_exec: reject one syscall in the child without changing
// the test runner's permissions or allocating memory after fork.
fn deny_syscall(syscall_number: libc::c_long) -> io::Result<()> {
let mut filter = [
libc::sock_filter {
code: (libc::BPF_LD | libc::BPF_W | libc::BPF_ABS) as _,
jt: 0,
jf: 0,
k: std::mem::offset_of!(libc::seccomp_data, nr) as _,
},
libc::sock_filter {
code: (libc::BPF_JMP | libc::BPF_JEQ | libc::BPF_K) as _,
jt: 0,
jf: 1,
k: syscall_number as _,
},
libc::sock_filter {
code: (libc::BPF_RET | libc::BPF_K) as _,
jt: 0,
jf: 0,
k: libc::SECCOMP_RET_ERRNO | libc::EPERM as u32,
},
libc::sock_filter {
code: (libc::BPF_RET | libc::BPF_K) as _,
jt: 0,
jf: 0,
k: libc::SECCOMP_RET_ALLOW,
},
];
let program = libc::sock_fprog {
len: filter.len() as _,
filter: filter.as_mut_ptr(),
};
// SAFETY: The kernel copies the stack-owned filter before prctl returns.
unsafe {
if libc::prctl(
libc::PR_SET_NO_NEW_PRIVS,
1_usize,
0_usize,
0_usize,
0_usize,
) == -1
|| libc::prctl(
libc::PR_SET_SECCOMP,
libc::SECCOMP_MODE_FILTER as usize,
&raw const program,
0_usize,
0_usize,
) == -1
{
return Err(io::Error::last_os_error());
}
// Qualify failure injection. Invalid arguments make the probe harmless
// for close_range and getdents64 even if the filter is ineffective.
if libc::syscall(syscall_number, -1_isize, 0_usize, 0_usize) != -1
|| io::Error::last_os_error().raw_os_error() != Some(libc::EPERM)
{
return Err(io::Error::from_raw_os_error(libc::EIO));
}
}
Ok(())
}
fn output_with_input(command: &mut Command) -> io::Result<Output> {
let mut child = command
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()?;
child
.stdin
.take()
.expect("piped stdin")
.write_all(b"stdio payload\n")?;
child.wait_with_output()
}
#[test]
fn cleanup_excludes_unrelated_fds_and_preserves_explicit_fds_and_stdio() -> anyhow::Result<()> {
let python = crate::tests::find_python().context("descriptor tests require Python")?;
let file = tempfile::tempfile()?;
// Model the occupied descriptor table of a parallel test runner.
let _occupied: Vec<_> = (0..64)
.map(|_| file.try_clone())
.collect::<io::Result<_>>()?;
// SAFETY: Reserve a low descriptor without replacing another owner.
let raw = unsafe { libc::fcntl(file.as_raw_fd(), libc::F_DUPFD_CLOEXEC, 3) };
anyhow::ensure!(raw != -1, "{}", io::Error::last_os_error());
// SAFETY: fcntl returned a new descriptor owned by this test.
let reservation = unsafe { OwnedFd::from_raw_fd(raw) };
let reserved_fd = reservation.as_raw_fd();
// Keep every sentinel above the limit even when the parent's low slots fill.
let minimum = (reserved_fd + 1).max(/*other*/ 200);
let mut descriptors = Vec::new();
for operation in [libc::F_DUPFD, libc::F_DUPFD, libc::F_DUPFD_CLOEXEC] {
// SAFETY: fcntl reserves a new high descriptor without replacing any existing owner.
let fd = unsafe { libc::fcntl(file.as_raw_fd(), operation, minimum) };
anyhow::ensure!(fd != -1, "{}", io::Error::last_os_error());
// SAFETY: The duplicate is newly owned by this test.
descriptors.push(unsafe { OwnedFd::from_raw_fd(fd) });
}
let fds: Vec<_> = descriptors.iter().map(AsRawFd::as_raw_fd).collect();
let command = || {
let mut command = Command::new(&python);
command
.arg("-c")
.arg(
r#"import errno, os, sys
inherited = []
for fd in map(int, sys.argv[1:]):
try:
os.fstat(fd)
inherited.append(True)
except OSError as error:
if error.errno != errno.EBADF: raise
inherited.append(False)
print(inherited)
print(sys.stdin.read(), end="")
print("stderr preserved", file=sys.stderr)
"#,
)
.args(fds.iter().map(ToString::to_string));
command
};
let expected = |inherited| Output {
status: ExitStatus::from_raw(/*raw*/ 0),
stdout: format!("{inherited}\nstdio payload\n").into_bytes(),
stderr: b"stderr preserved\n".to_vec(),
};
// Qualify the oracle: the executable itself must not sanitize inherited FDs.
assert_eq!(
output_with_input(&mut command())?,
expected("[True, True, False]")
);
for (name, force_fallback) in [("default", false), ("fallback above fd limit", true)] {
for preserved in [&[][..], &[fds[2], fds[1], fds[2]][..]] {
// Unsorted and repeated entries must preserve the same inheritance.
let allowlist = preserved.to_vec();
let mut command = command();
// SAFETY: The hook uses only preallocated data and fork-safe syscalls.
unsafe {
command.pre_exec(move || {
if force_fallback {
deny_syscall(libc::SYS_close_range)?;
// Leave a free slot for procfs below the lowered limit,
// even if parallel tests filled every other low slot.
let mut limit = libc::rlimit {
rlim_cur: 0,
rlim_max: 0,
};
if libc::close(reserved_fd) == -1
|| libc::getrlimit(libc::RLIMIT_NOFILE, &mut limit) == -1
{
return Err(io::Error::last_os_error());
}
limit.rlim_cur = reserved_fd as libc::rlim_t + 1;
if libc::setrlimit(libc::RLIMIT_NOFILE, &limit) == -1 {
return Err(io::Error::last_os_error());
}
}
crate::pty::close_inherited_fds_except(&allowlist);
Ok(())
});
}
let inheritance = if preserved.is_empty() {
"[False, False, False]"
} else {
"[False, True, False]"
};
assert_eq!(
output_with_input(&mut command)
.with_context(|| format!("{name}, allowlist {preserved:?}"))?,
expected(inheritance),
"{name}, allowlist {preserved:?}"
);
}
}
// The child must not mutate the parent's descriptors or inheritance flags.
let flags: Vec<_> = fds
.iter()
.map(|&fd| unsafe { libc::fcntl(fd, libc::F_GETFD) })
.collect();
assert_eq!(flags, [0, 0, libc::FD_CLOEXEC]);
Ok(())
}
#[test]
fn cleanup_fallback_preserves_exec_failure_reporting() -> anyhow::Result<()> {
let temporary = tempfile::tempdir()?;
let mut command = Command::new(temporary.path().join("does-not-exist"));
// SAFETY: The hook uses only stack storage and fork-safe syscalls in the child.
unsafe {
command.pre_exec(|| {
deny_syscall(libc::SYS_close_range)?;
crate::pty::close_inherited_fds_except(&[]);
Ok(())
});
}
let error = match command.spawn() {
Err(error) => error,
Ok(mut child) => {
child.wait()?;
anyhow::bail!("exec failure reported as success");
}
};
assert_eq!(error.raw_os_error(), Some(libc::ENOENT));
Ok(())
}
#[tokio::test]
async fn cleanup_failures_do_not_prevent_explicit_launch() -> anyhow::Result<()> {
let mut command = crate::Command::new("/bin/sh");
command
.args(["-c", "exit 42"])
.descriptor_policy(crate::DescriptorPolicy::Explicit);
// SAFETY: The hook only installs child-local syscall filters using stack
// storage. Command::spawn registers its real cleanup hook after this hook.
unsafe {
command.inner.pre_exec(|| {
deny_syscall(libc::SYS_close_range)?;
deny_syscall(libc::SYS_getdents64)
});
}
assert_eq!(
command.spawn()?.wait().await?,
ExitStatus::from_raw(/*raw*/ 42 << 8)
);
Ok(())
}

View File

@@ -0,0 +1,294 @@
//! Regression coverage for native spawn compatibility, descriptor inheritance, and reaping.
use super::*;
use crate::child::ChildKind;
use crate::child::posix::*;
use pretty_assertions::assert_eq;
use std::fs;
use std::os::fd::AsRawFd;
use std::os::fd::FromRawFd;
use std::os::fd::OwnedFd;
use std::os::unix::ffi::OsStrExt;
use std::os::unix::ffi::OsStringExt;
use std::os::unix::fs::symlink;
use std::os::unix::process::ExitStatusExt;
use std::ptr;
use std::time::Duration;
use tokio::io::AsyncReadExt;
use tokio::io::AsyncWriteExt;
async fn native_output(command: Command) -> anyhow::Result<std::process::Output> {
let child = command.spawn()?;
assert!(matches!(child.inner, ChildKind::Native(_)));
Ok(child.wait_with_output().await?)
}
#[tokio::test]
async fn bare_script_search_matches_child_path_and_preserves_script_spelling() -> anyhow::Result<()>
{
let root = tempfile::tempdir()?;
let program = std::ffi::OsString::from("server=é");
let bin = root.path().join("bin");
let blocked = root.path().join("blocked");
fs::create_dir(&bin)?;
fs::create_dir(&blocked)?;
fs::write(blocked.join(&program), "not executable")?;
let script = bin.join(&program);
codex_utils_cargo_bin::write_executable(
&script,
"#!/bin/sh\nprintf '%s\\n' \"$0\" \"$1\" \"$MCP_TEST\"; /bin/pwd; printf diagnostic >&2; exit 23\n",
)?;
symlink(&script, root.path().join(&program))?;
for path in [
bin.into_os_string(),
"bin/".into(),
"missing:blocked:bin".into(),
"missing:".into(),
"".into(),
] {
let mut command = Command::new(&program);
command
.current_dir(root.path())
.process_mode(ProcessMode::NewGroup)
.env("PATH", path)
.env("MCP_TEST", "kept")
.arg("spaces ; literal $arg");
let expected = command.inner.output().await?;
assert_eq!(native_output(command).await?, expected);
}
Ok(())
}
#[tokio::test]
async fn bare_executable_uses_default_path_and_preserves_argv0() -> anyhow::Result<()> {
let mut command = Command::new("sh");
command
.process_mode(ProcessMode::NewGroup)
.args(["-c", "printf '%s' \"$0\""]);
let expected = command.inner.output().await?;
assert_eq!(native_output(command).await?, expected);
Ok(())
}
#[tokio::test]
async fn relative_script_preserves_paths_stdio_environment_and_process_group() -> anyhow::Result<()>
{
let root = tempfile::tempdir()?;
fs::create_dir_all(root.path().join("actual/bin"))?;
symlink("actual/bin", root.path().join("link"))?;
let script = root.path().join("actual/server");
codex_utils_cargo_bin::write_executable(
&script,
"#!/bin/sh\nread -r input\nprintf '%s\\n' \"$0\" \"$1\" \"$2\" \"$MCP_TEST\" \"$input\"\nprintf diagnostic >&2\nexit 23\n",
)?;
let mut command = Command::new("./link/../server");
command
.current_dir(root.path())
.process_mode(ProcessMode::NewGroup)
.env("MCP_TEST", "kept")
.arg("spaces ; literal $arg")
.arg(std::ffi::OsString::from_vec(b"raw-\xff".to_vec()));
let mut child = NativeChild::spawn(&command)?.expect("native child");
let mut stdin = child.stdin.take();
let mut stdout = child.stdout.take().expect("piped stdout");
let mut stderr = child.stderr.take().expect("piped stderr");
let pid = child.id().expect("live PID") as libc::pid_t;
// SAFETY: getpgid only inspects the live child, which waits for input below.
assert_eq!(unsafe { libc::getpgid(pid) }, pid);
stdin
.as_mut()
.expect("piped stdin")
.write_all(b"hello\n")
.await?;
drop(stdin);
let mut output = Vec::new();
let mut diagnostic = String::new();
let (_, _, status) = tokio::try_join!(
stdout.read_to_end(&mut output),
stderr.read_to_string(&mut diagnostic),
child.wait()
)?;
assert_eq!(
(output.as_slice(), diagnostic.as_str(), status.code()),
(
b"./link/../server\nspaces ; literal $arg\nraw-\xff\nkept\nhello\n".as_slice(),
"diagnostic",
Some(23)
)
);
assert_eq!(child.wait().await?, status);
assert_eq!(child.id(), None);
Ok(())
}
#[tokio::test]
async fn native_executable_preserves_argv0() -> anyhow::Result<()> {
let root = tempfile::tempdir()?;
symlink("/bin/sh", root.path().join("shell"))?;
let program = Path::new("./shell");
let mut command = Command::new(program);
command
.current_dir(root.path())
.process_mode(ProcessMode::NewGroup)
.args(["-c", "printf '%s' \"$0\""]);
let mut child = NativeChild::spawn(&command)?.expect("native child");
let stdin = child.stdin.take();
let mut stdout = child.stdout.take().expect("piped stdout");
drop(stdin);
let mut output = Vec::new();
stdout.read_to_end(&mut output).await?;
assert!(child.wait().await?.success());
assert_eq!(output, program.as_os_str().as_bytes());
Ok(())
}
#[tokio::test]
async fn cancelled_wait_can_still_kill_and_reap_child() -> anyhow::Result<()> {
let root = tempfile::tempdir()?;
symlink("/bin/cat", root.path().join("server"))?;
let mut command = Command::new("./server");
command
.current_dir(root.path())
.process_mode(ProcessMode::NewGroup);
let mut child = NativeChild::spawn(&command)?.expect("native child");
let _stdin = child.stdin.take();
assert!(
tokio::time::timeout(Duration::from_millis(20), child.wait())
.await
.is_err()
);
child.kill().await?;
assert_eq!(child.wait().await?.signal(), Some(libc::SIGKILL));
assert_eq!(child.id(), None);
Ok(())
}
#[tokio::test]
async fn descriptor_inheritance_matches_command() -> anyhow::Result<()> {
let root = tempfile::tempdir()?;
symlink("/bin/sh", root.path().join("shell"))?;
let file = fs::File::open("/dev/null")?;
for (operation, expected) in [
(libc::F_DUPFD, "inherited"),
(libc::F_DUPFD_CLOEXEC, "closed"),
] {
// SAFETY: Duplicate a harmless descriptor with the requested inheritance flag.
let fd = unsafe { libc::fcntl(file.as_raw_fd(), operation, 200) };
assert!(fd >= 0);
// SAFETY: fcntl returned a new owned descriptor.
let _sentinel = unsafe { OwnedFd::from_raw_fd(fd) };
let mut command = Command::new("./shell");
command
.current_dir(root.path())
.process_mode(ProcessMode::NewGroup)
.env("SENTINEL", fd.to_string())
.args([
"-c",
"if [ -e /dev/fd/\"$SENTINEL\" ]; then printf inherited; else printf closed; fi",
]);
let mut child = NativeChild::spawn(&command)?.expect("native child");
let stdin = child.stdin.take();
let mut stdout = child.stdout.take().expect("piped stdout");
drop(stdin);
let mut output = String::new();
stdout.read_to_string(&mut output).await?;
assert!(child.wait().await?.success());
assert_eq!(output, expected);
assert_eq!(
command.inner.as_std_mut().output()?.stdout,
output.as_bytes()
);
}
Ok(())
}
#[tokio::test]
async fn launch_failures_preserve_os_errors() -> anyhow::Result<()> {
let root = tempfile::tempdir()?;
fs::write(root.path().join("not-executable"), "#!/bin/sh\nexit 0\n")?;
for (program, cwd, errno) in [
("./missing", root.path().to_path_buf(), libc::ENOENT),
("./not-executable", root.path().to_path_buf(), libc::EACCES),
("missing", root.path().to_path_buf(), libc::ENOENT),
("not-executable", root.path().to_path_buf(), libc::EACCES),
("", root.path().to_path_buf(), libc::ENOENT),
("/bin/sh", root.path().join("missing"), libc::ENOENT),
] {
let mut command = Command::new(program);
command
.process_mode(ProcessMode::NewGroup)
.env("PATH", root.path())
.current_dir(cwd);
let error = command.spawn().err().expect("spawn should fail");
assert_eq!(error.raw_os_error(), Some(errno));
}
Ok(())
}
#[tokio::test]
async fn executable_text_without_shebang_retains_command_fallback() -> anyhow::Result<()> {
let root = tempfile::tempdir()?;
let script = root.path().join("server");
codex_utils_cargo_bin::write_executable(&script, "printf '%s' \"$0\"\n")?;
for program in ["./server", "server"] {
let mut command = Command::new(program);
command
.current_dir(root.path())
.process_mode(ProcessMode::NewGroup)
.env("PATH", ".");
let mut child = command.spawn()?;
let mut output = Vec::new();
child
.stdout
.take()
.expect("piped stdout")
.read_to_end(&mut output)
.await?;
assert!(child.wait().await?.success());
assert_eq!(output, b"./server");
}
Ok(())
}
#[test]
fn dropping_after_runtime_shutdown_kills_and_reaps_child() -> anyhow::Result<()> {
let root = tempfile::tempdir()?;
symlink("/bin/cat", root.path().join("server"))?;
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()?;
let mut child = runtime
.block_on(async {
let mut command = Command::new("./server");
command
.current_dir(root.path())
.process_mode(ProcessMode::NewGroup);
NativeChild::spawn(&command)
})?
.expect("native child");
let stdin = child.stdin.take();
let pid = child.id().expect("live PID") as libc::pid_t;
drop(runtime);
drop(child);
drop(stdin);
let deadline = std::time::Instant::now() + Duration::from_secs(5);
loop {
// SAFETY: Signal zero probes existence without changing the process.
if unsafe { libc::kill(pid, 0) } == -1 {
assert_eq!(io::Error::last_os_error().raw_os_error(), Some(libc::ESRCH));
break;
}
anyhow::ensure!(std::time::Instant::now() < deadline, "child was not reaped");
std::thread::sleep(Duration::from_millis(10));
}
// SAFETY: WNOHANG verifies our drop reaper already collected this child.
assert_eq!(
unsafe { libc::waitpid(pid, ptr::null_mut(), libc::WNOHANG) },
-1
);
assert_eq!(
io::Error::last_os_error().raw_os_error(),
Some(libc::ECHILD)
);
Ok(())
}

View File

@@ -0,0 +1,218 @@
//! Native descriptor isolation, socket stdio, and launch errors.
use super::*;
use pretty_assertions::assert_eq;
use std::fs;
use std::io::Seek;
use std::os::fd::AsRawFd;
use std::os::fd::FromRawFd;
use std::os::fd::OwnedFd;
use std::os::unix::net::UnixStream;
use tokio::io::AsyncReadExt;
use tokio::io::AsyncWriteExt;
#[tokio::test]
async fn explicit_stdio_excludes_inheritable_descriptors_without_changing_parent()
-> anyhow::Result<()> {
let file = fs::File::open("/dev/null")?;
// SAFETY: Duplicate a live descriptor without CLOEXEC so the control inherits it.
let raw = unsafe { libc::fcntl(file.as_raw_fd(), libc::F_DUPFD, 200) };
assert!(raw >= 200);
// SAFETY: fcntl returned a new descriptor owned by this test.
let sentinel = unsafe { OwnedFd::from_raw_fd(raw) };
// SAFETY: The test owns this descriptor throughout both launches.
let flags = unsafe { libc::fcntl(raw, libc::F_GETFD) };
let script = format!("if [ -e /dev/fd/{raw} ]; then printf open; else printf closed; fi");
let mut control = Command::new("/bin/sh");
control.args(["-c", &script]);
let control = control.spawn()?.wait_with_output().await?;
assert_eq!(
(control.status.success(), control.stdout),
(true, b"open".to_vec())
);
let mut command = Command::new("/bin/sh");
command
.args(["-c", &script])
.descriptor_policy(DescriptorPolicy::Explicit);
let output = command.spawn()?.wait_with_output().await?;
assert_eq!(
(output.status.success(), output.stdout, output.stderr),
(true, b"closed".to_vec(), vec![])
);
// SAFETY: Spawning must not mutate the parent's descriptor flags.
assert_eq!(
unsafe { libc::fcntl(sentinel.as_raw_fd(), libc::F_GETFD) },
flags
);
Ok(())
}
#[tokio::test]
async fn socket_stdin_preserves_bidirectional_io_and_custom_argv0() -> anyhow::Result<()> {
let (parent, socket) = UnixStream::pair()?;
parent.set_nonblocking(true)?;
let mut parent = tokio::net::UnixStream::from_std(parent)?;
let mut command = Command::new("/bin/sh");
command
.args(["--norc", "-c", "IFS= read -r line; printf 'reply:%s\\n' \"$line\" >&0; printf '%s:%s:%s' \"$0\" \"$FS_TEST\" \"${HOME-unset}\"; printf diagnostic >&2; exit 19"])
.arg0("helper")
.env("FS_TEST", "literal ; $value")
.stdin(ChildStdin::File(socket.into()))
.descriptor_policy(DescriptorPolicy::Explicit)
.fallback(SpawnFallback::ReturnError);
let child = command.spawn()?;
assert!(child.stdin.is_none());
parent.write_all(b"socket\n").await?;
parent.shutdown().await?;
let mut reply = Vec::new();
parent.read_to_end(&mut reply).await?;
let output = child.wait_with_output().await?;
assert_eq!(reply, b"reply:socket\n");
assert_eq!(
(output.status.code(), output.stdout, output.stderr),
(
Some(19),
b"helper:literal ; $value:unset".to_vec(),
b"diagnostic".to_vec()
)
);
Ok(())
}
#[tokio::test]
async fn native_launch_can_reject_executable_text_without_shell_fallback() -> anyhow::Result<()> {
let directory = tempfile::tempdir()?;
let script = directory.path().join("no-shebang");
codex_utils_cargo_bin::write_executable(&script, "printf unexpected-fallback\n")?;
let mut command = Command::new(script);
command.fallback(SpawnFallback::ReturnError);
let error = command.spawn().err().expect("executable text must fail");
assert_eq!(error.raw_os_error(), Some(libc::ENOEXEC));
Ok(())
}
#[tokio::test]
async fn inherited_descriptors_survive_native_and_executable_text_spawns() -> anyhow::Result<()> {
let directory = tempfile::tempdir()?;
let data = directory.path().join("data");
fs::write(&data, "captured descriptor")?;
let mut file = fs::File::open(&data)?;
for native in [true, false] {
file.rewind()?;
// SAFETY: Duplicate this live file into a new inheritable descriptor.
let raw = unsafe { libc::fcntl(file.as_raw_fd(), libc::F_DUPFD, 100) };
assert!(raw >= 100);
// SAFETY: fcntl returned a newly owned descriptor.
let _original = unsafe { OwnedFd::from_raw_fd(raw) };
let descriptor = format!("/dev/fd/{raw}");
let mut command = if native {
let mut command = Command::new("/bin/cat");
command.arg(&descriptor);
command
} else {
let script = directory.path().join("executable-text");
codex_utils_cargo_bin::write_executable(&script, &format!("/bin/cat {descriptor}\n"))?;
Command::new(script)
};
command
.descriptor_policy(DescriptorPolicy::Explicit)
.preserve_fds(&[raw]);
let child = command.spawn()?;
assert_eq!(
matches!(child.inner, crate::child::ChildKind::Native(_)),
native
);
let output = child.wait_with_output().await?;
assert_eq!(
(output.status.code(), output.stdout, output.stderr),
(Some(0), b"captured descriptor".to_vec(), vec![])
);
}
Ok(())
}
#[tokio::test]
async fn high_stdio_descriptors_use_compatible_fallback() -> anyhow::Result<()> {
if std::env::var_os("CODEX_TEST_HIGH_STDIO_FDS").is_none() {
let output = std::process::Command::new(std::env::current_exe()?)
.args([
"--exact",
"child_command::descriptor_tests::high_stdio_descriptors_use_compatible_fallback",
"--nocapture",
])
.env("CODEX_TEST_HIGH_STDIO_FDS", "1")
.output()?;
assert!(output.status.success(), "{output:?}");
return Ok(());
}
let mut limit = std::mem::MaybeUninit::<libc::rlimit>::uninit();
// SAFETY: getrlimit initializes writable storage. Only this isolated test
// subprocess raises its soft limit; the test runner and host are unchanged.
assert_eq!(
unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, limit.as_mut_ptr()) },
0
);
let mut limit = unsafe { limit.assume_init() };
limit.rlim_cur = limit.rlim_cur.max(16_384);
assert_eq!(unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, &limit) }, 0);
let file = fs::File::open("/dev/null")?;
// SAFETY: Create a new inheritable descriptor to check fallback isolation.
let raw = unsafe { libc::fcntl(file.as_raw_fd(), libc::F_DUPFD, 3) };
anyhow::ensure!(raw >= 3, "{}", io::Error::last_os_error());
let sentinel = unsafe { OwnedFd::from_raw_fd(raw) };
let mut occupied = Vec::new();
loop {
let descriptor = file.try_clone()?;
let raw = descriptor.as_raw_fd();
occupied.push(descriptor);
// Darwin's spawn file actions reject valid descriptors >= OPEN_MAX
// (10240), even when RLIMIT_NOFILE allows the descriptor to be opened.
if raw >= 10_240 {
break;
}
}
let mut strict = Command::new("/usr/bin/true");
strict.fallback(SpawnFallback::ReturnError);
let error = strict
.spawn()
.err()
.expect("native high-fd action must fail");
assert_eq!(error.raw_os_error(), Some(libc::EBADF));
for mode in [ProcessMode::NewGroup, ProcessMode::NewSession] {
let mut command = Command::new("/bin/sh");
command
.args(["-c", &format!(
"test ! -e /dev/fd/{} || exit 99; IFS= read -r line; printf '%s' \"$line\"; printf diagnostic >&2; exit 23",
sentinel.as_raw_fd()
)])
.descriptor_policy(DescriptorPolicy::Explicit)
.process_mode(mode);
let mut child = command.spawn()?;
assert!(matches!(child.inner, ChildKind::Tokio(_)));
let pid = child.id().expect("live child") as libc::pid_t;
// SAFETY: The child waits for input and still owns this PID.
assert_eq!(unsafe { libc::getpgid(pid) }, pid);
child
.stdin
.take()
.expect("piped stdin")
.write_all(b"round trip\n")
.await?;
let output = child.wait_with_output().await?;
assert_eq!(
(output.status.code(), output.stdout, output.stderr),
(Some(23), b"round trip".to_vec(), b"diagnostic".to_vec())
);
}
// SAFETY: Child setup must not close or change the parent's descriptor.
assert_eq!(
unsafe { libc::fcntl(sentinel.as_raw_fd(), libc::F_GETFD) },
0
);
Ok(())
}

View File

@@ -0,0 +1,355 @@
//! Pipe I/O and process-tree ownership on top of the shared local child launcher.
use std::collections::HashMap;
use std::ffi::OsStr;
use std::io;
use std::io::ErrorKind;
use std::path::Path;
use std::sync::Arc;
use std::sync::Mutex as StdMutex;
use std::sync::atomic::AtomicBool;
use crate::ChildStdin;
use crate::Command;
#[cfg(unix)]
use crate::DescriptorPolicy;
#[cfg(unix)]
use crate::ProcessMode;
use crate::child_command::ChildDropPolicy;
use anyhow::Result;
use tokio::io::AsyncRead;
use tokio::io::AsyncReadExt;
use tokio::io::AsyncWriteExt;
use tokio::io::BufReader;
use tokio::sync::mpsc;
use tokio::sync::oneshot;
use tokio::task::JoinHandle;
use crate::process::ChildTerminator;
use crate::process::ProcessHandle;
use crate::process::ProcessSignal;
use crate::process::SpawnedProcess;
use crate::process::exit_code_from_status;
#[cfg(windows)]
enum WindowsChildTerminator {
Job(Arc<crate::win::JobObject>),
Process(u32),
}
struct PipeChildTerminator {
#[cfg(windows)]
windows: WindowsChildTerminator,
#[cfg(unix)]
process_group_id: u32,
}
impl ChildTerminator for PipeChildTerminator {
fn signal(&mut self, signal: ProcessSignal) -> io::Result<()> {
match signal {
ProcessSignal::Interrupt => {
#[cfg(unix)]
{
crate::process_group::interrupt_process_group(self.process_group_id)
}
#[cfg(windows)]
{
self.kill()
}
#[cfg(not(any(unix, windows)))]
{
Err(crate::process::unsupported_signal(signal))
}
}
}
}
fn kill(&mut self) -> io::Result<()> {
#[cfg(unix)]
{
crate::process_group::kill_process_group(self.process_group_id)
}
#[cfg(windows)]
{
match &self.windows {
WindowsChildTerminator::Job(job) => job.terminate(),
WindowsChildTerminator::Process(pid) => kill_process(*pid),
}
}
#[cfg(not(any(unix, windows)))]
{
Ok(())
}
}
}
#[cfg(windows)]
fn kill_process(pid: u32) -> io::Result<()> {
unsafe {
let handle = winapi::um::processthreadsapi::OpenProcess(
winapi::um::winnt::PROCESS_TERMINATE,
0,
pid,
);
if handle.is_null() {
return Err(io::Error::last_os_error());
}
let success = winapi::um::processthreadsapi::TerminateProcess(handle, 1);
let err = io::Error::last_os_error();
winapi::um::handleapi::CloseHandle(handle);
if success == 0 { Err(err) } else { Ok(()) }
}
}
async fn read_output_stream<R>(mut reader: R, output_tx: mpsc::Sender<Vec<u8>>)
where
R: AsyncRead + Unpin,
{
let mut buf = vec![0u8; 8_192];
loop {
match reader.read(&mut buf).await {
Ok(0) => break,
Ok(n) => {
let _ = output_tx.send(buf[..n].to_vec()).await;
}
Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
Err(_) => break,
}
}
}
#[derive(Clone, Copy)]
enum PipeStdinMode {
Piped,
Null,
}
/// On Windows, process-tree containment is best-effort because Tokio returns
/// only after the root process starts, so job assignment cannot be atomic.
async fn spawn_process_with_stdin_mode(
program: &OsStr,
args: &[String],
cwd: &Path,
env: &HashMap<String, String>,
arg0: &Option<String>,
stdin_mode: PipeStdinMode,
inherited_fds: &[i32],
) -> Result<SpawnedProcess> {
if program.is_empty() {
anyhow::bail!("missing program for pipe spawn");
}
#[cfg(not(unix))]
let _ = inherited_fds;
let mut command = Command::new(program);
#[cfg(unix)]
if let Some(arg0) = arg0 {
command.arg0(arg0);
}
#[cfg(unix)]
command
.process_mode(ProcessMode::NewSession)
.descriptor_policy(DescriptorPolicy::Explicit)
.inherit_fds(inherited_fds);
#[cfg(target_os = "linux")]
command.terminate_on_parent_death();
#[cfg(not(unix))]
let _ = arg0;
command
.current_dir(cwd)
.envs(env)
.args(args)
.drop_policy(ChildDropPolicy::ReapOnly)
.stdin(match stdin_mode {
PipeStdinMode::Piped => ChildStdin::Piped,
PipeStdinMode::Null => ChildStdin::Null,
});
#[cfg(windows)]
let job = crate::win::JobObject::create().map(Arc::new);
#[cfg(target_os = "linux")]
let mut child =
match crate::spawn_helper::spawn(&command, crate::spawn_helper::Setup::Pipe).await? {
Some(child) => child,
None => command.spawn()?,
};
#[cfg(not(target_os = "linux"))]
let mut child = command.spawn()?;
#[cfg(windows)]
let windows_terminator = {
// Accept the small race: a descendant created between spawn and
// assignment is not guaranteed to join the job and can escape termination.
let pid = child
.id()
.ok_or_else(|| io::Error::other("missing child pid"))?;
let assigned_job = job.and_then(|job| {
let crate::child::ChildKind::Tokio(child) = &child.inner;
let process_handle = child
.raw_handle()
.ok_or_else(|| io::Error::other("missing child process handle"))?;
job.assign_process(process_handle)?;
Ok(job)
});
match assigned_job {
Ok(job) => WindowsChildTerminator::Job(job),
Err(err) => {
log::warn!(
"Windows pipe process tree containment unavailable for pid {pid}: {err}"
);
WindowsChildTerminator::Process(pid)
}
}
};
#[cfg(unix)]
let process_group_id = child
.id()
.ok_or_else(|| io::Error::other("missing child pid"))?;
let stdin = child.stdin.take();
let stdout = child.stdout.take();
let stderr = child.stderr.take();
let (writer_tx, mut writer_rx) = mpsc::channel::<Vec<u8>>(128);
let (stdout_tx, stdout_rx) = mpsc::channel::<Vec<u8>>(128);
let (stderr_tx, stderr_rx) = mpsc::channel::<Vec<u8>>(128);
let writer_handle = if let Some(stdin) = stdin {
tokio::spawn(async move {
let mut writer = stdin;
while let Some(bytes) = writer_rx.recv().await {
let _ = writer.write_all(&bytes).await;
let _ = writer.flush().await;
}
})
} else {
drop(writer_rx);
tokio::spawn(async {})
};
let stdout_handle = stdout.map(|stdout| {
let stdout_tx = stdout_tx.clone();
tokio::spawn(async move {
read_output_stream(BufReader::new(stdout), stdout_tx).await;
})
});
let stderr_handle = stderr.map(|stderr| {
let stderr_tx = stderr_tx.clone();
tokio::spawn(async move {
read_output_stream(BufReader::new(stderr), stderr_tx).await;
})
});
let (exit_tx, exit_rx) = oneshot::channel::<i32>();
let exit_status = Arc::new(AtomicBool::new(false));
let wait_exit_status = Arc::clone(&exit_status);
let exit_code = Arc::new(StdMutex::new(None));
let wait_exit_code = Arc::clone(&exit_code);
#[cfg(windows)]
let wait_job = match &windows_terminator {
WindowsChildTerminator::Job(job) => Some(Arc::clone(job)),
WindowsChildTerminator::Process(_) => None,
};
let wait_handle: JoinHandle<()> = tokio::spawn(async move {
let code = match child.wait().await {
Ok(status) => {
#[cfg(windows)]
if let Some(job) = wait_job
&& let Err(err) = job.preserve_descendants()
{
log::warn!(
"Windows pipe failed to preserve descendants after root exit: {err}"
);
}
exit_code_from_status(status)
}
Err(_) => -1,
};
wait_exit_status.store(true, std::sync::atomic::Ordering::SeqCst);
if let Ok(mut guard) = wait_exit_code.lock() {
*guard = Some(code);
}
let _ = exit_tx.send(code);
});
let handle = ProcessHandle::new(
writer_tx,
Box::new(PipeChildTerminator {
#[cfg(windows)]
windows: windows_terminator,
#[cfg(unix)]
process_group_id,
}),
stdout_handle,
stderr_handle,
writer_handle,
wait_handle,
exit_status,
exit_code,
/*pty_handles*/ None,
/*resizer*/ None,
);
Ok(SpawnedProcess {
session: handle,
stdout_rx,
stderr_rx,
exit_rx,
})
}
/// Spawn a process using regular pipes and preserve selected inherited file
/// descriptors across exec on Unix. The executable path retains its native encoding.
pub async fn spawn_process(
program: impl AsRef<OsStr>,
args: &[String],
cwd: &Path,
env: &HashMap<String, String>,
arg0: &Option<String>,
inherited_fds: &[i32],
) -> Result<SpawnedProcess> {
spawn_process_with_stdin_mode(
program.as_ref(),
args,
cwd,
env,
arg0,
PipeStdinMode::Piped,
inherited_fds,
)
.await
}
/// Spawn a process using regular pipes, close stdin immediately, and preserve
/// selected inherited file descriptors across exec on Unix. The executable path
/// retains its native encoding.
pub async fn spawn_process_no_stdin(
program: impl AsRef<OsStr>,
args: &[String],
cwd: &Path,
env: &HashMap<String, String>,
arg0: &Option<String>,
inherited_fds: &[i32],
) -> Result<SpawnedProcess> {
spawn_process_with_stdin_mode(
program.as_ref(),
args,
cwd,
env,
arg0,
PipeStdinMode::Null,
inherited_fds,
)
.await
}
#[cfg(all(test, windows))]
#[path = "pipe_tests.rs"]
mod tests;
#[cfg(all(test, unix))]
#[path = "pipe_unix_tests.rs"]
mod unix_tests;

View File

@@ -0,0 +1,20 @@
use super::*;
use std::process::Stdio;
#[test]
fn process_fallback_interrupt_terminates_root() -> anyhow::Result<()> {
let mut child = std::process::Command::new("ping.exe")
.args(["-n", "60", "127.0.0.1"])
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()?;
let mut terminator = PipeChildTerminator {
windows: WindowsChildTerminator::Process(child.id()),
};
terminator.signal(ProcessSignal::Interrupt)?;
assert!(!child.wait()?.success());
Ok(())
}

View File

@@ -0,0 +1,137 @@
//! Pipe and PTY compatibility under inherited-descriptor pressure.
use std::collections::HashMap;
use std::io;
use std::io::Seek;
use std::os::fd::AsRawFd;
use std::os::fd::FromRawFd;
use std::os::fd::OwnedFd;
use std::path::Path;
use pretty_assertions::assert_eq;
#[tokio::test]
async fn descriptor_capture_pressure_falls_back_to_direct_spawn() -> anyhow::Result<()> {
if std::env::var_os("CODEX_TEST_PIPE_FD_PRESSURE").is_none() {
let output = std::process::Command::new(std::env::current_exe()?)
.args([
"--exact",
"pipe::unix_tests::descriptor_capture_pressure_falls_back_to_direct_spawn",
"--nocapture",
])
.env("CODEX_TEST_PIPE_FD_PRESSURE", "1")
.output()?;
assert!(output.status.success(), "{output:?}");
return Ok(());
}
let root = tempfile::tempdir()?;
let path = root.path().join("input");
std::fs::write(&path, "preserved")?;
let mut source = std::fs::File::open(path)?;
let descriptors = (0..17)
.map(|_| {
// SAFETY: fcntl duplicates a live source into a newly owned slot.
let fd = unsafe { libc::fcntl(source.as_raw_fd(), libc::F_DUPFD, 3) };
anyhow::ensure!(fd >= 3, "{}", io::Error::last_os_error());
Ok(unsafe { OwnedFd::from_raw_fd(fd) })
})
.collect::<anyhow::Result<Vec<_>>>()?;
let targets = descriptors[..16]
.iter()
.map(AsRawFd::as_raw_fd)
.collect::<Vec<_>>();
let excluded = descriptors[16].as_raw_fd();
let script = format!(
"for fd in \"$@\"; do test -e /dev/fd/$fd || exit 10; done; \
test ! -e /dev/fd/{excluded} || exit 11; /bin/cat /dev/fd/$1"
);
let mut args = vec!["-c".to_owned(), script, "sh".to_owned()];
args.extend(targets.iter().map(ToString::to_string));
let mut limit = std::mem::MaybeUninit::<libc::rlimit>::uninit();
// SAFETY: getrlimit initializes writable storage.
assert_eq!(
unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, limit.as_mut_ptr()) },
0
);
let mut limit = unsafe { limit.assume_init() };
limit.rlim_cur = limit.rlim_cur.min(128);
// SAFETY: Only this isolated subprocess's soft descriptor limit changes.
assert_eq!(unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, &limit) }, 0);
enum Transport {
Pipe(super::PipeStdinMode),
Pty,
}
for (spare_slots, transport) in [
(12, Transport::Pipe(super::PipeStdinMode::Piped)),
(12, Transport::Pipe(super::PipeStdinMode::Null)),
(12, Transport::Pty),
(20, Transport::Pipe(super::PipeStdinMode::Piped)),
(20, Transport::Pipe(super::PipeStdinMode::Null)),
(20, Transport::Pty),
] {
source.rewind()?;
let mut occupied = Vec::new();
loop {
let fd = unsafe { libc::fcntl(source.as_raw_fd(), libc::F_DUPFD_CLOEXEC, 3) };
if fd == -1 {
assert_eq!(
io::Error::last_os_error().raw_os_error(),
Some(libc::EMFILE)
);
break;
}
occupied.push(unsafe { OwnedFd::from_raw_fd(fd) });
}
// Twelve slots reject capture itself; twenty allow all sixteen copies
// but leave too little room for stdio. Both must preserve the old launch.
anyhow::ensure!(
occupied.len() >= spare_slots,
"not enough descriptors to reserve"
);
occupied.truncate(occupied.len() - spare_slots);
let mut spawned = match transport {
Transport::Pipe(stdin) => {
super::spawn_process_with_stdin_mode(
std::ffi::OsStr::new("/bin/sh"),
&args,
Path::new("."),
&HashMap::new(),
&None,
stdin,
&targets,
)
.await?
}
Transport::Pty => {
crate::spawn_pty_process(
"/bin/sh",
&args,
Path::new("."),
&HashMap::new(),
&None,
crate::TerminalSize::default(),
crate::ChildFds::Inherited(&targets),
)
.await?
}
};
drop(occupied);
spawned.session.close_stdin();
let mut stdout = Vec::new();
while let Some(bytes) = spawned.stdout_rx.recv().await {
stdout.extend(bytes);
}
let mut stderr = Vec::new();
while let Some(bytes) = spawned.stderr_rx.recv().await {
stderr.extend(bytes);
}
assert_eq!(
(spawned.exit_rx.await?, stdout, stderr),
(0, b"preserved".to_vec(), vec![])
);
for fd in &descriptors {
assert_eq!(unsafe { libc::fcntl(fd.as_raw_fd(), libc::F_GETFD) }, 0);
}
}
Ok(())
}

View File

@@ -0,0 +1,488 @@
//! 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. Linux also uses it to start the registered process-setup helper.
//! 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;
use std::os::unix::ffi::OsStrExt;
use std::os::unix::process::ExitStatusExt;
use std::process::ExitStatus;
use std::ptr;
use tokio::process::ChildStderr;
use tokio::process::ChildStdin;
use tokio::process::ChildStdout;
use tokio::signal::unix::Signal;
use tokio::signal::unix::SignalKind;
use tokio::signal::unix::signal;
use crate::child_command::ChildDropPolicy;
use crate::child::reaper;
#[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;
// 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,
path: *const libc::c_char,
) -> libc::c_int;
}
/// Owns a child PID until reaping, so cancellation cannot lose or reuse it.
/// Drop obeys the configured kill policy and reaps independently of Tokio.
pub(crate) struct NativeChild {
pid: Option<libc::pid_t>,
status: Option<ExitStatus>,
sigchld: Signal,
reaper: Option<std::sync::mpsc::Sender<reaper::ChildToReap>>,
}
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)
.collect::<io::Result<Vec<_>>>()?;
let argv = args
.iter()
.map(|arg| arg.as_ptr().cast_mut())
.chain(std::iter::once(ptr::null_mut()))
.collect::<Vec<_>>();
let env = command
.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);
c_string(&entry)
})
.collect::<io::Result<Vec<_>>>()?;
let envp = env
.iter()
.map(|entry| entry.as_ptr().cast_mut())
.chain(std::iter::once(ptr::null_mut()))
.collect::<Vec<_>>();
let cwd = command
.get_current_dir()
.map(|cwd| c_string(cwd.as_os_str()))
.transpose()?;
// Reserve the non-killing cleanup worker before creating a child. Drop
// must not need a new thread or synchronously wait for a live process.
let reaper = match request.drop_policy {
ChildDropPolicy::KillAndReap => None,
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 {
crate::ChildStdin::Piped => {
let (reader, writer) = io::pipe()?;
(
OwnedFd::from(reader),
Some(ChildStdin::from_std(OwnedFd::from(writer).into())?),
)
}
crate::ChildStdin::Null => (std::fs::File::open("/dev/null")?.into(), None),
crate::ChildStdin::File(fd) => (fd.try_clone()?, None),
};
let (stdout_read, stdout_write) = child_output(request.stdout_file.as_ref())?;
let (stderr_read, stderr_write) = child_output(request.stderr_file.as_ref())?;
let child_fds = [
child_fd(stdin_read)?,
child_fd(stdout_write)?,
child_fd(stderr_write)?,
];
let stdout = stdout_read
.map(|fd| ChildStdout::from_std(fd.into()))
.transpose()?;
let stderr = stderr_read
.map(|fd| ChildStderr::from_std(fd.into()))
.transpose()?;
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 {
if let Some(cwd) = &cwd {
cvt(addchdir(&mut actions.0, cwd.as_ptr()))?;
}
for (target, source) in child_fds.iter().enumerate() {
let result = libc::posix_spawn_file_actions_adddup2(
&mut actions.0,
source.as_raw_fd(),
target as i32,
);
// Darwin rejects valid high descriptors in spawn file actions,
// even below RLIMIT_NOFILE. The compatibility backend's dup2
// can still wire these owned stdio descriptors after fork.
#[cfg(target_os = "macos")]
if result == libc::EBADF && request.fallback == crate::SpawnFallback::Compatible {
return Ok(None);
}
cvt(result)?;
}
for target in &request.inherited_fds {
#[cfg(target_os = "macos")]
let result = posix_spawn_file_actions_addinherit_np(&mut actions.0, *target);
#[cfg(target_os = "linux")]
let result =
libc::posix_spawn_file_actions_adddup2(&mut actions.0, *target, *target);
// macOS file actions can reject valid high descriptors below
// RLIMIT_NOFILE. The compatibility backend can inherit them directly.
if result == libc::EBADF && request.fallback == crate::SpawnFallback::Compatible {
return Ok(None);
}
cvt(result)?;
}
let group_flags = match request.process_mode {
crate::ProcessMode::Inherit => 0,
crate::ProcessMode::NewGroup => {
cvt(libc::posix_spawnattr_setpgroup(
&mut attrs.0,
/*pgroup*/ 0,
))?;
libc::POSIX_SPAWN_SETPGROUP
}
crate::ProcessMode::NewSession => POSIX_SPAWN_SETSID as _,
};
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,
};
#[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,
executable.as_ptr(),
&actions.0,
&attrs.0,
argv.as_ptr(),
envp.as_ptr(),
)
};
if !search_path {
spawn(&program)
} else {
// posix_spawnp searches the parent's PATH, not envp. Search the
// child's PATH ourselves, using Apple's default when it is unset.
let path = command
.get_envs()
.find(|(key, _)| *key == "PATH")
.and_then(|(_, value)| value)
.unwrap_or(OsStr::new("/usr/bin:/bin"));
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.
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 {
Ok(None)
} else {
Err(io::Error::from_raw_os_error(libc::ENAMETOOLONG))
};
}
result = spawn(&c_string(&executable)?);
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
}
};
// Retain Command's shell fallback and exact PATH search errors.
if request.fallback == crate::SpawnFallback::Compatible
&& (result == libc::ENOEXEC
|| (search_path && result != 0)
|| (matches!(request.process_mode, crate::ProcessMode::NewSession)
&& matches!(result, libc::EINVAL | libc::EPERM)))
{
return Ok(None);
}
cvt(result)?;
let child = Self {
pid: Some(pid),
status: None,
sigchld,
reaper,
};
Ok(Some(crate::Child {
inner: super::ChildKind::Native(child),
stdin,
stdout,
stderr,
}))
}
pub(crate) fn id(&self) -> Option<u32> {
self.pid.map(|pid| pid as u32)
}
/// Polls and caches the exit status, relinquishing the PID once it is reaped.
/// `ECHILD` also relinquishes it to prevent later signaling of a reused PID.
fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
if self.status.is_some() {
return Ok(self.status);
}
let pid = self
.pid
.ok_or_else(|| io::Error::from_raw_os_error(libc::ECHILD))?;
let mut status = 0;
// SAFETY: We own this child PID and provide writable status storage.
match unsafe { libc::waitpid(pid, &mut status, libc::WNOHANG) } {
0 => Ok(None),
-1 => {
let error = io::Error::last_os_error();
if error.raw_os_error() == Some(libc::ECHILD) {
self.pid = None;
}
Err(error)
}
_ => {
self.pid = None;
self.status = Some(ExitStatus::from_raw(status));
Ok(self.status)
}
}
}
/// Waits without transferring child ownership into the future, so callers
/// may cancel a wait and then wait again or kill the same child.
pub(crate) async fn wait(&mut self) -> io::Result<ExitStatus> {
loop {
match self.try_wait() {
Ok(Some(status)) => return Ok(status),
Ok(None) => {}
Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
Err(error) => return Err(error),
}
self.sigchld
.recv()
.await
.ok_or_else(|| io::Error::other("SIGCHLD stream closed"))?;
}
}
/// Sends SIGKILL if still owned, then waits for the child to be reaped.
pub(crate) async fn kill(&mut self) -> io::Result<()> {
if let Some(pid) = self.pid {
// SAFETY: An unreaped child retains its PID, even after it exits.
let result = unsafe { libc::kill(pid, libc::SIGKILL) };
if result == -1 && io::Error::last_os_error().raw_os_error() != Some(libc::ESRCH) {
return Err(io::Error::last_os_error());
}
}
self.wait().await.map(|_| ())
}
}
impl Drop for NativeChild {
fn drop(&mut self) {
let _ = self.try_wait();
let Some(pid) = self.pid.take() else { return };
if let Some(reaper) = &self.reaper {
// The shared sender keeps the worker alive for the process lifetime.
let _ = reaper.send(reaper::ChildToReap::Native(pid));
return;
}
// SAFETY: This child has not been reaped, so its PID cannot be reused.
unsafe {
libc::kill(pid, libc::SIGKILL);
}
// Drop may run during runtime shutdown. Reap independently of Tokio,
// without blocking its worker threads while this process exits.
if std::thread::Builder::new()
.name("codex-child-reaper".into())
.spawn(move || reap(pid))
.is_err()
{
// Resource exhaustion must not turn a dropped child into a zombie.
reap(pid);
}
}
}
/// Reaps the child transferred by `Drop`, retrying interrupted waits without
/// requiring a live Tokio runtime. The caller relinquishes ownership of `pid`.
fn reap(pid: libc::pid_t) {
loop {
// SAFETY: The caller transferred exclusive ownership of this unreaped PID.
let result = unsafe {
libc::waitpid(pid, ptr::null_mut(), /*options*/ 0)
};
if result != -1 || io::Error::last_os_error().kind() != io::ErrorKind::Interrupted {
break;
}
}
}
fn c_string(value: &OsStr) -> io::Result<CString> {
CString::new(value.as_bytes())
.map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "nul byte in MCP command"))
}
/// Keeps a child descriptor above stdio so `dup2` cannot clobber it when the
/// parent has closed standard descriptors. Spawn actions either duplicate it
/// onto stdio or explicitly preserve it across exec.
pub(crate) fn child_fd(fd: OwnedFd) -> io::Result<OwnedFd> {
// SAFETY: fcntl duplicates this live descriptor; the returned fd is newly owned.
let duplicate = unsafe { libc::fcntl(fd.as_raw_fd(), libc::F_DUPFD_CLOEXEC, 3) };
cvt_errno(duplicate)?;
Ok(unsafe { OwnedFd::from_raw_fd(duplicate) })
}
/// Converts a spawn API's returned error number, which does not use `errno`.
fn cvt(result: libc::c_int) -> io::Result<()> {
if result == 0 {
Ok(())
} else {
Err(io::Error::from_raw_os_error(result))
}
}
/// Converts a syscall's `-1` sentinel using the thread's current `errno`.
fn cvt_errno(result: libc::c_int) -> io::Result<()> {
if result == -1 {
Err(io::Error::last_os_error())
} else {
Ok(())
}
}
struct FileActions(libc::posix_spawn_file_actions_t);
#[cfg(target_os = "macos")]
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;
}
struct Attributes(libc::posix_spawnattr_t);
impl Drop for FileActions {
fn drop(&mut self) {
// 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) {
// SAFETY: This object was initialized by posix_spawnattr_init.
unsafe {
libc::posix_spawnattr_destroy(&mut self.0);
}
}
}
/// Wire a caller-owned output descriptor or return a new pipe for the parent.
fn child_output(file: Option<&OwnedFd>) -> io::Result<(Option<OwnedFd>, OwnedFd)> {
if let Some(fd) = file {
Ok((None, fd.try_clone()?))
} else {
let (reader, writer) = io::pipe()?;
Ok((Some(reader.into()), writer.into()))
}
}

View File

@@ -0,0 +1,482 @@
use core::fmt;
use std::io;
#[cfg(unix)]
use std::os::fd::RawFd;
use std::process::ExitStatus;
use std::sync::Arc;
use std::sync::Mutex as StdMutex;
use std::sync::atomic::AtomicBool;
use anyhow::anyhow;
use portable_pty::MasterPty;
use portable_pty::PtySize;
use portable_pty::SlavePty;
use tokio::sync::broadcast;
use tokio::sync::mpsc;
use tokio::sync::oneshot;
use tokio::sync::watch;
use tokio::task::AbortHandle;
use tokio::task::JoinHandle;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ProcessSignal {
Interrupt,
}
pub(crate) fn unsupported_signal(signal: ProcessSignal) -> io::Error {
match signal {
ProcessSignal::Interrupt => io::Error::new(
io::ErrorKind::Unsupported,
"process interrupt is not supported by this process backend",
),
}
}
pub(crate) fn exit_code_from_status(status: ExitStatus) -> i32 {
if let Some(code) = status.code() {
return code;
}
#[cfg(unix)]
{
use std::os::unix::process::ExitStatusExt;
if let Some(signal) = status.signal() {
return 128 + signal;
}
}
-1
}
pub(crate) trait ChildTerminator: Send + Sync {
fn signal(&mut self, signal: ProcessSignal) -> io::Result<()>;
fn kill(&mut self) -> io::Result<()>;
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct TerminalSize {
pub rows: u16,
pub cols: u16,
}
impl Default for TerminalSize {
fn default() -> Self {
Self { rows: 24, cols: 80 }
}
}
impl From<TerminalSize> for PtySize {
fn from(value: TerminalSize) -> Self {
Self {
rows: value.rows,
cols: value.cols,
pixel_width: 0,
pixel_height: 0,
}
}
}
#[cfg(unix)]
pub(crate) trait PtyHandleKeepAlive: Send {}
#[cfg(unix)]
impl<T: Send + ?Sized> PtyHandleKeepAlive for T {}
pub(crate) enum PtyMasterHandle {
Resizable(Box<dyn MasterPty + Send>),
#[cfg(unix)]
Opaque {
raw_fd: RawFd,
_handle: Box<dyn PtyHandleKeepAlive>,
},
}
pub struct PtyHandles {
pub _slave: Option<Box<dyn SlavePty + Send>>,
pub(crate) _master: PtyMasterHandle,
}
impl fmt::Debug for PtyHandles {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("PtyHandles").finish()
}
}
/// Callback used by driver-backed sessions to resize a PTY-like backend when
/// there is no local `PtyHandles` instance to resize directly.
type ResizeFn = Box<dyn FnMut(TerminalSize) -> anyhow::Result<()> + Send>;
/// Handle for driving an interactive process (PTY or pipe).
pub struct ProcessHandle {
writer_tx: StdMutex<Option<mpsc::Sender<Vec<u8>>>>,
killer: StdMutex<Option<Box<dyn ChildTerminator>>>,
stdout_reader: Option<JoinHandle<()>>,
stderr_reader: Option<JoinHandle<()>>,
writer_handle: StdMutex<Option<JoinHandle<()>>>,
wait_handle: StdMutex<Option<JoinHandle<()>>>,
exit_status: Arc<AtomicBool>,
exit_code: Arc<StdMutex<Option<i32>>>,
// PtyHandles must be preserved because the process will receive Control+C if the
// slave is closed
_pty_handles: StdMutex<Option<PtyHandles>>,
// Optional resize hook for driver-backed sessions that proxy PTY control to
// another backend instead of owning local PTY handles.
resizer: StdMutex<Option<ResizeFn>>,
}
impl fmt::Debug for ProcessHandle {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ProcessHandle").finish()
}
}
impl ProcessHandle {
#[allow(clippy::too_many_arguments)]
pub(crate) fn new(
writer_tx: mpsc::Sender<Vec<u8>>,
killer: Box<dyn ChildTerminator>,
stdout_reader: Option<JoinHandle<()>>,
stderr_reader: Option<JoinHandle<()>>,
writer_handle: JoinHandle<()>,
wait_handle: JoinHandle<()>,
exit_status: Arc<AtomicBool>,
exit_code: Arc<StdMutex<Option<i32>>>,
pty_handles: Option<PtyHandles>,
resizer: Option<ResizeFn>,
) -> Self {
Self {
writer_tx: StdMutex::new(Some(writer_tx)),
killer: StdMutex::new(Some(killer)),
stdout_reader,
stderr_reader,
writer_handle: StdMutex::new(Some(writer_handle)),
wait_handle: StdMutex::new(Some(wait_handle)),
exit_status,
exit_code,
_pty_handles: StdMutex::new(pty_handles),
resizer: StdMutex::new(resizer),
}
}
pub fn stdout_reader(&self) -> Option<AbortHandle> {
self.stdout_reader.as_ref().map(JoinHandle::abort_handle)
}
pub fn stderr_reader(&self) -> Option<AbortHandle> {
self.stderr_reader.as_ref().map(JoinHandle::abort_handle)
}
/// Returns a channel sender for writing raw bytes to the child stdin.
pub fn writer_sender(&self) -> mpsc::Sender<Vec<u8>> {
if let Ok(writer_tx) = self.writer_tx.lock()
&& let Some(writer_tx) = writer_tx.as_ref()
{
return writer_tx.clone();
}
let (writer_tx, writer_rx) = mpsc::channel(1);
drop(writer_rx);
writer_tx
}
/// True if the child process has exited.
pub fn has_exited(&self) -> bool {
self.exit_status.load(std::sync::atomic::Ordering::SeqCst)
}
/// Returns the exit code if known.
pub fn exit_code(&self) -> Option<i32> {
self.exit_code.lock().ok().and_then(|guard| *guard)
}
/// Resize the PTY in character cells.
pub fn resize(&self, size: TerminalSize) -> anyhow::Result<()> {
{
let handles = self
._pty_handles
.lock()
.map_err(|_| anyhow!("failed to lock PTY handles"))?;
if let Some(handles) = handles.as_ref() {
return match &handles._master {
PtyMasterHandle::Resizable(master) => master.resize(size.into()),
#[cfg(unix)]
PtyMasterHandle::Opaque { raw_fd, .. } => resize_raw_pty(*raw_fd, size),
};
}
}
let mut resizer = self
.resizer
.lock()
.map_err(|_| anyhow!("failed to lock PTY resizer"))?;
if let Some(resizer) = resizer.as_mut() {
resizer(size)
} else {
Err(anyhow!("process is not attached to a PTY"))
}
}
/// Close the child's stdin channel.
pub fn close_stdin(&self) {
if let Ok(mut writer_tx) = self.writer_tx.lock() {
writer_tx.take();
}
}
/// Attempts to kill the child while leaving the reader/writer tasks alive
/// so callers can still drain output until EOF.
pub fn request_terminate(&self) {
if let Ok(mut killer_opt) = self.killer.lock()
&& let Some(mut killer) = killer_opt.take()
{
let _ = killer.kill();
}
}
pub fn signal(&self, signal: ProcessSignal) -> io::Result<()> {
let Ok(mut killer_opt) = self.killer.lock() else {
return Ok(());
};
let Some(killer) = killer_opt.as_mut() else {
return Ok(());
};
let result = killer.signal(signal);
#[cfg(windows)]
if result.is_ok() {
killer_opt.take();
}
result
}
/// Attempts to kill the child and abort I/O helper tasks.
pub fn terminate(&self) {
self.request_terminate();
for reader in [&self.stdout_reader, &self.stderr_reader]
.into_iter()
.flatten()
{
reader.abort();
}
if let Ok(mut h) = self.writer_handle.lock()
&& let Some(handle) = h.take()
{
handle.abort();
}
if let Ok(mut h) = self.wait_handle.lock()
&& let Some(handle) = h.take()
{
// Even a queued PTY waiter must run to reap the terminated child.
drop(handle);
}
}
}
impl Drop for ProcessHandle {
fn drop(&mut self) {
self.terminate();
}
}
/// Adapts a closure into a `ChildTerminator` implementation.
struct ClosureTerminator {
inner: Option<Box<dyn FnMut() + Send + Sync>>,
#[cfg(windows)]
interrupt_terminates: bool,
}
impl ChildTerminator for ClosureTerminator {
fn signal(&mut self, signal: ProcessSignal) -> io::Result<()> {
#[cfg(windows)]
if self.interrupt_terminates {
return self.kill();
}
Err(unsupported_signal(signal))
}
fn kill(&mut self) -> io::Result<()> {
if let Some(inner) = self.inner.as_mut() {
(inner)();
}
Ok(())
}
}
#[cfg(unix)]
fn resize_raw_pty(raw_fd: RawFd, size: TerminalSize) -> anyhow::Result<()> {
let mut winsize = libc::winsize {
ws_row: size.rows,
ws_col: size.cols,
ws_xpixel: 0,
ws_ypixel: 0,
};
let result = unsafe { libc::ioctl(raw_fd, libc::TIOCSWINSZ, &mut winsize) };
if result == -1 {
return Err(std::io::Error::last_os_error().into());
}
Ok(())
}
/// Combine split stdout/stderr receivers into a single broadcast receiver.
pub fn combine_output_receivers(
mut stdout_rx: mpsc::Receiver<Vec<u8>>,
mut stderr_rx: mpsc::Receiver<Vec<u8>>,
) -> broadcast::Receiver<Vec<u8>> {
let (combined_tx, combined_rx) = broadcast::channel(256);
tokio::spawn(async move {
let mut stdout_open = true;
let mut stderr_open = true;
loop {
tokio::select! {
stdout = stdout_rx.recv(), if stdout_open => match stdout {
Some(chunk) => {
let _ = combined_tx.send(chunk);
}
None => {
stdout_open = false;
}
},
stderr = stderr_rx.recv(), if stderr_open => match stderr {
Some(chunk) => {
let _ = combined_tx.send(chunk);
}
None => {
stderr_open = false;
}
},
else => break,
}
}
});
combined_rx
}
/// Return value from PTY or pipe spawn helpers.
#[derive(Debug)]
pub struct SpawnedProcess {
pub session: ProcessHandle,
pub stdout_rx: mpsc::Receiver<Vec<u8>>,
pub stderr_rx: mpsc::Receiver<Vec<u8>>,
pub exit_rx: oneshot::Receiver<i32>,
}
/// Driver-backed process handles for non-standard spawn backends.
pub struct ProcessDriver {
pub writer_tx: mpsc::Sender<Vec<u8>>,
pub stdout_rx: broadcast::Receiver<Vec<u8>>,
pub stderr_rx: Option<broadcast::Receiver<Vec<u8>>>,
pub exit_rx: oneshot::Receiver<i32>,
pub terminator: Option<Box<dyn FnMut() + Send + Sync>>,
pub writer_handle: Option<JoinHandle<()>>,
pub resizer: Option<ResizeFn>,
/// Whether this Windows process is attached to a pseudo-console.
#[cfg(windows)]
pub tty: bool,
}
/// Build a `SpawnedProcess` from a driver that supplies stdin/output/exit channels.
pub fn spawn_from_driver(driver: ProcessDriver) -> SpawnedProcess {
let ProcessDriver {
writer_tx,
stdout_rx: stdout_driver_rx,
stderr_rx: mut stderr_driver_rx,
exit_rx,
terminator,
writer_handle,
resizer,
#[cfg(windows)]
tty,
} = driver;
#[cfg(windows)]
let interrupt_terminates = terminator.is_some() && !tty;
let (stdout_tx, stdout_rx) = mpsc::channel::<Vec<u8>>(256);
let (stderr_tx, stderr_rx) = mpsc::channel::<Vec<u8>>(256);
let (exit_seen_tx, exit_seen_rx) = watch::channel(false);
let spawn_stream_reader =
|mut output_rx: broadcast::Receiver<Vec<u8>>,
output_tx: mpsc::Sender<Vec<u8>>,
mut exit_seen_rx: watch::Receiver<bool>| {
tokio::spawn(async move {
loop {
let recv_result = if *exit_seen_rx.borrow() {
// Once exit has been observed, we no longer want a timer here. Some
// backends publish the exit code before their final stdout/stderr bytes
// have been forwarded through the broadcast channel, so a fixed grace
// period can still drop the tail of the stream under load.
//
// Instead, keep waiting until the driver closes the broadcast sender.
// That makes the shutdown contract explicit: the backend is responsible
// for dropping its sender when it has truly finished forwarding output.
output_rx.recv().await
} else {
tokio::select! {
_ = exit_seen_rx.changed() => {
continue;
}
result = output_rx.recv() => result,
}
};
match recv_result {
Ok(chunk) => {
if output_tx.send(chunk).await.is_err() {
break;
}
}
Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue,
Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
}
}
})
};
let reader_handle = spawn_stream_reader(stdout_driver_rx, stdout_tx, exit_seen_rx.clone());
let stderr_reader_handle = stderr_driver_rx
.take()
.map(|rx| spawn_stream_reader(rx, stderr_tx, exit_seen_rx));
let writer_handle = writer_handle.unwrap_or_else(|| tokio::spawn(async {}));
let (exit_tx, exit_rx_out) = oneshot::channel::<i32>();
let exit_status = Arc::new(AtomicBool::new(false));
let wait_exit_status = Arc::clone(&exit_status);
let exit_code = Arc::new(StdMutex::new(None));
let wait_exit_code = Arc::clone(&exit_code);
let wait_handle = tokio::spawn(async move {
let code = exit_rx.await.unwrap_or(-1);
wait_exit_status.store(true, std::sync::atomic::Ordering::SeqCst);
if let Ok(mut guard) = wait_exit_code.lock() {
*guard = Some(code);
}
let _ = exit_seen_tx.send(true);
let _ = exit_tx.send(code);
});
let handle = ProcessHandle::new(
writer_tx,
Box::new(ClosureTerminator {
inner: terminator,
#[cfg(windows)]
interrupt_terminates,
}),
Some(reader_handle),
stderr_reader_handle,
writer_handle,
wait_handle,
exit_status,
exit_code,
/*pty_handles*/ None,
resizer,
);
SpawnedProcess {
session: handle,
stdout_rx,
stderr_rx,
exit_rx: exit_rx_out,
}
}

View File

@@ -0,0 +1,336 @@
//! Process-group helpers shared by pipe/pty and shell command execution.
//!
//! This module centralizes the OS-specific pieces that ensure a spawned
//! command can be cleaned up reliably:
//! - `set_process_group` is called in `pre_exec` so the child starts its own
//! process group.
//! - `detach_from_tty` starts a new session so non-interactive children do not
//! inherit the controlling TTY.
//! - `kill_process_group_by_pid` targets the whole group (children/grandchildren)
//! - `kill_process_group` targets a known process group ID directly
//! instead of a single PID.
//! - `set_parent_death_signal` (Linux only) arranges for the child to receive a
//! `SIGTERM` when the parent exits, and re-checks the parent PID to avoid
//! races during fork/exec.
//!
//! On macOS, `terminate_process_group` and `kill_process_group` retry denied
//! group signals against individual members.
//! On non-Unix platforms these helpers are no-ops.
use std::io;
use tokio::process::Child;
#[cfg(target_os = "linux")]
/// Ensure the child receives SIGTERM when the original parent dies.
///
/// This should run in `pre_exec` and uses `parent_pid` captured before spawn to
/// avoid a race where the parent exits between fork and exec.
pub fn set_parent_death_signal(parent_pid: libc::pid_t) -> io::Result<()> {
if unsafe { libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGTERM) } == -1 {
return Err(io::Error::last_os_error());
}
if unsafe { libc::getppid() } != parent_pid {
unsafe {
libc::raise(libc::SIGTERM);
}
}
Ok(())
}
#[cfg(not(target_os = "linux"))]
/// No-op on non-Linux platforms.
pub fn set_parent_death_signal(_parent_pid: i32) -> io::Result<()> {
Ok(())
}
#[cfg(unix)]
/// Detach from the controlling TTY by starting a new session.
pub fn detach_from_tty() -> io::Result<()> {
let result = unsafe { libc::setsid() };
if result == -1 {
let err = io::Error::last_os_error();
if err.raw_os_error() == Some(libc::EPERM) {
return set_process_group();
}
return Err(err);
}
Ok(())
}
#[cfg(not(unix))]
/// No-op on non-Unix platforms.
pub fn detach_from_tty() -> io::Result<()> {
Ok(())
}
#[cfg(unix)]
/// Put the calling process into its own process group.
///
/// Intended for use in `pre_exec` so the child becomes the group leader.
pub fn set_process_group() -> io::Result<()> {
let result = unsafe { libc::setpgid(0, 0) };
if result == -1 {
Err(io::Error::last_os_error())
} else {
Ok(())
}
}
#[cfg(not(unix))]
/// No-op on non-Unix platforms.
pub fn set_process_group() -> io::Result<()> {
Ok(())
}
#[cfg(unix)]
/// Kill the process group for the given PID (best-effort).
///
/// This resolves the PGID for `pid` and sends SIGKILL to the whole group.
pub fn kill_process_group_by_pid(pid: u32) -> io::Result<()> {
use std::io::ErrorKind;
let pid = pid as libc::pid_t;
let pgid = unsafe { libc::getpgid(pid) };
if pgid == -1 {
let err = io::Error::last_os_error();
if err.kind() != ErrorKind::NotFound && err.raw_os_error() != Some(libc::ESRCH) {
return Err(err);
}
return Ok(());
}
let result = unsafe { libc::killpg(pgid, libc::SIGKILL) };
if result == -1 {
let err = io::Error::last_os_error();
if err.kind() != ErrorKind::NotFound && err.raw_os_error() != Some(libc::ESRCH) {
return Err(err);
}
}
Ok(())
}
#[cfg(not(unix))]
/// No-op on non-Unix platforms.
pub fn kill_process_group_by_pid(_pid: u32) -> io::Result<()> {
Ok(())
}
#[cfg(unix)]
fn signal_process_group_id(pgid: libc::pid_t, signal: libc::c_int) -> io::Result<bool> {
use std::io::ErrorKind;
let result = unsafe { libc::killpg(pgid, signal) };
if result == -1 {
let err = io::Error::last_os_error();
if err.kind() == ErrorKind::NotFound || err.raw_os_error() == Some(libc::ESRCH) {
return Ok(false);
}
return Err(err);
}
Ok(true)
}
#[cfg(target_os = "macos")]
fn signal_process_id(pid: libc::pid_t, signal: libc::c_int) -> io::Result<bool> {
if unsafe { libc::kill(pid, signal) } == -1 {
let error = io::Error::last_os_error();
if error.raw_os_error() == Some(libc::ESRCH) {
return Ok(false);
}
return Err(error);
}
Ok(true)
}
#[cfg(target_os = "macos")]
fn signal_process_group_with_member_fallback(
process_group_id: u32,
signal: libc::c_int,
signal_group: impl FnOnce(libc::pid_t, libc::c_int) -> io::Result<bool>,
mut signal_member: impl FnMut(libc::pid_t, libc::c_int) -> io::Result<bool>,
) -> io::Result<bool> {
let process_group_id = libc::pid_t::try_from(process_group_id)
.ok()
.filter(|process_group_id| *process_group_id > 0)
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "invalid process group ID"))?;
match signal_group(process_group_id, signal) {
Err(error) if error.kind() == io::ErrorKind::PermissionDenied => {}
result => return result,
}
let mut process_ids: Vec<libc::pid_t> = vec![0; 16];
loop {
let buffer_size = libc::c_int::try_from(std::mem::size_of_val(process_ids.as_slice()))
.map_err(|_| {
io::Error::new(io::ErrorKind::InvalidData, "process group is too large")
})?;
let count = unsafe {
libc::proc_listpgrppids(
process_group_id,
process_ids.as_mut_ptr().cast(),
buffer_size,
)
};
if count < 0 {
return Err(io::Error::last_os_error());
}
let count = count as usize;
if count < process_ids.len() {
process_ids.truncate(count);
break;
}
let capacity = process_ids.len().checked_mul(2).ok_or_else(|| {
io::Error::new(io::ErrorKind::InvalidData, "process group is too large")
})?;
process_ids.resize(capacity, 0);
}
process_ids.sort_unstable_by_key(|process_id| *process_id == process_group_id);
let mut signalled = false;
let mut first_error = None;
for process_id in process_ids {
if process_id <= 0 {
continue;
}
let current_group_id = unsafe { libc::getpgid(process_id) };
if current_group_id == -1 {
let error = io::Error::last_os_error();
if error.raw_os_error() != Some(libc::ESRCH) && first_error.is_none() {
first_error = Some(error);
}
continue;
}
if current_group_id != process_group_id {
continue;
}
match signal_member(process_id, signal) {
Ok(delivered) => signalled |= delivered,
Err(error) if first_error.is_none() => first_error = Some(error),
Err(_) => {}
}
}
if signalled {
Ok(true)
} else {
first_error.map_or(Ok(false), Err)
}
}
#[cfg(all(unix, not(target_os = "macos")))]
/// Send SIGTERM to a specific process group ID (best-effort).
///
/// Returns `Ok(true)` when SIGTERM was delivered to an existing group and
/// `Ok(false)` when the group no longer exists.
pub fn terminate_process_group(process_group_id: u32) -> io::Result<bool> {
signal_process_group_id(process_group_id as libc::pid_t, libc::SIGTERM)
}
#[cfg(target_os = "macos")]
/// Send SIGTERM to a specific process group, retrying denied signals against its members.
///
/// Returns `Ok(true)` when the group or at least one member was signalled.
pub fn terminate_process_group(process_group_id: u32) -> io::Result<bool> {
signal_process_group_with_member_fallback(
process_group_id,
libc::SIGTERM,
signal_process_group_id,
signal_process_id,
)
}
#[cfg(not(unix))]
/// No-op on non-Unix platforms.
pub fn terminate_process_group(_process_group_id: u32) -> io::Result<bool> {
Ok(false)
}
#[cfg(unix)]
/// Send SIGINT to a specific process group ID (best-effort).
pub fn interrupt_process_group(process_group_id: u32) -> io::Result<()> {
signal_process_group_id(process_group_id as libc::pid_t, libc::SIGINT).map(|_| ())
}
#[cfg(not(unix))]
/// No-op on non-Unix platforms.
pub fn interrupt_process_group(_process_group_id: u32) -> io::Result<()> {
Ok(())
}
#[cfg(all(unix, not(target_os = "macos")))]
/// Kill a specific process group ID (best-effort).
pub fn kill_process_group(process_group_id: u32) -> io::Result<()> {
signal_process_group_id(process_group_id as libc::pid_t, libc::SIGKILL).map(|_| ())
}
#[cfg(target_os = "macos")]
/// Kill a specific process group, retrying denied signals against its members (best-effort).
pub fn kill_process_group(process_group_id: u32) -> io::Result<()> {
signal_process_group_with_member_fallback(
process_group_id,
libc::SIGKILL,
signal_process_group_id,
signal_process_id,
)
.map(|_| ())
}
#[cfg(not(unix))]
/// No-op on non-Unix platforms.
pub fn kill_process_group(_process_group_id: u32) -> io::Result<()> {
Ok(())
}
/// Wait up to `grace` for a signaled group's members to release their resources.
/// After that, allow the caller to proceed. An unreaped zombie or a recycled group ID
/// can remain visible after the original processes have released their resources.
#[cfg(unix)]
pub fn wait_for_process_group_exit(process_group_id: u32, grace: std::time::Duration) {
let deadline = std::time::Instant::now() + grace;
loop {
#[cfg(target_os = "macos")]
let exists = signal_process_group_with_member_fallback(
process_group_id,
/*signal*/ 0,
signal_process_group_id,
signal_process_id,
);
#[cfg(not(target_os = "macos"))]
let exists = signal_process_group_id(process_group_id as libc::pid_t, /*signal*/ 0);
if matches!(exists, Ok(false)) {
break;
}
let remaining = deadline.saturating_duration_since(std::time::Instant::now());
if remaining.is_zero() {
break;
}
std::thread::sleep(remaining.min(std::time::Duration::from_millis(10)));
}
}
#[cfg(unix)]
/// Kill the process group for a tokio child (best-effort).
pub fn kill_child_process_group(child: &mut Child) -> io::Result<()> {
if let Some(pid) = child.id() {
return kill_process_group_by_pid(pid);
}
Ok(())
}
#[cfg(not(unix))]
/// No-op on non-Unix platforms.
pub fn kill_child_process_group(_child: &mut Child) -> io::Result<()> {
Ok(())
}
#[cfg(all(test, target_os = "macos"))]
#[path = "process_group_tests.rs"]
mod tests;

View File

@@ -0,0 +1,94 @@
use std::io;
use std::process::Stdio;
use std::time::Duration;
use anyhow::Context;
use anyhow::Result;
use pretty_assertions::assert_eq;
use tokio::io::AsyncBufReadExt;
use tokio::io::BufReader;
use tokio::process::Command;
use tokio::time::timeout;
use super::signal_process_group_with_member_fallback;
use super::signal_process_id;
use super::terminate_process_group;
#[tokio::test]
async fn denied_group_signal_terminates_owned_descendants_and_preserves_escalation() -> Result<()> {
for leader_exited in [false, true] {
let mut wrapper = Command::new("/bin/sh")
.args([
"-c",
"trap '' TERM; /bin/sleep 30 & resistant=$!; trap - TERM; /bin/sleep 30 & sibling=$!; printf '%s %s\\n' \"$resistant\" \"$sibling\"; wait",
])
.stdout(Stdio::piped())
.stderr(Stdio::null())
.kill_on_drop(true)
.process_group(0)
.spawn()?;
let process_group_id =
wrapper.id().context("wrapper process has no process ID")? as libc::pid_t;
let stdout = wrapper.stdout.take().context("wrapper has no stdout")?;
let line = timeout(
Duration::from_secs(5),
BufReader::new(stdout).lines().next_line(),
)
.await??
.context("missing descendant IDs")?;
let (resistant_pid, sibling_pid) =
line.split_once(' ').context("invalid descendant IDs")?;
let resistant_pid = resistant_pid.parse::<libc::pid_t>()?;
let sibling_pid = sibling_pid.parse::<libc::pid_t>()?;
if leader_exited {
wrapper.kill().await?;
}
let mut denied_leader = false;
for signal in [libc::SIGTERM, libc::SIGKILL] {
assert!(signal_process_group_with_member_fallback(
process_group_id as u32,
signal,
|_, _| Err(io::Error::from_raw_os_error(libc::EPERM)),
|process_id, signal| {
if process_id == process_group_id {
denied_leader = true;
Err(io::Error::from_raw_os_error(libc::EPERM))
} else {
signal_process_id(process_id, signal)
}
},
)?);
if signal == libc::SIGTERM {
assert_eq!(denied_leader, !leader_exited);
assert!(signal_process_id(resistant_pid, /*signal*/ 0)?);
}
}
for process_id in [resistant_pid, sibling_pid] {
timeout(Duration::from_secs(5), async move {
while signal_process_id(process_id, /*signal*/ 0)? {
tokio::time::sleep(Duration::from_millis(20)).await;
}
Ok::<(), io::Error>(())
})
.await??;
}
if !leader_exited {
timeout(Duration::from_secs(5), wrapper.wait()).await??;
}
}
Ok(())
}
#[test]
fn denied_group_signal_rejects_unsafe_process_group_ids() {
for process_group_id in [0, u32::MAX] {
let error = terminate_process_group(process_group_id)
.expect_err("unsafe process group ID should be rejected");
assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
}
}

View File

@@ -0,0 +1,679 @@
use std::collections::HashMap;
#[cfg(unix)]
use std::fs::File;
use std::io::ErrorKind;
#[cfg(unix)]
use std::os::fd::AsRawFd;
#[cfg(unix)]
use std::os::fd::FromRawFd;
#[cfg(unix)]
use std::os::fd::RawFd;
#[cfg(all(unix, not(target_os = "linux")))]
use std::os::unix::process::CommandExt;
use std::path::Path;
#[cfg(all(unix, not(target_os = "linux")))]
use std::process::Command as StdCommand;
#[cfg(all(unix, not(target_os = "linux")))]
use std::process::Stdio;
use std::sync::Arc;
use std::sync::Mutex as StdMutex;
use std::sync::atomic::AtomicBool;
#[cfg(not(unix))]
use std::time::Duration;
use anyhow::Result;
use portable_pty::CommandBuilder;
#[cfg(not(windows))]
use portable_pty::native_pty_system;
use tokio::sync::mpsc;
use tokio::sync::oneshot;
use tokio::task::JoinHandle;
#[cfg(target_os = "linux")]
pub(crate) use crate::linux_fds::close_inherited_fds_except;
use crate::process::ChildTerminator;
use crate::process::ProcessHandle;
use crate::process::ProcessSignal;
use crate::process::PtyHandles;
use crate::process::PtyMasterHandle;
use crate::process::SpawnedProcess;
use crate::process::TerminalSize;
#[cfg(unix)]
use crate::process::exit_code_from_status;
/// Extra descriptors accompanying a process launch.
#[derive(Clone, Copy)]
pub enum ChildFds<'a> {
/// Existing escalation sockets, with the legacy PTY I/O and status behavior.
Inherited(&'a [i32]),
/// Launch attachments, including CLOEXEC files, with ordinary PTY behavior.
Attached(&'a [i32]),
}
impl<'a> ChildFds<'a> {
pub fn as_slice(self) -> &'a [i32] {
match self {
Self::Inherited(fds) | Self::Attached(fds) => fds,
}
}
}
/// Returns true when ConPTY support is available (Windows only).
#[cfg(windows)]
pub fn conpty_supported() -> bool {
crate::win::conpty_supported()
}
/// Returns true when ConPTY support is available (non-Windows always true).
#[cfg(not(windows))]
pub fn conpty_supported() -> bool {
true
}
struct PtyChildTerminator {
killer: Box<dyn portable_pty::ChildKiller + Send + Sync>,
#[cfg(unix)]
process_group_id: Option<u32>,
}
impl ChildTerminator for PtyChildTerminator {
fn signal(&mut self, signal: ProcessSignal) -> std::io::Result<()> {
match signal {
ProcessSignal::Interrupt => {
#[cfg(unix)]
if let Some(process_group_id) = self.process_group_id {
return crate::process_group::interrupt_process_group(process_group_id);
}
Err(crate::process::unsupported_signal(signal))
}
}
}
fn kill(&mut self) -> std::io::Result<()> {
#[cfg(unix)]
if let Some(process_group_id) = self.process_group_id {
// Match the pipe backend's hard-kill behavior so descendant
// processes from interactive shells/REPLs do not survive shutdown.
// Also try the direct child killer in case the cached PGID is stale.
let process_group_kill_result =
crate::process_group::kill_process_group(process_group_id);
let child_kill_result = self.killer.kill();
return match child_kill_result {
Ok(()) => Ok(()),
Err(err) if err.kind() == ErrorKind::NotFound => process_group_kill_result,
Err(err) => process_group_kill_result.or(Err(err)),
};
}
self.killer.kill()
}
}
#[cfg(unix)]
struct RawPidTerminator {
process_group_id: u32,
}
#[cfg(unix)]
impl ChildTerminator for RawPidTerminator {
fn signal(&mut self, signal: ProcessSignal) -> std::io::Result<()> {
match signal {
ProcessSignal::Interrupt => {
crate::process_group::interrupt_process_group(self.process_group_id)
}
}
}
fn kill(&mut self) -> std::io::Result<()> {
crate::process_group::kill_process_group(self.process_group_id)
}
}
fn platform_native_pty_system() -> Box<dyn portable_pty::PtySystem + Send> {
#[cfg(windows)]
{
Box::new(crate::win::ConPtySystem::default())
}
#[cfg(not(windows))]
{
native_pty_system()
}
}
/// Spawn a process attached to a PTY, preserving selected inherited file
/// descriptors across exec on Unix.
pub async fn spawn_process(
program: &str,
args: &[String],
cwd: &Path,
env: &HashMap<String, String>,
arg0: &Option<String>,
size: TerminalSize,
inherited_fds: ChildFds<'_>,
) -> Result<SpawnedProcess> {
if program.is_empty() {
anyhow::bail!("missing program for PTY spawn");
}
#[cfg(not(unix))]
let _ = inherited_fds;
#[cfg(target_os = "linux")]
if crate::spawn_helper::is_available()
&& inherited_fds.as_slice().is_empty()
&& Path::new(program).is_absolute()
&& arg0.is_none()
&& cwd.is_dir()
{
// Keep portable-pty's PATH, argv0, and missing-cwd behavior for requests
// whose launch settings require its command builder.
return spawn_process_preserving_fds(program, args, cwd, env, arg0, size, inherited_fds)
.await;
}
#[cfg(unix)]
if !inherited_fds.as_slice().is_empty() {
return spawn_process_preserving_fds(program, args, cwd, env, arg0, size, inherited_fds)
.await;
}
spawn_process_portable(program, args, cwd, env, arg0, size).await
}
async fn spawn_process_portable(
program: &str,
args: &[String],
cwd: &Path,
env: &HashMap<String, String>,
arg0: &Option<String>,
size: TerminalSize,
) -> Result<SpawnedProcess> {
let pty_system = platform_native_pty_system();
let pair = pty_system.openpty(size.into())?;
#[cfg(unix)]
let io = crate::unix_io::PtyIo::new(
pair.master
.as_raw_fd()
.ok_or_else(|| anyhow::anyhow!("PTY master has no file descriptor"))?,
)?;
let mut command_builder = CommandBuilder::new(arg0.as_ref().unwrap_or(&program.to_string()));
command_builder.cwd(cwd);
command_builder.env_clear();
for arg in args {
command_builder.arg(arg);
}
for (key, value) in env {
command_builder.env(key, value);
}
let mut child = pair.slave.spawn_command(command_builder)?;
#[cfg(unix)]
// portable-pty establishes the spawned PTY child as a new session leader on
// Unix, so PID == PGID and we can reuse the pipe backend's process-group
// hard-kill semantics for descendants.
let process_group_id = child.process_id();
let killer = child.clone_killer();
let (writer_tx, writer_rx) = mpsc::channel::<Vec<u8>>(128);
let (stdout_tx, stdout_rx) = mpsc::channel::<Vec<u8>>(128);
let (_stderr_tx, stderr_rx) = mpsc::channel::<Vec<u8>>(1);
#[cfg(unix)]
let (reader_handle, writer_handle) = io.spawn(
stdout_tx,
writer_rx,
crate::unix_io::StdinCloseBehavior::SendEof,
);
#[cfg(not(unix))]
let (reader_handle, writer_handle) = {
let mut reader = pair.master.try_clone_reader()?;
let reader_handle: JoinHandle<()> = tokio::task::spawn_blocking(move || {
let mut buf = [0u8; 8_192];
loop {
match reader.read(&mut buf) {
Ok(0) => break,
Ok(n) => {
let _ = stdout_tx.blocking_send(buf[..n].to_vec());
}
Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
Err(ref e) if e.kind() == ErrorKind::WouldBlock => {
std::thread::sleep(Duration::from_millis(5));
continue;
}
Err(_) => break,
}
}
});
let mut writer_rx = writer_rx;
let writer = pair.master.take_writer()?;
let writer = Arc::new(tokio::sync::Mutex::new(writer));
let writer_handle: JoinHandle<()> = tokio::spawn({
let writer = Arc::clone(&writer);
async move {
#[cfg(windows)]
let mut windows_input = crate::WindowsTtyInputNormalizer::default();
while let Some(bytes) = writer_rx.recv().await {
#[cfg(windows)]
let bytes = windows_input.normalize(&bytes);
let mut guard = writer.lock().await;
use std::io::Write;
let _ = guard.write_all(&bytes);
let _ = guard.flush();
}
}
});
(reader_handle, writer_handle)
};
let (exit_tx, exit_rx) = oneshot::channel::<i32>();
let exit_status = Arc::new(AtomicBool::new(false));
let wait_exit_status = Arc::clone(&exit_status);
let exit_code = Arc::new(StdMutex::new(None));
let wait_exit_code = Arc::clone(&exit_code);
let wait_handle: JoinHandle<()> = tokio::task::spawn_blocking(move || {
let code = match child.wait() {
Ok(status) => status.exit_code() as i32,
Err(_) => -1,
};
wait_exit_status.store(true, std::sync::atomic::Ordering::SeqCst);
if let Ok(mut guard) = wait_exit_code.lock() {
*guard = Some(code);
}
let _ = exit_tx.send(code);
});
let handles = PtyHandles {
_slave: if cfg!(windows) {
Some(pair.slave)
} else {
None
},
_master: PtyMasterHandle::Resizable(pair.master),
};
let handle = ProcessHandle::new(
writer_tx,
Box::new(PtyChildTerminator {
killer,
#[cfg(unix)]
process_group_id,
}),
Some(reader_handle),
/*stderr_reader*/ None,
writer_handle,
wait_handle,
exit_status,
exit_code,
Some(handles),
/*resizer*/ None,
);
Ok(SpawnedProcess {
session: handle,
stdout_rx,
stderr_rx,
exit_rx,
})
}
#[cfg(unix)]
async fn spawn_process_preserving_fds(
program: &str,
args: &[String],
cwd: &Path,
env: &HashMap<String, String>,
arg0: &Option<String>,
size: TerminalSize,
descriptors: ChildFds<'_>,
) -> Result<SpawnedProcess> {
let (master, slave) = open_unix_pty(size)?;
let io = crate::unix_io::PtyIo::new(master.as_raw_fd())?;
let uses_portable_status = match descriptors {
ChildFds::Inherited(fds) => fds.is_empty(),
ChildFds::Attached(_) => true,
};
let inherited_fds = descriptors.as_slice();
let stdin_close_behavior = if uses_portable_status {
crate::unix_io::StdinCloseBehavior::SendEof
} else {
crate::unix_io::StdinCloseBehavior::NoEof
};
let default_shell = (uses_portable_status && !env.contains_key("SHELL")).then(|| {
let mut builder = CommandBuilder::new(program);
builder.env_clear();
builder.get_shell()
});
#[cfg(target_os = "linux")]
let mut child = {
let mut command = crate::Command::new(program);
if let Some(shell) = &default_shell {
// portable-pty supplies the login shell when SHELL is absent.
command.env("SHELL", shell);
}
command
.args(args)
.current_dir(cwd)
.envs(env)
.drop_policy(crate::child_command::ChildDropPolicy::ReapOnly)
.descriptor_policy(crate::DescriptorPolicy::Explicit)
.inherit_fds(inherited_fds)
.stdin(crate::ChildStdin::File(slave.try_clone()?.into()));
if let Some(arg0) = arg0 {
command.arg0(arg0);
}
command.stdout_file = Some(slave.try_clone()?.into());
command.stderr_file = Some(slave.try_clone()?.into());
match crate::spawn_helper::spawn(&command, crate::spawn_helper::Setup::Pty).await? {
Some(child) => child,
None if inherited_fds.is_empty() => {
// Free the first PTY before allocating its portable replacement.
drop(command);
drop(io);
drop(slave);
drop(master);
return spawn_process_portable(program, args, cwd, env, arg0, size).await;
}
None => {
// Explicit descriptors select the shared fallback on Linux. Keep
// terminal setup there when this executable cannot run the helper.
unsafe {
command.inner.pre_exec(configure_child_terminal);
}
command.spawn()?
}
}
};
#[cfg(not(target_os = "linux"))]
let mut child = {
let mut command = StdCommand::new(program);
if let Some(arg0) = arg0 {
command.arg0(arg0);
}
command.current_dir(cwd).env_clear().args(args).envs(env);
if let Some(shell) = &default_shell {
command.env("SHELL", shell);
}
let inherited_fds = inherited_fds.to_vec();
// The child sees the same terminal on stdin, stdout, and stderr.
unsafe {
command
.stdin(Stdio::from(slave.try_clone()?))
.stdout(Stdio::from(slave.try_clone()?))
.stderr(Stdio::from(slave.try_clone()?))
.pre_exec(move || {
configure_child_terminal()?;
close_inherited_fds_except(&inherited_fds);
make_fds_inheritable(&inherited_fds)?;
Ok(())
});
}
command.spawn()?
};
drop(slave);
#[cfg(target_os = "linux")]
let process_group_id = child
.id()
.ok_or_else(|| std::io::Error::other("missing child pid"))?;
#[cfg(not(target_os = "linux"))]
let process_group_id = child.id();
let (writer_tx, writer_rx) = mpsc::channel::<Vec<u8>>(128);
let (stdout_tx, stdout_rx) = mpsc::channel::<Vec<u8>>(128);
let (_stderr_tx, stderr_rx) = mpsc::channel::<Vec<u8>>(1);
let (reader_handle, writer_handle) = io.spawn(stdout_tx, writer_rx, stdin_close_behavior);
let (exit_tx, exit_rx) = oneshot::channel::<i32>();
let exit_status = Arc::new(AtomicBool::new(false));
let wait_exit_status = Arc::clone(&exit_status);
let exit_code = Arc::new(StdMutex::new(None));
let wait_exit_code = Arc::clone(&exit_code);
let on_exit = move |status: std::io::Result<std::process::ExitStatus>| {
let code = match status {
Ok(status) if uses_portable_status => {
portable_pty::ExitStatus::from(status).exit_code() as i32
}
Ok(status) => exit_code_from_status(status),
Err(_) => -1,
};
wait_exit_status.store(true, std::sync::atomic::Ordering::SeqCst);
if let Ok(mut guard) = wait_exit_code.lock() {
*guard = Some(code);
}
let _ = exit_tx.send(code);
};
#[cfg(target_os = "linux")]
let wait_handle = tokio::spawn(async move { on_exit(child.wait().await) });
#[cfg(not(target_os = "linux"))]
let wait_handle = tokio::task::spawn_blocking(move || on_exit(child.wait()));
let handles = PtyHandles {
_slave: None,
_master: PtyMasterHandle::Opaque {
raw_fd: master.as_raw_fd(),
_handle: Box::new(master),
},
};
let handle = ProcessHandle::new(
writer_tx,
Box::new(RawPidTerminator { process_group_id }),
Some(reader_handle),
/*stderr_reader*/ None,
writer_handle,
wait_handle,
exit_status,
exit_code,
Some(handles),
/*resizer*/ None,
);
Ok(SpawnedProcess {
session: handle,
stdout_rx,
stderr_rx,
exit_rx,
})
}
#[cfg(unix)]
fn open_unix_pty(size: TerminalSize) -> Result<(File, File)> {
let mut master: RawFd = -1;
let mut slave: RawFd = -1;
let mut size = libc::winsize {
ws_row: size.rows,
ws_col: size.cols,
ws_xpixel: 0,
ws_ypixel: 0,
};
let winp = std::ptr::addr_of_mut!(size);
let result = unsafe {
libc::openpty(
&mut master,
&mut slave,
std::ptr::null_mut(),
std::ptr::null_mut(),
winp,
)
};
if result != 0 {
anyhow::bail!("failed to openpty: {:?}", std::io::Error::last_os_error());
}
set_cloexec(master)?;
set_cloexec(slave)?;
Ok(unsafe { (File::from_raw_fd(master), File::from_raw_fd(slave)) })
}
#[cfg(unix)]
fn set_cloexec(fd: RawFd) -> std::io::Result<()> {
let flags = unsafe { libc::fcntl(fd, libc::F_GETFD) };
if flags == -1 {
return Err(std::io::Error::last_os_error());
}
let result = unsafe { libc::fcntl(fd, libc::F_SETFD, flags | libc::FD_CLOEXEC) };
if result == -1 {
return Err(std::io::Error::last_os_error());
}
Ok(())
}
/// Called only in the child: never make attachments inheritable in the parent.
#[cfg(unix)]
pub(crate) fn make_fds_inheritable(fds: &[RawFd]) -> std::io::Result<()> {
for &fd in fds {
// SAFETY: fcntl only changes the current process's descriptor flags.
let flags = unsafe { libc::fcntl(fd, libc::F_GETFD) };
if flags == -1 || unsafe { libc::fcntl(fd, libc::F_SETFD, flags & !libc::FD_CLOEXEC) } == -1
{
return Err(std::io::Error::last_os_error());
}
}
Ok(())
}
// macOS needs a fork-safe sweep because recvmsg cannot set close-on-exec.
// Cleanup is best-effort; enumeration and close failures do not prevent launch.
#[cfg(target_os = "macos")]
pub fn close_inherited_fds_except(preserved_fds: &[RawFd]) {
let mut descriptors = [libc::proc_fdinfo {
proc_fd: 0,
proc_fdtype: 0,
}; 1024];
// SAFETY: proc_pidinfo writes descriptor records into the stack buffer.
let bytes = unsafe {
libc::proc_pidinfo(
libc::getpid(),
libc::PROC_PIDLISTFDS,
/*arg*/ 0,
descriptors.as_mut_ptr().cast(),
std::mem::size_of_val(&descriptors) as libc::c_int,
)
};
let close_inheritable = |fd| {
if fd <= libc::STDERR_FILENO || preserved_fds.contains(&fd) {
return;
}
// std::process keeps a CLOEXEC pipe open until exec to report spawn errors.
// SAFETY: fcntl and close only operate on a descriptor owned by this process.
unsafe {
let flags = libc::fcntl(fd, libc::F_GETFD);
if flags >= 0 && flags & libc::FD_CLOEXEC == 0 {
libc::close(fd);
}
}
};
if bytes > 0 && (bytes as usize) < std::mem::size_of_val(&descriptors) {
let count = bytes as usize / std::mem::size_of::<libc::proc_fdinfo>();
for descriptor in descriptors.iter().take(count) {
close_inheritable(descriptor.proc_fd);
}
return;
}
// SAFETY: proc_pidinfo accepts a null buffer when its size is zero.
let descriptor_table_bytes = unsafe {
libc::proc_pidinfo(
libc::getpid(),
libc::PROC_PIDLISTFDS,
/*arg*/ 0,
std::ptr::null_mut(),
/*buffersize*/ 0,
)
};
if descriptor_table_bytes > 0 {
let upper_bound =
descriptor_table_bytes as usize / std::mem::size_of::<libc::proc_fdinfo>();
for fd in libc::STDERR_FILENO + 1..upper_bound as RawFd {
close_inheritable(fd);
}
return;
}
let mut limit = libc::rlimit {
rlim_cur: 0,
rlim_max: 0,
};
// SAFETY: getrlimit writes into the stack-owned resource-limit structure.
if unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &raw mut limit) } == 0 {
let upper_bound = limit.rlim_cur.min(RawFd::MAX as _) as RawFd;
for fd in libc::STDERR_FILENO + 1..upper_bound {
close_inheritable(fd);
}
}
}
// Other Unix platforms use best-effort /dev/fd cleanup.
// Directory enumeration allocates, so this path is not guaranteed fork-safe.
#[cfg(all(unix, not(any(target_os = "linux", target_os = "macos"))))]
pub(crate) fn close_inherited_fds_except(preserved_fds: &[RawFd]) {
if let Ok(dir) = std::fs::read_dir("/dev/fd") {
let mut fds = Vec::new();
for entry in dir {
let num = entry
.ok()
.map(|entry| entry.file_name())
.and_then(|name| name.into_string().ok())
.and_then(|name| name.parse::<RawFd>().ok());
if let Some(num) = num {
if num <= 2 || preserved_fds.contains(&num) {
continue;
}
// Keep CLOEXEC descriptors open so std::process can still use
// its internal exec-error pipe to report spawn failures.
let flags = unsafe { libc::fcntl(num, libc::F_GETFD) };
if flags == -1 || flags & libc::FD_CLOEXEC != 0 {
continue;
}
fds.push(num);
}
}
for fd in fds {
unsafe {
libc::close(fd);
}
}
}
}
/// Establish the controlling terminal and signal state before a PTY target exec.
/// This also runs in the legacy pre-exec callback, so it must stay async-signal-safe.
#[cfg(unix)]
pub(crate) fn configure_child_terminal() -> std::io::Result<()> {
// SAFETY: These operations only change the calling child's signal/session state.
unsafe {
for signo in &[
libc::SIGCHLD,
libc::SIGHUP,
libc::SIGINT,
libc::SIGQUIT,
libc::SIGTERM,
libc::SIGALRM,
] {
libc::signal(*signo, libc::SIG_DFL);
}
let empty_set: libc::sigset_t = std::mem::zeroed();
libc::sigprocmask(libc::SIG_SETMASK, &empty_set, std::ptr::null_mut());
if libc::setsid() == -1 {
return Err(std::io::Error::last_os_error());
}
// stdin now refers to the PTY slave, so make that fd the
// controlling terminal for the child's new session. stdout and
// stderr point at clones of the same slave device.
#[allow(clippy::cast_lossless)]
if libc::ioctl(0, libc::TIOCSCTTY as _, 0) == -1 {
return Err(std::io::Error::last_os_error());
}
}
Ok(())
}
#[cfg(all(test, target_os = "linux"))]
#[path = "pty_linux_tests.rs"]
mod linux_tests;

View File

@@ -0,0 +1,69 @@
//! Portable PTY fallback must release the unsuccessful native launch's resources.
use std::collections::HashMap;
use std::io;
use std::os::fd::AsRawFd;
use std::os::fd::FromRawFd;
use std::os::fd::OwnedFd;
use std::path::Path;
use pretty_assertions::assert_eq;
#[tokio::test]
async fn portable_fallback_releases_native_pty_descriptors() -> anyhow::Result<()> {
if std::env::var_os("CODEX_TEST_PTY_FALLBACK_PRESSURE").is_none() {
let output = std::process::Command::new(std::env::current_exe()?)
.args([
"--exact",
"pty::linux_tests::portable_fallback_releases_native_pty_descriptors",
"--nocapture",
])
.env("CODEX_TEST_PTY_FALLBACK_PRESSURE", "1")
.output()?;
assert!(output.status.success(), "{output:?}");
return Ok(());
}
let source = std::fs::File::open("/dev/null")?;
let mut limit = std::mem::MaybeUninit::<libc::rlimit>::uninit();
// SAFETY: This isolated subprocess owns its descriptor limit and reservations.
assert_eq!(
unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, limit.as_mut_ptr()) },
0
);
let mut limit = unsafe { limit.assume_init() };
limit.rlim_cur = limit.rlim_cur.min(128);
assert_eq!(unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, &limit) }, 0);
let mut occupied = Vec::new();
loop {
let fd = unsafe { libc::fcntl(source.as_raw_fd(), libc::F_DUPFD_CLOEXEC, 3) };
if fd == -1 {
assert_eq!(
io::Error::last_os_error().raw_os_error(),
Some(libc::EMFILE)
);
break;
}
occupied.push(unsafe { OwnedFd::from_raw_fd(fd) });
}
// The initial PTY fits, but helper setup cannot. The portable replacement
// fits only after the initial PTY and its stdio copies have been closed.
anyhow::ensure!(occupied.len() >= 10, "not enough descriptors to reserve");
occupied.truncate(occupied.len() - 10);
let mut child = crate::spawn_pty_process(
"/bin/sh",
&["-c".to_owned(), "printf fallback".to_owned()],
Path::new("/"),
&HashMap::from([("SHELL".to_owned(), "/bin/sh".to_owned())]),
&None,
crate::TerminalSize::default(),
crate::ChildFds::Inherited(&[]),
)
.await?;
drop(occupied);
let mut output = Vec::new();
while let Some(bytes) = child.stdout_rx.recv().await {
output.extend(bytes);
}
assert_eq!((child.exit_rx.await?, output), (0, b"fallback".to_vec()));
Ok(())
}

View File

@@ -0,0 +1,201 @@
//! Linux launch setup in a fresh image, avoiding a fork of the app-server.
//!
//! The shared launcher preserves descriptors and owns reaping. A private socket transfers
//! the target environment after exec. The helper itself starts with an empty
//! environment so parent and target loader settings cannot affect its bootstrap.
//! A prefix followed by EOF acknowledges target exec; setup failures append errno.
//! Exiting without a prefix means the target has not run, so direct spawn is safe.
use std::ffi::CString;
use std::io;
use std::os::fd::AsRawFd;
use std::os::unix::ffi::OsStrExt;
use std::os::unix::net::UnixStream;
use std::path::Path;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use tokio::io::AsyncReadExt;
use tokio::io::AsyncWriteExt;
use crate::child_command::ChildDropPolicy;
/// Setup that needs a fresh, single-threaded image before target exec.
pub(crate) enum Setup {
/// Detach from the terminal and terminate when the parent dies.
Pipe,
/// Establish a controlling terminal and reset interactive signal state.
Pty,
}
pub(super) const HELPER_ARG: &str = "--codex-run-as-process-setup";
pub(super) const MAX_ENV_BYTES: usize = 8 * 1024 * 1024;
pub(super) const REPORT_PREFIX: u8 = 0;
static HELPER_READY: AtomicBool = AtomicBool::new(false);
const HELPER_EXE: &str = "/proc/self/exe";
/// Dispatch internal setup, or register this executable for later helper launches.
/// Pass the full argument list before starting threads or application initialization.
/// Executables that do not register retain their existing spawning behavior.
/// Before Rust initializes argv (notably musl constructors), read the kernel's
/// command line so re-execution can dispatch before registering the helper.
pub fn init_spawn_helper(args: impl IntoIterator<Item = std::ffi::OsString>) {
use std::os::unix::ffi::OsStringExt;
let mut args = args.into_iter().collect::<Vec<_>>();
if args.is_empty() {
let Ok(command_line) = std::fs::read("/proc/self/cmdline") else {
return;
};
let Some(command_line) = command_line.strip_suffix(&[0]) else {
return;
};
args = command_line
.split(|byte| *byte == 0)
.map(|arg| std::ffi::OsString::from_vec(arg.to_vec()))
.collect();
}
let mut args = args.into_iter().skip(1);
if args.next().as_deref() == Some(std::ffi::OsStr::new(HELPER_ARG)) {
crate::spawn_helper_main::dispatch(args);
}
if std::fs::metadata(HELPER_EXE).is_ok() {
HELPER_READY.store(true, Ordering::Relaxed);
}
}
pub(crate) fn is_available() -> bool {
HELPER_READY.load(Ordering::Relaxed)
}
/// Start the helper and await target exec without blocking a runtime worker.
/// Return `None` when registration, helper resource setup, or helper launch fails,
/// preserving compatibility with callers and sandboxes that only permit the target.
pub(crate) async fn spawn(
target: &crate::Command,
setup: Setup,
) -> io::Result<Option<crate::Child>> {
target.validate()?;
if !is_available() {
return Ok(None);
}
let settings = target.inner.as_std();
let mut environment = Vec::new();
for (key, value) in settings.get_envs().filter_map(|(k, v)| v.map(|v| (k, v))) {
let mut entry = key.as_bytes().to_vec();
entry.push(b'=');
entry.extend_from_slice(value.as_bytes());
environment.extend_from_slice(CString::new(entry)?.as_bytes_with_nul());
}
if environment.len() > MAX_ENV_BYTES {
return Err(io::Error::from_raw_os_error(libc::E2BIG));
}
// Helper-only resources may be denied or exhaust descriptors even when
// the original command can still spawn. Drop them before trying the fallback.
let prepared = (|| -> io::Result<_> {
let (control, helper_control) = UnixStream::pair()?;
let helper_control = crate::child::posix::child_fd(helper_control.into())?;
control.set_nonblocking(true)?;
let control = tokio::net::UnixStream::from_std(control)?;
let fd = helper_control.as_raw_fd();
let mut helper = crate::Command::new(HELPER_EXE);
helper
.arg(HELPER_ARG)
.arg(fd.to_string())
.arg(std::process::id().to_string())
.arg(match setup {
Setup::Pipe => "pipe",
Setup::Pty => "pty",
})
.arg(
target
.inherited_fds
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
.join(","),
)
.arg(settings.get_current_dir().unwrap_or_else(|| Path::new(".")))
.arg(settings.get_program())
.arg(target.arg0.as_deref().unwrap_or(settings.get_program()))
.args(settings.get_args())
.drop_policy(ChildDropPolicy::ReapOnly)
.stdin(match &target.stdin {
crate::ChildStdin::Piped => crate::ChildStdin::Piped,
crate::ChildStdin::Null => crate::ChildStdin::Null,
crate::ChildStdin::File(fd) => crate::ChildStdin::File(fd.try_clone()?),
});
helper.stdout_file = target
.stdout_file
.as_ref()
.map(std::os::fd::OwnedFd::try_clone)
.transpose()?;
helper.stderr_file = target
.stderr_file
.as_ref()
.map(std::os::fd::OwnedFd::try_clone)
.transpose()?;
helper.inherited_fds = target.inherited_fds.clone();
helper.inherited_fds.push(fd);
Ok((control, helper, helper_control))
})();
let (mut control, helper, helper_control) = match prepared {
Ok(prepared) => prepared,
Err(_) => return Ok(None),
};
// Call the shared native backend directly: the helper needs no child callbacks.
// Unsupported libc/platform setup falls back at the original target boundary.
let child = match crate::child::posix::NativeChild::spawn(&helper) {
Ok(Some(child)) => child,
Ok(None) | Err(_) => return Ok(None),
};
drop(helper);
drop(helper_control);
// All inherited descriptors were passed to the helper synchronously, before
// the first suspension. The caller can now close its copies safely.
let mut starting = StartingChild(Some(child));
let sent = async {
control
.write_all(&(environment.len() as u32).to_le_bytes())
.await?;
control.write_all(&environment).await
}
.await;
let mut report = Vec::new();
let received = control.take(/*limit*/ 6).read_to_end(&mut report).await;
if report.is_empty() {
// Bootstrap can fail before dispatch (for example in the dynamic loader).
// No prefix means the target never ran. Kill and reap the incomplete
// helper before falling back, including when its socket was reset.
return Ok(None);
}
if (report.len() != 1 && report.len() != 5) || report.first() != Some(&REPORT_PREFIX) {
sent?;
received?;
return Err(io::Error::other("invalid spawn helper report"));
}
if report.len() == 5 {
// Prefer the setup errno when failure closed the socket during env transfer.
let errno = i32::from_le_bytes(report[1..].try_into().map_err(io::Error::other)?);
return Err(io::Error::from_raw_os_error(errno));
}
sent?;
received?;
Ok(starting.0.take())
}
/// Kill incomplete launches on cancellation; the shared child still owns reaping.
struct StartingChild(Option<crate::Child>);
impl Drop for StartingChild {
fn drop(&mut self) {
if let Some(pid) = self.0.as_ref().and_then(crate::Child::id) {
// SAFETY: The child retains this unreaped PID. Kill covers both sides
// of setsid and the window after target exec but before acknowledgement.
unsafe {
libc::kill(-(pid as libc::pid_t), libc::SIGKILL);
libc::kill(pid as libc::pid_t, libc::SIGKILL);
}
}
}
}

View File

@@ -0,0 +1,119 @@
//! Early executable dispatch for Linux pipe and PTY spawns. All child setup happens
//! after exec, before application initialization or runtime threads exist.
//! A report prefix precedes target exec; failures append errno before exit.
use crate::spawn_helper::MAX_ENV_BYTES;
use crate::spawn_helper::REPORT_PREFIX;
use std::fs::File;
use std::io;
use std::io::Read;
use std::io::Write;
use std::os::fd::FromRawFd;
use std::os::unix::ffi::OsStrExt;
use std::os::unix::process::CommandExt;
use std::process::Command;
/// Complete setup in the fresh, single-threaded image, then replace it with the target.
pub(super) fn dispatch(mut args: impl Iterator<Item = std::ffi::OsString>) -> ! {
let Some(control_fd) = args
.next()
.and_then(|arg| arg.to_str()?.parse::<i32>().ok())
.filter(|fd| *fd > 2 && unsafe { libc::fcntl(*fd, libc::F_GETFD) } != -1)
else {
std::process::exit(127);
};
// The parent passes ownership of this descriptor through posix_spawn.
let mut control = unsafe { File::from_raw_fd(control_fd) };
let mut reported = false;
let result = (|| -> io::Result<()> {
let parent_pid = args
.next()
.and_then(|arg| arg.to_str()?.parse::<libc::pid_t>().ok())
.filter(|pid| *pid > 0)
.ok_or_else(|| io::Error::from_raw_os_error(libc::EINVAL))?;
let setup = args
.next()
.ok_or_else(|| io::Error::from_raw_os_error(libc::EINVAL))?;
let setup = match setup.to_str() {
Some("pipe") => crate::spawn_helper::Setup::Pipe,
Some("pty") => crate::spawn_helper::Setup::Pty,
_ => return Err(io::Error::from_raw_os_error(libc::EINVAL)),
};
let preserved = args
.next()
.ok_or_else(|| io::Error::from_raw_os_error(libc::EINVAL))?;
let preserved = preserved
.to_str()
.ok_or_else(|| io::Error::from_raw_os_error(libc::EINVAL))?;
let inherited_fds = preserved
.split(',')
.filter(|fd| !fd.is_empty())
.map(str::parse::<i32>)
.collect::<Result<Vec<_>, _>>()
.map_err(|_| io::Error::from_raw_os_error(libc::EINVAL))?;
let cwd = args
.next()
.ok_or_else(|| io::Error::from_raw_os_error(libc::EINVAL))?;
let program = args
.next()
.ok_or_else(|| io::Error::from_raw_os_error(libc::EINVAL))?;
let arg0 = args
.next()
.ok_or_else(|| io::Error::from_raw_os_error(libc::EINVAL))?;
let mut command = Command::new(program);
command.current_dir(cwd).arg0(arg0).args(args).env_clear();
if unsafe { libc::fcntl(control_fd, libc::F_SETFD, libc::FD_CLOEXEC) } == -1 {
return Err(io::Error::last_os_error());
}
match setup {
crate::spawn_helper::Setup::Pipe => {
crate::process_group::detach_from_tty()?;
crate::process_group::set_parent_death_signal(parent_pid)?;
}
crate::spawn_helper::Setup::Pty => crate::pty::configure_child_terminal()?,
}
// Allocation is safe in this fresh, single-threaded image. CLOEXEC
// leaves the report socket open until the target actually execs.
crate::pty::close_inherited_fds_except(&inherited_fds);
#[cfg(test)]
crate::spawn_helper_tests::pause_handshake("environment")?;
let mut size = [0; 4];
control.read_exact(&mut size)?;
let size = u32::from_le_bytes(size) as usize;
if size > MAX_ENV_BYTES {
return Err(io::Error::from_raw_os_error(libc::E2BIG));
}
let mut environment = vec![0; size];
control.read_exact(&mut environment)?;
for entry in environment
.split(|byte| *byte == 0)
.filter(|entry| !entry.is_empty())
{
let separator = entry
.iter()
.position(|byte| *byte == b'=')
.ok_or_else(|| io::Error::from_raw_os_error(libc::EINVAL))?;
command.env(
std::ffi::OsStr::from_bytes(&entry[..separator]),
std::ffi::OsStr::from_bytes(&entry[separator + 1..]),
);
}
#[cfg(test)]
crate::spawn_helper_tests::pause_handshake("report")?;
control.write_all(&[REPORT_PREFIX])?;
reported = true;
#[cfg(test)]
crate::spawn_helper_tests::pause_handshake("exec")?;
Err(command.exec())
})();
if !reported {
let _ = control.write_all(&[REPORT_PREFIX]);
}
let errno = result
.err()
.and_then(|error| error.raw_os_error())
.unwrap_or(libc::EIO);
let _ = control.write_all(&errno.to_le_bytes());
// No diagnostics: program arguments and environment may contain secrets.
std::process::exit(127);
}

View File

@@ -0,0 +1,802 @@
//! Exercise the exec-helper boundary with real children, including descriptors,
//! startup errors, cancellation cleanup, and concurrent exit notification.
//! Procfs-dependent fixtures are skipped when procfs is unavailable.
use std::collections::HashMap;
use std::io;
use std::os::fd::AsFd;
use std::os::fd::AsRawFd;
use std::os::fd::FromRawFd;
use std::os::fd::OwnedFd;
use std::path::Path;
use std::time::Duration;
use pretty_assertions::assert_eq;
use crate::spawn_pipe_process;
use crate::spawn_pipe_process_no_stdin;
const PARENT_FIXTURE: &str = "--codex-spawn-test-parent";
const CHILD_FIXTURE: &str = "--codex-spawn-test-child";
#[ctor::ctor]
fn initialize_spawn_helper() {
if let Ok(arguments) = std::fs::read("/proc/self/cmdline") {
let mut arguments = arguments.split(|byte| *byte == 0).skip(1);
if arguments.next() == Some(crate::spawn_helper::HELPER_ARG.as_bytes())
&& arguments.any(|arg| arg == b"--codex-test-fail-helper-bootstrap")
{
// Simulate a loader failure before the helper can report setup.
std::process::exit(127);
}
}
#[cfg(target_env = "gnu")]
if std::env::var_os("CODEX_TEST_PARENT_LOADER_ENV").is_some() {
// SAFETY: This isolated fixture is still single-threaded, before the test
// harness starts. Simulate .env loading after the dynamic loader ran.
unsafe { std::env::set_var("LD_TRACE_LOADED_OBJECTS", "1") };
}
if std::env::var_os("CODEX_TEST_EARLY_HELPER_ARGV").is_some() {
crate::init_spawn_helper(std::iter::empty());
} else {
crate::init_spawn_helper(std::env::args_os());
}
let Ok(arguments) = process_arguments() else {
return;
};
let mut arguments = arguments.into_iter().skip(1);
let argument = arguments.next();
if argument.as_deref() == Some(std::ffi::OsStr::new(CHILD_FIXTURE)) {
let Some(cleanup_fd) = arguments
.next()
.and_then(|argument| argument.to_str()?.parse().ok())
else {
std::process::exit(1);
};
// SAFETY: The parent passed this owned read end as an inherited descriptor.
let mut cleanup = unsafe { std::fs::File::from_raw_fd(cleanup_fd) };
// Preserve a final empty argument through musl's constructor argv fallback.
assert_eq!(arguments.collect::<Vec<_>>(), [std::ffi::OsString::new()]);
let mut signal = 0;
assert_eq!(
unsafe { libc::prctl(libc::PR_GET_PDEATHSIG, &mut signal) },
0
);
assert_eq!(signal, libc::SIGTERM);
println!("{}", std::process::id());
// Only the test owns the write end. EOF provides cleanup if the
// parent-death signal fails, without a timer that could mask that failure.
match std::io::copy(&mut cleanup, &mut std::io::sink()) {
Ok(_) => std::process::exit(0),
Err(_) => std::process::exit(1),
}
}
if argument.as_deref() == Some(std::ffi::OsStr::new(PARENT_FIXTURE)) {
let result = (|| -> anyhow::Result<()> {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()?;
runtime.block_on(async {
let cleanup = std::io::stdin().as_fd().try_clone_to_owned()?;
// The shared launcher only preserves explicitly inheritable fds.
assert_eq!(
unsafe { libc::fcntl(cleanup.as_raw_fd(), libc::F_SETFD, 0) },
0
);
let mut child = spawn_pipe_process_no_stdin(
"/proc/self/exe",
&[
CHILD_FIXTURE.to_string(),
cleanup.as_raw_fd().to_string(),
String::new(),
],
Path::new("/"),
&HashMap::new(),
&None,
&[cleanup.as_raw_fd()],
)
.await?;
let ready = child
.stdout_rx
.recv()
.await
.ok_or_else(|| io::Error::other("fixture child did not start"))?;
std::io::Write::write_all(&mut std::io::stdout(), &ready)?;
// Kill this parent without destructors so session cleanup
// cannot mask the kernel's parent-death signal behavior.
std::future::pending::<()>().await;
anyhow::Ok(())
})
})();
if let Err(error) = result {
eprintln!("spawn fixture failed: {error}");
std::process::exit(1);
}
std::process::exit(0);
}
}
/// Pin a process identity so exit observation and cleanup cannot follow PID reuse.
fn open_pidfd(pid: libc::pid_t) -> io::Result<OwnedFd> {
// SAFETY: pidfd_open takes a PID and flags, and returns a new owned descriptor.
let fd = unsafe { libc::syscall(libc::SYS_pidfd_open, pid, 0u32) };
if fd == -1 {
return Err(io::Error::last_os_error());
}
// SAFETY: The successful syscall returned a fresh descriptor owned by this call.
Ok(unsafe { OwnedFd::from_raw_fd(fd as _) })
}
#[tokio::test]
async fn helper_target_dies_when_parent_is_killed() -> anyhow::Result<()> {
use tokio::io::AsyncBufReadExt;
if !Path::new("/proc/self/exe").exists() || process_arguments().is_err() {
eprintln!("skipping parent-death test: procfs is unavailable");
return Ok(());
}
// Check support and sandbox permissions before creating fixtures.
match open_pidfd(std::process::id() as _) {
Ok(_) => {}
Err(error)
if matches!(
error.raw_os_error(),
Some(libc::ENOSYS | libc::EPERM | libc::EACCES)
) =>
{
eprintln!("skipping parent-death test: pidfd_open is unavailable");
return Ok(());
}
Err(error) => return Err(error.into()),
}
let mut parent = tokio::process::Command::new(std::env::current_exe()?)
.arg(PARENT_FIXTURE)
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.kill_on_drop(true)
.spawn()?;
// Keep the cleanup pipe open independently of the parent's lifetime.
let cleanup = parent.stdin.take().expect("parent fixture stdin is piped");
let mut output = tokio::io::BufReader::new(parent.stdout.take().unwrap()).lines();
let pid = tokio::time::timeout(Duration::from_secs(5), output.next_line())
.await??
.expect("child reports its PID after verifying PDEATHSIG")
.parse::<libc::pid_t>()?;
// The fixture child waits on the cleanup pipe while its parent is alive.
let child = tokio::io::unix::AsyncFd::new(open_pidfd(pid)?)?;
parent.kill().await?;
let stopped = tokio::time::timeout(Duration::from_secs(5), child.readable()).await;
drop(cleanup);
if stopped.is_err() {
drop(tokio::time::timeout(Duration::from_secs(5), child.readable()).await??);
}
drop(stopped??);
Ok(())
}
/// Probe an actual helper launch before requiring the native handshake.
async fn native_helper_available() -> anyhow::Result<bool> {
if !Path::new("/proc/self/exe").exists() || process_arguments().is_err() {
return Ok(false);
}
let command = crate::Command::new("/bin/true");
let Some(child) =
crate::spawn_helper::spawn(&command, crate::spawn_helper::Setup::Pipe).await?
else {
return Ok(false);
};
Ok(child.wait_with_output().await?.status.success())
}
#[tokio::test]
async fn helper_preserves_cwd_env_arg0_and_streams() -> anyhow::Result<()> {
thread_local! { static FORKS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; }
extern "C" fn after_fork() {
FORKS.with(|count| count.set(count.get() + 1));
}
FORKS.with(|count| count.set(0));
assert_eq!(
unsafe { libc::pthread_atfork(None, Some(after_fork), None) },
0
);
let mut child = spawn_pipe_process(
"sh",
&["-c".into(), "read value; printf '%s|%s|%s|%s' \"$0\" \"$MARKER\" \"$PWD\" \"$value\"; printf error >&2; exit 23".into()],
Path::new("/tmp"),
&HashMap::from([("PATH".into(), "/bin".into()), ("MARKER".into(), "a value".into())]),
&Some("custom-arg0".into()),
&[],
).await?;
if native_helper_available().await? {
assert_eq!(FORKS.with(std::cell::Cell::get), 0);
}
child
.session
.writer_sender()
.send(b"input\n".to_vec())
.await?;
child.session.close_stdin();
let mut stdout = Vec::new();
let mut stderr = Vec::new();
while let Some(chunk) = child.stdout_rx.recv().await {
stdout.extend(chunk);
}
while let Some(chunk) = child.stderr_rx.recv().await {
stderr.extend(chunk);
}
assert_eq!(
(stdout, stderr, child.exit_rx.await?),
(
b"custom-arg0|a value|/tmp|input".to_vec(),
b"error".to_vec(),
23
)
);
Ok(())
}
#[tokio::test]
async fn helper_reports_target_exec_and_cwd_errno() {
for (program, cwd, errno) in [
("/codex-missing-spawn-target", "/", libc::ENOENT),
("/bin/sh", "/codex-missing-spawn-directory", libc::ENOENT),
("/", "/", libc::EACCES),
] {
let result =
spawn_pipe_process_no_stdin(program, &[], Path::new(cwd), &HashMap::new(), &None, &[])
.await;
let error = result.expect_err("invalid target must fail at spawn");
assert_eq!(
error
.downcast_ref::<io::Error>()
.and_then(io::Error::raw_os_error),
Some(errno)
);
}
}
#[tokio::test]
async fn target_loader_environment_does_not_disable_helper_dispatch() -> anyhow::Result<()> {
if !Path::new("/proc/self/exe").exists() {
eprintln!("skipping loader isolation test: procfs is unavailable");
return Ok(());
}
// glibc's loader exits before main when this is set. It must affect the
// requested executable only, after the helper has completed its setup.
let mut command = crate::Command::new("/codex-missing-loader-env-target");
command.current_dir("/").env("LD_TRACE_LOADED_OBJECTS", "1");
// A failed helper bootstrap returns None; require the helper's target error.
let Err(error) = crate::spawn_helper::spawn(&command, crate::spawn_helper::Setup::Pipe).await
else {
panic!("helper must reach target exec despite loader settings");
};
assert_eq!(error.raw_os_error(), Some(libc::ENOENT));
Ok(())
}
#[tokio::test]
async fn large_environment_can_cross_the_control_socket() -> anyhow::Result<()> {
if !Path::new("/proc/self/exe").exists() || process_arguments().is_err() {
eprintln!("skipping control-socket test: procfs is unavailable");
return Ok(());
}
// Stay below Linux's minimum ARG_MAX; cancellation tests force socket backpressure.
let mut command = crate::Command::new("/bin/sh");
command
.args([
"-c",
"test ${#LARGE_0} -eq 8192 && test ${#LARGE_7} -eq 8192",
])
.current_dir("/")
.envs((0..8).map(|index| (format!("LARGE_{index}"), "x".repeat(8_192))));
let child = tokio::time::timeout(
Duration::from_secs(5),
crate::spawn_helper::spawn(&command, crate::spawn_helper::Setup::Pipe),
)
.await??
.expect("native helper must transfer the environment");
assert!(child.wait_with_output().await?.status.success());
Ok(())
}
#[tokio::test]
async fn helper_preserves_inheritable_fds_and_closes_unrequested_fds() -> anyhow::Result<()> {
let file = std::fs::File::open("/dev/null")?;
if std::fs::metadata(format!("/proc/self/fd/{}", file.as_raw_fd())).is_err() {
eprintln!("skipping descriptor inspection test: procfs is unavailable");
return Ok(());
}
let descriptors = [file.try_clone()?, file.try_clone()?];
let preserved = descriptors[0].as_raw_fd();
let unwanted = descriptors[1].as_raw_fd();
assert_eq!(unsafe { libc::fcntl(unwanted, libc::F_SETFD, 0) }, 0);
assert_eq!(unsafe { libc::fcntl(preserved, libc::F_SETFD, 0) }, 0);
let script = format!("test -e /proc/self/fd/{preserved} && test ! -e /proc/self/fd/{unwanted}");
let mut command = crate::Command::new("/bin/sh");
command
.args(["-c", &script])
.current_dir("/")
.descriptor_policy(crate::DescriptorPolicy::Explicit)
.preserve_fds(&[preserved]);
let child = crate::spawn_helper::spawn(&command, crate::spawn_helper::Setup::Pipe)
.await?
.expect("native helper must preserve requested descriptors");
assert!(child.wait_with_output().await?.status.success());
assert_eq!(unsafe { libc::fcntl(preserved, libc::F_GETFD) }, 0);
assert_eq!(unsafe { libc::fcntl(unwanted, libc::F_GETFD) }, 0);
Ok(())
}
// Test-only helper synchronization travels as target arguments and inherited
// descriptors. Production dispatch has no environment switches or pause points.
pub(crate) fn pause_handshake(phase: &str) -> io::Result<()> {
let arguments = process_arguments()?;
let marker = format!("--codex-spawn-test-pause={phase}");
let Some(index) = arguments
.iter()
.position(|argument| argument == std::ffi::OsStr::new(&marker))
else {
return Ok(());
};
let fd = arguments
.get(index + 1)
.and_then(|argument| argument.to_str())
.and_then(|argument| argument.parse::<i32>().ok())
.ok_or_else(|| io::Error::other("invalid handshake notification fd"))?;
let pid = std::process::id().to_le_bytes();
assert_eq!(
unsafe { libc::write(fd, pid.as_ptr().cast(), pid.len()) },
4
);
loop {
unsafe { libc::pause() };
}
}
// Keep the inherited notification socket alive inside the future, so the
// cancellation tests exercise the same fd ownership as a real spawn caller.
fn paused_spawn(
phase: &str,
) -> io::Result<(
impl std::future::Future<Output = anyhow::Result<crate::SpawnedProcess>>,
tokio::net::UnixStream,
)> {
let (notify, helper_notify) = std::os::unix::net::UnixStream::pair()?;
notify.set_nonblocking(true)?;
let notify = tokio::net::UnixStream::from_std(notify)?;
assert_eq!(
unsafe { libc::fcntl(helper_notify.as_raw_fd(), libc::F_SETFD, 0) },
0
);
let arguments = vec![
"-c".into(),
"printf fallback".into(),
"sh".into(),
format!("--codex-spawn-test-pause={phase}"),
helper_notify.as_raw_fd().to_string(),
];
let env = if phase == "environment" {
// Exceed socket capacity to test cancellation of an environment write.
HashMap::from([("LARGE".into(), "x".repeat(2 * 1024 * 1024))])
} else {
HashMap::new()
};
let spawn = async move {
spawn_pipe_process_no_stdin(
"/bin/sh",
&arguments,
Path::new("/"),
&env,
&None,
&[helper_notify.as_raw_fd()],
)
.await
};
Ok((spawn, notify))
}
async fn paused_pid(
spawn: std::pin::Pin<
&mut impl std::future::Future<Output = anyhow::Result<crate::SpawnedProcess>>,
>,
notify: &mut tokio::net::UnixStream,
) -> anyhow::Result<libc::pid_t> {
use tokio::io::AsyncReadExt;
let mut pid = [0; 4];
tokio::time::timeout(Duration::from_secs(5), async {
tokio::select! {
biased;
result = spawn => panic!("helper returned before cancellation: {result:?}"),
result = notify.read_exact(&mut pid) => result,
}
})
.await??;
Ok(u32::from_le_bytes(pid) as libc::pid_t)
}
fn is_reaped(pid: libc::pid_t) -> bool {
let mut info = std::mem::MaybeUninit::<libc::siginfo_t>::zeroed();
// SAFETY: Observe our child without reaping it or probing an unrelated reused PID.
if unsafe {
libc::waitid(
libc::P_PID,
pid as libc::id_t,
info.as_mut_ptr(),
libc::WEXITED | libc::WNOHANG | libc::WNOWAIT,
)
} == 0
{
return false;
}
assert_eq!(
io::Error::last_os_error().raw_os_error(),
Some(libc::ECHILD)
);
true
}
fn wait_for_fallback_reaping(pid: libc::pid_t) -> anyhow::Result<()> {
let deadline = std::time::Instant::now() + Duration::from_secs(5);
while !is_reaped(pid) {
anyhow::ensure!(std::time::Instant::now() < deadline, "child was not reaped");
std::thread::sleep(Duration::from_millis(10));
}
Ok(())
}
#[tokio::test]
async fn cancelling_real_helper_handshakes_kills_and_reaps() -> anyhow::Result<()> {
if !native_helper_available().await? {
eprintln!("skipping helper handshake test: native spawning is unavailable");
return Ok(());
}
for phase in ["environment", "report", "exec"] {
let (spawn, mut notify) = paused_spawn(phase)?;
let mut spawn = Box::pin(spawn);
let pid = paused_pid(spawn.as_mut(), &mut notify).await?;
drop(spawn);
tokio::time::timeout(Duration::from_secs(5), async {
while !is_reaped(pid) {
tokio::task::yield_now().await;
}
})
.await?;
}
Ok(())
}
#[test]
fn runtime_shutdown_retains_reaping_ownership_without_head_of_line_blocking() -> anyhow::Result<()>
{
let mut children = Vec::new();
for _ in 0..2 {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()?;
let child = runtime.block_on(async {
let mut child = spawn_pipe_process_no_stdin(
"/bin/sh",
&["-c".into(), "echo $$; exec sleep 60".into()],
Path::new("/"),
&HashMap::new(),
&None,
&[],
)
.await?;
let output = tokio::time::timeout(Duration::from_secs(5), child.stdout_rx.recv())
.await?
.expect("target reports pid");
let pid = std::str::from_utf8(&output)?
.trim()
.parse::<libc::pid_t>()?;
anyhow::Ok((child, pid))
})?;
// Shutdown completes the first child's transfer to the shared reaper
// before the second can arrive, while both children remain alive.
drop(runtime);
children.push(child);
}
for index in [1, 0] {
children[index].0.session.terminate();
wait_for_fallback_reaping(children[index].1)?;
if index == 1 {
assert_eq!(unsafe { libc::kill(children[0].1, 0) }, 0);
}
}
Ok(())
}
#[test]
fn cancelling_startup_after_runtime_shutdown_reaps_helper() -> anyhow::Result<()> {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()?;
if !runtime.block_on(native_helper_available())? {
eprintln!("skipping helper handshake test: native spawning is unavailable");
return Ok(());
}
let (spawn, mut notify) = {
let _entered = runtime.enter();
paused_spawn("environment")?
};
let mut spawn = Box::pin(spawn);
let pid = runtime.block_on(paused_pid(spawn.as_mut(), &mut notify))?;
drop(runtime);
drop(spawn);
wait_for_fallback_reaping(pid)
}
/// Read argv before Rust's musl startup has initialized std::env::args_os.
fn process_arguments() -> io::Result<Vec<std::ffi::OsString>> {
use std::os::unix::ffi::OsStringExt;
let command_line = std::fs::read("/proc/self/cmdline")?;
Ok(command_line
.strip_suffix(&[0])
.unwrap_or(&command_line)
.split(|byte| *byte == 0)
.map(|arg| std::ffi::OsString::from_vec(arg.to_vec()))
.collect())
}
#[tokio::test]
async fn helper_exit_before_acknowledgement_falls_back() -> anyhow::Result<()> {
if !native_helper_available().await? {
eprintln!("skipping helper handshake test: native spawning is unavailable");
return Ok(());
}
let (spawn, mut notify) = paused_spawn("report")?;
let mut spawn = Box::pin(spawn);
let pid = paused_pid(spawn.as_mut(), &mut notify).await?;
assert_eq!(unsafe { libc::kill(pid, libc::SIGKILL) }, 0);
let mut child = tokio::time::timeout(Duration::from_secs(5), spawn).await??;
let mut stdout = Vec::new();
while let Some(chunk) = child.stdout_rx.recv().await {
stdout.extend(chunk);
}
assert_eq!((child.exit_rx.await?, stdout), (0, b"fallback".to_vec()));
wait_for_fallback_reaping(pid)
}
#[tokio::test]
async fn pty_helper_establishes_a_controlling_terminal_without_forking() -> anyhow::Result<()> {
use std::cell::Cell;
thread_local! { static FORKS: Cell<usize> = const { Cell::new(0) }; }
extern "C" fn after_fork() {
FORKS.with(|count| count.set(count.get() + 1));
}
FORKS.with(|count| count.set(0));
// SAFETY: The parent callback only updates initialized thread-local storage.
assert_eq!(
unsafe {
libc::pthread_atfork(/*prepare*/ None, Some(after_fork), /*child*/ None)
},
0
);
let mut spawned = crate::spawn_pty_process(
"/bin/sh",
&[
"-c".to_owned(),
"test -t 0 && test -t 1 && test -t 2 && printf ready >/dev/tty".to_owned(),
],
std::path::Path::new("."),
&std::env::vars().collect(),
/*arg0*/ &None,
crate::TerminalSize::default(),
crate::ChildFds::Inherited(&[]),
)
.await?;
let mut output = Vec::new();
while let Some(chunk) = spawned.stdout_rx.recv().await {
output.extend(chunk);
}
assert_eq!((spawned.exit_rx.await?, output), (0, b"ready".to_vec()));
if native_helper_available().await? {
assert_eq!(FORKS.with(Cell::get), 0);
}
Ok(())
}
#[tokio::test]
async fn pty_helper_preserves_portable_signal_exit_status() -> anyhow::Result<()> {
let env = std::env::vars().collect();
for program in ["/bin/sh", "sh"] {
let spawned = crate::spawn_pty_process(
program,
&["-c".to_owned(), "kill -TERM $$".to_owned()],
std::path::Path::new("."),
&env,
/*arg0*/ &None,
crate::TerminalSize::default(),
crate::ChildFds::Inherited(&[]),
)
.await?;
assert_eq!(spawned.exit_rx.await?, 1);
}
Ok(())
}
#[test]
fn helper_dispatch_before_rust_initializes_argv() -> anyhow::Result<()> {
let output = std::process::Command::new(std::env::current_exe()?)
.args([
"--exact",
"tests::spawn_helper_tests::helper_preserves_cwd_env_arg0_and_streams",
"--nocapture",
])
.env("CODEX_TEST_EARLY_HELPER_ARGV", "1")
.output()?;
assert!(output.status.success(), "{output:?}");
Ok(())
}
#[tokio::test]
async fn helper_bootstrap_failure_falls_back_to_direct_spawn() -> anyhow::Result<()> {
let mut child = spawn_pipe_process_no_stdin(
"/bin/echo",
&["--codex-test-fail-helper-bootstrap".into()],
Path::new("/"),
&HashMap::new(),
&None,
&[],
)
.await?;
let mut stdout = Vec::new();
while let Some(chunk) = child.stdout_rx.recv().await {
stdout.extend(chunk);
}
assert_eq!(
(child.exit_rx.await?, stdout),
(0, b"--codex-test-fail-helper-bootstrap\n".to_vec())
);
Ok(())
}
#[tokio::test]
async fn helper_control_socket_survives_closed_stdio() -> anyhow::Result<()> {
use std::os::fd::AsRawFd;
use std::os::fd::BorrowedFd;
if std::env::var_os("CODEX_TEST_HELPER_CLOSED_STDIO").is_none() {
let output = std::process::Command::new(std::env::current_exe()?)
.args([
"--exact",
"tests::spawn_helper_tests::helper_control_socket_survives_closed_stdio",
"--nocapture",
])
.env("CODEX_TEST_HELPER_CLOSED_STDIO", "1")
.output()?;
assert!(output.status.success(), "{output:?}");
return Ok(());
}
let mut command = crate::Command::new("/bin/echo");
command.arg("closed-stdio").stdin(crate::ChildStdin::Null);
let Some(probe) =
crate::spawn_helper::spawn(&command, crate::spawn_helper::Setup::Pipe).await?
else {
return Ok(());
};
assert!(probe.wait_with_output().await?.status.success());
// This isolated subprocess has an initialized runtime. Close stdio only
// after saving it, so the helper socket really receives descriptor 0 or 1.
let saved = [0, 1]
.map(|fd| unsafe { BorrowedFd::borrow_raw(fd) }.try_clone_to_owned())
.into_iter()
.collect::<io::Result<Vec<_>>>()?;
for fd in [0, 1] {
assert_eq!(unsafe { libc::close(fd) }, 0);
}
let result = crate::spawn_helper::spawn(&command, crate::spawn_helper::Setup::Pipe).await;
for (fd, saved) in [0, 1].into_iter().zip(saved) {
assert_eq!(unsafe { libc::dup2(saved.as_raw_fd(), fd) }, fd);
}
let output = result
.expect("closed stdio must not break the helper handshake")
.expect("closed stdio must not force a fallback")
.wait_with_output()
.await?;
assert_eq!(
(output.status.code(), output.stdout, output.stderr),
(Some(0), b"closed-stdio\n".to_vec(), vec![])
);
Ok(())
}
#[tokio::test]
async fn helper_descriptor_pressure_falls_back_to_direct_spawn() -> anyhow::Result<()> {
use std::os::fd::AsRawFd;
use std::os::fd::FromRawFd;
use std::os::fd::OwnedFd;
if std::env::var_os("CODEX_TEST_HELPER_FD_PRESSURE").is_none() {
let output = std::process::Command::new(std::env::current_exe()?)
.args([
"--exact",
"tests::spawn_helper_tests::helper_descriptor_pressure_falls_back_to_direct_spawn",
"--nocapture",
])
.env("CODEX_TEST_HELPER_FD_PRESSURE", "1")
.output()?;
assert!(output.status.success(), "{output:?}");
return Ok(());
}
let source = std::fs::File::open("/dev/null")?;
let originals = (0..16)
.map(|_| {
// SAFETY: fcntl duplicates a live descriptor into a newly owned slot.
let fd = unsafe { libc::fcntl(source.as_raw_fd(), libc::F_DUPFD, 3) };
anyhow::ensure!(fd >= 3, "{}", io::Error::last_os_error());
Ok(unsafe { OwnedFd::from_raw_fd(fd) })
})
.collect::<anyhow::Result<Vec<_>>>()?;
let targets = originals.iter().map(AsRawFd::as_raw_fd).collect::<Vec<_>>();
let mut command = crate::Command::new("/bin/echo");
command
.arg("fallback")
.stdin(crate::ChildStdin::File(source.try_clone()?.into()))
.process_mode(crate::ProcessMode::NewSession)
.terminate_on_parent_death()
.preserve_fds(&targets);
// Restrict only this subprocess, after constructing the target's stdio.
let mut limit = std::mem::MaybeUninit::<libc::rlimit>::uninit();
assert_eq!(
unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, limit.as_mut_ptr()) },
0
);
let mut limit = unsafe { limit.assume_init() };
limit.rlim_cur = limit.rlim_cur.min(128);
assert_eq!(unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, &limit) }, 0);
let mut occupied = Vec::new();
loop {
let fd = unsafe { libc::fcntl(source.as_raw_fd(), libc::F_DUPFD_CLOEXEC, 3) };
if fd == -1 {
assert_eq!(
io::Error::last_os_error().raw_os_error(),
Some(libc::EMFILE)
);
break;
}
occupied.push(unsafe { OwnedFd::from_raw_fd(fd) });
}
// Direct spawning fits, but the helper also clones stdin and opens its control socket.
anyhow::ensure!(occupied.len() >= 7, "not enough descriptors to reserve");
occupied.truncate(occupied.len() - 7);
assert!(
crate::spawn_helper::spawn(&command, crate::spawn_helper::Setup::Pipe)
.await?
.is_none()
);
let output = command.spawn()?.wait_with_output().await?;
assert_eq!(
(output.status.code(), output.stdout, output.stderr),
(Some(0), b"fallback\n".to_vec(), vec![])
);
Ok(())
}
#[cfg(target_env = "gnu")]
#[tokio::test]
async fn parent_loader_environment_does_not_disable_helper_dispatch() -> anyhow::Result<()> {
if !Path::new("/proc/self/exe").exists() {
eprintln!("skipping loader isolation test: procfs is unavailable");
return Ok(());
}
if std::env::var_os("CODEX_TEST_PARENT_LOADER_ENV").is_none() {
let output = std::process::Command::new(std::env::current_exe()?)
.args([
"--exact",
"tests::spawn_helper_tests::parent_loader_environment_does_not_disable_helper_dispatch",
"--nocapture",
])
.env("CODEX_TEST_PARENT_LOADER_ENV", "1")
.env_remove("LD_TRACE_LOADED_OBJECTS")
.output()?;
assert!(output.status.success(), "{output:?}");
return Ok(());
}
let mut command = crate::Command::new("/codex-missing-parent-loader-env-target");
command.current_dir("/");
let Err(error) = crate::spawn_helper::spawn(&command, crate::spawn_helper::Setup::Pipe).await
else {
panic!("helper must reach target exec despite parent loader settings");
};
assert_eq!(error.raw_os_error(), Some(libc::ENOENT));
Ok(())
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,109 @@
use std::fs::File;
use std::io;
use std::io::Read;
use std::io::Write;
use std::os::fd::AsRawFd;
use std::os::fd::BorrowedFd;
use std::os::fd::RawFd;
use std::sync::Arc;
use tokio::io::Interest;
use tokio::io::unix::AsyncFd;
use tokio::sync::mpsc;
use tokio::task::JoinHandle;
pub(crate) enum StdinCloseBehavior {
SendEof,
NoEof,
}
pub(crate) struct PtyIo {
fd: Arc<AsyncFd<File>>,
}
impl PtyIo {
pub(crate) fn new(master_fd: RawFd) -> io::Result<Self> {
// The PTY owner remains alive while its descriptor is duplicated.
let fd = unsafe { BorrowedFd::borrow_raw(master_fd) }.try_clone_to_owned()?;
let flags = unsafe { libc::fcntl(fd.as_raw_fd(), libc::F_GETFL) };
if flags == -1
|| unsafe { libc::fcntl(fd.as_raw_fd(), libc::F_SETFL, flags | libc::O_NONBLOCK) } == -1
{
return Err(io::Error::last_os_error());
}
// Duplicates share O_NONBLOCK, so both reads and writes must use readiness.
// Async tasks can be aborted even when a detached child keeps the PTY open
// or the output channel is full; blocking read/send tasks cannot.
// AsyncFd panics if the current runtime has no I/O driver.
let fd = std::panic::catch_unwind(move || AsyncFd::new(File::from(fd)))
.map_err(|_| io::Error::other("PTY I/O requires a Tokio runtime with I/O enabled"))??;
Ok(Self { fd: Arc::new(fd) })
}
pub(crate) fn spawn(
self,
stdout_tx: mpsc::Sender<Vec<u8>>,
mut writer_rx: mpsc::Receiver<Vec<u8>>,
stdin_close: StdinCloseBehavior,
) -> (JoinHandle<()>, JoinHandle<()>) {
let fd = self.fd;
let reader = Arc::clone(&fd);
let reader_handle = tokio::spawn(async move {
let mut buf = [0u8; 8_192];
loop {
match reader
.async_io(Interest::READABLE, |mut file| file.read(&mut buf))
.await
{
Ok(0) => break,
Ok(count) => {
// Output caps may close the receiver before the child exits.
let _ = stdout_tx.send(buf[..count].to_vec()).await;
}
Err(err) if err.kind() == io::ErrorKind::Interrupted => continue,
// Unix PTYs may report EIO rather than EOF when the slave closes.
Err(_) => break,
}
}
});
let writer_handle = tokio::spawn(async move {
while let Some(bytes) = writer_rx.recv().await {
if write_all(&fd, &bytes).await.is_err() {
return;
}
}
match stdin_close {
StdinCloseBehavior::SendEof => {
// Preserve portable-pty's newline + current VEOF on stdin close,
// including when the terminal input queue requires waiting.
let mut termios = std::mem::MaybeUninit::<libc::termios>::uninit();
if unsafe { libc::tcgetattr(fd.get_ref().as_raw_fd(), termios.as_mut_ptr()) }
== 0
{
let eof = unsafe { termios.assume_init() }.c_cc[libc::VEOF];
if eof != 0 {
let _ = write_all(&fd, &[b'\n', eof]).await;
}
}
}
StdinCloseBehavior::NoEof => {}
}
});
(reader_handle, writer_handle)
}
}
async fn write_all(fd: &AsyncFd<File>, mut bytes: &[u8]) -> io::Result<()> {
while !bytes.is_empty() {
match fd
.async_io(Interest::WRITABLE, |mut file| file.write(bytes))
.await
{
Ok(0) => return Err(io::ErrorKind::WriteZero.into()),
Ok(count) => bytes = &bytes[count..],
Err(err) if err.kind() == io::ErrorKind::Interrupted => continue,
Err(err) => return Err(err),
}
}
Ok(())
}

View File

@@ -0,0 +1,192 @@
#![allow(clippy::unwrap_used)]
// This file is copied from https://github.com/wezterm/wezterm (MIT license).
// Copyright (c) 2018-Present Wez Furlong
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
use crate::win::psuedocon::PsuedoCon;
use anyhow::Error;
use filedescriptor::FileDescriptor;
use filedescriptor::Pipe;
use portable_pty::Child;
use portable_pty::MasterPty;
use portable_pty::PtyPair;
use portable_pty::PtySize;
use portable_pty::PtySystem;
use portable_pty::SlavePty;
use portable_pty::cmdbuilder::CommandBuilder;
use std::mem::ManuallyDrop;
use std::os::windows::io::RawHandle;
use std::ptr;
use std::sync::Arc;
use std::sync::Mutex;
use winapi::um::wincon::COORD;
#[derive(Default)]
pub struct ConPtySystem {}
fn create_conpty_handles(
size: PtySize,
) -> anyhow::Result<(PsuedoCon, FileDescriptor, FileDescriptor)> {
let stdin = Pipe::new()?;
let stdout = Pipe::new()?;
let con = PsuedoCon::new(
COORD {
X: size.cols as i16,
Y: size.rows as i16,
},
stdin.read,
stdout.write,
)?;
Ok((con, stdin.write, stdout.read))
}
pub struct RawConPty {
con: PsuedoCon,
input_write: FileDescriptor,
output_read: FileDescriptor,
}
impl RawConPty {
pub fn new(cols: i16, rows: i16) -> anyhow::Result<Self> {
let (con, input_write, output_read) = create_conpty_handles(PtySize {
rows: rows as u16,
cols: cols as u16,
pixel_width: 0,
pixel_height: 0,
})?;
Ok(Self {
con,
input_write,
output_read,
})
}
pub fn pseudoconsole_handle(&self) -> RawHandle {
self.con.raw_handle()
}
pub fn into_handles(self) -> (PsuedoCon, FileDescriptor, FileDescriptor) {
let me = ManuallyDrop::new(self);
unsafe {
(
ptr::read(&me.con),
ptr::read(&me.input_write),
ptr::read(&me.output_read),
)
}
}
}
impl PtySystem for ConPtySystem {
fn openpty(&self, size: PtySize) -> anyhow::Result<PtyPair> {
let (con, writable, readable) = create_conpty_handles(size)?;
let master = ConPtyMasterPty {
inner: Arc::new(Mutex::new(Inner {
con,
readable,
writable: Some(writable),
size,
})),
};
let slave = ConPtySlavePty {
inner: master.inner.clone(),
};
Ok(PtyPair {
master: Box::new(master),
slave: Box::new(slave),
})
}
}
struct Inner {
con: PsuedoCon,
readable: FileDescriptor,
writable: Option<FileDescriptor>,
size: PtySize,
}
impl Inner {
pub fn resize(
&mut self,
num_rows: u16,
num_cols: u16,
pixel_width: u16,
pixel_height: u16,
) -> Result<(), Error> {
self.con.resize(COORD {
X: num_cols as i16,
Y: num_rows as i16,
})?;
self.size = PtySize {
rows: num_rows,
cols: num_cols,
pixel_width,
pixel_height,
};
Ok(())
}
}
#[derive(Clone)]
pub struct ConPtyMasterPty {
inner: Arc<Mutex<Inner>>,
}
pub struct ConPtySlavePty {
inner: Arc<Mutex<Inner>>,
}
impl MasterPty for ConPtyMasterPty {
fn resize(&self, size: PtySize) -> anyhow::Result<()> {
let mut inner = self.inner.lock().unwrap();
inner.resize(size.rows, size.cols, size.pixel_width, size.pixel_height)
}
fn get_size(&self) -> Result<PtySize, Error> {
let inner = self.inner.lock().unwrap();
Ok(inner.size)
}
fn try_clone_reader(&self) -> anyhow::Result<Box<dyn std::io::Read + Send>> {
Ok(Box::new(self.inner.lock().unwrap().readable.try_clone()?))
}
fn take_writer(&self) -> anyhow::Result<Box<dyn std::io::Write + Send>> {
Ok(Box::new(
self.inner
.lock()
.unwrap()
.writable
.take()
.ok_or_else(|| anyhow::anyhow!("writer already taken"))?,
))
}
}
impl SlavePty for ConPtySlavePty {
fn spawn_command(&self, cmd: CommandBuilder) -> anyhow::Result<Box<dyn Child + Send + Sync>> {
let mut inner = self.inner.lock().unwrap();
let child = inner.con.spawn_command(cmd)?;
Ok(Box::new(child))
}
}

View File

@@ -0,0 +1,396 @@
use filedescriptor::OwnedHandle;
use std::collections::HashMap;
use std::io;
use std::os::windows::io::AsRawHandle;
use std::os::windows::io::FromRawHandle;
use std::os::windows::io::OwnedHandle as ProcessHandle;
use std::os::windows::io::RawHandle;
use std::sync::Mutex;
use std::time::Duration;
use std::time::Instant;
use tokio::process::Child;
use tokio::process::Command;
use winapi::shared::ntdef::NT_SUCCESS;
use winapi::shared::ntdef::NTSTATUS;
use winapi::shared::winerror::ERROR_INVALID_PARAMETER;
use winapi::shared::winerror::ERROR_MORE_DATA;
use winapi::shared::winerror::WAIT_TIMEOUT;
use winapi::um::jobapi::IsProcessInJob;
use winapi::um::jobapi2::AssignProcessToJobObject;
use winapi::um::jobapi2::CreateJobObjectW;
use winapi::um::jobapi2::QueryInformationJobObject;
use winapi::um::jobapi2::SetInformationJobObject;
use winapi::um::jobapi2::TerminateJobObject;
use winapi::um::processthreadsapi::OpenProcess;
use winapi::um::processthreadsapi::TerminateProcess;
use winapi::um::synchapi::WaitForSingleObject;
use winapi::um::winbase::CREATE_NO_WINDOW;
use winapi::um::winbase::CREATE_SUSPENDED;
use winapi::um::winbase::WAIT_OBJECT_0;
use winapi::um::winnt::HANDLE;
use winapi::um::winnt::JOB_OBJECT_LIMIT_BREAKAWAY_OK;
use winapi::um::winnt::JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
use winapi::um::winnt::JOBOBJECT_BASIC_PROCESS_ID_LIST;
use winapi::um::winnt::JOBOBJECT_EXTENDED_LIMIT_INFORMATION;
use winapi::um::winnt::JobObjectBasicProcessIdList;
use winapi::um::winnt::JobObjectExtendedLimitInformation;
use winapi::um::winnt::PROCESS_QUERY_LIMITED_INFORMATION;
use winapi::um::winnt::PROCESS_SET_QUOTA;
use winapi::um::winnt::PROCESS_SUSPEND_RESUME;
use winapi::um::winnt::PROCESS_TERMINATE;
use winapi::um::winnt::SYNCHRONIZE;
#[link(name = "ntdll")]
unsafe extern "system" {
fn NtResumeProcess(process_handle: HANDLE) -> NTSTATUS;
}
/// Owns a Windows Job Object used to terminate a spawned process tree.
#[derive(Debug)]
pub struct JobObject {
handle: OwnedHandle,
// A mutex makes the state check, Job Object API call, and state update
// atomic with respect to concurrent preserve and terminate requests.
preserve_descendants: Mutex<bool>,
}
// A failed restart must still stop any remaining members.
struct TerminateOnDrop<'a>(Option<&'a JobObject>);
impl Drop for TerminateOnDrop<'_> {
fn drop(&mut self) {
if let Some(job) = self.0
&& let Err(error) = job.terminate()
{
log::warn!("Failed to terminate Windows job after an interrupted restart: {error}");
}
}
}
impl JobObject {
/// Creates a Job Object configured to terminate all members when its last handle closes.
pub fn create() -> io::Result<Self> {
let handle = unsafe { CreateJobObjectW(std::ptr::null_mut(), std::ptr::null()) };
if handle.is_null() {
return Err(io::Error::last_os_error());
}
let handle = unsafe { OwnedHandle::from_raw_handle(handle.cast()) };
Self::set_limit_flags(
&handle,
JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE | JOB_OBJECT_LIMIT_BREAKAWAY_OK,
)?;
Ok(Self {
handle,
preserve_descendants: Mutex::new(false),
})
}
/// Creates a Job Object whose owned descendants cannot explicitly break away.
pub fn create_without_breakaway() -> io::Result<Self> {
let job = Self::create()?;
Self::set_limit_flags(&job.handle, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE)?;
Ok(job)
}
/// Captures an owned process handle before its numeric identifier can be reused.
pub fn open_process_handle(process_id: u32) -> io::Result<ProcessHandle> {
Self::open_process(process_id, PROCESS_TERMINATE)
}
fn open_process(process_id: u32, access: u32) -> io::Result<ProcessHandle> {
let handle = unsafe {
OpenProcess(access, /*bInheritHandle*/ 0, process_id)
};
if handle.is_null() {
return Err(io::Error::last_os_error());
}
Ok(unsafe { ProcessHandle::from_raw_handle(handle.cast()) })
}
/// Terminates the exact process identified by a previously captured handle.
pub fn terminate_process_handle(handle: &ProcessHandle) -> io::Result<()> {
let terminated = unsafe {
TerminateProcess(handle.as_raw_handle().cast(), /*uExitCode*/ 1)
};
if terminated == 0 {
Err(io::Error::last_os_error())
} else {
Ok(())
}
}
fn set_limit_flags(handle: &OwnedHandle, flags: u32) -> io::Result<()> {
let mut limits: JOBOBJECT_EXTENDED_LIMIT_INFORMATION = unsafe { std::mem::zeroed() };
limits.BasicLimitInformation.LimitFlags = flags;
let configured = unsafe {
SetInformationJobObject(
handle.as_raw_handle().cast(),
JobObjectExtendedLimitInformation,
std::ptr::addr_of_mut!(limits).cast(),
std::mem::size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32,
)
};
if configured == 0 {
return Err(io::Error::last_os_error());
}
Ok(())
}
/// Assigns a running process to this job.
///
/// Assignment is not retroactive: descendants created before this call
/// completes are not guaranteed to become members of the job.
pub(crate) fn assign_process(&self, process_handle: RawHandle) -> io::Result<()> {
let assigned = unsafe {
AssignProcessToJobObject(self.handle.as_raw_handle().cast(), process_handle.cast())
};
if assigned == 0 {
Err(io::Error::last_os_error())
} else {
Ok(())
}
}
/// Prepares a background child to be assigned to this job before it runs.
///
/// Replaces all creation flags with `CREATE_SUSPENDED | CREATE_NO_WINDOW`.
/// Interactive children that need to inherit a console require an explicit launch.
pub fn prepare_suspended_spawn(&self, command: &mut Command) {
command
.creation_flags(CREATE_NO_WINDOW | CREATE_SUSPENDED)
.kill_on_drop(true);
}
/// Assigns and resumes a suspended child, returning its handle if containment succeeded.
///
/// Nested jobs can reject assignment. Such a child is resumed without
/// containment so callers can preserve their existing compatibility fallback.
pub fn assign_and_resume_process(&self, process_id: u32) -> io::Result<Option<ProcessHandle>> {
let process = Self::open_process(
process_id,
PROCESS_SET_QUOTA | PROCESS_TERMINATE | PROCESS_SUSPEND_RESUME | SYNCHRONIZE,
)?;
let assignment = self.assign_process(process.as_raw_handle());
let status = unsafe { NtResumeProcess(process.as_raw_handle().cast()) };
if !NT_SUCCESS(status) {
unsafe {
TerminateProcess(process.as_raw_handle().cast(), /*uExitCode*/ 1)
};
return Err(io::Error::other(format!(
"failed to resume suspended process: NTSTATUS {status:#x}"
)));
}
match assignment {
Ok(()) => Ok(Some(process)),
Err(error) => {
log::warn!(
"Windows process job assignment unavailable for pid {process_id}: {error}"
);
Ok(None)
}
}
}
/// Starts a console-free background process, falling back when containment is unavailable.
/// The returned job owns the contained process tree when assignment succeeds.
pub fn spawn_background(command: &mut Command) -> io::Result<(Child, Option<Self>)> {
Self::spawn_background_with_job(command, Self::create())
}
fn spawn_background_with_job(
command: &mut Command,
job: io::Result<Self>,
) -> io::Result<(Child, Option<Self>)> {
match job.and_then(|job| job.spawn_contained(command).map(|child| (child, job))) {
Ok((child, job)) => Ok((child, Some(job))),
Err(_) => {
// Remove suspension before retrying, including after failed assignment.
command.creation_flags(CREATE_NO_WINDOW).kill_on_drop(true);
command.spawn().map(|child| (child, None))
}
}
}
/// Starts a background child without a console, assigning it to this job before it runs.
///
/// Replaces existing creation flags as in [`Self::prepare_suspended_spawn`].
pub fn spawn_contained(&self, command: &mut Command) -> io::Result<Child> {
self.prepare_suspended_spawn(command);
let child = command.spawn()?;
let process_handle = child
.raw_handle()
.ok_or_else(|| io::Error::other("missing child process handle"))?;
self.assign_process(process_handle)?;
let status = unsafe { NtResumeProcess(process_handle.cast()) };
if !NT_SUCCESS(status) {
return Err(io::Error::other(format!(
"failed to resume contained process: NTSTATUS {status:#x}"
)));
}
Ok(child)
}
/// Allows contained descendants to keep running after the root exits normally.
///
/// This disables both explicit job termination and kill-on-close for this
/// object. Calls race safely with [`Self::terminate`]: whichever operation
/// acquires the state lock first determines whether the process tree is
/// preserved or terminated.
pub fn preserve_descendants(&self) -> io::Result<()> {
let mut preserve_descendants = self
.preserve_descendants
.lock()
.map_err(|_| io::Error::other("job state lock poisoned"))?;
if *preserve_descendants {
return Ok(());
}
Self::set_limit_flags(&self.handle, JOB_OBJECT_LIMIT_BREAKAWAY_OK)?;
*preserve_descendants = true;
Ok(())
}
/// Terminates every process currently assigned to the job.
pub fn terminate(&self) -> io::Result<()> {
let preserve_descendants = self
.preserve_descendants
.lock()
.map_err(|_| io::Error::other("job state lock poisoned"))?;
if *preserve_descendants {
return Ok(());
}
let terminated = unsafe {
TerminateJobObject(self.handle.as_raw_handle().cast(), /*uExitCode*/ 1)
};
if terminated == 0 {
Err(io::Error::last_os_error())
} else {
Ok(())
}
}
/// Stops a root from [`Self::assign_and_resume_process`] and the remaining members of its job.
pub fn terminate_and_wait(&self, root: &ProcessHandle, grace: Duration) -> io::Result<()> {
let mut cleanup = TerminateOnDrop(Some(self));
let deadline = Instant::now() + grace;
Self::request_stop(root)?;
Self::wait_for_exit(root, deadline)?;
// TerminateJobObject can empty the job list before members release their handles.
// Stop by process handle, then rescan for children born during the previous pass.
let mut list = vec![0usize; 16];
let mut stopped = HashMap::new();
loop {
if Instant::now() >= deadline {
return Err(io::ErrorKind::TimedOut.into());
}
let pids = self.member_ids(&mut list)?;
if pids.iter().all(|pid| stopped.contains_key(pid)) {
self.terminate()?;
cleanup.0 = None;
return Ok(());
}
for &pid in pids {
if stopped.contains_key(&pid) {
continue;
}
let member = match Self::open_process(
pid as u32,
PROCESS_TERMINATE | PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE,
) {
Ok(member) => member,
Err(error) if error.raw_os_error() == Some(ERROR_INVALID_PARAMETER as i32) => {
continue;
}
Err(error) => return Err(error),
};
// A listed PID can be reused before OpenProcess. Only signal confirmed job members.
let mut in_job = 0;
if unsafe {
IsProcessInJob(
member.as_raw_handle().cast(),
self.handle.as_raw_handle().cast(),
&mut in_job,
)
} == 0
{
return Err(io::Error::last_os_error());
}
if in_job != 0 {
Self::request_stop(&member)?;
stopped.insert(pid, member);
}
}
for member in stopped.values() {
Self::wait_for_exit(member, deadline)?;
}
}
}
fn member_ids<'a>(&self, list: &'a mut Vec<usize>) -> io::Result<&'a [usize]> {
const HEADER_WORDS: usize =
std::mem::offset_of!(JOBOBJECT_BASIC_PROCESS_ID_LIST, ProcessIdList)
/ std::mem::size_of::<usize>();
loop {
let listed = unsafe {
QueryInformationJobObject(
self.handle.as_raw_handle().cast(),
JobObjectBasicProcessIdList,
list.as_mut_ptr().cast(),
u32::try_from(std::mem::size_of_val(list.as_slice()))
.map_err(io::Error::other)?,
std::ptr::null_mut(),
)
};
if listed != 0 {
let header = unsafe { &*list.as_ptr().cast::<JOBOBJECT_BASIC_PROCESS_ID_LIST>() };
if header.NumberOfProcessIdsInList == header.NumberOfAssignedProcesses {
return Ok(&list[HEADER_WORDS..][..header.NumberOfProcessIdsInList as usize]);
}
} else {
let error = io::Error::last_os_error();
if error.raw_os_error() != Some(ERROR_MORE_DATA as i32) {
return Err(error);
}
}
list.resize(list.len() * 2, 0);
}
}
fn request_stop(process: &ProcessHandle) -> io::Result<()> {
// Windows also returns access denied when the process has already exited. Its handle
// must still signal before a replacement can start.
match Self::terminate_process_handle(process) {
Err(error) if error.kind() == io::ErrorKind::PermissionDenied => Ok(()),
result => result,
}
}
fn wait_for_exit(process: &ProcessHandle, deadline: Instant) -> io::Result<()> {
let remaining = deadline.saturating_duration_since(Instant::now());
// The largest DWORD denotes INFINITE, so cap this bounded wait below it.
let millis = remaining.as_millis().min(u128::from(u32::MAX - 1)) as u32;
match unsafe { WaitForSingleObject(process.as_raw_handle().cast(), millis) } {
WAIT_OBJECT_0 => Ok(()),
WAIT_TIMEOUT => Err(io::ErrorKind::TimedOut.into()),
_ => Err(io::Error::last_os_error()),
}
}
}
impl AsRawHandle for JobObject {
fn as_raw_handle(&self) -> RawHandle {
self.handle.as_raw_handle()
}
}
#[cfg(test)]
#[path = "job_tests.rs"]
mod tests;

View File

@@ -0,0 +1,87 @@
//! Verifies console suppression through contained launches and both containment fallbacks.
use super::*;
use pretty_assertions::assert_eq;
use std::os::windows::process::CommandExt;
use std::process::Stdio;
use std::time::Duration;
use winapi::um::winnt::JOB_OBJECT_LIMIT_ACTIVE_PROCESS;
#[tokio::test]
async fn background_launches_keep_consoles_hidden_when_containment_fails() -> anyhow::Result<()> {
const TEST_NAME: &str =
"win::job::tests::background_launches_keep_consoles_hidden_when_containment_fails";
const PHASE: &str = "CODEX_TEST_BACKGROUND_JOB_PHASE";
let executable = std::env::current_exe()?;
match std::env::var(PHASE).as_deref() {
Ok("probe") => {
assert!(unsafe { winapi::um::wincon::GetConsoleWindow() }.is_null());
println!("background probe completed");
return Ok(());
}
Ok("hold") => {
std::thread::sleep(Duration::from_secs(/*secs*/ 30));
return Ok(());
}
Ok("parent") => {}
_ => {
let output = std::process::Command::new(executable)
.args(["--exact", TEST_NAME, "--nocapture"])
.env(PHASE, "parent")
.creation_flags(winapi::um::winbase::DETACHED_PROCESS)
.output()?;
assert!(output.status.success(), "detached probe failed: {output:?}");
return Ok(());
}
}
// Fill a one-process job so assigning the next suspended child must fail.
// The parent remains outside this job, allowing the uncontained retry to run.
let full_job = JobObject::create()?;
let mut limits: JOBOBJECT_EXTENDED_LIMIT_INFORMATION = unsafe { std::mem::zeroed() };
limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_ACTIVE_PROCESS
| JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
| JOB_OBJECT_LIMIT_BREAKAWAY_OK;
limits.BasicLimitInformation.ActiveProcessLimit = 1;
let configured = unsafe {
SetInformationJobObject(
full_job.handle.as_raw_handle().cast(),
JobObjectExtendedLimitInformation,
std::ptr::addr_of_mut!(limits).cast(),
std::mem::size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32,
)
};
anyhow::ensure!(configured != 0, "{}", io::Error::last_os_error());
let mut holder_command = Command::new(&executable);
holder_command
.args(["--exact", TEST_NAME])
.env(PHASE, "hold");
let mut holder = full_job.spawn_contained(&mut holder_command)?;
for (case, job, expected_containment) in [
(
"creation failure",
Err(io::Error::other("forced creation failure")),
false,
),
("assignment failure", Ok(full_job), false),
("contained", JobObject::create(), true),
] {
let mut command = Command::new(&executable);
command
.args(["--exact", TEST_NAME, "--nocapture"])
.env(PHASE, "probe")
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
let (child, job) = JobObject::spawn_background_with_job(&mut command, job)?;
assert_eq!(job.is_some(), expected_containment, "{case}");
let output =
tokio::time::timeout(Duration::from_secs(/*secs*/ 10), child.wait_with_output())
.await??;
assert!(output.status.success(), "{case}: {output:?}");
assert!(String::from_utf8_lossy(&output.stdout).contains("background probe completed"));
}
tokio::time::timeout(Duration::from_secs(/*secs*/ 10), holder.wait()).await??;
Ok(())
}

View File

@@ -0,0 +1,181 @@
#![allow(clippy::unwrap_used)]
// This file is copied from https://github.com/wezterm/wezterm (MIT license).
// Copyright (c) 2018-Present Wez Furlong
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// Local modifications:
// - Place spawned processes in a Job Object so kill operations terminate the
// full process tree, while normal root exit preserves background descendants.
use anyhow::Context as _;
use filedescriptor::OwnedHandle;
use portable_pty::Child;
use portable_pty::ChildKiller;
use portable_pty::ExitStatus;
use std::io::Error as IoError;
use std::io::Result as IoResult;
use std::os::windows::io::AsRawHandle;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::Mutex;
use std::task::Context;
use std::task::Poll;
use winapi::shared::minwindef::DWORD;
use winapi::um::minwinbase::STILL_ACTIVE;
use winapi::um::processthreadsapi::*;
use winapi::um::synchapi::WaitForSingleObject;
use winapi::um::winbase::INFINITE;
pub(crate) mod conpty;
mod job;
mod procthreadattr;
mod psuedocon;
pub use conpty::ConPtySystem;
pub use job::JobObject;
pub use psuedocon::PsuedoCon;
pub use psuedocon::conpty_supported;
#[derive(Debug)]
pub struct WinChild {
proc: Mutex<OwnedHandle>,
job: Arc<JobObject>,
}
impl WinChild {
pub(crate) fn new(proc: OwnedHandle, job: Arc<JobObject>) -> Self {
Self {
proc: Mutex::new(proc),
job,
}
}
fn is_complete(&mut self) -> IoResult<Option<ExitStatus>> {
let mut status: DWORD = 0;
let proc = self.proc.lock().unwrap().try_clone().unwrap();
let res = unsafe { GetExitCodeProcess(proc.as_raw_handle() as _, &mut status) };
if res != 0 {
if status == STILL_ACTIVE {
Ok(None)
} else {
self.preserve_descendants();
Ok(Some(ExitStatus::with_exit_code(status)))
}
} else {
Ok(None)
}
}
fn do_kill(&mut self) -> IoResult<()> {
self.job.terminate()
}
fn preserve_descendants(&self) {
if let Err(err) = self.job.preserve_descendants() {
log::warn!("ConPTY failed to preserve descendants after root exit: {err}");
}
}
}
impl ChildKiller for WinChild {
fn kill(&mut self) -> IoResult<()> {
if let Err(err) = self.do_kill() {
log::warn!("ConPTY failed to terminate process tree: {err}");
}
Ok(())
}
fn clone_killer(&self) -> Box<dyn ChildKiller + Send + Sync> {
Box::new(WinChildKiller {
job: Arc::clone(&self.job),
})
}
}
#[derive(Debug)]
pub struct WinChildKiller {
job: Arc<JobObject>,
}
impl ChildKiller for WinChildKiller {
fn kill(&mut self) -> IoResult<()> {
self.job.terminate()
}
fn clone_killer(&self) -> Box<dyn ChildKiller + Send + Sync> {
Box::new(WinChildKiller {
job: Arc::clone(&self.job),
})
}
}
impl Child for WinChild {
fn try_wait(&mut self) -> IoResult<Option<ExitStatus>> {
self.is_complete()
}
fn wait(&mut self) -> IoResult<ExitStatus> {
if let Ok(Some(status)) = self.try_wait() {
return Ok(status);
}
let proc = self.proc.lock().unwrap().try_clone().unwrap();
unsafe {
WaitForSingleObject(proc.as_raw_handle() as _, INFINITE);
}
let mut status: DWORD = 0;
let res = unsafe { GetExitCodeProcess(proc.as_raw_handle() as _, &mut status) };
if res != 0 {
self.preserve_descendants();
Ok(ExitStatus::with_exit_code(status))
} else {
Err(IoError::last_os_error())
}
}
fn process_id(&self) -> Option<u32> {
let res = unsafe { GetProcessId(self.proc.lock().unwrap().as_raw_handle() as _) };
if res == 0 { None } else { Some(res) }
}
fn as_raw_handle(&self) -> Option<std::os::windows::io::RawHandle> {
let proc = self.proc.lock().unwrap();
Some(proc.as_raw_handle())
}
}
impl std::future::Future for WinChild {
type Output = anyhow::Result<ExitStatus>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<anyhow::Result<ExitStatus>> {
match self.is_complete() {
Ok(Some(status)) => Poll::Ready(Ok(status)),
Err(err) => Poll::Ready(Err(err).context("Failed to retrieve process exit status")),
Ok(None) => {
let proc = self.proc.lock().unwrap().try_clone()?;
let waker = cx.waker().clone();
std::thread::spawn(move || {
unsafe {
WaitForSingleObject(proc.as_raw_handle() as _, INFINITE);
}
waker.wake();
});
Poll::Pending
}
}
}
}

View File

@@ -0,0 +1,127 @@
#![allow(clippy::uninit_vec)]
// This file is copied from https://github.com/wezterm/wezterm (MIT license).
// Copyright (c) 2018-Present Wez Furlong
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
use super::psuedocon::HPCON;
use anyhow::Error;
use anyhow::ensure;
use std::ffi::c_void;
use std::io::Error as IoError;
use std::mem;
use std::ptr;
use winapi::shared::minwindef::DWORD;
use winapi::um::processthreadsapi::*;
use winapi::um::winnt::HANDLE;
const PROC_THREAD_ATTRIBUTE_JOB_LIST: usize = 0x0002000D;
const PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE: usize = 0x00020016;
pub struct ProcThreadAttributeList {
data: Vec<u8>,
job_list: Vec<HANDLE>,
}
impl ProcThreadAttributeList {
pub fn with_capacity(num_attributes: DWORD) -> Result<Self, Error> {
let mut bytes_required: usize = 0;
unsafe {
InitializeProcThreadAttributeList(
ptr::null_mut(),
num_attributes,
0,
&mut bytes_required,
)
};
let mut data = Vec::with_capacity(bytes_required);
unsafe { data.set_len(bytes_required) };
let attr_ptr = data.as_mut_slice().as_mut_ptr() as *mut _;
let res = unsafe {
InitializeProcThreadAttributeList(attr_ptr, num_attributes, 0, &mut bytes_required)
};
ensure!(
res != 0,
"InitializeProcThreadAttributeList failed: {}",
IoError::last_os_error()
);
Ok(Self {
data,
job_list: Vec::new(),
})
}
pub fn as_mut_ptr(&mut self) -> LPPROC_THREAD_ATTRIBUTE_LIST {
self.data.as_mut_slice().as_mut_ptr() as *mut _
}
pub fn set_pty(&mut self, con: HPCON) -> Result<(), Error> {
// SAFETY: `con` is the Windows-defined value and size for this attribute.
unsafe {
self.update(
PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE,
con,
mem::size_of::<HPCON>(),
)
}
}
pub fn set_job(&mut self, job: HANDLE) -> Result<(), Error> {
// Atomic job attachment is intentionally required for native ConPTY
// spawns. If Windows cannot honor the job list (for example, because a
// parent job forbids nesting), fail the spawn rather than briefly run
// an uncontained process tree.
self.job_list = vec![job];
let value = self.job_list.as_mut_ptr().cast();
let size = std::mem::size_of_val(self.job_list.as_slice());
// SAFETY: `value` points to `self.job_list`, which remains alive while
// the attribute list can reference it, and `size` covers that slice.
unsafe { self.update(PROC_THREAD_ATTRIBUTE_JOB_LIST, value, size) }
}
unsafe fn update(
&mut self,
attribute: usize,
value: *mut c_void,
size: usize,
) -> Result<(), Error> {
let res = unsafe {
UpdateProcThreadAttribute(
self.as_mut_ptr(),
0,
attribute,
value,
size,
ptr::null_mut(),
ptr::null_mut(),
)
};
ensure!(
res != 0,
"UpdateProcThreadAttribute failed: {}",
IoError::last_os_error()
);
Ok(())
}
}
impl Drop for ProcThreadAttributeList {
fn drop(&mut self) {
unsafe { DeleteProcThreadAttributeList(self.as_mut_ptr()) };
}
}

View File

@@ -0,0 +1,387 @@
#![allow(clippy::expect_used)]
#![allow(clippy::upper_case_acronyms)]
// This file is copied from https://github.com/wezterm/wezterm (MIT license).
// Copyright (c) 2018-Present Wez Furlong
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
use super::WinChild;
use crate::win::job::JobObject;
use crate::win::procthreadattr::ProcThreadAttributeList;
use anyhow::Error;
use anyhow::bail;
use anyhow::ensure;
use filedescriptor::FileDescriptor;
use filedescriptor::OwnedHandle;
use lazy_static::lazy_static;
use portable_pty::cmdbuilder::CommandBuilder;
use shared_library::shared_library;
use std::env;
use std::ffi::OsStr;
use std::ffi::OsString;
use std::io::Error as IoError;
use std::mem;
use std::os::windows::ffi::OsStrExt;
use std::os::windows::ffi::OsStringExt;
use std::os::windows::io::AsRawHandle;
use std::os::windows::io::FromRawHandle;
use std::path::Path;
use std::ptr;
use std::sync::Arc;
use winapi::shared::minwindef::DWORD;
use winapi::shared::ntdef::NTSTATUS;
use winapi::shared::ntstatus::STATUS_SUCCESS;
use winapi::shared::winerror::HRESULT;
use winapi::shared::winerror::S_OK;
use winapi::um::handleapi::*;
use winapi::um::processthreadsapi::*;
use winapi::um::winbase::CREATE_UNICODE_ENVIRONMENT;
use winapi::um::winbase::EXTENDED_STARTUPINFO_PRESENT;
use winapi::um::winbase::STARTF_USESTDHANDLES;
use winapi::um::winbase::STARTUPINFOEXW;
use winapi::um::wincon::COORD;
use winapi::um::winnt::HANDLE;
use winapi::um::winnt::OSVERSIONINFOW;
pub type HPCON = HANDLE;
pub const PSEUDOCONSOLE_RESIZE_QUIRK: DWORD = 0x2;
#[allow(dead_code)]
pub const PSEUDOCONSOLE_PASSTHROUGH_MODE: DWORD = 0x8;
// https://learn.microsoft.com/en-gb/windows/console/createpseudoconsole
// https://learn.microsoft.com/en-gb/windows/release-health/release-information
const MIN_CONPTY_BUILD: u32 = 17_763;
shared_library!(ConPtyFuncs,
pub fn CreatePseudoConsole(
size: COORD,
hInput: HANDLE,
hOutput: HANDLE,
flags: DWORD,
hpc: *mut HPCON
) -> HRESULT,
pub fn ResizePseudoConsole(hpc: HPCON, size: COORD) -> HRESULT,
pub fn ClosePseudoConsole(hpc: HPCON),
);
shared_library!(ConPtyReleaseFuncs,
pub fn ReleasePseudoConsole(hpc: HPCON) -> HRESULT,
);
shared_library!(Ntdll,
pub fn RtlGetVersion(
version_info: *mut OSVERSIONINFOW
) -> NTSTATUS,
);
lazy_static! {
static ref CONPTY: ConPtyFuncs = ConPtyFuncs::open(Path::new("kernel32.dll")).expect(
"this system does not support conpty. Windows 10 October 2018 or newer is required",
);
static ref CONPTY_RELEASE: Option<ConPtyReleaseFuncs> =
ConPtyReleaseFuncs::open(Path::new("kernel32.dll")).ok();
}
pub fn conpty_supported() -> bool {
windows_build_number().is_some_and(|build| build >= MIN_CONPTY_BUILD)
}
fn windows_build_number() -> Option<u32> {
let ntdll = Ntdll::open(Path::new("ntdll.dll")).ok()?;
let mut info: OSVERSIONINFOW = unsafe { mem::zeroed() };
info.dwOSVersionInfoSize = mem::size_of::<OSVERSIONINFOW>() as u32;
let status = unsafe { (ntdll.RtlGetVersion)(&mut info) };
if status == STATUS_SUCCESS {
Some(info.dwBuildNumber)
} else {
None
}
}
pub struct PsuedoCon {
con: HPCON,
// Retain the creation handles until a client has attached. Keeping the
// output write handle afterward would prevent the reader from seeing EOF.
creation_handles: Option<(FileDescriptor, FileDescriptor)>,
}
unsafe impl Send for PsuedoCon {}
unsafe impl Sync for PsuedoCon {}
impl Drop for PsuedoCon {
fn drop(&mut self) {
unsafe { (CONPTY.ClosePseudoConsole)(self.con) };
}
}
impl PsuedoCon {
pub fn raw_handle(&self) -> HPCON {
self.con
}
pub fn new(size: COORD, input: FileDescriptor, output: FileDescriptor) -> Result<Self, Error> {
let mut con: HPCON = INVALID_HANDLE_VALUE;
let result = unsafe {
(CONPTY.CreatePseudoConsole)(
size,
input.as_raw_handle() as _,
output.as_raw_handle() as _,
PSEUDOCONSOLE_RESIZE_QUIRK,
&mut con,
)
};
ensure!(
result == S_OK,
"failed to create psuedo console: HRESULT {result}"
);
Ok(Self {
con,
creation_handles: Some((input, output)),
})
}
pub fn resize(&self, size: COORD) -> Result<(), Error> {
let result = unsafe { (CONPTY.ResizePseudoConsole)(self.con, size) };
ensure!(
result == S_OK,
"failed to resize console to {}x{}: HRESULT: {}",
size.X,
size.Y,
result
);
Ok(())
}
pub fn spawn_command(&mut self, cmd: CommandBuilder) -> anyhow::Result<WinChild> {
let job = Arc::new(JobObject::create()?);
let mut si: STARTUPINFOEXW = unsafe { mem::zeroed() };
si.StartupInfo.cb = mem::size_of::<STARTUPINFOEXW>() as u32;
si.StartupInfo.dwFlags = STARTF_USESTDHANDLES;
si.StartupInfo.hStdInput = INVALID_HANDLE_VALUE;
si.StartupInfo.hStdOutput = INVALID_HANDLE_VALUE;
si.StartupInfo.hStdError = INVALID_HANDLE_VALUE;
let mut attrs = ProcThreadAttributeList::with_capacity(/*num_attributes*/ 2)?;
attrs.set_pty(self.con)?;
attrs.set_job(job.as_raw_handle().cast())?;
si.lpAttributeList = attrs.as_mut_ptr();
let mut pi: PROCESS_INFORMATION = unsafe { mem::zeroed() };
let (mut exe, mut cmdline) = build_cmdline(&cmd)?;
let cmd_os = OsString::from_wide(&cmdline);
let cwd = resolve_current_directory(&cmd);
let mut env_block = build_environment_block(&cmd);
let res = unsafe {
CreateProcessW(
exe.as_mut_ptr(),
cmdline.as_mut_ptr(),
ptr::null_mut(),
ptr::null_mut(),
0,
EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT,
env_block.as_mut_ptr() as *mut _,
cwd.as_ref().map_or(ptr::null(), std::vec::Vec::as_ptr),
&mut si.StartupInfo,
&mut pi,
)
};
if res == 0 {
let err = IoError::last_os_error();
let msg = format!(
"CreateProcessW `{:?}` in cwd `{:?}` failed: {}",
cmd_os,
cwd.as_ref().map(|c| OsString::from_wide(c)),
err
);
log::error!("{msg}");
bail!("{msg}");
}
let _main_thread = unsafe { OwnedHandle::from_raw_handle(pi.hThread as _) };
let proc = unsafe { OwnedHandle::from_raw_handle(pi.hProcess as _) };
self.creation_handles.take();
// Windows 11 24H2+ lets the console close its output after the last
// attached client exits, without terminating surviving descendants.
// Older Windows retains its existing ClosePseudoConsole-on-drop path.
if let Some(release) = CONPTY_RELEASE.as_ref() {
let result = unsafe { (release.ReleasePseudoConsole)(self.con) };
if result != S_OK {
log::warn!("failed to release pseudoconsole ownership: HRESULT {result}");
}
}
Ok(WinChild::new(proc, job))
}
}
#[cfg(test)]
#[path = "psuedocon_tests.rs"]
mod lifecycle_tests;
fn resolve_current_directory(cmd: &CommandBuilder) -> Option<Vec<u16>> {
let home = cmd
.get_env("USERPROFILE")
.and_then(|path| Path::new(path).is_dir().then(|| path.to_owned()));
let cwd = cmd
.get_cwd()
.and_then(|path| Path::new(path).is_dir().then(|| path.to_owned()));
let dir = cwd.or(home)?;
let mut wide = Vec::new();
if Path::new(&dir).is_relative() {
if let Ok(current_dir) = env::current_dir() {
wide.extend(current_dir.join(&dir).as_os_str().encode_wide());
} else {
wide.extend(dir.encode_wide());
}
} else {
wide.extend(dir.encode_wide());
}
wide.push(0);
Some(wide)
}
fn build_environment_block(cmd: &CommandBuilder) -> Vec<u16> {
let mut block = Vec::new();
for (key, value) in cmd.iter_full_env_as_str() {
block.extend(OsStr::new(key).encode_wide());
block.push(b'=' as u16);
block.extend(OsStr::new(value).encode_wide());
block.push(0);
}
block.push(0);
block
}
fn build_cmdline(cmd: &CommandBuilder) -> anyhow::Result<(Vec<u16>, Vec<u16>)> {
let exe_os: OsString = if cmd.is_default_prog() {
cmd.get_env("ComSpec")
.unwrap_or(OsStr::new("cmd.exe"))
.to_os_string()
} else {
let argv = cmd.get_argv();
let Some(first) = argv.first() else {
anyhow::bail!("missing program name");
};
search_path(cmd, first)
};
let mut cmdline = Vec::new();
append_quoted(&exe_os, &mut cmdline);
for arg in cmd.get_argv().iter().skip(1) {
cmdline.push(' ' as u16);
ensure!(
!arg.encode_wide().any(|c| c == 0),
"invalid encoding for command line argument {arg:?}"
);
append_quoted(arg, &mut cmdline);
}
cmdline.push(0);
let mut exe: Vec<u16> = exe_os.encode_wide().collect();
exe.push(0);
Ok((exe, cmdline))
}
fn search_path(cmd: &CommandBuilder, exe: &OsStr) -> OsString {
if let Some(path) = cmd.get_env("PATH") {
let extensions = cmd.get_env("PATHEXT").unwrap_or(OsStr::new(".EXE"));
for path in env::split_paths(path) {
let candidate = path.join(exe);
if candidate.exists() {
return candidate.into_os_string();
}
for ext in env::split_paths(extensions) {
let ext = ext.to_str().unwrap_or("");
let path = path
.join(exe)
.with_extension(ext.strip_prefix('.').unwrap_or(ext));
if path.exists() {
return path.into_os_string();
}
}
}
}
exe.to_os_string()
}
fn append_quoted(arg: &OsStr, cmdline: &mut Vec<u16>) {
if !arg.is_empty()
&& !arg.encode_wide().any(|c| {
c == ' ' as u16
|| c == '\t' as u16
|| c == '\n' as u16
|| c == '\x0b' as u16
|| c == '\"' as u16
})
{
cmdline.extend(arg.encode_wide());
return;
}
cmdline.push('"' as u16);
let arg: Vec<_> = arg.encode_wide().collect();
let mut i = 0;
while i < arg.len() {
let mut num_backslashes = 0;
while i < arg.len() && arg[i] == '\\' as u16 {
i += 1;
num_backslashes += 1;
}
if i == arg.len() {
for _ in 0..num_backslashes * 2 {
cmdline.push('\\' as u16);
}
break;
} else if arg[i] == b'"' as u16 {
for _ in 0..num_backslashes * 2 + 1 {
cmdline.push('\\' as u16);
}
cmdline.push(arg[i]);
} else {
for _ in 0..num_backslashes {
cmdline.push('\\' as u16);
}
cmdline.push(arg[i]);
}
i += 1;
}
cmdline.push('"' as u16);
}
#[cfg(test)]
mod tests {
use super::MIN_CONPTY_BUILD;
use super::windows_build_number;
#[test]
fn windows_build_number_returns_value() {
// We can't stably check the version of the GH workers, but we can
// at least check that this.
let version = windows_build_number().unwrap();
assert!(version > MIN_CONPTY_BUILD);
}
}

View File

@@ -0,0 +1,140 @@
//! Verify natural and terminated console clients close output without losing descendants.
use std::collections::HashMap;
use std::path::Path;
use std::time::Duration;
use pretty_assertions::assert_eq;
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn output_closes_after_client_exit_while_session_is_retained() -> anyhow::Result<()> {
if super::CONPTY_RELEASE.is_none() {
eprintln!("automatic ConPTY closure requires Windows 11 24H2 or newer");
return Ok(());
}
let env: HashMap<String, String> = std::env::vars().collect();
let spawned = crate::spawn_pty_process(
"cmd.exe",
&[
"/d".to_string(),
"/c".to_string(),
"echo complete".to_string(),
],
Path::new("."),
&env,
/*arg0*/ &None,
crate::TerminalSize::default(),
crate::ChildFds::Inherited(&[]),
)
.await?;
let mut output = spawned.stdout_rx;
let bytes = tokio::time::timeout(Duration::from_secs(5), async {
let mut bytes = Vec::new();
while let Some(chunk) = output.recv().await {
bytes.extend(chunk);
}
bytes
})
.await?;
assert!(String::from_utf8_lossy(&bytes).contains("complete"));
assert_eq!(spawned.exit_rx.await?, 0);
assert!(spawned.session.has_exited());
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn output_remains_open_for_surviving_console_child() -> anyhow::Result<()> {
if super::CONPTY_RELEASE.is_none() {
eprintln!("automatic ConPTY closure requires Windows 11 24H2 or newer");
return Ok(());
}
let Some(python) = crate::tests::find_python() else {
eprintln!("python not found; skipping ConPTY surviving-child test");
return Ok(());
};
let env: HashMap<String, String> = std::env::vars().collect();
let spawned = crate::spawn_pty_process(
&python,
&[
"-u".to_string(),
"-c".to_string(),
"import subprocess,sys; subprocess.Popen([sys.executable,'-u','-c',sys.argv[1]])".to_string(),
"import sys; print('child-ready',flush=True); line=sys.stdin.readline().strip(); print('child-received:'+line,flush=True)".to_string(),
],
Path::new("."),
&env,
/*arg0*/ &None,
crate::TerminalSize::default(),
crate::ChildFds::Inherited(&[]),
)
.await?;
let mut output = spawned.stdout_rx;
assert_eq!(
tokio::time::timeout(Duration::from_secs(5), spawned.exit_rx).await??,
0
);
let mut bytes = Vec::new();
tokio::time::timeout(Duration::from_secs(5), async {
while !String::from_utf8_lossy(&bytes).contains("child-ready") {
bytes.extend(
output
.recv()
.await
.expect("child output closed before readiness"),
);
}
spawned
.session
.writer_sender()
.send(b"continued\r".to_vec())
.await?;
while let Some(chunk) = output.recv().await {
bytes.extend(chunk);
}
Ok::<_, anyhow::Error>(())
})
.await??;
assert!(String::from_utf8_lossy(&bytes).contains("child-received:continued"));
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn output_closes_after_termination_while_session_is_retained() -> anyhow::Result<()> {
if super::CONPTY_RELEASE.is_none() {
eprintln!("automatic ConPTY closure requires Windows 11 24H2 or newer");
return Ok(());
}
let env: HashMap<String, String> = std::env::vars().collect();
let spawned = crate::spawn_pty_process(
"cmd.exe",
&[
"/d".to_string(),
"/c".to_string(),
"set /p line=child-ready".to_string(),
],
Path::new("."),
&env,
/*arg0*/ &None,
crate::TerminalSize::default(),
crate::ChildFds::Inherited(&[]),
)
.await?;
let mut output = spawned.stdout_rx;
tokio::time::timeout(Duration::from_secs(5), async {
let mut bytes = Vec::new();
while !String::from_utf8_lossy(&bytes).contains("child-ready") {
bytes.extend(
output
.recv()
.await
.expect("child output closed before readiness"),
);
}
spawned.session.request_terminate();
while output.recv().await.is_some() {}
})
.await?;
assert_ne!(spawned.exit_rx.await?, 0);
assert!(spawned.session.has_exited());
Ok(())
}

View File

@@ -0,0 +1,35 @@
/// Stateful normalizer for bytes written to a Windows pseudoconsole.
///
/// ConPTY accepts UTF-8 input, but an Enter key is represented by a carriage
/// return on Windows. This converts line feeds and collapses existing CRLF
/// sequences, including when the two bytes arrive in separate writes, so each
/// requested newline submits exactly one line. Backspace is encoded as DEL,
/// which ConPTY translates to `VK_BACK`. All other bytes, including UTF-8 and
/// terminal control characters, pass through unchanged.
#[derive(Default)]
pub struct WindowsTtyInputNormalizer {
previous_was_cr: bool,
}
impl WindowsTtyInputNormalizer {
pub fn normalize(&mut self, bytes: &[u8]) -> Vec<u8> {
let mut normalized = Vec::with_capacity(bytes.len());
for &byte in bytes {
match byte {
b'\x08' => normalized.push(b'\x7f'),
b'\n' => {
if !self.previous_was_cr {
normalized.push(b'\r');
}
}
_ => normalized.push(byte),
}
self.previous_was_cr = byte == b'\r';
}
normalized
}
}
#[cfg(test)]
#[path = "windows_input_tests.rs"]
mod tests;

View File

@@ -0,0 +1,16 @@
use super::WindowsTtyInputNormalizer;
use pretty_assertions::assert_eq;
#[test]
fn normalizes_terminal_input_without_changing_text_or_ctrl_c() {
let mut normalizer = WindowsTtyInputNormalizer::default();
assert_eq!(normalizer.normalize(b"first\n"), b"first\r");
assert_eq!(normalizer.normalize(b"second\r"), b"second\r");
assert_eq!(normalizer.normalize(b"\nthird\r\n"), b"third\r");
let mut input_with_controls = "cafeé 漢字".as_bytes().to_vec();
input_with_controls.extend_from_slice(b"\x08\x03");
let mut expected = "cafeé 漢字".as_bytes().to_vec();
expected.extend_from_slice(b"\x7f\x03");
assert_eq!(normalizer.normalize(&input_with_controls), expected);
}

View File

@@ -0,0 +1,518 @@
use super::collect_output_until_exit;
use super::combine_spawned_output;
use super::find_python;
use super::wait_for_output_contains;
use crate::TerminalSize;
use crate::spawn_pipe_process_no_stdin;
use crate::spawn_pty_process;
use pretty_assertions::assert_eq;
use std::collections::HashMap;
use std::os::windows::io::AsRawHandle;
use std::os::windows::io::BorrowedHandle;
use std::os::windows::io::FromRawHandle;
use std::os::windows::io::OwnedHandle;
use std::os::windows::process::CommandExt;
use std::path::Path;
use std::process::Stdio;
use std::time::Duration;
use tokio::io::AsyncBufReadExt;
use tokio::io::AsyncWriteExt;
use tokio::io::BufReader;
use tokio::process::Command;
use winapi::um::jobapi::IsProcessInJob;
use winapi::um::processthreadsapi::OpenProcess;
use winapi::um::synchapi::WaitForSingleObject;
use winapi::um::winbase::WAIT_OBJECT_0;
use winapi::um::winnt::PROCESS_QUERY_LIMITED_INFORMATION;
use winapi::um::winnt::SYNCHRONIZE;
const READY_MARKER: &str = "__CODEX_CHILD_READY__";
const VALUE_MARKER: &str = "__CODEX_CHILD_VALUE__";
#[tokio::test]
async fn piped_child_has_no_console_with_or_without_job_containment() -> anyhow::Result<()> {
// Nextest itself can run without a visible console. Re-execute this test
// detached, like app-server-daemon, so children cannot inherit its console.
if std::env::var_os("CODEX_PTY_DETACHED_CONSOLE_PROBE").is_none() {
let output = std::process::Command::new(std::env::current_exe()?)
.args([
"--exact",
"tests::windows_tests::piped_child_has_no_console_with_or_without_job_containment",
"--nocapture",
])
.env("CODEX_PTY_DETACHED_CONSOLE_PROBE", "1")
.creation_flags(winapi::um::winbase::DETACHED_PROCESS)
.output()?;
anyhow::ensure!(
output.status.success(),
"detached probe failed:\n{}\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr),
);
return Ok(());
}
let Some(python) = find_python() else {
eprintln!("python not found; skipping Windows pipe console test");
return Ok(());
};
let job = crate::JobObject::create_without_breakaway()?;
for containment in [None, Some(&job)] {
let mut command = crate::Command::new(&python);
command.envs(std::env::vars()).args([
"-u",
"-c",
"import ctypes,sys; print(ctypes.windll.kernel32.GetConsoleWindow()); print(sys.stdin.readline().strip())",
]);
if let Some(job) = containment {
command.prepare_suspended_spawn(job);
}
let mut child = command.spawn()?;
if let Some(job) = containment {
let pid = child
.id()
.ok_or_else(|| anyhow::anyhow!("missing child pid"))?;
anyhow::ensure!(
job.assign_and_resume_process(pid)?.is_some(),
"job assignment failed"
);
}
child
.stdin
.as_mut()
.unwrap()
.write_all(b"stdio works\n")
.await?;
let output =
tokio::time::timeout(Duration::from_secs(10), child.wait_with_output()).await??;
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
assert_eq!(
String::from_utf8(output.stdout)?.replace("\r\n", "\n"),
"0\nstdio works\n"
);
}
Ok(())
}
struct WindowsShell {
name: &'static str,
program: String,
args: Vec<String>,
child_command: String,
}
fn find_powershell() -> Option<String> {
["pwsh.exe", "powershell.exe"]
.into_iter()
.find_map(|candidate| {
std::process::Command::new(candidate)
.args(["-NoLogo", "-NoProfile", "-Command", "exit 0"])
.status()
.ok()
.filter(std::process::ExitStatus::success)
.map(|_| candidate.to_string())
})
}
fn utf8_hex(value: &str) -> String {
value
.as_bytes()
.iter()
.map(|byte| format!("{byte:02x}"))
.collect::<Vec<_>>()
.join("")
}
async fn wait_for_path(path: &Path, timeout: Duration) -> bool {
let deadline = tokio::time::Instant::now() + timeout;
loop {
if path.exists() {
return true;
}
let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
if remaining.is_zero() {
return false;
}
tokio::time::sleep(remaining.min(Duration::from_millis(25))).await;
}
}
async fn assert_terminate_kills_descendant(
backend: &str,
python: &str,
env: &HashMap<String, String>,
) -> anyhow::Result<()> {
let marker = std::env::temp_dir().join(format!(
"codex-job-descendant-{backend}-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)?
.as_nanos()
));
let child_code = format!(
"import pathlib,time; print('{READY_MARKER}',flush=True); time.sleep(1); pathlib.Path(bytes.fromhex('{}').decode()).write_text('survived')",
utf8_hex(&marker.to_string_lossy())
);
// Exercise descendants created after the best-effort pipe assignment,
// without making the test depend on winning the intentionally accepted race.
let code = format!(
"import subprocess,sys,time; time.sleep(0.5); code=bytes.fromhex('{}').decode(); subprocess.Popen([sys.executable,'-u','-c',code]); time.sleep(60)",
utf8_hex(&child_code)
);
let args = vec!["-u".to_string(), "-c".to_string(), code];
let spawned = if backend == "pipe" {
spawn_pipe_process_no_stdin(python, &args, Path::new("."), env, /*arg0*/ &None, &[]).await?
} else {
spawn_pty_process(
python,
&args,
Path::new("."),
env,
/*arg0*/ &None,
TerminalSize::default(),
crate::ChildFds::Inherited(&[]),
)
.await?
};
let (session, mut output_rx, exit_rx) = combine_spawned_output(spawned);
wait_for_output_contains(&mut output_rx, READY_MARKER, /*timeout_ms*/ 10_000).await?;
session.request_terminate();
let (_, exit_code) = collect_output_until_exit(output_rx, exit_rx, /*timeout_ms*/ 10_000).await;
assert_ne!(
exit_code, -1,
"{backend} root did not exit after termination"
);
tokio::time::sleep(Duration::from_secs(2)).await;
let survived = marker.exists();
if survived {
std::fs::remove_file(&marker)?;
}
assert!(!survived, "{backend} descendant survived termination");
Ok(())
}
async fn assert_normal_exit_preserves_descendant(
backend: &str,
python: &str,
env: &HashMap<String, String>,
) -> anyhow::Result<()> {
let marker_base = std::env::temp_dir().join(format!(
"codex-job-natural-exit-{backend}-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)?
.as_nanos()
));
let ready_marker = marker_base.with_extension("ready");
let survival_marker = marker_base.with_extension("survived");
let child_code = format!(
"import pathlib,time; pathlib.Path(bytes.fromhex('{}').decode()).write_text('ready'); time.sleep(1); pathlib.Path(bytes.fromhex('{}').decode()).write_text('survived')",
utf8_hex(&ready_marker.to_string_lossy()),
utf8_hex(&survival_marker.to_string_lossy())
);
let code = format!(
"import pathlib,subprocess,sys,time; code=bytes.fromhex('{}').decode(); ready=pathlib.Path(bytes.fromhex('{}').decode()); subprocess.Popen([sys.executable,'-u','-c',code],stdin=subprocess.DEVNULL,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,creationflags=subprocess.DETACHED_PROCESS|subprocess.CREATE_NEW_PROCESS_GROUP); deadline=time.time()+10\nwhile not ready.exists() and time.time()<deadline: time.sleep(.05)\nsys.exit(0 if ready.exists() else 2)",
utf8_hex(&child_code),
utf8_hex(&ready_marker.to_string_lossy())
);
let args = vec!["-u".to_string(), "-c".to_string(), code];
let spawned = if backend == "pipe" {
spawn_pipe_process_no_stdin(python, &args, Path::new("."), env, /*arg0*/ &None, &[]).await?
} else {
spawn_pty_process(
python,
&args,
Path::new("."),
env,
/*arg0*/ &None,
TerminalSize::default(),
crate::ChildFds::Inherited(&[]),
)
.await?
};
let (session, output_rx, exit_rx) = combine_spawned_output(spawned);
let (_, exit_code) = collect_output_until_exit(output_rx, exit_rx, /*timeout_ms*/ 10_000).await;
assert_eq!(exit_code, 0, "{backend} root did not exit normally");
drop(session);
let survived = wait_for_path(&survival_marker, Duration::from_secs(10)).await;
let _ = std::fs::remove_file(ready_marker);
let _ = std::fs::remove_file(survival_marker);
assert!(survived, "{backend} descendant did not survive normal exit");
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn terminate_kills_descendants_for_best_effort_pipe_and_atomic_conpty() -> anyhow::Result<()>
{
let Some(python) = find_python() else {
eprintln!("python not found; skipping Windows process-tree termination test");
return Ok(());
};
let env: HashMap<String, String> = std::env::vars().collect();
assert_terminate_kills_descendant("pipe", &python, &env).await?;
assert_terminate_kills_descendant("ConPTY", &python, &env).await
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn normal_exit_preserves_descendants_for_pipe_and_conpty() -> anyhow::Result<()> {
let Some(python) = find_python() else {
eprintln!("python not found; skipping Windows process-tree natural-exit test");
return Ok(());
};
let env: HashMap<String, String> = std::env::vars().collect();
assert_normal_exit_preserves_descendant("pipe", &python, &env).await?;
assert_normal_exit_preserves_descendant("ConPTY", &python, &env).await
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn contained_spawn_owns_immediate_descendant() -> anyhow::Result<()> {
let Some(python) = find_python() else {
eprintln!("python not found; skipping Windows contained-spawn test");
return Ok(());
};
let mut command = Command::new(&python);
command
.args([
"-u",
"-c",
"import subprocess,sys; child=subprocess.Popen([sys.executable,'-c','import time; time.sleep(60)']); print(child.pid,flush=True); child.wait()",
])
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null());
let job = crate::JobObject::create()?;
let mut root = job.spawn_contained(&mut command)?;
let stdout = root
.stdout
.take()
.ok_or_else(|| anyhow::anyhow!("missing contained process stdout"))?;
let mut stdout = BufReader::new(stdout);
let mut child_pid = String::new();
tokio::time::timeout(Duration::from_secs(10), stdout.read_line(&mut child_pid)).await??;
let child_pid: u32 = child_pid.trim().parse()?;
let process = unsafe {
OpenProcess(
PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE,
/*bInheritHandle*/ 0,
child_pid,
)
};
anyhow::ensure!(!process.is_null(), "failed to open immediate child process");
let process = unsafe { OwnedHandle::from_raw_handle(process.cast()) };
let mut in_job = 0;
let checked = unsafe {
IsProcessInJob(
process.as_raw_handle().cast(),
job.as_raw_handle().cast(),
&mut in_job,
)
};
anyhow::ensure!(checked != 0, "failed to inspect child Job Object");
anyhow::ensure!(in_job != 0, "immediate child escaped its Job Object");
let root_handle = root
.raw_handle()
.ok_or_else(|| anyhow::anyhow!("missing contained root handle"))?;
let root_handle = unsafe { BorrowedHandle::borrow_raw(root_handle) }.try_clone_to_owned()?;
job.terminate_and_wait(&root_handle, Duration::from_secs(10))?;
let child_status = unsafe {
WaitForSingleObject(process.as_raw_handle().cast(), /*dwMilliseconds*/ 0)
};
assert_eq!(child_status, WAIT_OBJECT_0);
tokio::time::timeout(Duration::from_secs(10), root.wait()).await??;
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn rejected_job_assignment_resumes_existing_job_member() -> anyhow::Result<()> {
let Some(python) = find_python() else {
eprintln!("python not found; skipping Windows nested-job fallback test");
return Ok(());
};
let owning_job = crate::JobObject::create()?;
let rejected_job = crate::JobObject::create_without_breakaway()?;
let mut occupied_command = Command::new(&python);
occupied_command
.args(["-c", "import time; time.sleep(60)"])
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null());
let mut existing_member = rejected_job.spawn_contained(&mut occupied_command)?;
let mut command = Command::new(&python);
command
.args([
"-u",
"-c",
"import time; print('resumed',flush=True); time.sleep(60)",
])
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null());
rejected_job.prepare_suspended_spawn(&mut command);
let mut root = command.spawn()?;
let process_handle = root
.raw_handle()
.ok_or_else(|| anyhow::anyhow!("missing suspended process handle"))?;
owning_job.assign_process(process_handle)?;
let process_id = root
.id()
.ok_or_else(|| anyhow::anyhow!("missing suspended process id"))?;
assert!(
rejected_job
.assign_and_resume_process(process_id)?
.is_none(),
"unrelated nested job unexpectedly accepted the process"
);
let stdout = root
.stdout
.take()
.ok_or_else(|| anyhow::anyhow!("missing resumed process stdout"))?;
let mut stdout = BufReader::new(stdout);
let mut marker = String::new();
tokio::time::timeout(Duration::from_secs(10), stdout.read_line(&mut marker)).await??;
assert_eq!(marker.trim(), "resumed");
let process_handle = crate::JobObject::open_process_handle(process_id)?;
crate::JobObject::terminate_process_handle(&process_handle)?;
rejected_job.terminate()?;
let status = tokio::time::timeout(Duration::from_secs(10), root.wait()).await??;
assert_eq!(status.code(), Some(1));
tokio::time::timeout(Duration::from_secs(10), existing_member.wait()).await??;
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn conpty_delivers_input_to_foreground_children() -> anyhow::Result<()> {
let Some(python) = find_python() else {
eprintln!("python not found; skipping ConPTY input test");
return Ok(());
};
let code = format!(
"print('__CODEX_CHILD_'+'READY__', flush=True); value=input(); print('{VALUE_MARKER}'+value.encode('utf-8').hex(), flush=True)"
);
let expected = "cafeé 漢字";
let expected_marker = format!("{VALUE_MARKER}{}", utf8_hex(expected));
let mut shells = vec![WindowsShell {
name: "cmd",
program: std::env::var("COMSPEC").unwrap_or_else(|_| "cmd.exe".to_string()),
args: vec!["/D".to_string(), "/Q".to_string()],
child_command: format!("\"{}\" -u -c \"{code}\"", python.replace('"', "\"\"")),
}];
if let Some(program) = find_powershell() {
shells.push(WindowsShell {
name: "PowerShell",
program,
args: vec!["-NoLogo".to_string(), "-NoProfile".to_string()],
child_command: format!("& '{}' -u -c \"{code}\"", python.replace('\'', "''")),
});
}
let env: HashMap<String, String> = std::env::vars().collect();
for shell in shells {
let spawned = spawn_pty_process(
&shell.program,
&shell.args,
Path::new("."),
&env,
/*arg0*/ &None,
TerminalSize::default(),
crate::ChildFds::Inherited(&[]),
)
.await?;
let (session, mut output_rx, exit_rx) = combine_spawned_output(spawned);
let writer = session.writer_sender();
writer
.send(format!("{}\n", shell.child_command).into_bytes())
.await?;
wait_for_output_contains(&mut output_rx, READY_MARKER, /*timeout_ms*/ 10_000)
.await
.map_err(|err| anyhow::anyhow!("{} child did not become ready: {err}", shell.name))?;
writer
.send(format!("{expected}X\u{8}\n").into_bytes())
.await?;
let mut output =
wait_for_output_contains(&mut output_rx, &expected_marker, /*timeout_ms*/ 10_000)
.await
.map_err(|err| {
anyhow::anyhow!("{} child received incorrect input: {err}", shell.name)
})?;
writer.send(b"exit 0\n".to_vec()).await?;
let (remaining, exit_code) =
collect_output_until_exit(output_rx, exit_rx, /*timeout_ms*/ 10_000).await;
output.extend_from_slice(&remaining);
assert_eq!(
exit_code,
0,
"{} did not exit cleanly: {:?}",
shell.name,
String::from_utf8_lossy(&output)
);
}
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn conpty_ctrl_c_interrupts_powershell_foreground_child() -> anyhow::Result<()> {
let Some(program) = find_powershell() else {
return Ok(());
};
let args = vec!["-NoLogo".to_string(), "-NoProfile".to_string()];
let env: HashMap<String, String> = std::env::vars().collect();
let spawned = spawn_pty_process(
&program,
&args,
Path::new("."),
&env,
/*arg0*/ &None,
TerminalSize::default(),
crate::ChildFds::Inherited(&[]),
)
.await?;
let (session, mut output_rx, exit_rx) = combine_spawned_output(spawned);
let writer = session.writer_sender();
// CI may pass its ignored Ctrl-C disposition to children. Reset it in the
// foreground process itself before checking delivery through ConPTY.
let python = find_python()
.ok_or_else(|| anyhow::anyhow!("Python is required for the Ctrl-C fixture"))?;
let python = python.replace('\'', "''");
let command = format!(
r#"& '{python}' -u -c "import ctypes,time; assert ctypes.windll.kernel32.SetConsoleCtrlHandler(None, False); print('__CODEX_CHILD_'+'READY__'); time.sleep(60)""#
);
writer.send(format!("{command}\n").into_bytes()).await?;
wait_for_output_contains(&mut output_rx, READY_MARKER, /*timeout_ms*/ 10_000).await?;
writer.send(vec![0x03]).await?;
wait_for_output_contains(&mut output_rx, "PS ", /*timeout_ms*/ 10_000).await?;
writer.send(b"cmd.exe /D /C ver\n".to_vec()).await?;
let mut output = wait_for_output_contains(
&mut output_rx,
"Microsoft Windows",
/*timeout_ms*/ 10_000,
)
.await?;
writer.send(b"exit 0\n".to_vec()).await?;
let (remaining, exit_code) =
collect_output_until_exit(output_rx, exit_rx, /*timeout_ms*/ 10_000).await;
output.extend_from_slice(&remaining);
assert_eq!(
exit_code,
0,
"PowerShell did not resume after Ctrl-C: {:?}",
String::from_utf8_lossy(&output)
);
Ok(())
}

View File

@@ -0,0 +1,70 @@
#![cfg(windows)]
use codex_utils_pty::RawConPty;
use std::ffi::OsStr;
use std::fs;
use std::os::windows::ffi::OsStrExt;
use std::path::Path;
use std::path::PathBuf;
use winapi::um::libloaderapi::GetModuleHandleW;
struct CurrentDirGuard {
original: PathBuf,
}
impl CurrentDirGuard {
fn enter(path: &Path) -> std::io::Result<Self> {
let original = std::env::current_dir()?;
std::env::set_current_dir(path)?;
Ok(Self { original })
}
}
impl Drop for CurrentDirGuard {
fn drop(&mut self) {
let _ = std::env::set_current_dir(&self.original);
}
}
#[test]
fn conpty_ignores_dll_in_current_directory() -> anyhow::Result<()> {
let temp_dir = std::env::temp_dir().join(format!(
"codex-conpty-search-path-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)?
.as_nanos()
));
fs::create_dir(&temp_dir)?;
let system_root =
std::env::var_os("SystemRoot").ok_or_else(|| anyhow::anyhow!("SystemRoot is not set"))?;
let candidate = temp_dir.join("conpty.dll");
// A kernel32 copy exports the ConPTY functions, so the old bare-name probe
// would successfully load and retain this repository-controlled file.
codex_utils_cargo_bin::copy_executable(
&PathBuf::from(system_root)
.join("System32")
.join("kernel32.dll"),
&candidate,
)?;
{
let _current_dir = CurrentDirGuard::enter(&temp_dir)?;
drop(RawConPty::new(/*cols*/ 80, /*rows*/ 24)?);
let conpty_dll = OsStr::new("conpty.dll")
.encode_wide()
.chain(std::iter::once(0))
.collect::<Vec<_>>();
let module = unsafe { GetModuleHandleW(conpty_dll.as_ptr()) };
assert!(
module.is_null(),
"ConPTY loaded conpty.dll from the process current directory"
);
}
fs::remove_file(candidate)?;
fs::remove_dir(temp_dir)?;
Ok(())
}

View File

@@ -0,0 +1,166 @@
//! Exercise the public pipe adapter with native spawning and explicit inheritance.
//! This binary isolates atfork registration from the rest of the test suite.
#![cfg(target_os = "macos")]
use std::collections::HashMap;
use std::io::Read;
use std::io::Seek;
use std::os::fd::AsRawFd;
use std::os::fd::FromRawFd;
use std::os::fd::OwnedFd;
use std::os::unix::fs::symlink;
use std::os::unix::process::CommandExt;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::time::Duration;
use codex_utils_pty::spawn_pipe_process;
use codex_utils_pty::spawn_pipe_process_no_stdin;
use pretty_assertions::assert_eq;
static PARENT_FORKS: AtomicUsize = AtomicUsize::new(0);
extern "C" fn record_parent_fork() {
PARENT_FORKS.fetch_add(1, Ordering::Relaxed);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn pipe_commands_avoid_fork() -> anyhow::Result<()> {
let directory = tempfile::tempdir()?;
let cwd = directory.path().canonicalize()?;
let executable = std::env::current_exe()?;
symlink(&executable, cwd.join("probe"))?;
let mut file = std::fs::File::create(cwd.join("preserved"))?;
let preserved = inheritable_fd(&file, /*minimum*/ 100)?;
let excluded = inheritable_fd(&file, /*minimum*/ 200)?;
let args = ["--exact", "pipe_child", "--ignored", "--nocapture"].map(str::to_owned);
let mut env = HashMap::from([
("PATH".to_string(), ".".to_string()),
("PRESERVED".to_string(), preserved.as_raw_fd().to_string()),
("EXCLUDED".to_string(), excluded.as_raw_fd().to_string()),
(
"EXPECTED_CWD".to_string(),
cwd.to_string_lossy().into_owned(),
),
]);
// SAFETY: This is the binary's only active test; the permanent parent hook
// only updates a lock-free atomic and remains valid until process exit.
assert_eq!(
unsafe {
libc::pthread_atfork(
/*prepare*/ None,
Some(record_parent_fork),
/*child*/ None,
)
},
0
);
let mut control = std::process::Command::new("/usr/bin/true");
// SAFETY: A no-op pre-exec hook forces fork for the positive control.
unsafe {
control.pre_exec(|| Ok(()));
}
assert!(control.status()?.success());
assert_eq!(PARENT_FORKS.load(Ordering::Relaxed), 1);
for program in [executable.as_os_str(), "./probe".as_ref(), "probe".as_ref()] {
for input in ["hello", ""] {
env.insert("EXPECTED_INPUT".to_string(), input.to_string());
file.set_len(0)?;
file.rewind()?;
let inherited = [preserved.as_raw_fd()];
let arg0 = Some("pipe-probe".to_string());
let mut child = if input.is_empty() {
spawn_pipe_process_no_stdin(program, &args, &cwd, &env, &arg0, &inherited).await?
} else {
spawn_pipe_process(program, &args, &cwd, &env, &arg0, &inherited).await?
};
if !input.is_empty() {
child
.session
.writer_sender()
.send(input.as_bytes().to_vec())
.await?;
}
child.session.close_stdin();
let (status, stdout, stderr) = tokio::time::timeout(Duration::from_secs(10), async {
let stdout = async {
let mut output = Vec::new();
while let Some(bytes) = child.stdout_rx.recv().await {
output.extend(bytes);
}
output
};
let stderr = async {
let mut output = Vec::new();
while let Some(bytes) = child.stderr_rx.recv().await {
output.extend(bytes);
}
output
};
tokio::join!(child.exit_rx, stdout, stderr)
})
.await?;
assert_eq!(
status?,
0,
"{}\n{}",
String::from_utf8_lossy(&stdout),
String::from_utf8_lossy(&stderr)
);
assert!(String::from_utf8_lossy(&stdout).contains("pipe child assertions completed"));
assert!(String::from_utf8_lossy(&stderr).contains("pipe diagnostic"));
assert_eq!(std::fs::read(cwd.join("preserved"))?, b"fd");
assert_eq!(PARENT_FORKS.load(Ordering::Relaxed), 1);
}
}
Ok(())
}
#[test]
#[ignore = "child process for pipe_commands_avoid_fork"]
fn pipe_child() -> anyhow::Result<()> {
assert_eq!(std::env::args().next().as_deref(), Some("pipe-probe"));
assert_eq!(
std::env::current_dir()?,
std::path::PathBuf::from(std::env::var("EXPECTED_CWD")?)
);
assert!(std::env::var_os("HOME").is_none());
// SAFETY: These calls inspect the current process's group and session.
assert_eq!(
unsafe {
(libc::getpgrp(), libc::getsid(/*pid*/ 0))
},
unsafe { (libc::getpid(), libc::getpid()) }
);
let preserved = std::env::var("PRESERVED")?.parse::<i32>()?;
let excluded = std::env::var("EXCLUDED")?.parse::<i32>()?;
// SAFETY: The buffer is valid; the syscall reports an error if the fd was not inherited.
assert_eq!(
unsafe { libc::write(preserved, b"fd".as_ptr().cast(), 2) },
2
);
// SAFETY: fcntl safely probes whether the unrelated descriptor survived exec.
assert_eq!(unsafe { libc::fcntl(excluded, libc::F_GETFD) }, -1);
assert_eq!(
std::io::Error::last_os_error().raw_os_error(),
Some(libc::EBADF)
);
let mut input = String::new();
std::io::stdin().read_to_string(&mut input)?;
assert_eq!(input, std::env::var("EXPECTED_INPUT")?);
eprintln!("pipe diagnostic");
println!("pipe child assertions completed");
Ok(())
}
fn inheritable_fd(file: &std::fs::File, minimum: i32) -> anyhow::Result<OwnedFd> {
// SAFETY: The live file is duplicated into a new descriptor without CLOEXEC.
let raw = unsafe { libc::fcntl(file.as_raw_fd(), libc::F_DUPFD, minimum) };
if raw == -1 {
return Err(std::io::Error::last_os_error().into());
}
// SAFETY: fcntl returned a new owned descriptor.
Ok(unsafe { OwnedFd::from_raw_fd(raw) })
}