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