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(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 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 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 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 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 #[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 let mut info = std::mem::MaybeUninit::<libc::siginfo_t>::zeroed();
270 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}