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