]> git.proxmox.com Git - rustc.git/blob - library/std/src/sys/windows/process.rs
New upstream version 1.74.1+dfsg1
[rustc.git] / library / std / src / sys / windows / process.rs
1 #![unstable(feature = "process_internals", issue = "none")]
2
3 #[cfg(test)]
4 mod tests;
5
6 use crate::cmp;
7 use crate::collections::BTreeMap;
8 use crate::env;
9 use crate::env::consts::{EXE_EXTENSION, EXE_SUFFIX};
10 use crate::ffi::{OsStr, OsString};
11 use crate::fmt;
12 use crate::io::{self, Error, ErrorKind};
13 use crate::mem;
14 use crate::mem::MaybeUninit;
15 use crate::num::NonZeroI32;
16 use crate::os::windows::ffi::{OsStrExt, OsStringExt};
17 use crate::os::windows::io::{AsHandle, AsRawHandle, BorrowedHandle, FromRawHandle, IntoRawHandle};
18 use crate::path::{Path, PathBuf};
19 use crate::ptr;
20 use crate::sync::Mutex;
21 use crate::sys::args::{self, Arg};
22 use crate::sys::c;
23 use crate::sys::c::NonZeroDWORD;
24 use crate::sys::cvt;
25 use crate::sys::fs::{File, OpenOptions};
26 use crate::sys::handle::Handle;
27 use crate::sys::path;
28 use crate::sys::pipe::{self, AnonPipe};
29 use crate::sys::stdio;
30 use crate::sys_common::process::{CommandEnv, CommandEnvs};
31 use crate::sys_common::IntoInner;
32
33 use libc::{c_void, EXIT_FAILURE, EXIT_SUCCESS};
34
35 ////////////////////////////////////////////////////////////////////////////////
36 // Command
37 ////////////////////////////////////////////////////////////////////////////////
38
39 #[derive(Clone, Debug, Eq)]
40 #[doc(hidden)]
41 pub struct EnvKey {
42 os_string: OsString,
43 // This stores a UTF-16 encoded string to workaround the mismatch between
44 // Rust's OsString (WTF-8) and the Windows API string type (UTF-16).
45 // Normally converting on every API call is acceptable but here
46 // `c::CompareStringOrdinal` will be called for every use of `==`.
47 utf16: Vec<u16>,
48 }
49
50 impl EnvKey {
51 fn new<T: Into<OsString>>(key: T) -> Self {
52 EnvKey::from(key.into())
53 }
54 }
55
56 // Comparing Windows environment variable keys[1] are behaviourally the
57 // composition of two operations[2]:
58 //
59 // 1. Case-fold both strings. This is done using a language-independent
60 // uppercase mapping that's unique to Windows (albeit based on data from an
61 // older Unicode spec). It only operates on individual UTF-16 code units so
62 // surrogates are left unchanged. This uppercase mapping can potentially change
63 // between Windows versions.
64 //
65 // 2. Perform an ordinal comparison of the strings. A comparison using ordinal
66 // is just a comparison based on the numerical value of each UTF-16 code unit[3].
67 //
68 // Because the case-folding mapping is unique to Windows and not guaranteed to
69 // be stable, we ask the OS to compare the strings for us. This is done by
70 // calling `CompareStringOrdinal`[4] with `bIgnoreCase` set to `TRUE`.
71 //
72 // [1] https://docs.microsoft.com/en-us/dotnet/standard/base-types/best-practices-strings#choosing-a-stringcomparison-member-for-your-method-call
73 // [2] https://docs.microsoft.com/en-us/dotnet/standard/base-types/best-practices-strings#stringtoupper-and-stringtolower
74 // [3] https://docs.microsoft.com/en-us/dotnet/api/system.stringcomparison?view=net-5.0#System_StringComparison_Ordinal
75 // [4] https://docs.microsoft.com/en-us/windows/win32/api/stringapiset/nf-stringapiset-comparestringordinal
76 impl Ord for EnvKey {
77 fn cmp(&self, other: &Self) -> cmp::Ordering {
78 unsafe {
79 let result = c::CompareStringOrdinal(
80 self.utf16.as_ptr(),
81 self.utf16.len() as _,
82 other.utf16.as_ptr(),
83 other.utf16.len() as _,
84 c::TRUE,
85 );
86 match result {
87 c::CSTR_LESS_THAN => cmp::Ordering::Less,
88 c::CSTR_EQUAL => cmp::Ordering::Equal,
89 c::CSTR_GREATER_THAN => cmp::Ordering::Greater,
90 // `CompareStringOrdinal` should never fail so long as the parameters are correct.
91 _ => panic!("comparing environment keys failed: {}", Error::last_os_error()),
92 }
93 }
94 }
95 }
96 impl PartialOrd for EnvKey {
97 fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
98 Some(self.cmp(other))
99 }
100 }
101 impl PartialEq for EnvKey {
102 fn eq(&self, other: &Self) -> bool {
103 if self.utf16.len() != other.utf16.len() {
104 false
105 } else {
106 self.cmp(other) == cmp::Ordering::Equal
107 }
108 }
109 }
110 impl PartialOrd<str> for EnvKey {
111 fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
112 Some(self.cmp(&EnvKey::new(other)))
113 }
114 }
115 impl PartialEq<str> for EnvKey {
116 fn eq(&self, other: &str) -> bool {
117 if self.os_string.len() != other.len() {
118 false
119 } else {
120 self.cmp(&EnvKey::new(other)) == cmp::Ordering::Equal
121 }
122 }
123 }
124
125 // Environment variable keys should preserve their original case even though
126 // they are compared using a caseless string mapping.
127 impl From<OsString> for EnvKey {
128 fn from(k: OsString) -> Self {
129 EnvKey { utf16: k.encode_wide().collect(), os_string: k }
130 }
131 }
132
133 impl From<EnvKey> for OsString {
134 fn from(k: EnvKey) -> Self {
135 k.os_string
136 }
137 }
138
139 impl From<&OsStr> for EnvKey {
140 fn from(k: &OsStr) -> Self {
141 Self::from(k.to_os_string())
142 }
143 }
144
145 impl AsRef<OsStr> for EnvKey {
146 fn as_ref(&self) -> &OsStr {
147 &self.os_string
148 }
149 }
150
151 pub(crate) fn ensure_no_nuls<T: AsRef<OsStr>>(str: T) -> io::Result<T> {
152 if str.as_ref().encode_wide().any(|b| b == 0) {
153 Err(io::const_io_error!(ErrorKind::InvalidInput, "nul byte found in provided data"))
154 } else {
155 Ok(str)
156 }
157 }
158
159 pub struct Command {
160 program: OsString,
161 args: Vec<Arg>,
162 env: CommandEnv,
163 cwd: Option<OsString>,
164 flags: u32,
165 detach: bool, // not currently exposed in std::process
166 stdin: Option<Stdio>,
167 stdout: Option<Stdio>,
168 stderr: Option<Stdio>,
169 force_quotes_enabled: bool,
170 proc_thread_attributes: BTreeMap<usize, ProcThreadAttributeValue>,
171 }
172
173 pub enum Stdio {
174 Inherit,
175 InheritSpecific { from_stdio_id: c::DWORD },
176 Null,
177 MakePipe,
178 Pipe(AnonPipe),
179 Handle(Handle),
180 }
181
182 pub struct StdioPipes {
183 pub stdin: Option<AnonPipe>,
184 pub stdout: Option<AnonPipe>,
185 pub stderr: Option<AnonPipe>,
186 }
187
188 impl Command {
189 pub fn new(program: &OsStr) -> Command {
190 Command {
191 program: program.to_os_string(),
192 args: Vec::new(),
193 env: Default::default(),
194 cwd: None,
195 flags: 0,
196 detach: false,
197 stdin: None,
198 stdout: None,
199 stderr: None,
200 force_quotes_enabled: false,
201 proc_thread_attributes: Default::default(),
202 }
203 }
204
205 pub fn arg(&mut self, arg: &OsStr) {
206 self.args.push(Arg::Regular(arg.to_os_string()))
207 }
208 pub fn env_mut(&mut self) -> &mut CommandEnv {
209 &mut self.env
210 }
211 pub fn cwd(&mut self, dir: &OsStr) {
212 self.cwd = Some(dir.to_os_string())
213 }
214 pub fn stdin(&mut self, stdin: Stdio) {
215 self.stdin = Some(stdin);
216 }
217 pub fn stdout(&mut self, stdout: Stdio) {
218 self.stdout = Some(stdout);
219 }
220 pub fn stderr(&mut self, stderr: Stdio) {
221 self.stderr = Some(stderr);
222 }
223 pub fn creation_flags(&mut self, flags: u32) {
224 self.flags = flags;
225 }
226
227 pub fn force_quotes(&mut self, enabled: bool) {
228 self.force_quotes_enabled = enabled;
229 }
230
231 pub fn raw_arg(&mut self, command_str_to_append: &OsStr) {
232 self.args.push(Arg::Raw(command_str_to_append.to_os_string()))
233 }
234
235 pub fn get_program(&self) -> &OsStr {
236 &self.program
237 }
238
239 pub fn get_args(&self) -> CommandArgs<'_> {
240 let iter = self.args.iter();
241 CommandArgs { iter }
242 }
243
244 pub fn get_envs(&self) -> CommandEnvs<'_> {
245 self.env.iter()
246 }
247
248 pub fn get_current_dir(&self) -> Option<&Path> {
249 self.cwd.as_ref().map(|cwd| Path::new(cwd))
250 }
251
252 pub unsafe fn raw_attribute<T: Copy + Send + Sync + 'static>(
253 &mut self,
254 attribute: usize,
255 value: T,
256 ) {
257 self.proc_thread_attributes.insert(
258 attribute,
259 ProcThreadAttributeValue { size: mem::size_of::<T>(), data: Box::new(value) },
260 );
261 }
262
263 pub fn spawn(
264 &mut self,
265 default: Stdio,
266 needs_stdin: bool,
267 ) -> io::Result<(Process, StdioPipes)> {
268 let maybe_env = self.env.capture_if_changed();
269
270 let child_paths = if let Some(env) = maybe_env.as_ref() {
271 env.get(&EnvKey::new("PATH")).map(|s| s.as_os_str())
272 } else {
273 None
274 };
275 let program = resolve_exe(&self.program, || env::var_os("PATH"), child_paths)?;
276 // Case insensitive "ends_with" of UTF-16 encoded ".bat" or ".cmd"
277 let is_batch_file = matches!(
278 program.len().checked_sub(5).and_then(|i| program.get(i..)),
279 Some([46, 98 | 66, 97 | 65, 116 | 84, 0] | [46, 99 | 67, 109 | 77, 100 | 68, 0])
280 );
281 let (program, mut cmd_str) = if is_batch_file {
282 (
283 command_prompt()?,
284 args::make_bat_command_line(&program, &self.args, self.force_quotes_enabled)?,
285 )
286 } else {
287 let cmd_str = make_command_line(&self.program, &self.args, self.force_quotes_enabled)?;
288 (program, cmd_str)
289 };
290 cmd_str.push(0); // add null terminator
291
292 // stolen from the libuv code.
293 let mut flags = self.flags | c::CREATE_UNICODE_ENVIRONMENT;
294 if self.detach {
295 flags |= c::DETACHED_PROCESS | c::CREATE_NEW_PROCESS_GROUP;
296 }
297
298 let (envp, _data) = make_envp(maybe_env)?;
299 let (dirp, _data) = make_dirp(self.cwd.as_ref())?;
300 let mut pi = zeroed_process_information();
301
302 // Prepare all stdio handles to be inherited by the child. This
303 // currently involves duplicating any existing ones with the ability to
304 // be inherited by child processes. Note, however, that once an
305 // inheritable handle is created, *any* spawned child will inherit that
306 // handle. We only want our own child to inherit this handle, so we wrap
307 // the remaining portion of this spawn in a mutex.
308 //
309 // For more information, msdn also has an article about this race:
310 // https://support.microsoft.com/kb/315939
311 static CREATE_PROCESS_LOCK: Mutex<()> = Mutex::new(());
312
313 let _guard = CREATE_PROCESS_LOCK.lock();
314
315 let mut pipes = StdioPipes { stdin: None, stdout: None, stderr: None };
316 let null = Stdio::Null;
317 let default_stdin = if needs_stdin { &default } else { &null };
318 let stdin = self.stdin.as_ref().unwrap_or(default_stdin);
319 let stdout = self.stdout.as_ref().unwrap_or(&default);
320 let stderr = self.stderr.as_ref().unwrap_or(&default);
321 let stdin = stdin.to_handle(c::STD_INPUT_HANDLE, &mut pipes.stdin)?;
322 let stdout = stdout.to_handle(c::STD_OUTPUT_HANDLE, &mut pipes.stdout)?;
323 let stderr = stderr.to_handle(c::STD_ERROR_HANDLE, &mut pipes.stderr)?;
324
325 let mut si = zeroed_startupinfo();
326
327 // If at least one of stdin, stdout or stderr are set (i.e. are non null)
328 // then set the `hStd` fields in `STARTUPINFO`.
329 // Otherwise skip this and allow the OS to apply its default behaviour.
330 // This provides more consistent behaviour between Win7 and Win8+.
331 let is_set = |stdio: &Handle| !stdio.as_raw_handle().is_null();
332 if is_set(&stderr) || is_set(&stdout) || is_set(&stdin) {
333 si.dwFlags |= c::STARTF_USESTDHANDLES;
334 si.hStdInput = stdin.as_raw_handle();
335 si.hStdOutput = stdout.as_raw_handle();
336 si.hStdError = stderr.as_raw_handle();
337 }
338
339 let si_ptr: *mut c::STARTUPINFOW;
340
341 let mut proc_thread_attribute_list;
342 let mut si_ex;
343
344 if !self.proc_thread_attributes.is_empty() {
345 si.cb = mem::size_of::<c::STARTUPINFOEXW>() as u32;
346 flags |= c::EXTENDED_STARTUPINFO_PRESENT;
347
348 proc_thread_attribute_list =
349 make_proc_thread_attribute_list(&self.proc_thread_attributes)?;
350 si_ex = c::STARTUPINFOEXW {
351 StartupInfo: si,
352 lpAttributeList: proc_thread_attribute_list.0.as_mut_ptr() as _,
353 };
354 si_ptr = &mut si_ex as *mut _ as _;
355 } else {
356 si.cb = mem::size_of::<c::STARTUPINFOW>() as c::DWORD;
357 si_ptr = &mut si as *mut _ as _;
358 }
359
360 unsafe {
361 cvt(c::CreateProcessW(
362 program.as_ptr(),
363 cmd_str.as_mut_ptr(),
364 ptr::null_mut(),
365 ptr::null_mut(),
366 c::TRUE,
367 flags,
368 envp,
369 dirp,
370 si_ptr,
371 &mut pi,
372 ))
373 }?;
374
375 unsafe {
376 Ok((
377 Process {
378 handle: Handle::from_raw_handle(pi.hProcess),
379 main_thread_handle: Handle::from_raw_handle(pi.hThread),
380 },
381 pipes,
382 ))
383 }
384 }
385
386 pub fn output(&mut self) -> io::Result<(ExitStatus, Vec<u8>, Vec<u8>)> {
387 let (proc, pipes) = self.spawn(Stdio::MakePipe, false)?;
388 crate::sys_common::process::wait_with_output(proc, pipes)
389 }
390 }
391
392 impl fmt::Debug for Command {
393 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
394 self.program.fmt(f)?;
395 for arg in &self.args {
396 f.write_str(" ")?;
397 match arg {
398 Arg::Regular(s) => s.fmt(f),
399 Arg::Raw(s) => f.write_str(&s.to_string_lossy()),
400 }?;
401 }
402 Ok(())
403 }
404 }
405
406 // Resolve `exe_path` to the executable name.
407 //
408 // * If the path is simply a file name then use the paths given by `search_paths` to find the executable.
409 // * Otherwise use the `exe_path` as given.
410 //
411 // This function may also append `.exe` to the name. The rationale for doing so is as follows:
412 //
413 // It is a very strong convention that Windows executables have the `exe` extension.
414 // In Rust, it is common to omit this extension.
415 // Therefore this functions first assumes `.exe` was intended.
416 // It falls back to the plain file name if a full path is given and the extension is omitted
417 // or if only a file name is given and it already contains an extension.
418 fn resolve_exe<'a>(
419 exe_path: &'a OsStr,
420 parent_paths: impl FnOnce() -> Option<OsString>,
421 child_paths: Option<&OsStr>,
422 ) -> io::Result<Vec<u16>> {
423 // Early return if there is no filename.
424 if exe_path.is_empty() || path::has_trailing_slash(exe_path) {
425 return Err(io::const_io_error!(
426 io::ErrorKind::InvalidInput,
427 "program path has no file name",
428 ));
429 }
430 // Test if the file name has the `exe` extension.
431 // This does a case-insensitive `ends_with`.
432 let has_exe_suffix = if exe_path.len() >= EXE_SUFFIX.len() {
433 exe_path.as_encoded_bytes()[exe_path.len() - EXE_SUFFIX.len()..]
434 .eq_ignore_ascii_case(EXE_SUFFIX.as_bytes())
435 } else {
436 false
437 };
438
439 // If `exe_path` is an absolute path or a sub-path then don't search `PATH` for it.
440 if !path::is_file_name(exe_path) {
441 if has_exe_suffix {
442 // The application name is a path to a `.exe` file.
443 // Let `CreateProcessW` figure out if it exists or not.
444 return args::to_user_path(Path::new(exe_path));
445 }
446 let mut path = PathBuf::from(exe_path);
447
448 // Append `.exe` if not already there.
449 path = path::append_suffix(path, EXE_SUFFIX.as_ref());
450 if let Some(path) = program_exists(&path) {
451 return Ok(path);
452 } else {
453 // It's ok to use `set_extension` here because the intent is to
454 // remove the extension that was just added.
455 path.set_extension("");
456 return args::to_user_path(&path);
457 }
458 } else {
459 ensure_no_nuls(exe_path)?;
460 // From the `CreateProcessW` docs:
461 // > If the file name does not contain an extension, .exe is appended.
462 // Note that this rule only applies when searching paths.
463 let has_extension = exe_path.as_encoded_bytes().contains(&b'.');
464
465 // Search the directories given by `search_paths`.
466 let result = search_paths(parent_paths, child_paths, |mut path| {
467 path.push(&exe_path);
468 if !has_extension {
469 path.set_extension(EXE_EXTENSION);
470 }
471 program_exists(&path)
472 });
473 if let Some(path) = result {
474 return Ok(path);
475 }
476 }
477 // If we get here then the executable cannot be found.
478 Err(io::const_io_error!(io::ErrorKind::NotFound, "program not found"))
479 }
480
481 // Calls `f` for every path that should be used to find an executable.
482 // Returns once `f` returns the path to an executable or all paths have been searched.
483 fn search_paths<Paths, Exists>(
484 parent_paths: Paths,
485 child_paths: Option<&OsStr>,
486 mut exists: Exists,
487 ) -> Option<Vec<u16>>
488 where
489 Paths: FnOnce() -> Option<OsString>,
490 Exists: FnMut(PathBuf) -> Option<Vec<u16>>,
491 {
492 // 1. Child paths
493 // This is for consistency with Rust's historic behaviour.
494 if let Some(paths) = child_paths {
495 for path in env::split_paths(paths).filter(|p| !p.as_os_str().is_empty()) {
496 if let Some(path) = exists(path) {
497 return Some(path);
498 }
499 }
500 }
501
502 // 2. Application path
503 if let Ok(mut app_path) = env::current_exe() {
504 app_path.pop();
505 if let Some(path) = exists(app_path) {
506 return Some(path);
507 }
508 }
509
510 // 3 & 4. System paths
511 // SAFETY: This uses `fill_utf16_buf` to safely call the OS functions.
512 unsafe {
513 if let Ok(Some(path)) = super::fill_utf16_buf(
514 |buf, size| c::GetSystemDirectoryW(buf, size),
515 |buf| exists(PathBuf::from(OsString::from_wide(buf))),
516 ) {
517 return Some(path);
518 }
519 #[cfg(not(target_vendor = "uwp"))]
520 {
521 if let Ok(Some(path)) = super::fill_utf16_buf(
522 |buf, size| c::GetWindowsDirectoryW(buf, size),
523 |buf| exists(PathBuf::from(OsString::from_wide(buf))),
524 ) {
525 return Some(path);
526 }
527 }
528 }
529
530 // 5. Parent paths
531 if let Some(parent_paths) = parent_paths() {
532 for path in env::split_paths(&parent_paths).filter(|p| !p.as_os_str().is_empty()) {
533 if let Some(path) = exists(path) {
534 return Some(path);
535 }
536 }
537 }
538 None
539 }
540
541 /// Check if a file exists without following symlinks.
542 fn program_exists(path: &Path) -> Option<Vec<u16>> {
543 unsafe {
544 let path = args::to_user_path(path).ok()?;
545 // Getting attributes using `GetFileAttributesW` does not follow symlinks
546 // and it will almost always be successful if the link exists.
547 // There are some exceptions for special system files (e.g. the pagefile)
548 // but these are not executable.
549 if c::GetFileAttributesW(path.as_ptr()) == c::INVALID_FILE_ATTRIBUTES {
550 None
551 } else {
552 Some(path)
553 }
554 }
555 }
556
557 impl Stdio {
558 fn to_handle(&self, stdio_id: c::DWORD, pipe: &mut Option<AnonPipe>) -> io::Result<Handle> {
559 let use_stdio_id = |stdio_id| match stdio::get_handle(stdio_id) {
560 Ok(io) => unsafe {
561 let io = Handle::from_raw_handle(io);
562 let ret = io.duplicate(0, true, c::DUPLICATE_SAME_ACCESS);
563 io.into_raw_handle();
564 ret
565 },
566 // If no stdio handle is available, then propagate the null value.
567 Err(..) => unsafe { Ok(Handle::from_raw_handle(ptr::null_mut())) },
568 };
569 match *self {
570 Stdio::Inherit => use_stdio_id(stdio_id),
571 Stdio::InheritSpecific { from_stdio_id } => use_stdio_id(from_stdio_id),
572
573 Stdio::MakePipe => {
574 let ours_readable = stdio_id != c::STD_INPUT_HANDLE;
575 let pipes = pipe::anon_pipe(ours_readable, true)?;
576 *pipe = Some(pipes.ours);
577 Ok(pipes.theirs.into_handle())
578 }
579
580 Stdio::Pipe(ref source) => {
581 let ours_readable = stdio_id != c::STD_INPUT_HANDLE;
582 pipe::spawn_pipe_relay(source, ours_readable, true).map(AnonPipe::into_handle)
583 }
584
585 Stdio::Handle(ref handle) => handle.duplicate(0, true, c::DUPLICATE_SAME_ACCESS),
586
587 // Open up a reference to NUL with appropriate read/write
588 // permissions as well as the ability to be inherited to child
589 // processes (as this is about to be inherited).
590 Stdio::Null => {
591 let size = mem::size_of::<c::SECURITY_ATTRIBUTES>();
592 let mut sa = c::SECURITY_ATTRIBUTES {
593 nLength: size as c::DWORD,
594 lpSecurityDescriptor: ptr::null_mut(),
595 bInheritHandle: 1,
596 };
597 let mut opts = OpenOptions::new();
598 opts.read(stdio_id == c::STD_INPUT_HANDLE);
599 opts.write(stdio_id != c::STD_INPUT_HANDLE);
600 opts.security_attributes(&mut sa);
601 File::open(Path::new("NUL"), &opts).map(|file| file.into_inner())
602 }
603 }
604 }
605 }
606
607 impl From<AnonPipe> for Stdio {
608 fn from(pipe: AnonPipe) -> Stdio {
609 Stdio::Pipe(pipe)
610 }
611 }
612
613 impl From<File> for Stdio {
614 fn from(file: File) -> Stdio {
615 Stdio::Handle(file.into_inner())
616 }
617 }
618
619 impl From<io::Stdout> for Stdio {
620 fn from(_: io::Stdout) -> Stdio {
621 Stdio::InheritSpecific { from_stdio_id: c::STD_OUTPUT_HANDLE }
622 }
623 }
624
625 impl From<io::Stderr> for Stdio {
626 fn from(_: io::Stderr) -> Stdio {
627 Stdio::InheritSpecific { from_stdio_id: c::STD_ERROR_HANDLE }
628 }
629 }
630
631 ////////////////////////////////////////////////////////////////////////////////
632 // Processes
633 ////////////////////////////////////////////////////////////////////////////////
634
635 /// A value representing a child process.
636 ///
637 /// The lifetime of this value is linked to the lifetime of the actual
638 /// process - the Process destructor calls self.finish() which waits
639 /// for the process to terminate.
640 pub struct Process {
641 handle: Handle,
642 main_thread_handle: Handle,
643 }
644
645 impl Process {
646 pub fn kill(&mut self) -> io::Result<()> {
647 let result = unsafe { c::TerminateProcess(self.handle.as_raw_handle(), 1) };
648 if result == c::FALSE {
649 let error = unsafe { c::GetLastError() };
650 // TerminateProcess returns ERROR_ACCESS_DENIED if the process has already been
651 // terminated (by us, or for any other reason). So check if the process was actually
652 // terminated, and if so, do not return an error.
653 if error != c::ERROR_ACCESS_DENIED || self.try_wait().is_err() {
654 return Err(crate::io::Error::from_raw_os_error(error as i32));
655 }
656 }
657 Ok(())
658 }
659
660 pub fn id(&self) -> u32 {
661 unsafe { c::GetProcessId(self.handle.as_raw_handle()) as u32 }
662 }
663
664 pub fn main_thread_handle(&self) -> BorrowedHandle<'_> {
665 self.main_thread_handle.as_handle()
666 }
667
668 pub fn wait(&mut self) -> io::Result<ExitStatus> {
669 unsafe {
670 let res = c::WaitForSingleObject(self.handle.as_raw_handle(), c::INFINITE);
671 if res != c::WAIT_OBJECT_0 {
672 return Err(Error::last_os_error());
673 }
674 let mut status = 0;
675 cvt(c::GetExitCodeProcess(self.handle.as_raw_handle(), &mut status))?;
676 Ok(ExitStatus(status))
677 }
678 }
679
680 pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
681 unsafe {
682 match c::WaitForSingleObject(self.handle.as_raw_handle(), 0) {
683 c::WAIT_OBJECT_0 => {}
684 c::WAIT_TIMEOUT => {
685 return Ok(None);
686 }
687 _ => return Err(io::Error::last_os_error()),
688 }
689 let mut status = 0;
690 cvt(c::GetExitCodeProcess(self.handle.as_raw_handle(), &mut status))?;
691 Ok(Some(ExitStatus(status)))
692 }
693 }
694
695 pub fn handle(&self) -> &Handle {
696 &self.handle
697 }
698
699 pub fn into_handle(self) -> Handle {
700 self.handle
701 }
702 }
703
704 #[derive(PartialEq, Eq, Clone, Copy, Debug, Default)]
705 pub struct ExitStatus(c::DWORD);
706
707 impl ExitStatus {
708 pub fn exit_ok(&self) -> Result<(), ExitStatusError> {
709 match NonZeroDWORD::try_from(self.0) {
710 /* was nonzero */ Ok(failure) => Err(ExitStatusError(failure)),
711 /* was zero, couldn't convert */ Err(_) => Ok(()),
712 }
713 }
714 pub fn code(&self) -> Option<i32> {
715 Some(self.0 as i32)
716 }
717 }
718
719 /// Converts a raw `c::DWORD` to a type-safe `ExitStatus` by wrapping it without copying.
720 impl From<c::DWORD> for ExitStatus {
721 fn from(u: c::DWORD) -> ExitStatus {
722 ExitStatus(u)
723 }
724 }
725
726 impl fmt::Display for ExitStatus {
727 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
728 // Windows exit codes with the high bit set typically mean some form of
729 // unhandled exception or warning. In this scenario printing the exit
730 // code in decimal doesn't always make sense because it's a very large
731 // and somewhat gibberish number. The hex code is a bit more
732 // recognizable and easier to search for, so print that.
733 if self.0 & 0x80000000 != 0 {
734 write!(f, "exit code: {:#x}", self.0)
735 } else {
736 write!(f, "exit code: {}", self.0)
737 }
738 }
739 }
740
741 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
742 pub struct ExitStatusError(c::NonZeroDWORD);
743
744 impl Into<ExitStatus> for ExitStatusError {
745 fn into(self) -> ExitStatus {
746 ExitStatus(self.0.into())
747 }
748 }
749
750 impl ExitStatusError {
751 pub fn code(self) -> Option<NonZeroI32> {
752 Some((u32::from(self.0) as i32).try_into().unwrap())
753 }
754 }
755
756 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
757 pub struct ExitCode(c::DWORD);
758
759 impl ExitCode {
760 pub const SUCCESS: ExitCode = ExitCode(EXIT_SUCCESS as _);
761 pub const FAILURE: ExitCode = ExitCode(EXIT_FAILURE as _);
762
763 #[inline]
764 pub fn as_i32(&self) -> i32 {
765 self.0 as i32
766 }
767 }
768
769 impl From<u8> for ExitCode {
770 fn from(code: u8) -> Self {
771 ExitCode(c::DWORD::from(code))
772 }
773 }
774
775 impl From<u32> for ExitCode {
776 fn from(code: u32) -> Self {
777 ExitCode(c::DWORD::from(code))
778 }
779 }
780
781 fn zeroed_startupinfo() -> c::STARTUPINFOW {
782 c::STARTUPINFOW {
783 cb: 0,
784 lpReserved: ptr::null_mut(),
785 lpDesktop: ptr::null_mut(),
786 lpTitle: ptr::null_mut(),
787 dwX: 0,
788 dwY: 0,
789 dwXSize: 0,
790 dwYSize: 0,
791 dwXCountChars: 0,
792 dwYCountChars: 0,
793 dwFillAttribute: 0,
794 dwFlags: 0,
795 wShowWindow: 0,
796 cbReserved2: 0,
797 lpReserved2: ptr::null_mut(),
798 hStdInput: ptr::null_mut(),
799 hStdOutput: ptr::null_mut(),
800 hStdError: ptr::null_mut(),
801 }
802 }
803
804 fn zeroed_process_information() -> c::PROCESS_INFORMATION {
805 c::PROCESS_INFORMATION {
806 hProcess: ptr::null_mut(),
807 hThread: ptr::null_mut(),
808 dwProcessId: 0,
809 dwThreadId: 0,
810 }
811 }
812
813 // Produces a wide string *without terminating null*; returns an error if
814 // `prog` or any of the `args` contain a nul.
815 fn make_command_line(argv0: &OsStr, args: &[Arg], force_quotes: bool) -> io::Result<Vec<u16>> {
816 // Encode the command and arguments in a command line string such
817 // that the spawned process may recover them using CommandLineToArgvW.
818 let mut cmd: Vec<u16> = Vec::new();
819
820 // Always quote the program name so CreateProcess to avoid ambiguity when
821 // the child process parses its arguments.
822 // Note that quotes aren't escaped here because they can't be used in arg0.
823 // But that's ok because file paths can't contain quotes.
824 cmd.push(b'"' as u16);
825 cmd.extend(argv0.encode_wide());
826 cmd.push(b'"' as u16);
827
828 for arg in args {
829 cmd.push(' ' as u16);
830 args::append_arg(&mut cmd, arg, force_quotes)?;
831 }
832 Ok(cmd)
833 }
834
835 // Get `cmd.exe` for use with bat scripts, encoded as a UTF-16 string.
836 fn command_prompt() -> io::Result<Vec<u16>> {
837 let mut system: Vec<u16> = super::fill_utf16_buf(
838 |buf, size| unsafe { c::GetSystemDirectoryW(buf, size) },
839 |buf| buf.into(),
840 )?;
841 system.extend("\\cmd.exe".encode_utf16().chain([0]));
842 Ok(system)
843 }
844
845 fn make_envp(maybe_env: Option<BTreeMap<EnvKey, OsString>>) -> io::Result<(*mut c_void, Vec<u16>)> {
846 // On Windows we pass an "environment block" which is not a char**, but
847 // rather a concatenation of null-terminated k=v\0 sequences, with a final
848 // \0 to terminate.
849 if let Some(env) = maybe_env {
850 let mut blk = Vec::new();
851
852 // If there are no environment variables to set then signal this by
853 // pushing a null.
854 if env.is_empty() {
855 blk.push(0);
856 }
857
858 for (k, v) in env {
859 ensure_no_nuls(k.os_string)?;
860 blk.extend(k.utf16);
861 blk.push('=' as u16);
862 blk.extend(ensure_no_nuls(v)?.encode_wide());
863 blk.push(0);
864 }
865 blk.push(0);
866 Ok((blk.as_mut_ptr() as *mut c_void, blk))
867 } else {
868 Ok((ptr::null_mut(), Vec::new()))
869 }
870 }
871
872 fn make_dirp(d: Option<&OsString>) -> io::Result<(*const u16, Vec<u16>)> {
873 match d {
874 Some(dir) => {
875 let mut dir_str: Vec<u16> = ensure_no_nuls(dir)?.encode_wide().collect();
876 dir_str.push(0);
877 Ok((dir_str.as_ptr(), dir_str))
878 }
879 None => Ok((ptr::null(), Vec::new())),
880 }
881 }
882
883 struct ProcThreadAttributeList(Box<[MaybeUninit<u8>]>);
884
885 impl Drop for ProcThreadAttributeList {
886 fn drop(&mut self) {
887 let lp_attribute_list = self.0.as_mut_ptr() as _;
888 unsafe { c::DeleteProcThreadAttributeList(lp_attribute_list) }
889 }
890 }
891
892 /// Wrapper around the value data to be used as a Process Thread Attribute.
893 struct ProcThreadAttributeValue {
894 data: Box<dyn Send + Sync>,
895 size: usize,
896 }
897
898 fn make_proc_thread_attribute_list(
899 attributes: &BTreeMap<usize, ProcThreadAttributeValue>,
900 ) -> io::Result<ProcThreadAttributeList> {
901 // To initialize our ProcThreadAttributeList, we need to determine
902 // how many bytes to allocate for it. The Windows API simplifies this process
903 // by allowing us to call `InitializeProcThreadAttributeList` with
904 // a null pointer to retrieve the required size.
905 let mut required_size = 0;
906 let Ok(attribute_count) = attributes.len().try_into() else {
907 return Err(io::const_io_error!(
908 ErrorKind::InvalidInput,
909 "maximum number of ProcThreadAttributes exceeded",
910 ));
911 };
912 unsafe {
913 c::InitializeProcThreadAttributeList(
914 ptr::null_mut(),
915 attribute_count,
916 0,
917 &mut required_size,
918 )
919 };
920
921 let mut proc_thread_attribute_list = ProcThreadAttributeList(
922 vec![MaybeUninit::uninit(); required_size as usize].into_boxed_slice(),
923 );
924
925 // Once we've allocated the necessary memory, it's safe to invoke
926 // `InitializeProcThreadAttributeList` to properly initialize the list.
927 cvt(unsafe {
928 c::InitializeProcThreadAttributeList(
929 proc_thread_attribute_list.0.as_mut_ptr() as *mut _,
930 attribute_count,
931 0,
932 &mut required_size,
933 )
934 })?;
935
936 // # Add our attributes to the buffer.
937 // It's theoretically possible for the attribute count to exceed a u32 value.
938 // Therefore, we ensure that we don't add more attributes than the buffer was initialized for.
939 for (&attribute, value) in attributes.iter().take(attribute_count as usize) {
940 let value_ptr = &*value.data as *const (dyn Send + Sync) as _;
941 cvt(unsafe {
942 c::UpdateProcThreadAttribute(
943 proc_thread_attribute_list.0.as_mut_ptr() as _,
944 0,
945 attribute,
946 value_ptr,
947 value.size,
948 ptr::null_mut(),
949 ptr::null_mut(),
950 )
951 })?;
952 }
953
954 Ok(proc_thread_attribute_list)
955 }
956
957 pub struct CommandArgs<'a> {
958 iter: crate::slice::Iter<'a, Arg>,
959 }
960
961 impl<'a> Iterator for CommandArgs<'a> {
962 type Item = &'a OsStr;
963 fn next(&mut self) -> Option<&'a OsStr> {
964 self.iter.next().map(|arg| match arg {
965 Arg::Regular(s) | Arg::Raw(s) => s.as_ref(),
966 })
967 }
968 fn size_hint(&self) -> (usize, Option<usize>) {
969 self.iter.size_hint()
970 }
971 }
972
973 impl<'a> ExactSizeIterator for CommandArgs<'a> {
974 fn len(&self) -> usize {
975 self.iter.len()
976 }
977 fn is_empty(&self) -> bool {
978 self.iter.is_empty()
979 }
980 }
981
982 impl<'a> fmt::Debug for CommandArgs<'a> {
983 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
984 f.debug_list().entries(self.iter.clone()).finish()
985 }
986 }