use core::ffi::c_void;
pub(crate) mod signal;
use core::time::Duration;
use crate::process::ResourceUsage;
use crate::sys::{cvt, dll, last_error};
use crate::{Error, OwnedHandle, Result};
dll!("kernel32.dll" {
fn GetCurrentProcessId() -> u32;
fn GetCurrentProcess() -> *mut c_void;
fn ExitProcess(code: u32) -> !;
fn TerminateProcess(process: *mut c_void, code: u32) -> i32;
fn OpenProcess(access: u32, inherit: i32, pid: u32) -> *mut c_void;
fn WaitForSingleObject(handle: *mut c_void, milliseconds: u32) -> u32;
});
const PROCESS_TERMINATE: u32 = 0x0001;
const SYNCHRONIZE: u32 = 0x0010_0000;
const WAIT_OBJECT_0: u32 = 0;
const WAIT_TIMEOUT: u32 = 258;
const ERROR_ACCESS_DENIED: i32 = 5;
const ERROR_INVALID_PARAMETER: i32 = 87;
dll!("ntdll.dll" {
fn NtQueryInformationProcess(
process: *mut c_void,
class: u32,
info: *mut c_void,
len: u32,
returned: *mut u32,
) -> i32;
fn RtlNtStatusToDosError(status: i32) -> u32;
});
const PROCESS_BASIC_INFORMATION: u32 = 0;
const INHERITED_FROM_UNIQUE_PROCESS_ID: usize = 5;
#[cfg(not(any(target_arch = "x86", target_arch = "x86_64", target_arch = "aarch64")))]
const FAIL_FAST_EXIT_CODE: u32 = 0xc000_0409;
pub(crate) fn id() -> u32 {
unsafe { GetCurrentProcessId() }
}
pub(crate) fn parent_id() -> u32 {
let mut info = [0usize; 6];
let status = unsafe {
NtQueryInformationProcess(
GetCurrentProcess(),
PROCESS_BASIC_INFORMATION,
info.as_mut_ptr().cast(),
size_of_val(&info) as u32,
core::ptr::null_mut(),
)
};
if status < 0 {
return 0;
}
info[INHERITED_FROM_UNIQUE_PROCESS_ID] as u32
}
const PROCESS_VM_COUNTERS: u32 = 3;
const PEAK_WORKING_SET_SIZE: usize = 3;
const PROCESS_TIMES: u32 = 4;
fn usage_of(process: *mut c_void) -> Result<ResourceUsage> {
let mut times = [0i64; 4];
let mut memory = [0usize; 11];
let statuses = unsafe {
[
NtQueryInformationProcess(
process,
PROCESS_TIMES,
times.as_mut_ptr().cast(),
size_of_val(×) as u32,
core::ptr::null_mut(),
),
NtQueryInformationProcess(
process,
PROCESS_VM_COUNTERS,
memory.as_mut_ptr().cast(),
size_of_val(&memory) as u32,
core::ptr::null_mut(),
),
]
};
for status in statuses {
if status < 0 {
let code = unsafe { RtlNtStatusToDosError(status) };
return Err(Error::from_raw_os_error(code as i32));
}
}
let time = |units: i64| {
let units = units.max(0) as u64;
Duration::new(units / 10_000_000, (units % 10_000_000) as u32 * 100)
};
Ok(ResourceUsage {
user_time: time(times[3]),
system_time: time(times[2]),
max_resident_memory: memory[PEAK_WORKING_SET_SIZE] as u64,
})
}
pub(crate) fn resource_usage() -> Result<ResourceUsage> {
usage_of(unsafe { GetCurrentProcess() })
}
pub(crate) fn exit(code: i32) -> ! {
unsafe { ExitProcess(code as u32) }
}
pub(crate) fn abort() -> ! {
const FAST_FAIL_FATAL_APP_EXIT: u32 = 7;
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
unsafe {
core::arch::asm!(
"int 0x29",
in("ecx") FAST_FAIL_FATAL_APP_EXIT,
options(noreturn, nostack),
)
}
#[cfg(target_arch = "aarch64")]
unsafe {
core::arch::asm!(
"brk 0xf003",
in("x0") FAST_FAIL_FATAL_APP_EXIT as u64,
options(noreturn, nostack),
)
}
#[cfg(not(any(target_arch = "x86", target_arch = "x86_64", target_arch = "aarch64")))]
loop {
let _ = FAST_FAIL_FATAL_APP_EXIT;
unsafe { TerminateProcess(GetCurrentProcess(), FAIL_FAST_EXIT_CODE) };
}
}
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".exe";
pub(crate) fn search_dir(entry: &[u8]) -> &[u8] {
let entry = entry.strip_prefix(b"\"").unwrap_or(entry);
entry.strip_suffix(b"\"").unwrap_or(entry)
}
pub(crate) fn is_bare_name(name: &[u8]) -> bool {
!name.iter().any(|&c| matches!(c, b'/' | b'\\' | b':'))
}
pub(crate) fn is_program(path: &[u8]) -> bool {
crate::sys::fs::metadata(path, true).is_ok_and(|metadata| metadata.is_file())
}
fn open(pid: u32, access: u32) -> Result<OwnedHandle> {
let handle = unsafe { OpenProcess(access, 0, pid) };
if handle.is_null() {
return Err(last_error());
}
Ok(unsafe { OwnedHandle::from_raw(handle) })
}
pub(crate) fn exists(pid: u32) -> Result<bool> {
match open(pid, SYNCHRONIZE) {
Ok(process) => match unsafe { WaitForSingleObject(process.as_raw(), 0) } {
WAIT_TIMEOUT => Ok(true),
WAIT_OBJECT_0 => Ok(false),
_ => Err(last_error()),
},
Err(error) => match error.raw_os_error() {
ERROR_INVALID_PARAMETER => Ok(false),
ERROR_ACCESS_DENIED => Ok(true),
_ => Err(error),
},
}
}
pub(crate) fn kill(pid: u32) -> Result<()> {
let process = open(pid, PROCESS_TERMINATE | SYNCHRONIZE)?;
let result = cvt(unsafe { TerminateProcess(process.as_raw(), 1) });
if result.is_err() && unsafe { WaitForSingleObject(process.as_raw(), 0) } == WAIT_OBJECT_0 {
return Err(Error::from_raw_os_error(ERROR_INVALID_PARAMETER));
}
result
}
#[cfg(feature = "alloc")]
pub(crate) use spawn::{Child, spawn};
#[cfg(feature = "alloc")]
mod spawn {
use alloc::vec::Vec;
use core::ffi::c_void;
use core::ptr;
use super::{
GetCurrentProcess, TerminateProcess, WAIT_OBJECT_0, WAIT_TIMEOUT, WaitForSingleObject,
usage_of,
};
use crate::path::with_wide;
use crate::process::{Command, ExitStatus, ResourceUsage, Stdio};
use crate::sys::{cvt, dll, last_error};
use crate::{AsHandle, BorrowedHandle, ErrorKind, OwnedHandle, Result};
#[repr(C)]
struct SecurityAttributes {
len: u32,
descriptor: *mut c_void,
inherit: i32,
}
#[repr(C)]
struct StartupInfoEx {
cb: u32,
reserved: *mut u16,
desktop: *mut u16,
title: *mut u16,
x: u32,
y: u32,
x_size: u32,
y_size: u32,
x_count_chars: u32,
y_count_chars: u32,
fill_attribute: u32,
flags: u32,
show_window: u16,
reserved2_len: u16,
reserved2: *mut u8,
stdin: *mut c_void,
stdout: *mut c_void,
stderr: *mut c_void,
attribute_list: *mut c_void,
}
#[repr(C)]
struct ProcessInformation {
process: *mut c_void,
thread: *mut c_void,
process_id: u32,
thread_id: u32,
}
dll!("kernel32.dll" {
fn CreateProcessW(
application: *const u16,
command_line: *mut u16,
process_attributes: *const c_void,
thread_attributes: *const c_void,
inherit_handles: i32,
flags: u32,
environment: *const c_void,
directory: *const u16,
startup: *const StartupInfoEx,
info: *mut ProcessInformation,
) -> i32;
fn InitializeProcThreadAttributeList(
list: *mut c_void,
count: u32,
flags: u32,
size: *mut usize,
) -> i32;
fn UpdateProcThreadAttribute(
list: *mut c_void,
flags: u32,
attribute: usize,
value: *const c_void,
size: usize,
previous: *mut c_void,
returned: *const usize,
) -> i32;
fn DeleteProcThreadAttributeList(list: *mut c_void);
fn DuplicateHandle(
source_process: *mut c_void,
source: *mut c_void,
target_process: *mut c_void,
target: *mut *mut c_void,
access: u32,
inherit: i32,
options: u32,
) -> i32;
fn CreateFileW(
name: *const u16,
access: u32,
share: u32,
security: *const c_void,
creation: u32,
flags: u32,
template: *mut c_void,
) -> *mut c_void;
fn GetExitCodeProcess(process: *mut c_void, code: *mut u32) -> i32;
fn GetFullPathNameW(
path: *const u16,
len: u32,
buf: *mut u16,
file_part: *mut *mut u16,
) -> u32;
fn CompareStringOrdinal(
a: *const u16,
a_len: i32,
b: *const u16,
b_len: i32,
ignore_case: i32,
) -> i32;
});
const DUPLICATE_SAME_ACCESS: u32 = 2;
const GENERIC_READ: u32 = 0x8000_0000;
const GENERIC_WRITE: u32 = 0x4000_0000;
const FILE_SHARE_READ_WRITE: u32 = 0x1 | 0x2;
const OPEN_EXISTING: u32 = 3;
const CREATE_NEW_CONSOLE: u32 = 0x10;
const CREATE_NEW_PROCESS_GROUP: u32 = 0x200;
const CREATE_UNICODE_ENVIRONMENT: u32 = 0x400;
const EXTENDED_STARTUPINFO_PRESENT: u32 = 0x8_0000;
const STARTF_USESTDHANDLES: u32 = 0x100;
const PROC_THREAD_ATTRIBUTE_HANDLE_LIST: usize = 0x2_0002;
const INFINITE: u32 = u32::MAX;
const ERROR_INVALID_HANDLE: i32 = 6;
const QUOTE: u16 = b'"' as u16;
const BACKSLASH: u16 = b'\\' as u16;
fn reserve<T>(vec: &mut Vec<T>, additional: usize) -> Result<()> {
vec.try_reserve(additional)
.map_err(|_| ErrorKind::OutOfMemory.into())
}
fn push_wide(out: &mut Vec<u16>, bytes: &[u8]) -> Result<()> {
with_wide(bytes, |wide| {
let wide = &wide[..wide.len() - 1];
reserve(out, wide.len())?;
out.extend_from_slice(wide);
Ok(())
})
}
fn wide_string(bytes: &[u8]) -> Result<Vec<u16>> {
let mut out = Vec::new();
push_wide(&mut out, bytes)?;
reserve(&mut out, 1)?;
out.push(0);
Ok(out)
}
fn push_argument(line: &mut Vec<u16>, arg: &[u8]) -> Result<()> {
let mut units = Vec::new();
push_wide(&mut units, arg)?;
let quote = units.is_empty()
|| units
.iter()
.any(|&unit| unit == b' ' as u16 || unit == b'\t' as u16);
reserve(line, 2 * units.len() + 3)?;
if quote {
line.push(QUOTE);
}
let mut backslashes = 0;
for &unit in &units {
if unit == BACKSLASH {
backslashes += 1;
} else {
if unit == QUOTE {
line.extend(core::iter::repeat_n(BACKSLASH, backslashes + 1));
}
backslashes = 0;
}
line.push(unit);
}
if quote {
line.extend(core::iter::repeat_n(BACKSLASH, backslashes));
line.push(QUOTE);
}
Ok(())
}
fn command_line(command: &Command<'_>) -> Result<Vec<u16>> {
let mut line = Vec::new();
if let Some(raw) = command.raw_command_line {
push_wide(&mut line, raw)?;
} else {
let arg0 = command.arg0.unwrap_or(command.program);
if arg0.contains(&b'"') {
return Err(ErrorKind::InvalidInput.into());
}
reserve(&mut line, 1)?;
line.push(QUOTE);
push_wide(&mut line, arg0)?;
reserve(&mut line, 1)?;
line.push(QUOTE);
for arg in command.args.iter() {
reserve(&mut line, 1)?;
line.push(b' ' as u16);
push_argument(&mut line, arg)?;
}
}
reserve(&mut line, 1)?;
line.push(0);
Ok(line)
}
fn variable_name(var: &[u16]) -> &[u16] {
let end = var
.iter()
.skip(1)
.position(|&unit| unit == b'=' as u16)
.map_or(var.len(), |at| at + 1);
&var[..end]
}
fn compare_names(a: &[u16], b: &[u16]) -> core::cmp::Ordering {
const CSTR_LESS_THAN: i32 = 1;
const CSTR_GREATER_THAN: i32 = 3;
let len = |units: &[u16]| units.len().min(i32::MAX as usize) as i32;
match unsafe { CompareStringOrdinal(a.as_ptr(), len(a), b.as_ptr(), len(b), 1) } {
CSTR_LESS_THAN => core::cmp::Ordering::Less,
CSTR_GREATER_THAN => core::cmp::Ordering::Greater,
_ => core::cmp::Ordering::Equal,
}
}
fn environment_block(command: &Command<'_>) -> Result<Option<Vec<u16>>> {
let Some(vars) = command.env else {
return Ok(None);
};
let mut units = Vec::new();
let mut ranges = Vec::new();
for var in vars.iter() {
let start = units.len();
push_wide(&mut units, var)?;
reserve(&mut ranges, 1)?;
ranges.push(start..units.len());
}
ranges.sort_by(|a, b| {
compare_names(
variable_name(&units[a.clone()]),
variable_name(&units[b.clone()]),
)
});
let mut block = Vec::new();
reserve(&mut block, units.len() + ranges.len() + 2)?;
for range in ranges {
block.extend_from_slice(&units[range]);
block.push(0);
}
if block.is_empty() {
block.push(0);
}
block.push(0);
Ok(Some(block))
}
fn inheritable(handle: BorrowedHandle<'_>) -> Result<OwnedHandle> {
let mut new = ptr::null_mut();
cvt(unsafe {
let process = GetCurrentProcess();
DuplicateHandle(
process,
handle.as_raw(),
process,
&raw mut new,
0,
1,
DUPLICATE_SAME_ACCESS,
)
})?;
Ok(unsafe { OwnedHandle::from_raw(new) })
}
fn null_device() -> Result<OwnedHandle> {
let name: [u16; 4] = [b'N' as u16, b'U' as u16, b'L' as u16, 0];
let security = SecurityAttributes {
len: size_of::<SecurityAttributes>() as u32,
descriptor: ptr::null_mut(),
inherit: 1,
};
let handle = unsafe {
CreateFileW(
name.as_ptr(),
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ_WRITE,
(&raw const security).cast(),
OPEN_EXISTING,
0,
ptr::null_mut(),
)
};
if handle as isize == -1 {
return Err(last_error());
}
Ok(unsafe { OwnedHandle::from_raw(handle) })
}
fn standard_handle(index: usize, stdio: &Stdio<'_>) -> Result<Option<OwnedHandle>> {
match stdio {
Stdio::Null => null_device().map(Some),
Stdio::Handle(handle) => inheritable(*handle).map(Some),
Stdio::Inherit => {
let own = match index {
0 => crate::sys::io::stdin(),
1 => crate::sys::io::stdout(),
_ => crate::sys::io::stderr(),
};
match own.map(inheritable) {
None => Ok(None),
Some(Ok(handle)) => Ok(Some(handle)),
Some(Err(error)) if error.raw_os_error() == ERROR_INVALID_HANDLE => Ok(None),
Some(Err(error)) => Err(error),
}
}
}
}
struct AttributeList(Vec<usize>);
impl AttributeList {
fn as_ptr(&mut self) -> *mut c_void {
self.0.as_mut_ptr().cast()
}
}
impl Drop for AttributeList {
fn drop(&mut self) {
unsafe { DeleteProcThreadAttributeList(self.as_ptr()) };
}
}
fn handle_list(handles: &[*mut c_void]) -> Result<AttributeList> {
let mut size = 0;
unsafe { InitializeProcThreadAttributeList(ptr::null_mut(), 1, 0, &raw mut size) };
let mut buffer = Vec::new();
let words = size.div_ceil(size_of::<usize>()).max(1);
reserve(&mut buffer, words)?;
buffer.resize(words, 0usize);
cvt(unsafe {
InitializeProcThreadAttributeList(buffer.as_mut_ptr().cast(), 1, 0, &raw mut size)
})?;
let mut list = AttributeList(buffer);
cvt(unsafe {
UpdateProcThreadAttribute(
list.as_ptr(),
0,
PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
handles.as_ptr().cast(),
size_of_val(handles),
ptr::null_mut(),
ptr::null(),
)
})?;
Ok(list)
}
#[derive(Debug)]
pub(crate) struct Child {
process: OwnedHandle,
pid: u32,
}
fn has_batch_extension(name: &[u16]) -> bool {
let mut name = name;
while let [rest @ .., last] = name
&& *last < 0x80
&& b". \\/".contains(&(*last as u8))
{
name = rest;
}
let Some(extension) = name.last_chunk::<4>() else {
return false;
};
let lower = extension.map(|unit| match u8::try_from(unit) {
Ok(byte) => byte.to_ascii_lowercase(),
Err(_) => 0,
});
&lower == b".bat" || &lower == b".cmd"
}
fn is_batch_file(program: &[u16]) -> Result<bool> {
let name = &program[..program.len() - 1];
if has_batch_extension(name) {
return Ok(true);
}
let verbatim = [b'\\' as u16, b'\\' as u16, b'?' as u16, b'\\' as u16];
if name.starts_with(&verbatim) {
return Ok(false);
}
let mut full = Vec::new();
let mut size = name.len() + 64;
loop {
reserve(&mut full, size)?;
full.resize(size, 0u16);
let len = unsafe {
GetFullPathNameW(
program.as_ptr(),
full.len() as u32,
full.as_mut_ptr(),
ptr::null_mut(),
)
} as usize;
if len == 0 {
return Ok(false);
}
if len < full.len() {
return Ok(has_batch_extension(&full[..len]));
}
size = len + 1;
}
}
pub(crate) fn spawn(command: &Command<'_>) -> Result<Child> {
let application = wide_string(command.program)?;
if command.raw_command_line.is_none() && is_batch_file(&application)? {
return Err(ErrorKind::InvalidInput.into());
}
let mut line = command_line(command)?;
let environment = environment_block(command)?;
let directory = command.current_dir.map(wide_string).transpose()?;
let standard = [
standard_handle(0, &command.stdio[0])?,
standard_handle(1, &command.stdio[1])?,
standard_handle(2, &command.stdio[2])?,
];
let raw = |index: usize| {
standard[index]
.as_ref()
.map_or(ptr::null_mut(), OwnedHandle::as_raw)
};
let mut handles = [ptr::null_mut(); 3];
let mut count = 0;
for handle in standard.iter().flatten() {
handles[count] = handle.as_raw();
count += 1;
}
let mut list = if count > 0 {
Some(handle_list(&handles[..count])?)
} else {
None
};
let (size, extended) = match list {
Some(_) => (size_of::<StartupInfoEx>(), EXTENDED_STARTUPINFO_PRESENT),
None => (size_of::<StartupInfoEx>() - size_of::<*mut c_void>(), 0),
};
let startup = StartupInfoEx {
cb: size as u32,
reserved: ptr::null_mut(),
desktop: ptr::null_mut(),
title: ptr::null_mut(),
x: 0,
y: 0,
x_size: 0,
y_size: 0,
x_count_chars: 0,
y_count_chars: 0,
fill_attribute: 0,
flags: STARTF_USESTDHANDLES,
show_window: 0,
reserved2_len: 0,
reserved2: ptr::null_mut(),
stdin: raw(0),
stdout: raw(1),
stderr: raw(2),
attribute_list: list.as_mut().map_or(ptr::null_mut(), AttributeList::as_ptr),
};
let mut group = if command.new_process_group {
CREATE_NEW_PROCESS_GROUP
} else {
0
};
if command.new_console {
group |= CREATE_NEW_CONSOLE;
}
let mut info = ProcessInformation {
process: ptr::null_mut(),
thread: ptr::null_mut(),
process_id: 0,
thread_id: 0,
};
cvt(unsafe {
CreateProcessW(
application.as_ptr(),
line.as_mut_ptr(),
ptr::null(),
ptr::null(),
(count > 0) as i32,
CREATE_UNICODE_ENVIRONMENT | extended | group,
environment
.as_ref()
.map_or(ptr::null(), |block| block.as_ptr().cast()),
directory.as_ref().map_or(ptr::null(), |dir| dir.as_ptr()),
&raw const startup,
&raw mut info,
)
})?;
let process = unsafe {
drop(OwnedHandle::from_raw(info.thread));
OwnedHandle::from_raw(info.process)
};
Ok(Child {
process,
pid: info.process_id,
})
}
impl Child {
pub(crate) fn id(&self) -> u32 {
self.pid
}
pub(crate) fn handle(&self) -> BorrowedHandle<'_> {
self.process.as_handle()
}
pub(crate) fn wait(
&self,
block: bool,
) -> Result<Option<(ExitStatus, Option<ResourceUsage>)>> {
let timeout = if block { INFINITE } else { 0 };
match unsafe { WaitForSingleObject(self.process.as_raw(), timeout) } {
WAIT_OBJECT_0 => {}
WAIT_TIMEOUT => return Ok(None),
_ => return Err(last_error()),
}
let mut code = 0;
cvt(unsafe { GetExitCodeProcess(self.process.as_raw(), &raw mut code) })?;
let usage = usage_of(self.process.as_raw()).ok();
Ok(Some((ExitStatus::exited(code as i32), usage)))
}
pub(crate) fn kill(&self) -> Result<()> {
let result = cvt(unsafe { TerminateProcess(self.process.as_raw(), 1) });
if result.is_err() && matches!(self.wait(false), Ok(Some(_))) {
return Ok(());
}
result
}
}
}