1#![unstable(feature = "process_internals", issue = "none")]
2
3#[cfg(test)]
4mod tests;
5
6use core::ffi::c_void;
7
8use super::env::{CommandEnv, CommandEnvs};
9use crate::collections::BTreeMap;
10use crate::env::consts::{EXE_EXTENSION, EXE_SUFFIX};
11use crate::ffi::{OsStr, OsString};
12use crate::io::{self, Error};
13use crate::num::NonZero;
14use crate::os::windows::ffi::{OsStrExt, OsStringExt};
15use crate::os::windows::io::{AsHandle, AsRawHandle, BorrowedHandle, FromRawHandle, IntoRawHandle};
16use crate::os::windows::process::ProcThreadAttributeList;
17use crate::path::{Path, PathBuf};
18use crate::process::StdioPipes;
19use crate::sync::Mutex;
20use crate::sys::args::{self, Arg};
21use crate::sys::c::{self, EXIT_FAILURE, EXIT_SUCCESS};
22use crate::sys::fs::{File, OpenOptions};
23use crate::sys::handle::Handle;
24use crate::sys::pal::api::{self, WinError, utf16};
25use crate::sys::pal::{ensure_no_nuls, fill_utf16_buf};
26use crate::sys::pipe::{self, AnonPipe};
27use crate::sys::{cvt, path, stdio};
28use crate::sys_common::IntoInner;
29use crate::{cmp, env, fmt, ptr};
30
31#[derive(Clone, Debug, Eq)]
36#[doc(hidden)]
37pub struct EnvKey {
38 os_string: OsString,
39 utf16: Vec<u16>,
44}
45
46impl EnvKey {
47 fn new<T: Into<OsString>>(key: T) -> Self {
48 EnvKey::from(key.into())
49 }
50}
51
52impl Ord for EnvKey {
73 fn cmp(&self, other: &Self) -> cmp::Ordering {
74 unsafe {
75 let result = c::CompareStringOrdinal(
76 self.utf16.as_ptr(),
77 self.utf16.len() as _,
78 other.utf16.as_ptr(),
79 other.utf16.len() as _,
80 c::TRUE,
81 );
82 match result {
83 c::CSTR_LESS_THAN => cmp::Ordering::Less,
84 c::CSTR_EQUAL => cmp::Ordering::Equal,
85 c::CSTR_GREATER_THAN => cmp::Ordering::Greater,
86 _ => panic!("comparing environment keys failed: {}", Error::last_os_error()),
88 }
89 }
90 }
91}
92impl PartialOrd for EnvKey {
93 fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
94 Some(self.cmp(other))
95 }
96}
97impl PartialEq for EnvKey {
98 fn eq(&self, other: &Self) -> bool {
99 if self.utf16.len() != other.utf16.len() {
100 false
101 } else {
102 self.cmp(other) == cmp::Ordering::Equal
103 }
104 }
105}
106impl PartialOrd<str> for EnvKey {
107 fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
108 Some(self.cmp(&EnvKey::new(other)))
109 }
110}
111impl PartialEq<str> for EnvKey {
112 fn eq(&self, other: &str) -> bool {
113 if self.os_string.len() != other.len() {
114 false
115 } else {
116 self.cmp(&EnvKey::new(other)) == cmp::Ordering::Equal
117 }
118 }
119}
120
121impl From<OsString> for EnvKey {
124 fn from(k: OsString) -> Self {
125 EnvKey { utf16: k.encode_wide().collect(), os_string: k }
126 }
127}
128
129impl From<EnvKey> for OsString {
130 fn from(k: EnvKey) -> Self {
131 k.os_string
132 }
133}
134
135impl From<&OsStr> for EnvKey {
136 fn from(k: &OsStr) -> Self {
137 Self::from(k.to_os_string())
138 }
139}
140
141impl AsRef<OsStr> for EnvKey {
142 fn as_ref(&self) -> &OsStr {
143 &self.os_string
144 }
145}
146
147pub struct Command {
148 program: OsString,
149 args: Vec<Arg>,
150 env: CommandEnv,
151 cwd: Option<OsString>,
152 flags: u32,
153 show_window: Option<u16>,
154 detach: bool, stdin: Option<Stdio>,
156 stdout: Option<Stdio>,
157 stderr: Option<Stdio>,
158 force_quotes_enabled: bool,
159 startupinfo_fullscreen: bool,
160 startupinfo_untrusted_source: bool,
161 startupinfo_force_feedback: Option<bool>,
162 inherit_handles: bool,
163}
164
165pub enum Stdio {
166 Inherit,
167 InheritSpecific { from_stdio_id: u32 },
168 Null,
169 MakePipe,
170 Pipe(AnonPipe),
171 Handle(Handle),
172}
173
174impl Command {
175 pub fn new(program: &OsStr) -> Command {
176 Command {
177 program: program.to_os_string(),
178 args: Vec::new(),
179 env: Default::default(),
180 cwd: None,
181 flags: 0,
182 show_window: None,
183 detach: false,
184 stdin: None,
185 stdout: None,
186 stderr: None,
187 force_quotes_enabled: false,
188 startupinfo_fullscreen: false,
189 startupinfo_untrusted_source: false,
190 startupinfo_force_feedback: None,
191 inherit_handles: true,
192 }
193 }
194
195 pub fn arg(&mut self, arg: &OsStr) {
196 self.args.push(Arg::Regular(arg.to_os_string()))
197 }
198 pub fn env_mut(&mut self) -> &mut CommandEnv {
199 &mut self.env
200 }
201 pub fn cwd(&mut self, dir: &OsStr) {
202 self.cwd = Some(dir.to_os_string())
203 }
204 pub fn stdin(&mut self, stdin: Stdio) {
205 self.stdin = Some(stdin);
206 }
207 pub fn stdout(&mut self, stdout: Stdio) {
208 self.stdout = Some(stdout);
209 }
210 pub fn stderr(&mut self, stderr: Stdio) {
211 self.stderr = Some(stderr);
212 }
213 pub fn creation_flags(&mut self, flags: u32) {
214 self.flags = flags;
215 }
216 pub fn show_window(&mut self, cmd_show: Option<u16>) {
217 self.show_window = cmd_show;
218 }
219
220 pub fn force_quotes(&mut self, enabled: bool) {
221 self.force_quotes_enabled = enabled;
222 }
223
224 pub fn raw_arg(&mut self, command_str_to_append: &OsStr) {
225 self.args.push(Arg::Raw(command_str_to_append.to_os_string()))
226 }
227
228 pub fn startupinfo_fullscreen(&mut self, enabled: bool) {
229 self.startupinfo_fullscreen = enabled;
230 }
231
232 pub fn startupinfo_untrusted_source(&mut self, enabled: bool) {
233 self.startupinfo_untrusted_source = enabled;
234 }
235
236 pub fn startupinfo_force_feedback(&mut self, enabled: Option<bool>) {
237 self.startupinfo_force_feedback = enabled;
238 }
239
240 pub fn get_program(&self) -> &OsStr {
241 &self.program
242 }
243
244 pub fn get_args(&self) -> CommandArgs<'_> {
245 let iter = self.args.iter();
246 CommandArgs { iter }
247 }
248
249 pub fn get_envs(&self) -> CommandEnvs<'_> {
250 self.env.iter()
251 }
252
253 pub fn get_current_dir(&self) -> Option<&Path> {
254 self.cwd.as_ref().map(Path::new)
255 }
256
257 pub fn inherit_handles(&mut self, inherit_handles: bool) {
258 self.inherit_handles = inherit_handles;
259 }
260
261 pub fn spawn(
262 &mut self,
263 default: Stdio,
264 needs_stdin: bool,
265 ) -> io::Result<(Process, StdioPipes)> {
266 self.spawn_with_attributes(default, needs_stdin, None)
267 }
268
269 pub fn spawn_with_attributes(
270 &mut self,
271 default: Stdio,
272 needs_stdin: bool,
273 proc_thread_attribute_list: Option<&ProcThreadAttributeList<'_>>,
274 ) -> io::Result<(Process, StdioPipes)> {
275 let env_saw_path = self.env.have_changed_path();
276 let maybe_env = self.env.capture_if_changed();
277
278 let child_paths = if env_saw_path && let Some(env) = maybe_env.as_ref() {
279 env.get(&EnvKey::new("PATH")).map(|s| s.as_os_str())
280 } else {
281 None
282 };
283 let program = resolve_exe(&self.program, || env::var_os("PATH"), child_paths)?;
284 let has_bat_extension = |program: &[u16]| {
285 matches!(
286 program.len().checked_sub(4).and_then(|i| program.get(i..)),
288 Some([46, 98 | 66, 97 | 65, 116 | 84] | [46, 99 | 67, 109 | 77, 100 | 68])
289 )
290 };
291 let is_batch_file = if path::is_verbatim(&program) {
292 has_bat_extension(&program[..program.len() - 1])
293 } else {
294 fill_utf16_buf(
295 |buffer, size| unsafe {
296 c::GetFullPathNameW(program.as_ptr(), size, buffer, ptr::null_mut())
298 },
299 |program| has_bat_extension(program),
300 )?
301 };
302 let (program, mut cmd_str) = if is_batch_file {
303 (
304 command_prompt()?,
305 args::make_bat_command_line(&program, &self.args, self.force_quotes_enabled)?,
306 )
307 } else {
308 let cmd_str = make_command_line(&self.program, &self.args, self.force_quotes_enabled)?;
309 (program, cmd_str)
310 };
311 cmd_str.push(0); let mut flags = self.flags | c::CREATE_UNICODE_ENVIRONMENT;
315 if self.detach {
316 flags |= c::DETACHED_PROCESS | c::CREATE_NEW_PROCESS_GROUP;
317 }
318
319 let inherit_handles = self.inherit_handles as c::BOOL;
320 let (envp, _data) = make_envp(maybe_env)?;
321 let (dirp, _data) = make_dirp(self.cwd.as_ref())?;
322 let mut pi = zeroed_process_information();
323
324 static CREATE_PROCESS_LOCK: Mutex<()> = Mutex::new(());
334
335 let _guard = CREATE_PROCESS_LOCK.lock();
336
337 let mut pipes = StdioPipes { stdin: None, stdout: None, stderr: None };
338 let null = Stdio::Null;
339 let default_stdin = if needs_stdin { &default } else { &null };
340 let stdin = self.stdin.as_ref().unwrap_or(default_stdin);
341 let stdout = self.stdout.as_ref().unwrap_or(&default);
342 let stderr = self.stderr.as_ref().unwrap_or(&default);
343 let stdin = stdin.to_handle(c::STD_INPUT_HANDLE, &mut pipes.stdin)?;
344 let stdout = stdout.to_handle(c::STD_OUTPUT_HANDLE, &mut pipes.stdout)?;
345 let stderr = stderr.to_handle(c::STD_ERROR_HANDLE, &mut pipes.stderr)?;
346
347 let mut si = zeroed_startupinfo();
348
349 let is_set = |stdio: &Handle| !stdio.as_raw_handle().is_null();
354 if is_set(&stderr) || is_set(&stdout) || is_set(&stdin) {
355 si.dwFlags |= c::STARTF_USESTDHANDLES;
356 si.hStdInput = stdin.as_raw_handle();
357 si.hStdOutput = stdout.as_raw_handle();
358 si.hStdError = stderr.as_raw_handle();
359 }
360
361 if let Some(cmd_show) = self.show_window {
362 si.dwFlags |= c::STARTF_USESHOWWINDOW;
363 si.wShowWindow = cmd_show;
364 }
365
366 if self.startupinfo_fullscreen {
367 si.dwFlags |= c::STARTF_RUNFULLSCREEN;
368 }
369
370 if self.startupinfo_untrusted_source {
371 si.dwFlags |= c::STARTF_UNTRUSTEDSOURCE;
372 }
373
374 match self.startupinfo_force_feedback {
375 Some(true) => {
376 si.dwFlags |= c::STARTF_FORCEONFEEDBACK;
377 }
378 Some(false) => {
379 si.dwFlags |= c::STARTF_FORCEOFFFEEDBACK;
380 }
381 None => {}
382 }
383
384 let si_ptr: *mut c::STARTUPINFOW;
385
386 let mut si_ex;
387
388 if let Some(proc_thread_attribute_list) = proc_thread_attribute_list {
389 si.cb = size_of::<c::STARTUPINFOEXW>() as u32;
390 flags |= c::EXTENDED_STARTUPINFO_PRESENT;
391
392 si_ex = c::STARTUPINFOEXW {
393 StartupInfo: si,
394 lpAttributeList: proc_thread_attribute_list.as_ptr().cast::<c_void>().cast_mut(),
398 };
399 si_ptr = (&raw mut si_ex) as _;
400 } else {
401 si.cb = size_of::<c::STARTUPINFOW>() as u32;
402 si_ptr = (&raw mut si) as _;
403 }
404
405 unsafe {
406 cvt(c::CreateProcessW(
407 program.as_ptr(),
408 cmd_str.as_mut_ptr(),
409 ptr::null_mut(),
410 ptr::null_mut(),
411 inherit_handles,
412 flags,
413 envp,
414 dirp,
415 si_ptr,
416 &mut pi,
417 ))
418 }?;
419
420 unsafe {
421 Ok((
422 Process {
423 handle: Handle::from_raw_handle(pi.hProcess),
424 main_thread_handle: Handle::from_raw_handle(pi.hThread),
425 },
426 pipes,
427 ))
428 }
429 }
430}
431
432impl fmt::Debug for Command {
433 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
434 self.program.fmt(f)?;
435 for arg in &self.args {
436 f.write_str(" ")?;
437 match arg {
438 Arg::Regular(s) => s.fmt(f),
439 Arg::Raw(s) => f.write_str(&s.to_string_lossy()),
440 }?;
441 }
442 Ok(())
443 }
444}
445
446fn resolve_exe<'a>(
459 exe_path: &'a OsStr,
460 parent_paths: impl FnOnce() -> Option<OsString>,
461 child_paths: Option<&OsStr>,
462) -> io::Result<Vec<u16>> {
463 if exe_path.is_empty() || path::has_trailing_slash(exe_path) {
465 return Err(io::const_error!(io::ErrorKind::InvalidInput, "program path has no file name"));
466 }
467 let has_exe_suffix = if exe_path.len() >= EXE_SUFFIX.len() {
470 exe_path.as_encoded_bytes()[exe_path.len() - EXE_SUFFIX.len()..]
471 .eq_ignore_ascii_case(EXE_SUFFIX.as_bytes())
472 } else {
473 false
474 };
475
476 if !path::is_file_name(exe_path) {
478 if has_exe_suffix {
479 return args::to_user_path(Path::new(exe_path));
482 }
483 let mut path = PathBuf::from(exe_path);
484
485 path = path::append_suffix(path, EXE_SUFFIX.as_ref());
487 if let Some(path) = program_exists(&path) {
488 return Ok(path);
489 } else {
490 path.set_extension("");
493 return args::to_user_path(&path);
494 }
495 } else {
496 ensure_no_nuls(exe_path)?;
497 let has_extension = exe_path.as_encoded_bytes().contains(&b'.');
501
502 let result = search_paths(parent_paths, child_paths, |mut path| {
504 path.push(exe_path);
505 if !has_extension {
506 path.set_extension(EXE_EXTENSION);
507 }
508 program_exists(&path)
509 });
510 if let Some(path) = result {
511 return Ok(path);
512 }
513 }
514 Err(io::const_error!(io::ErrorKind::NotFound, "program not found"))
516}
517
518fn search_paths<Paths, Exists>(
521 parent_paths: Paths,
522 child_paths: Option<&OsStr>,
523 mut exists: Exists,
524) -> Option<Vec<u16>>
525where
526 Paths: FnOnce() -> Option<OsString>,
527 Exists: FnMut(PathBuf) -> Option<Vec<u16>>,
528{
529 if let Some(paths) = child_paths {
532 for path in env::split_paths(paths).filter(|p| !p.as_os_str().is_empty()) {
533 if let Some(path) = exists(path) {
534 return Some(path);
535 }
536 }
537 }
538
539 if let Ok(mut app_path) = env::current_exe() {
541 app_path.pop();
542 if let Some(path) = exists(app_path) {
543 return Some(path);
544 }
545 }
546
547 unsafe {
550 if let Ok(Some(path)) = fill_utf16_buf(
551 |buf, size| c::GetSystemDirectoryW(buf, size),
552 |buf| exists(PathBuf::from(OsString::from_wide(buf))),
553 ) {
554 return Some(path);
555 }
556 #[cfg(not(target_vendor = "uwp"))]
557 {
558 if let Ok(Some(path)) = fill_utf16_buf(
559 |buf, size| c::GetWindowsDirectoryW(buf, size),
560 |buf| exists(PathBuf::from(OsString::from_wide(buf))),
561 ) {
562 return Some(path);
563 }
564 }
565 }
566
567 if let Some(parent_paths) = parent_paths() {
569 for path in env::split_paths(&parent_paths).filter(|p| !p.as_os_str().is_empty()) {
570 if let Some(path) = exists(path) {
571 return Some(path);
572 }
573 }
574 }
575 None
576}
577
578fn program_exists(path: &Path) -> Option<Vec<u16>> {
580 unsafe {
581 let path = args::to_user_path(path).ok()?;
582 if c::GetFileAttributesW(path.as_ptr()) == c::INVALID_FILE_ATTRIBUTES {
587 None
588 } else {
589 Some(path)
590 }
591 }
592}
593
594impl Stdio {
595 fn to_handle(&self, stdio_id: u32, pipe: &mut Option<AnonPipe>) -> io::Result<Handle> {
596 let use_stdio_id = |stdio_id| match stdio::get_handle(stdio_id) {
597 Ok(io) => unsafe {
598 let io = Handle::from_raw_handle(io);
599 let ret = io.duplicate(0, true, c::DUPLICATE_SAME_ACCESS);
600 let _ = io.into_raw_handle(); ret
602 },
603 Err(..) => unsafe { Ok(Handle::from_raw_handle(ptr::null_mut())) },
605 };
606 match *self {
607 Stdio::Inherit => use_stdio_id(stdio_id),
608 Stdio::InheritSpecific { from_stdio_id } => use_stdio_id(from_stdio_id),
609
610 Stdio::MakePipe => {
611 let ours_readable = stdio_id != c::STD_INPUT_HANDLE;
612 let pipes = pipe::anon_pipe(ours_readable, true)?;
613 *pipe = Some(pipes.ours);
614 Ok(pipes.theirs.into_handle())
615 }
616
617 Stdio::Pipe(ref source) => {
618 let ours_readable = stdio_id != c::STD_INPUT_HANDLE;
619 pipe::spawn_pipe_relay(source, ours_readable, true).map(AnonPipe::into_handle)
620 }
621
622 Stdio::Handle(ref handle) => handle.duplicate(0, true, c::DUPLICATE_SAME_ACCESS),
623
624 Stdio::Null => {
628 let mut opts = OpenOptions::new();
629 opts.read(stdio_id == c::STD_INPUT_HANDLE);
630 opts.write(stdio_id != c::STD_INPUT_HANDLE);
631 opts.inherit_handle(true);
632 File::open(Path::new(r"\\.\NUL"), &opts).map(|file| file.into_inner())
633 }
634 }
635 }
636}
637
638impl From<AnonPipe> for Stdio {
639 fn from(pipe: AnonPipe) -> Stdio {
640 Stdio::Pipe(pipe)
641 }
642}
643
644impl From<Handle> for Stdio {
645 fn from(pipe: Handle) -> Stdio {
646 Stdio::Handle(pipe)
647 }
648}
649
650impl From<File> for Stdio {
651 fn from(file: File) -> Stdio {
652 Stdio::Handle(file.into_inner())
653 }
654}
655
656impl From<io::Stdout> for Stdio {
657 fn from(_: io::Stdout) -> Stdio {
658 Stdio::InheritSpecific { from_stdio_id: c::STD_OUTPUT_HANDLE }
659 }
660}
661
662impl From<io::Stderr> for Stdio {
663 fn from(_: io::Stderr) -> Stdio {
664 Stdio::InheritSpecific { from_stdio_id: c::STD_ERROR_HANDLE }
665 }
666}
667
668pub struct Process {
678 handle: Handle,
679 main_thread_handle: Handle,
680}
681
682impl Process {
683 pub fn kill(&mut self) -> io::Result<()> {
684 let result = unsafe { c::TerminateProcess(self.handle.as_raw_handle(), 1) };
685 if result == c::FALSE {
686 let error = api::get_last_error();
687 if error != WinError::ACCESS_DENIED || self.try_wait().is_err() {
691 return Err(crate::io::Error::from_raw_os_error(error.code as i32));
692 }
693 }
694 Ok(())
695 }
696
697 pub fn id(&self) -> u32 {
698 unsafe { c::GetProcessId(self.handle.as_raw_handle()) }
699 }
700
701 pub fn main_thread_handle(&self) -> BorrowedHandle<'_> {
702 self.main_thread_handle.as_handle()
703 }
704
705 pub fn wait(&mut self) -> io::Result<ExitStatus> {
706 unsafe {
707 let res = c::WaitForSingleObject(self.handle.as_raw_handle(), c::INFINITE);
708 if res != c::WAIT_OBJECT_0 {
709 return Err(Error::last_os_error());
710 }
711 let mut status = 0;
712 cvt(c::GetExitCodeProcess(self.handle.as_raw_handle(), &mut status))?;
713 Ok(ExitStatus(status))
714 }
715 }
716
717 pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
718 unsafe {
719 match c::WaitForSingleObject(self.handle.as_raw_handle(), 0) {
720 c::WAIT_OBJECT_0 => {}
721 c::WAIT_TIMEOUT => {
722 return Ok(None);
723 }
724 _ => return Err(io::Error::last_os_error()),
725 }
726 let mut status = 0;
727 cvt(c::GetExitCodeProcess(self.handle.as_raw_handle(), &mut status))?;
728 Ok(Some(ExitStatus(status)))
729 }
730 }
731
732 pub fn handle(&self) -> &Handle {
733 &self.handle
734 }
735
736 pub fn into_handle(self) -> Handle {
737 self.handle
738 }
739}
740
741#[derive(PartialEq, Eq, Clone, Copy, Debug, Default)]
742pub struct ExitStatus(u32);
743
744impl ExitStatus {
745 pub fn exit_ok(&self) -> Result<(), ExitStatusError> {
746 match NonZero::<u32>::try_from(self.0) {
747 Ok(failure) => Err(ExitStatusError(failure)),
748 Err(_) => Ok(()),
749 }
750 }
751 pub fn code(&self) -> Option<i32> {
752 Some(self.0 as i32)
753 }
754}
755
756impl From<u32> for ExitStatus {
758 fn from(u: u32) -> ExitStatus {
759 ExitStatus(u)
760 }
761}
762
763impl fmt::Display for ExitStatus {
764 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
765 if self.0 & 0x80000000 != 0 {
771 write!(f, "exit code: {:#x}", self.0)
772 } else {
773 write!(f, "exit code: {}", self.0)
774 }
775 }
776}
777
778#[derive(PartialEq, Eq, Clone, Copy, Debug)]
779pub struct ExitStatusError(NonZero<u32>);
780
781impl Into<ExitStatus> for ExitStatusError {
782 fn into(self) -> ExitStatus {
783 ExitStatus(self.0.into())
784 }
785}
786
787impl ExitStatusError {
788 pub fn code(self) -> Option<NonZero<i32>> {
789 Some((u32::from(self.0) as i32).try_into().unwrap())
790 }
791}
792
793#[derive(PartialEq, Eq, Clone, Copy, Debug)]
794pub struct ExitCode(u32);
795
796impl ExitCode {
797 pub const SUCCESS: ExitCode = ExitCode(EXIT_SUCCESS as _);
798 pub const FAILURE: ExitCode = ExitCode(EXIT_FAILURE as _);
799
800 #[inline]
801 pub fn as_i32(&self) -> i32 {
802 self.0 as i32
803 }
804}
805
806impl From<u8> for ExitCode {
807 fn from(code: u8) -> Self {
808 ExitCode(u32::from(code))
809 }
810}
811
812impl From<u32> for ExitCode {
813 fn from(code: u32) -> Self {
814 ExitCode(u32::from(code))
815 }
816}
817
818fn zeroed_startupinfo() -> c::STARTUPINFOW {
819 c::STARTUPINFOW {
820 cb: 0,
821 lpReserved: ptr::null_mut(),
822 lpDesktop: ptr::null_mut(),
823 lpTitle: ptr::null_mut(),
824 dwX: 0,
825 dwY: 0,
826 dwXSize: 0,
827 dwYSize: 0,
828 dwXCountChars: 0,
829 dwYCountChars: 0,
830 dwFillAttribute: 0,
831 dwFlags: 0,
832 wShowWindow: 0,
833 cbReserved2: 0,
834 lpReserved2: ptr::null_mut(),
835 hStdInput: ptr::null_mut(),
836 hStdOutput: ptr::null_mut(),
837 hStdError: ptr::null_mut(),
838 }
839}
840
841fn zeroed_process_information() -> c::PROCESS_INFORMATION {
842 c::PROCESS_INFORMATION {
843 hProcess: ptr::null_mut(),
844 hThread: ptr::null_mut(),
845 dwProcessId: 0,
846 dwThreadId: 0,
847 }
848}
849
850fn make_command_line(argv0: &OsStr, args: &[Arg], force_quotes: bool) -> io::Result<Vec<u16>> {
853 let mut cmd: Vec<u16> = Vec::new();
856
857 cmd.push(b'"' as u16);
862 cmd.extend(argv0.encode_wide());
863 cmd.push(b'"' as u16);
864
865 for arg in args {
866 cmd.push(' ' as u16);
867 args::append_arg(&mut cmd, arg, force_quotes)?;
868 }
869 Ok(cmd)
870}
871
872fn command_prompt() -> io::Result<Vec<u16>> {
874 let mut system: Vec<u16> =
875 fill_utf16_buf(|buf, size| unsafe { c::GetSystemDirectoryW(buf, size) }, |buf| buf.into())?;
876 system.extend("\\cmd.exe".encode_utf16().chain([0]));
877 Ok(system)
878}
879
880fn make_envp(maybe_env: Option<BTreeMap<EnvKey, OsString>>) -> io::Result<(*mut c_void, Vec<u16>)> {
881 if let Some(env) = maybe_env {
885 let mut blk = Vec::new();
886
887 if env.is_empty() {
890 blk.push(0);
891 }
892
893 for (k, v) in env {
894 ensure_no_nuls(k.os_string)?;
895 blk.extend(k.utf16);
896 blk.push('=' as u16);
897 blk.extend(ensure_no_nuls(v)?.encode_wide());
898 blk.push(0);
899 }
900 blk.push(0);
901 Ok((blk.as_mut_ptr() as *mut c_void, blk))
902 } else {
903 Ok((ptr::null_mut(), Vec::new()))
904 }
905}
906
907fn make_dirp(d: Option<&OsString>) -> io::Result<(*const u16, Vec<u16>)> {
908 match d {
909 Some(dir) => {
910 let mut dir_str: Vec<u16> = ensure_no_nuls(dir)?.encode_wide().chain([0]).collect();
911 let ptr = if dir_str.starts_with(utf16!(r"\\?\UNC")) {
915 let start = r"\\?\UN".len();
917 dir_str[start] = b'\\' as u16;
918 if path::is_absolute_exact(&dir_str[start..]) {
919 dir_str[start..].as_ptr()
920 } else {
921 dir_str[start] = b'C' as u16;
923 dir_str.as_ptr()
924 }
925 } else if dir_str.starts_with(utf16!(r"\\?\")) {
926 let start = r"\\?\".len();
928 if path::is_absolute_exact(&dir_str[start..]) {
929 dir_str[start..].as_ptr()
930 } else {
931 dir_str.as_ptr()
932 }
933 } else {
934 dir_str.as_ptr()
935 };
936 Ok((ptr, dir_str))
937 }
938 None => Ok((ptr::null(), Vec::new())),
939 }
940}
941
942pub struct CommandArgs<'a> {
943 iter: crate::slice::Iter<'a, Arg>,
944}
945
946impl<'a> Iterator for CommandArgs<'a> {
947 type Item = &'a OsStr;
948 fn next(&mut self) -> Option<&'a OsStr> {
949 self.iter.next().map(|arg| match arg {
950 Arg::Regular(s) | Arg::Raw(s) => s.as_ref(),
951 })
952 }
953 fn size_hint(&self) -> (usize, Option<usize>) {
954 self.iter.size_hint()
955 }
956}
957
958impl<'a> ExactSizeIterator for CommandArgs<'a> {
959 fn len(&self) -> usize {
960 self.iter.len()
961 }
962 fn is_empty(&self) -> bool {
963 self.iter.is_empty()
964 }
965}
966
967impl<'a> fmt::Debug for CommandArgs<'a> {
968 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
969 f.debug_list().entries(self.iter.clone()).finish()
970 }
971}