Skip to main content

alpha2_os/
lifetime.rs

1//! Process and child lifetime: exit without handlers, parent-exit watching, standard handle
2//! inheritance, and a job that kills its children.
3
4use std::io;
5
6use crate::Termination;
7
8/// Ends the process now with `code`, without running exit handlers. The caller must flush first.
9///
10/// A thread stuck inside a GPU driver's hardware decoder makes the driver's exit handlers wait
11/// forever. On Windows `std::process::exit` and `_exit` both go through `ExitProcess`, which runs
12/// DLL detach code that can wait on a lock a stopped thread holds; `TerminateProcess` runs none.
13pub fn exit_without_handlers(code: u8) -> ! {
14    #[cfg(unix)]
15    {
16        // SAFETY: `_exit` accepts any status and never returns.
17        unsafe { libc::_exit(libc::c_int::from(code)) }
18    }
19    #[cfg(windows)]
20    {
21        use windows_sys::Win32::System::Threading::{GetCurrentProcess, TerminateProcess};
22        // SAFETY: the current-process pseudo-handle has every access right, including terminate.
23        if unsafe { TerminateProcess(GetCurrentProcess(), u32::from(code)) } != 0 {
24            loop {
25                std::thread::park();
26            }
27        }
28        std::process::exit(i32::from(code))
29    }
30    #[cfg(not(any(unix, windows)))]
31    std::process::exit(i32::from(code))
32}
33
34/// Stops children from implicitly inheriting this process's standard handles (Windows only).
35///
36/// Windows hands a child every inheritable handle when its streams are redirected, so a child
37/// would keep this process's pipes open and a client waiting for EOF would wait for the child.
38/// `Stdio::inherit` still works because the standard library duplicates the handle.
39pub fn stop_std_handle_inheritance() {
40    #[cfg(windows)]
41    {
42        use windows_sys::Win32::Foundation::{
43            HANDLE_FLAG_INHERIT, INVALID_HANDLE_VALUE, SetHandleInformation,
44        };
45        use windows_sys::Win32::System::Console::{
46            GetStdHandle, STD_ERROR_HANDLE, STD_INPUT_HANDLE, STD_OUTPUT_HANDLE,
47        };
48        for stream in [STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, STD_ERROR_HANDLE] {
49            // SAFETY: any standard handle id may be asked for; the handle is not closed here.
50            let handle = unsafe { GetStdHandle(stream) };
51            if handle.is_null() || handle == INVALID_HANDLE_VALUE {
52                continue;
53            }
54            // SAFETY: `handle` is open for the process's life; only its inherit flag changes.
55            let _ = unsafe { SetHandleInformation(handle, HANDLE_FLAG_INHERIT, 0) };
56        }
57    }
58}
59
60/// Takes standard output for a protocol stream.
61///
62/// Returns a writer on the stream standard output was, which children do not inherit, and points
63/// standard output at standard error (a null device when that is closed), so text any library
64/// prints to standard output stays out of the stream. On Windows the C runtime's descriptor 1
65/// follows too.
66///
67/// # Errors
68/// When standard output is closed or cannot be duplicated.
69pub fn claim_stdout() -> io::Result<std::fs::File> {
70    #[cfg(unix)]
71    {
72        crate::platform::claim_stream(libc::STDOUT_FILENO, libc::STDERR_FILENO)
73    }
74    #[cfg(windows)]
75    {
76        crate::platform::claim_stdout()
77    }
78    #[cfg(not(any(unix, windows)))]
79    {
80        Err(io::Error::from(io::ErrorKind::Unsupported))
81    }
82}
83
84pub(crate) const PARENT_EXITED_NAME: &str = "PARENT_EXITED";
85
86/// Reported like `SIGTERM`.
87const PARENT_EXITED: Termination = Termination::new(PARENT_EXITED_NAME, 143, false);
88
89/// Calls the [`crate::on_termination`] handler with a `PARENT_EXITED` termination (status 143)
90/// when the parent process exits, or at once if it already has.
91///
92/// - Linux: waits on a `pidfd`. Kernels before 5.3 fall back to `PR_SET_PDEATHSIG`, which
93///   delivers `SIGTERM` and also fires when the parent's spawning thread exits.
94/// - macOS: waits on a `kqueue` for `NOTE_EXIT`.
95/// - Windows: waits on the parent's handle; a process with that id created after this one means
96///   the id was reused and the parent is gone.
97///
98/// A Unix parent of pid 1 is not watched.
99///
100/// # Errors
101/// When no termination handler is installed, or the parent cannot be watched.
102pub fn watch_parent() -> io::Result<()> {
103    let handler = crate::platform::termination_handler().ok_or_else(|| {
104        io::Error::new(
105            io::ErrorKind::NotFound,
106            "no termination handler is installed",
107        )
108    })?;
109    let Some(parent) = platform::Parent::open()? else {
110        return Ok(());
111    };
112    std::thread::Builder::new()
113        .name("alpha2-parent-watch".to_owned())
114        .spawn(move || {
115            if parent.wait() {
116                handler(PARENT_EXITED);
117            }
118        })?;
119    Ok(())
120}
121
122/// A Windows job that kills its processes when dropped or when this process ends, for probe
123/// children that may hang. A no-op elsewhere.
124pub struct KillOnCloseJob {
125    #[cfg(windows)]
126    handle: platform::OwnedHandle,
127}
128
129impl KillOnCloseJob {
130    /// Creates the job.
131    ///
132    /// # Errors
133    /// When the operating system refuses the job.
134    pub fn new() -> io::Result<Self> {
135        Ok(Self {
136            #[cfg(windows)]
137            handle: platform::kill_on_close_job()?,
138        })
139    }
140
141    /// Puts `child` in the job; call right after spawning.
142    ///
143    /// # Errors
144    /// When the OS refuses, for example because the child already exited.
145    pub fn assign(&self, child: &std::process::Child) -> io::Result<()> {
146        #[cfg(windows)]
147        {
148            platform::assign(&self.handle, child)
149        }
150        #[cfg(not(windows))]
151        {
152            let _ = child;
153            Ok(())
154        }
155    }
156}
157
158impl std::fmt::Debug for KillOnCloseJob {
159    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
160        formatter
161            .debug_struct("KillOnCloseJob")
162            .finish_non_exhaustive()
163    }
164}
165
166#[cfg(target_os = "linux")]
167mod platform {
168    use std::io;
169
170    /// The parent's `pidfd`, or `None` if the parent is gone.
171    pub(super) struct Parent(Option<std::fs::File>);
172
173    impl Parent {
174        pub(super) fn open() -> io::Result<Option<Self>> {
175            use std::os::fd::FromRawFd;
176            // SAFETY: `getppid` cannot fail.
177            let parent = unsafe { libc::getppid() };
178            if parent <= 1 {
179                return Ok(None);
180            }
181            // SAFETY: `pidfd_open` takes a pid and flags and returns a new descriptor or -1.
182            let fd = unsafe { libc::syscall(libc::SYS_pidfd_open, parent, 0) };
183            if fd < 0 {
184                let error = io::Error::last_os_error();
185                return match error.raw_os_error() {
186                    Some(libc::ESRCH) => Ok(Some(Self(None))),
187                    Some(libc::ENOSYS) => death_signal(parent),
188                    _ => Err(error),
189                };
190            }
191            let fd = libc::c_int::try_from(fd)
192                .map_err(|_| io::Error::other("pidfd_open returned an impossible descriptor"))?;
193            // SAFETY: `fd` was just opened by `pidfd_open` and is owned by nothing else.
194            let pidfd = unsafe { std::fs::File::from_raw_fd(fd) };
195            // The parent may have exited before `pidfd_open`; then this process was reparented.
196            // SAFETY: `getppid` cannot fail.
197            if unsafe { libc::getppid() } != parent {
198                return Ok(Some(Self(None)));
199            }
200            Ok(Some(Self(Some(pidfd))))
201        }
202
203        /// Blocks until the parent exits; `false` if the wait failed.
204        pub(super) fn wait(&self) -> bool {
205            use std::os::fd::AsRawFd;
206            let Some(pidfd) = &self.0 else {
207                return true;
208            };
209            let mut poll = libc::pollfd {
210                fd: pidfd.as_raw_fd(),
211                events: libc::POLLIN,
212                revents: 0,
213            };
214            loop {
215                // SAFETY: `poll` is one valid `pollfd` that outlives the call.
216                let ready = unsafe { libc::poll(&raw mut poll, 1, -1) };
217                if ready > 0 {
218                    return true;
219                }
220                if ready < 0 && io::Error::last_os_error().kind() != io::ErrorKind::Interrupted {
221                    return false;
222                }
223            }
224        }
225    }
226
227    /// Fallback for kernels without `pidfd_open`.
228    fn death_signal(parent: libc::pid_t) -> io::Result<Option<Parent>> {
229        // SAFETY: `PR_SET_PDEATHSIG` takes a signal number and changes nothing else.
230        if unsafe { libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGTERM) } != 0 {
231            return Err(io::Error::last_os_error());
232        }
233        // A parent that exited before the call sends nothing.
234        // SAFETY: `getppid` cannot fail.
235        if unsafe { libc::getppid() } != parent {
236            return Ok(Some(Parent(None)));
237        }
238        Ok(None)
239    }
240}
241
242#[cfg(any(target_os = "macos", target_os = "ios", target_os = "freebsd"))]
243mod platform {
244    use std::io;
245
246    /// A `kqueue` watching the parent's `NOTE_EXIT`, or `None` if the parent is gone.
247    pub(super) struct Parent(Option<std::fs::File>);
248
249    impl Parent {
250        pub(super) fn open() -> io::Result<Option<Self>> {
251            use std::os::fd::{AsRawFd, FromRawFd};
252            // SAFETY: `getppid` cannot fail.
253            let parent = unsafe { libc::getppid() };
254            if parent <= 1 {
255                return Ok(None);
256            }
257            // SAFETY: `kqueue` takes nothing and returns a new descriptor or -1.
258            let fd = unsafe { libc::kqueue() };
259            if fd < 0 {
260                return Err(io::Error::last_os_error());
261            }
262            // SAFETY: `fd` was just opened by `kqueue` and is owned by nothing else.
263            let queue = unsafe { std::fs::File::from_raw_fd(fd) };
264            // SAFETY: an all-zero `kevent` is valid; the fields that matter are set below.
265            let mut change: libc::kevent = unsafe { std::mem::zeroed() };
266            change.ident = usize::try_from(parent).unwrap_or(0);
267            change.filter = libc::EVFILT_PROC;
268            change.flags = libc::EV_ADD | libc::EV_ONESHOT;
269            change.fflags = libc::NOTE_EXIT;
270            // SAFETY: `change` is one valid `kevent` that outlives the call; no events are read.
271            let registered = unsafe {
272                libc::kevent(
273                    queue.as_raw_fd(),
274                    &raw const change,
275                    1,
276                    std::ptr::null_mut(),
277                    0,
278                    std::ptr::null(),
279                )
280            };
281            if registered < 0 {
282                let error = io::Error::last_os_error();
283                return if error.raw_os_error() == Some(libc::ESRCH) {
284                    Ok(Some(Self(None)))
285                } else {
286                    Err(error)
287                };
288            }
289            // The parent may have exited before registration.
290            // SAFETY: `getppid` cannot fail.
291            if unsafe { libc::getppid() } != parent {
292                return Ok(Some(Self(None)));
293            }
294            Ok(Some(Self(Some(queue))))
295        }
296
297        /// Blocks until the parent exits; `false` if the wait failed.
298        pub(super) fn wait(&self) -> bool {
299            use std::os::fd::AsRawFd;
300            let Some(queue) = &self.0 else {
301                return true;
302            };
303            loop {
304                // SAFETY: an all-zero `kevent` is valid; the call fills it.
305                let mut event: libc::kevent = unsafe { std::mem::zeroed() };
306                // SAFETY: `event` has room for the one event asked for and outlives the call.
307                let ready = unsafe {
308                    libc::kevent(
309                        queue.as_raw_fd(),
310                        std::ptr::null(),
311                        0,
312                        &raw mut event,
313                        1,
314                        std::ptr::null(),
315                    )
316                };
317                if ready > 0 {
318                    return true;
319                }
320                if ready < 0 && io::Error::last_os_error().kind() != io::ErrorKind::Interrupted {
321                    return false;
322                }
323            }
324        }
325    }
326}
327
328#[cfg(windows)]
329mod platform {
330    use std::io;
331    use std::os::windows::io::AsRawHandle;
332
333    use windows_sys::Win32::Foundation::{
334        CloseHandle, ERROR_INVALID_PARAMETER, FILETIME, HANDLE, INVALID_HANDLE_VALUE, WAIT_OBJECT_0,
335    };
336    use windows_sys::Win32::System::Diagnostics::ToolHelp::{
337        CreateToolhelp32Snapshot, PROCESSENTRY32W, Process32FirstW, Process32NextW,
338        TH32CS_SNAPPROCESS,
339    };
340    use windows_sys::Win32::System::JobObjects::{
341        AssignProcessToJobObject, CreateJobObjectW, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
342        JOBOBJECT_EXTENDED_LIMIT_INFORMATION, JobObjectExtendedLimitInformation,
343        SetInformationJobObject,
344    };
345    use windows_sys::Win32::System::Threading::{
346        GetCurrentProcess, GetCurrentProcessId, GetProcessTimes, INFINITE, OpenProcess,
347        PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_SYNCHRONIZE, WaitForSingleObject,
348    };
349
350    pub(super) struct OwnedHandle(HANDLE);
351
352    // SAFETY: a kernel handle is a process-wide value; any thread may wait on or close it.
353    unsafe impl Send for OwnedHandle {}
354    // SAFETY: the calls made through a shared reference (waits, job assignment) are thread-safe.
355    unsafe impl Sync for OwnedHandle {}
356
357    impl Drop for OwnedHandle {
358        fn drop(&mut self) {
359            // SAFETY: the handle is open and owned by this value alone.
360            unsafe { CloseHandle(self.0) };
361        }
362    }
363
364    /// The parent's handle, or `None` if the parent is gone.
365    pub(super) struct Parent(Option<OwnedHandle>);
366
367    impl Parent {
368        pub(super) fn open() -> io::Result<Option<Self>> {
369            let Some(parent) = parent_id()? else {
370                return Ok(None);
371            };
372            // SAFETY: `OpenProcess` takes plain values and returns a new handle or null.
373            let handle = unsafe {
374                OpenProcess(
375                    PROCESS_SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION,
376                    0,
377                    parent,
378                )
379            };
380            if handle.is_null() {
381                let error = io::Error::last_os_error();
382                return if error.raw_os_error() == i32::try_from(ERROR_INVALID_PARAMETER).ok() {
383                    Ok(Some(Self(None)))
384                } else {
385                    Err(error)
386                };
387            }
388            let handle = OwnedHandle(handle);
389            // SAFETY: the pseudo-handle of the current process needs no closing.
390            let ours = created(unsafe { GetCurrentProcess() })?;
391            // A process created after this one cannot be the parent; the id was reused.
392            if created(handle.0)? > ours {
393                return Ok(Some(Self(None)));
394            }
395            Ok(Some(Self(Some(handle))))
396        }
397
398        /// Blocks until the parent exits; `false` if the wait failed.
399        pub(super) fn wait(&self) -> bool {
400            let Some(handle) = &self.0 else {
401                return true;
402            };
403            // SAFETY: the handle is open, with `SYNCHRONIZE` access, for the call.
404            unsafe { WaitForSingleObject(handle.0, INFINITE) == WAIT_OBJECT_0 }
405        }
406    }
407
408    fn parent_id() -> io::Result<Option<u32>> {
409        // SAFETY: a process snapshot takes no process id.
410        let snapshot = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) };
411        if snapshot == INVALID_HANDLE_VALUE {
412            return Err(io::Error::last_os_error());
413        }
414        let snapshot = OwnedHandle(snapshot);
415        // SAFETY: the current process id cannot fail.
416        let ours = unsafe { GetCurrentProcessId() };
417        let mut entry = PROCESSENTRY32W {
418            dwSize: u32::try_from(std::mem::size_of::<PROCESSENTRY32W>()).unwrap_or(0),
419            ..PROCESSENTRY32W::default()
420        };
421        // SAFETY: `entry` is a `PROCESSENTRY32W` with its size set, outliving the call.
422        let mut more = unsafe { Process32FirstW(snapshot.0, &raw mut entry) } != 0;
423        while more {
424            if entry.th32ProcessID == ours {
425                return Ok(Some(entry.th32ParentProcessID).filter(|parent| *parent != 0));
426            }
427            // SAFETY: as for the first entry.
428            more = unsafe { Process32NextW(snapshot.0, &raw mut entry) } != 0;
429        }
430        Ok(None)
431    }
432
433    /// When `process` was created, in 100 ns intervals since 1601.
434    fn created(process: HANDLE) -> io::Result<u64> {
435        let zero = || FILETIME {
436            dwLowDateTime: 0,
437            dwHighDateTime: 0,
438        };
439        let (mut created, mut exited, mut kernel, mut user) = (zero(), zero(), zero(), zero());
440        // SAFETY: `process` has query access; the four structures outlive the call.
441        let read = unsafe {
442            GetProcessTimes(
443                process,
444                &raw mut created,
445                &raw mut exited,
446                &raw mut kernel,
447                &raw mut user,
448            )
449        };
450        if read == 0 {
451            return Err(io::Error::last_os_error());
452        }
453        Ok(u64::from(created.dwHighDateTime) << 32 | u64::from(created.dwLowDateTime))
454    }
455
456    pub(super) fn kill_on_close_job() -> io::Result<OwnedHandle> {
457        // SAFETY: an unnamed job with default security; the call returns a new handle or null.
458        let job = unsafe { CreateJobObjectW(std::ptr::null(), std::ptr::null()) };
459        if job.is_null() {
460            return Err(io::Error::last_os_error());
461        }
462        let job = OwnedHandle(job);
463        let mut limits = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default();
464        limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
465        // SAFETY: `limits` matches this information class and size, and outlives the call.
466        let set = unsafe {
467            SetInformationJobObject(
468                job.0,
469                JobObjectExtendedLimitInformation,
470                (&raw const limits).cast(),
471                u32::try_from(std::mem::size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>())
472                    .unwrap_or(0),
473            )
474        };
475        if set == 0 {
476            return Err(io::Error::last_os_error());
477        }
478        Ok(job)
479    }
480
481    pub(super) fn assign(job: &OwnedHandle, child: &std::process::Child) -> io::Result<()> {
482        // SAFETY: both handles are open for the call; `child` keeps its process handle open.
483        if unsafe { AssignProcessToJobObject(job.0, child.as_raw_handle()) } == 0 {
484            return Err(io::Error::last_os_error());
485        }
486        Ok(())
487    }
488}
489
490#[cfg(not(any(
491    target_os = "linux",
492    target_os = "macos",
493    target_os = "ios",
494    target_os = "freebsd",
495    windows
496)))]
497mod platform {
498    use std::io;
499
500    /// No parent watch on this platform.
501    pub(super) struct Parent;
502
503    // Same signatures as the platforms that watch.
504    #[allow(clippy::unnecessary_wraps, clippy::unused_self)]
505    impl Parent {
506        pub(super) fn open() -> io::Result<Option<Self>> {
507            Ok(None)
508        }
509
510        pub(super) fn wait(&self) -> bool {
511            false
512        }
513    }
514}
515
516#[cfg(test)]
517#[path = "lifetime_tests.rs"]
518mod tests;