sinf 0.1.0

Library for obtaining in-depth system information at both the hardware and software levels
Documentation
// This file must hold exactly one test.

#![cfg(all(feature = "system", unix))]

use sinf::{system::ProcessesToUpdate, system::System};

/// Returns the number of file descriptors this process has open, counted by probing each descriptor number in turn.
fn count_open_descriptors() -> usize {
    // Descriptor numbers stay below the process open-file limit reported by `sysconf`.
    const CAP: libc::c_long = 1 << 16;
    let limit = match unsafe { libc::sysconf(libc::_SC_OPEN_MAX) } {
        n if n > 0 => n.min(CAP),
        _ => CAP,
    };
    (0..limit as libc::c_int)
        // `F_GETFD` reads only the descriptor flags and fails with `EBADF` when no such descriptor is open.
        .filter(|&fd| unsafe { libc::fcntl(fd, libc::F_GETFD) } != -1)
        .count()
}

/// Returns what the FreeBSD kernel lists for this process under `kern.proc.filedesc`: one line per record, with its descriptor number, type and path.
#[cfg(target_os = "freebsd")]
fn describe_kernel_file_table() -> String {
    let mib = [
        libc::CTL_KERN,
        libc::KERN_PROC,
        libc::KERN_PROC_FILEDESC,
        std::process::id() as libc::c_int,
    ];
    let mut len: libc::size_t = 0;
    let mut out = String::new();
    unsafe {
        if libc::sysctl(
            mib.as_ptr(),
            mib.len() as _,
            std::ptr::null_mut(),
            &mut len,
            std::ptr::null_mut(),
            0,
        ) != 0
        {
            return "kern.proc.filedesc: the size query failed".to_string();
        }
        // Leave room for descriptors opened between the two calls, as libutil's `kinfo_getfile` does.
        len = len * 4 / 3;
        let mut buf = vec![0u8; len];
        if libc::sysctl(
            mib.as_ptr(),
            mib.len() as _,
            buf.as_mut_ptr() as _,
            &mut len,
            std::ptr::null_mut(),
            0,
        ) != 0
        {
            return "kern.proc.filedesc: the read failed".to_string();
        }
        let mut offset = 0;
        while offset < len {
            let record = buf.as_ptr().add(offset) as *const libc::kinfo_file;
            let size = std::ptr::addr_of!((*record).kf_structsize).read_unaligned();
            if size <= 0 {
                break;
            }
            let fd = std::ptr::addr_of!((*record).kf_fd).read_unaligned();
            let kind = std::ptr::addr_of!((*record).kf_type).read_unaligned();
            let path = std::ffi::CStr::from_ptr(std::ptr::addr_of!((*record).kf_path) as _);
            out.push_str(&format!(
                "  kf_fd={fd:>3} kf_type={kind} path={:?}\n",
                path.to_string_lossy()
            ));
            offset += size as usize;
        }
    }
    out
}

#[cfg(not(target_os = "freebsd"))]
fn describe_kernel_file_table() -> String {
    String::new()
}

// `Process::open_files` must report exactly the number of file descriptors the process has open.
#[test]
fn open_files_counts_the_open_descriptors() {
    if cfg!(feature = "apple-sandbox") {
        return;
    }
    let Ok(pid) = sinf::system::get_current_pid() else {
        return;
    };
    let Ok(mut s) = System::new() else { return };
    let probe = usize::from(cfg!(any(
        target_os = "linux",
        target_os = "android",
        target_os = "netbsd"
    )));
    // Refresh once before counting.
    s.refresh_processes(ProcessesToUpdate::Some(&[pid]), false);
    let expected = count_open_descriptors() + probe;
    s.refresh_processes(ProcessesToUpdate::Some(&[pid]), false);
    let Some(reported) = s.process(pid).and_then(|p| p.open_files()) else {
        // Not supported on this system.
        return;
    };
    assert_eq!(
        reported,
        expected,
        "`open_files` differs from a direct count of the open descriptors\n{}",
        describe_kernel_file_table(),
    );
}