Debian Codegraph @

src/collection/processes/macos/sysctl_bindings.rs

raw symbols SCIP
1 //! Partial bindings from Apple's open source code for getting process
2 //! information. Some of this is based on [heim's binding implementation](https://github.com/heim-rs/heim/blob/master/heim-process/src/sys/macos/bindings/process.rs).
3
4 use std::mem;
5
6 use anyhow::{Result, bail};
7 use libc::{
8 CTL_KERN, KERN_PROC, KERN_PROC_PID, MAXCOMLEN, boolean_t, c_char, c_long, c_short, c_uchar,
9 c_ushort, c_void, dev_t, gid_t, itimerval, pid_t, rusage, sigset_t, timeval, uid_t, xucred,
10 };
11 use mach2::vm_types::user_addr_t;
12
13 use crate::collection::Pid;
14
15 #[repr(C)]
16 pub(crate) struct kinfo_proc {
17 pub kp_proc: extern_proc,
18 pub kp_eproc: eproc,
19 }
20
21 #[repr(C)]
22 #[derive(Copy, Clone)]
23 pub struct p_st1 {
24 /// Doubly-linked run/sleep queue.
25 p_forw: user_addr_t,
26 p_back: user_addr_t,
27 }
28
29 #[repr(C)]
30 pub union p_un {
31 pub p_st1: p_st1,
32
33 /// process start time
34 pub p_starttime: timeval,
35 }
36
37 /// Exported fields for kern sysctl. See
38 /// [`proc.h`](https://opensource.apple.com/source/xnu/xnu-201/bsd/sys/proc.h)
39 #[repr(C)]
40 pub(crate) struct extern_proc {
41 pub p_un: p_un,
42
43 /// Address space.
44 pub p_vmspace: *mut vmspace,
45
46 /// Signal actions, state (PROC ONLY). Should point to
47 /// a `sigacts` but we don't really seem to need this.
48 pub p_sigacts: user_addr_t,
49
50 /// P_* flags.
51 pub p_flag: i32,
52
53 /// S* process status.
54 pub p_stat: c_char,
55
56 /// Process identifier.
57 pub p_pid: pid_t,
58
59 /// Save parent pid during ptrace.
60 pub p_oppid: pid_t,
61
62 /// Sideways return value from fdopen.
63 pub p_dupfd: i32,
64
65 /// where user stack was allocated
66 pub user_stack: caddr_t,
67
68 /// Which thread is exiting?
69 pub exit_thread: *mut c_void,
70
71 /// allow to debug
72 pub p_debugger: i32,
73
74 /// indication to suspend
75 pub sigwait: boolean_t,
76
77 /// Time averaged value of p_cpticks.
78 pub p_estcpu: u32,
79
80 /// Ticks of cpu time.
81 pub p_cpticks: i32,
82
83 /// %cpu for this process during p_swtime
84 pub p_pctcpu: fixpt_t,
85
86 /// Sleep address.
87 pub p_wchan: *mut c_void,
88
89 /// Reason for sleep.
90 pub p_wmesg: *mut c_char,
91
92 /// Time swapped in or out.
93 pub p_swtime: u32,
94
95 /// Time since last blocked.
96 pub p_slptime: u32,
97
98 /// Alarm timer.
99 pub p_realtimer: itimerval,
100
101 /// Real time.
102 pub p_rtime: timeval,
103
104 /// Statclock hit in user mode.
105 pub p_uticks: u64,
106
107 /// Statclock hits in system mode.
108 pub p_sticks: u64,
109
110 /// Statclock hits processing intr.
111 pub p_iticks: u64,
112
113 /// Kernel trace points.
114 pub p_traceflag: i32,
115
116 /// Trace to vnode. Originally a pointer to a struct of vnode.
117 pub p_tracep: *mut c_void,
118
119 /// DEPRECATED.
120 pub p_siglist: i32,
121
122 /// Vnode of executable. Originally a pointer to a struct of vnode.
123 pub p_textvp: *mut c_void,
124
125 /// If non-zero, don't swap.
126 pub p_holdcnt: i32,
127
128 /// DEPRECATED.
129 pub p_sigmask: sigset_t,
130
131 /// Signals being ignored.
132 pub p_sigignore: sigset_t,
133
134 /// Signals being caught by user.
135 pub p_sigcatch: sigset_t,
136
137 /// Process priority.
138 pub p_priority: c_uchar,
139
140 /// User-priority based on p_cpu and p_nice.
141 pub p_usrpri: c_uchar,
142
143 /// Process "nice" value.
144 pub p_nice: c_char,
145
146 pub p_comm: [c_char; MAXCOMLEN + 1],
147
148 /// Pointer to process group. Originally a pointer to a `pgrp`.
149 pub p_pgrp: *mut c_void,
150
151 /// Kernel virtual addr of u-area (PROC ONLY). Originally a pointer to a
152 /// `user`.
153 pub p_addr: *mut c_void,
154
155 /// Exit status for wait; also stop signal.
156 pub p_xstat: c_ushort,
157
158 /// Accounting flags.
159 pub p_acflag: c_ushort,
160
161 /// Exit information. XXX
162 pub p_ru: *mut rusage,
163 }
164
165 const WMESGLEN: usize = 7;
166 const COMAPT_MAXLOGNAME: usize = 12;
167
168 /// See `_caddr_t.h`.
169 #[expect(non_camel_case_types)]
170 type caddr_t = *const libc::c_char;
171
172 /// See `types.h`.
173 #[expect(non_camel_case_types)]
174 type segsz_t = i32;
175
176 /// See `types.h`.
177 #[expect(non_camel_case_types)]
178 type fixpt_t = u32;
179
180 /// See [`proc.h`](https://opensource.apple.com/source/xnu/xnu-201/bsd/sys/proc.h)
181 #[repr(C)]
182 pub(crate) struct pcred {
183 pub pc_lock: [c_char; 72],
184 pub pc_ucred: *mut xucred,
185 pub p_ruid: uid_t,
186 pub p_svuid: uid_t,
187 pub p_rgid: gid_t,
188 pub p_svgid: gid_t,
189 pub p_refcnt: i32,
190 }
191
192 /// See `vm.h`.
193 #[repr(C)]
194 pub(crate) struct vmspace {
195 pub dummy: i32,
196 pub dummy2: caddr_t,
197 pub dummy3: [i32; 5],
198 pub dummy4: [caddr_t; 3],
199 }
200
201 /// See [`sysctl.h`](https://opensource.apple.com/source/xnu/xnu-344/bsd/sys/sysctl.h).
202 #[repr(C)]
203 pub(crate) struct eproc {
204 /// Address of proc. We just cheat and use a c_void pointer since we aren't
205 /// using this.
206 pub e_paddr: *mut c_void,
207
208 /// Session pointer. We just cheat and use a c_void pointer since we aren't
209 /// using this.
210 pub e_sess: *mut c_void,
211
212 /// Process credentials
213 pub e_pcred: pcred,
214
215 /// Current credentials
216 pub e_ucred: xucred,
217
218 /// Address space
219 pub e_vm: vmspace,
220
221 /// Parent process ID
222 pub e_ppid: pid_t,
223
224 /// Process group ID
225 pub e_pgid: pid_t,
226
227 /// Job control counter
228 pub e_jobc: c_short,
229
230 /// Controlling tty dev
231 pub e_tdev: dev_t,
232
233 /// tty process group id
234 pub e_tpgid: pid_t,
235
236 /// tty session pointer. We just cheat and use a c_void pointer since we
237 /// aren't using this.
238 pub e_tsess: *mut c_void,
239
240 /// wchan message
241 pub e_wmesg: [c_char; WMESGLEN + 1],
242
243 /// text size
244 pub e_xsize: segsz_t,
245
246 /// text rss
247 pub e_xrssize: c_short,
248
249 /// text references
250 pub e_xccount: c_short,
251
252 pub e_xswrss: c_short,
253
254 pub e_flag: c_long,
255
256 /// short setlogin() name
257 pub e_login: [c_char; COMAPT_MAXLOGNAME],
258
259 pub e_spare: [c_long; 4],
260 }
261
262 /// Obtains the [`kinfo_proc`] given a process PID.
263 ///
264 /// Based on the implementation from [heim](https://github.com/heim-rs/heim/blob/master/heim-process/src/sys/macos/bindings/process.rs#L235).
265 pub(crate) fn kinfo_process(pid: Pid) -> Result<kinfo_proc> {
266 let mut name: [i32; 4] = [CTL_KERN, KERN_PROC, KERN_PROC_PID, pid];
267 let mut size = mem::size_of::<kinfo_proc>();
268 let mut info = mem::MaybeUninit::<kinfo_proc>::uninit();
269
270 // SAFETY: libc binding, we assume all arguments are valid.
271 let result = unsafe {
272 libc::sysctl(
273 name.as_mut_ptr(),
274 4,
275 info.as_mut_ptr() as *mut libc::c_void,
276 &mut size,
277 std::ptr::null_mut(),
278 0,
279 )
280 };
281
282 if result < 0 {
283 bail!("failed to get process for pid {pid}");
284 }
285
286 // sysctl succeeds but size is zero, happens when process has gone away
287 if size == 0 {
288 bail!("failed to get process for pid {pid}");
289 }
290
291 // SAFETY: info is initialized if result succeeded and returned a non-negative
292 // result. If sysctl failed, it returns -1 with errno set.
293 //
294 // Source: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man3/sysctl.3.html
295 unsafe { Ok(info.assume_init()) }
296 }
297
298 #[cfg(test)]
299 mod test {
300 use std::mem;
301
302 use super::*;
303
304 /// A quick test to ensure that things are sized correctly.
305 #[test]
306 fn test_struct_sizes() {
307 assert_eq!(mem::size_of::<p_st1>(), 16);
308 assert_eq!(mem::align_of::<p_st1>(), 8);
309
310 assert_eq!(mem::size_of::<pcred>(), 104);
311 assert_eq!(mem::align_of::<pcred>(), 8);
312
313 assert_eq!(mem::size_of::<vmspace>(), 64);
314 assert_eq!(mem::align_of::<vmspace>(), 8);
315
316 assert_eq!(mem::size_of::<extern_proc>(), 296);
317 assert_eq!(mem::align_of::<extern_proc>(), 8);
318
319 assert_eq!(mem::size_of::<eproc>(), 376);
320 assert_eq!(mem::align_of::<eproc>(), 8);
321
322 assert_eq!(mem::size_of::<kinfo_proc>(), 672);
323 assert_eq!(mem::align_of::<kinfo_proc>(), 8);
324 }
325 }