Debian Codegraph @

debian/rust-vendor/nix/src/sys/resource.rs

raw
1 //! Configure the process resource limits.
2 use cfg_if::cfg_if;
3 use libc::{c_int, c_long, rusage};
4
5 use crate::errno::Errno;
6 use crate::sys::time::TimeVal;
7 use crate::Result;
8 pub use libc::rlim_t;
9 pub use libc::RLIM_INFINITY;
10 use std::mem;
11
12 cfg_if! {
13 if #[cfg(any(
14 all(target_os = "linux", any(target_env = "gnu", target_env = "uclibc")),
15 target_os = "hurd"
16 ))]{
17 use libc::{__rlimit_resource_t, rlimit};
18 } else if #[cfg(any(
19 bsd,
20 target_os = "android",
21 target_os = "aix",
22 target_os = "illumos",
23 all(target_os = "linux", not(target_env = "gnu")),
24 target_os = "cygwin"
25 ))]{
26 use libc::rlimit;
27 }
28 }
29
30 libc_enum! {
31 /// Types of process resources.
32 ///
33 /// The Resource enum is platform dependent. Check different platform
34 /// manuals for more details. Some platform links have been provided for
35 /// easier reference (non-exhaustive).
36 ///
37 /// * [Linux](https://man7.org/linux/man-pages/man2/getrlimit.2.html)
38 /// * [FreeBSD](https://www.freebsd.org/cgi/man.cgi?query=setrlimit)
39 /// * [NetBSD](https://man.netbsd.org/setrlimit.2)
40
41 // linux-gnu uses u_int as resource enum, which is implemented in libc as
42 // well.
43 //
44 // https://gcc.gnu.org/legacy-ml/gcc/2015-08/msg00441.html
45 // https://github.com/rust-lang/libc/blob/master/src/unix/linux_like/linux/gnu/mod.rs
46 #[cfg_attr(any(
47 all(target_os = "linux", any(target_env = "gnu", target_env = "uclibc")),
48 target_os = "hurd"
49 ), repr(u32))]
50 #[cfg_attr(any(
51 bsd,
52 target_os = "android",
53 target_os = "aix",
54 target_os = "illumos",
55 all(target_os = "linux", not(any(target_env = "gnu", target_env = "uclibc"))),
56 target_os = "cygwin"
57 ), repr(i32))]
58 #[non_exhaustive]
59 pub enum Resource {
60 #[cfg(not(any(target_os = "freebsd", netbsdlike)))]
61 /// The maximum amount (in bytes) of virtual memory the process is
62 /// allowed to map.
63 RLIMIT_AS,
64 /// The largest size (in bytes) core(5) file that may be created.
65 RLIMIT_CORE,
66 /// The maximum amount of cpu time (in seconds) to be used by each
67 /// process.
68 RLIMIT_CPU,
69 /// The maximum size (in bytes) of the data segment for a process
70 RLIMIT_DATA,
71 /// The largest size (in bytes) file that may be created.
72 RLIMIT_FSIZE,
73 /// The maximum number of open files for this process.
74 RLIMIT_NOFILE,
75 /// The maximum size (in bytes) of the stack segment for a process.
76 RLIMIT_STACK,
77
78 #[cfg(target_os = "freebsd")]
79 /// The maximum number of kqueues this user id is allowed to create.
80 RLIMIT_KQUEUES,
81
82 #[cfg(linux_android)]
83 /// A limit on the combined number of flock locks and fcntl leases that
84 /// this process may establish.
85 RLIMIT_LOCKS,
86
87 #[cfg(any(linux_android, target_os = "freebsd", netbsdlike))]
88 /// The maximum size (in bytes) which a process may lock into memory
89 /// using the mlock(2) system call.
90 RLIMIT_MEMLOCK,
91
92 #[cfg(linux_android)]
93 /// A limit on the number of bytes that can be allocated for POSIX
94 /// message queues for the real user ID of the calling process.
95 RLIMIT_MSGQUEUE,
96
97 #[cfg(linux_android)]
98 /// A ceiling to which the process's nice value can be raised using
99 /// setpriority or nice.
100 RLIMIT_NICE,
101
102 #[cfg(any(
103 linux_android,
104 target_os = "freebsd",
105 netbsdlike,
106 target_os = "aix",
107 ))]
108 /// The maximum number of simultaneous processes for this user id.
109 RLIMIT_NPROC,
110
111 #[cfg(target_os = "freebsd")]
112 /// The maximum number of pseudo-terminals this user id is allowed to
113 /// create.
114 RLIMIT_NPTS,
115
116 #[cfg(any(linux_android,
117 target_os = "freebsd",
118 netbsdlike,
119 target_os = "aix",
120 ))]
121 /// When there is memory pressure and swap is available, prioritize
122 /// eviction of a process' resident pages beyond this amount (in bytes).
123 RLIMIT_RSS,
124
125 #[cfg(linux_android)]
126 /// A ceiling on the real-time priority that may be set for this process
127 /// using sched_setscheduler and sched_set‐ param.
128 RLIMIT_RTPRIO,
129
130 #[cfg(any(target_os = "linux"))]
131 /// A limit (in microseconds) on the amount of CPU time that a process
132 /// scheduled under a real-time scheduling policy may con‐ sume without
133 /// making a blocking system call.
134 RLIMIT_RTTIME,
135
136 #[cfg(linux_android)]
137 /// A limit on the number of signals that may be queued for the real
138 /// user ID of the calling process.
139 RLIMIT_SIGPENDING,
140
141 #[cfg(freebsdlike)]
142 /// The maximum size (in bytes) of socket buffer usage for this user.
143 RLIMIT_SBSIZE,
144
145 #[cfg(target_os = "freebsd")]
146 /// The maximum size (in bytes) of the swap space that may be reserved
147 /// or used by all of this user id's processes.
148 RLIMIT_SWAP,
149
150 #[cfg(target_os = "freebsd")]
151 /// An alias for RLIMIT_AS.
152 RLIMIT_VMEM,
153 }
154 }
155
156 /// Get the current processes resource limits
157 ///
158 /// The special value [`RLIM_INFINITY`] indicates that no limit will be
159 /// enforced.
160 ///
161 /// # Parameters
162 ///
163 /// * `resource`: The [`Resource`] that we want to get the limits of.
164 ///
165 /// # Examples
166 ///
167 /// ```
168 /// # use nix::sys::resource::{getrlimit, Resource};
169 ///
170 /// let (soft_limit, hard_limit) = getrlimit(Resource::RLIMIT_NOFILE).unwrap();
171 /// println!("current soft_limit: {}", soft_limit);
172 /// println!("current hard_limit: {}", hard_limit);
173 /// ```
174 ///
175 /// # References
176 ///
177 /// [getrlimit(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/getrlimit.html#tag_16_215)
178 ///
179 /// [`Resource`]: enum.Resource.html
180 pub fn getrlimit(resource: Resource) -> Result<(rlim_t, rlim_t)> {
181 let mut old_rlim = mem::MaybeUninit::<rlimit>::uninit();
182
183 cfg_if! {
184 if #[cfg(any(
185 all(target_os = "linux", any(target_env = "gnu", target_env = "uclibc")),
186 target_os = "hurd"
187 ))] {
188 let res = unsafe { libc::getrlimit(resource as __rlimit_resource_t, old_rlim.as_mut_ptr()) };
189 } else {
190 let res = unsafe { libc::getrlimit(resource as c_int, old_rlim.as_mut_ptr()) };
191 }
192 }
193
194 Errno::result(res).map(|_| {
195 let rlimit { rlim_cur, rlim_max } = unsafe { old_rlim.assume_init() };
196 (rlim_cur, rlim_max)
197 })
198 }
199
200 /// Set the current processes resource limits
201 ///
202 /// # Parameters
203 ///
204 /// * `resource`: The [`Resource`] that we want to set the limits of.
205 /// * `soft_limit`: The value that the kernel enforces for the corresponding
206 /// resource.
207 /// * `hard_limit`: The ceiling for the soft limit. Must be lower or equal to
208 /// the current hard limit for non-root users.
209 ///
210 /// The special value [`RLIM_INFINITY`] indicates that no limit will be
211 /// enforced.
212 ///
213 /// # Examples
214 ///
215 /// ```
216 /// # use nix::sys::resource::{setrlimit, Resource};
217 ///
218 /// let soft_limit = 512;
219 /// let hard_limit = 1024;
220 /// setrlimit(Resource::RLIMIT_NOFILE, soft_limit, hard_limit).unwrap();
221 /// ```
222 ///
223 /// # References
224 ///
225 /// [setrlimit(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/getrlimit.html#tag_16_215)
226 ///
227 /// [`Resource`]: enum.Resource.html
228 ///
229 /// Note: `setrlimit` provides a safe wrapper to libc's `setrlimit`.
230 pub fn setrlimit(
231 resource: Resource,
232 soft_limit: rlim_t,
233 hard_limit: rlim_t,
234 ) -> Result<()> {
235 let new_rlim = rlimit {
236 rlim_cur: soft_limit,
237 rlim_max: hard_limit,
238 };
239 cfg_if! {
240 if #[cfg(any(
241 all(target_os = "linux", any(target_env = "gnu", target_env = "uclibc")),
242 target_os = "hurd",
243 ))]{
244 let res = unsafe { libc::setrlimit(resource as __rlimit_resource_t, &new_rlim as *const rlimit) };
245 }else{
246 let res = unsafe { libc::setrlimit(resource as c_int, &new_rlim as *const rlimit) };
247 }
248 }
249
250 Errno::result(res).map(drop)
251 }
252
253 libc_enum! {
254 /// Whose resource usage should be returned by [`getrusage`].
255 #[repr(i32)]
256 #[non_exhaustive]
257 pub enum UsageWho {
258 /// Resource usage for the current process.
259 RUSAGE_SELF,
260
261 /// Resource usage for all the children that have terminated and been waited for.
262 RUSAGE_CHILDREN,
263
264 #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
265 /// Resource usage for the calling thread.
266 RUSAGE_THREAD,
267 }
268 }
269
270 /// Output of `getrusage` with information about resource usage. Some of the fields
271 /// may be unused in some platforms, and will be always zeroed out. See their manuals
272 /// for details.
273 #[repr(transparent)]
274 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
275 pub struct Usage(rusage);
276
277 impl AsRef<rusage> for Usage {
278 fn as_ref(&self) -> &rusage {
279 &self.0
280 }
281 }
282
283 impl AsMut<rusage> for Usage {
284 fn as_mut(&mut self) -> &mut rusage {
285 &mut self.0
286 }
287 }
288
289 impl Usage {
290 /// Total amount of time spent executing in user mode.
291 pub fn user_time(&self) -> TimeVal {
292 TimeVal::from(self.0.ru_utime)
293 }
294
295 /// Total amount of time spent executing in kernel mode.
296 pub fn system_time(&self) -> TimeVal {
297 TimeVal::from(self.0.ru_stime)
298 }
299
300 /// The resident set size at its peak,
301 #[cfg_attr(apple_targets, doc = " in bytes.")]
302 #[cfg_attr(not(apple_targets), doc = " in kilobytes.")]
303 pub fn max_rss(&self) -> c_long {
304 self.0.ru_maxrss
305 }
306
307 /// Integral value expressed in kilobytes times ticks of execution indicating
308 /// the amount of text memory shared with other processes.
309 pub fn shared_integral(&self) -> c_long {
310 self.0.ru_ixrss
311 }
312
313 /// Integral value expressed in kilobytes times ticks of execution indicating
314 /// the amount of unshared memory used by data.
315 pub fn unshared_data_integral(&self) -> c_long {
316 self.0.ru_idrss
317 }
318
319 /// Integral value expressed in kilobytes times ticks of execution indicating
320 /// the amount of unshared memory used for stack space.
321 pub fn unshared_stack_integral(&self) -> c_long {
322 self.0.ru_isrss
323 }
324
325 /// Number of page faults that were served without resorting to I/O, with pages
326 /// that have been allocated previously by the kernel.
327 pub fn minor_page_faults(&self) -> c_long {
328 self.0.ru_minflt
329 }
330
331 /// Number of page faults that were served through I/O (i.e. swap).
332 pub fn major_page_faults(&self) -> c_long {
333 self.0.ru_majflt
334 }
335
336 /// Number of times all of the memory was fully swapped out.
337 pub fn full_swaps(&self) -> c_long {
338 self.0.ru_nswap
339 }
340
341 /// Number of times a read was done from a block device.
342 pub fn block_reads(&self) -> c_long {
343 self.0.ru_inblock
344 }
345
346 /// Number of times a write was done to a block device.
347 pub fn block_writes(&self) -> c_long {
348 self.0.ru_oublock
349 }
350
351 /// Number of IPC messages sent.
352 pub fn ipc_sends(&self) -> c_long {
353 self.0.ru_msgsnd
354 }
355
356 /// Number of IPC messages received.
357 pub fn ipc_receives(&self) -> c_long {
358 self.0.ru_msgrcv
359 }
360
361 /// Number of signals received.
362 pub fn signals(&self) -> c_long {
363 self.0.ru_nsignals
364 }
365
366 /// Number of times a context switch was voluntarily invoked.
367 pub fn voluntary_context_switches(&self) -> c_long {
368 self.0.ru_nvcsw
369 }
370
371 /// Number of times a context switch was imposed by the kernel (usually due to
372 /// time slice expiring or preemption by a higher priority process).
373 pub fn involuntary_context_switches(&self) -> c_long {
374 self.0.ru_nivcsw
375 }
376 }
377
378 /// Get usage information for a process, its children or the current thread
379 ///
380 /// Real time information can be obtained for either the current process or (in some
381 /// systems) thread, but information about children processes is only provided for
382 /// those that have terminated and been waited for (see [`super::wait::wait`]).
383 ///
384 /// Some information may be missing depending on the platform, and the way information
385 /// is provided for children may also vary. Check the manuals for details.
386 ///
387 /// # References
388 ///
389 /// * [getrusage(2)](https://pubs.opengroup.org/onlinepubs/009696699/functions/getrusage.html)
390 /// * [Linux](https://man7.org/linux/man-pages/man2/getrusage.2.html)
391 /// * [FreeBSD](https://www.freebsd.org/cgi/man.cgi?query=getrusage)
392 /// * [NetBSD](https://man.netbsd.org/getrusage.2)
393 /// * [MacOS](https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/getrusage.2.html)
394 ///
395 /// [`UsageWho`]: enum.UsageWho.html
396 ///
397 /// Note: `getrusage` provides a safe wrapper to libc's [`libc::getrusage`].
398 pub fn getrusage(who: UsageWho) -> Result<Usage> {
399 unsafe {
400 let mut rusage = mem::MaybeUninit::<rusage>::uninit();
401 let res = libc::getrusage(who as c_int, rusage.as_mut_ptr());
402 Errno::result(res).map(|_| Usage(rusage.assume_init()))
403 }
404 }