1 #![unstable(feature = "process_internals", issue = "none")]
7 use crate::collections
::BTreeMap
;
9 use crate::env
::consts
::{EXE_EXTENSION, EXE_SUFFIX}
;
10 use crate::ffi
::{OsStr, OsString}
;
12 use crate::io
::{self, Error, ErrorKind}
;
14 use crate::num
::NonZeroI32
;
15 use crate::os
::windows
::ffi
::{OsStrExt, OsStringExt}
;
16 use crate::os
::windows
::io
::{AsHandle, AsRawHandle, BorrowedHandle, FromRawHandle, IntoRawHandle}
;
17 use crate::path
::{Path, PathBuf}
;
19 use crate::sync
::Mutex
;
20 use crate::sys
::args
::{self, Arg}
;
22 use crate::sys
::c
::NonZeroDWORD
;
24 use crate::sys
::fs
::{File, OpenOptions}
;
25 use crate::sys
::handle
::Handle
;
27 use crate::sys
::pipe
::{self, AnonPipe}
;
28 use crate::sys
::stdio
;
29 use crate::sys_common
::process
::{CommandEnv, CommandEnvs}
;
30 use crate::sys_common
::IntoInner
;
32 use libc
::{c_void, EXIT_FAILURE, EXIT_SUCCESS}
;
34 ////////////////////////////////////////////////////////////////////////////////
36 ////////////////////////////////////////////////////////////////////////////////
38 #[derive(Clone, Debug, Eq)]
42 // This stores a UTF-16 encoded string to workaround the mismatch between
43 // Rust's OsString (WTF-8) and the Windows API string type (UTF-16).
44 // Normally converting on every API call is acceptable but here
45 // `c::CompareStringOrdinal` will be called for every use of `==`.
50 fn new
<T
: Into
<OsString
>>(key
: T
) -> Self {
51 EnvKey
::from(key
.into())
55 // Comparing Windows environment variable keys[1] are behaviourally the
56 // composition of two operations[2]:
58 // 1. Case-fold both strings. This is done using a language-independent
59 // uppercase mapping that's unique to Windows (albeit based on data from an
60 // older Unicode spec). It only operates on individual UTF-16 code units so
61 // surrogates are left unchanged. This uppercase mapping can potentially change
62 // between Windows versions.
64 // 2. Perform an ordinal comparison of the strings. A comparison using ordinal
65 // is just a comparison based on the numerical value of each UTF-16 code unit[3].
67 // Because the case-folding mapping is unique to Windows and not guaranteed to
68 // be stable, we ask the OS to compare the strings for us. This is done by
69 // calling `CompareStringOrdinal`[4] with `bIgnoreCase` set to `TRUE`.
71 // [1] https://docs.microsoft.com/en-us/dotnet/standard/base-types/best-practices-strings#choosing-a-stringcomparison-member-for-your-method-call
72 // [2] https://docs.microsoft.com/en-us/dotnet/standard/base-types/best-practices-strings#stringtoupper-and-stringtolower
73 // [3] https://docs.microsoft.com/en-us/dotnet/api/system.stringcomparison?view=net-5.0#System_StringComparison_Ordinal
74 // [4] https://docs.microsoft.com/en-us/windows/win32/api/stringapiset/nf-stringapiset-comparestringordinal
76 fn cmp(&self, other
: &Self) -> cmp
::Ordering
{
78 let result
= c
::CompareStringOrdinal(
80 self.utf16
.len() as _
,
82 other
.utf16
.len() as _
,
86 c
::CSTR_LESS_THAN
=> cmp
::Ordering
::Less
,
87 c
::CSTR_EQUAL
=> cmp
::Ordering
::Equal
,
88 c
::CSTR_GREATER_THAN
=> cmp
::Ordering
::Greater
,
89 // `CompareStringOrdinal` should never fail so long as the parameters are correct.
90 _
=> panic
!("comparing environment keys failed: {}", Error
::last_os_error()),
95 impl PartialOrd
for EnvKey
{
96 fn partial_cmp(&self, other
: &Self) -> Option
<cmp
::Ordering
> {
100 impl PartialEq
for EnvKey
{
101 fn eq(&self, other
: &Self) -> bool
{
102 if self.utf16
.len() != other
.utf16
.len() {
105 self.cmp(other
) == cmp
::Ordering
::Equal
109 impl PartialOrd
<str> for EnvKey
{
110 fn partial_cmp(&self, other
: &str) -> Option
<cmp
::Ordering
> {
111 Some(self.cmp(&EnvKey
::new(other
)))
114 impl PartialEq
<str> for EnvKey
{
115 fn eq(&self, other
: &str) -> bool
{
116 if self.os_string
.len() != other
.len() {
119 self.cmp(&EnvKey
::new(other
)) == cmp
::Ordering
::Equal
124 // Environment variable keys should preserve their original case even though
125 // they are compared using a caseless string mapping.
126 impl From
<OsString
> for EnvKey
{
127 fn from(k
: OsString
) -> Self {
128 EnvKey { utf16: k.encode_wide().collect(), os_string: k }
132 impl From
<EnvKey
> for OsString
{
133 fn from(k
: EnvKey
) -> Self {
138 impl From
<&OsStr
> for EnvKey
{
139 fn from(k
: &OsStr
) -> Self {
140 Self::from(k
.to_os_string())
144 impl AsRef
<OsStr
> for EnvKey
{
145 fn as_ref(&self) -> &OsStr
{
150 pub(crate) fn ensure_no_nuls
<T
: AsRef
<OsStr
>>(str: T
) -> io
::Result
<T
> {
151 if str.as_ref().encode_wide().any(|b
| b
== 0) {
152 Err(io
::const_io_error
!(ErrorKind
::InvalidInput
, "nul byte found in provided data"))
162 cwd
: Option
<OsString
>,
164 detach
: bool
, // not currently exposed in std::process
165 stdin
: Option
<Stdio
>,
166 stdout
: Option
<Stdio
>,
167 stderr
: Option
<Stdio
>,
168 force_quotes_enabled
: bool
,
179 pub struct StdioPipes
{
180 pub stdin
: Option
<AnonPipe
>,
181 pub stdout
: Option
<AnonPipe
>,
182 pub stderr
: Option
<AnonPipe
>,
186 pub fn new(program
: &OsStr
) -> Command
{
188 program
: program
.to_os_string(),
190 env
: Default
::default(),
197 force_quotes_enabled
: false,
201 pub fn arg(&mut self, arg
: &OsStr
) {
202 self.args
.push(Arg
::Regular(arg
.to_os_string()))
204 pub fn env_mut(&mut self) -> &mut CommandEnv
{
207 pub fn cwd(&mut self, dir
: &OsStr
) {
208 self.cwd
= Some(dir
.to_os_string())
210 pub fn stdin(&mut self, stdin
: Stdio
) {
211 self.stdin
= Some(stdin
);
213 pub fn stdout(&mut self, stdout
: Stdio
) {
214 self.stdout
= Some(stdout
);
216 pub fn stderr(&mut self, stderr
: Stdio
) {
217 self.stderr
= Some(stderr
);
219 pub fn creation_flags(&mut self, flags
: u32) {
223 pub fn force_quotes(&mut self, enabled
: bool
) {
224 self.force_quotes_enabled
= enabled
;
227 pub fn raw_arg(&mut self, command_str_to_append
: &OsStr
) {
228 self.args
.push(Arg
::Raw(command_str_to_append
.to_os_string()))
231 pub fn get_program(&self) -> &OsStr
{
235 pub fn get_args(&self) -> CommandArgs
<'_
> {
236 let iter
= self.args
.iter();
240 pub fn get_envs(&self) -> CommandEnvs
<'_
> {
244 pub fn get_current_dir(&self) -> Option
<&Path
> {
245 self.cwd
.as_ref().map(|cwd
| Path
::new(cwd
))
252 ) -> io
::Result
<(Process
, StdioPipes
)> {
253 let maybe_env
= self.env
.capture_if_changed();
255 let child_paths
= if let Some(env
) = maybe_env
.as_ref() {
256 env
.get(&EnvKey
::new("PATH")).map(|s
| s
.as_os_str())
260 let program
= resolve_exe(&self.program
, || env
::var_os("PATH"), child_paths
)?
;
261 // Case insensitive "ends_with" of UTF-16 encoded ".bat" or ".cmd"
262 let is_batch_file
= matches
!(
263 program
.len().checked_sub(5).and_then(|i
| program
.get(i
..)),
264 Some([46, 98 | 66, 97 | 65, 116 | 84, 0] | [46, 99 | 67, 109 | 77, 100 | 68, 0])
266 let (program
, mut cmd_str
) = if is_batch_file
{
269 args
::make_bat_command_line(&program
, &self.args
, self.force_quotes_enabled
)?
,
272 let cmd_str
= make_command_line(&self.program
, &self.args
, self.force_quotes_enabled
)?
;
275 cmd_str
.push(0); // add null terminator
277 // stolen from the libuv code.
278 let mut flags
= self.flags
| c
::CREATE_UNICODE_ENVIRONMENT
;
280 flags
|= c
::DETACHED_PROCESS
| c
::CREATE_NEW_PROCESS_GROUP
;
283 let (envp
, _data
) = make_envp(maybe_env
)?
;
284 let (dirp
, _data
) = make_dirp(self.cwd
.as_ref())?
;
285 let mut pi
= zeroed_process_information();
287 // Prepare all stdio handles to be inherited by the child. This
288 // currently involves duplicating any existing ones with the ability to
289 // be inherited by child processes. Note, however, that once an
290 // inheritable handle is created, *any* spawned child will inherit that
291 // handle. We only want our own child to inherit this handle, so we wrap
292 // the remaining portion of this spawn in a mutex.
294 // For more information, msdn also has an article about this race:
295 // https://support.microsoft.com/kb/315939
296 static CREATE_PROCESS_LOCK
: Mutex
<()> = Mutex
::new(());
298 let _guard
= CREATE_PROCESS_LOCK
.lock();
300 let mut pipes
= StdioPipes { stdin: None, stdout: None, stderr: None }
;
301 let null
= Stdio
::Null
;
302 let default_stdin
= if needs_stdin { &default }
else { &null }
;
303 let stdin
= self.stdin
.as_ref().unwrap_or(default_stdin
);
304 let stdout
= self.stdout
.as_ref().unwrap_or(&default);
305 let stderr
= self.stderr
.as_ref().unwrap_or(&default);
306 let stdin
= stdin
.to_handle(c
::STD_INPUT_HANDLE
, &mut pipes
.stdin
)?
;
307 let stdout
= stdout
.to_handle(c
::STD_OUTPUT_HANDLE
, &mut pipes
.stdout
)?
;
308 let stderr
= stderr
.to_handle(c
::STD_ERROR_HANDLE
, &mut pipes
.stderr
)?
;
310 let mut si
= zeroed_startupinfo();
311 si
.cb
= mem
::size_of
::<c
::STARTUPINFOW
>() as c
::DWORD
;
313 // If at least one of stdin, stdout or stderr are set (i.e. are non null)
314 // then set the `hStd` fields in `STARTUPINFO`.
315 // Otherwise skip this and allow the OS to apply its default behaviour.
316 // This provides more consistent behaviour between Win7 and Win8+.
317 let is_set
= |stdio
: &Handle
| !stdio
.as_raw_handle().is_null();
318 if is_set(&stderr
) || is_set(&stdout
) || is_set(&stdin
) {
319 si
.dwFlags
|= c
::STARTF_USESTDHANDLES
;
320 si
.hStdInput
= stdin
.as_raw_handle();
321 si
.hStdOutput
= stdout
.as_raw_handle();
322 si
.hStdError
= stderr
.as_raw_handle();
326 cvt(c
::CreateProcessW(
328 cmd_str
.as_mut_ptr(),
343 handle
: Handle
::from_raw_handle(pi
.hProcess
),
344 main_thread_handle
: Handle
::from_raw_handle(pi
.hThread
),
351 pub fn output(&mut self) -> io
::Result
<(ExitStatus
, Vec
<u8>, Vec
<u8>)> {
352 let (proc
, pipes
) = self.spawn(Stdio
::MakePipe
, false)?
;
353 crate::sys_common
::process
::wait_with_output(proc
, pipes
)
357 impl fmt
::Debug
for Command
{
358 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
359 self.program
.fmt(f
)?
;
360 for arg
in &self.args
{
363 Arg
::Regular(s
) => s
.fmt(f
),
364 Arg
::Raw(s
) => f
.write_str(&s
.to_string_lossy()),
371 // Resolve `exe_path` to the executable name.
373 // * If the path is simply a file name then use the paths given by `search_paths` to find the executable.
374 // * Otherwise use the `exe_path` as given.
376 // This function may also append `.exe` to the name. The rationale for doing so is as follows:
378 // It is a very strong convention that Windows executables have the `exe` extension.
379 // In Rust, it is common to omit this extension.
380 // Therefore this functions first assumes `.exe` was intended.
381 // It falls back to the plain file name if a full path is given and the extension is omitted
382 // or if only a file name is given and it already contains an extension.
385 parent_paths
: impl FnOnce() -> Option
<OsString
>,
386 child_paths
: Option
<&OsStr
>,
387 ) -> io
::Result
<Vec
<u16>> {
388 // Early return if there is no filename.
389 if exe_path
.is_empty() || path
::has_trailing_slash(exe_path
) {
390 return Err(io
::const_io_error
!(
391 io
::ErrorKind
::InvalidInput
,
392 "program path has no file name",
395 // Test if the file name has the `exe` extension.
396 // This does a case-insensitive `ends_with`.
397 let has_exe_suffix
= if exe_path
.len() >= EXE_SUFFIX
.len() {
398 exe_path
.as_os_str_bytes()[exe_path
.len() - EXE_SUFFIX
.len()..]
399 .eq_ignore_ascii_case(EXE_SUFFIX
.as_bytes())
404 // If `exe_path` is an absolute path or a sub-path then don't search `PATH` for it.
405 if !path
::is_file_name(exe_path
) {
407 // The application name is a path to a `.exe` file.
408 // Let `CreateProcessW` figure out if it exists or not.
409 return args
::to_user_path(Path
::new(exe_path
));
411 let mut path
= PathBuf
::from(exe_path
);
413 // Append `.exe` if not already there.
414 path
= path
::append_suffix(path
, EXE_SUFFIX
.as_ref());
415 if let Some(path
) = program_exists(&path
) {
418 // It's ok to use `set_extension` here because the intent is to
419 // remove the extension that was just added.
420 path
.set_extension("");
421 return args
::to_user_path(&path
);
424 ensure_no_nuls(exe_path
)?
;
425 // From the `CreateProcessW` docs:
426 // > If the file name does not contain an extension, .exe is appended.
427 // Note that this rule only applies when searching paths.
428 let has_extension
= exe_path
.as_os_str_bytes().contains(&b'
.'
);
430 // Search the directories given by `search_paths`.
431 let result
= search_paths(parent_paths
, child_paths
, |mut path
| {
432 path
.push(&exe_path
);
434 path
.set_extension(EXE_EXTENSION
);
436 program_exists(&path
)
438 if let Some(path
) = result
{
442 // If we get here then the executable cannot be found.
443 Err(io
::const_io_error
!(io
::ErrorKind
::NotFound
, "program not found"))
446 // Calls `f` for every path that should be used to find an executable.
447 // Returns once `f` returns the path to an executable or all paths have been searched.
448 fn search_paths
<Paths
, Exists
>(
450 child_paths
: Option
<&OsStr
>,
452 ) -> Option
<Vec
<u16>>
454 Paths
: FnOnce() -> Option
<OsString
>,
455 Exists
: FnMut(PathBuf
) -> Option
<Vec
<u16>>,
458 // This is for consistency with Rust's historic behaviour.
459 if let Some(paths
) = child_paths
{
460 for path
in env
::split_paths(paths
).filter(|p
| !p
.as_os_str().is_empty()) {
461 if let Some(path
) = exists(path
) {
467 // 2. Application path
468 if let Ok(mut app_path
) = env
::current_exe() {
470 if let Some(path
) = exists(app_path
) {
475 // 3 & 4. System paths
476 // SAFETY: This uses `fill_utf16_buf` to safely call the OS functions.
478 if let Ok(Some(path
)) = super::fill_utf16_buf(
479 |buf
, size
| c
::GetSystemDirectoryW(buf
, size
),
480 |buf
| exists(PathBuf
::from(OsString
::from_wide(buf
))),
484 #[cfg(not(target_vendor = "uwp"))]
486 if let Ok(Some(path
)) = super::fill_utf16_buf(
487 |buf
, size
| c
::GetWindowsDirectoryW(buf
, size
),
488 |buf
| exists(PathBuf
::from(OsString
::from_wide(buf
))),
496 if let Some(parent_paths
) = parent_paths() {
497 for path
in env
::split_paths(&parent_paths
).filter(|p
| !p
.as_os_str().is_empty()) {
498 if let Some(path
) = exists(path
) {
506 /// Check if a file exists without following symlinks.
507 fn program_exists(path
: &Path
) -> Option
<Vec
<u16>> {
509 let path
= args
::to_user_path(path
).ok()?
;
510 // Getting attributes using `GetFileAttributesW` does not follow symlinks
511 // and it will almost always be successful if the link exists.
512 // There are some exceptions for special system files (e.g. the pagefile)
513 // but these are not executable.
514 if c
::GetFileAttributesW(path
.as_ptr()) == c
::INVALID_FILE_ATTRIBUTES
{
523 fn to_handle(&self, stdio_id
: c
::DWORD
, pipe
: &mut Option
<AnonPipe
>) -> io
::Result
<Handle
> {
525 Stdio
::Inherit
=> match stdio
::get_handle(stdio_id
) {
527 let io
= Handle
::from_raw_handle(io
);
528 let ret
= io
.duplicate(0, true, c
::DUPLICATE_SAME_ACCESS
);
529 io
.into_raw_handle();
532 // If no stdio handle is available, then propagate the null value.
533 Err(..) => unsafe { Ok(Handle::from_raw_handle(ptr::null_mut())) }
,
537 let ours_readable
= stdio_id
!= c
::STD_INPUT_HANDLE
;
538 let pipes
= pipe
::anon_pipe(ours_readable
, true)?
;
539 *pipe
= Some(pipes
.ours
);
540 Ok(pipes
.theirs
.into_handle())
543 Stdio
::Pipe(ref source
) => {
544 let ours_readable
= stdio_id
!= c
::STD_INPUT_HANDLE
;
545 pipe
::spawn_pipe_relay(source
, ours_readable
, true).map(AnonPipe
::into_handle
)
548 Stdio
::Handle(ref handle
) => handle
.duplicate(0, true, c
::DUPLICATE_SAME_ACCESS
),
550 // Open up a reference to NUL with appropriate read/write
551 // permissions as well as the ability to be inherited to child
552 // processes (as this is about to be inherited).
554 let size
= mem
::size_of
::<c
::SECURITY_ATTRIBUTES
>();
555 let mut sa
= c
::SECURITY_ATTRIBUTES
{
556 nLength
: size
as c
::DWORD
,
557 lpSecurityDescriptor
: ptr
::null_mut(),
560 let mut opts
= OpenOptions
::new();
561 opts
.read(stdio_id
== c
::STD_INPUT_HANDLE
);
562 opts
.write(stdio_id
!= c
::STD_INPUT_HANDLE
);
563 opts
.security_attributes(&mut sa
);
564 File
::open(Path
::new("NUL"), &opts
).map(|file
| file
.into_inner())
570 impl From
<AnonPipe
> for Stdio
{
571 fn from(pipe
: AnonPipe
) -> Stdio
{
576 impl From
<File
> for Stdio
{
577 fn from(file
: File
) -> Stdio
{
578 Stdio
::Handle(file
.into_inner())
582 ////////////////////////////////////////////////////////////////////////////////
584 ////////////////////////////////////////////////////////////////////////////////
586 /// A value representing a child process.
588 /// The lifetime of this value is linked to the lifetime of the actual
589 /// process - the Process destructor calls self.finish() which waits
590 /// for the process to terminate.
593 main_thread_handle
: Handle
,
597 pub fn kill(&mut self) -> io
::Result
<()> {
598 let result
= unsafe { c::TerminateProcess(self.handle.as_raw_handle(), 1) }
;
599 if result
== c
::FALSE
{
600 let error
= unsafe { c::GetLastError() }
;
601 // TerminateProcess returns ERROR_ACCESS_DENIED if the process has already been
602 // terminated (by us, or for any other reason). So check if the process was actually
603 // terminated, and if so, do not return an error.
604 if error
!= c
::ERROR_ACCESS_DENIED
|| self.try_wait().is_err() {
605 return Err(crate::io
::Error
::from_raw_os_error(error
as i32));
611 pub fn id(&self) -> u32 {
612 unsafe { c::GetProcessId(self.handle.as_raw_handle()) as u32 }
615 pub fn main_thread_handle(&self) -> BorrowedHandle
<'_
> {
616 self.main_thread_handle
.as_handle()
619 pub fn wait(&mut self) -> io
::Result
<ExitStatus
> {
621 let res
= c
::WaitForSingleObject(self.handle
.as_raw_handle(), c
::INFINITE
);
622 if res
!= c
::WAIT_OBJECT_0
{
623 return Err(Error
::last_os_error());
626 cvt(c
::GetExitCodeProcess(self.handle
.as_raw_handle(), &mut status
))?
;
627 Ok(ExitStatus(status
))
631 pub fn try_wait(&mut self) -> io
::Result
<Option
<ExitStatus
>> {
633 match c
::WaitForSingleObject(self.handle
.as_raw_handle(), 0) {
634 c
::WAIT_OBJECT_0
=> {}
638 _
=> return Err(io
::Error
::last_os_error()),
641 cvt(c
::GetExitCodeProcess(self.handle
.as_raw_handle(), &mut status
))?
;
642 Ok(Some(ExitStatus(status
)))
646 pub fn handle(&self) -> &Handle
{
650 pub fn into_handle(self) -> Handle
{
655 #[derive(PartialEq, Eq, Clone, Copy, Debug, Default)]
656 pub struct ExitStatus(c
::DWORD
);
659 pub fn exit_ok(&self) -> Result
<(), ExitStatusError
> {
660 match NonZeroDWORD
::try_from(self.0) {
661 /* was nonzero */ Ok(failure
) => Err(ExitStatusError(failure
)),
662 /* was zero, couldn't convert */ Err(_
) => Ok(()),
665 pub fn code(&self) -> Option
<i32> {
670 /// Converts a raw `c::DWORD` to a type-safe `ExitStatus` by wrapping it without copying.
671 impl From
<c
::DWORD
> for ExitStatus
{
672 fn from(u
: c
::DWORD
) -> ExitStatus
{
677 impl fmt
::Display
for ExitStatus
{
678 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
679 // Windows exit codes with the high bit set typically mean some form of
680 // unhandled exception or warning. In this scenario printing the exit
681 // code in decimal doesn't always make sense because it's a very large
682 // and somewhat gibberish number. The hex code is a bit more
683 // recognizable and easier to search for, so print that.
684 if self.0 & 0x80000000 != 0 {
685 write
!(f
, "exit code: {:#x}", self.0)
687 write
!(f
, "exit code: {}", self.0)
692 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
693 pub struct ExitStatusError(c
::NonZeroDWORD
);
695 impl Into
<ExitStatus
> for ExitStatusError
{
696 fn into(self) -> ExitStatus
{
697 ExitStatus(self.0.into
())
701 impl ExitStatusError
{
702 pub fn code(self) -> Option
<NonZeroI32
> {
703 Some((u32::from(self.0) as i32).try_into().unwrap())
707 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
708 pub struct ExitCode(c
::DWORD
);
711 pub const SUCCESS
: ExitCode
= ExitCode(EXIT_SUCCESS
as _
);
712 pub const FAILURE
: ExitCode
= ExitCode(EXIT_FAILURE
as _
);
715 pub fn as_i32(&self) -> i32 {
720 impl From
<u8> for ExitCode
{
721 fn from(code
: u8) -> Self {
722 ExitCode(c
::DWORD
::from(code
))
726 impl From
<u32> for ExitCode
{
727 fn from(code
: u32) -> Self {
728 ExitCode(c
::DWORD
::from(code
))
732 fn zeroed_startupinfo() -> c
::STARTUPINFOW
{
735 lpReserved
: ptr
::null_mut(),
736 lpDesktop
: ptr
::null_mut(),
737 lpTitle
: ptr
::null_mut(),
748 lpReserved2
: ptr
::null_mut(),
749 hStdInput
: ptr
::null_mut(),
750 hStdOutput
: ptr
::null_mut(),
751 hStdError
: ptr
::null_mut(),
755 fn zeroed_process_information() -> c
::PROCESS_INFORMATION
{
756 c
::PROCESS_INFORMATION
{
757 hProcess
: ptr
::null_mut(),
758 hThread
: ptr
::null_mut(),
764 // Produces a wide string *without terminating null*; returns an error if
765 // `prog` or any of the `args` contain a nul.
766 fn make_command_line(argv0
: &OsStr
, args
: &[Arg
], force_quotes
: bool
) -> io
::Result
<Vec
<u16>> {
767 // Encode the command and arguments in a command line string such
768 // that the spawned process may recover them using CommandLineToArgvW.
769 let mut cmd
: Vec
<u16> = Vec
::new();
771 // Always quote the program name so CreateProcess to avoid ambiguity when
772 // the child process parses its arguments.
773 // Note that quotes aren't escaped here because they can't be used in arg0.
774 // But that's ok because file paths can't contain quotes.
775 cmd
.push(b'
"' as u16);
776 cmd.extend(argv0.encode_wide());
777 cmd.push(b'"'
as u16);
780 cmd
.push(' '
as u16);
781 args
::append_arg(&mut cmd
, arg
, force_quotes
)?
;
786 // Get `cmd.exe` for use with bat scripts, encoded as a UTF-16 string.
787 fn command_prompt() -> io
::Result
<Vec
<u16>> {
788 let mut system
: Vec
<u16> = super::fill_utf16_buf(
789 |buf
, size
| unsafe { c::GetSystemDirectoryW(buf, size) }
,
792 system
.extend("\\cmd.exe".encode_utf16().chain([0]));
796 fn make_envp(maybe_env
: Option
<BTreeMap
<EnvKey
, OsString
>>) -> io
::Result
<(*mut c_void
, Vec
<u16>)> {
797 // On Windows we pass an "environment block" which is not a char**, but
798 // rather a concatenation of null-terminated k=v\0 sequences, with a final
800 if let Some(env
) = maybe_env
{
801 let mut blk
= Vec
::new();
803 // If there are no environment variables to set then signal this by
810 ensure_no_nuls(k
.os_string
)?
;
812 blk
.push('
='
as u16);
813 blk
.extend(ensure_no_nuls(v
)?
.encode_wide());
817 Ok((blk
.as_mut_ptr() as *mut c_void
, blk
))
819 Ok((ptr
::null_mut(), Vec
::new()))
823 fn make_dirp(d
: Option
<&OsString
>) -> io
::Result
<(*const u16, Vec
<u16>)> {
826 let mut dir_str
: Vec
<u16> = ensure_no_nuls(dir
)?
.encode_wide().collect();
828 Ok((dir_str
.as_ptr(), dir_str
))
830 None
=> Ok((ptr
::null(), Vec
::new())),
834 pub struct CommandArgs
<'a
> {
835 iter
: crate::slice
::Iter
<'a
, Arg
>,
838 impl<'a
> Iterator
for CommandArgs
<'a
> {
839 type Item
= &'a OsStr
;
840 fn next(&mut self) -> Option
<&'a OsStr
> {
841 self.iter
.next().map(|arg
| match arg
{
842 Arg
::Regular(s
) | Arg
::Raw(s
) => s
.as_ref(),
845 fn size_hint(&self) -> (usize, Option
<usize>) {
846 self.iter
.size_hint()
850 impl<'a
> ExactSizeIterator
for CommandArgs
<'a
> {
851 fn len(&self) -> usize {
854 fn is_empty(&self) -> bool
{
859 impl<'a
> fmt
::Debug
for CommandArgs
<'a
> {
860 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
861 f
.debug_list().entries(self.iter
.clone()).finish()