nix/sys/
prctl.rs

1//! prctl is a Linux-only API for performing operations on a process or thread.
2//!
3//! Note that careless use of some prctl() operations can confuse the user-space run-time
4//! environment, so these operations should be used with care.
5//!
6//! For more documentation, please read [prctl(2)](https://man7.org/linux/man-pages/man2/prctl.2.html).
7
8use crate::errno::Errno;
9use crate::sys::signal::Signal;
10use crate::Result;
11
12use libc::{c_int, c_ulong};
13use std::convert::TryFrom;
14use std::ffi::{CStr, CString};
15
16libc_enum! {
17    /// The type of hardware memory corruption kill policy for the thread.
18
19    #[repr(i32)]
20    #[non_exhaustive]
21    #[allow(non_camel_case_types)]
22    pub enum PrctlMCEKillPolicy {
23        /// The thread will receive SIGBUS as soon as a memory corruption is detected.
24        PR_MCE_KILL_EARLY,
25        /// The process is killed only when it accesses a corrupted page.
26        PR_MCE_KILL_LATE,
27        /// Uses the system-wide default.
28        PR_MCE_KILL_DEFAULT,
29    }
30    impl TryFrom<i32>
31}
32
33fn prctl_set_bool(option: c_int, status: bool) -> Result<()> {
34    let res = unsafe { libc::prctl(option, status as c_ulong, 0, 0, 0) };
35    Errno::result(res).map(drop)
36}
37
38fn prctl_get_bool(option: c_int) -> Result<bool> {
39    let res = unsafe { libc::prctl(option, 0, 0, 0, 0) };
40    Errno::result(res).map(|res| res != 0)
41}
42
43/// Set the "child subreaper" attribute for this process
44pub fn set_child_subreaper(attribute: bool) -> Result<()> {
45    prctl_set_bool(libc::PR_SET_CHILD_SUBREAPER, attribute)
46}
47
48/// Get the "child subreaper" attribute for this process
49pub fn get_child_subreaper() -> Result<bool> {
50    // prctl writes into this var
51    let mut subreaper: c_int = 0;
52
53    let res = unsafe {
54        libc::prctl(libc::PR_GET_CHILD_SUBREAPER, &mut subreaper, 0, 0, 0)
55    };
56
57    Errno::result(res).map(|_| subreaper != 0)
58}
59
60/// Set the dumpable attribute which determines if core dumps are created for this process.
61pub fn set_dumpable(attribute: bool) -> Result<()> {
62    prctl_set_bool(libc::PR_SET_DUMPABLE, attribute)
63}
64
65/// Get the dumpable attribute for this process.
66pub fn get_dumpable() -> Result<bool> {
67    prctl_get_bool(libc::PR_GET_DUMPABLE)
68}
69
70/// Set the "keep capabilities" attribute for this process. This causes the thread to retain
71/// capabilities even if it switches its UID to a nonzero value.
72pub fn set_keepcaps(attribute: bool) -> Result<()> {
73    prctl_set_bool(libc::PR_SET_KEEPCAPS, attribute)
74}
75
76/// Get the "keep capabilities" attribute for this process
77pub fn get_keepcaps() -> Result<bool> {
78    prctl_get_bool(libc::PR_GET_KEEPCAPS)
79}
80
81/// Clear the thread memory corruption kill policy and use the system-wide default
82pub fn clear_mce_kill() -> Result<()> {
83    let res = unsafe {
84        libc::prctl(libc::PR_MCE_KILL, libc::PR_MCE_KILL_CLEAR, 0, 0, 0)
85    };
86
87    Errno::result(res).map(drop)
88}
89
90/// Set the thread memory corruption kill policy
91pub fn set_mce_kill(policy: PrctlMCEKillPolicy) -> Result<()> {
92    let res = unsafe {
93        libc::prctl(
94            libc::PR_MCE_KILL,
95            libc::PR_MCE_KILL_SET,
96            policy as c_ulong,
97            0,
98            0,
99        )
100    };
101
102    Errno::result(res).map(drop)
103}
104
105/// Get the thread memory corruption kill policy
106pub fn get_mce_kill() -> Result<PrctlMCEKillPolicy> {
107    let res = unsafe { libc::prctl(libc::PR_MCE_KILL_GET, 0, 0, 0, 0) };
108
109    match Errno::result(res) {
110        Ok(val) => Ok(PrctlMCEKillPolicy::try_from(val)?),
111        Err(e) => Err(e),
112    }
113}
114
115/// Set the parent-death signal of the calling process. This is the signal that the calling process
116/// will get when its parent dies.
117pub fn set_pdeathsig<T: Into<Option<Signal>>>(signal: T) -> Result<()> {
118    let sig = match signal.into() {
119        Some(s) => s as c_int,
120        None => 0,
121    };
122
123    let res = unsafe { libc::prctl(libc::PR_SET_PDEATHSIG, sig, 0, 0, 0) };
124
125    Errno::result(res).map(drop)
126}
127
128/// Returns the current parent-death signal
129pub fn get_pdeathsig() -> Result<Option<Signal>> {
130    // prctl writes into this var
131    let mut sig: c_int = 0;
132
133    let res = unsafe { libc::prctl(libc::PR_GET_PDEATHSIG, &mut sig, 0, 0, 0) };
134
135    match Errno::result(res) {
136        Ok(_) => Ok(match sig {
137            0 => None,
138            _ => Some(Signal::try_from(sig)?),
139        }),
140        Err(e) => Err(e),
141    }
142}
143
144/// Set the name of the calling thread. Strings longer than 15 bytes will be truncated.
145pub fn set_name(name: &CStr) -> Result<()> {
146    let res = unsafe { libc::prctl(libc::PR_SET_NAME, name.as_ptr(), 0, 0, 0) };
147
148    Errno::result(res).map(drop)
149}
150
151/// Return the name of the calling thread
152pub fn get_name() -> Result<CString> {
153    // Size of buffer determined by linux/sched.h TASK_COMM_LEN
154    let buf = [0u8; 16];
155
156    let res = unsafe { libc::prctl(libc::PR_GET_NAME, &buf, 0, 0, 0) };
157
158    Errno::result(res).and_then(|_| {
159        CStr::from_bytes_until_nul(&buf)
160            .map(CStr::to_owned)
161            .map_err(|_| Errno::EINVAL)
162    })
163}
164
165/// Sets the timer slack value for the calling thread. Timer slack is used by the kernel to group
166/// timer expirations and make them the supplied amount of nanoseconds late.
167pub fn set_timerslack(ns: u64) -> Result<()> {
168    let res = unsafe { libc::prctl(libc::PR_SET_TIMERSLACK, ns, 0, 0, 0) };
169
170    Errno::result(res).map(drop)
171}
172
173/// Get the timerslack for the calling thread.
174pub fn get_timerslack() -> Result<i32> {
175    let res = unsafe { libc::prctl(libc::PR_GET_TIMERSLACK, 0, 0, 0, 0) };
176
177    Errno::result(res)
178}
179
180/// Disable all performance counters attached to the calling process.
181pub fn task_perf_events_disable() -> Result<()> {
182    let res =
183        unsafe { libc::prctl(libc::PR_TASK_PERF_EVENTS_DISABLE, 0, 0, 0, 0) };
184
185    Errno::result(res).map(drop)
186}
187
188/// Enable all performance counters attached to the calling process.
189pub fn task_perf_events_enable() -> Result<()> {
190    let res =
191        unsafe { libc::prctl(libc::PR_TASK_PERF_EVENTS_ENABLE, 0, 0, 0, 0) };
192
193    Errno::result(res).map(drop)
194}
195
196/// Set the calling threads "no new privs" attribute. Once set this option can not be unset.
197pub fn set_no_new_privs() -> Result<()> {
198    prctl_set_bool(libc::PR_SET_NO_NEW_PRIVS, true) // Cannot be unset
199}
200
201/// Get the "no new privs" attribute for the calling thread.
202pub fn get_no_new_privs() -> Result<bool> {
203    prctl_get_bool(libc::PR_GET_NO_NEW_PRIVS)
204}
205
206/// Set the state of the "THP disable" flag for the calling thread. Setting this disables
207/// transparent huge pages.
208pub fn set_thp_disable(flag: bool) -> Result<()> {
209    prctl_set_bool(libc::PR_SET_THP_DISABLE, flag)
210}
211
212/// Get the "THP disable" flag for the calling thread.
213pub fn get_thp_disable() -> Result<bool> {
214    prctl_get_bool(libc::PR_GET_THP_DISABLE)
215}