#![allow(unsafe_code)]
mod environment;
mod wait;
pub use environment::Environment;
use environment::wide_without_nul;
use std::{
ffi::OsStr,
future::poll_fn,
io,
mem::{size_of, size_of_val},
os::windows::{
io::{AsHandle, AsRawHandle, BorrowedHandle, FromRawHandle, OwnedHandle, RawHandle},
process::ExitStatusExt,
},
path::{Path, PathBuf},
process::ExitStatus,
ptr::{null, null_mut},
task::Poll,
};
use wait::ProcessWait;
use windows_sys::Win32::{
Foundation::{
DuplicateHandle, DUPLICATE_SAME_ACCESS, ERROR_ACCESS_DENIED, GENERIC_READ,
INVALID_HANDLE_VALUE, WAIT_OBJECT_0, WAIT_TIMEOUT,
},
Security::SECURITY_ATTRIBUTES,
Storage::FileSystem::{CreateFileW, FILE_SHARE_READ, FILE_SHARE_WRITE, OPEN_EXISTING},
System::{
Pipes::CreatePipe,
Threading::{
CreateProcessW, DeleteProcThreadAttributeList, GetCurrentProcess, GetExitCodeProcess,
InitializeProcThreadAttributeList, ResumeThread, TerminateProcess,
UpdateProcThreadAttribute, WaitForSingleObject, CREATE_NO_WINDOW, CREATE_SUSPENDED,
CREATE_UNICODE_ENVIRONMENT, EXTENDED_STARTUPINFO_PRESENT, PROCESS_INFORMATION,
PROC_THREAD_ATTRIBUTE_HANDLE_LIST, STARTF_USESTDHANDLES, STARTUPINFOEXW,
},
},
};
#[derive(Debug)]
pub struct Child {
wait: Option<ProcessWait>,
process: OwnedHandle,
primary_thread: Option<OwnedHandle>,
pid: u32,
exit: Option<ExitStatus>,
kill_on_drop: bool,
stdout: Option<OwnedHandle>,
stderr: Option<OwnedHandle>,
}
impl Child {
pub fn id(&self) -> Option<u32> {
self.exit.is_none().then_some(self.pid)
}
pub fn process_handle(&self) -> Option<BorrowedHandle<'_>> {
self.id().map(|_| self.process.as_handle())
}
pub fn take_stdout(&mut self) -> Option<OwnedHandle> {
self.stdout.take()
}
pub fn take_stderr(&mut self) -> Option<OwnedHandle> {
self.stderr.take()
}
pub fn resume(&mut self) -> io::Result<()> {
let thread = self
.primary_thread
.as_ref()
.ok_or_else(|| io::Error::other("child already resumed"))?;
if unsafe { ResumeThread(thread.as_raw_handle()) } == u32::MAX {
return Err(io::Error::last_os_error());
}
self.primary_thread = None;
Ok(())
}
pub fn disarm_kill_on_drop(&mut self) {
assert!(
self.primary_thread.is_none(),
"cannot disarm a suspended child"
);
self.kill_on_drop = false;
}
pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
if self.exit.is_some() {
return Ok(self.exit);
}
let handle = self.process.as_raw_handle();
match unsafe { WaitForSingleObject(handle, 0) } {
WAIT_OBJECT_0 => {
let mut code = 0;
if unsafe { GetExitCodeProcess(handle, &mut code) } == 0 {
return Err(io::Error::last_os_error());
}
self.wait = None;
self.exit = Some(ExitStatus::from_raw(code));
Ok(self.exit)
}
WAIT_TIMEOUT => Ok(None),
_ => Err(io::Error::last_os_error()),
}
}
pub async fn wait(&mut self) -> io::Result<ExitStatus> {
poll_fn(|cx| {
if let Some(status) = self.try_wait()? {
return Poll::Ready(Ok(status));
}
let registration = match &self.wait {
Some(wait) => wait,
None => self
.wait
.insert(ProcessWait::new(self.process.as_raw_handle())?),
};
match registration.poll(cx) {
Poll::Pending => Poll::Pending,
Poll::Ready(()) => Poll::Ready(
self.try_wait()?
.ok_or_else(|| io::Error::other("process wait callback fired before exit")),
),
}
})
.await
}
pub fn start_kill(&mut self) -> io::Result<()> {
if self.exit.is_some() {
return Ok(());
}
if unsafe { TerminateProcess(self.process.as_raw_handle(), 1) } != 0 {
return Ok(());
}
let error = io::Error::last_os_error();
if error.raw_os_error() == Some(ERROR_ACCESS_DENIED as i32) && self.try_wait()?.is_some() {
return Ok(());
}
Err(error)
}
}
impl Drop for Child {
fn drop(&mut self) {
if self.kill_on_drop {
let _ = self.start_kill();
}
}
}
#[cfg(feature = "test-support")]
pub fn current_thread_id_for_test() -> u32 {
unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() }
}
pub fn spawn<'a>(
program: &Path,
args: impl IntoIterator<Item = &'a OsStr>,
environment: &Environment,
current_dir: &Path,
) -> io::Result<Child> {
let program = std::path::absolute(resolve_program(program)?)?;
let mut command_line = command_line(program.as_os_str(), args)?;
let mut application = wide_without_nul(program.as_os_str())?;
application.push(0);
let mut directory = wide_without_nul(std::path::absolute(current_dir)?.as_os_str())?;
directory.push(0);
let _inheritance = crate::child_spawn::windows_inheritance_lock();
let (stdout, out_write) = output_pipe()?;
let (stderr, err_write) = output_pipe()?;
let stdin = null_input()?;
let handles = [
stdin.as_raw_handle(),
out_write.as_raw_handle(),
err_write.as_raw_handle(),
];
let mut attributes = Attributes::new(&handles)?;
let mut startup = STARTUPINFOEXW::default();
startup.StartupInfo.cb = size_of::<STARTUPINFOEXW>() as u32;
startup.StartupInfo.dwFlags = STARTF_USESTDHANDLES;
[
startup.StartupInfo.hStdInput,
startup.StartupInfo.hStdOutput,
startup.StartupInfo.hStdError,
] = handles;
startup.lpAttributeList = attributes.as_mut_ptr();
let mut info = PROCESS_INFORMATION::default();
crate::windows_acl::with_child_security(|process, thread| {
if unsafe {
CreateProcessW(
application.as_ptr(),
command_line.as_mut_ptr(),
process,
thread,
1,
CREATE_SUSPENDED
| CREATE_NO_WINDOW
| CREATE_UNICODE_ENVIRONMENT
| EXTENDED_STARTUPINFO_PRESENT,
environment.0.as_ptr().cast(),
directory.as_ptr(),
&startup.StartupInfo,
&mut info,
)
} == 0
{
return Err(io::Error::last_os_error());
}
Ok(())
})?;
let (process, primary_thread) = unsafe {
(
OwnedHandle::from_raw_handle(info.hProcess),
OwnedHandle::from_raw_handle(info.hThread),
)
};
Ok(Child {
wait: None,
process,
primary_thread: Some(primary_thread),
pid: info.dwProcessId,
exit: None,
kill_on_drop: true,
stdout: Some(stdout),
stderr: Some(stderr),
})
}
fn resolve_program(program: &Path) -> io::Result<PathBuf> {
match program.extension() {
Some(ext) if ext.eq_ignore_ascii_case("exe") => Ok(program.to_path_buf()),
None => {
let mut exe = program.as_os_str().to_owned();
exe.push(".exe");
let exe = PathBuf::from(exe);
Ok(if exe.is_file() {
exe
} else {
program.to_path_buf()
})
}
Some(_) => Err(io::Error::new(
io::ErrorKind::InvalidInput,
"Windows module program must be an .exe or have no extension",
)),
}
}
fn command_line<'a>(
program: &OsStr,
args: impl IntoIterator<Item = &'a OsStr>,
) -> io::Result<Vec<u16>> {
const QUOTE: u16 = b'"' as u16;
const SPACE: u16 = b' ' as u16;
const TAB: u16 = b'\t' as u16;
const SLASH: u16 = b'\\' as u16;
let program = wide_without_nul(program)?;
if program.contains("E) {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"executable path contains a quote",
));
}
let mut line = Vec::from([QUOTE]);
line.extend(program);
line.push(QUOTE);
for arg in args {
let arg = wide_without_nul(arg)?;
line.push(SPACE);
let quoted = arg.is_empty() || arg.contains(&SPACE) || arg.contains(&TAB);
if quoted {
line.push(QUOTE);
}
let mut slashes = 0;
for ch in arg {
match ch {
SLASH => slashes += 1,
_ => {
let escapes = if ch == QUOTE {
2 * slashes + 1
} else {
slashes
};
line.extend(std::iter::repeat_n(SLASH, escapes));
line.push(ch);
slashes = 0;
}
}
}
line.extend(std::iter::repeat_n(
SLASH,
if quoted { 2 * slashes } else { slashes },
));
if quoted {
line.push(QUOTE);
}
}
line.push(0);
Ok(line)
}
fn null_input() -> io::Result<OwnedHandle> {
let nul = [b'N' as u16, b'U' as u16, b'L' as u16, 0];
let attributes = SECURITY_ATTRIBUTES {
nLength: size_of::<SECURITY_ATTRIBUTES>() as u32,
lpSecurityDescriptor: null_mut(),
bInheritHandle: 1,
};
let handle = unsafe {
CreateFileW(
nul.as_ptr(),
GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE,
&attributes,
OPEN_EXISTING,
0,
null_mut(),
)
};
if handle == INVALID_HANDLE_VALUE {
return Err(io::Error::last_os_error());
}
Ok(unsafe { OwnedHandle::from_raw_handle(handle) })
}
fn output_pipe() -> io::Result<(OwnedHandle, OwnedHandle)> {
let (mut reader, mut writer) = (null_mut(), null_mut());
if unsafe { CreatePipe(&mut reader, &mut writer, null(), 0) } == 0 {
return Err(io::Error::last_os_error());
}
let (reader, writer) = unsafe {
(
OwnedHandle::from_raw_handle(reader),
OwnedHandle::from_raw_handle(writer),
)
};
let mut child_writer = null_mut();
if unsafe {
let process = GetCurrentProcess();
DuplicateHandle(
process,
writer.as_raw_handle(),
process,
&mut child_writer,
0,
1,
DUPLICATE_SAME_ACCESS,
)
} == 0
{
return Err(io::Error::last_os_error());
}
Ok((reader, unsafe {
OwnedHandle::from_raw_handle(child_writer)
}))
}
struct Attributes<'a> {
storage: Vec<usize>,
_handles: &'a [RawHandle; 3],
}
impl<'a> Attributes<'a> {
fn new(handles: &'a [RawHandle; 3]) -> io::Result<Self> {
let mut bytes = 0;
unsafe { InitializeProcThreadAttributeList(null_mut(), 1, 0, &mut bytes) };
if bytes == 0 {
return Err(io::Error::last_os_error());
}
let mut storage = vec![0usize; bytes.div_ceil(size_of::<usize>())];
if unsafe {
InitializeProcThreadAttributeList(storage.as_mut_ptr().cast(), 1, 0, &mut bytes)
} == 0
{
return Err(io::Error::last_os_error());
}
let mut list = Self {
storage,
_handles: handles,
};
if unsafe {
UpdateProcThreadAttribute(
list.as_mut_ptr(),
0,
PROC_THREAD_ATTRIBUTE_HANDLE_LIST as usize,
handles.as_ptr().cast(),
size_of_val(handles),
null_mut(),
null(),
)
} == 0
{
return Err(io::Error::last_os_error());
}
Ok(list)
}
fn as_mut_ptr(&mut self) -> *mut std::ffi::c_void {
self.storage.as_mut_ptr().cast()
}
}
impl Drop for Attributes<'_> {
fn drop(&mut self) {
unsafe { DeleteProcThreadAttributeList(self.as_mut_ptr()) };
}
}
#[cfg(test)]
#[path = "windows_spawn_tests.rs"]
mod tests;