use core::ffi::{c_char, c_int};
pub(crate) mod signal;
use core::time::Duration;
use crate::path::with_cstr;
use crate::process::ResourceUsage;
use crate::process::unix::{Limit, Resource};
use crate::sys::{cvt, errno};
use crate::{Error, ErrorKind, Result};
const SIGKILL: c_int = 9;
pub(crate) const SIGSTOP: i32 = 17;
pub(crate) const SIGCONT: i32 = 19;
pub(crate) const SIGCHLD: i32 = 20;
pub(crate) const SIGUSR1: i32 = 30;
pub(crate) const SIGUSR2: i32 = 31;
unsafe extern "C" {
fn getpid() -> c_int;
fn getppid() -> c_int;
fn getpgid(pid: c_int) -> c_int;
fn getsid(pid: c_int) -> c_int;
#[link_name = "kill"]
fn c_kill(pid: c_int, signal: c_int) -> c_int;
fn faccessat(dir: c_int, path: *const c_char, mode: c_int, flags: c_int) -> c_int;
fn getrusage(who: c_int, usage: *mut RUsage) -> c_int;
fn getrlimit(resource: c_int, limit: *mut [u64; 2]) -> c_int;
fn setrlimit(resource: c_int, limit: *const [u64; 2]) -> c_int;
fn _exit(code: c_int) -> !;
#[link_name = "abort"]
fn c_abort() -> !;
}
pub(crate) fn id() -> u32 {
unsafe { getpid() as u32 }
}
pub(crate) fn parent_id() -> u32 {
unsafe { getppid() as u32 }
}
pub(crate) fn exit(code: i32) -> ! {
unsafe { _exit(code) }
}
pub(crate) fn abort() -> ! {
unsafe { c_abort() }
}
pub(crate) const HAS_PROCESSES: bool = true;
pub(crate) const SEARCH_SEPARATOR: u8 = b':';
pub(crate) const DIR_SEPARATOR: &[u8] = b"/";
pub(crate) const PROGRAM_SUFFIX: &[u8] = b"";
pub(crate) fn search_dir(entry: &[u8]) -> &[u8] {
entry
}
pub(crate) fn is_bare_name(name: &[u8]) -> bool {
!name.contains(&b'/')
}
pub(crate) fn is_program(path: &[u8]) -> bool {
const AT_FDCWD: c_int = -2;
const X_OK: c_int = 1;
const AT_EACCESS: c_int = 0x0010;
if !crate::sys::fs::metadata(path, true).is_ok_and(|metadata| metadata.is_file()) {
return false;
}
with_cstr(path, |path| {
cvt(unsafe { faccessat(AT_FDCWD, path.as_ptr(), X_OK, AT_EACCESS) })
})
.is_ok()
}
pub(crate) fn send_signal(pid: i32, signal: i32) -> Result<()> {
cvt(unsafe { c_kill(pid, signal) }).map(drop)
}
pub(crate) fn exists(pid: u32) -> Result<bool> {
match send_signal(pid as i32, 0) {
Ok(()) => Ok(true),
Err(error) => exists_from(error),
}
}
fn exists_from(error: Error) -> Result<bool> {
match error.raw_os_error() {
errno::ESRCH => Ok(false),
errno::EPERM => Ok(true),
_ => Err(error),
}
}
pub(crate) fn kill(pid: u32) -> Result<()> {
send_signal(pid as i32, SIGKILL)
}
#[repr(C)]
#[derive(Clone, Copy, Default)]
struct TimeVal {
seconds: i64,
micros: i32,
}
#[repr(C)]
#[derive(Clone, Copy, Default)]
pub(crate) struct RUsage {
user: TimeVal,
system: TimeVal,
max_rss: i64,
others: [i64; 13],
}
const _: () = assert!(size_of::<RUsage>() == 144);
pub(crate) fn usage_from(usage: &RUsage) -> ResourceUsage {
let time = |time: TimeVal| {
Duration::new(time.seconds.max(0) as u64, 0)
+ Duration::from_micros(time.micros.clamp(0, 999_999) as u64)
};
ResourceUsage {
user_time: time(usage.user),
system_time: time(usage.system),
max_resident_memory: usage.max_rss.max(0) as u64,
}
}
pub(crate) fn resource_usage() -> Result<ResourceUsage> {
const RUSAGE_SELF: c_int = 0;
let mut usage = RUsage::default();
cvt(unsafe { getrusage(RUSAGE_SELF, &raw mut usage) })?;
Ok(usage_from(&usage))
}
const UNLIMITED: u64 = 0x7fff_ffff_ffff_ffff;
fn resource_number(resource: Resource) -> c_int {
match resource {
Resource::CpuTime => 0,
Resource::FileSize => 1,
Resource::Data => 2,
Resource::Stack => 3,
Resource::CoreSize => 4,
Resource::AddressSpace => 5,
Resource::LockedMemory => 6,
Resource::Processes => 7,
Resource::OpenFiles => 8,
}
}
pub(crate) fn limit(resource: Resource) -> Result<Limit> {
let mut old = [0u64; 2];
cvt(unsafe { getrlimit(resource_number(resource), &raw mut old) })?;
let value = |raw: u64| (raw < UNLIMITED).then_some(raw);
Ok(Limit {
soft: value(old[0]),
hard: value(old[1]),
})
}
pub(crate) fn set_limit(resource: Resource, limit: Limit) -> Result<()> {
let raw = |value: Option<u64>| match value {
None => Ok(UNLIMITED),
Some(value) if value >= UNLIMITED => Err(Error::from(ErrorKind::InvalidInput)),
Some(value) => Ok(value),
};
let new = [raw(limit.soft)?, raw(limit.hard)?];
cvt(unsafe { setrlimit(resource_number(resource), &raw const new) }).map(drop)
}
pub(crate) fn process_group(pid: u32) -> Result<u32> {
cvt(unsafe { getpgid(pid as c_int) }).map(|pgid| pgid as u32)
}
pub(crate) fn session(pid: u32) -> Result<u32> {
cvt(unsafe { getsid(pid as c_int) }).map(|sid| sid as u32)
}
#[cfg(feature = "alloc")]
pub(crate) use spawn::{Child, spawn};
#[cfg(feature = "alloc")]
mod spawn {
use core::ffi::{c_char, c_int, c_short, c_void};
use core::ptr;
use core::sync::atomic::{AtomicBool, Ordering};
use super::{RUsage, SIGKILL, SIGSTOP, c_kill, usage_from};
use crate::process::{CStrings, Command, ExitStatus, ResourceUsage, Stdio};
use crate::sys::io::fcntl;
use crate::sys::{cvt, errno};
use crate::{Error, ErrorKind, OwnedHandle, Result};
type Opaque = *mut c_void;
type SigSet = u32;
unsafe extern "C" {
fn posix_spawn(
pid: *mut c_int,
path: *const c_char,
file_actions: *const Opaque,
attributes: *const Opaque,
argv: *const *const c_char,
envp: *const *const c_char,
) -> c_int;
fn posix_spawnattr_init(attributes: *mut Opaque) -> c_int;
fn posix_spawnattr_destroy(attributes: *mut Opaque) -> c_int;
fn posix_spawnattr_setflags(attributes: *mut Opaque, flags: c_short) -> c_int;
fn posix_spawnattr_setsigdefault(attributes: *mut Opaque, set: *const SigSet) -> c_int;
fn posix_spawnattr_setsigmask(attributes: *mut Opaque, set: *const SigSet) -> c_int;
fn posix_spawnattr_setpgroup(attributes: *mut Opaque, group: c_int) -> c_int;
fn posix_spawn_file_actions_init(actions: *mut Opaque) -> c_int;
fn posix_spawn_file_actions_destroy(actions: *mut Opaque) -> c_int;
fn posix_spawn_file_actions_addopen(
actions: *mut Opaque,
fd: c_int,
path: *const c_char,
flags: c_int,
mode: u16,
) -> c_int;
fn posix_spawn_file_actions_adddup2(actions: *mut Opaque, fd: c_int, new: c_int) -> c_int;
fn posix_spawn_file_actions_addinherit_np(actions: *mut Opaque, fd: c_int) -> c_int;
fn posix_spawn_file_actions_addchdir_np(actions: *mut Opaque, path: *const c_char)
-> c_int;
fn _NSGetEnviron() -> *mut *const *const c_char;
fn wait4(pid: c_int, status: *mut c_int, options: c_int, usage: *mut RUsage) -> c_int;
}
const POSIX_SPAWN_SETPGROUP: c_short = 0x0002;
const POSIX_SPAWN_SETSID: c_short = 0x0400;
const POSIX_SPAWN_SETSIGDEF: c_short = 0x0004;
const POSIX_SPAWN_SETSIGMASK: c_short = 0x0008;
const POSIX_SPAWN_CLOEXEC_DEFAULT: c_short = 0x4000;
const O_RDWR: c_int = 2;
const F_GETFD: c_int = 1;
const F_DUPFD_CLOEXEC: c_int = 67;
const WNOHANG: c_int = 1;
fn check(ret: c_int) -> Result<()> {
if ret == 0 {
Ok(())
} else {
Err(Error::from_raw_os_error(ret))
}
}
struct Attributes(Opaque);
impl Drop for Attributes {
fn drop(&mut self) {
unsafe { posix_spawnattr_destroy(&raw mut self.0) };
}
}
struct FileActions(Opaque);
impl Drop for FileActions {
fn drop(&mut self) {
unsafe { posix_spawn_file_actions_destroy(&raw mut self.0) };
}
}
#[derive(Debug)]
pub(crate) struct Child {
pid: c_int,
gone: AtomicBool,
}
pub(crate) fn spawn(command: &Command<'_>) -> Result<Child> {
let mut paths = CStrings::new();
match command.current_dir {
Some(_) if !command.program.is_empty() && !command.program.starts_with(b"/") => {
let here = crate::fs::current_dir_vec()?;
paths.push(&[&here, b"/", command.program])?;
}
_ => paths.push(&[command.program])?,
}
if let Some(dir) = command.current_dir {
paths.push(&[dir])?;
}
let group = match command.process_group {
None => None,
Some(group) => Some(c_int::try_from(group).map_err(|_| ErrorKind::InvalidInput)?),
};
let mut argv = CStrings::new();
argv.push(&[command.arg0.unwrap_or(command.program)])?;
for arg in command.args.iter() {
argv.push(&[arg])?;
}
let mut envp = CStrings::new();
if let Some(vars) = command.env {
for var in vars.iter() {
envp.push(&[var])?;
}
}
let paths = paths.pointers()?;
let argv = argv.pointers()?;
let envp = match command.env {
Some(_) => envp.pointers()?.as_ptr(),
None => unsafe { *_NSGetEnviron() },
};
let mut attributes = Attributes(ptr::null_mut());
check(unsafe { posix_spawnattr_init(&raw mut attributes.0) })?;
let default: SigSet = !(1 << (SIGKILL - 1) | 1 << (SIGSTOP - 1));
let mask: SigSet = 0;
let mut flags =
POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK | POSIX_SPAWN_CLOEXEC_DEFAULT;
if command.new_session {
flags |= POSIX_SPAWN_SETSID;
} else if let Some(group) = group {
flags |= POSIX_SPAWN_SETPGROUP;
check(unsafe { posix_spawnattr_setpgroup(&raw mut attributes.0, group) })?;
}
unsafe {
check(posix_spawnattr_setsigdefault(
&raw mut attributes.0,
&raw const default,
))?;
check(posix_spawnattr_setsigmask(
&raw mut attributes.0,
&raw const mask,
))?;
check(posix_spawnattr_setflags(&raw mut attributes.0, flags))?;
}
let mut actions = FileActions(ptr::null_mut());
check(unsafe { posix_spawn_file_actions_init(&raw mut actions.0) })?;
let mut held: [Option<OwnedHandle>; 3] = [None, None, None];
for (target, source) in command.stdio.iter().enumerate() {
let target = target as c_int;
check(unsafe {
match source {
Stdio::Inherit if fcntl(target, F_GETFD) == -1 => 0,
Stdio::Inherit => {
posix_spawn_file_actions_addinherit_np(&raw mut actions.0, target)
}
Stdio::Null => posix_spawn_file_actions_addopen(
&raw mut actions.0,
target,
c"/dev/null".as_ptr(),
O_RDWR,
0,
),
Stdio::Handle(handle) => {
let mut fd = handle.as_raw();
if fd == target {
posix_spawn_file_actions_addinherit_np(&raw mut actions.0, target)
} else {
if (0..3).contains(&fd) {
let min: c_int = 3;
fd = cvt(fcntl(fd, F_DUPFD_CLOEXEC, min))?;
held[target as usize] = Some(OwnedHandle::from_raw(fd));
}
posix_spawn_file_actions_adddup2(&raw mut actions.0, fd, target)
}
}
}
})?;
}
if command.current_dir.is_some() {
check(unsafe { posix_spawn_file_actions_addchdir_np(&raw mut actions.0, paths[1]) })?;
}
let mut pid: c_int = 0;
check(unsafe {
posix_spawn(
&raw mut pid,
paths[0],
&raw const actions.0,
&raw const attributes.0,
argv.as_ptr(),
envp,
)
})?;
drop(held);
Ok(Child {
pid,
gone: AtomicBool::new(false),
})
}
impl Child {
pub(crate) fn id(&self) -> u32 {
self.pid as u32
}
pub(crate) fn is_gone(&self) -> bool {
self.gone.load(Ordering::Acquire)
}
pub(crate) fn wait(
&self,
block: bool,
) -> Result<Option<(ExitStatus, Option<ResourceUsage>)>> {
if self.gone.load(Ordering::Acquire) {
return Err(Error::from_raw_os_error(errno::ECHILD));
}
let mut status: c_int = 0;
let mut usage = RUsage::default();
let options = if block { 0 } else { WNOHANG };
let waited = unsafe { wait4(self.pid, &raw mut status, options, &raw mut usage) };
let pid = match cvt(waited) {
Ok(pid) => pid,
Err(error) => {
if error.raw_os_error() == errno::ECHILD {
self.gone.store(true, Ordering::Release);
}
return Err(error);
}
};
if pid == 0 {
return Ok(None);
}
let signal = status & 0x7f;
let status = if signal == 0 {
ExitStatus::exited(status >> 8 & 0xff)
} else {
ExitStatus::signaled(signal, status & 0x80 != 0)
};
Ok(Some((status, Some(usage_from(&usage)))))
}
pub(crate) fn kill(&self) -> Result<()> {
if self.gone.load(Ordering::Acquire) {
return Ok(());
}
self.send_signal(SIGKILL)
}
pub(crate) fn send_signal(&self, signal: i32) -> Result<()> {
if self.pid <= 0 || self.gone.load(Ordering::Acquire) {
return Err(ErrorKind::NoSuchProcess.into());
}
cvt(unsafe { c_kill(self.pid, signal) }).map(drop)
}
}
}