1use std::collections::HashMap;
10use std::sync::OnceLock;
11
12use arrayvec::ArrayString;
13
14fn clock_ticks_per_sec() -> i64 {
19 static TICKS: OnceLock<i64> = OnceLock::new();
20 *TICKS.get_or_init(|| {
21 let ticks = unsafe { libc::sysconf(libc::_SC_CLK_TCK) };
25 if ticks <= 0 { 100 } else { ticks }
26 })
27}
28
29pub fn read_proc_comm(pid: u32) -> Option<String> {
39 let path = proc_path(pid, "comm");
40 let mut buf = [0u8; 64];
41 let mut file = std::fs::File::open(path.as_str()).ok()?;
42 use std::io::Read;
43 let n = file.read(&mut buf).ok()?;
44 let s = std::str::from_utf8(&buf[..n]).ok()?;
45 Some(s.trim().to_string())
46}
47
48fn proc_path(pid: u32, suffix: &str) -> ArrayString<32> {
50 use std::fmt::Write;
51 let mut buf = ArrayString::new();
52 write!(buf, "/proc/{pid}/{suffix}").unwrap();
53 buf
54}
55
56pub fn read_proc_start_time_ns(pid: u32) -> u64 {
66 let path = proc_path(pid, "stat");
67 let stat = match std::fs::read_to_string(path.as_str()) {
68 Ok(s) => s,
69 Err(_) => return 0,
70 };
71 let after_comm = match stat.rfind(") ") {
74 Some(pos) => pos + 2,
75 None => return 0,
76 };
77 let mut rest = &stat[after_comm..];
78 for _ in 0..19 {
83 if let Some(pos) = rest.find(' ') {
84 rest = &rest[pos + 1..];
85 } else {
86 return 0;
87 }
88 }
89 let starttime_jiffies: u64 = match rest.split_whitespace().next() {
90 Some(s) => s.parse().unwrap_or(0),
91 None => return 0,
92 };
93 if starttime_jiffies == 0 {
94 return 0;
95 }
96 (starttime_jiffies as u128 * 1_000_000_000 / clock_ticks_per_sec() as u128) as u64
97}
98
99fn uid_passwd_map() -> &'static HashMap<u32, String> {
102 static MAP: OnceLock<HashMap<u32, String>> = OnceLock::new();
103 MAP.get_or_init(|| {
104 let mut map = HashMap::new();
105 if let Ok(passwd) = std::fs::read_to_string("/etc/passwd") {
106 for entry in passwd.lines() {
107 let mut parts = entry.splitn(4, ':');
108 let name = parts.next();
109 let _shell = parts.next(); let uid_str = parts.next();
111 if let (Some(name), Some(uid_str)) = (name, uid_str)
112 && let Ok(uid) = uid_str.parse::<u32>()
113 {
114 map.insert(uid, name.to_string());
115 }
116 }
117 }
118 map
119 })
120}
121
122pub fn parse_proc_entry(pid: u32) -> Option<crate::types::ProcessInfo> {
135 let path = proc_path(pid, "status");
136 let status = std::fs::read_to_string(path.as_str()).ok()?;
137 let mut ppid = 0u32;
138 let mut cmd = String::new();
139 let mut user = String::new();
140 let mut tgid = 0u32;
141 for line in status.lines() {
142 if let Some(val) = line.strip_prefix("PPid:") {
143 ppid = val.trim().parse().unwrap_or(0);
144 } else if let Some(val) = line.strip_prefix("Name:") {
145 cmd = val.trim().to_string();
146 } else if let Some(val) = line.strip_prefix("Uid:") {
147 if let Some(uid_str) = val.split_whitespace().next()
148 && let Ok(uid) = uid_str.parse::<u32>()
149 {
150 user = uid_to_username(uid).unwrap_or_else(|| "unknown".to_string());
151 } else {
152 user = "unknown".to_string();
153 }
154 } else if let Some(val) = line.strip_prefix("Tgid:") {
155 tgid = val.trim().parse().unwrap_or(0);
156 }
157 }
158 let start_time_ns = read_proc_start_time_ns(pid);
159 Some(crate::types::ProcessInfo {
160 cmd,
161 user,
162 ppid,
163 tgid,
164 start_time_ns,
165 })
166}
167
168pub fn uid_to_username(uid: u32) -> Option<String> {
178 uid_passwd_map().get(&uid).cloned()
179}
180
181#[cfg(test)]
182mod tests {
183 use super::*;
184
185 #[test]
186 fn test_read_proc_comm_pid1() {
187 let comm = read_proc_comm(1);
188 assert!(comm.is_some(), "PID 1 should exist");
189 assert!(!comm.unwrap().is_empty());
190 }
191
192 #[test]
193 fn test_read_proc_comm_nonexistent() {
194 assert!(read_proc_comm(0x7FFFFFFF).is_none());
195 }
196
197 #[test]
198 fn test_read_proc_start_time_ns_pid1() {
199 let ns = read_proc_start_time_ns(1);
200 assert!(ns > 0, "PID 1 start_time_ns should be > 0, got {ns}");
201 }
202
203 #[test]
204 fn test_read_proc_start_time_ns_nonexistent() {
205 assert_eq!(read_proc_start_time_ns(0x7FFFFFFF), 0);
206 }
207
208 #[test]
209 fn test_uid_to_username_root() {
210 let name = uid_to_username(0);
212 assert_eq!(name.as_deref(), Some("root"));
213 }
214
215 #[test]
216 fn test_uid_to_username_nonexistent() {
217 assert!(uid_to_username(0xFFFFFFFF).is_none());
219 }
220}