Debian Codegraph @

debian/rust-vendor/rlimit/src/tools.rs

raw
1 use std::io;
2
3 /// Returns the value of `kern.maxfilesperproc` by sysctl.
4 /// # Errors
5 /// Returns an error if any syscall failed.
6 #[cfg(rlimit__get_kern_max_files_per_proc)]
7 fn get_kern_max_files_per_proc() -> io::Result<u64> {
8 use std::mem;
9 use std::ptr;
10
11 let mut mib = [libc::CTL_KERN, libc::KERN_MAXFILESPERPROC];
12 let mut max_files_per_proc: libc::c_int = 0;
13 let mut oldlen = mem::size_of::<libc::c_int>();
14 let ret = unsafe {
15 libc::sysctl(
16 mib.as_mut_ptr(),
17 2,
18 &mut max_files_per_proc as *mut libc::c_int as *mut libc::c_void,
19 &mut oldlen,
20 ptr::null_mut(),
21 0,
22 )
23 };
24
25 if ret < 0 {
26 return Err(io::Error::last_os_error());
27 }
28
29 // SAFETY: sysctl should return a non-negative value for KERN_MAXFILESPERPROC.
30 // Casting a non-negative c_int to u64 is always safe (widening conversion).
31 debug_assert!(max_files_per_proc >= 0);
32 Ok(max_files_per_proc as u64)
33 }
34
35 /// Try to increase NOFILE limit and return the current soft limit.
36 ///
37 /// `lim` is the expected limit which can be up to [`u64::MAX`].
38 ///
39 /// This function does nothing and returns `Ok(lim)`
40 /// if `RLIMIT_NOFILE` does not exist on current platform.
41 ///
42 /// # Errors
43 /// Returns an error if any syscall failed.
44 pub fn increase_nofile_limit(lim: u64) -> io::Result<u64> {
45 #[cfg(unix)]
46 {
47 use crate::Resource;
48
49 if !Resource::NOFILE.is_supported() {
50 return Ok(lim);
51 }
52
53 let (soft, hard) = Resource::NOFILE.get()?;
54
55 if soft >= hard {
56 return Ok(hard);
57 }
58
59 if soft >= lim {
60 return Ok(soft);
61 }
62
63 let mut lim = lim;
64
65 lim = lim.min(hard);
66
67 #[cfg(rlimit__get_kern_max_files_per_proc)]
68 {
69 lim = lim.min(get_kern_max_files_per_proc()?)
70 }
71
72 Resource::NOFILE.set(lim, hard)?;
73
74 Ok(lim)
75 }
76 #[cfg(windows)]
77 {
78 Ok(lim)
79 }
80 }