pub(crate) mod contain;
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::{errno, syscall};
use crate::{Error, Result};
const SIGABRT: usize = 6;
const SIGKILL: usize = 9;
pub(crate) const SIGUSR1: i32 = 10;
pub(crate) const SIGUSR2: i32 = 12;
pub(crate) const SIGCHLD: i32 = 17;
pub(crate) const SIGCONT: i32 = 18;
pub(crate) const SIGSTOP: i32 = 19;
const AT_FDCWD: i32 = -100;
const SIG_UNBLOCK: usize = 1;
#[cfg(feature = "alloc")]
const SIG_SETMASK: usize = 2;
const SIGSET_SIZE: usize = 8;
type DefaultAction = [usize; 8];
pub(crate) fn id() -> u32 {
unsafe { syscall!(GETPID) }.map_or(0, |pid| pid as u32)
}
pub(crate) fn parent_id() -> u32 {
unsafe { syscall!(GETPPID) }.map_or(0, |pid| pid as u32)
}
pub(crate) fn exit(code: i32) -> ! {
loop {
let _ = unsafe { syscall!(EXIT_GROUP, code) };
}
}
pub(crate) fn abort() -> ! {
let action: DefaultAction = [0; 8];
let set: u64 = 1 << (SIGABRT - 1);
unsafe {
let pid = syscall!(GETPID).unwrap_or(0);
let tid = syscall!(GETTID).unwrap_or(0);
let _ = syscall!(TGKILL, pid, tid, SIGABRT);
let _ = syscall!(RT_SIGACTION, SIGABRT, action.as_ptr(), 0, SIGSET_SIZE);
let _ = syscall!(TGKILL, pid, tid, SIGABRT);
let _ = syscall!(RT_SIGPROCMASK, SIG_UNBLOCK, &raw const set, 0, SIGSET_SIZE);
}
exit(127)
}
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 X_OK: usize = 1;
const AT_EACCESS: usize = 0x200;
if !crate::sys::fs::metadata(path, true).is_ok_and(|metadata| metadata.is_file()) {
return false;
}
with_cstr(path, |path| {
let result = unsafe { syscall!(FACCESSAT2, AT_FDCWD, path.as_ptr(), X_OK, AT_EACCESS) };
match result {
Err(error) if error.raw_os_error() == errno::ENOSYS => {
unsafe { syscall!(FACCESSAT, AT_FDCWD, path.as_ptr(), X_OK) }
}
result => result,
}
})
.is_ok()
}
pub(crate) fn send_signal(pid: i32, signal: i32) -> Result<()> {
unsafe { syscall!(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 as i32)
}
pub(crate) type RUsage = [isize; 18];
pub(crate) fn usage_from(usage: &RUsage) -> ResourceUsage {
let time = |seconds: isize, micros: isize| {
Duration::new(seconds.max(0) as u64, 0)
+ Duration::from_micros(micros.clamp(0, 999_999) as u64)
};
ResourceUsage {
user_time: time(usage[0], usage[1]),
system_time: time(usage[2], usage[3]),
max_resident_memory: (usage[4].max(0) as u64).saturating_mul(1024),
}
}
pub(crate) fn resource_usage() -> Result<ResourceUsage> {
const RUSAGE_SELF: usize = 0;
let mut usage: RUsage = [0; 18];
unsafe { syscall!(GETRUSAGE, RUSAGE_SELF, &raw mut usage) }?;
Ok(usage_from(&usage))
}
const UNLIMITED: u64 = u64::MAX;
fn resource_number(resource: Resource) -> usize {
match resource {
Resource::CpuTime => 0,
Resource::FileSize => 1,
Resource::Data => 2,
Resource::Stack => 3,
Resource::CoreSize => 4,
Resource::Processes => 6,
Resource::OpenFiles => 7,
Resource::LockedMemory => 8,
Resource::AddressSpace => 9,
}
}
pub(crate) fn limit(resource: Resource) -> Result<Limit> {
let mut old = [0u64; 2];
unsafe { syscall!(PRLIMIT64, 0, resource_number(resource), 0, &raw mut old) }?;
let value = |raw: u64| (raw != UNLIMITED).then_some(raw);
Ok(Limit {
soft: value(old[0]),
hard: value(old[1]),
})
}
fn raw_limit(limit: Limit) -> Result<[u64; 2]> {
let raw = |value: Option<u64>| match value {
None => Ok(UNLIMITED),
Some(UNLIMITED) => Err(Error::from(crate::ErrorKind::InvalidInput)),
Some(value) => Ok(value),
};
Ok([raw(limit.soft)?, raw(limit.hard)?])
}
pub(crate) fn set_limit(resource: Resource, limit: Limit) -> Result<()> {
let new = raw_limit(limit)?;
unsafe { syscall!(PRLIMIT64, 0, resource_number(resource), &raw const new, 0) }.map(drop)
}
pub(crate) fn process_group(pid: u32) -> Result<u32> {
unsafe { syscall!(GETPGID, pid) }.map(|pgid| pgid as u32)
}
pub(crate) fn session(pid: u32) -> Result<u32> {
unsafe { syscall!(GETSID, pid) }.map(|sid| sid as u32)
}
#[cfg(feature = "alloc")]
pub(crate) use spawn::{Child, fork, spawn, wait_pidfd};
#[cfg(feature = "alloc")]
mod setup;
#[cfg(feature = "alloc")]
mod spawn {
use core::ffi::{c_char, c_void};
use super::contain::{self, CloneArgs};
use super::setup::Setup;
use super::{
AT_FDCWD, DefaultAction, RUsage, SIG_SETMASK, SIGCHLD, SIGKILL, SIGSET_SIZE, SIGSTOP,
usage_from,
};
use crate::mem::Protection;
use crate::process::{CStrings, Command, ExitStatus, ResourceUsage, Stdio};
use crate::sys::io::fcntl;
use crate::sys::{check, errno, mem, nr, syscall};
use crate::{AsHandle, BorrowedHandle, Error, ErrorKind, OwnedHandle, Result};
#[cfg(not(feature = "std"))]
const O_RDONLY: usize = 0;
const O_RDWR: usize = 2;
const O_CLOEXEC: usize = 0o2000000;
const F_SETFD: usize = 2;
const F_DUPFD_CLOEXEC: usize = 1030;
const CSIGNAL: usize = 0xff;
const CLONE_VM: usize = 0x100;
const CLONE_PIDFD: usize = 0x1000;
const CLONE_VFORK: usize = 0x4000;
const P_PID: usize = 1;
const P_PIDFD: usize = 3;
const WNOHANG: usize = 1;
const WEXITED: usize = 4;
const CLD_EXITED: i32 = 1;
const CLD_KILLED: i32 = 2;
const CLD_DUMPED: i32 = 3;
const SIGNALS: usize = 64;
const STACK_SIZE: usize = 64 * 1024;
#[repr(C)]
struct Exec {
program: *const c_char,
argv: *const *const c_char,
envp: *const *const c_char,
dir: *const c_char,
stdio: [i32; 3],
error: i32,
session: bool,
group: i32,
sync: [i32; 2],
cgroup: i32,
no_new_privileges: bool,
setup: Setup,
}
#[cfg(target_arch = "x86_64")]
#[unsafe(naked)]
unsafe extern "C" fn clone_vfork(
flags: usize,
stack: *mut u8,
pidfd: *mut i32,
f: unsafe extern "C" fn(*mut c_void) -> !,
arg: *mut c_void,
) -> isize {
core::arch::naked_asm!(
"and rsi, -16",
"sub rsi, 16",
"mov [rsi], rcx",
"mov [rsi + 8], r8",
"xor r10d, r10d",
"xor r8d, r8d",
"mov eax, {clone}",
"syscall",
"test rax, rax",
"jz 2f",
"ret",
"2:",
"xor ebp, ebp",
"pop rax",
"pop rdi",
"call rax",
"ud2",
clone = const nr::CLONE,
)
}
#[cfg(target_arch = "x86")]
#[unsafe(naked)]
unsafe extern "C" fn clone_vfork(
flags: usize,
stack: *mut u8,
pidfd: *mut i32,
f: unsafe extern "C" fn(*mut c_void) -> !,
arg: *mut c_void,
) -> isize {
core::arch::naked_asm!(
"push ebx",
"mov ecx, [esp + 12]",
"and ecx, -16",
"sub ecx, 16",
"mov eax, [esp + 24]",
"mov [ecx], eax",
"mov eax, [esp + 20]",
"mov [ecx + 4], eax",
"mov ebx, [esp + 8]",
"mov edx, [esp + 16]",
"mov eax, {clone}",
"int 0x80",
"test eax, eax",
"jz 2f",
"pop ebx",
"ret",
"2:",
"xor ebp, ebp",
"mov eax, [esp + 4]",
"call eax",
"ud2",
clone = const nr::CLONE,
)
}
#[cfg(target_arch = "aarch64")]
#[unsafe(naked)]
unsafe extern "C" fn clone_vfork(
flags: usize,
stack: *mut u8,
pidfd: *mut i32,
f: unsafe extern "C" fn(*mut c_void) -> !,
arg: *mut c_void,
) -> isize {
core::arch::naked_asm!(
"hint #34",
"and x1, x1, #-16",
"stp x3, x4, [x1, #-16]!",
"mov x3, #0",
"mov x4, #0",
"mov x8, {clone}",
"svc #0",
"cbz x0, 2f",
"ret",
"2:",
"mov x29, #0",
"mov x30, #0",
"ldp x1, x0, [sp]",
"blr x1",
"brk #1",
clone = const nr::CLONE,
)
}
#[cfg(target_arch = "arm")]
#[unsafe(naked)]
unsafe extern "C" fn clone_vfork(
flags: usize,
stack: *mut u8,
pidfd: *mut i32,
f: unsafe extern "C" fn(*mut c_void) -> !,
arg: *mut c_void,
) -> isize {
core::arch::naked_asm!(
"push {{r4, r7}}",
"ldr r4, [sp, #8]",
"bic r1, r1, #15",
"str r4, [r1, #-4]!",
"str r3, [r1, #-4]!",
"mov r7, #{clone}",
"svc 0",
"cmp r0, #0",
"beq 2f",
"pop {{r4, r7}}",
"bx lr",
"2:",
"mov r11, #0",
"mov lr, #0",
"ldr r1, [sp]",
"ldr r0, [sp, #4]",
"blx r1",
"udf #0",
clone = const nr::CLONE,
)
}
#[cfg(any(target_arch = "riscv32", target_arch = "riscv64"))]
#[unsafe(naked)]
unsafe extern "C" fn clone_vfork(
flags: usize,
stack: *mut u8,
pidfd: *mut i32,
f: unsafe extern "C" fn(*mut c_void) -> !,
arg: *mut c_void,
) -> isize {
#[cfg(target_arch = "riscv64")]
core::arch::naked_asm!(
"andi a1, a1, -16",
"addi a1, a1, -16",
"sd a3, 0(a1)",
"sd a4, 8(a1)",
"li a7, {clone}",
"ecall",
"beqz a0, 2f",
"ret",
"2:",
"mv s0, zero",
"mv ra, zero",
"ld a1, 0(sp)",
"ld a0, 8(sp)",
"jalr a1",
"unimp",
clone = const nr::CLONE,
);
#[cfg(target_arch = "riscv32")]
core::arch::naked_asm!(
"andi a1, a1, -16",
"addi a1, a1, -16",
"sw a3, 0(a1)",
"sw a4, 4(a1)",
"li a7, {clone}",
"ecall",
"beqz a0, 2f",
"ret",
"2:",
"mv s0, zero",
"mv ra, zero",
"lw a1, 0(sp)",
"lw a0, 4(sp)",
"jalr a1",
"unimp",
clone = const nr::CLONE,
);
}
unsafe extern "C" fn child(arg: *mut c_void) -> ! {
let exec = unsafe { &*arg.cast::<Exec>() };
let code = unsafe { exec_program(exec) }.raw_os_error();
unsafe {
let _ = syscall!(WRITE, exec.error, &raw const code, size_of::<i32>());
loop {
let _ = syscall!(EXIT_GROUP, 127);
}
}
}
unsafe fn exec_program(exec: &Exec) -> Error {
let result: Result<usize> = unsafe {
(|| {
if exec.sync[0] >= 0 {
let _ = syscall!(CLOSE, exec.sync[1]);
let mut byte = 0u8;
if syscall!(READ, exec.sync[0], &raw mut byte, 1usize)? != 1 {
return Err(Error::from_raw_os_error(errno::ECANCELED));
}
}
if exec.cgroup >= 0 {
contain::join_cgroup(exec.cgroup)?;
}
let action: DefaultAction = [0; 8];
let mut signal = 1;
while signal <= SIGNALS {
if signal != SIGKILL && signal != SIGSTOP as usize {
let _ = syscall!(RT_SIGACTION, signal, action.as_ptr(), 0, SIGSET_SIZE);
}
signal += 1;
}
if exec.session {
syscall!(SETSID)?;
} else if exec.group >= 0 {
syscall!(SETPGID, 0, exec.group)?;
}
let mut target = 0;
while target < 3 {
let fd = exec.stdio[target as usize];
if fd == target {
fcntl(fd, F_SETFD, 0)?;
} else if fd >= 0 {
syscall!(DUP3, fd, target, 0)?;
}
target += 1;
}
if exec.error > 3 {
let _ = syscall!(CLOSE_RANGE, 3, exec.error - 1, 0);
}
let _ = syscall!(CLOSE_RANGE, exec.error + 1, u32::MAX, 0);
exec.setup.apply()?;
if !exec.dir.is_null() {
syscall!(CHDIR, exec.dir)?;
}
let none: u64 = 0;
syscall!(RT_SIGPROCMASK, SIG_SETMASK, &raw const none, 0, SIGSET_SIZE)?;
if exec.no_new_privileges {
syscall!(
PRCTL,
contain::PR_SET_NO_NEW_PRIVS,
1usize,
0usize,
0usize,
0usize
)?;
}
syscall!(EXECVE, exec.program, exec.argv, exec.envp)
})()
};
match result {
Err(error) => error,
Ok(_) => Error::from_raw_os_error(errno::EIO),
}
}
fn inherited_environment(env: &mut CStrings) -> Result<()> {
#[cfg(feature = "std")]
for (name, value) in std::env::vars_os() {
env.push(&[name.as_encoded_bytes(), b"=", value.as_encoded_bytes()])?;
}
#[cfg(not(feature = "std"))]
{
let path = c"/proc/self/environ";
let fd = unsafe { syscall!(OPENAT, AT_FDCWD, path.as_ptr(), O_RDONLY | O_CLOEXEC, 0) }?;
let file = unsafe { OwnedHandle::from_raw(fd as i32) };
let mut data = alloc::vec::Vec::<u8>::new();
loop {
data.try_reserve(4096).map_err(|_| ErrorKind::OutOfMemory)?;
let spare = data.spare_capacity_mut();
let n = unsafe { syscall!(READ, file.as_raw(), spare.as_mut_ptr(), spare.len()) }?;
if n == 0 {
break;
}
unsafe { data.set_len(data.len() + n) };
}
for variable in data.split(|byte| *byte == 0) {
if !variable.is_empty() {
env.push(&[variable])?;
}
}
}
Ok(())
}
fn duplicate_above_stdio(fd: i32) -> Result<OwnedHandle> {
let new = unsafe { fcntl(fd, F_DUPFD_CLOEXEC, 3) }?;
Ok(unsafe { OwnedHandle::from_raw(new as i32) })
}
struct Stack(*mut u8);
impl Drop for Stack {
fn drop(&mut self) {
let _ = unsafe { mem::unmap(self.0, STACK_SIZE) };
}
}
pub(crate) struct Child {
pid: u32,
pidfd: OwnedHandle,
}
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()?;
if !here.starts_with(b"/") {
return Err(ErrorKind::NotFound.into());
}
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 => -1,
Some(group) => i32::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();
match command.env {
Some(vars) => {
for var in vars.iter() {
envp.push(&[var])?;
}
}
None => inherited_environment(&mut envp)?,
}
let paths = paths.pointers()?;
let argv = argv.pointers()?;
let envp = envp.pointers()?;
let mut limits = alloc::vec::Vec::new();
let setup = Setup::new(command, &mut limits)?;
let own_memory = setup.changes_identity();
let namespaces = contain::clone_flags(command.linux.namespaces);
let maps = contain::Maps::new(&command.linux)?;
let sync = match maps {
Some(_) => Some(crate::sys::io::pipe()?),
None => None,
};
let cgroup = command.linux.cgroup.map(|cgroup| cgroup.as_raw());
let mut held: [Option<OwnedHandle>; 4] = [None, None, None, None];
let mut held_count = 0;
let mut null = None;
let mut stdio = [-1; 3];
for (target, source) in command.stdio.iter().enumerate() {
let fd = match source {
Stdio::Inherit => continue,
Stdio::Handle(handle) => handle.as_raw(),
Stdio::Null => match null {
Some(fd) => fd,
None => {
let path = c"/dev/null";
let fd = unsafe {
syscall!(OPENAT, AT_FDCWD, path.as_ptr(), O_RDWR | O_CLOEXEC, 0)
}? as i32;
held[held_count] = Some(unsafe { OwnedHandle::from_raw(fd) });
held_count += 1;
null = Some(fd);
fd
}
},
};
if fd < 0 {
return Err(ErrorKind::BadHandle.into());
}
stdio[target] = if fd < 3 && fd != target as i32 {
let moved = duplicate_above_stdio(fd)?;
let fd = moved.as_raw();
held[held_count] = Some(moved);
held_count += 1;
fd
} else {
fd
};
}
let (error_read, mut error_write) = crate::sys::io::pipe()?;
if error_write.as_raw() < 3 {
error_write = duplicate_above_stdio(error_write.as_raw())?;
}
let mut exec = Exec {
program: paths[0],
argv: argv.as_ptr(),
envp: envp.as_ptr(),
dir: if command.current_dir.is_some() {
paths[1]
} else {
core::ptr::null()
},
stdio,
error: error_write.as_raw(),
session: command.new_session,
group,
sync: match &sync {
Some((read, write)) => [read.as_raw(), write.as_raw()],
None => [-1, -1],
},
cgroup: -1,
no_new_privileges: command.linux.no_new_privileges,
setup,
};
let stack = Stack(crate::mem::map_anonymous(
STACK_SIZE,
Protection::READ | Protection::WRITE,
)?);
let stack_end = unsafe { stack.0.add(STACK_SIZE) };
let all: u64 = !0;
let mut saved: u64 = 0;
unsafe {
syscall!(
RT_SIGPROCMASK,
SIG_SETMASK,
&raw const all,
&raw mut saved,
SIGSET_SIZE
)
}?;
let suspend = if sync.is_some() { 0 } else { CLONE_VFORK };
let memory = if own_memory { 0 } else { CLONE_VM };
let mut pidfd: i32 = -1;
let mut cloned = None;
let time = namespaces & CSIGNAL;
if cgroup.is_some() || time != 0 {
let args = CloneArgs {
flags: (memory | suspend | CLONE_PIDFD | namespaces) as u64
| if cgroup.is_some() {
contain::CLONE_INTO_CGROUP
} else {
0
},
pidfd: (&raw mut pidfd).addr() as u64,
exit_signal: SIGCHLD as u64,
stack: stack.0.addr() as u64,
stack_size: STACK_SIZE as u64,
cgroup: cgroup.unwrap_or(0) as u64,
..CloneArgs::default()
};
let result = check(unsafe {
contain::clone3_vfork(
&raw const args,
size_of::<CloneArgs>(),
child,
(&raw mut exec).cast(),
) as usize
});
match result {
Err(error) if error.raw_os_error() == errno::ENOSYS && time == 0 => {
pidfd = -1;
exec.cgroup = cgroup.unwrap_or(-1);
}
result => cloned = Some(result),
}
}
let exec = (&raw mut exec).cast::<c_void>();
let cloned = match cloned {
Some(cloned) => cloned,
None => {
let flags = memory | suspend | namespaces | SIGCHLD as usize;
let mut cloned = check(unsafe {
clone_vfork(flags | CLONE_PIDFD, stack_end, &raw mut pidfd, child, exec)
as usize
});
if matches!(cloned, Err(error) if error.raw_os_error() == errno::EINVAL) {
pidfd = -1;
cloned = check(unsafe {
clone_vfork(flags, stack_end, &raw mut pidfd, child, exec) as usize
});
}
cloned
}
};
drop(error_write);
let mut failure = None;
if let Ok(pid) = cloned {
let released = match (&maps, &sync) {
(Some(maps), Some((_, write))) => maps.write(pid as u32).and_then(|()| {
unsafe { syscall!(WRITE, write.as_raw(), b"m".as_ptr(), 1usize) }.map(drop)
}),
_ => Ok(()),
};
let mut code: i32 = 0;
let read = released.and_then(|()| {
unsafe { syscall!(READ, error_read.as_raw(), &raw mut code, size_of::<i32>()) }
});
match read {
Ok(0) => {}
Ok(n) if n == size_of::<i32>() => {
failure = Some(Error::from_raw_os_error(code));
let _ = unsafe { syscall!(WAITID, P_PID, pid, 0, WEXITED, 0) };
}
read if sync.is_some() => {
failure = Some(match read {
Err(error) => error,
Ok(_) => Error::from_raw_os_error(errno::EIO),
});
unsafe {
let _ = syscall!(KILL, pid, SIGKILL);
let _ = syscall!(WAITID, P_PID, pid, 0, WEXITED, 0);
}
}
_ => {}
}
}
drop(sync);
let _ = unsafe {
syscall!(
RT_SIGPROCMASK,
SIG_SETMASK,
&raw const saved,
0,
SIGSET_SIZE
)
};
drop(stack);
drop(held);
let pid = cloned?;
let pidfd = (pidfd >= 0).then(|| unsafe { OwnedHandle::from_raw(pidfd) });
if let Some(error) = failure {
return Err(error);
}
let pidfd = match pidfd {
Some(pidfd) => pidfd,
None => match unsafe { syscall!(PIDFD_OPEN, pid, 0) } {
Ok(fd) => unsafe { OwnedHandle::from_raw(fd as i32) },
Err(error) => {
unsafe {
let _ = syscall!(KILL, pid, SIGKILL);
let _ = syscall!(WAITID, P_PID, pid, 0, WEXITED, 0);
}
return Err(error);
}
},
};
Ok(Child {
pid: pid as u32,
pidfd,
})
}
pub(crate) unsafe fn fork() -> Result<Option<Child>> {
let flags = SIGCHLD as usize;
let mut pidfd: i32 = -1;
let mut cloned = unsafe { syscall!(CLONE, flags | CLONE_PIDFD, 0, &raw mut pidfd, 0, 0) };
if matches!(cloned, Err(error) if error.raw_os_error() == errno::EINVAL) {
pidfd = -1;
cloned = unsafe { syscall!(CLONE, flags, 0, 0, 0, 0) };
}
let pid = cloned?;
if pid == 0 {
return Ok(None);
}
let pidfd = if pidfd >= 0 {
unsafe { OwnedHandle::from_raw(pidfd) }
} else {
match unsafe { syscall!(PIDFD_OPEN, pid, 0) } {
Ok(fd) => unsafe { OwnedHandle::from_raw(fd as i32) },
Err(error) => {
unsafe {
let _ = syscall!(KILL, pid, SIGKILL);
let _ = syscall!(WAITID, P_PID, pid, 0, WEXITED, 0);
}
return Err(error);
}
}
};
Ok(Some(Child {
pid: pid as u32,
pidfd,
}))
}
#[repr(C, align(8))]
struct SigInfo([i32; 32]);
const SI_CODE: usize = 2;
const SI_FIELDS: usize = if cfg!(target_pointer_width = "64") {
4
} else {
3
};
const SI_PID: usize = SI_FIELDS;
const SI_STATUS: usize = SI_FIELDS + 2;
impl Child {
pub(crate) fn id(&self) -> u32 {
self.pid
}
pub(crate) fn handle(&self) -> BorrowedHandle<'_> {
self.pidfd.as_handle()
}
pub(crate) fn wait(
&self,
block: bool,
) -> Result<Option<(ExitStatus, Option<ResourceUsage>)>> {
wait_pidfd(self.pidfd.as_raw(), block)
}
pub(crate) fn kill(&self) -> Result<()> {
match self.send_signal(SIGKILL as i32) {
Err(error) if error.raw_os_error() == errno::ESRCH => Ok(()),
result => result,
}
}
pub(crate) fn send_signal(&self, signal: i32) -> Result<()> {
contain::pidfd_send_signal(self.pidfd.as_raw(), signal)
}
}
pub(crate) fn wait_pidfd(
pidfd: i32,
block: bool,
) -> Result<Option<(ExitStatus, Option<ResourceUsage>)>> {
let mut info = SigInfo([0; 32]);
let mut usage: RUsage = [0; 18];
let options = if block { WEXITED } else { WEXITED | WNOHANG };
unsafe {
syscall!(
WAITID,
P_PIDFD,
pidfd,
&raw mut info,
options,
&raw mut usage
)
}?;
let info = info.0;
if info[SI_PID] == 0 {
return Ok(None);
}
let status = info[SI_STATUS];
let status = match info[SI_CODE] {
CLD_EXITED => ExitStatus::exited(status),
CLD_KILLED => ExitStatus::signaled(status, false),
CLD_DUMPED => ExitStatus::signaled(status, true),
_ => return Err(ErrorKind::Other.into()),
};
Ok(Some((status, Some(usage_from(&usage)))))
}
impl core::fmt::Debug for Child {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("Child")
.field("pid", &self.pid)
.field("pidfd", &self.pidfd)
.finish()
}
}
}