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_env_clear(&self) -> bool {
254 self.env.does_clear()
255 }
256
257 pub fn get_current_dir(&self) -> Option<&Path> {
258 self.cwd.as_ref().map(Path::new)
259 }
260
261 pub fn inherit_handles(&mut self, inherit_handles: bool) {
262 self.inherit_handles = inherit_handles;
263 }
264
265 pub fn spawn(
266 &mut self,
267 default: Stdio,
268 needs_stdin: bool,
269 ) -> io::Result<(Process, StdioPipes)> {
270 self.spawn_with_attributes(default, needs_stdin, None)
271 }
272
273 pub fn spawn_with_attributes(
274 &mut self,
275 default: Stdio,
276 needs_stdin: bool,
277 proc_thread_attribute_list: Option<&ProcThreadAttributeList<'_>>,
278 ) -> io::Result<(Process, StdioPipes)> {
279 let env_saw_path = self.env.have_changed_path();
280 let maybe_env = self.env.capture_if_changed();
281
282 let child_paths = if env_saw_path && let Some(env) = maybe_env.as_ref() {
283 env.get(&EnvKey::new("PATH")).map(|s| s.as_os_str())
284 } else {
285 None
286 };
287 let program = resolve_exe(&self.program, || env::var_os("PATH"), child_paths)?;
288 let has_bat_extension = |program: &[u16]| {
289 matches!(
290 program.len().checked_sub(4).and_then(|i| program.get(i..)),
292 Some([46, 98 | 66, 97 | 65, 116 | 84] | [46, 99 | 67, 109 | 77, 100 | 68])
293 )
294 };
295 let is_batch_file = if path::is_verbatim(&program) {
296 has_bat_extension(&program[..program.len() - 1])
297 } else {
298 fill_utf16_buf(
299 |buffer, size| unsafe {
300 c::GetFullPathNameW(program.as_ptr(), size, buffer, ptr::null_mut())
302 },
303 |program| has_bat_extension(program),
304 )?
305 };
306 let (program, mut cmd_str) = if is_batch_file {
307 (
308 command_prompt()?,
309 args::make_bat_command_line(&program, &self.args, self.force_quotes_enabled)?,
310 )
311 } else {
312 let cmd_str = make_command_line(&self.program, &self.args, self.force_quotes_enabled)?;
313 (program, cmd_str)
314 };
315 cmd_str.push(0); let mut flags = self.flags | c::CREATE_UNICODE_ENVIRONMENT;
319 if self.detach {
320 flags |= c::DETACHED_PROCESS | c::CREATE_NEW_PROCESS_GROUP;
321 }
322
323 let inherit_handles = self.inherit_handles as c::BOOL;
324 let (envp, _data) = make_envp(maybe_env)?;
325 let (dirp, _data) = make_dirp(self.cwd.as_ref())?;
326 let mut pi = zeroed_process_information();
327
328 static CREATE_PROCESS_LOCK: Mutex<()> = Mutex::new(());
338
339 let _guard = CREATE_PROCESS_LOCK.lock();
340
341 let mut pipes = StdioPipes { stdin: None, stdout: None, stderr: None };
342 let null = Stdio::Null;
343 let default_stdin = if needs_stdin { &default } else { &null };
344 let stdin = self.stdin.as_ref().unwrap_or(default_stdin);
345 let stdout = self.stdout.as_ref().unwrap_or(&default);
346 let stderr = self.stderr.as_ref().unwrap_or(&default);
347 let stdin = stdin.to_handle(c::STD_INPUT_HANDLE, &mut pipes.stdin)?;
348 let stdout = stdout.to_handle(c::STD_OUTPUT_HANDLE, &mut pipes.stdout)?;
349 let stderr = stderr.to_handle(c::STD_ERROR_HANDLE, &mut pipes.stderr)?;
350
351 let mut si = zeroed_startupinfo();
352
353 let is_set = |stdio: &Handle| !stdio.as_raw_handle().is_null();
358 if is_set(&stderr) || is_set(&stdout) || is_set(&stdin) {
359 si.dwFlags |= c::STARTF_USESTDHANDLES;
360 si.hStdInput = stdin.as_raw_handle();
361 si.hStdOutput = stdout.as_raw_handle();
362 si.hStdError = stderr.as_raw_handle();
363 }
364
365 if let Some(cmd_show) = self.show_window {
366 si.dwFlags |= c::STARTF_USESHOWWINDOW;
367 si.wShowWindow = cmd_show;
368 }
369
370 if self.startupinfo_fullscreen {
371 si.dwFlags |= c::STARTF_RUNFULLSCREEN;
372 }
373
374 if self.startupinfo_untrusted_source {
375 si.dwFlags |= c::STARTF_UNTRUSTEDSOURCE;
376 }
377
378 match self.startupinfo_force_feedback {
379 Some(true) => {
380 si.dwFlags |= c::STARTF_FORCEONFEEDBACK;
381 }
382 Some(false) => {
383 si.dwFlags |= c::STARTF_FORCEOFFFEEDBACK;
384 }
385 None => {}
386 }
387
388 let si_ptr: *mut c::STARTUPINFOW;
389
390 let mut si_ex;
391
392 if let Some(proc_thread_attribute_list) = proc_thread_attribute_list {
393 si.cb = size_of::<c::STARTUPINFOEXW>() as u32;
394 flags |= c::EXTENDED_STARTUPINFO_PRESENT;
395
396 si_ex = c::STARTUPINFOEXW {
397 StartupInfo: si,
398 lpAttributeList: proc_thread_attribute_list.as_ptr().cast::<c_void>().cast_mut(),
402 };
403 si_ptr = (&raw mut si_ex) as _;
404 } else {
405 si.cb = size_of::<c::STARTUPINFOW>() as u32;
406 si_ptr = (&raw mut si) as _;
407 }
408
409 unsafe {
410 cvt(c::CreateProcessW(
411 program.as_ptr(),
412 cmd_str.as_mut_ptr(),
413 ptr::null_mut(),
414 ptr::null_mut(),
415 inherit_handles,
416 flags,
417 envp,
418 dirp,
419 si_ptr,
420 &mut pi,
421 ))
422 }?;
423
424 unsafe {
425 Ok((
426 Process {
427 handle: Handle::from_raw_handle(pi.hProcess),
428 main_thread_handle: Handle::from_raw_handle(pi.hThread),
429 },
430 pipes,
431 ))
432 }
433 }
434}
435
436impl fmt::Debug for Command {
437 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
438 self.program.fmt(f)?;
439 for arg in &self.args {
440 f.write_str(" ")?;
441 match arg {
442 Arg::Regular(s) => s.fmt(f),
443 Arg::Raw(s) => f.write_str(&s.to_string_lossy()),
444 }?;
445 }
446 Ok(())
447 }
448}
449
450fn resolve_exe<'a>(
463 exe_path: &'a OsStr,
464 parent_paths: impl FnOnce() -> Option<OsString>,
465 child_paths: Option<&OsStr>,
466) -> io::Result<Vec<u16>> {
467 if exe_path.is_empty() || path::has_trailing_slash(exe_path) {
469 return Err(io::const_error!(io::ErrorKind::InvalidInput, "program path has no file name"));
470 }
471 let has_exe_suffix = if exe_path.len() >= EXE_SUFFIX.len() {
474 exe_path.as_encoded_bytes()[exe_path.len() - EXE_SUFFIX.len()..]
475 .eq_ignore_ascii_case(EXE_SUFFIX.as_bytes())
476 } else {
477 false
478 };
479
480 if !path::is_file_name(exe_path) {
482 if has_exe_suffix {
483 return args::to_user_path(Path::new(exe_path));
486 }
487 let mut path = PathBuf::from(exe_path);
488
489 path = path::append_suffix(path, EXE_SUFFIX.as_ref());
491 if let Some(path) = program_exists(&path) {
492 return Ok(path);
493 } else {
494 path.set_extension("");
497 return args::to_user_path(&path);
498 }
499 } else {
500 ensure_no_nuls(exe_path)?;
501 let has_extension = exe_path.as_encoded_bytes().contains(&b'.');
505
506 let result = search_paths(parent_paths, child_paths, |mut path| {
508 path.push(exe_path);
509 if !has_extension {
510 path.set_extension(EXE_EXTENSION);
511 }
512 program_exists(&path)
513 });
514 if let Some(path) = result {
515 return Ok(path);
516 }
517 }
518 Err(io::const_error!(io::ErrorKind::NotFound, "program not found"))
520}
521
522fn search_paths<Paths, Exists>(
525 parent_paths: Paths,
526 child_paths: Option<&OsStr>,
527 mut exists: Exists,
528) -> Option<Vec<u16>>
529where
530 Paths: FnOnce() -> Option<OsString>,
531 Exists: FnMut(PathBuf) -> Option<Vec<u16>>,
532{
533 if let Some(paths) = child_paths {
536 for path in env::split_paths(paths).filter(|p| !p.as_os_str().is_empty()) {
537 if let Some(path) = exists(path) {
538 return Some(path);
539 }
540 }
541 }
542
543 if let Ok(mut app_path) = env::current_exe() {
545 app_path.pop();
546 if let Some(path) = exists(app_path) {
547 return Some(path);
548 }
549 }
550
551 unsafe {
554 if let Ok(Some(path)) = fill_utf16_buf(
555 |buf, size| c::GetSystemDirectoryW(buf, size),
556 |buf| exists(PathBuf::from(OsString::from_wide(buf))),
557 ) {
558 return Some(path);
559 }
560 #[cfg(not(target_vendor = "uwp"))]
561 {
562 if let Ok(Some(path)) = fill_utf16_buf(
563 |buf, size| c::GetWindowsDirectoryW(buf, size),
564 |buf| exists(PathBuf::from(OsString::from_wide(buf))),
565 ) {
566 return Some(path);
567 }
568 }
569 }
570
571 if let Some(parent_paths) = parent_paths() {
573 for path in env::split_paths(&parent_paths).filter(|p| !p.as_os_str().is_empty()) {
574 if let Some(path) = exists(path) {
575 return Some(path);
576 }
577 }
578 }
579 None
580}
581
582fn program_exists(path: &Path) -> Option<Vec<u16>> {
584 unsafe {
585 let path = args::to_user_path(path).ok()?;
586 if c::GetFileAttributesW(path.as_ptr()) == c::INVALID_FILE_ATTRIBUTES {
591 None
592 } else {
593 Some(path)
594 }
595 }
596}
597
598impl Stdio {
599 fn to_handle(&self, stdio_id: u32, pipe: &mut Option<AnonPipe>) -> io::Result<Handle> {
600 let use_stdio_id = |stdio_id| match stdio::get_handle(stdio_id) {
601 Ok(io) => unsafe {
602 let io = Handle::from_raw_handle(io);
603 let ret = io.duplicate(0, true, c::DUPLICATE_SAME_ACCESS);
604 let _ = io.into_raw_handle(); ret
606 },
607 Err(..) => unsafe { Ok(Handle::from_raw_handle(ptr::null_mut())) },
609 };
610 match *self {
611 Stdio::Inherit => use_stdio_id(stdio_id),
612 Stdio::InheritSpecific { from_stdio_id } => use_stdio_id(from_stdio_id),
613
614 Stdio::MakePipe => {
615 let ours_readable = stdio_id != c::STD_INPUT_HANDLE;
616 let pipes = pipe::anon_pipe(ours_readable, true)?;
617 *pipe = Some(pipes.ours);
618 Ok(pipes.theirs.into_handle())
619 }
620
621 Stdio::Pipe(ref source) => {
622 let ours_readable = stdio_id != c::STD_INPUT_HANDLE;
623 pipe::spawn_pipe_relay(source, ours_readable, true).map(AnonPipe::into_handle)
624 }
625
626 Stdio::Handle(ref handle) => handle.duplicate(0, true, c::DUPLICATE_SAME_ACCESS),
627
628 Stdio::Null => {
632 let mut opts = OpenOptions::new();
633 opts.read(stdio_id == c::STD_INPUT_HANDLE);
634 opts.write(stdio_id != c::STD_INPUT_HANDLE);
635 opts.inherit_handle(true);
636 File::open(Path::new(r"\\.\NUL"), &opts).map(|file| file.into_inner())
637 }
638 }
639 }
640}
641
642impl From<AnonPipe> for Stdio {
643 fn from(pipe: AnonPipe) -> Stdio {
644 Stdio::Pipe(pipe)
645 }
646}
647
648impl From<Handle> for Stdio {
649 fn from(pipe: Handle) -> Stdio {
650 Stdio::Handle(pipe)
651 }
652}
653
654impl From<File> for Stdio {
655 fn from(file: File) -> Stdio {
656 Stdio::Handle(file.into_inner())
657 }
658}
659
660impl From<io::Stdout> for Stdio {
661 fn from(_: io::Stdout) -> Stdio {
662 Stdio::InheritSpecific { from_stdio_id: c::STD_OUTPUT_HANDLE }
663 }
664}
665
666impl From<io::Stderr> for Stdio {
667 fn from(_: io::Stderr) -> Stdio {
668 Stdio::InheritSpecific { from_stdio_id: c::STD_ERROR_HANDLE }
669 }
670}
671
672pub struct Process {
682 handle: Handle,
683 main_thread_handle: Handle,
684}
685
686impl Process {
687 pub fn kill(&mut self) -> io::Result<()> {
688 let result = unsafe { c::TerminateProcess(self.handle.as_raw_handle(), 1) };
689 if result == c::FALSE {
690 let error = api::get_last_error();
691 if error != WinError::ACCESS_DENIED || self.try_wait().is_err() {
695 return Err(crate::io::Error::from_raw_os_error(error.code as i32));
696 }
697 }
698 Ok(())
699 }
700
701 pub fn id(&self) -> u32 {
702 unsafe { c::GetProcessId(self.handle.as_raw_handle()) }
703 }
704
705 pub fn main_thread_handle(&self) -> BorrowedHandle<'_> {
706 self.main_thread_handle.as_handle()
707 }
708
709 pub fn wait(&mut self) -> io::Result<ExitStatus> {
710 unsafe {
711 let res = c::WaitForSingleObject(self.handle.as_raw_handle(), c::INFINITE);
712 if res != c::WAIT_OBJECT_0 {
713 return Err(Error::last_os_error());
714 }
715 let mut status = 0;
716 cvt(c::GetExitCodeProcess(self.handle.as_raw_handle(), &mut status))?;
717 Ok(ExitStatus(status))
718 }
719 }
720
721 pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
722 unsafe {
723 match c::WaitForSingleObject(self.handle.as_raw_handle(), 0) {
724 c::WAIT_OBJECT_0 => {}
725 c::WAIT_TIMEOUT => {
726 return Ok(None);
727 }
728 _ => return Err(io::Error::last_os_error()),
729 }
730 let mut status = 0;
731 cvt(c::GetExitCodeProcess(self.handle.as_raw_handle(), &mut status))?;
732 Ok(Some(ExitStatus(status)))
733 }
734 }
735
736 pub fn handle(&self) -> &Handle {
737 &self.handle
738 }
739
740 pub fn into_handle(self) -> Handle {
741 self.handle
742 }
743}
744
745#[derive(PartialEq, Eq, Clone, Copy, Debug, Default)]
746pub struct ExitStatus(u32);
747
748impl ExitStatus {
749 pub fn exit_ok(&self) -> Result<(), ExitStatusError> {
750 match NonZero::<u32>::try_from(self.0) {
751 Ok(failure) => Err(ExitStatusError(failure)),
752 Err(_) => Ok(()),
753 }
754 }
755 pub fn code(&self) -> Option<i32> {
756 Some(self.0 as i32)
757 }
758}
759
760impl From<u32> for ExitStatus {
762 fn from(u: u32) -> ExitStatus {
763 ExitStatus(u)
764 }
765}
766
767impl fmt::Display for ExitStatus {
768 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
769 if self.0 & 0x80000000 != 0 {
775 write!(f, "exit code: {:#x}", self.0)
776 } else {
777 write!(f, "exit code: {}", self.0)
778 }
779 }
780}
781
782#[derive(PartialEq, Eq, Clone, Copy, Debug)]
783pub struct ExitStatusError(NonZero<u32>);
784
785impl Into<ExitStatus> for ExitStatusError {
786 fn into(self) -> ExitStatus {
787 ExitStatus(self.0.into())
788 }
789}
790
791impl ExitStatusError {
792 pub fn code(self) -> Option<NonZero<i32>> {
793 Some((u32::from(self.0) as i32).try_into().unwrap())
794 }
795}
796
797#[derive(PartialEq, Eq, Clone, Copy, Debug)]
798pub struct ExitCode(u32);
799
800impl ExitCode {
801 pub const SUCCESS: ExitCode = ExitCode(EXIT_SUCCESS as _);
802 pub const FAILURE: ExitCode = ExitCode(EXIT_FAILURE as _);
803
804 #[inline]
805 pub fn as_i32(&self) -> i32 {
806 self.0 as i32
807 }
808}
809
810impl From<u8> for ExitCode {
811 fn from(code: u8) -> Self {
812 ExitCode(u32::from(code))
813 }
814}
815
816impl From<u32> for ExitCode {
817 fn from(code: u32) -> Self {
818 ExitCode(u32::from(code))
819 }
820}
821
822fn zeroed_startupinfo() -> c::STARTUPINFOW {
823 c::STARTUPINFOW {
824 cb: 0,
825 lpReserved: ptr::null_mut(),
826 lpDesktop: ptr::null_mut(),
827 lpTitle: ptr::null_mut(),
828 dwX: 0,
829 dwY: 0,
830 dwXSize: 0,
831 dwYSize: 0,
832 dwXCountChars: 0,
833 dwYCountChars: 0,
834 dwFillAttribute: 0,
835 dwFlags: 0,
836 wShowWindow: 0,
837 cbReserved2: 0,
838 lpReserved2: ptr::null_mut(),
839 hStdInput: ptr::null_mut(),
840 hStdOutput: ptr::null_mut(),
841 hStdError: ptr::null_mut(),
842 }
843}
844
845fn zeroed_process_information() -> c::PROCESS_INFORMATION {
846 c::PROCESS_INFORMATION {
847 hProcess: ptr::null_mut(),
848 hThread: ptr::null_mut(),
849 dwProcessId: 0,
850 dwThreadId: 0,
851 }
852}
853
854fn make_command_line(argv0: &OsStr, args: &[Arg], force_quotes: bool) -> io::Result<Vec<u16>> {
857 let mut cmd: Vec<u16> = Vec::new();
860
861 cmd.push(b'"' as u16);
866 cmd.extend(argv0.encode_wide());
867 cmd.push(b'"' as u16);
868
869 for arg in args {
870 cmd.push(' ' as u16);
871 args::append_arg(&mut cmd, arg, force_quotes)?;
872 }
873 Ok(cmd)
874}
875
876fn command_prompt() -> io::Result<Vec<u16>> {
878 let mut system: Vec<u16> =
879 fill_utf16_buf(|buf, size| unsafe { c::GetSystemDirectoryW(buf, size) }, |buf| buf.into())?;
880 system.extend("\\cmd.exe".encode_utf16().chain([0]));
881 Ok(system)
882}
883
884fn make_envp(maybe_env: Option<BTreeMap<EnvKey, OsString>>) -> io::Result<(*mut c_void, Vec<u16>)> {
885 if let Some(env) = maybe_env {
889 let mut blk = Vec::new();
890
891 if env.is_empty() {
894 blk.push(0);
895 }
896
897 for (k, v) in env {
898 ensure_no_nuls(k.os_string)?;
899 blk.extend(k.utf16);
900 blk.push('=' as u16);
901 blk.extend(ensure_no_nuls(v)?.encode_wide());
902 blk.push(0);
903 }
904 blk.push(0);
905 Ok((blk.as_mut_ptr() as *mut c_void, blk))
906 } else {
907 Ok((ptr::null_mut(), Vec::new()))
908 }
909}
910
911fn make_dirp(d: Option<&OsString>) -> io::Result<(*const u16, Vec<u16>)> {
912 match d {
913 Some(dir) => {
914 let mut dir_str: Vec<u16> = ensure_no_nuls(dir)?.encode_wide().chain([0]).collect();
915 let ptr = if dir_str.starts_with(utf16!(r"\\?\UNC")) {
919 let start = r"\\?\UN".len();
921 dir_str[start] = b'\\' as u16;
922 if path::is_absolute_exact(&dir_str[start..]) {
923 dir_str[start..].as_ptr()
924 } else {
925 dir_str[start] = b'C' as u16;
927 dir_str.as_ptr()
928 }
929 } else if dir_str.starts_with(utf16!(r"\\?\")) {
930 let start = r"\\?\".len();
932 if path::is_absolute_exact(&dir_str[start..]) {
933 dir_str[start..].as_ptr()
934 } else {
935 dir_str.as_ptr()
936 }
937 } else {
938 dir_str.as_ptr()
939 };
940 Ok((ptr, dir_str))
941 }
942 None => Ok((ptr::null(), Vec::new())),
943 }
944}
945
946pub struct CommandArgs<'a> {
947 iter: crate::slice::Iter<'a, Arg>,
948}
949
950impl<'a> Iterator for CommandArgs<'a> {
951 type Item = &'a OsStr;
952 fn next(&mut self) -> Option<&'a OsStr> {
953 self.iter.next().map(|arg| match arg {
954 Arg::Regular(s) | Arg::Raw(s) => s.as_ref(),
955 })
956 }
957 fn size_hint(&self) -> (usize, Option<usize>) {
958 self.iter.size_hint()
959 }
960}
961
962impl<'a> ExactSizeIterator for CommandArgs<'a> {
963 fn len(&self) -> usize {
964 self.iter.len()
965 }
966 fn is_empty(&self) -> bool {
967 self.iter.is_empty()
968 }
969}
970
971impl<'a> fmt::Debug for CommandArgs<'a> {
972 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
973 f.debug_list().entries(self.iter.clone()).finish()
974 }
975}