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