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 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 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#[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#[must_use]
89pub fn open_file_count(pid: u32) -> Option<usize> {
90 table::open_file_count(pid)
91}
92
93#[must_use]
98pub fn start_time(pid: u32) -> Option<u64> {
99 table::start_time(pid)
100}
101
102#[must_use]
105pub fn identity_record(pid: u32) -> Option<String> {
106 Some(format!("{pid} {}\n", start_time(pid)?))
107}
108
109#[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
123pub fn probe_process_table() -> std::io::Result<()> {
127 table::probe()
128}
129
130pub fn raise_open_file_limit() {
134 limits::raise_open_files();
135}
136
137#[cfg(unix)]
143pub fn raise_open_file_limit_to_hard() {
144 let mut limit = libc::rlimit {
145 rlim_cur: 0,
146 rlim_max: 0,
147 };
148 if unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &raw mut limit) } != 0
150 || limit.rlim_cur >= limit.rlim_max
151 {
152 return;
153 }
154 limit.rlim_cur = limit.rlim_max;
155 let _ = unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, &raw const limit) };
158}
159
160#[cfg(target_os = "macos")]
161mod limits {
162 const OPEN_FILES: libc::rlim_t = 1024;
163
164 pub fn raise_open_files() {
165 let mut limit = libc::rlimit {
166 rlim_cur: 0,
167 rlim_max: 0,
168 };
169 if unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &raw mut limit) } != 0 {
171 return;
172 }
173 let wanted = OPEN_FILES.min(limit.rlim_max);
174 if limit.rlim_cur >= wanted {
175 return;
176 }
177 limit.rlim_cur = wanted;
178 let _ = unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, &raw const limit) };
181 }
182}
183
184#[cfg(not(target_os = "macos"))]
185mod limits {
186 pub const fn raise_open_files() {}
187}
188
189#[cfg(target_os = "linux")]
190mod table {
191 pub fn open_file_count(pid: u32) -> Option<usize> {
192 std::fs::read_dir(format!("/proc/{pid}/fd"))
193 .ok()
194 .map(|entries| entries.flatten().count())
195 }
196
197 pub fn start_time(pid: u32) -> Option<u64> {
201 let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
202 let mut fields = stat.rsplit_once(')')?.1.split_whitespace();
203 if matches!(fields.next()?, "Z" | "X") {
204 return None;
205 }
206 fields.nth(18)?.parse().ok()
207 }
208
209 pub fn probe() -> std::io::Result<()> {
210 std::fs::read_dir("/proc").map(|_| ())
211 }
212}
213
214#[cfg(not(target_os = "linux"))]
215mod table {
216 pub const fn open_file_count(_pid: u32) -> Option<usize> {
217 None
218 }
219
220 pub const fn start_time(_pid: u32) -> Option<u64> {
221 None
222 }
223
224 #[allow(
225 clippy::unnecessary_wraps,
226 reason = "the signature is shared with the Linux backend, whose read can fail"
227 )]
228 pub const fn probe() -> std::io::Result<()> {
229 Ok(())
230 }
231}
232
233#[cfg(not(target_family = "wasm"))]
234mod backend {
235 pub const HAS_PROCESS_ID: bool = true;
236
237 #[allow(
238 clippy::unnecessary_wraps,
239 reason = "the signature is shared with the browser backend, which has no id"
240 )]
241 pub fn id() -> Option<u32> {
242 Some(std::process::id())
243 }
244}
245
246#[cfg(target_family = "wasm")]
247mod backend {
248 pub const HAS_PROCESS_ID: bool = false;
249
250 pub fn id() -> Option<u32> {
251 None
252 }
253}
254
255#[cfg(test)]
256mod tests {
257 use super::*;
258
259 #[test]
260 fn open_files_are_counted_only_where_the_system_lists_them() {
261 let own = id().unwrap_or(0);
262 assert_eq!(open_file_count(own).is_some(), cfg!(target_os = "linux"));
263 assert_eq!(open_file_count(u32::MAX), None);
264 assert!(probe_process_table().is_ok());
265 }
266
267 #[test]
268 fn a_process_record_names_its_id_and_start_time_and_nothing_else() {
269 let own = id().expect("a native process has an id");
270 let record = identity_record(own).expect("the system describes this process");
271 assert!(identity_names(&record, own), "{record:?}");
272 assert!(!identity_names(&record, own.wrapping_add(1)));
274 let start = start_time(own).expect("a start time");
275 assert!(!identity_names(&format!("{own} {}\n", start + 1), own));
276 for malformed in ["", "\n", "not a record", "1", "1 2 3"] {
277 assert!(!identity_names(malformed, own), "{malformed:?}");
278 }
279 }
280
281 #[cfg(target_os = "linux")]
284 #[test]
285 fn an_exited_process_not_yet_reaped_has_no_start_time() {
286 use tilo_test_env::SpawnUnderEnvLock as _;
287 let mut child = std::process::Command::new("true")
288 .spawn_locked()
289 .expect("a child starts");
290 let pid = child.id();
291 let mut info = std::mem::MaybeUninit::<libc::siginfo_t>::zeroed();
293 let waited = unsafe {
295 libc::waitid(
296 libc::P_PID,
297 pid,
298 info.as_mut_ptr(),
299 libc::WEXITED | libc::WNOWAIT,
300 )
301 };
302 assert_eq!(waited, 0, "{}", std::io::Error::last_os_error());
303 assert!(
304 std::fs::metadata(format!("/proc/{pid}")).is_ok(),
305 "the zombie is still in the table"
306 );
307 assert_eq!(start_time(pid), None);
308 child.wait().expect("reaped");
309 }
310}