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