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