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