forked from openai/codex
-
Notifications
You must be signed in to change notification settings - Fork 229
Expand file tree
/
Copy pathspawn.rs
More file actions
365 lines (322 loc) · 12.6 KB
/
spawn.rs
File metadata and controls
365 lines (322 loc) · 12.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
use std::collections::HashMap;
use std::io;
use std::path::PathBuf;
use std::process::Stdio;
use std::time::Duration;
use tokio::process::Child;
use tokio::process::Command;
use tokio::time::sleep;
use tracing::trace;
use crate::protocol::SandboxPolicy;
/// Experimental environment variable that will be set to some non-empty value
/// if both of the following are true:
///
/// 1. The process was spawned by Codex as part of a shell tool call.
/// 2. SandboxPolicy.has_full_network_access() was false for the tool call.
///
/// We may try to have just one environment variable for all sandboxing
/// attributes, so this may change in the future.
pub const CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR: &str = "CODEX_SANDBOX_NETWORK_DISABLED";
/// Should be set when the process is spawned under a sandbox. Currently, the
/// value is "seatbelt" for macOS, but it may change in the future to
/// accommodate sandboxing configuration and other sandboxing mechanisms.
pub const CODEX_SANDBOX_ENV_VAR: &str = "CODEX_SANDBOX";
const SPAWN_RETRY_DELAYS_MS: [u64; 3] = [0, 10, 50];
#[cfg(unix)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum UnixChildSessionStrategy {
NewSession,
NewProcessGroup,
}
#[cfg(unix)]
fn unix_child_session_strategy(stdio_policy: StdioPolicy) -> UnixChildSessionStrategy {
match stdio_policy {
// Shell tool commands are non-interactive, but they may launch their own
// long-lived descendants (for example via `nohup ... &`). Starting the
// shell tool in a new session ensures those descendants cannot retain
// the TUI's controlling terminal and steal foreground ownership.
StdioPolicy::RedirectForShellTool => UnixChildSessionStrategy::NewSession,
// Interactive children should keep terminal semantics while still being
// isolated in their own process group for targeted signal handling.
StdioPolicy::Inherit => UnixChildSessionStrategy::NewProcessGroup,
}
}
fn is_temporary_resource_error(err: &io::Error) -> bool {
err.kind() == io::ErrorKind::WouldBlock
|| matches!(err.raw_os_error(), Some(35) | Some(libc::ENOMEM))
}
fn spawn_with_retry_blocking<F, T>(mut spawn: F) -> io::Result<T>
where
F: FnMut() -> io::Result<T>,
{
let mut last_err: Option<io::Error> = None;
for delay_ms in SPAWN_RETRY_DELAYS_MS {
match spawn() {
Ok(child) => return Ok(child),
Err(err) if is_temporary_resource_error(&err) => {
last_err = Some(err);
if delay_ms > 0 {
std::thread::sleep(Duration::from_millis(delay_ms));
}
}
Err(err) => return Err(err),
}
}
Err(last_err.unwrap_or_else(|| io::Error::other("spawn failed")))
}
async fn spawn_with_retry_async<F, T>(mut spawn: F) -> io::Result<T>
where
F: FnMut() -> io::Result<T>,
{
let mut last_err: Option<io::Error> = None;
for delay_ms in SPAWN_RETRY_DELAYS_MS {
match spawn() {
Ok(child) => return Ok(child),
Err(err) if is_temporary_resource_error(&err) => {
last_err = Some(err);
if delay_ms > 0 {
sleep(Duration::from_millis(delay_ms)).await;
}
}
Err(err) => return Err(err),
}
}
Err(last_err.unwrap_or_else(|| io::Error::other("spawn failed")))
}
pub fn spawn_std_command_with_retry(
cmd: &mut std::process::Command,
) -> io::Result<std::process::Child> {
spawn_with_retry_blocking(|| cmd.spawn())
}
/// Spawn a fire-and-forget helper without sharing this process's controlling
/// terminal. This avoids job-control collisions with the TUI when background
/// helpers are launched from interactive sessions.
pub fn spawn_background_command_with_retry(
cmd: &mut std::process::Command,
) -> io::Result<std::process::Child> {
cmd.stdin(Stdio::null());
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
unsafe {
cmd.pre_exec(|| {
if libc::setsid() == -1 {
let err = io::Error::last_os_error();
if err.raw_os_error() != Some(libc::EPERM) {
return Err(err);
}
}
Ok(())
});
}
}
spawn_std_command_with_retry(cmd)
}
pub async fn spawn_tokio_command_with_retry(cmd: &mut Command) -> io::Result<Child> {
spawn_with_retry_async(|| cmd.spawn()).await
}
#[derive(Debug, Clone, Copy)]
pub enum StdioPolicy {
RedirectForShellTool,
Inherit,
}
/// Spawns the appropriate child process for the ExecParams and SandboxPolicy,
/// ensuring the args and environment variables used to create the `Command`
/// (and `Child`) honor the configuration.
///
/// For now, we take `SandboxPolicy` as a parameter to spawn_child() because
/// we need to determine whether to set the
/// `CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR` environment variable.
pub(crate) async fn spawn_child_async(
program: PathBuf,
args: Vec<String>,
#[cfg_attr(not(unix), allow(unused_variables))] arg0: Option<&str>,
cwd: PathBuf,
sandbox_policy: &SandboxPolicy,
stdio_policy: StdioPolicy,
env: HashMap<String, String>,
) -> std::io::Result<Child> {
trace!(
"spawn_child_async: {program:?} {args:?} {arg0:?} {cwd:?} {sandbox_policy:?} {stdio_policy:?} {env:?}"
);
let mut cmd = Command::new(&program);
#[cfg(unix)]
cmd.arg0(arg0.map_or_else(|| program.to_string_lossy().to_string(), String::from));
cmd.args(args);
cmd.current_dir(cwd);
cmd.env_clear();
cmd.envs(env);
if !sandbox_policy.has_full_network_access() {
cmd.env(CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR, "1");
}
// If this Codex process dies (including being killed via SIGKILL), we want
// any child processes that were spawned as part of a `"shell"` tool call
// to also be terminated.
// Ensure children form their own process group; on timeout we can kill the group.
// Also, on Linux, set PDEATHSIG so children die if parent dies.
#[cfg(unix)]
unsafe {
#[cfg(target_os = "linux")]
let exec_memory_max_bytes = match stdio_policy {
StdioPolicy::RedirectForShellTool => crate::cgroup::default_exec_memory_max_bytes(),
StdioPolicy::Inherit => None,
};
#[cfg(unix)]
let session_strategy = unix_child_session_strategy(stdio_policy);
cmd.pre_exec(move || {
#[cfg(unix)]
match session_strategy {
UnixChildSessionStrategy::NewSession => {
if libc::setsid() == -1 {
let err = std::io::Error::last_os_error();
if err.raw_os_error() != Some(libc::EPERM) {
return Err(err);
}
}
}
UnixChildSessionStrategy::NewProcessGroup => {
// Start a new process group.
let _ = libc::setpgid(0, 0);
}
}
#[cfg(target_os = "linux")]
{
if libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGTERM) == -1 {
return Err(std::io::Error::last_os_error());
}
if libc::getppid() == 1 {
libc::raise(libc::SIGTERM);
}
if let Some(memory_max_bytes) = exec_memory_max_bytes {
crate::cgroup::best_effort_attach_self_to_exec_cgroup(
libc::getpid() as u32,
memory_max_bytes,
);
}
}
Ok(())
});
}
match stdio_policy {
StdioPolicy::RedirectForShellTool => {
// Do not create a file descriptor for stdin because otherwise some
// commands may hang forever waiting for input. For example, ripgrep has
// a heuristic where it may try to read from stdin as explained here:
// https://github.com/BurntSushi/ripgrep/blob/e2362d4d5185d02fa857bf381e7bd52e66fafc73/crates/core/flags/hiargs.rs#L1101-L1103
cmd.stdin(Stdio::null());
cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
}
StdioPolicy::Inherit => {
// Inherit stdin, stdout, and stderr from the parent process.
cmd.stdin(Stdio::inherit())
.stdout(Stdio::inherit())
.stderr(Stdio::inherit());
}
}
cmd.kill_on_drop(true);
spawn_tokio_command_with_retry(&mut cmd).await
}
#[cfg(test)]
mod tests {
use super::*;
use crate::protocol::SandboxPolicy;
#[cfg(unix)]
static STDIN_GUARD: std::sync::Mutex<()> = std::sync::Mutex::new(());
#[cfg(unix)]
struct StdinRedirectGuard {
saved_stdin_fd: i32,
read_fd: i32,
write_fd: i32,
}
#[cfg(unix)]
impl StdinRedirectGuard {
fn install_pipe_as_stdin() -> Self {
let mut fds = [0; 2];
assert_eq!(unsafe { libc::pipe(fds.as_mut_ptr()) }, 0, "pipe");
let saved_stdin_fd = unsafe { libc::dup(libc::STDIN_FILENO) };
assert!(saved_stdin_fd >= 0, "dup stdin");
assert_eq!(unsafe { libc::dup2(fds[0], libc::STDIN_FILENO) }, libc::STDIN_FILENO, "dup2 stdin");
Self {
saved_stdin_fd,
read_fd: fds[0],
write_fd: fds[1],
}
}
}
#[cfg(unix)]
impl Drop for StdinRedirectGuard {
fn drop(&mut self) {
unsafe {
let _ = libc::dup2(self.saved_stdin_fd, libc::STDIN_FILENO);
let _ = libc::close(self.saved_stdin_fd);
let _ = libc::close(self.read_fd);
let _ = libc::close(self.write_fd);
}
}
}
#[cfg(unix)]
#[test]
fn background_spawn_redirects_stdin_away_from_parent_terminal() {
let _guard = STDIN_GUARD.lock().expect("stdin test mutex");
let _stdin_guard = StdinRedirectGuard::install_pipe_as_stdin();
let mut cmd = std::process::Command::new("python3");
cmd.arg("-c")
.arg("import sys; data = sys.stdin.read(); print('eof' if data == '' else 'data')")
.stdout(Stdio::piped())
.stderr(Stdio::piped());
let mut child = spawn_background_command_with_retry(&mut cmd).expect("spawn background helper");
let deadline = std::time::Instant::now() + Duration::from_secs(2);
loop {
if let Some(_status) = child.try_wait().expect("poll child") {
break;
}
assert!(std::time::Instant::now() < deadline, "background helper should not block on inherited stdin");
std::thread::sleep(Duration::from_millis(10));
}
let output = child.wait_with_output().expect("wait with output");
assert!(output.status.success(), "child should exit successfully: {output:?}");
assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "eof");
}
#[cfg(unix)]
#[test]
fn redirect_for_shell_tool_uses_new_session_strategy() {
assert_eq!(
unix_child_session_strategy(StdioPolicy::RedirectForShellTool),
UnixChildSessionStrategy::NewSession,
);
assert_eq!(
unix_child_session_strategy(StdioPolicy::Inherit),
UnixChildSessionStrategy::NewProcessGroup,
);
}
#[cfg(unix)]
#[tokio::test]
async fn redirect_for_shell_tool_detaches_from_controlling_tty() {
let parent_tty = match std::fs::OpenOptions::new().read(true).open("/dev/tty") {
Ok(tty) => tty,
Err(_) => return,
};
drop(parent_tty);
let child = spawn_child_async(
PathBuf::from("python3"),
vec![
"-c".to_string(),
"import os\ntry:\n os.open('/dev/tty', os.O_RDONLY)\n print('tty-present')\nexcept OSError as e:\n print(f'tty-missing:{e.errno}')".to_string(),
],
None,
std::env::current_dir().expect("cwd"),
&SandboxPolicy::DangerFullAccess,
StdioPolicy::RedirectForShellTool,
HashMap::new(),
)
.await
.expect("spawn shell tool child");
let output = child.wait_with_output().await.expect("wait for child");
assert!(output.status.success(), "child should exit successfully: {output:?}");
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(
stdout.trim_start().starts_with("tty-missing:"),
"shell tool child should not retain a controlling tty: {stdout:?}"
);
}
}