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;
10use crate::diagnostics as proc_diag;
11use oxdock_diagnostics::DiagnosticResult;
12
13#[allow(clippy::disallowed_types, clippy::disallowed_methods)]
17struct ChildInner {
18 child: Option<Child>,
19 io_threads: Vec<std::thread::JoinHandle<()>>,
20 reaped: bool,
21 exit_status: Option<ExitStatus>,
22 killed: AtomicBool,
23}
24
25#[derive(Clone)]
26#[allow(clippy::disallowed_types, clippy::disallowed_methods)]
27pub struct ChildHandle {
28 inner: Arc<Mutex<ChildInner>>,
29 pid: Arc<AtomicU32>,
32 #[cfg(windows)]
34 job: Arc<OwnedHandle>,
35}
36
37impl ChildHandle {
38 #[allow(clippy::disallowed_types, clippy::disallowed_methods)]
39 pub(crate) fn new(
40 child: Child,
41 stdin_thread: Option<std::thread::JoinHandle<()>>,
42 io_threads: Vec<std::thread::JoinHandle<()>>,
43 ) -> DiagnosticResult<Self> {
44 let _ = stdin_thread;
53 let pid = child.id();
54 #[cfg(windows)]
55 let job = match assign_job(&child) {
56 Ok(job) => Arc::new(job),
57 Err(err) => {
58 let mut child = child;
61 let _ = child.kill();
62 return Err(proc_diag::from_anyhow(err));
63 }
64 };
65 Ok(Self {
66 inner: Arc::new(Mutex::new(ChildInner {
67 child: Some(child),
68 io_threads,
69 reaped: false,
70 exit_status: None,
71 killed: AtomicBool::new(false),
72 })),
73 pid: Arc::new(AtomicU32::new(pid)),
74 #[cfg(windows)]
75 job,
76 })
77 }
78}
79
80impl BackgroundHandle for ChildHandle {
81 fn try_wait(&mut self) -> Result<Option<ExitStatus>> {
82 let mut guard = self.inner.lock().unwrap_or_else(|e| e.into_inner());
83 if let Some(ref mut child) = guard.child {
84 match child
85 .try_wait()
86 .map_err(|e| anyhow::Error::new(proc_diag::wait_failed(&e)))?
87 {
88 Some(status) => {
89 #[cfg(unix)]
93 if guard.killed.load(Ordering::SeqCst) {
94 sweep_process_group(self.pid.load(Ordering::SeqCst));
95 }
96 guard.reaped = true;
97 guard.exit_status = Some(status);
98 self.pid.store(0, Ordering::SeqCst);
100 for thread in guard.io_threads.drain(..) {
104 let _ = thread.join();
105 }
106 guard.child = None;
107 Ok(Some(status))
108 }
109 None => Ok(None),
110 }
111 } else if guard.reaped {
112 Ok(Some(
114 guard
115 .exit_status
116 .unwrap_or_else(|| exit_status_from_code(0)),
117 ))
118 } else {
119 Ok(None)
121 }
122 }
123
124 fn wait(&mut self) -> Result<ExitStatus> {
125 let child_opt = {
128 let mut guard = self.inner.lock().unwrap_or_else(|e| e.into_inner());
129 guard.child.take()
130 };
131
132 if let Some(mut child) = child_opt {
133 let status = child
134 .wait()
135 .map_err(|e| anyhow::Error::new(proc_diag::wait_failed(&e)))?;
136 let mut guard = self.inner.lock().unwrap_or_else(|e| e.into_inner());
140 #[cfg(unix)]
147 if guard.killed.load(Ordering::SeqCst) {
148 sweep_process_group(self.pid.load(Ordering::SeqCst));
149 }
150 self.pid.store(0, Ordering::SeqCst);
152 for thread in guard.io_threads.drain(..) {
153 let _ = thread.join();
154 }
155 guard.reaped = true;
156 guard.exit_status = Some(status);
157 Ok(status)
158 } else {
159 let guard = self.inner.lock().unwrap_or_else(|e| e.into_inner());
161 Ok(guard
162 .exit_status
163 .unwrap_or_else(|| exit_status_from_code(0)))
164 }
165 }
166
167 fn kill(&mut self) -> Result<()> {
168 let pid = self.pid.load(Ordering::SeqCst);
169 if pid == 0 {
170 return Ok(());
171 }
172 self.inner
176 .lock()
177 .unwrap_or_else(|e| e.into_inner())
178 .killed
179 .store(true, Ordering::SeqCst);
180 #[cfg(unix)]
181 kill_tree(pid);
182 #[cfg(windows)]
183 terminate_job(self.job.as_ref());
184 Ok(())
185 }
186}
187
188#[cfg(unix)]
194fn kill_tree(pid: u32) {
195 let group = -(pid as i32);
197 let rc = unsafe { libc::kill(group, libc::SIGKILL) };
198 if rc != 0 && std::io::Error::last_os_error().raw_os_error() != Some(libc::ESRCH) {
199 unsafe {
200 libc::kill(pid as i32, libc::SIGKILL);
201 }
202 }
203}
204
205#[cfg(windows)]
214#[allow(clippy::disallowed_types)]
215fn assign_job(child: &Child) -> Result<OwnedHandle> {
216 use std::os::windows::io::{AsRawHandle, FromRawHandle};
217 use windows_sys::Win32::System::JobObjects::{AssignProcessToJobObject, CreateJobObjectW};
218
219 let raw = unsafe { CreateJobObjectW(std::ptr::null(), std::ptr::null()) };
220 if raw.is_null() {
221 return Err(
222 anyhow::Error::new(std::io::Error::last_os_error()).context("CreateJobObjectW failed")
223 );
224 }
225 let job = unsafe { OwnedHandle::from_raw_handle(raw) };
226 if unsafe { AssignProcessToJobObject(job.as_raw_handle(), child.as_raw_handle()) } == 0 {
227 return Err(anyhow::Error::new(std::io::Error::last_os_error())
228 .context("AssignProcessToJobObject failed"));
229 }
230 Ok(job)
231}
232
233#[cfg(windows)]
238fn terminate_job(job: &OwnedHandle) {
239 use std::os::windows::io::AsRawHandle;
240 use windows_sys::Win32::System::JobObjects::TerminateJobObject;
241
242 unsafe {
243 TerminateJobObject(job.as_raw_handle(), 1);
244 }
245}
246
247#[cfg(unix)]
257fn sweep_process_group(pid: u32) {
258 if pid == 0 {
259 return;
260 }
261 let group = -(pid as i32);
262 if unsafe { libc::kill(group, 0) } != 0 {
263 return;
264 }
265 unsafe {
266 libc::kill(group, libc::SIGKILL);
267 }
268}
269
270impl Drop for ChildHandle {
271 fn drop(&mut self) {
272 if Arc::strong_count(&self.inner) > 1 {
274 return;
275 }
276 let mut guard = self.inner.lock().unwrap_or_else(|e| e.into_inner());
277 if guard.reaped {
278 return;
279 }
280 let running = guard
281 .child
282 .as_mut()
283 .is_some_and(|child| matches!(child.try_wait(), Ok(None)));
284 if running {
285 guard.killed.store(true, Ordering::SeqCst);
290 #[cfg(unix)]
291 kill_tree(self.pid.load(Ordering::SeqCst));
292 #[cfg(windows)]
293 terminate_job(self.job.as_ref());
294 if let Some(child) = guard.child.as_mut() {
295 let _ = child.wait();
296 }
297 }
298 #[cfg(unix)]
302 if guard.killed.load(Ordering::SeqCst) {
303 sweep_process_group(self.pid.load(Ordering::SeqCst));
304 }
305 guard.reaped = true;
306 }
310}
311
312fn exit_status_from_code(code: i32) -> ExitStatus {
314 #[cfg(unix)]
315 {
316 use std::os::unix::process::ExitStatusExt;
317 ExitStatus::from_raw(code << 8)
318 }
319 #[cfg(windows)]
320 {
321 use std::os::windows::process::ExitStatusExt;
322 ExitStatus::from_raw(code as u32)
323 }
324}
325
326#[cfg(all(test, unix))]
327mod tests {
328 use super::sweep_process_group;
329 use std::os::unix::process::CommandExt;
330 use std::time::{Duration, Instant};
331
332 #[cfg_attr(miri, ignore = "spawns a real child process, unsupported under Miri")]
337 #[test]
338 fn sweep_process_group_kills_escapee_that_outlives_the_leader() {
339 #[allow(clippy::disallowed_types, clippy::disallowed_methods)]
340 let mut leader = std::process::Command::new("sh")
341 .arg("-c")
342 .arg("sleep 30 & echo started; wait")
347 .process_group(0)
348 .stdout(std::process::Stdio::piped())
349 .spawn()
350 .expect("spawn leader");
351 let pid = leader.id();
352 {
353 use std::io::BufRead;
354 let mut line = String::new();
355 let stdout = leader.stdout.as_mut().expect("leader stdout");
356 std::io::BufReader::new(stdout)
357 .read_line(&mut line)
358 .expect("read readiness line");
359 assert_eq!(line.trim(), "started");
360 }
361 unsafe {
365 libc::kill(pid as i32, libc::SIGKILL);
366 }
367 let _ = leader.wait();
368 assert_eq!(
369 unsafe { libc::kill(-(pid as i32), 0) },
370 0,
371 "orphaned sleeper should keep the group alive"
372 );
373 sweep_process_group(pid);
374 let deadline = Instant::now() + Duration::from_secs(5);
375 while unsafe { libc::kill(-(pid as i32), 0) } == 0 && Instant::now() < deadline {
376 std::thread::sleep(Duration::from_millis(10));
377 }
378 assert_eq!(
379 unsafe { libc::kill(-(pid as i32), 0) },
380 -1,
381 "sweep must end the escapee's process group"
382 );
383 }
384}
385
386#[cfg(all(test, windows))]
387mod windows_tests {
388 use super::ChildHandle;
389 use crate::CommandBuilder;
390 use crate::contract::BackgroundHandle;
391 use std::os::windows::io::AsRawHandle;
392 use std::time::{Duration, Instant};
393 use windows_sys::Win32::System::JobObjects::{
394 JOBOBJECT_BASIC_ACCOUNTING_INFORMATION, JobObjectBasicAccountingInformation,
395 QueryInformationJobObject,
396 };
397
398 fn active_processes(handle: &ChildHandle) -> u32 {
399 let mut info = JOBOBJECT_BASIC_ACCOUNTING_INFORMATION::default();
400 let ok = unsafe {
401 QueryInformationJobObject(
402 handle.job.as_raw_handle(),
403 JobObjectBasicAccountingInformation,
404 &mut info as *mut _ as *mut _,
405 std::mem::size_of::<JOBOBJECT_BASIC_ACCOUNTING_INFORMATION>() as u32,
406 std::ptr::null_mut(),
407 )
408 };
409 assert_ne!(
410 ok,
411 0,
412 "QueryInformationJobObject failed: {}",
413 std::io::Error::last_os_error()
414 );
415 info.ActiveProcesses
416 }
417
418 #[cfg_attr(miri, ignore = "spawns a real child process, unsupported under Miri")]
424 #[test]
425 fn kill_terminates_grandchild_that_outlives_the_leader() {
426 let mut handle = CommandBuilder::new("cmd")
427 .args(["/c", "start /b ping -n 30 127.0.0.1 & ping -n 30 127.0.0.1"])
428 .spawn()
429 .expect("spawn");
430 let deadline = Instant::now() + Duration::from_secs(5);
431 while active_processes(&handle) < 2 && Instant::now() < deadline {
432 std::thread::sleep(Duration::from_millis(50));
433 }
434 assert!(
435 active_processes(&handle) >= 2,
436 "leader and grandchild should both be in the job"
437 );
438 handle.kill().expect("kill");
439 handle.wait().expect("wait");
440 let deadline = Instant::now() + Duration::from_secs(5);
441 while active_processes(&handle) != 0 && Instant::now() < deadline {
442 std::thread::sleep(Duration::from_millis(50));
443 }
444 assert_eq!(
445 active_processes(&handle),
446 0,
447 "job kill must terminate the grandchild too"
448 );
449 }
450}