Vendor asic-rs 0.8.1 (280 crates, offline builds) + wxWidgets 3.3.3 (pristine + patch queue); UI spec + ADR-0003; M1 on asic-rs
This commit is contained in:
Vendored
+4638
File diff suppressed because it is too large
Load Diff
Vendored
+144
@@ -0,0 +1,144 @@
|
||||
//! rlimit - Resource limits.
|
||||
//!
|
||||
//! ## Set resource limit
|
||||
//! ```no_run
|
||||
//! # #[cfg(unix)]
|
||||
//! # {
|
||||
//! use rlimit::{setrlimit, Resource};
|
||||
//!
|
||||
//! const DEFAULT_SOFT_LIMIT: u64 = 4 * 1024 * 1024;
|
||||
//! const DEFAULT_HARD_LIMIT: u64 = 8 * 1024 * 1024;
|
||||
//! assert!(Resource::FSIZE.set(DEFAULT_SOFT_LIMIT, DEFAULT_HARD_LIMIT).is_ok());
|
||||
//!
|
||||
//! let soft = 16384;
|
||||
//! let hard = soft * 2;
|
||||
//! assert!(setrlimit(Resource::NOFILE, soft, hard).is_ok());
|
||||
//! # }
|
||||
//! ```
|
||||
//!
|
||||
//! ## Get resource limit
|
||||
//! ```no_run
|
||||
//! # #[cfg(unix)]
|
||||
//! # {
|
||||
//! use rlimit::{getrlimit, Resource};
|
||||
//!
|
||||
//! assert!(Resource::NOFILE.get().is_ok());
|
||||
//! assert_eq!(getrlimit(Resource::CPU).unwrap(), (rlimit::INFINITY, rlimit::INFINITY));
|
||||
//! # }
|
||||
//! ```
|
||||
//!
|
||||
//! ## Windows
|
||||
//!
|
||||
//! Windows does not have Unix-like resource limits.
|
||||
//! It only supports changing the number of simultaneously open files currently permitted at the stdio level.
|
||||
//!
|
||||
//! See the official documentation of
|
||||
//! [`_getmaxstdio`](https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/getmaxstdio?view=msvc-170)
|
||||
//! and
|
||||
//! [`_setmaxstdio`](https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/setmaxstdio?view=msvc-170).
|
||||
//!
|
||||
//! ```no_run
|
||||
//! # #[cfg(windows)]
|
||||
//! # {
|
||||
//! println!("{}", rlimit::getmaxstdio()); // 512
|
||||
//! rlimit::setmaxstdio(2048).unwrap();
|
||||
//! println!("{}", rlimit::getmaxstdio()); // 2048
|
||||
//! # }
|
||||
//! ```
|
||||
//!
|
||||
//! ## Increase NOFILE limit
|
||||
//! See the example [nofile](https://github.com/Nugine/rlimit/blob/main/examples/nofile.rs).
|
||||
//!
|
||||
//! You can also use the tool function [`rlimit::increase_nofile_limit`][`crate::increase_nofile_limit`]
|
||||
//!
|
||||
//! ```no_run
|
||||
//! rlimit::increase_nofile_limit(10240).unwrap();
|
||||
//! rlimit::increase_nofile_limit(u64::MAX).unwrap();
|
||||
//! ```
|
||||
//!
|
||||
//! # Troubleshoot
|
||||
//!
|
||||
//! ## Failed to increase NOFILE to hard limit on macOS
|
||||
//! On macOS, getrlimit by default reports that the hard limit is
|
||||
//! unlimited, but there is usually a stricter hard limit discoverable
|
||||
//! via sysctl (`kern.maxfilesperproc`). Failing to discover this secret stricter hard limit will
|
||||
//! cause the call to setrlimit to fail.
|
||||
//!
|
||||
//! [`rlimit::increase_nofile_limit`][`crate::increase_nofile_limit`]
|
||||
//! respects `kern.maxfilesperproc`.
|
||||
//!
|
||||
|
||||
#![cfg_attr(docsrs, feature(doc_cfg))]
|
||||
#![deny(
|
||||
missing_docs,
|
||||
missing_debug_implementations,
|
||||
clippy::all,
|
||||
clippy::pedantic,
|
||||
clippy::cargo
|
||||
)]
|
||||
#![allow(
|
||||
clippy::option_if_let_else, // I don't like it. The match expression is more readable.
|
||||
)]
|
||||
|
||||
#[allow(unused_macros)]
|
||||
macro_rules! group {
|
||||
($($item:item)*) => {
|
||||
$($item)*
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(doc, windows))]
|
||||
group! {
|
||||
mod windows;
|
||||
|
||||
#[doc(inline)]
|
||||
pub use self::windows::*;
|
||||
}
|
||||
|
||||
#[cfg(any(doc, unix))]
|
||||
group! {
|
||||
mod bindings;
|
||||
|
||||
mod unix;
|
||||
mod resource;
|
||||
|
||||
#[doc(inline)]
|
||||
pub use self::unix::*;
|
||||
|
||||
#[doc(inline)]
|
||||
pub use self::resource::Resource;
|
||||
}
|
||||
|
||||
#[cfg(any(doc, target_os = "linux", target_os = "android"))]
|
||||
group! {
|
||||
mod proc_limits;
|
||||
|
||||
#[doc(inline)]
|
||||
pub use self::proc_limits::*;
|
||||
|
||||
mod sys_limits;
|
||||
|
||||
#[doc(inline)]
|
||||
pub use self::sys_limits::*;
|
||||
}
|
||||
|
||||
mod tools;
|
||||
#[doc(inline)]
|
||||
pub use self::tools::*;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[allow(clippy::assertions_on_constants)]
|
||||
#[test]
|
||||
fn build_cfg() {
|
||||
if cfg!(target_os = "linux") || cfg!(target_os = "android") {
|
||||
assert!(cfg!(rlimit__has_prlimit64));
|
||||
assert!(cfg!(not(rlimit__get_kern_max_files_per_proc)));
|
||||
}
|
||||
|
||||
if cfg!(target_os = "macos") {
|
||||
assert!(cfg!(not(rlimit__has_prlimit64)));
|
||||
assert!(cfg!(rlimit__get_kern_max_files_per_proc));
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+185
@@ -0,0 +1,185 @@
|
||||
#![deny(unsafe_code)]
|
||||
|
||||
use crate::unix::pid_t;
|
||||
|
||||
use std::fs;
|
||||
use std::io::{self, BufRead};
|
||||
use std::num::ParseIntError;
|
||||
use std::path::Path;
|
||||
|
||||
/// A process's resource limits. It is parsed from the **proc** filesystem.
|
||||
///
|
||||
/// See <https://man7.org/linux/man-pages/man5/proc.5.html>.
|
||||
///
|
||||
#[cfg_attr(docsrs, doc(cfg(any(target_os = "linux", target_os = "android"))))]
|
||||
#[derive(Debug, Clone, Default)]
|
||||
#[non_exhaustive]
|
||||
pub struct ProcLimits {
|
||||
/// Max cpu time. See also [`Resource::CPU`](struct.Resource.html#associatedconstant.CPU).
|
||||
pub max_cpu_time: Option<ProcLimit>,
|
||||
/// Max file size. See also [`Resource::FSIZE`](struct.Resource.html#associatedconstant.FSIZE).
|
||||
pub max_file_size: Option<ProcLimit>,
|
||||
/// Max data size. See also [`Resource::DATA`](struct.Resource.html#associatedconstant.DATA).
|
||||
pub max_data_size: Option<ProcLimit>,
|
||||
/// Max stack size. See also [`Resource::STACK`](struct.Resource.html#associatedconstant.STACK).
|
||||
pub max_stack_size: Option<ProcLimit>,
|
||||
/// Max core file size. See also [`Resource::CORE`](struct.Resource.html#associatedconstant.CORE).
|
||||
pub max_core_file_size: Option<ProcLimit>,
|
||||
/// Max resident set. See also [`Resource::RSS`](struct.Resource.html#associatedconstant.RSS).
|
||||
pub max_resident_set: Option<ProcLimit>,
|
||||
/// Max processes. See also [`Resource::NPROC`](struct.Resource.html#associatedconstant.NPROC).
|
||||
pub max_processes: Option<ProcLimit>,
|
||||
/// Max open files. See also [`Resource::NOFILE`](struct.Resource.html#associatedconstant.NOFILE).
|
||||
pub max_open_files: Option<ProcLimit>,
|
||||
/// Max locked memory. See also [`Resource::MEMLOCK`](struct.Resource.html#associatedconstant.MEMLOCK).
|
||||
pub max_locked_memory: Option<ProcLimit>,
|
||||
/// Max address space. See also [`Resource::AS`](struct.Resource.html#associatedconstant.AS).
|
||||
pub max_address_space: Option<ProcLimit>,
|
||||
/// Max file locks. See also [`Resource::LOCKS`](struct.Resource.html#associatedconstant.LOCKS).
|
||||
pub max_file_locks: Option<ProcLimit>,
|
||||
/// Max pending signals. See also [`Resource::SIGPENDING`](struct.Resource.html#associatedconstant.SIGPENDING).
|
||||
pub max_pending_signals: Option<ProcLimit>,
|
||||
/// Max msgqueue size. See also [`Resource::MSGQUEUE`](struct.Resource.html#associatedconstant.MSGQUEUE).
|
||||
pub max_msgqueue_size: Option<ProcLimit>,
|
||||
/// Max nice priority. See also [`Resource::NICE`](struct.Resource.html#associatedconstant.NICE).
|
||||
pub max_nice_priority: Option<ProcLimit>,
|
||||
/// Max realtime priority. See also [`Resource::RTPRIO`](struct.Resource.html#associatedconstant.RTPRIO).
|
||||
pub max_realtime_priority: Option<ProcLimit>,
|
||||
/// Max realtime timeout. See also [`Resource::RTTIME`](struct.Resource.html#associatedconstant.RTTIME).
|
||||
pub max_realtime_timeout: Option<ProcLimit>,
|
||||
}
|
||||
|
||||
/// A process's resource limit field.
|
||||
#[cfg_attr(docsrs, doc(cfg(any(target_os = "linux", target_os = "android"))))]
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct ProcLimit {
|
||||
/// Soft limit. `None` indicates `unlimited`.
|
||||
pub soft_limit: Option<u64>,
|
||||
/// Hard limit. `None` indicates `unlimited`.
|
||||
pub hard_limit: Option<u64>,
|
||||
}
|
||||
|
||||
impl ProcLimits {
|
||||
/// Reads the current process's resource limits from `/proc/self/limits`.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns an error if any IO operation failed.
|
||||
///
|
||||
/// Returns an error if the file format is invalid.
|
||||
///
|
||||
pub fn read_self() -> io::Result<Self> {
|
||||
Self::read_proc_fs("/proc/self/limits")
|
||||
}
|
||||
|
||||
/// Reads a process's resource limits from `/proc/[pid]/limits`.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns an error if `pid` is negative.
|
||||
///
|
||||
/// Returns an error if any IO operation failed.
|
||||
///
|
||||
/// Returns an error if the file format is invalid.
|
||||
///
|
||||
pub fn read_process(pid: pid_t) -> io::Result<Self> {
|
||||
if pid < 0 {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"ProcLimits: pid must be non-negative",
|
||||
));
|
||||
}
|
||||
Self::read_proc_fs(format!("/proc/{pid}/limits"))
|
||||
}
|
||||
|
||||
fn read_proc_fs(limits_path: impl AsRef<Path>) -> io::Result<Self> {
|
||||
fn parse_head(head: &str) -> Option<(usize, usize, usize)> {
|
||||
let s_idx = head.find('S')?;
|
||||
let h_idx = head[s_idx..].find('H')?;
|
||||
let u_idx = head[s_idx + h_idx..].find('U')?;
|
||||
Some((s_idx, h_idx, u_idx))
|
||||
}
|
||||
|
||||
fn parse_limit_number(s: &str) -> Result<Option<u64>, ParseIntError> {
|
||||
match s {
|
||||
"unlimited" => Ok(None),
|
||||
_ => match s.parse::<u64>() {
|
||||
Ok(n) => Ok(Some(n)),
|
||||
Err(e) => Err(e),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn io_error_other(s: impl Into<String>) -> io::Error {
|
||||
io::Error::new(io::ErrorKind::Other, s.into())
|
||||
}
|
||||
|
||||
let error_missing_table_head = || io_error_other("ProcLimits: missing table head");
|
||||
|
||||
let error_invalid_table_head = || io_error_other("ProcLimits: invalid table head");
|
||||
|
||||
let error_invalid_limit_number =
|
||||
|e| io_error_other(format!("ProcLimits: invalid limit number: {e}"));
|
||||
|
||||
let error_duplicate_limit_field = || io_error_other("ProcLimits: duplicate limit field");
|
||||
|
||||
let error_unknown_limit_field =
|
||||
|s: &str| io_error_other(format!("ProcLimits: unknown limit field: {s:?}"));
|
||||
|
||||
let reader = io::BufReader::new(fs::File::open(limits_path)?);
|
||||
let mut lines = reader.lines();
|
||||
|
||||
let head = lines.next().ok_or_else(error_missing_table_head)??;
|
||||
|
||||
let (name_len, soft_len, hard_len) =
|
||||
parse_head(&head).ok_or_else(error_invalid_table_head)?;
|
||||
|
||||
let mut ans = Self::default();
|
||||
|
||||
let sorted_table: [(&str, &mut Option<ProcLimit>); 16] = [
|
||||
("max address space", &mut ans.max_address_space),
|
||||
("max core file size", &mut ans.max_core_file_size),
|
||||
("max cpu time", &mut ans.max_cpu_time),
|
||||
("max data size", &mut ans.max_data_size),
|
||||
("max file locks", &mut ans.max_file_locks),
|
||||
("max file size", &mut ans.max_file_size),
|
||||
("max locked memory", &mut ans.max_locked_memory),
|
||||
("max msgqueue size", &mut ans.max_msgqueue_size),
|
||||
("max nice priority", &mut ans.max_nice_priority),
|
||||
("max open files", &mut ans.max_open_files),
|
||||
("max pending signals", &mut ans.max_pending_signals),
|
||||
("max processes", &mut ans.max_processes),
|
||||
("max realtime priority", &mut ans.max_realtime_priority),
|
||||
("max realtime timeout", &mut ans.max_realtime_timeout),
|
||||
("max resident set", &mut ans.max_resident_set),
|
||||
("max stack size", &mut ans.max_stack_size),
|
||||
];
|
||||
|
||||
for line in lines {
|
||||
let line = line?;
|
||||
|
||||
let (name, line) = line.split_at(name_len);
|
||||
let (soft, line) = line.split_at(soft_len);
|
||||
let (hard, _) = line.split_at(hard_len);
|
||||
|
||||
let name = name.trim().to_lowercase();
|
||||
let soft_limit = parse_limit_number(soft.trim()).map_err(error_invalid_limit_number)?;
|
||||
let hard_limit = parse_limit_number(hard.trim()).map_err(error_invalid_limit_number)?;
|
||||
let limit = ProcLimit {
|
||||
soft_limit,
|
||||
hard_limit,
|
||||
};
|
||||
|
||||
match sorted_table.binary_search_by_key(&name.as_str(), |&(s, _)| s) {
|
||||
Ok(idx) => {
|
||||
let field = &mut *sorted_table[idx].1;
|
||||
if field.is_some() {
|
||||
return Err(error_duplicate_limit_field());
|
||||
}
|
||||
*field = Some(limit);
|
||||
}
|
||||
Err(_) => return Err(error_unknown_limit_field(&name)),
|
||||
}
|
||||
}
|
||||
|
||||
Ok(ans)
|
||||
}
|
||||
}
|
||||
+265
@@ -0,0 +1,265 @@
|
||||
use super::ParseResourceError;
|
||||
use super::Resource;
|
||||
use crate::bindings as C;
|
||||
|
||||
impl Resource {
|
||||
/// The maximum size (in bytes) of the process's virtual memory (address space).
|
||||
pub const AS: Self = Self {
|
||||
tag: 1,
|
||||
value: C::RLIMIT_AS,
|
||||
};
|
||||
|
||||
/// The maximum size (in bytes) of a core file that the process may dump.
|
||||
pub const CORE: Self = Self {
|
||||
tag: 2,
|
||||
value: C::RLIMIT_CORE,
|
||||
};
|
||||
|
||||
/// A limit (in seconds) on the amount of CPU time that the process can consume.
|
||||
pub const CPU: Self = Self {
|
||||
tag: 3,
|
||||
value: C::RLIMIT_CPU,
|
||||
};
|
||||
|
||||
/// The maximum size (in bytes) of the process's data segment (initialized data, uninitialized data, and heap).
|
||||
pub const DATA: Self = Self {
|
||||
tag: 4,
|
||||
value: C::RLIMIT_DATA,
|
||||
};
|
||||
|
||||
/// The maximum size (in bytes) of files that the process may create.
|
||||
pub const FSIZE: Self = Self {
|
||||
tag: 5,
|
||||
value: C::RLIMIT_FSIZE,
|
||||
};
|
||||
|
||||
/// The maximum number of kqueues this user id is allowed to create.
|
||||
pub const KQUEUES: Self = Self {
|
||||
tag: 6,
|
||||
value: C::RLIMIT_KQUEUES,
|
||||
};
|
||||
|
||||
/// (early Linux 2.4 only)
|
||||
///
|
||||
/// A limit on the combined number of `flock(2)` locks and `fcntl(2)` leases that this process may establish.
|
||||
pub const LOCKS: Self = Self {
|
||||
tag: 7,
|
||||
value: C::RLIMIT_LOCKS,
|
||||
};
|
||||
|
||||
/// The maximum number (in bytes) of memory that may be locked into RAM.
|
||||
pub const MEMLOCK: Self = Self {
|
||||
tag: 8,
|
||||
value: C::RLIMIT_MEMLOCK,
|
||||
};
|
||||
|
||||
/// A limit on the number of bytes that can be allocated for POSIX message queues for the real user ID of the calling process.
|
||||
pub const MSGQUEUE: Self = Self {
|
||||
tag: 9,
|
||||
value: C::RLIMIT_MSGQUEUE,
|
||||
};
|
||||
|
||||
/// This specifies a ceiling to which the process's nice value can be raised using `setpriority(2)` or `nice(2)`.
|
||||
pub const NICE: Self = Self {
|
||||
tag: 10,
|
||||
value: C::RLIMIT_NICE,
|
||||
};
|
||||
|
||||
/// This specifies a value one greater than the maximum file descriptor number that can be opened by this process.
|
||||
pub const NOFILE: Self = Self {
|
||||
tag: 11,
|
||||
value: C::RLIMIT_NOFILE,
|
||||
};
|
||||
|
||||
/// The number of open vnode monitors.
|
||||
pub const NOVMON: Self = Self {
|
||||
tag: 12,
|
||||
value: C::RLIMIT_NOVMON,
|
||||
};
|
||||
|
||||
/// A limit on the number of extant process (or, more precisely on Linux, threads) for the real user ID of the calling process.
|
||||
pub const NPROC: Self = Self {
|
||||
tag: 13,
|
||||
value: C::RLIMIT_NPROC,
|
||||
};
|
||||
|
||||
/// The maximum number of pseudo-terminals this user id is allowed to create.
|
||||
pub const NPTS: Self = Self {
|
||||
tag: 14,
|
||||
value: C::RLIMIT_NPTS,
|
||||
};
|
||||
|
||||
/// The maximum number of simultaneous threads (Lightweight Processes) for this user id.
|
||||
/// Kernel threads and the first thread of each process are not counted against this limit.
|
||||
pub const NTHR: Self = Self {
|
||||
tag: 15,
|
||||
value: C::RLIMIT_NTHR,
|
||||
};
|
||||
|
||||
/// The maximum number of POSIX-type advisory-mode locks available to this user.
|
||||
pub const POSIXLOCKS: Self = Self {
|
||||
tag: 16,
|
||||
value: C::RLIMIT_POSIXLOCKS,
|
||||
};
|
||||
|
||||
/// A limit (in bytes) on the process's resident set (the number of virtual pages resident in RAM).
|
||||
pub const RSS: Self = Self {
|
||||
tag: 17,
|
||||
value: C::RLIMIT_RSS,
|
||||
};
|
||||
|
||||
/// This specifies a ceiling on the real-time priority that may be set for this process using `sched_setscheduler(2)` and `sched_setparam(2)`.
|
||||
pub const RTPRIO: Self = Self {
|
||||
tag: 18,
|
||||
value: C::RLIMIT_RTPRIO,
|
||||
};
|
||||
|
||||
/// A limit (in microseconds) on the amount of CPU time that a process scheduled under a real-time scheduling policy may consume without making a blocking system call.
|
||||
pub const RTTIME: Self = Self {
|
||||
tag: 19,
|
||||
value: C::RLIMIT_RTTIME,
|
||||
};
|
||||
|
||||
/// The maximum size (in bytes) of socket buffer usage for this user. This limits the amount of network memory, and hence the amount of mbufs, that this user may hold at any time.
|
||||
pub const SBSIZE: Self = Self {
|
||||
tag: 20,
|
||||
value: C::RLIMIT_SBSIZE,
|
||||
};
|
||||
|
||||
/// A limit on the number of signals that may be queued for the real user ID ofthe calling process.
|
||||
pub const SIGPENDING: Self = Self {
|
||||
tag: 21,
|
||||
value: C::RLIMIT_SIGPENDING,
|
||||
};
|
||||
|
||||
/// The maximum size (in bytes) of the process stack.
|
||||
pub const STACK: Self = Self {
|
||||
tag: 22,
|
||||
value: C::RLIMIT_STACK,
|
||||
};
|
||||
|
||||
/// The maximum size (in bytes) of the swap space that may be reserved or used by all of this user id's processes.
|
||||
pub const SWAP: Self = Self {
|
||||
tag: 23,
|
||||
value: C::RLIMIT_SWAP,
|
||||
};
|
||||
|
||||
/// **AIX**: The maximum number of threads each process can create. This limit is enforced by the kernel and the pthread debug library.
|
||||
pub const THREADS: Self = Self {
|
||||
tag: 24,
|
||||
value: C::RLIMIT_THREADS,
|
||||
};
|
||||
|
||||
/// The number of shared locks a given user may create simultaneously.
|
||||
pub const UMTXP: Self = Self {
|
||||
tag: 25,
|
||||
value: C::RLIMIT_UMTXP,
|
||||
};
|
||||
|
||||
/// An alias for [`RLIMIT_AS`](Resource::AS). The maximum size of a process's mapped address space in bytes.
|
||||
pub const VMEM: Self = Self {
|
||||
tag: 26,
|
||||
value: C::RLIMIT_VMEM,
|
||||
};
|
||||
}
|
||||
|
||||
impl Resource {
|
||||
pub(super) const fn find_name_by_tag(tag: u8) -> Option<&'static str> {
|
||||
match tag {
|
||||
1 => Some("RLIMIT_AS"),
|
||||
2 => Some("RLIMIT_CORE"),
|
||||
3 => Some("RLIMIT_CPU"),
|
||||
4 => Some("RLIMIT_DATA"),
|
||||
5 => Some("RLIMIT_FSIZE"),
|
||||
6 => Some("RLIMIT_KQUEUES"),
|
||||
7 => Some("RLIMIT_LOCKS"),
|
||||
8 => Some("RLIMIT_MEMLOCK"),
|
||||
9 => Some("RLIMIT_MSGQUEUE"),
|
||||
10 => Some("RLIMIT_NICE"),
|
||||
11 => Some("RLIMIT_NOFILE"),
|
||||
12 => Some("RLIMIT_NOVMON"),
|
||||
13 => Some("RLIMIT_NPROC"),
|
||||
14 => Some("RLIMIT_NPTS"),
|
||||
15 => Some("RLIMIT_NTHR"),
|
||||
16 => Some("RLIMIT_POSIXLOCKS"),
|
||||
17 => Some("RLIMIT_RSS"),
|
||||
18 => Some("RLIMIT_RTPRIO"),
|
||||
19 => Some("RLIMIT_RTTIME"),
|
||||
20 => Some("RLIMIT_SBSIZE"),
|
||||
21 => Some("RLIMIT_SIGPENDING"),
|
||||
22 => Some("RLIMIT_STACK"),
|
||||
23 => Some("RLIMIT_SWAP"),
|
||||
24 => Some("RLIMIT_THREADS"),
|
||||
25 => Some("RLIMIT_UMTXP"),
|
||||
26 => Some("RLIMIT_VMEM"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) const fn find_ident_by_tag(tag: u8) -> Option<&'static str> {
|
||||
match tag {
|
||||
1 => Some("AS"),
|
||||
2 => Some("CORE"),
|
||||
3 => Some("CPU"),
|
||||
4 => Some("DATA"),
|
||||
5 => Some("FSIZE"),
|
||||
6 => Some("KQUEUES"),
|
||||
7 => Some("LOCKS"),
|
||||
8 => Some("MEMLOCK"),
|
||||
9 => Some("MSGQUEUE"),
|
||||
10 => Some("NICE"),
|
||||
11 => Some("NOFILE"),
|
||||
12 => Some("NOVMON"),
|
||||
13 => Some("NPROC"),
|
||||
14 => Some("NPTS"),
|
||||
15 => Some("NTHR"),
|
||||
16 => Some("POSIXLOCKS"),
|
||||
17 => Some("RSS"),
|
||||
18 => Some("RTPRIO"),
|
||||
19 => Some("RTTIME"),
|
||||
20 => Some("SBSIZE"),
|
||||
21 => Some("SIGPENDING"),
|
||||
22 => Some("STACK"),
|
||||
23 => Some("SWAP"),
|
||||
24 => Some("THREADS"),
|
||||
25 => Some("UMTXP"),
|
||||
26 => Some("VMEM"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl std::str::FromStr for Resource {
|
||||
type Err = ParseResourceError;
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
match s {
|
||||
"RLIMIT_AS" => Ok(Self::AS),
|
||||
"RLIMIT_CORE" => Ok(Self::CORE),
|
||||
"RLIMIT_CPU" => Ok(Self::CPU),
|
||||
"RLIMIT_DATA" => Ok(Self::DATA),
|
||||
"RLIMIT_FSIZE" => Ok(Self::FSIZE),
|
||||
"RLIMIT_KQUEUES" => Ok(Self::KQUEUES),
|
||||
"RLIMIT_LOCKS" => Ok(Self::LOCKS),
|
||||
"RLIMIT_MEMLOCK" => Ok(Self::MEMLOCK),
|
||||
"RLIMIT_MSGQUEUE" => Ok(Self::MSGQUEUE),
|
||||
"RLIMIT_NICE" => Ok(Self::NICE),
|
||||
"RLIMIT_NOFILE" => Ok(Self::NOFILE),
|
||||
"RLIMIT_NOVMON" => Ok(Self::NOVMON),
|
||||
"RLIMIT_NPROC" => Ok(Self::NPROC),
|
||||
"RLIMIT_NPTS" => Ok(Self::NPTS),
|
||||
"RLIMIT_NTHR" => Ok(Self::NTHR),
|
||||
"RLIMIT_POSIXLOCKS" => Ok(Self::POSIXLOCKS),
|
||||
"RLIMIT_RSS" => Ok(Self::RSS),
|
||||
"RLIMIT_RTPRIO" => Ok(Self::RTPRIO),
|
||||
"RLIMIT_RTTIME" => Ok(Self::RTTIME),
|
||||
"RLIMIT_SBSIZE" => Ok(Self::SBSIZE),
|
||||
"RLIMIT_SIGPENDING" => Ok(Self::SIGPENDING),
|
||||
"RLIMIT_STACK" => Ok(Self::STACK),
|
||||
"RLIMIT_SWAP" => Ok(Self::SWAP),
|
||||
"RLIMIT_THREADS" => Ok(Self::THREADS),
|
||||
"RLIMIT_UMTXP" => Ok(Self::UMTXP),
|
||||
"RLIMIT_VMEM" => Ok(Self::VMEM),
|
||||
_ => Err(ParseResourceError(())),
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+116
@@ -0,0 +1,116 @@
|
||||
mod generated;
|
||||
|
||||
use crate::{getrlimit, setrlimit};
|
||||
|
||||
use std::fmt;
|
||||
use std::io;
|
||||
|
||||
/// A kind of resource.
|
||||
///
|
||||
/// All resource constants are available on all unix platforms.
|
||||
/// Passing an unsupported resource to `[set|get|p]rlimit` will
|
||||
/// result in a custom IO error.
|
||||
///
|
||||
/// **Be careful**: The documentation of [`Resource`](Resource) constants are based on a few systems.
|
||||
///
|
||||
/// It may be inconsistent with other platforms.
|
||||
///
|
||||
/// ## References
|
||||
///
|
||||
/// Linux: <https://man7.org/linux/man-pages/man2/getrlimit.2.html>
|
||||
///
|
||||
/// FreeBSD: <https://www.freebsd.org/cgi/man.cgi?query=getrlimit>
|
||||
///
|
||||
/// NetBSD: <https://man.netbsd.org/getrlimit.2>
|
||||
///
|
||||
/// AIX: <https://www.ibm.com/docs/en/aix/7.3?topic=g-getrlimit-getrlimit64-setrlimit-setrlimit64-vlimit-subroutine>
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub struct Resource {
|
||||
tag: u8,
|
||||
value: u8,
|
||||
}
|
||||
|
||||
impl fmt::Debug for Resource {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match Self::find_ident_by_tag(self.tag) {
|
||||
Some(ident) => write!(f, "Resource::{ident}"),
|
||||
None => unreachable!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An error returned when `Resource::from_str` fails
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ParseResourceError(());
|
||||
|
||||
impl fmt::Display for ParseResourceError {
|
||||
#[inline]
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "Failed to parse Resource")
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for ParseResourceError {}
|
||||
|
||||
impl Resource {
|
||||
/// Set resource limits.
|
||||
/// # Errors
|
||||
/// See [`setrlimit`]
|
||||
#[inline]
|
||||
pub fn set(self, soft: u64, hard: u64) -> io::Result<()> {
|
||||
setrlimit(self, soft, hard)
|
||||
}
|
||||
|
||||
/// Get resource limits.
|
||||
/// # Errors
|
||||
/// See [`getrlimit`]
|
||||
#[inline]
|
||||
pub fn get(self) -> io::Result<(u64, u64)> {
|
||||
getrlimit(self)
|
||||
}
|
||||
|
||||
/// Get soft resource limit (`rlim_cur`)
|
||||
/// # Errors
|
||||
/// See [`getrlimit`]
|
||||
pub fn get_soft(self) -> io::Result<u64> {
|
||||
self.get().map(|(soft, _)| soft)
|
||||
}
|
||||
|
||||
/// Get hard resource limit (`rlim_max`)
|
||||
/// # Errors
|
||||
/// See [`getrlimit`]
|
||||
pub fn get_hard(self) -> io::Result<u64> {
|
||||
self.get().map(|(_, hard)| hard)
|
||||
}
|
||||
|
||||
/// Returns the name of the resource.
|
||||
///
|
||||
/// # Example
|
||||
/// ```
|
||||
/// # #[cfg(unix)]
|
||||
/// # {
|
||||
/// # use rlimit::Resource;
|
||||
/// assert_eq!(Resource::NOFILE.as_name(), "RLIMIT_NOFILE");
|
||||
/// # }
|
||||
/// ```
|
||||
#[must_use]
|
||||
pub fn as_name(self) -> &'static str {
|
||||
match Self::find_name_by_tag(self.tag) {
|
||||
Some(name) => name,
|
||||
None => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns true if the current platform supports this resource.
|
||||
#[must_use]
|
||||
pub const fn is_supported(self) -> bool {
|
||||
self.value != u8::MAX
|
||||
}
|
||||
|
||||
/// `u8::MAX` indicates unsupported resource.
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub(crate) const fn as_raw(self) -> u8 {
|
||||
self.value
|
||||
}
|
||||
}
|
||||
Vendored
+261
@@ -0,0 +1,261 @@
|
||||
#![deny(unsafe_code)]
|
||||
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
|
||||
/// System-wide file descriptor limits and statistics.
|
||||
///
|
||||
/// These values are read from and written to the **proc** filesystem under `/proc/sys/fs/`.
|
||||
///
|
||||
/// See <https://www.kernel.org/doc/Documentation/sysctl/fs.txt> and
|
||||
/// <https://man7.org/linux/man-pages/man5/proc.5.html>.
|
||||
///
|
||||
#[cfg_attr(docsrs, doc(cfg(any(target_os = "linux", target_os = "android"))))]
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub struct SysLimits {
|
||||
/// System-wide limit on the total number of file descriptors that can be allocated.
|
||||
///
|
||||
/// This corresponds to `/proc/sys/fs/file-max`.
|
||||
pub file_max: Option<u64>,
|
||||
|
||||
/// Current file descriptor usage statistics.
|
||||
///
|
||||
/// This corresponds to `/proc/sys/fs/file-nr` and contains three values:
|
||||
/// - `allocated`: Number of allocated file descriptors
|
||||
/// - `free`: Number of free file descriptors (deprecated, always 0 in modern kernels)
|
||||
/// - `maximum`: Maximum number of file descriptors (same as `file_max`)
|
||||
///
|
||||
/// This field is read-only.
|
||||
pub file_nr: Option<FileNr>,
|
||||
|
||||
/// Per-process maximum number of file descriptors that can be allocated.
|
||||
///
|
||||
/// This corresponds to `/proc/sys/fs/nr_open`. This is the ceiling value that
|
||||
/// can be set for the per-process NOFILE limit (both hard and soft).
|
||||
pub nr_open: Option<u64>,
|
||||
}
|
||||
|
||||
/// File descriptor usage statistics from `/proc/sys/fs/file-nr`.
|
||||
///
|
||||
/// **Note:** The "free" field has been deprecated since Linux 2.6 and is always 0 in modern kernels.
|
||||
#[cfg_attr(docsrs, doc(cfg(any(target_os = "linux", target_os = "android"))))]
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct FileNr {
|
||||
/// Number of allocated file descriptors.
|
||||
pub allocated: u64,
|
||||
/// Number of free file descriptors.
|
||||
///
|
||||
/// **Deprecated:** This field has been deprecated since Linux 2.6 and is always 0 in modern kernels.
|
||||
/// It does not contain meaningful data.
|
||||
pub free: u64,
|
||||
/// Maximum number of file descriptors (same as `file_max`).
|
||||
pub maximum: u64,
|
||||
}
|
||||
|
||||
impl SysLimits {
|
||||
/// Reads system-wide file descriptor limits from `/proc/sys/fs/`.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns an error if any IO operation failed or if the file format is invalid.
|
||||
///
|
||||
/// # Examples
|
||||
/// ```no_run
|
||||
/// # #[cfg(any(target_os = "linux", target_os = "android"))]
|
||||
/// # {
|
||||
/// use rlimit::SysLimits;
|
||||
///
|
||||
/// let limits = SysLimits::read().unwrap();
|
||||
/// println!("System file-max: {:?}", limits.file_max);
|
||||
/// println!("Current usage: {:?}", limits.file_nr);
|
||||
/// println!("Per-process nr_open: {:?}", limits.nr_open);
|
||||
/// # }
|
||||
/// ```
|
||||
pub fn read() -> io::Result<Self> {
|
||||
let file_max = read_u64_from_file("/proc/sys/fs/file-max").ok();
|
||||
let file_nr = read_file_nr("/proc/sys/fs/file-nr").ok();
|
||||
let nr_open = read_u64_from_file("/proc/sys/fs/nr_open").ok();
|
||||
|
||||
Ok(Self {
|
||||
file_max,
|
||||
file_nr,
|
||||
nr_open,
|
||||
})
|
||||
}
|
||||
|
||||
/// Writes the `file_max` value to `/proc/sys/fs/file-max`.
|
||||
///
|
||||
/// This operation typically requires root privileges or `CAP_SYS_ADMIN` capability.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns an error if the write operation failed, which can happen if:
|
||||
/// - The process lacks sufficient privileges
|
||||
/// - The value is invalid
|
||||
/// - The filesystem is read-only
|
||||
///
|
||||
/// # Examples
|
||||
/// ```no_run
|
||||
/// # #[cfg(any(target_os = "linux", target_os = "android"))]
|
||||
/// # {
|
||||
/// use rlimit::SysLimits;
|
||||
///
|
||||
/// // This typically requires root privileges
|
||||
/// SysLimits::set_file_max(1048576).unwrap();
|
||||
/// # }
|
||||
/// ```
|
||||
pub fn set_file_max(value: u64) -> io::Result<()> {
|
||||
write_u64_to_file("/proc/sys/fs/file-max", value)
|
||||
}
|
||||
|
||||
/// Writes the `nr_open` value to `/proc/sys/fs/nr_open`.
|
||||
///
|
||||
/// This operation typically requires root privileges or `CAP_SYS_ADMIN` capability.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns an error if the write operation failed, which can happen if:
|
||||
/// - The process lacks sufficient privileges
|
||||
/// - The value is invalid
|
||||
/// - The filesystem is read-only
|
||||
///
|
||||
/// # Examples
|
||||
/// ```no_run
|
||||
/// # #[cfg(any(target_os = "linux", target_os = "android"))]
|
||||
/// # {
|
||||
/// use rlimit::SysLimits;
|
||||
///
|
||||
/// // This typically requires root privileges
|
||||
/// SysLimits::set_nr_open(1048576).unwrap();
|
||||
/// # }
|
||||
/// ```
|
||||
pub fn set_nr_open(value: u64) -> io::Result<()> {
|
||||
write_u64_to_file("/proc/sys/fs/nr_open", value)
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads a u64 value from a file in `/proc/sys/fs/`.
|
||||
fn read_u64_from_file(path: impl AsRef<Path>) -> io::Result<u64> {
|
||||
let content = fs::read_to_string(path)?;
|
||||
content
|
||||
.trim()
|
||||
.parse::<u64>()
|
||||
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
|
||||
}
|
||||
|
||||
/// Reads file descriptor statistics from `/proc/sys/fs/file-nr`.
|
||||
///
|
||||
/// The file contains three whitespace-separated values: allocated, free, and maximum.
|
||||
fn read_file_nr(path: impl AsRef<Path>) -> io::Result<FileNr> {
|
||||
let content = fs::read_to_string(path)?;
|
||||
let parts: Vec<&str> = content.split_whitespace().collect();
|
||||
|
||||
if parts.len() != 3 {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
format!("Expected 3 values in file-nr, got {}", parts.len()),
|
||||
));
|
||||
}
|
||||
|
||||
let allocated = parts[0]
|
||||
.parse::<u64>()
|
||||
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
|
||||
let free = parts[1]
|
||||
.parse::<u64>()
|
||||
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
|
||||
let maximum = parts[2]
|
||||
.parse::<u64>()
|
||||
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
|
||||
|
||||
Ok(FileNr {
|
||||
allocated,
|
||||
free,
|
||||
maximum,
|
||||
})
|
||||
}
|
||||
|
||||
/// Writes a u64 value to a file in `/proc/sys/fs/`.
|
||||
fn write_u64_to_file(path: impl AsRef<Path>, value: u64) -> io::Result<()> {
|
||||
fs::write(path, value.to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_read_system_limits() {
|
||||
// This test only verifies that the function doesn't crash
|
||||
// The actual values depend on the system configuration
|
||||
let result = SysLimits::read();
|
||||
|
||||
// Should succeed on Linux/Android systems
|
||||
if cfg!(any(target_os = "linux", target_os = "android")) {
|
||||
let limits = result.unwrap();
|
||||
|
||||
// At least one of the fields should be populated
|
||||
assert!(
|
||||
limits.file_max.is_some() || limits.file_nr.is_some() || limits.nr_open.is_some(),
|
||||
"At least one limit should be readable"
|
||||
);
|
||||
|
||||
// If file_nr is present, validate its structure
|
||||
if let Some(file_nr) = limits.file_nr {
|
||||
// Maximum should match file_max if both are present
|
||||
if let Some(file_max) = limits.file_max {
|
||||
assert_eq!(file_nr.maximum, file_max);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_file_nr_parsing() {
|
||||
// Test the internal parsing logic with mock data
|
||||
use std::io::Write;
|
||||
|
||||
let temp_dir = std::env::temp_dir();
|
||||
let test_file = temp_dir.join(format!(
|
||||
"test_file_nr_{:?}.txt",
|
||||
std::thread::current().id()
|
||||
));
|
||||
|
||||
// Write test data
|
||||
let mut file = fs::File::create(&test_file).unwrap();
|
||||
write!(file, "2208\t0\t9223372036854775807").unwrap();
|
||||
file.flush().unwrap();
|
||||
drop(file);
|
||||
|
||||
// Read and verify
|
||||
let result = read_file_nr(&test_file).unwrap();
|
||||
assert_eq!(result.allocated, 2208);
|
||||
assert_eq!(result.free, 0);
|
||||
assert_eq!(result.maximum, 9_223_372_036_854_775_807);
|
||||
|
||||
// Clean up
|
||||
fs::remove_file(&test_file).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_u64_parsing() {
|
||||
use std::io::Write;
|
||||
|
||||
let temp_dir = std::env::temp_dir();
|
||||
let test_file = temp_dir.join(format!(
|
||||
"test_u64_{:?}.txt",
|
||||
std::thread::current().id()
|
||||
));
|
||||
|
||||
// Write test data
|
||||
let mut file = fs::File::create(&test_file).unwrap();
|
||||
writeln!(file, "1048576").unwrap();
|
||||
file.flush().unwrap();
|
||||
drop(file);
|
||||
|
||||
// Read and verify
|
||||
let result = read_u64_from_file(&test_file).unwrap();
|
||||
assert_eq!(result, 1_048_576);
|
||||
|
||||
// Clean up
|
||||
fs::remove_file(&test_file).ok();
|
||||
}
|
||||
}
|
||||
Vendored
+80
@@ -0,0 +1,80 @@
|
||||
use std::io;
|
||||
|
||||
/// Returns the value of `kern.maxfilesperproc` by sysctl.
|
||||
/// # Errors
|
||||
/// Returns an error if any syscall failed.
|
||||
#[cfg(rlimit__get_kern_max_files_per_proc)]
|
||||
fn get_kern_max_files_per_proc() -> io::Result<u64> {
|
||||
use std::mem;
|
||||
use std::ptr;
|
||||
|
||||
let mut mib = [libc::CTL_KERN, libc::KERN_MAXFILESPERPROC];
|
||||
let mut max_files_per_proc: libc::c_int = 0;
|
||||
let mut oldlen = mem::size_of::<libc::c_int>();
|
||||
let ret = unsafe {
|
||||
libc::sysctl(
|
||||
mib.as_mut_ptr(),
|
||||
2,
|
||||
&mut max_files_per_proc as *mut libc::c_int as *mut libc::c_void,
|
||||
&mut oldlen,
|
||||
ptr::null_mut(),
|
||||
0,
|
||||
)
|
||||
};
|
||||
|
||||
if ret < 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
|
||||
// SAFETY: sysctl should return a non-negative value for KERN_MAXFILESPERPROC.
|
||||
// Casting a non-negative c_int to u64 is always safe (widening conversion).
|
||||
debug_assert!(max_files_per_proc >= 0);
|
||||
Ok(max_files_per_proc as u64)
|
||||
}
|
||||
|
||||
/// Try to increase NOFILE limit and return the current soft limit.
|
||||
///
|
||||
/// `lim` is the expected limit which can be up to [`u64::MAX`].
|
||||
///
|
||||
/// This function does nothing and returns `Ok(lim)`
|
||||
/// if `RLIMIT_NOFILE` does not exist on current platform.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns an error if any syscall failed.
|
||||
pub fn increase_nofile_limit(lim: u64) -> io::Result<u64> {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use crate::Resource;
|
||||
|
||||
if !Resource::NOFILE.is_supported() {
|
||||
return Ok(lim);
|
||||
}
|
||||
|
||||
let (soft, hard) = Resource::NOFILE.get()?;
|
||||
|
||||
if soft >= hard {
|
||||
return Ok(hard);
|
||||
}
|
||||
|
||||
if soft >= lim {
|
||||
return Ok(soft);
|
||||
}
|
||||
|
||||
let mut lim = lim;
|
||||
|
||||
lim = lim.min(hard);
|
||||
|
||||
#[cfg(rlimit__get_kern_max_files_per_proc)]
|
||||
{
|
||||
lim = lim.min(get_kern_max_files_per_proc()?)
|
||||
}
|
||||
|
||||
Resource::NOFILE.set(lim, hard)?;
|
||||
|
||||
Ok(lim)
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
Ok(lim)
|
||||
}
|
||||
}
|
||||
Vendored
+125
@@ -0,0 +1,125 @@
|
||||
use crate::bindings as C;
|
||||
use crate::resource::Resource;
|
||||
|
||||
use std::{io, mem};
|
||||
|
||||
/// A value indicating no limit.
|
||||
///
|
||||
/// This constant is the minimum of the platform's `RLIM_INFINITY` and `u64::MAX`.
|
||||
/// On most platforms, `RLIM_INFINITY` is already `u64`, making this cast lossless.
|
||||
#[allow(clippy::unnecessary_cast)]
|
||||
pub const INFINITY: u64 = C::RLIM_INFINITY as u64;
|
||||
|
||||
fn check_supported(resource: Resource) -> io::Result<()> {
|
||||
let raw_resource = resource.as_raw();
|
||||
if raw_resource == u8::MAX {
|
||||
return Err(io::Error::new(io::ErrorKind::Other, "unsupported resource"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Set resource limits.
|
||||
/// # Errors
|
||||
/// \[Linux\] See <https://man7.org/linux/man-pages/man2/setrlimit.2.html>
|
||||
#[allow(clippy::unnecessary_min_or_max)]
|
||||
#[inline]
|
||||
pub fn setrlimit(resource: Resource, soft: u64, hard: u64) -> io::Result<()> {
|
||||
check_supported(resource)?;
|
||||
// SAFETY: Values are clamped to INFINITY, which is the maximum value representable
|
||||
// by the platform's rlim_t type. On platforms where rlim_t is u64, this is a no-op.
|
||||
// On platforms where rlim_t is smaller (e.g., u32), the min() ensures we don't
|
||||
// exceed the platform's maximum value before truncating.
|
||||
let rlim = C::rlimit {
|
||||
rlim_cur: soft.min(INFINITY) as _,
|
||||
rlim_max: hard.min(INFINITY) as _,
|
||||
};
|
||||
#[allow(clippy::cast_lossless)]
|
||||
let ret = unsafe { C::setrlimit(resource.as_raw() as _, &rlim) };
|
||||
if ret == 0 {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(io::Error::last_os_error())
|
||||
}
|
||||
}
|
||||
|
||||
/// Get resource limits.
|
||||
/// # Errors
|
||||
/// \[Linux\] See <https://man7.org/linux/man-pages/man2/getrlimit.2.html>
|
||||
#[allow(clippy::unnecessary_min_or_max)]
|
||||
#[inline]
|
||||
pub fn getrlimit(resource: Resource) -> io::Result<(u64, u64)> {
|
||||
check_supported(resource)?;
|
||||
let mut rlim = unsafe { mem::zeroed() };
|
||||
#[allow(clippy::cast_lossless)]
|
||||
let ret = unsafe { C::getrlimit(resource.as_raw() as _, &mut rlim) };
|
||||
|
||||
#[allow(clippy::unnecessary_cast)]
|
||||
if ret == 0 {
|
||||
// SAFETY: On platforms where rlim_t is u64, this cast is lossless (no-op).
|
||||
// On platforms where rlim_t is smaller (e.g., u32), this is a widening cast
|
||||
// which is always safe. The min(INFINITY) clamps to our portable maximum.
|
||||
let soft = (rlim.rlim_cur as u64).min(INFINITY);
|
||||
let hard = (rlim.rlim_max as u64).min(INFINITY);
|
||||
Ok((soft, hard))
|
||||
} else {
|
||||
Err(io::Error::last_os_error())
|
||||
}
|
||||
}
|
||||
|
||||
/// The type of a process ID
|
||||
#[allow(non_camel_case_types)]
|
||||
#[cfg_attr(docsrs, doc(cfg(any(target_os = "linux", target_os = "android"))))]
|
||||
#[cfg(any(doc, target_os = "linux", target_os = "android"))]
|
||||
pub type pid_t = i32;
|
||||
|
||||
/// Set and get the resource limits of an arbitrary process.
|
||||
/// # Errors
|
||||
/// See <https://man7.org/linux/man-pages/man2/prlimit.2.html>
|
||||
#[allow(clippy::unnecessary_min_or_max)]
|
||||
#[inline]
|
||||
#[cfg_attr(docsrs, doc(cfg(any(target_os = "linux", target_os = "android"))))]
|
||||
#[cfg(any(doc, rlimit__has_prlimit64))]
|
||||
pub fn prlimit(
|
||||
pid: pid_t,
|
||||
resource: Resource,
|
||||
new_limit: Option<(u64, u64)>,
|
||||
old_limit: Option<(&mut u64, &mut u64)>,
|
||||
) -> io::Result<()> {
|
||||
check_supported(resource)?;
|
||||
|
||||
// SAFETY: Values are clamped to INFINITY before casting to rlim_t.
|
||||
// See setrlimit() for detailed explanation of truncation safety.
|
||||
let new_rlim: Option<C::rlimit> = new_limit.map(|(soft, hard)| C::rlimit {
|
||||
rlim_cur: soft.min(INFINITY) as _,
|
||||
rlim_max: hard.min(INFINITY) as _,
|
||||
});
|
||||
|
||||
let new_rlimit_ptr: *const C::rlimit = match new_rlim {
|
||||
Some(ref rlim) => rlim,
|
||||
None => std::ptr::null(),
|
||||
};
|
||||
|
||||
let mut old_rlim: C::rlimit = unsafe { mem::zeroed() };
|
||||
|
||||
let old_rlimit_ptr: *mut C::rlimit = if old_limit.is_some() {
|
||||
&mut old_rlim
|
||||
} else {
|
||||
std::ptr::null_mut()
|
||||
};
|
||||
|
||||
#[allow(clippy::cast_lossless)]
|
||||
let ret = unsafe { C::prlimit(pid, resource.as_raw() as _, new_rlimit_ptr, old_rlimit_ptr) };
|
||||
|
||||
if ret == 0 {
|
||||
#[allow(clippy::unnecessary_cast)]
|
||||
if let Some((soft, hard)) = old_limit {
|
||||
// SAFETY: See getrlimit() for detailed explanation of cast safety.
|
||||
*soft = (old_rlim.rlim_cur as u64).min(INFINITY);
|
||||
*hard = (old_rlim.rlim_max as u64).min(INFINITY);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
} else {
|
||||
Err(io::Error::last_os_error())
|
||||
}
|
||||
}
|
||||
Vendored
+60
@@ -0,0 +1,60 @@
|
||||
use std::io;
|
||||
use std::os::raw::c_int;
|
||||
|
||||
extern "C" {
|
||||
fn _setmaxstdio(new_max: c_int) -> c_int;
|
||||
fn _getmaxstdio() -> c_int;
|
||||
}
|
||||
|
||||
/// Sets a maximum for the number of simultaneously open files at the stream I/O level.
|
||||
///
|
||||
/// The maximum allowed value is platform-dependent, typically 8192 on modern systems.
|
||||
/// Values that would overflow when converted to `c_int` or exceed the platform's
|
||||
/// maximum will result in an error.
|
||||
///
|
||||
/// See <https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/setmaxstdio?view=msvc-170>
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns an error if:
|
||||
/// - `new_max` exceeds `c_int::MAX` (typically 2,147,483,647)
|
||||
/// - `new_max` is below the minimum (typically 20) or above the platform maximum (typically 8192)
|
||||
/// - The underlying `_setmaxstdio` call fails
|
||||
#[cfg_attr(docsrs, doc(cfg(windows)))]
|
||||
pub fn setmaxstdio(new_max: u32) -> io::Result<u32> {
|
||||
// Validate that new_max fits in c_int to prevent overflow.
|
||||
// SAFETY: c_int::MAX (i32::MAX = 2147483647) fits in u32, so this cast is safe.
|
||||
if new_max > c_int::MAX as u32 {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"new_max exceeds maximum allowed value",
|
||||
));
|
||||
}
|
||||
|
||||
// SAFETY: We've validated that new_max fits in c_int, so the cast is safe
|
||||
// (though clippy warns about possible wrapping). The cast back to u32 is
|
||||
// safe because we've checked that ret >= 0.
|
||||
#[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)]
|
||||
unsafe {
|
||||
let ret = _setmaxstdio(new_max as c_int);
|
||||
if ret < 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
Ok(ret as u32)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the number of simultaneously open files permitted at the stream I/O level.
|
||||
///
|
||||
/// See <https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/getmaxstdio?view=msvc-170>
|
||||
#[cfg_attr(docsrs, doc(cfg(windows)))]
|
||||
#[must_use]
|
||||
pub fn getmaxstdio() -> u32 {
|
||||
// SAFETY: A negative `ret` should never appear.
|
||||
// It is safe even if the return value is wrong.
|
||||
#[allow(clippy::cast_sign_loss)]
|
||||
unsafe {
|
||||
let ret = _getmaxstdio();
|
||||
debug_assert!(ret >= 0);
|
||||
ret as u32
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user