kaeru 0.1.9

Reopens your terminal tabs, and the coding agent sessions in them, after the terminal closes or the computer restarts.
//! macOS: the parent and the start time of any process. sysinfo reads them
//! with a call that works only for the user's own processes, so it can't
//! read them for `login`, which runs as root and starts each terminal tab's
//! shell. The calls here work for every process, as they do for `ps`.

use std::mem;
use std::ptr;

/// The parent and the start time of a process.
pub struct ProcessBasics {
    /// The parent's process id, or `None` for a process without a parent.
    pub parent: Option<u32>,
    /// The start time, in milliseconds since the Unix epoch, if it can be
    /// read.
    pub started_ms: Option<u64>,
}

/// Returns the parent and the start time of the process `pid`, or `None`
/// when there is no such process.
pub fn process_basics(pid: u32) -> Option<ProcessBasics> {
    let pid = libc::c_int::try_from(pid).ok()?;
    Some(ProcessBasics {
        parent: parent_of(pid)?,
        started_ms: started_ms(pid),
    })
}

/// Returns the parent of the process `pid`, from the short form of its BSD
/// information, which macOS gives for every process: `Some(None)` for a
/// process without a parent, and `None` when there is no such process.
fn parent_of(pid: libc::c_int) -> Option<Option<u32>> {
    // SAFETY: `proc_bsdshortinfo` is plain data, for which all zeros is a
    // valid value.
    let mut info: libc::proc_bsdshortinfo = unsafe { mem::zeroed() };
    let size = mem::size_of::<libc::proc_bsdshortinfo>() as libc::c_int;
    // SAFETY: `info` is a valid place for the `size` bytes that the call
    // writes, and it lives until the call returns.
    let written = unsafe {
        libc::proc_pidinfo(
            pid,
            libc::PROC_PIDT_SHORTBSDINFO,
            0,
            (&raw mut info).cast(),
            size,
        )
    };
    (written == size).then_some((info.pbsi_ppid != 0).then_some(info.pbsi_ppid))
}

/// Returns the start time of the process `pid`, in milliseconds since the
/// Unix epoch, from the kernel's process table, or `None` when there is no
/// such process. Like sysinfo, it reads whole seconds.
fn started_ms(pid: libc::c_int) -> Option<u64> {
    let mut name = [libc::CTL_KERN, libc::KERN_PROC, libc::KERN_PROC_PID, pid];
    let mut size: libc::size_t = 0;
    // SAFETY: `name` holds the 4 numbers that are passed, and a null buffer
    // asks only for the size of the record, which the call writes to `size`.
    let asked = unsafe {
        libc::sysctl(
            name.as_mut_ptr(),
            4,
            ptr::null_mut(),
            &mut size,
            ptr::null_mut(),
            0,
        )
    };
    if asked != 0 || size == 0 {
        return None;
    }
    let mut record = vec![0u8; size];
    // SAFETY: `record` has room for the `size` bytes that the call may
    // write, and the call writes how many it wrote back to `size`.
    let read = unsafe {
        libc::sysctl(
            name.as_mut_ptr(),
            4,
            record.as_mut_ptr().cast(),
            &mut size,
            ptr::null_mut(),
            0,
        )
    };
    // The record is a `struct kinfo_proc` (see `<sys/sysctl.h>`), whose
    // first field, `kp_proc.p_starttime`, is the start time.
    if read != 0 || size < mem::size_of::<libc::timeval>() {
        return None;
    }
    // SAFETY: the record holds at least one `timeval` at its start, which
    // `read_unaligned` reads wherever it is in memory.
    let started: libc::timeval = unsafe { ptr::read_unaligned(record.as_ptr().cast()) };
    u64::try_from(started.tv_sec)
        .ok()
        .filter(|&seconds| seconds > 0)
        .map(|seconds| seconds * 1000)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn this_process_has_its_parent_and_start_time() {
        let me = process_basics(std::process::id()).unwrap();
        assert_eq!(me.parent, Some(std::os::unix::process::parent_id()));
        let started = me.started_ms.unwrap();
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_millis() as u64;
        assert!(started <= now && now - started < 3_600_000, "{started}");
    }

    #[test]
    fn launchd_runs_as_root_and_still_has_a_start_time() {
        let launchd = process_basics(1).unwrap();
        assert_eq!(launchd.parent, None);
        assert!(launchd.started_ms.is_some());
    }

    #[test]
    fn a_process_that_doesn_t_exist_has_nothing() {
        // Process ids on macOS stay below 100000.
        assert!(process_basics(999_999).is_none());
    }
}