1use anyhow::Result;
2#[cfg(windows)]
3use std::os::windows::io::OwnedHandle;
4#[allow(clippy::disallowed_types, clippy::disallowed_methods)]
5use std::process::{Child, ExitStatus};
6use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
7use std::sync::{Arc, Mutex};
8
9use crate::contract::BackgroundHandle;
10
11#[allow(clippy::disallowed_types, clippy::disallowed_methods)]
15struct ChildInner {
16 child: Option<Child>,
17 io_threads: Vec<std::thread::JoinHandle<()>>,
18 reaped: bool,
19 exit_status: Option<ExitStatus>,
20 killed: AtomicBool,
21}
22
23#[derive(Clone)]
24#[allow(clippy::disallowed_types, clippy::disallowed_methods)]
25pub struct ChildHandle {
26 inner: Arc<Mutex<ChildInner>>,
27 pid: Arc<AtomicU32>,
30 #[cfg(windows)]
32 job: Arc<OwnedHandle>,
33}
34
35impl ChildHandle {
36 #[allow(clippy::disallowed_types, clippy::disallowed_methods)]
37 pub(crate) fn new(
38 child: Child,
39 stdin_thread: Option<std::thread::JoinHandle<()>>,
40 io_threads: Vec<std::thread::JoinHandle<()>>,
41 ) -> Result<Self> {
42 let _ = stdin_thread;
51 let pid = child.id();
52 #[cfg(windows)]
53 let job = match assign_job(&child) {
54 Ok(job) => Arc::new(job),
55 Err(err) => {
56 let mut child = child;
59 let _ = child.kill();
60 return Err(err);
61 }
62 };
63 Ok(Self {
64 inner: Arc::new(Mutex::new(ChildInner {
65 child: Some(child),
66 io_threads,
67 reaped: false,
68 exit_status: None,
69 killed: AtomicBool::new(false),
70 })),
71 pid: Arc::new(AtomicU32::new(pid)),
72 #[cfg(windows)]
73 job,
74 })
75 }
76}
77
78impl BackgroundHandle for ChildHandle {
79 fn try_wait(&mut self) -> Result<Option<ExitStatus>> {
80 let mut guard = self.inner.lock().unwrap_or_else(|e| e.into_inner());
81 if let Some(ref mut child) = guard.child {
82 match child.try_wait()? {
83 Some(status) => {
84 #[cfg(unix)]
88 if guard.killed.load(Ordering::SeqCst) {
89 sweep_process_group(self.pid.load(Ordering::SeqCst));
90 }
91 guard.reaped = true;
92 guard.exit_status = Some(status);
93 self.pid.store(0, Ordering::SeqCst);
95 for thread in guard.io_threads.drain(..) {
99 let _ = thread.join();
100 }
101 guard.child = None;
102 Ok(Some(status))
103 }
104 None => Ok(None),
105 }
106 } else if guard.reaped {
107 Ok(Some(
109 guard
110 .exit_status
111 .unwrap_or_else(|| exit_status_from_code(0)),
112 ))
113 } else {
114 Ok(None)
116 }
117 }
118
119 fn wait(&mut self) -> Result<ExitStatus> {
120 let child_opt = {
123 let mut guard = self.inner.lock().unwrap_or_else(|e| e.into_inner());
124 guard.child.take()
125 };
126
127 if let Some(mut child) = child_opt {
128 let status = child.wait()?;
129 let mut guard = self.inner.lock().unwrap_or_else(|e| e.into_inner());
133 #[cfg(unix)]
140 if guard.killed.load(Ordering::SeqCst) {
141 sweep_process_group(self.pid.load(Ordering::SeqCst));
142 }
143 self.pid.store(0, Ordering::SeqCst);
145 for thread in guard.io_threads.drain(..) {
146 let _ = thread.join();
147 }
148 guard.reaped = true;
149 guard.exit_status = Some(status);
150 Ok(status)
151 } else {
152 let guard = self.inner.lock().unwrap_or_else(|e| e.into_inner());
154 Ok(guard
155 .exit_status
156 .unwrap_or_else(|| exit_status_from_code(0)))
157 }
158 }
159
160 fn kill(&mut self) -> Result<()> {
161 let pid = self.pid.load(Ordering::SeqCst);
162 if pid == 0 {
163 return Ok(());
164 }
165 self.inner
169 .lock()
170 .unwrap_or_else(|e| e.into_inner())
171 .killed
172 .store(true, Ordering::SeqCst);
173 #[cfg(unix)]
174 kill_tree(pid);
175 #[cfg(windows)]
176 terminate_job(self.job.as_ref());
177 Ok(())
178 }
179}
180
181#[cfg(unix)]
187fn kill_tree(pid: u32) {
188 let group = -(pid as i32);
190 let rc = unsafe { libc::kill(group, libc::SIGKILL) };
191 if rc != 0 && std::io::Error::last_os_error().raw_os_error() != Some(libc::ESRCH) {
192 unsafe {
193 libc::kill(pid as i32, libc::SIGKILL);
194 }
195 }
196}
197
198#[cfg(windows)]
207#[allow(clippy::disallowed_types)]
208fn assign_job(child: &Child) -> Result<OwnedHandle> {
209 use std::os::windows::io::{AsRawHandle, FromRawHandle};
210 use windows_sys::Win32::System::JobObjects::{AssignProcessToJobObject, CreateJobObjectW};
211
212 let raw = unsafe { CreateJobObjectW(std::ptr::null(), std::ptr::null()) };
213 if raw.is_null() {
214 return Err(
215 anyhow::Error::new(std::io::Error::last_os_error()).context("CreateJobObjectW failed")
216 );
217 }
218 let job = unsafe { OwnedHandle::from_raw_handle(raw) };
219 if unsafe { AssignProcessToJobObject(job.as_raw_handle(), child.as_raw_handle()) } == 0 {
220 return Err(anyhow::Error::new(std::io::Error::last_os_error())
221 .context("AssignProcessToJobObject failed"));
222 }
223 Ok(job)
224}
225
226#[cfg(windows)]
231fn terminate_job(job: &OwnedHandle) {
232 use std::os::windows::io::AsRawHandle;
233 use windows_sys::Win32::System::JobObjects::TerminateJobObject;
234
235 unsafe {
236 TerminateJobObject(job.as_raw_handle(), 1);
237 }
238}
239
240#[cfg(unix)]
250fn sweep_process_group(pid: u32) {
251 if pid == 0 {
252 return;
253 }
254 let group = -(pid as i32);
255 if unsafe { libc::kill(group, 0) } != 0 {
256 return;
257 }
258 unsafe {
259 libc::kill(group, libc::SIGKILL);
260 }
261}
262
263impl Drop for ChildHandle {
264 fn drop(&mut self) {
265 if Arc::strong_count(&self.inner) > 1 {
267 return;
268 }
269 let mut guard = self.inner.lock().unwrap_or_else(|e| e.into_inner());
270 if guard.reaped {
271 return;
272 }
273 let running = guard
274 .child
275 .as_mut()
276 .is_some_and(|child| matches!(child.try_wait(), Ok(None)));
277 if running {
278 guard.killed.store(true, Ordering::SeqCst);
283 #[cfg(unix)]
284 kill_tree(self.pid.load(Ordering::SeqCst));
285 #[cfg(windows)]
286 terminate_job(self.job.as_ref());
287 if let Some(child) = guard.child.as_mut() {
288 let _ = child.wait();
289 }
290 }
291 #[cfg(unix)]
295 if guard.killed.load(Ordering::SeqCst) {
296 sweep_process_group(self.pid.load(Ordering::SeqCst));
297 }
298 guard.reaped = true;
299 }
303}
304
305fn exit_status_from_code(code: i32) -> ExitStatus {
307 #[cfg(unix)]
308 {
309 use std::os::unix::process::ExitStatusExt;
310 ExitStatus::from_raw(code << 8)
311 }
312 #[cfg(windows)]
313 {
314 use std::os::windows::process::ExitStatusExt;
315 ExitStatus::from_raw(code as u32)
316 }
317}
318
319#[cfg(all(test, unix))]
320mod tests {
321 use super::sweep_process_group;
322 use std::os::unix::process::CommandExt;
323 use std::time::{Duration, Instant};
324
325 #[cfg_attr(miri, ignore = "spawns a real child process, unsupported under Miri")]
330 #[test]
331 fn sweep_process_group_kills_escapee_that_outlives_the_leader() {
332 #[allow(clippy::disallowed_types, clippy::disallowed_methods)]
333 let mut leader = std::process::Command::new("sh")
334 .arg("-c")
335 .arg("sleep 30 & echo started; wait")
340 .process_group(0)
341 .stdout(std::process::Stdio::piped())
342 .spawn()
343 .expect("spawn leader");
344 let pid = leader.id();
345 {
346 use std::io::BufRead;
347 let mut line = String::new();
348 let stdout = leader.stdout.as_mut().expect("leader stdout");
349 std::io::BufReader::new(stdout)
350 .read_line(&mut line)
351 .expect("read readiness line");
352 assert_eq!(line.trim(), "started");
353 }
354 unsafe {
358 libc::kill(pid as i32, libc::SIGKILL);
359 }
360 let _ = leader.wait();
361 assert_eq!(
362 unsafe { libc::kill(-(pid as i32), 0) },
363 0,
364 "orphaned sleeper should keep the group alive"
365 );
366 sweep_process_group(pid);
367 let deadline = Instant::now() + Duration::from_secs(5);
368 while unsafe { libc::kill(-(pid as i32), 0) } == 0 && Instant::now() < deadline {
369 std::thread::sleep(Duration::from_millis(10));
370 }
371 assert_eq!(
372 unsafe { libc::kill(-(pid as i32), 0) },
373 -1,
374 "sweep must end the escapee's process group"
375 );
376 }
377}
378
379#[cfg(all(test, windows))]
380mod windows_tests {
381 use super::ChildHandle;
382 use crate::CommandBuilder;
383 use crate::contract::BackgroundHandle;
384 use std::os::windows::io::AsRawHandle;
385 use std::time::{Duration, Instant};
386 use windows_sys::Win32::System::JobObjects::{
387 JOBOBJECT_BASIC_ACCOUNTING_INFORMATION, JobObjectBasicAccountingInformation,
388 QueryInformationJobObject,
389 };
390
391 fn active_processes(handle: &ChildHandle) -> u32 {
392 let mut info = JOBOBJECT_BASIC_ACCOUNTING_INFORMATION::default();
393 let ok = unsafe {
394 QueryInformationJobObject(
395 handle.job.as_raw_handle(),
396 JobObjectBasicAccountingInformation,
397 &mut info as *mut _ as *mut _,
398 std::mem::size_of::<JOBOBJECT_BASIC_ACCOUNTING_INFORMATION>() as u32,
399 std::ptr::null_mut(),
400 )
401 };
402 assert_ne!(
403 ok,
404 0,
405 "QueryInformationJobObject failed: {}",
406 std::io::Error::last_os_error()
407 );
408 info.ActiveProcesses
409 }
410
411 #[cfg_attr(miri, ignore = "spawns a real child process, unsupported under Miri")]
417 #[test]
418 fn kill_terminates_grandchild_that_outlives_the_leader() {
419 let mut handle = CommandBuilder::new("cmd")
420 .args(["/c", "start /b ping -n 30 127.0.0.1 & ping -n 30 127.0.0.1"])
421 .spawn()
422 .expect("spawn");
423 let deadline = Instant::now() + Duration::from_secs(5);
424 while active_processes(&handle) < 2 && Instant::now() < deadline {
425 std::thread::sleep(Duration::from_millis(50));
426 }
427 assert!(
428 active_processes(&handle) >= 2,
429 "leader and grandchild should both be in the job"
430 );
431 handle.kill().expect("kill");
432 handle.wait().expect("wait");
433 let deadline = Instant::now() + Duration::from_secs(5);
434 while active_processes(&handle) != 0 && Instant::now() < deadline {
435 std::thread::sleep(Duration::from_millis(50));
436 }
437 assert_eq!(
438 active_processes(&handle),
439 0,
440 "job kill must terminate the grandchild too"
441 );
442 }
443}