Skip to main content

tilo_process/
lib.rs

1//! The current process, with one API on every target.
2//!
3//! On Linux and macOS an app runs as an OS process with an id; in the browser it runs
4//! inside the page, which has none, so the functions here answer `None` rather than
5//! panicking as `std::process::id` does.
6
7#[cfg(target_os = "android")]
8pub mod android;
9pub mod child;
10#[cfg(unix)]
11pub mod confinement;
12#[cfg(unix)]
13pub mod descriptor;
14#[cfg(feature = "native-editor")]
15pub mod editor;
16pub mod environment;
17pub use tilo_platform_caps::{Availability, availability, available};
18#[cfg(unix)]
19pub mod local_socket;
20pub mod login_shell;
21#[cfg(unix)]
22pub mod pty;
23pub mod rendezvous;
24pub mod shared_memory;
25pub mod tools;
26
27#[derive(Clone, Copy, Debug, PartialEq, Eq)]
28pub enum Feature {
29    ProcessId,
30    Rendezvous,
31}
32
33impl tilo_platform_caps::Feature for Feature {
34    /// The feature's availability on Linux, macOS and the web, in that order.
35    fn targets(self) -> [Availability; 3] {
36        use Availability::{Available, Unsupported};
37        match self {
38            Self::ProcessId => [
39                Available,
40                Available,
41                Unsupported("a page has no process id"),
42            ],
43            Self::Rendezvous => [
44                Available,
45                Available,
46                Unsupported("a page has no local sockets"),
47            ],
48        }
49    }
50
51    fn availability(self) -> Availability {
52        let here = match self {
53            Self::ProcessId => backend::HAS_PROCESS_ID,
54            Self::Rendezvous => cfg!(unix),
55        };
56        if here {
57            Availability::Available
58        } else {
59            self.targets()[2]
60        }
61    }
62}
63
64/// The current process's OS id, or `None` where apps do not run as OS
65/// processes (the browser).
66#[must_use]
67pub fn id() -> Option<u32> {
68    backend::id()
69}
70
71#[cfg(unix)]
72#[must_use]
73pub fn uid() -> u32 {
74    rustix::process::getuid().as_raw()
75}
76
77#[cfg(unix)]
78#[must_use]
79pub fn effective_uid() -> u32 {
80    rustix::process::geteuid().as_raw()
81}
82
83/// How many files `pid` has open, where the system says (Linux's `/proc/<pid>/fd`).
84/// `None` elsewhere, and when the process has exited or its table is unreadable;
85/// never a made-up zero.
86#[must_use]
87pub fn open_file_count(pid: u32) -> Option<usize> {
88    table::open_file_count(pid)
89}
90
91/// The kernel's start time for `pid`, the value that tells a live process from another
92/// that reused its id. `None` where the system has no process table, or the process is gone:
93/// one that exited and was not reaped yet (a zombie) still has its table entry, but does
94/// nothing and holds nothing, so it is gone too.
95#[must_use]
96pub fn start_time(pid: u32) -> Option<u64> {
97    table::start_time(pid)
98}
99
100/// One line naming the live process `pid`: its id and [`start_time`], as [`identity_names`]
101/// reads it back. `None` where the system cannot see the process.
102#[must_use]
103pub fn identity_record(pid: u32) -> Option<String> {
104    Some(format!("{pid} {}\n", start_time(pid)?))
105}
106
107/// Whether `record`, as [`identity_record`] wrote it, names the process `pid` that is alive
108/// now: a process that reused the id has another start time, so its predecessor's record
109/// never names it. Anything but the one record shape is `false`.
110#[must_use]
111pub fn identity_names(record: &str, pid: u32) -> bool {
112    let mut fields = record.split_whitespace();
113    let (Some(record_pid), Some(record_start), None) =
114        (fields.next(), fields.next(), fields.next())
115    else {
116        return false;
117    };
118    record_pid.parse::<u32>() == Ok(pid) && record_start.parse::<u64>().ok() == start_time(pid)
119}
120
121/// Whether this process may read the system's process table: the read error on Linux,
122/// `Ok` where no separate table exists to fail, so an empty list can be told apart from
123/// a denied one.
124pub fn probe_process_table() -> std::io::Result<()> {
125    table::probe()
126}
127
128/// Raise this process's soft open-file limit to the 1024 descriptors a Linux app starts
129/// with, as far as the hard limit allows; macOS starts processes at 256, which one app
130/// retaining a descriptor per selected file exhausts.
131pub fn raise_open_file_limit() {
132    limits::raise_open_files();
133}
134
135#[cfg(target_os = "macos")]
136mod limits {
137    const OPEN_FILES: libc::rlim_t = 1024;
138
139    pub fn raise_open_files() {
140        let mut limit = libc::rlimit {
141            rlim_cur: 0,
142            rlim_max: 0,
143        };
144        // SAFETY: getrlimit only writes the rlimit it is given.
145        if unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &raw mut limit) } != 0 {
146            return;
147        }
148        let wanted = OPEN_FILES.min(limit.rlim_max);
149        if limit.rlim_cur >= wanted {
150            return;
151        }
152        limit.rlim_cur = wanted;
153        // SAFETY: setrlimit only reads the initialized rlimit it is given. A
154        // refusal leaves the previous limit, which is still usable.
155        let _ = unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, &raw const limit) };
156    }
157}
158
159#[cfg(not(target_os = "macos"))]
160mod limits {
161    pub const fn raise_open_files() {}
162}
163
164#[cfg(target_os = "linux")]
165mod table {
166    pub fn open_file_count(pid: u32) -> Option<usize> {
167        std::fs::read_dir(format!("/proc/{pid}/fd"))
168            .ok()
169            .map(|entries| entries.flatten().count())
170    }
171
172    /// Field 22 of `/proc/<pid>/stat`, of a process whose state (field 3) is not zombie or dead.
173    /// `comm` is parenthesised and may itself hold spaces or a `)`, so the last closing
174    /// parenthesis is what precedes the fields after it.
175    pub fn start_time(pid: u32) -> Option<u64> {
176        let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
177        let mut fields = stat.rsplit_once(')')?.1.split_whitespace();
178        if matches!(fields.next()?, "Z" | "X") {
179            return None;
180        }
181        fields.nth(18)?.parse().ok()
182    }
183
184    pub fn probe() -> std::io::Result<()> {
185        std::fs::read_dir("/proc").map(|_| ())
186    }
187}
188
189#[cfg(not(target_os = "linux"))]
190mod table {
191    pub const fn open_file_count(_pid: u32) -> Option<usize> {
192        None
193    }
194
195    pub const fn start_time(_pid: u32) -> Option<u64> {
196        None
197    }
198
199    #[allow(
200        clippy::unnecessary_wraps,
201        reason = "the signature is shared with the Linux backend, whose read can fail"
202    )]
203    pub const fn probe() -> std::io::Result<()> {
204        Ok(())
205    }
206}
207
208#[cfg(not(target_family = "wasm"))]
209mod backend {
210    pub const HAS_PROCESS_ID: bool = true;
211
212    #[allow(
213        clippy::unnecessary_wraps,
214        reason = "the signature is shared with the browser backend, which has no id"
215    )]
216    pub fn id() -> Option<u32> {
217        Some(std::process::id())
218    }
219}
220
221#[cfg(target_family = "wasm")]
222mod backend {
223    pub const HAS_PROCESS_ID: bool = false;
224
225    pub fn id() -> Option<u32> {
226        None
227    }
228}
229
230#[cfg(test)]
231mod tests {
232    use super::*;
233
234    #[test]
235    fn native_processes_have_an_id() {
236        assert_eq!(id().is_some(), cfg!(not(target_family = "wasm")));
237    }
238
239    #[test]
240    fn open_files_are_counted_only_where_the_system_lists_them() {
241        let own = id().unwrap_or(0);
242        assert_eq!(open_file_count(own).is_some(), cfg!(target_os = "linux"));
243        assert_eq!(open_file_count(u32::MAX), None);
244        assert!(probe_process_table().is_ok());
245    }
246
247    #[test]
248    fn a_process_record_names_its_id_and_start_time_and_nothing_else() {
249        let own = id().expect("a native process has an id");
250        let record = identity_record(own).expect("the system describes this process");
251        assert!(identity_names(&record, own), "{record:?}");
252        // Another process, whether a live one or an id nothing has, is never this one.
253        assert!(!identity_names(&record, own.wrapping_add(1)));
254        let start = start_time(own).expect("a start time");
255        assert!(!identity_names(&format!("{own} {}\n", start + 1), own));
256        for malformed in ["", "\n", "not a record", "1", "1 2 3"] {
257            assert!(!identity_names(malformed, own), "{malformed:?}");
258        }
259    }
260
261    /// A child that exited and was not reaped yet keeps its table entry, but is not alive: it has
262    /// no start time, so nothing takes it for the live process it was.
263    #[cfg(target_os = "linux")]
264    #[test]
265    fn an_exited_process_not_yet_reaped_has_no_start_time() {
266        use tilo_test_env::SpawnUnderEnvLock as _;
267        let mut child = std::process::Command::new("true")
268            .spawn_locked()
269            .expect("a child starts");
270        let pid = child.id();
271        // Wait for the exit without reaping it: the child stays a zombie until `wait`.
272        let mut info = std::mem::MaybeUninit::<libc::siginfo_t>::zeroed();
273        // SAFETY: waitid writes only the siginfo it is given; WNOWAIT leaves the child unreaped.
274        let waited = unsafe {
275            libc::waitid(
276                libc::P_PID,
277                pid,
278                info.as_mut_ptr(),
279                libc::WEXITED | libc::WNOWAIT,
280            )
281        };
282        assert_eq!(waited, 0, "{}", std::io::Error::last_os_error());
283        assert!(
284            std::fs::metadata(format!("/proc/{pid}")).is_ok(),
285            "the zombie is still in the table"
286        );
287        assert_eq!(start_time(pid), None);
288        child.wait().expect("reaped");
289    }
290}