1#[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 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 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#[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#[must_use]
87pub fn open_file_count(pid: u32) -> Option<usize> {
88 table::open_file_count(pid)
89}
90
91#[must_use]
96pub fn start_time(pid: u32) -> Option<u64> {
97 table::start_time(pid)
98}
99
100#[must_use]
103pub fn identity_record(pid: u32) -> Option<String> {
104 Some(format!("{pid} {}\n", start_time(pid)?))
105}
106
107#[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
121pub fn probe_process_table() -> std::io::Result<()> {
125 table::probe()
126}
127
128pub 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 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 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 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 open_files_are_counted_only_where_the_system_lists_them() {
236 let own = id().unwrap_or(0);
237 assert_eq!(open_file_count(own).is_some(), cfg!(target_os = "linux"));
238 assert_eq!(open_file_count(u32::MAX), None);
239 assert!(probe_process_table().is_ok());
240 }
241
242 #[test]
243 fn a_process_record_names_its_id_and_start_time_and_nothing_else() {
244 let own = id().expect("a native process has an id");
245 let record = identity_record(own).expect("the system describes this process");
246 assert!(identity_names(&record, own), "{record:?}");
247 assert!(!identity_names(&record, own.wrapping_add(1)));
249 let start = start_time(own).expect("a start time");
250 assert!(!identity_names(&format!("{own} {}\n", start + 1), own));
251 for malformed in ["", "\n", "not a record", "1", "1 2 3"] {
252 assert!(!identity_names(malformed, own), "{malformed:?}");
253 }
254 }
255
256 #[cfg(target_os = "linux")]
259 #[test]
260 fn an_exited_process_not_yet_reaped_has_no_start_time() {
261 use tilo_test_env::SpawnUnderEnvLock as _;
262 let mut child = std::process::Command::new("true")
263 .spawn_locked()
264 .expect("a child starts");
265 let pid = child.id();
266 let mut info = std::mem::MaybeUninit::<libc::siginfo_t>::zeroed();
268 let waited = unsafe {
270 libc::waitid(
271 libc::P_PID,
272 pid,
273 info.as_mut_ptr(),
274 libc::WEXITED | libc::WNOWAIT,
275 )
276 };
277 assert_eq!(waited, 0, "{}", std::io::Error::last_os_error());
278 assert!(
279 std::fs::metadata(format!("/proc/{pid}")).is_ok(),
280 "the zombie is still in the table"
281 );
282 assert_eq!(start_time(pid), None);
283 child.wait().expect("reaped");
284 }
285}