compiletest/
raise_fd_limit.rs

1/// darwin_fd_limit exists to work around an issue where launchctl on macOS
2/// defaults the rlimit maxfiles to 256/unlimited. The default soft limit of 256
3/// ends up being far too low for our multithreaded scheduler testing, depending
4/// on the number of cores available.
5///
6/// This fixes issue #7772.
7#[cfg(target_vendor = "apple")]
8#[allow(non_camel_case_types)]
9// FIXME(#139616): document caller contract.
10pub unsafe fn raise_fd_limit() {
11    use std::ptr::null_mut;
12    use std::{cmp, io};
13
14    static CTL_KERN: libc::c_int = 1;
15    static KERN_MAXFILESPERPROC: libc::c_int = 29;
16
17    // The strategy here is to fetch the current resource limits, read the
18    // kern.maxfilesperproc sysctl value, and bump the soft resource limit for
19    // maxfiles up to the sysctl value.
20
21    // Fetch the kern.maxfilesperproc value
22    let mut mib: [libc::c_int; 2] = [CTL_KERN, KERN_MAXFILESPERPROC];
23    let mut maxfiles: libc::c_int = 0;
24    let mut size: libc::size_t = size_of_val(&maxfiles) as libc::size_t;
25    // FIXME(#139616): justify why this is sound.
26    if unsafe {
27        libc::sysctl(&mut mib[0], 2, &mut maxfiles as *mut _ as *mut _, &mut size, null_mut(), 0)
28    } != 0
29    {
30        let err = io::Error::last_os_error();
31        panic!("raise_fd_limit: error calling sysctl: {}", err);
32    }
33
34    // Fetch the current resource limits
35    let mut rlim = libc::rlimit { rlim_cur: 0, rlim_max: 0 };
36    // FIXME(#139616): justify why this is sound.
37    if unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &mut rlim) } != 0 {
38        let err = io::Error::last_os_error();
39        panic!("raise_fd_limit: error calling getrlimit: {}", err);
40    }
41
42    // Make sure we're only ever going to increase the rlimit.
43    if rlim.rlim_cur < maxfiles as libc::rlim_t {
44        // Bump the soft limit to the smaller of kern.maxfilesperproc and the hard limit.
45        rlim.rlim_cur = cmp::min(maxfiles as libc::rlim_t, rlim.rlim_max);
46
47        // Set our newly-increased resource limit.
48        // FIXME(#139616): justify why this is sound.
49        if unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, &rlim) } != 0 {
50            let err = io::Error::last_os_error();
51            panic!("raise_fd_limit: error calling setrlimit: {}", err);
52        }
53    }
54}
55
56#[cfg(not(target_vendor = "apple"))]
57pub unsafe fn raise_fd_limit() {}