Debian Codegraph @

third_party/rust/rustix/src/process/procctl.rs

raw
1 //! Bindings for the FreeBSD `procctl` system call.
2 //!
3 //! There are similarities (but also differences) with Linux's `prctl` system
4 //! call, whose interface is located in the `prctl.rs` file.
5
6 #![allow(unsafe_code)]
7
8 #[cfg(feature = "alloc")]
9 use alloc::{vec, vec::Vec};
10 use core::mem::MaybeUninit;
11 use core::ptr;
12
13 use bitflags::bitflags;
14
15 use crate::backend::c::{c_int, c_uint, c_void};
16 use crate::backend::process::syscalls;
17 use crate::backend::process::types::RawId;
18 use crate::io;
19 use crate::process::{Pid, RawPid};
20 use crate::signal::Signal;
21 use crate::utils::{as_mut_ptr, as_ptr};
22
23 //
24 // Helper functions.
25 //
26
27 /// Subset of `idtype_t` C enum, with only the values allowed by `procctl`.
28 #[repr(i32)]
29 pub enum IdType {
30 /// Process id.
31 Pid = 0,
32 /// Process group id.
33 Pgid = 2,
34 }
35
36 /// A process selector for use with the `procctl` interface.
37 ///
38 /// `None` represents the current process. `Some((IdType::Pid, pid))`
39 /// represents the process with pid `pid`. `Some((IdType::Pgid, pgid))`
40 /// represents the control processes belonging to the process group with id
41 /// `pgid`.
42 pub type ProcSelector = Option<(IdType, Pid)>;
43 fn proc_selector_to_raw(selector: ProcSelector) -> (IdType, RawPid) {
44 match selector {
45 Some((idtype, id)) => (idtype, id.as_raw_nonzero().get()),
46 None => (IdType::Pid, 0),
47 }
48 }
49
50 #[inline]
51 pub(crate) unsafe fn procctl(
52 option: c_int,
53 process: ProcSelector,
54 data: *mut c_void,
55 ) -> io::Result<()> {
56 let (idtype, id) = proc_selector_to_raw(process);
57 syscalls::procctl(idtype as c_uint, id as RawId, option, data)
58 }
59
60 #[inline]
61 pub(crate) unsafe fn procctl_set<P>(
62 option: c_int,
63 process: ProcSelector,
64 data: &P,
65 ) -> io::Result<()> {
66 procctl(option, process, (as_ptr(data) as *mut P).cast())
67 }
68
69 #[inline]
70 pub(crate) unsafe fn procctl_get_optional<P>(
71 option: c_int,
72 process: ProcSelector,
73 ) -> io::Result<P> {
74 let mut value: MaybeUninit<P> = MaybeUninit::uninit();
75 procctl(option, process, value.as_mut_ptr().cast())?;
76 Ok(value.assume_init())
77 }
78
79 //
80 // PROC_PDEATHSIG_STATUS/PROC_PDEATHSIG_CTL
81 //
82
83 const PROC_PDEATHSIG_STATUS: c_int = 12;
84
85 /// Get the current value of the parent process death signal.
86 ///
87 /// # References
88 /// - [Linux: `prctl(PR_GET_PDEATHSIG,…)`]
89 /// - [FreeBSD: `procctl(PROC_PDEATHSIG_STATUS,…)`]
90 ///
91 /// [Linux: `prctl(PR_GET_PDEATHSIG,…)`]: https://man7.org/linux/man-pages/man2/prctl.2.html
92 /// [FreeBSD: `procctl(PROC_PDEATHSIG_STATUS,…)`]: https://man.freebsd.org/cgi/man.cgi?query=procctl&sektion=2
93 #[inline]
94 pub fn parent_process_death_signal() -> io::Result<Option<Signal>> {
95 unsafe { procctl_get_optional::<c_int>(PROC_PDEATHSIG_STATUS, None) }.map(Signal::from_raw)
96 }
97
98 const PROC_PDEATHSIG_CTL: c_int = 11;
99
100 /// Set the parent-death signal of the calling process.
101 ///
102 /// # References
103 /// - [Linux: `prctl(PR_SET_PDEATHSIG,…)`]
104 /// - [FreeBSD: `procctl(PROC_PDEATHSIG_CTL,…)`]
105 ///
106 /// [Linux: `prctl(PR_SET_PDEATHSIG,…)`]: https://man7.org/linux/man-pages/man2/prctl.2.html
107 /// [FreeBSD: `procctl(PROC_PDEATHSIG_CTL,…)`]: https://man.freebsd.org/cgi/man.cgi?query=procctl&sektion=2
108 #[inline]
109 pub fn set_parent_process_death_signal(signal: Option<Signal>) -> io::Result<()> {
110 let signal = signal.map_or(0, |signal| signal as c_int);
111 unsafe { procctl_set::<c_int>(PROC_PDEATHSIG_CTL, None, &signal) }
112 }
113
114 //
115 // PROC_TRACE_CTL
116 //
117
118 const PROC_TRACE_CTL: c_int = 7;
119
120 const PROC_TRACE_CTL_ENABLE: i32 = 1;
121 const PROC_TRACE_CTL_DISABLE: i32 = 2;
122 const PROC_TRACE_CTL_DISABLE_EXEC: i32 = 3;
123
124 /// `PROC_TRACE_CTL_*`.
125 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
126 #[repr(i32)]
127 pub enum DumpableBehavior {
128 /// Not dumpable.
129 NotDumpable = PROC_TRACE_CTL_DISABLE,
130 /// Dumpable.
131 Dumpable = PROC_TRACE_CTL_ENABLE,
132 /// Not dumpable, and this behaviour is preserved across `execve` calls.
133 NotDumpableExecPreserved = PROC_TRACE_CTL_DISABLE_EXEC,
134 }
135
136 /// Set the state of the `dumpable` attribute for the process indicated by
137 /// `idtype` and `id`.
138 ///
139 /// This determines whether the process can be traced and whether core dumps
140 /// are produced for the process upon delivery of a signal whose default
141 /// behavior is to produce a core dump.
142 ///
143 /// This is similar to `set_dumpable_behavior` on Linux, with the exception
144 /// that on FreeBSD there is an extra argument `process`. When `process` is set
145 /// to `None`, the operation is performed for the current process, like on
146 /// Linux.
147 ///
148 /// # References
149 /// - [FreeBSD `procctl(PROC_TRACE_CTL,…)`]
150 ///
151 /// [FreeBSD `procctl(PROC_TRACE_CTL,…)`]: https://man.freebsd.org/cgi/man.cgi?query=procctl&sektion=2
152 #[inline]
153 pub fn set_dumpable_behavior(process: ProcSelector, config: DumpableBehavior) -> io::Result<()> {
154 unsafe { procctl(PROC_TRACE_CTL, process, config as usize as *mut _) }
155 }
156
157 //
158 // PROC_TRACE_STATUS
159 //
160
161 const PROC_TRACE_STATUS: c_int = 8;
162
163 /// Tracing status as returned by [`trace_status`].
164 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
165 pub enum TracingStatus {
166 /// Tracing is disabled for the process.
167 NotTraceble,
168 /// Tracing is not disabled for the process, but not debugger/tracer is
169 /// attached.
170 Tracable,
171 /// The process is being traced by the process whose pid is stored in the
172 /// first component of this variant.
173 BeingTraced(Pid),
174 }
175
176 /// Get the tracing status of the process indicated by `idtype` and `id`.
177 ///
178 /// # References
179 /// - [FreeBSD `procctl(PROC_TRACE_STATUS,…)`]
180 ///
181 /// [FreeBSD `procctl(PROC_TRACE_STATUS,…)`]: https://man.freebsd.org/cgi/man.cgi?query=procctl&sektion=2
182 #[inline]
183 pub fn trace_status(process: ProcSelector) -> io::Result<TracingStatus> {
184 let val = unsafe { procctl_get_optional::<c_int>(PROC_TRACE_STATUS, process) }?;
185 match val {
186 -1 => Ok(TracingStatus::NotTraceble),
187 0 => Ok(TracingStatus::Tracable),
188 pid => {
189 let pid = Pid::from_raw(pid as RawPid).ok_or(io::Errno::RANGE)?;
190 Ok(TracingStatus::BeingTraced(pid))
191 }
192 }
193 }
194
195 //
196 // PROC_REAP_*
197 //
198
199 const PROC_REAP_ACQUIRE: c_int = 2;
200 const PROC_REAP_RELEASE: c_int = 3;
201
202 /// Acquire or release the reaper status of the calling process.
203 ///
204 /// # References
205 /// - [FreeBSD: `procctl(PROC_REAP_ACQUIRE/RELEASE,…)`]
206 ///
207 /// [FreeBSD: `procctl(PROC_REAP_ACQUIRE/RELEASE,…)`]: https://man.freebsd.org/cgi/man.cgi?query=procctl&sektion=2
208 #[inline]
209 pub fn set_reaper_status(reaper: bool) -> io::Result<()> {
210 unsafe {
211 procctl(
212 if reaper {
213 PROC_REAP_ACQUIRE
214 } else {
215 PROC_REAP_RELEASE
216 },
217 None,
218 ptr::null_mut(),
219 )
220 }
221 }
222
223 const PROC_REAP_STATUS: c_int = 4;
224
225 bitflags! {
226 /// `REAPER_STATUS_*`.
227 #[repr(transparent)]
228 #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
229 pub struct ReaperStatusFlags: c_uint {
230 /// The process has acquired reaper status.
231 const OWNED = 1;
232 /// The process is the root of the reaper tree (pid 1).
233 const REALINIT = 2;
234
235 /// <https://docs.rs/bitflags/*/bitflags/#externally-defined-flags>
236 const _ = !0;
237 }
238 }
239
240 #[repr(C)]
241 struct procctl_reaper_status {
242 rs_flags: c_uint,
243 rs_children: c_uint,
244 rs_descendants: c_uint,
245 rs_reaper: RawPid,
246 rs_pid: RawPid,
247 rs_pad0: [c_uint; 15],
248 }
249
250 /// Reaper status as returned by [`get_reaper_status`].
251 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
252 pub struct ReaperStatus {
253 /// The flags.
254 pub flags: ReaperStatusFlags,
255 /// The number of children of the reaper among the descendants.
256 pub children: usize,
257 /// The total number of descendants of the reaper(s), not counting
258 /// descendants of the reaper in the subtree.
259 pub descendants: usize,
260 /// The pid of the reaper for the specified process id.
261 pub reaper: Pid,
262 /// The pid of one reaper child if there are any descendants.
263 pub pid: Option<Pid>,
264 }
265
266 /// Get information about the reaper of the specified process (or the process
267 /// itself if it is a reaper).
268 ///
269 /// # References
270 /// - [FreeBSD: `procctl(PROC_REAP_STATUS,…)`]
271 ///
272 /// [FreeBSD: `procctl(PROC_REAP_STATUS,…)`]: https://man.freebsd.org/cgi/man.cgi?query=procctl&sektion=2
273 #[inline]
274 pub fn get_reaper_status(process: ProcSelector) -> io::Result<ReaperStatus> {
275 let raw = unsafe { procctl_get_optional::<procctl_reaper_status>(PROC_REAP_STATUS, process) }?;
276 Ok(ReaperStatus {
277 flags: ReaperStatusFlags::from_bits_retain(raw.rs_flags),
278 children: raw.rs_children as _,
279 descendants: raw.rs_descendants as _,
280 reaper: Pid::from_raw(raw.rs_reaper).ok_or(io::Errno::RANGE)?,
281 pid: if raw.rs_pid == -1 {
282 None
283 } else {
284 Some(Pid::from_raw(raw.rs_pid).ok_or(io::Errno::RANGE)?)
285 },
286 })
287 }
288
289 #[cfg(feature = "alloc")]
290 const PROC_REAP_GETPIDS: c_int = 5;
291
292 bitflags! {
293 /// `REAPER_PIDINFO_*`.
294 #[repr(transparent)]
295 #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
296 pub struct PidInfoFlags: c_uint {
297 /// This structure was filled by the kernel.
298 const VALID = 1;
299 /// The pid field identifies a direct child of the reaper.
300 const CHILD = 2;
301 /// The reported process is itself a reaper. Descendants of a
302 /// subordinate reaper are not reported.
303 const REAPER = 4;
304 /// The reported process is in the zombie state.
305 const ZOMBIE = 8;
306 /// The reported process is stopped by
307 /// [`Signal::Stop`]/[`Signal::Tstp`].
308 const STOPPED = 16;
309 /// The reported process is in the process of exiting.
310 const EXITING = 32;
311 }
312 }
313
314 #[repr(C)]
315 #[derive(Default, Clone)]
316 struct procctl_reaper_pidinfo {
317 pi_pid: RawPid,
318 pi_subtree: RawPid,
319 pi_flags: c_uint,
320 pi_pad0: [c_uint; 15],
321 }
322
323 #[repr(C)]
324 struct procctl_reaper_pids {
325 rp_count: c_uint,
326 rp_pad0: [c_uint; 15],
327 rp_pids: *mut procctl_reaper_pidinfo,
328 }
329
330 /// A child process of a reaper.
331 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
332 pub struct PidInfo {
333 /// The flags of the process.
334 pub flags: PidInfoFlags,
335 /// The pid of the process.
336 pub pid: Pid,
337 /// The pid of the child of the reaper which is the (grand-…)parent of the
338 /// process.
339 pub subtree: Pid,
340 }
341
342 /// Get the list of descendants of the specified reaper process.
343 ///
344 /// # References
345 /// - [FreeBSD: `procctl(PROC_REAP_GETPIDS,…)`]
346 ///
347 /// [FreeBSD: `procctl(PROC_REAP_GETPIDS,…)`]: https://man.freebsd.org/cgi/man.cgi?query=procctl&sektion=2
348 #[cfg(feature = "alloc")]
349 pub fn get_reaper_pids(process: ProcSelector) -> io::Result<Vec<PidInfo>> {
350 // Sadly no better way to guarantee that we get all the results than to
351 // allocate ≈8MB of memory…
352 const PID_MAX: usize = 99999;
353 let mut pids: Vec<procctl_reaper_pidinfo> = vec![Default::default(); PID_MAX];
354 let mut pinfo = procctl_reaper_pids {
355 rp_count: PID_MAX as _,
356 rp_pad0: [0; 15],
357 rp_pids: pids.as_mut_slice().as_mut_ptr(),
358 };
359 unsafe { procctl(PROC_REAP_GETPIDS, process, as_mut_ptr(&mut pinfo).cast())? };
360 let mut result = Vec::new();
361 for raw in pids.into_iter() {
362 let flags = PidInfoFlags::from_bits_retain(raw.pi_flags);
363 if !flags.contains(PidInfoFlags::VALID) {
364 break;
365 }
366 result.push(PidInfo {
367 flags,
368 subtree: Pid::from_raw(raw.pi_subtree).ok_or(io::Errno::RANGE)?,
369 pid: Pid::from_raw(raw.pi_pid).ok_or(io::Errno::RANGE)?,
370 });
371 }
372 Ok(result)
373 }
374
375 const PROC_REAP_KILL: c_int = 6;
376
377 bitflags! {
378 /// `REAPER_KILL_*`.
379 #[repr(transparent)]
380 #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
381 struct KillFlags: c_uint {
382 const CHILDREN = 1;
383 const SUBTREE = 2;
384 }
385 }
386
387 #[repr(C)]
388 struct procctl_reaper_kill {
389 rk_sig: c_int,
390 rk_flags: c_uint,
391 rk_subtree: RawPid,
392 rk_killed: c_uint,
393 rk_fpid: RawPid,
394 rk_pad0: [c_uint; 15],
395 }
396
397 /// Reaper status as returned by [`get_reaper_status`].
398 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
399 pub struct KillResult {
400 /// The number of processes that were signalled.
401 pub killed: usize,
402 /// The pid of the first process that wasn't successfully signalled.
403 pub first_failed: Option<Pid>,
404 }
405
406 /// Deliver a signal to some subset of the descendants of the reaper.
407 ///
408 /// # References
409 /// - [FreeBSD: `procctl(PROC_REAP_KILL,…)`]
410 ///
411 /// [FreeBSD: `procctl(PROC_REAP_KILL,…)`]: https://man.freebsd.org/cgi/man.cgi?query=procctl&sektion=2
412 pub fn reaper_kill(
413 process: ProcSelector,
414 signal: Signal,
415 direct_children: bool,
416 subtree: Option<Pid>,
417 ) -> io::Result<KillResult> {
418 let mut flags = KillFlags::empty();
419 flags.set(KillFlags::CHILDREN, direct_children);
420 flags.set(KillFlags::SUBTREE, subtree.is_some());
421 let mut req = procctl_reaper_kill {
422 rk_sig: signal as c_int,
423 rk_flags: flags.bits(),
424 rk_subtree: subtree.map(|p| p.as_raw_nonzero().into()).unwrap_or(0),
425 rk_killed: 0,
426 rk_fpid: 0,
427 rk_pad0: [0; 15],
428 };
429 unsafe { procctl(PROC_REAP_KILL, process, as_mut_ptr(&mut req).cast())? };
430 Ok(KillResult {
431 killed: req.rk_killed as _,
432 first_failed: Pid::from_raw(req.rk_fpid),
433 })
434 }
435
436 //
437 // PROC_TRAPCAP_STATUS/PROC_TRAPCAP_CTL
438 //
439
440 const PROC_TRAPCAP_CTL: c_int = 9;
441
442 const PROC_TRAPCAP_CTL_ENABLE: i32 = 1;
443 const PROC_TRAPCAP_CTL_DISABLE: i32 = 2;
444
445 /// `PROC_TRAPCAP_CTL_*`.
446 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
447 #[repr(i32)]
448 pub enum TrapCapBehavior {
449 /// Disable the [`Signal::Trap`] signal delivery on capability mode access
450 /// violations.
451 Disable = PROC_TRAPCAP_CTL_DISABLE,
452 /// Enable the [`Signal::Trap`] signal delivery on capability mode access
453 /// violations.
454 Enable = PROC_TRAPCAP_CTL_ENABLE,
455 }
456
457 /// Set the current value of the capability mode violation trapping behavior.
458 ///
459 /// If this behavior is enabled, the kernel would deliver a [`Signal::Trap`]
460 /// signal on any return from a system call that would result in a
461 /// [`io::Errno::NOTCAPABLE`] or [`io::Errno::CAPMODE`] error.
462 ///
463 /// This behavior is inherited by the children of the process and is kept
464 /// across `execve` calls.
465 ///
466 /// # References
467 /// - [FreeBSD: `procctl(PROC_TRAPCAP_CTL,…)`]
468 ///
469 /// [FreeBSD: `procctl(PROC_TRAPCAP_CTL,…)`]: https://man.freebsd.org/cgi/man.cgi?query=procctl&sektion=2
470 #[inline]
471 pub fn set_trap_cap_behavior(process: ProcSelector, config: TrapCapBehavior) -> io::Result<()> {
472 let config = config as c_int;
473 unsafe { procctl_set::<c_int>(PROC_TRAPCAP_CTL, process, &config) }
474 }
475
476 const PROC_TRAPCAP_STATUS: c_int = 10;
477
478 /// Get the current value of the capability mode violation trapping behavior.
479 ///
480 /// # References
481 /// - [FreeBSD: `procctl(PROC_TRAPCAP_STATUS,…)`]
482 ///
483 /// [FreeBSD: `procctl(PROC_TRAPCAP_STATUS,…)`]: https://man.freebsd.org/cgi/man.cgi?query=procctl&sektion=2
484 #[inline]
485 pub fn trap_cap_behavior(process: ProcSelector) -> io::Result<TrapCapBehavior> {
486 let val = unsafe { procctl_get_optional::<c_int>(PROC_TRAPCAP_STATUS, process) }?;
487 match val {
488 PROC_TRAPCAP_CTL_DISABLE => Ok(TrapCapBehavior::Disable),
489 PROC_TRAPCAP_CTL_ENABLE => Ok(TrapCapBehavior::Enable),
490 _ => Err(io::Errno::RANGE),
491 }
492 }
493
494 //
495 // PROC_NO_NEW_PRIVS_STATUS/PROC_NO_NEW_PRIVS_CTL
496 //
497
498 const PROC_NO_NEW_PRIVS_CTL: c_int = 19;
499
500 const PROC_NO_NEW_PRIVS_ENABLE: c_int = 1;
501
502 /// Enable the `no_new_privs` mode that ignores SUID and SGID bits on `execve`
503 /// in the specified process and its future descendants.
504 ///
505 /// This is similar to `set_no_new_privs` on Linux, with the exception that on
506 /// FreeBSD there is no argument `no_new_privs` argument as it's only possible
507 /// to enable this mode and there's no going back.
508 ///
509 /// # References
510 /// - [Linux: `prctl(PR_SET_NO_NEW_PRIVS,…)`]
511 /// - [FreeBSD: `procctl(PROC_NO_NEW_PRIVS_CTL,…)`]
512 ///
513 /// [Linux: `prctl(PR_SET_NO_NEW_PRIVS,…)`]: https://man7.org/linux/man-pages/man2/prctl.2.html
514 /// [FreeBSD: `procctl(PROC_NO_NEW_PRIVS_CTL,…)`]: https://man.freebsd.org/cgi/man.cgi?query=procctl&sektion=2
515 #[inline]
516 pub fn set_no_new_privs(process: ProcSelector) -> io::Result<()> {
517 unsafe { procctl_set::<c_int>(PROC_NO_NEW_PRIVS_CTL, process, &PROC_NO_NEW_PRIVS_ENABLE) }
518 }
519
520 const PROC_NO_NEW_PRIVS_STATUS: c_int = 20;
521
522 /// Check the `no_new_privs` mode of the specified process.
523 ///
524 /// # References
525 /// - [Linux: `prctl(PR_GET_NO_NEW_PRIVS,…)`]
526 /// - [FreeBSD: `procctl(PROC_NO_NEW_PRIVS_STATUS,…)`]
527 ///
528 /// [Linux: `prctl(PR_GET_NO_NEW_PRIVS,…)`]: https://man7.org/linux/man-pages/man2/prctl.2.html
529 /// [FreeBSD: `procctl(PROC_NO_NEW_PRIVS_STATUS,…)`]: https://man.freebsd.org/cgi/man.cgi?query=procctl&sektion=2
530 #[inline]
531 pub fn no_new_privs(process: ProcSelector) -> io::Result<bool> {
532 unsafe { procctl_get_optional::<c_int>(PROC_NO_NEW_PRIVS_STATUS, process) }
533 .map(|x| x == PROC_NO_NEW_PRIVS_ENABLE)
534 }