#[cfg(feature = "alloc")]
use core::fmt;
#[cfg(feature = "alloc")]
use core::marker::PhantomData;
mod signal;
pub(crate) use signal::Wake;
pub use signal::{Signal, Signals};
#[cfg(feature = "alloc")]
use crate::BorrowedHandle;
use core::time::Duration;
use crate::sys;
use crate::{AsPath, ErrorKind, Result};
#[inline]
pub fn id() -> u32 {
sys::process::id()
}
#[inline]
pub fn parent_id() -> u32 {
sys::process::parent_id()
}
#[inline]
pub fn exit(code: i32) -> ! {
sys::process::exit(code)
}
#[inline]
pub fn abort() -> ! {
sys::process::abort()
}
pub fn find_program<N: AsPath + ?Sized, S: AsPath + ?Sized>(
name: &N,
search_path: &S,
buf: &mut [u8],
) -> Result<usize> {
let name = name.as_path_bytes();
let search_path = search_path.as_path_bytes();
if !sys::process::HAS_PROCESSES {
return Err(ErrorKind::Unsupported.into());
}
if name.contains(&0) || search_path.contains(&0) {
return Err(ErrorKind::InvalidInput.into());
}
if name.is_empty() {
return Err(ErrorKind::NotFound.into());
}
let mut check = |parts: &[&[u8]]| -> Result<Option<usize>> {
let mut len = 0;
for part in parts {
buf.get_mut(len..len + part.len())
.ok_or(ErrorKind::BufferTooSmall)?
.copy_from_slice(part);
len += part.len();
}
Ok(sys::process::is_program(&buf[..len]).then_some(len))
};
if !sys::process::is_bare_name(name) {
return check(&[name])?.ok_or(ErrorKind::NotFound.into());
}
let suffix: &[u8] = if name.contains(&b'.') {
b""
} else {
sys::process::PROGRAM_SUFFIX
};
for dir in search_path.split(|&c| c == sys::process::SEARCH_SEPARATOR) {
let dir = sys::process::search_dir(dir);
let Some(&last) = dir.last() else {
continue;
};
let separator: &[u8] = if sys::fs::is_separator(last) {
b""
} else {
sys::process::DIR_SEPARATOR
};
if let Some(len) = check(&[dir, separator, name, suffix])? {
return Ok(len);
}
}
Err(ErrorKind::NotFound.into())
}
#[cfg(feature = "alloc")]
pub fn find_program_vec<N: AsPath + ?Sized, S: AsPath + ?Sized>(
name: &N,
search_path: &S,
) -> Result<alloc::vec::Vec<u8>> {
let name = name.as_path_bytes();
let search_path = search_path.as_path_bytes();
let len = name.len() + search_path.len() + 1 + sys::process::PROGRAM_SUFFIX.len();
let mut buf = alloc::vec::Vec::new();
buf.try_reserve_exact(len)
.map_err(|_| ErrorKind::OutOfMemory)?;
buf.resize(len, 0);
let len = find_program(name, search_path, &mut buf)?;
buf.truncate(len);
Ok(buf)
}
pub fn exists(pid: u32) -> Result<bool> {
sys::process::exists(checked_pid(pid)?)
}
pub fn kill(pid: u32) -> Result<()> {
sys::process::kill(checked_pid(pid)?)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct ResourceUsage {
pub(crate) user_time: Duration,
pub(crate) system_time: Duration,
pub(crate) max_resident_memory: u64,
}
impl ResourceUsage {
#[inline]
pub const fn user_time(&self) -> Duration {
self.user_time
}
#[inline]
pub const fn system_time(&self) -> Duration {
self.system_time
}
#[inline]
pub const fn max_resident_memory(&self) -> u64 {
self.max_resident_memory
}
}
pub fn resource_usage() -> Result<ResourceUsage> {
sys::process::resource_usage()
}
fn checked_pid(pid: u32) -> Result<u32> {
if pid == 0 || pid > i32::MAX as u32 {
return Err(ErrorKind::InvalidInput.into());
}
Ok(pid)
}
#[cfg(feature = "alloc")]
#[derive(Clone, Copy)]
pub(crate) struct List<'a> {
data: *const (),
len: usize,
get: unsafe fn(*const (), usize) -> *const [u8],
marker: PhantomData<&'a [u8]>,
}
#[cfg(feature = "alloc")]
impl<'a> List<'a> {
fn new<S: AsPath>(items: &'a [S]) -> Self {
unsafe fn get<S: AsPath>(data: *const (), i: usize) -> *const [u8] {
unsafe { &*data.cast::<S>().add(i) }.as_path_bytes()
}
Self {
data: items.as_ptr().cast(),
len: items.len(),
get: get::<S>,
marker: PhantomData,
}
}
fn empty() -> Self {
Self::new::<&[u8]>(&[])
}
#[allow(dead_code)]
pub(crate) fn iter(self) -> impl Iterator<Item = &'a [u8]> {
(0..self.len).map(move |i| unsafe { &*(self.get)(self.data, i) })
}
}
#[cfg(feature = "alloc")]
#[derive(Clone, Copy, Debug, Default)]
pub enum Stdio<'a> {
#[default]
Inherit,
Null,
Handle(BorrowedHandle<'a>),
}
#[cfg(feature = "alloc")]
#[derive(Clone)]
pub struct Command<'a> {
pub(crate) program: &'a [u8],
pub(crate) arg0: Option<&'a [u8]>,
pub(crate) args: List<'a>,
pub(crate) env: Option<List<'a>>,
pub(crate) current_dir: Option<&'a [u8]>,
pub(crate) stdio: [Stdio<'a>; 3],
#[allow(dead_code)]
pub(crate) raw_command_line: Option<&'a [u8]>,
#[allow(dead_code)]
pub(crate) new_process_group: bool,
#[allow(dead_code)]
pub(crate) process_group: Option<u32>,
#[allow(dead_code)]
pub(crate) new_session: bool,
#[allow(dead_code)]
pub(crate) new_console: bool,
}
#[cfg(feature = "alloc")]
impl<'a> Command<'a> {
pub fn new<P: AsPath + ?Sized>(program: &'a P) -> Self {
Self {
program: program.as_path_bytes(),
arg0: None,
args: List::empty(),
env: None,
current_dir: None,
stdio: [Stdio::Inherit; 3],
raw_command_line: None,
new_process_group: false,
process_group: None,
new_session: false,
new_console: false,
}
}
pub fn args<S: AsPath>(mut self, args: &'a [S]) -> Self {
self.args = List::new(args);
self
}
pub fn arg0<S: AsPath + ?Sized>(mut self, arg0: &'a S) -> Self {
self.arg0 = Some(arg0.as_path_bytes());
self
}
pub fn env<S: AsPath>(mut self, vars: &'a [S]) -> Self {
self.env = Some(List::new(vars));
self
}
pub fn current_dir<P: AsPath + ?Sized>(mut self, dir: &'a P) -> Self {
self.current_dir = Some(dir.as_path_bytes());
self
}
pub fn stdin(mut self, stdio: Stdio<'a>) -> Self {
self.stdio[0] = stdio;
self
}
pub fn stdout(mut self, stdio: Stdio<'a>) -> Self {
self.stdio[1] = stdio;
self
}
pub fn stderr(mut self, stdio: Stdio<'a>) -> Self {
self.stdio[2] = stdio;
self
}
pub fn spawn(&self) -> Result<Child> {
if sys::process::HAS_PROCESSES
&& let Some(vars) = self.env
{
for var in vars.iter() {
let named = var.iter().skip(1).any(|&byte| byte == b'=');
if !named || var.contains(&0) {
return Err(ErrorKind::InvalidInput.into());
}
}
}
let inner = sys::process::spawn(self)?;
Ok(Child {
inner,
status: None,
usage: None,
})
}
}
#[cfg(feature = "alloc")]
impl fmt::Debug for Command<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
struct Bytes<'a>(&'a [u8]);
impl fmt::Debug for Bytes<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&alloc::string::String::from_utf8_lossy(self.0), f)
}
}
struct Strings<'a>(List<'a>);
impl fmt::Debug for Strings<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.0.iter().map(Bytes)).finish()
}
}
f.debug_struct("Command")
.field("program", &Bytes(self.program))
.field("arg0", &self.arg0.map(Bytes))
.field("args", &Strings(self.args))
.field("env", &self.env.map(Strings))
.field("current_dir", &self.current_dir.map(Bytes))
.field("stdin", &self.stdio[0])
.field("stdout", &self.stdio[1])
.field("stderr", &self.stdio[2])
.finish_non_exhaustive()
}
}
#[cfg(feature = "alloc")]
#[derive(Debug)]
pub struct Child {
inner: sys::process::Child,
status: Option<ExitStatus>,
usage: Option<ResourceUsage>,
}
#[cfg(feature = "alloc")]
impl Child {
#[inline]
pub fn id(&self) -> u32 {
self.inner.id()
}
pub fn wait(&mut self) -> Result<ExitStatus> {
if let Some(status) = self.status {
return Ok(status);
}
match self.inner.wait(true)? {
Some((status, usage)) => {
self.status = Some(status);
self.usage = usage;
Ok(status)
}
None => Err(ErrorKind::Other.into()),
}
}
pub fn try_wait(&mut self) -> Result<Option<ExitStatus>> {
if self.status.is_none()
&& let Some((status, usage)) = self.inner.wait(false)?
{
self.status = Some(status);
self.usage = usage;
}
Ok(self.status)
}
pub fn resource_usage(&self) -> Option<ResourceUsage> {
self.usage
}
pub fn kill(&self) -> Result<()> {
if self.status.is_some() {
return Ok(());
}
self.inner.kill()
}
#[inline]
pub(crate) fn sys(&self) -> &sys::process::Child {
&self.inner
}
#[inline]
pub(crate) fn collected(&self) -> bool {
self.status.is_some()
}
}
#[cfg(all(
feature = "alloc",
any(target_os = "linux", target_os = "fullrust", windows)
))]
impl crate::AsHandle for Child {
#[inline]
fn as_handle(&self) -> BorrowedHandle<'_> {
self.inner.handle()
}
}
#[cfg(feature = "alloc")]
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct ExitStatus(Status);
#[cfg(feature = "alloc")]
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
enum Status {
Exited(i32),
#[allow(dead_code)]
Signaled(i32, bool),
}
#[cfg(feature = "alloc")]
impl ExitStatus {
#[allow(dead_code)]
pub(crate) fn exited(code: i32) -> Self {
Self(Status::Exited(code))
}
#[allow(dead_code)]
pub(crate) fn signaled(signal: i32, core_dumped: bool) -> Self {
Self(Status::Signaled(signal, core_dumped))
}
#[inline]
pub fn success(&self) -> bool {
self.0 == Status::Exited(0)
}
#[inline]
pub fn code(&self) -> Option<i32> {
match self.0 {
Status::Exited(code) => Some(code),
Status::Signaled(..) => None,
}
}
}
#[cfg(feature = "alloc")]
impl fmt::Debug for ExitStatus {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.0 {
Status::Exited(code) => write!(f, "ExitStatus(code {code})"),
Status::Signaled(signal, _) => write!(f, "ExitStatus(signal {signal})"),
}
}
}
#[cfg(feature = "alloc")]
impl fmt::Display for ExitStatus {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.0 {
Status::Exited(code) => write!(f, "exit code: {code}"),
Status::Signaled(signal, false) => write!(f, "signal: {signal}"),
Status::Signaled(signal, true) => write!(f, "signal: {signal} (core dumped)"),
}
}
}
#[cfg(feature = "alloc")]
#[allow(dead_code)]
pub(crate) struct CStrings {
bytes: alloc::vec::Vec<u8>,
starts: alloc::vec::Vec<usize>,
pointers: alloc::vec::Vec<*const core::ffi::c_char>,
}
#[cfg(feature = "alloc")]
#[allow(dead_code)]
impl CStrings {
pub(crate) fn new() -> Self {
Self {
bytes: alloc::vec::Vec::new(),
starts: alloc::vec::Vec::new(),
pointers: alloc::vec::Vec::new(),
}
}
pub(crate) fn push(&mut self, parts: &[&[u8]]) -> Result<()> {
let len: usize = parts.iter().map(|part| part.len()).sum();
self.bytes
.try_reserve(len + 1)
.map_err(|_| ErrorKind::OutOfMemory)?;
self.starts
.try_reserve(1)
.map_err(|_| ErrorKind::OutOfMemory)?;
if parts.iter().any(|part| part.contains(&0)) {
return Err(ErrorKind::InvalidInput.into());
}
self.starts.push(self.bytes.len());
for part in parts {
self.bytes.extend_from_slice(part);
}
self.bytes.push(0);
Ok(())
}
pub(crate) fn pointers(&mut self) -> Result<&[*const core::ffi::c_char]> {
self.pointers.clear();
self.pointers
.try_reserve_exact(self.starts.len() + 1)
.map_err(|_| ErrorKind::OutOfMemory)?;
let base = self.bytes.as_ptr();
for &start in &self.starts {
self.pointers.push(unsafe { base.add(start) }.cast());
}
self.pointers.push(core::ptr::null());
Ok(&self.pointers)
}
}
#[cfg(any(target_os = "linux", target_os = "fullrust", target_os = "macos"))]
pub mod unix {
use super::Signal;
#[cfg(feature = "alloc")]
use super::{Child, Command, ExitStatus, Status};
use crate::{ErrorKind, Result, sys};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Resource {
OpenFiles,
Stack,
CoreSize,
FileSize,
CpuTime,
AddressSpace,
Data,
LockedMemory,
Processes,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Limit {
pub soft: Option<u64>,
pub hard: Option<u64>,
}
pub fn limit(resource: Resource) -> Result<Limit> {
sys::process::limit(resource)
}
pub fn set_limit(resource: Resource, limit: Limit) -> Result<()> {
sys::process::set_limit(resource, limit)
}
pub const SIGHUP: i32 = 1;
pub const SIGINT: i32 = 2;
pub const SIGQUIT: i32 = 3;
pub const SIGKILL: i32 = 9;
pub const SIGTERM: i32 = 15;
pub const SIGSTOP: i32 = sys::process::SIGSTOP;
pub const SIGCONT: i32 = sys::process::SIGCONT;
pub const SIGUSR1: i32 = sys::process::SIGUSR1;
pub const SIGUSR2: i32 = sys::process::SIGUSR2;
pub const SIGPIPE: i32 = 13;
pub const SIGALRM: i32 = 14;
pub const SIGCHLD: i32 = sys::process::SIGCHLD;
pub const SIGWINCH: i32 = 28;
pub trait SignalExt {
fn from_raw(signal: i32) -> Self;
fn as_raw(&self) -> i32;
}
impl SignalExt for Signal {
fn from_raw(signal: i32) -> Self {
Self(signal)
}
fn as_raw(&self) -> i32 {
self.0
}
}
pub fn ignore_signal(signal: i32) -> Result<()> {
sys::process::signal::set_disposition(signal, true)
}
pub fn default_signal(signal: i32) -> Result<()> {
sys::process::signal::set_disposition(signal, false)
}
pub fn send_signal(pid: u32, signal: i32) -> Result<()> {
sys::process::send_signal(super::checked_pid(pid)? as i32, signal)
}
pub fn send_signal_to_group(pgid: u32, signal: i32) -> Result<()> {
if pgid == 1 {
return Err(ErrorKind::InvalidInput.into());
}
sys::process::send_signal(-(super::checked_pid(pgid)? as i32), signal)
}
pub fn process_group(pid: u32) -> Result<u32> {
sys::process::process_group(super::checked_pid(pid)?)
}
pub fn session(pid: u32) -> Result<u32> {
sys::process::session(super::checked_pid(pid)?)
}
#[cfg(feature = "alloc")]
pub trait CommandExt {
fn process_group(self, pgid: u32) -> Self;
fn new_session(self) -> Self;
}
#[cfg(feature = "alloc")]
impl CommandExt for Command<'_> {
fn process_group(mut self, pgid: u32) -> Self {
self.process_group = Some(pgid);
self
}
fn new_session(mut self) -> Self {
self.new_session = true;
self
}
}
#[cfg(feature = "alloc")]
pub trait ExitStatusExt {
fn signal(&self) -> Option<i32>;
fn core_dumped(&self) -> bool;
}
#[cfg(feature = "alloc")]
impl ExitStatusExt for ExitStatus {
fn signal(&self) -> Option<i32> {
match self.0 {
Status::Signaled(signal, _) => Some(signal),
Status::Exited(_) => None,
}
}
fn core_dumped(&self) -> bool {
matches!(self.0, Status::Signaled(_, true))
}
}
#[cfg(feature = "alloc")]
pub trait ChildExt {
fn send_signal(&self, signal: i32) -> Result<()>;
}
#[cfg(feature = "alloc")]
impl ChildExt for Child {
fn send_signal(&self, signal: i32) -> Result<()> {
if self.status.is_some() {
return Err(ErrorKind::NoSuchProcess.into());
}
self.inner.send_signal(signal)
}
}
}
#[cfg(windows)]
pub mod windows {
use super::Signal;
#[cfg(feature = "alloc")]
use super::{Child, Command};
#[cfg(feature = "alloc")]
use crate::AsPath;
use crate::{Result, sys};
pub const CTRL_BREAK: Signal = Signal(sys::process::signal::BREAK);
pub const CTRL_LOGOFF: Signal = Signal(sys::process::signal::LOGOFF);
pub fn send_ctrl_event(event: Signal, group: u32) -> Result<()> {
sys::process::signal::send_ctrl_event(event.0, group)
}
pub fn set_ctrl_c_ignored(ignored: bool) -> Result<()> {
sys::process::signal::set_ctrl_c_ignored(ignored)
}
#[cfg(feature = "alloc")]
pub trait CommandExt<'a> {
fn raw_command_line<S: AsPath + ?Sized>(self, line: &'a S) -> Self;
fn new_process_group(self) -> Self;
fn new_console(self) -> Self;
}
#[cfg(feature = "alloc")]
impl<'a> CommandExt<'a> for Command<'a> {
fn raw_command_line<S: AsPath + ?Sized>(mut self, line: &'a S) -> Self {
self.raw_command_line = Some(line.as_path_bytes());
self
}
fn new_process_group(mut self) -> Self {
self.new_process_group = true;
self
}
fn new_console(mut self) -> Self {
self.new_console = true;
self
}
}
#[cfg(feature = "alloc")]
pub trait ChildExt {
fn send_ctrl_break(&self) -> Result<()>;
}
#[cfg(feature = "alloc")]
impl ChildExt for Child {
fn send_ctrl_break(&self) -> Result<()> {
if self.status.is_some() {
return Err(crate::ErrorKind::InvalidInput.into());
}
send_ctrl_event(CTRL_BREAK, self.inner.id())
}
}
}