1use std::fs::OpenOptions;
5use std::io::{self, Read, Write};
6use std::process::{Child, ChildStderr, ChildStdin, ChildStdout, Command, Stdio};
7use std::sync::{Arc, LazyLock};
8use std::thread;
9use std::time::{Duration, Instant};
10
11use harn_vm::process_sandbox;
12
13use super::handle::{
14 EnvMode, ExitStatus, OutputCapture, ProcessCleanupReport, ProcessError, ProcessHandle,
15 ProcessKiller, ProcessSpawner, SpawnSpec, WaitOutcome,
16};
17
18pub struct RealSpawner;
20
21static REAL_SPAWNER: LazyLock<Arc<dyn ProcessSpawner>> =
22 LazyLock::new(|| Arc::new(RealSpawner) as Arc<dyn ProcessSpawner>);
23
24pub fn default_spawner() -> Arc<dyn ProcessSpawner> {
26 Arc::clone(&REAL_SPAWNER)
27}
28
29impl ProcessSpawner for RealSpawner {
30 fn spawn(&self, spec: SpawnSpec) -> Result<Box<dyn ProcessHandle>, ProcessError> {
31 let (mut command, cleanup_token) = prepare_command(&spec, None)?;
32 let child = command.spawn().map_err(map_spawn_error)?;
33
34 let pid = child.id();
35 let pgid = child_process_group_id(pid);
36 let killer: Arc<dyn ProcessKiller> = Arc::new(RealKiller {
37 pid,
38 cleanup_token: cleanup_token.clone(),
39 });
40
41 Ok(Box::new(RealProcess {
42 pid,
43 pgid,
44 cleanup_token,
45 killer,
46 child: Some(child),
47 stdin: None,
48 stdout: None,
49 stderr: None,
50 stdin_taken: false,
51 stdout_taken: false,
52 stderr_taken: false,
53 }))
54 }
55}
56
57fn prepare_command(
58 spec: &SpawnSpec,
59 cleanup_token: Option<String>,
60) -> Result<(Command, String), ProcessError> {
61 if spec.program.is_empty() {
62 return Err(ProcessError::InvalidArgv(
63 "first element of argv must be a non-empty program name".to_string(),
64 ));
65 }
66
67 let mut command = process_sandbox::std_command_for(&spec.program, &spec.args)
68 .map_err(|e| ProcessError::SandboxSetup(format!("{e:?}")))?;
69
70 if let Some(cwd) = spec.cwd.as_ref() {
71 process_sandbox::enforce_process_cwd(cwd)
72 .map_err(|e| ProcessError::SandboxCwd(format!("{e:?}")))?;
73 command.current_dir(cwd);
74 }
75
76 match spec.env_mode {
77 EnvMode::Replace => {
79 command.env_clear();
80 }
81 EnvMode::InheritClean | EnvMode::Patch => {
88 for (key, _) in std::env::vars_os() {
89 if let Some(name) = key.to_str() {
90 if super::handle::is_sensitive_env_name(name) {
91 command.env_remove(&key);
92 }
93 }
94 }
95 }
96 }
97 for key in &spec.env_remove {
102 command.env_remove(key);
103 }
104 for (key, value) in &spec.env {
105 command.env(key, value);
106 }
107
108 for (key, value) in process_sandbox::active_workspace_process_env() {
112 if spec.env.contains_key(&key) {
113 continue;
114 }
115 command.env(key, value);
116 }
117
118 if !spec
126 .env
127 .contains_key(process_sandbox::MESSAGE_LOCALE_OVERRIDE_ENV)
128 {
129 command.env_remove(process_sandbox::MESSAGE_LOCALE_OVERRIDE_ENV);
130 }
131 for (key, value) in process_sandbox::deterministic_message_locale_env() {
132 if spec.env.contains_key(&key) {
133 continue;
134 }
135 command.env(key, value);
136 }
137
138 log_spawn_context(&command, spec.env_mode);
139
140 if spec.configure_process_group {
141 configure_background_process_group(&mut command);
142 }
143 let cleanup_token =
144 cleanup_token.unwrap_or_else(harn_vm::op_interrupt::new_process_cleanup_token);
145 command.env(
146 harn_vm::op_interrupt::PROCESS_CLEANUP_TOKEN_ENV,
147 &cleanup_token,
148 );
149
150 match &spec.output_capture {
151 OutputCapture::Inherit => {
152 command.stdout(Stdio::inherit());
153 command.stderr(Stdio::inherit());
154 }
155 OutputCapture::Pipe => {
156 command.stdout(Stdio::piped());
157 command.stderr(Stdio::piped());
158 }
159 OutputCapture::File {
160 stdout_path,
161 stderr_path,
162 } => {
163 let stdout = OpenOptions::new()
164 .write(true)
165 .truncate(true)
166 .open(stdout_path)
167 .map_err(|error| ProcessError::Spawn(format!("open stdout capture: {error}")))?;
168 let stderr = OpenOptions::new()
169 .write(true)
170 .truncate(true)
171 .open(stderr_path)
172 .map_err(|error| ProcessError::Spawn(format!("open stderr capture: {error}")))?;
173 command.stdout(Stdio::from(stdout));
174 command.stderr(Stdio::from(stderr));
175 }
176 }
177 command.stdin(match (&spec.output_capture, spec.use_stdin) {
178 (OutputCapture::Inherit, true) => Stdio::inherit(),
179 (_, true) => Stdio::piped(),
180 (_, false) => Stdio::null(),
181 });
182
183 Ok((command, cleanup_token))
184}
185
186fn log_spawn_context(command: &Command, env_mode: EnvMode) {
190 let program = command.get_program().to_string_lossy();
191 let cwd = command
192 .get_current_dir()
193 .map(std::path::Path::to_path_buf)
194 .or_else(|| std::env::current_dir().ok());
195 let path = resolved_env_value(command, "PATH", env_mode)
196 .map(|value| value.to_string_lossy().into_owned());
197 tracing::debug!(
198 target: "harn_hostlib::process",
199 shell_or_program = %program,
200 cwd = %cwd.as_deref().map_or_else(|| "<unresolved>".into(), std::path::Path::to_string_lossy),
201 path = %path.as_deref().unwrap_or("<unset>"),
202 env_mode = ?env_mode,
203 "resolved command spawn context"
204 );
205}
206
207fn resolved_env_value(
208 command: &Command,
209 name: &str,
210 env_mode: EnvMode,
211) -> Option<std::ffi::OsString> {
212 for (key, value) in command.get_envs() {
213 if env_key_eq(key, name) {
214 return value.map(std::ffi::OsStr::to_os_string);
215 }
216 }
217 if env_mode == EnvMode::Replace {
218 None
219 } else {
220 std::env::var_os(name)
221 }
222}
223
224fn env_key_eq(key: &std::ffi::OsStr, expected: &str) -> bool {
225 #[cfg(windows)]
226 {
227 key.to_string_lossy().eq_ignore_ascii_case(expected)
228 }
229 #[cfg(not(windows))]
230 {
231 key == expected
232 }
233}
234
235fn map_spawn_error(error: io::Error) -> ProcessError {
236 if let Some(violation) = process_sandbox::process_spawn_error(&error) {
237 return ProcessError::SandboxSpawn(format!("{violation:?}"));
238 }
239 ProcessError::Spawn(error.to_string())
240}
241
242#[cfg(unix)]
245pub fn replace_current_process(spec: SpawnSpec) -> Result<std::convert::Infallible, ProcessError> {
246 use std::os::unix::process::CommandExt;
247
248 super::handle::validate_process_spec(&spec)?;
249 let inherited_cleanup_token = std::env::var(harn_vm::op_interrupt::PROCESS_CLEANUP_TOKEN_ENV)
250 .ok()
251 .filter(|token| !token.is_empty());
252 let (mut command, _cleanup_token) = prepare_command(&spec, inherited_cleanup_token)?;
253 Err(map_spawn_error(command.exec()))
254}
255
256struct RealProcess {
257 pid: u32,
258 pgid: Option<u32>,
259 cleanup_token: String,
260 killer: Arc<dyn ProcessKiller>,
261 child: Option<Child>,
262 stdin: Option<ChildStdin>,
263 stdout: Option<ChildStdout>,
264 stderr: Option<ChildStderr>,
265 stdin_taken: bool,
266 stdout_taken: bool,
267 stderr_taken: bool,
268}
269
270impl RealProcess {
271 fn ensure_pipes_taken(&mut self) {
272 if let Some(child) = self.child.as_mut() {
273 if self.stdin.is_none() && !self.stdin_taken {
274 self.stdin = child.stdin.take();
275 }
276 if self.stdout.is_none() && !self.stdout_taken {
277 self.stdout = child.stdout.take();
278 }
279 if self.stderr.is_none() && !self.stderr_taken {
280 self.stderr = child.stderr.take();
281 }
282 }
283 }
284}
285
286impl ProcessHandle for RealProcess {
287 fn pid(&self) -> Option<u32> {
288 Some(self.pid)
289 }
290
291 fn process_group_id(&self) -> Option<u32> {
292 self.pgid
293 }
294
295 fn killer(&self) -> Arc<dyn ProcessKiller> {
296 Arc::clone(&self.killer)
297 }
298
299 fn take_stdin(&mut self) -> Option<Box<dyn Write + Send>> {
300 self.ensure_pipes_taken();
301 self.stdin_taken = true;
302 self.stdin
303 .take()
304 .map(|s| Box::new(s) as Box<dyn Write + Send>)
305 }
306
307 fn take_stdout(&mut self) -> Option<Box<dyn Read + Send>> {
308 self.ensure_pipes_taken();
309 self.stdout_taken = true;
310 self.stdout
311 .take()
312 .map(|s| Box::new(s) as Box<dyn Read + Send>)
313 }
314
315 fn take_stderr(&mut self) -> Option<Box<dyn Read + Send>> {
316 self.ensure_pipes_taken();
317 self.stderr_taken = true;
318 self.stderr
319 .take()
320 .map(|s| Box::new(s) as Box<dyn Read + Send>)
321 }
322
323 fn wait_with_timeout(
324 &mut self,
325 timeout: Option<Duration>,
326 interrupt: &dyn Fn() -> bool,
327 ) -> io::Result<WaitOutcome> {
328 let killer = Arc::clone(&self.killer);
329 let Some(child) = self.child.as_mut() else {
330 return Err(io::Error::other("child already reaped"));
331 };
332 let deadline = timeout.map(|timeout| Instant::now() + timeout);
333 loop {
334 match child.try_wait()? {
335 Some(status) => return Ok(WaitOutcome::Exited(decode_status(status))),
336 None => {
337 if interrupt() {
338 let (_, report) =
342 harn_vm::op_interrupt::terminate_child_group_with_cleanup_token_report(
343 child,
344 Some(&self.cleanup_token),
345 );
346 return Ok(WaitOutcome::Interrupted(report));
347 }
348 if deadline.is_some_and(|deadline| Instant::now() >= deadline) {
349 let mut report = killer.kill();
356 let _ = child.kill();
357 let _ = child.wait();
358 report.refresh_survivor_status();
359 return Ok(WaitOutcome::TimedOut(report));
360 }
361 let sleep = deadline
362 .map(|deadline| deadline.saturating_duration_since(Instant::now()))
363 .unwrap_or(Duration::MAX)
364 .min(Duration::from_millis(20));
365 thread::sleep(sleep);
366 }
367 }
368 }
369 }
370
371 fn wait(&mut self) -> io::Result<ExitStatus> {
372 let child = self
373 .child
374 .as_mut()
375 .ok_or_else(|| io::Error::other("child already reaped"))?;
376 let status = child.wait()?;
377 Ok(decode_status(status))
378 }
379}
380
381struct RealKiller {
382 pid: u32,
383 cleanup_token: String,
384}
385
386impl ProcessKiller for RealKiller {
387 fn kill(&self) -> ProcessCleanupReport {
388 let report = harn_vm::op_interrupt::signal_pid_tree_group_and_token_with_report(
389 self.pid,
390 Some(&self.cleanup_token),
391 9,
392 );
393 #[cfg(target_os = "windows")]
394 terminate_process(self.pid);
395 report
396 }
397}
398
399#[cfg(target_os = "windows")]
400fn terminate_process(pid: u32) {
401 use windows_sys::Win32::Foundation::CloseHandle;
402 use windows_sys::Win32::System::Threading::{OpenProcess, TerminateProcess, PROCESS_TERMINATE};
403
404 let handle = unsafe { OpenProcess(PROCESS_TERMINATE, 0, pid) };
405 if handle.is_null() {
406 return;
407 }
408 unsafe {
409 TerminateProcess(handle, 1);
410 CloseHandle(handle);
411 }
412}
413
414#[cfg(unix)]
415fn decode_status(status: std::process::ExitStatus) -> ExitStatus {
416 use std::os::unix::process::ExitStatusExt;
417 if let Some(code) = status.code() {
418 ExitStatus::from_code(code)
419 } else if let Some(sig) = status.signal() {
420 ExitStatus::from_signal(sig)
421 } else {
422 ExitStatus {
423 code: None,
424 signal: None,
425 }
426 }
427}
428
429#[cfg(not(unix))]
430fn decode_status(status: std::process::ExitStatus) -> ExitStatus {
431 ExitStatus::from_code(status.code().unwrap_or(-1))
432}
433
434pub(crate) fn child_process_group_id(pid: u32) -> Option<u32> {
435 #[cfg(unix)]
436 {
437 extern "C" {
438 fn getpgid(pid: i32) -> i32;
439 }
440 let pgid = unsafe { getpgid(pid as i32) };
441 if pgid > 0 {
442 Some(pgid as u32)
443 } else {
444 None
445 }
446 }
447 #[cfg(not(unix))]
448 {
449 Some(pid)
450 }
451}
452
453pub(crate) fn configure_background_process_group(command: &mut std::process::Command) {
454 #[cfg(unix)]
455 unsafe {
456 use std::os::unix::process::CommandExt;
457 command.pre_exec(|| {
458 extern "C" {
459 fn setpgid(pid: i32, pgid: i32) -> i32;
460 }
461 if setpgid(0, 0) == -1 {
462 return Err(std::io::Error::last_os_error());
463 }
464 Ok(())
465 });
466 }
467 #[cfg(not(unix))]
468 {
469 let _ = command;
470 }
471}
472
473#[cfg(test)]
474mod tests {
475 use super::*;
476
477 #[test]
478 fn resolved_path_prefers_the_child_override() {
479 let mut command = Command::new("shell");
480 command.env("PATH", "/resolved/toolchain/bin");
481
482 assert_eq!(
483 resolved_env_value(&command, "PATH", EnvMode::Patch),
484 Some(std::ffi::OsString::from("/resolved/toolchain/bin"))
485 );
486 }
487
488 #[test]
489 fn resolved_path_honors_an_explicit_removal() {
490 let mut command = Command::new("shell");
491 command.env_remove("PATH");
492
493 assert_eq!(resolved_env_value(&command, "PATH", EnvMode::Patch), None);
494 }
495
496 #[test]
497 fn replace_mode_does_not_report_an_inherited_path() {
498 let command = Command::new("shell");
499
500 assert_eq!(resolved_env_value(&command, "PATH", EnvMode::Replace), None);
501 }
502}