1use std::io;
4use std::process::ExitStatus;
5use std::time::{Duration, Instant};
6
7const CLEANUP_GRACE: Duration = Duration::from_secs(1);
8const REAP_RETRY_GRACE: Duration = Duration::from_millis(100);
9const CLEANUP_POLL_INTERVAL: Duration = Duration::from_millis(10);
10const MANAGED_PROCESS_TREE_ENV: &str = "FALLOW_MANAGED_PROCESS_TREE";
11
12#[cfg(feature = "tokio")]
14pub fn configure_tokio_command(command: &mut tokio::process::Command) {
15 configure_std_command(command.as_std_mut());
16}
17
18pub fn configure_std_command(command: &mut std::process::Command) {
20 command.env(MANAGED_PROCESS_TREE_ENV, "1");
21
22 #[cfg(unix)]
23 {
24 use std::os::unix::process::CommandExt;
25
26 command.process_group(0);
27 }
28
29 #[cfg(windows)]
30 {
31 use std::os::windows::process::CommandExt;
32
33 use windows_sys::Win32::System::Threading::CREATE_SUSPENDED;
34
35 command.creation_flags(CREATE_SUSPENDED);
36 }
37
38 #[cfg(not(any(unix, windows)))]
39 let _ = command;
40}
41
42pub fn inherits_managed_process_tree() -> bool {
49 std::env::var_os(MANAGED_PROCESS_TREE_ENV).is_some_and(|value| value == "1")
50}
51
52#[cfg(windows)]
53struct WindowsHandle(isize);
54
55#[cfg(windows)]
56impl WindowsHandle {
57 fn raw(&self) -> windows_sys::Win32::Foundation::HANDLE {
58 self.0 as _
59 }
60}
61
62#[cfg(windows)]
63#[expect(unsafe_code, reason = "owned Windows handles require CloseHandle")]
64impl Drop for WindowsHandle {
65 fn drop(&mut self) {
66 use windows_sys::Win32::Foundation::CloseHandle;
67
68 unsafe { CloseHandle(self.raw()) };
70 }
71}
72
73#[cfg(windows)]
74struct WindowsJobGuard {
75 job: Option<WindowsHandle>,
76}
77
78#[cfg(windows)]
79impl WindowsJobGuard {
80 fn new(job: WindowsHandle) -> Self {
81 Self { job: Some(job) }
82 }
83
84 fn raw(&self) -> io::Result<windows_sys::Win32::Foundation::HANDLE> {
85 self.job
86 .as_ref()
87 .map(WindowsHandle::raw)
88 .ok_or_else(|| io::Error::other("Windows Job Object guard is disarmed"))
89 }
90
91 fn disarm(mut self) -> io::Result<WindowsHandle> {
92 self.job
93 .take()
94 .ok_or_else(|| io::Error::other("Windows Job Object guard is already disarmed"))
95 }
96}
97
98#[cfg(windows)]
99#[expect(
100 unsafe_code,
101 reason = "armed Windows Job Object cleanup requires TerminateJobObject"
102)]
103impl Drop for WindowsJobGuard {
104 fn drop(&mut self) {
105 use windows_sys::Win32::System::JobObjects::TerminateJobObject;
106
107 let Some(job) = self.job.as_ref() else {
108 return;
109 };
110 unsafe { TerminateJobObject(job.raw(), 1) };
113 }
114}
115
116pub struct ProcessTree {
118 #[cfg(unix)]
119 process_group_id: i32,
120 #[cfg(all(unix, target_vendor = "apple"))]
121 leader_exit_observed: std::sync::atomic::AtomicBool,
122 #[cfg(windows)]
123 job: WindowsHandle,
124}
125
126impl ProcessTree {
127 #[cfg(all(feature = "tokio", unix))]
129 pub fn for_tokio_child(child: &tokio::process::Child) -> io::Result<Self> {
130 let pid = child
131 .id()
132 .ok_or_else(|| io::Error::other("fallow subprocess exited before setup"))?;
133 Self::for_pid(pid)
134 }
135
136 #[cfg(all(feature = "tokio", windows))]
138 pub fn for_tokio_child(child: &tokio::process::Child) -> io::Result<Self> {
139 let pid = child
140 .id()
141 .ok_or_else(|| io::Error::other("fallow subprocess exited before setup"))?;
142 let handle = child
143 .raw_handle()
144 .ok_or_else(|| io::Error::other("fallow subprocess exited before setup"))?;
145 Self::for_windows_handle(handle, pid)
146 }
147
148 #[cfg(all(feature = "tokio", not(any(unix, windows))))]
150 pub fn for_tokio_child(_child: &tokio::process::Child) -> io::Result<Self> {
151 Ok(Self {})
152 }
153
154 #[cfg(unix)]
157 pub fn for_std_child(child: &std::process::Child) -> io::Result<Self> {
158 Self::for_pid(child.id())
159 }
160
161 #[cfg(windows)]
164 pub fn for_std_child(child: &std::process::Child) -> io::Result<Self> {
165 use std::os::windows::io::AsRawHandle;
166
167 Self::for_windows_handle(child.as_raw_handle(), child.id())
168 }
169
170 #[cfg(not(any(unix, windows)))]
173 pub fn for_std_child(_child: &std::process::Child) -> io::Result<Self> {
174 Ok(Self {})
175 }
176
177 #[cfg(unix)]
178 pub(crate) fn for_pid(pid: u32) -> io::Result<Self> {
179 let process_group_id = i32::try_from(pid)
180 .map_err(|_| io::Error::other(format!("invalid fallow subprocess PID {pid}")))?;
181 Ok(Self {
182 process_group_id,
183 #[cfg(target_vendor = "apple")]
184 leader_exit_observed: std::sync::atomic::AtomicBool::new(false),
185 })
186 }
187
188 #[cfg(windows)]
189 #[expect(unsafe_code, reason = "Windows Job Objects require Win32 FFI calls")]
190 fn for_windows_handle(process: std::os::windows::io::RawHandle, pid: u32) -> io::Result<Self> {
191 use std::mem;
192 use std::ptr;
193
194 use windows_sys::Win32::System::JobObjects::{
195 AssignProcessToJobObject, CreateJobObjectW, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
196 JOBOBJECT_EXTENDED_LIMIT_INFORMATION, JobObjectExtendedLimitInformation,
197 SetInformationJobObject,
198 };
199
200 let job = unsafe { CreateJobObjectW(ptr::null(), ptr::null()) };
203 if job.is_null() {
204 return Err(io::Error::last_os_error());
205 }
206 let job = WindowsJobGuard::new(WindowsHandle(job as isize));
207 let mut limits = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default();
208 limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
209
210 if unsafe {
213 SetInformationJobObject(
214 job.raw()?,
215 JobObjectExtendedLimitInformation,
216 (&raw const limits).cast(),
217 mem::size_of_val(&limits) as u32,
218 )
219 } == 0
220 {
221 return Err(io::Error::last_os_error());
222 }
223
224 if unsafe { AssignProcessToJobObject(job.raw()?, process.cast()) } == 0 {
227 return Err(io::Error::last_os_error());
228 }
229
230 resume_suspended_process(pid)?;
231 Ok(Self { job: job.disarm()? })
232 }
233
234 #[cfg(unix)]
236 #[expect(
237 unsafe_code,
238 reason = "POSIX process-group termination requires libc::kill"
239 )]
240 pub fn terminate(&self) -> io::Result<()> {
241 if unsafe { libc::kill(-self.process_group_id, libc::SIGKILL) } == 0 {
244 return Ok(());
245 }
246
247 let error = io::Error::last_os_error();
248 if error.raw_os_error() == Some(libc::ESRCH) {
249 return Ok(());
250 }
251 #[cfg(target_vendor = "apple")]
252 if error.raw_os_error() == Some(libc::EPERM) && self.leader_has_exited() {
258 return Ok(());
259 }
260 Err(error)
261 }
262
263 #[cfg(all(unix, target_vendor = "apple"))]
267 fn leader_has_exited(&self) -> bool {
268 if self
269 .leader_exit_observed
270 .load(std::sync::atomic::Ordering::Relaxed)
271 {
272 return true;
273 }
274 match self.has_exited_without_reaping() {
275 Ok(exited) => exited,
276 Err(error) => error.raw_os_error() == Some(libc::ECHILD),
277 }
278 }
279
280 #[cfg(all(feature = "tokio", unix))]
282 pub async fn wait_for_exit_without_reaping(&self) -> io::Result<()> {
283 loop {
284 if self.has_exited_without_reaping()? {
285 return Ok(());
286 }
287 tokio::time::sleep(CLEANUP_POLL_INTERVAL).await;
288 }
289 }
290
291 #[cfg(unix)]
294 #[expect(
295 unsafe_code,
296 reason = "non-reaping POSIX child observation requires waitid"
297 )]
298 pub fn has_exited_without_reaping(&self) -> io::Result<bool> {
299 let mut info = std::mem::MaybeUninit::<libc::siginfo_t>::zeroed();
300 let result = unsafe {
303 libc::waitid(
304 libc::P_PID,
305 self.process_group_id as libc::id_t,
306 info.as_mut_ptr(),
307 libc::WEXITED | libc::WNOHANG | libc::WNOWAIT,
308 )
309 };
310 if result != 0 {
311 return Err(io::Error::last_os_error());
312 }
313
314 let exited = unsafe { info.assume_init().si_pid() } != 0;
317 #[cfg(target_vendor = "apple")]
319 if exited {
320 self.leader_exit_observed
321 .store(true, std::sync::atomic::Ordering::Relaxed);
322 }
323 Ok(exited)
324 }
325
326 #[cfg(windows)]
328 #[expect(
329 unsafe_code,
330 reason = "Windows Job Object termination requires a Win32 FFI call"
331 )]
332 pub fn terminate(&self) -> io::Result<()> {
333 use windows_sys::Win32::System::JobObjects::TerminateJobObject;
334
335 if unsafe { TerminateJobObject(self.job.raw(), 1) } != 0 {
337 return Ok(());
338 }
339 Err(io::Error::last_os_error())
340 }
341
342 #[cfg(not(any(unix, windows)))]
344 pub fn terminate(&self) -> io::Result<()> {
345 Err(io::Error::new(
346 io::ErrorKind::Unsupported,
347 "process-tree termination is unsupported on this platform",
348 ))
349 }
350
351 #[cfg(unix)]
352 #[expect(
353 unsafe_code,
354 reason = "POSIX process-group liveness checks require libc::kill"
355 )]
356 pub(crate) fn is_alive(&self) -> bool {
357 #[cfg(target_os = "linux")]
359 if let Some(running) =
360 crate::proc_state::process_group_has_running_member(self.process_group_id)
361 {
362 return running;
363 }
364 unsafe { libc::kill(-self.process_group_id, 0) == 0 }
366 }
367
368 #[cfg(windows)]
369 #[expect(
370 unsafe_code,
371 reason = "Windows Job Object liveness requires QueryInformationJobObject"
372 )]
373 pub(crate) fn is_alive(&self) -> bool {
374 use std::mem;
375 use std::ptr;
376
377 use windows_sys::Win32::System::JobObjects::{
378 JOBOBJECT_BASIC_ACCOUNTING_INFORMATION, JobObjectBasicAccountingInformation,
379 QueryInformationJobObject,
380 };
381
382 let mut accounting = JOBOBJECT_BASIC_ACCOUNTING_INFORMATION::default();
383 unsafe {
386 QueryInformationJobObject(
387 self.job.raw(),
388 JobObjectBasicAccountingInformation,
389 (&raw mut accounting).cast(),
390 mem::size_of_val(&accounting) as u32,
391 ptr::null_mut(),
392 ) != 0
393 && accounting.ActiveProcesses > 0
394 }
395 }
396
397 #[cfg(not(any(unix, windows)))]
398 pub(crate) fn is_alive(&self) -> bool {
399 false
400 }
401}
402
403pub struct ChildCleanup {
405 pub status: Option<ExitStatus>,
407 pub errors: Vec<String>,
409}
410
411#[cfg(feature = "tokio")]
412pub async fn cleanup_tokio_child(
414 process_tree: Option<&ProcessTree>,
415 child: &mut tokio::process::Child,
416) -> ChildCleanup {
417 let mut errors = Vec::new();
418 if !request_tree_termination(process_tree, &mut errors)
419 && let Err(error) = child.start_kill()
420 {
421 errors.push(format!("failed to kill direct subprocess: {error}"));
422 }
423
424 let status = match tokio::time::timeout(CLEANUP_GRACE, child.wait()).await {
425 Ok(Ok(status)) => {
426 return ChildCleanup {
427 status: Some(status),
428 errors,
429 };
430 }
431 Ok(Err(error)) => {
432 errors.push(format!("failed to reap direct subprocess: {error}"));
433 return ChildCleanup {
434 status: None,
435 errors,
436 };
437 }
438 Err(_) => {
439 errors.push(format!(
440 "direct subprocess did not exit within {}ms cleanup grace",
441 CLEANUP_GRACE.as_millis()
442 ));
443 None
444 }
445 };
446
447 if let Err(error) = child.start_kill() {
448 errors.push(format!("failed to retry direct subprocess kill: {error}"));
449 }
450 let status = match tokio::time::timeout(REAP_RETRY_GRACE, child.wait()).await {
451 Ok(Ok(status)) => Some(status),
452 Ok(Err(error)) => {
453 errors.push(format!(
454 "failed to reap direct subprocess after retry: {error}"
455 ));
456 status
457 }
458 Err(_) => {
459 errors.push(format!(
460 "direct subprocess still did not exit after {}ms kill retry",
461 REAP_RETRY_GRACE.as_millis()
462 ));
463 status
464 }
465 };
466 ChildCleanup { status, errors }
467}
468
469pub fn cleanup_std_child(
471 process_tree: Option<&ProcessTree>,
472 child: &mut std::process::Child,
473) -> ChildCleanup {
474 let mut errors = Vec::new();
475 if !request_tree_termination(process_tree, &mut errors)
476 && let Err(error) = child.kill()
477 {
478 errors.push(format!("failed to kill direct subprocess: {error}"));
479 }
480
481 let status = match poll_std_child(child, CLEANUP_GRACE) {
482 Ok(Some(status)) => {
483 return ChildCleanup {
484 status: Some(status),
485 errors,
486 };
487 }
488 Ok(None) => {
489 errors.push(format!(
490 "direct subprocess did not exit within {}ms cleanup grace",
491 CLEANUP_GRACE.as_millis()
492 ));
493 None
494 }
495 Err(error) => {
496 errors.push(format!("failed to reap direct subprocess: {error}"));
497 return ChildCleanup {
498 status: None,
499 errors,
500 };
501 }
502 };
503
504 if let Err(error) = child.kill() {
505 errors.push(format!("failed to retry direct subprocess kill: {error}"));
506 }
507 let status = match poll_std_child(child, REAP_RETRY_GRACE) {
508 Ok(Some(status)) => Some(status),
509 Ok(None) => {
510 errors.push(format!(
511 "direct subprocess still did not exit after {}ms kill retry",
512 REAP_RETRY_GRACE.as_millis()
513 ));
514 status
515 }
516 Err(error) => {
517 errors.push(format!(
518 "failed to reap direct subprocess after retry: {error}"
519 ));
520 status
521 }
522 };
523 ChildCleanup { status, errors }
524}
525
526fn request_tree_termination(process_tree: Option<&ProcessTree>, errors: &mut Vec<String>) -> bool {
527 let Some(process_tree) = process_tree else {
528 return false;
529 };
530 match process_tree.terminate() {
531 Ok(()) => true,
532 Err(error) => {
533 errors.push(format!("failed to terminate subprocess tree: {error}"));
534 false
535 }
536 }
537}
538
539fn poll_std_child(
540 child: &mut std::process::Child,
541 grace: Duration,
542) -> io::Result<Option<ExitStatus>> {
543 let deadline = Instant::now() + grace;
544 loop {
545 if let Some(status) = child.try_wait()? {
546 return Ok(Some(status));
547 }
548
549 let remaining = deadline.saturating_duration_since(Instant::now());
550 if remaining.is_zero() {
551 return Ok(None);
552 }
553 std::thread::sleep(CLEANUP_POLL_INTERVAL.min(remaining));
554 }
555}
556
557#[cfg(all(test, feature = "tokio", unix))]
558#[expect(
559 clippy::expect_used,
560 reason = "test setup failures should fail at the exact setup operation"
561)]
562mod tests {
563 use super::*;
564
565 #[tokio::test]
566 #[expect(
567 unsafe_code,
568 reason = "the regression test verifies that the observed PID remains reserved"
569 )]
570 async fn non_reaping_exit_observation_reserves_process_group_identity() {
571 let mut command = tokio::process::Command::new("/bin/sh");
572 command.args(["-c", "exit 0"]);
573 configure_tokio_command(&mut command);
574 let mut child = command.spawn().expect("test subprocess");
575 let pid = child.id().expect("test subprocess PID");
576 let process_tree = ProcessTree::for_tokio_child(&child).expect("test process tree");
577
578 tokio::time::timeout(
579 Duration::from_secs(1),
580 process_tree.wait_for_exit_without_reaping(),
581 )
582 .await
583 .expect("test subprocess exit")
584 .expect("non-reaping exit observation");
585 let leader_is_reserved = unsafe { libc::kill(pid as libc::pid_t, 0) } == 0;
587 let cleanup = cleanup_tokio_child(Some(&process_tree), &mut child).await;
588
589 assert!(leader_is_reserved, "subprocess leader was reaped too early");
590 assert!(cleanup.errors.is_empty(), "{:?}", cleanup.errors);
591 assert!(cleanup.status.is_some_and(|status| status.success()));
592 }
593}
594
595#[cfg(windows)]
596fn resume_suspended_process(pid: u32) -> io::Result<()> {
597 const THREAD_DISCOVERY_ATTEMPTS: usize = 20;
598 const THREAD_DISCOVERY_DELAY: std::time::Duration = std::time::Duration::from_millis(5);
599
600 for _ in 0..THREAD_DISCOVERY_ATTEMPTS {
601 match find_process_thread(pid) {
602 Ok(thread) => return resume_thread(&thread),
603 Err(error) if error.kind() == io::ErrorKind::NotFound => {
604 std::thread::sleep(THREAD_DISCOVERY_DELAY);
605 }
606 Err(error) => return Err(error),
607 }
608 }
609
610 Err(io::Error::new(
611 io::ErrorKind::NotFound,
612 format!("could not find suspended primary thread for fallow subprocess {pid}"),
613 ))
614}
615
616#[cfg(windows)]
617#[expect(
618 unsafe_code,
619 reason = "thread discovery requires Windows ToolHelp FFI calls"
620)]
621fn find_process_thread(pid: u32) -> io::Result<WindowsHandle> {
622 use std::mem;
623
624 use windows_sys::Win32::Foundation::{ERROR_NO_MORE_FILES, INVALID_HANDLE_VALUE};
625 use windows_sys::Win32::System::Diagnostics::ToolHelp::{
626 CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD, THREADENTRY32, Thread32First, Thread32Next,
627 };
628 use windows_sys::Win32::System::Threading::{OpenThread, THREAD_SUSPEND_RESUME};
629
630 let snapshot = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0) };
632 if snapshot == INVALID_HANDLE_VALUE {
633 return Err(io::Error::last_os_error());
634 }
635 let snapshot = WindowsHandle(snapshot as isize);
636 let mut entry = THREADENTRY32 {
637 dwSize: mem::size_of::<THREADENTRY32>() as u32,
638 ..THREADENTRY32::default()
639 };
640
641 if unsafe { Thread32First(snapshot.raw(), &raw mut entry) } == 0 {
643 return Err(thread_enumeration_error(pid, ERROR_NO_MORE_FILES));
644 }
645
646 loop {
647 if entry.th32OwnerProcessID == pid {
648 let thread = unsafe { OpenThread(THREAD_SUSPEND_RESUME, 0, entry.th32ThreadID) };
650 if thread.is_null() {
651 return Err(io::Error::last_os_error());
652 }
653 return Ok(WindowsHandle(thread as isize));
654 }
655
656 if unsafe { Thread32Next(snapshot.raw(), &raw mut entry) } == 0 {
658 return Err(thread_enumeration_error(pid, ERROR_NO_MORE_FILES));
659 }
660 }
661}
662
663#[cfg(windows)]
664fn thread_enumeration_error(pid: u32, no_more_files: u32) -> io::Error {
665 let error = io::Error::last_os_error();
666 if error.raw_os_error() == i32::try_from(no_more_files).ok() {
667 return io::Error::new(
668 io::ErrorKind::NotFound,
669 format!("no thread found for fallow subprocess {pid}"),
670 );
671 }
672 error
673}
674
675#[cfg(windows)]
676#[expect(
677 unsafe_code,
678 reason = "resuming a Windows thread requires ResumeThread"
679)]
680fn resume_thread(thread: &WindowsHandle) -> io::Result<()> {
681 use windows_sys::Win32::System::Threading::ResumeThread;
682
683 let previous_count = unsafe { ResumeThread(thread.raw()) };
685 if previous_count == u32::MAX {
686 return Err(io::Error::last_os_error());
687 }
688 if previous_count == 0 {
689 return Err(io::Error::other(
690 "fallow subprocess primary thread was not suspended",
691 ));
692 }
693
694 Ok(())
695}