aboutsummaryrefslogtreecommitdiffstats
path: root/src/tools/shell.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/tools/shell.rs')
-rw-r--r--src/tools/shell.rs67
1 files changed, 61 insertions, 6 deletions
diff --git a/src/tools/shell.rs b/src/tools/shell.rs
index 9c214fb..29d2375 100644
--- a/src/tools/shell.rs
+++ b/src/tools/shell.rs
@@ -1,17 +1,25 @@
1use std::fs::File; 1use std::fs::File;
2use std::io::{Read, Seek, SeekFrom}; 2use std::io::{Read, Seek, SeekFrom};
3use std::os::unix::process::{CommandExt, ExitStatusExt};
3use std::path::PathBuf; 4use std::path::PathBuf;
4use std::process::{Command, Stdio}; 5use std::process::{Command, Stdio};
5use std::sync::atomic::{AtomicU64, Ordering}; 6use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
6use std::time::{Duration, Instant}; 7use std::time::{Duration, Instant};
7 8
8use serde_json::Value; 9use serde_json::Value;
9 10
10const HEAD_BYTES: usize = 64 * 1024; 11const HEAD_BYTES: usize = 64 * 1024;
11const TAIL_BYTES: i64 = 16 * 1024; 12const TAIL_BYTES: i64 = 16 * 1024;
13/// The child cannot write more than this, so a runaway command cannot fill /tmp
14/// and take the machine down with it.
15const MAX_OUTPUT_BYTES: u64 = 64 * 1024 * 1024;
12static COUNTER: AtomicU64 = AtomicU64::new(0); 16static COUNTER: AtomicU64 = AtomicU64::new(0);
13 17
14pub fn bash(args: &Value, timeout: Duration) -> Result<String, String> { 18pub fn bash(
19 args: &Value,
20 timeout: Duration,
21 cancel: &AtomicBool,
22) -> Result<String, String> {
15 let cmd = match args.get("cmd").and_then(|v| v.as_str()) { 23 let cmd = match args.get("cmd").and_then(|v| v.as_str()) {
16 Some(cmd) => cmd.to_string(), 24 Some(cmd) => cmd.to_string(),
17 None => return Err("missing required argument `cmd`".into()), 25 None => return Err("missing required argument `cmd`".into()),
@@ -37,25 +45,53 @@ pub fn bash(args: &Value, timeout: Duration) -> Result<String, String> {
37 let stdout = file.try_clone().map_err(|e| e.to_string())?; 45 let stdout = file.try_clone().map_err(|e| e.to_string())?;
38 let stderr = file.try_clone().map_err(|e| e.to_string())?; 46 let stderr = file.try_clone().map_err(|e| e.to_string())?;
39 47
40 let mut child = Command::new("sh") 48 let mut command = Command::new("sh");
49 command
41 .arg("-c") 50 .arg("-c")
42 .arg(&cmd) 51 .arg(&cmd)
43 .current_dir(&cwd) 52 .current_dir(&cwd)
44 .stdin(Stdio::null()) 53 .stdin(Stdio::null())
45 .stdout(Stdio::from(stdout)) 54 .stdout(Stdio::from(stdout))
46 .stderr(Stdio::from(stderr)) 55 .stderr(Stdio::from(stderr))
56 // The harness owns the key; no build script needs it, and a failing
57 // command that dumps the environment would put it in the transcript.
58 .env_remove("OPENCODE_API_KEY")
59 // Own process group, so the whole tree can be killed and so terminal
60 // Ctrl-C does not race our own handling.
61 .process_group(0);
62 unsafe {
63 command.pre_exec(|| {
64 let limit = libc::rlimit {
65 rlim_cur: MAX_OUTPUT_BYTES,
66 rlim_max: MAX_OUTPUT_BYTES,
67 };
68 if libc::setrlimit(libc::RLIMIT_FSIZE, &limit) != 0 {
69 return Err(std::io::Error::last_os_error());
70 }
71 Ok(())
72 });
73 }
74
75 let mut child = command
47 .spawn() 76 .spawn()
48 .map_err(|e| format!("failed to start sh: {e}"))?; 77 .map_err(|e| format!("failed to start sh: {e}"))?;
78 let group = child.id() as i32;
49 79
50 let deadline = Instant::now() + timeout; 80 let deadline = Instant::now() + timeout;
51 let mut timed_out = false; 81 let mut timed_out = false;
82 let mut aborted = false;
52 let status = loop { 83 let status = loop {
84 if cancel.load(Ordering::Relaxed) {
85 aborted = true;
86 kill_group(group);
87 break child.wait().map_err(|e| e.to_string())?;
88 }
53 match child.try_wait().map_err(|e| e.to_string())? { 89 match child.try_wait().map_err(|e| e.to_string())? {
54 Some(status) => break status, 90 Some(status) => break status,
55 None => { 91 None => {
56 if Instant::now() >= deadline { 92 if Instant::now() >= deadline {
57 let _ = child.kill();
58 timed_out = true; 93 timed_out = true;
94 kill_group(group);
59 break child.wait().map_err(|e| e.to_string())?; 95 break child.wait().map_err(|e| e.to_string())?;
60 } 96 }
61 std::thread::sleep(Duration::from_millis(20)); 97 std::thread::sleep(Duration::from_millis(20));
@@ -63,6 +99,9 @@ pub fn bash(args: &Value, timeout: Duration) -> Result<String, String> {
63 } 99 }
64 }; 100 };
65 101
102 // A child that blew the file-size limit was killed by SIGXFSZ.
103 let over_limit = status.signal() == Some(libc::SIGXFSZ);
104
66 let output = read_capped(&mut file).map_err(|e| format!("could not read output: {e}"))?; 105 let output = read_capped(&mut file).map_err(|e| format!("could not read output: {e}"))?;
67 drop(file); 106 drop(file);
68 let _ = std::fs::remove_file(&path); 107 let _ = std::fs::remove_file(&path);
@@ -71,7 +110,14 @@ pub fn bash(args: &Value, timeout: Duration) -> Result<String, String> {
71 if !out.is_empty() && !out.ends_with('\n') { 110 if !out.is_empty() && !out.ends_with('\n') {
72 out.push('\n'); 111 out.push('\n');
73 } 112 }
74 if timed_out { 113 if over_limit {
114 out.push_str(&format!(
115 "[output exceeded {} MiB; command killed]",
116 MAX_OUTPUT_BYTES / (1024 * 1024)
117 ));
118 } else if aborted {
119 out.push_str("[aborted by the user]");
120 } else if timed_out {
75 out.push_str(&format!( 121 out.push_str(&format!(
76 "[timed out after {:.1}s; process killed]", 122 "[timed out after {:.1}s; process killed]",
77 timeout.as_secs_f64() 123 timeout.as_secs_f64()
@@ -80,7 +126,6 @@ pub fn bash(args: &Value, timeout: Duration) -> Result<String, String> {
80 match status.code() { 126 match status.code() {
81 Some(code) => out.push_str(&format!("[exit {code}]")), 127 Some(code) => out.push_str(&format!("[exit {code}]")),
82 None => { 128 None => {
83 use std::os::unix::process::ExitStatusExt;
84 out.push_str(&format!( 129 out.push_str(&format!(
85 "[killed by signal {}]", 130 "[killed by signal {}]",
86 status.signal().unwrap_or_default() 131 status.signal().unwrap_or_default()
@@ -127,3 +172,13 @@ fn read_capped(file: &mut File) -> Result<String, String> {
127 } 172 }
128 Ok(String::from_utf8_lossy(&out).into_owned()) 173 Ok(String::from_utf8_lossy(&out).into_owned())
129} 174}
175
176/// SIGKILL the whole process group the command created. `child.kill()` would
177/// only reach `sh`, leaving `sh`'s children running on the 2-core box.
178fn kill_group(pid: i32) {
179 if pid > 0 {
180 unsafe {
181 libc::kill(-pid, libc::SIGKILL);
182 }
183 }
184}