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()).map_err(
644 |e| {
645 let stream = match stdio_id {
650 c::STD_INPUT_HANDLE => "stdin".to_string(),
651 c::STD_OUTPUT_HANDLE => "stdout".to_string(),
652 c::STD_ERROR_HANDLE => "stderr".to_string(),
653 id => format!("stdio handle {id}"),
654 };
655 Error::new(
656 e.kind(),
657 format!("failed to open NUL device for child {stream}: {e}"),
658 )
659 },
660 )
661 }
662 }
663 }
664}
665
666impl From<ChildPipe> for Stdio {
667 fn from(pipe: ChildPipe) -> Stdio {
668 Stdio::Pipe(pipe)
669 }
670}
671
672impl From<Handle> for Stdio {
673 fn from(pipe: Handle) -> Stdio {
674 Stdio::Handle(pipe)
675 }
676}
677
678impl From<File> for Stdio {
679 fn from(file: File) -> Stdio {
680 Stdio::Handle(file.into_inner())
681 }
682}
683
684impl From<io::Stdout> for Stdio {
685 fn from(_: io::Stdout) -> Stdio {
686 Stdio::InheritSpecific { from_stdio_id: c::STD_OUTPUT_HANDLE }
687 }
688}
689
690impl From<io::Stderr> for Stdio {
691 fn from(_: io::Stderr) -> Stdio {
692 Stdio::InheritSpecific { from_stdio_id: c::STD_ERROR_HANDLE }
693 }
694}
695
696pub struct Process {
706 handle: Handle,
707 main_thread_handle: Handle,
708}
709
710impl Process {
711 pub fn kill(&mut self) -> io::Result<()> {
712 let result = unsafe { c::TerminateProcess(self.handle.as_raw_handle(), 1) };
713 if result == c::FALSE {
714 let error = api::get_last_error();
715 if error != WinError::ACCESS_DENIED || self.try_wait().is_err() {
719 return Err(crate::io::Error::from_raw_os_error(error.code as i32));
720 }
721 }
722 Ok(())
723 }
724
725 pub fn id(&self) -> u32 {
726 unsafe { c::GetProcessId(self.handle.as_raw_handle()) }
727 }
728
729 pub fn main_thread_handle(&self) -> BorrowedHandle<'_> {
730 self.main_thread_handle.as_handle()
731 }
732
733 pub fn wait(&mut self) -> io::Result<ExitStatus> {
734 unsafe {
735 let res = c::WaitForSingleObject(self.handle.as_raw_handle(), c::INFINITE);
736 if res != c::WAIT_OBJECT_0 {
737 return Err(Error::last_os_error());
738 }
739 let mut status = 0;
740 cvt(c::GetExitCodeProcess(self.handle.as_raw_handle(), &mut status))?;
741 Ok(ExitStatus(status))
742 }
743 }
744
745 pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
746 unsafe {
747 match c::WaitForSingleObject(self.handle.as_raw_handle(), 0) {
748 c::WAIT_OBJECT_0 => {}
749 c::WAIT_TIMEOUT => {
750 return Ok(None);
751 }
752 _ => return Err(io::Error::last_os_error()),
753 }
754 let mut status = 0;
755 cvt(c::GetExitCodeProcess(self.handle.as_raw_handle(), &mut status))?;
756 Ok(Some(ExitStatus(status)))
757 }
758 }
759
760 pub fn handle(&self) -> &Handle {
761 &self.handle
762 }
763
764 pub fn into_handle(self) -> Handle {
765 self.handle
766 }
767}
768
769#[derive(PartialEq, Eq, Clone, Copy, Debug, Default)]
770pub struct ExitStatus(u32);
771
772impl ExitStatus {
773 pub fn exit_ok(&self) -> Result<(), ExitStatusError> {
774 match NonZero::<u32>::try_from(self.0) {
775 Ok(failure) => Err(ExitStatusError(failure)),
776 Err(_) => Ok(()),
777 }
778 }
779 pub fn code(&self) -> Option<i32> {
780 Some(self.0 as i32)
781 }
782}
783
784impl From<u32> for ExitStatus {
786 fn from(u: u32) -> ExitStatus {
787 ExitStatus(u)
788 }
789}
790
791impl fmt::Display for ExitStatus {
792 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
793 if self.0 & 0x80000000 != 0 {
799 write!(f, "exit code: {:#x}", self.0)
800 } else {
801 write!(f, "exit code: {}", self.0)
802 }
803 }
804}
805
806#[derive(PartialEq, Eq, Clone, Copy, Debug)]
807pub struct ExitStatusError(NonZero<u32>);
808
809impl Into<ExitStatus> for ExitStatusError {
810 fn into(self) -> ExitStatus {
811 ExitStatus(self.0.into())
812 }
813}
814
815impl ExitStatusError {
816 pub fn code(self) -> Option<NonZero<i32>> {
817 Some((u32::from(self.0) as i32).try_into().unwrap())
818 }
819}
820
821#[derive(PartialEq, Eq, Clone, Copy, Debug)]
822pub struct ExitCode(u32);
823
824impl ExitCode {
825 pub const SUCCESS: ExitCode = ExitCode(EXIT_SUCCESS as _);
826 pub const FAILURE: ExitCode = ExitCode(EXIT_FAILURE as _);
827
828 #[inline]
829 pub fn as_i32(&self) -> i32 {
830 self.0 as i32
831 }
832}
833
834impl From<u8> for ExitCode {
835 fn from(code: u8) -> Self {
836 ExitCode(u32::from(code))
837 }
838}
839
840impl From<u32> for ExitCode {
841 fn from(code: u32) -> Self {
842 ExitCode(code)
843 }
844}
845
846fn zeroed_startupinfo() -> c::STARTUPINFOW {
847 c::STARTUPINFOW {
848 cb: 0,
849 lpReserved: ptr::null_mut(),
850 lpDesktop: ptr::null_mut(),
851 lpTitle: ptr::null_mut(),
852 dwX: 0,
853 dwY: 0,
854 dwXSize: 0,
855 dwYSize: 0,
856 dwXCountChars: 0,
857 dwYCountChars: 0,
858 dwFillAttribute: 0,
859 dwFlags: 0,
860 wShowWindow: 0,
861 cbReserved2: 0,
862 lpReserved2: ptr::null_mut(),
863 hStdInput: ptr::null_mut(),
864 hStdOutput: ptr::null_mut(),
865 hStdError: ptr::null_mut(),
866 }
867}
868
869fn zeroed_process_information() -> c::PROCESS_INFORMATION {
870 c::PROCESS_INFORMATION {
871 hProcess: ptr::null_mut(),
872 hThread: ptr::null_mut(),
873 dwProcessId: 0,
874 dwThreadId: 0,
875 }
876}
877
878fn make_command_line(argv0: &OsStr, args: &[Arg], force_quotes: bool) -> io::Result<Vec<u16>> {
881 let mut cmd: Vec<u16> = Vec::new();
884
885 cmd.push(b'"' as u16);
890 cmd.extend(argv0.encode_wide());
891 cmd.push(b'"' as u16);
892
893 for arg in args {
894 cmd.push(' ' as u16);
895 args::append_arg(&mut cmd, arg, force_quotes)?;
896 }
897 Ok(cmd)
898}
899
900fn command_prompt() -> io::Result<Vec<u16>> {
902 let mut system: Vec<u16> =
903 fill_utf16_buf(|buf, size| unsafe { c::GetSystemDirectoryW(buf, size) }, |buf| buf.into())?;
904 system.extend("\\cmd.exe".encode_utf16().chain([0]));
905 Ok(system)
906}
907
908fn make_envp(maybe_env: Option<BTreeMap<EnvKey, OsString>>) -> io::Result<(*mut c_void, Vec<u16>)> {
909 if let Some(env) = maybe_env {
913 let mut blk = Vec::new();
914
915 if env.is_empty() {
918 blk.push(0);
919 }
920
921 for (k, v) in env {
922 ensure_no_nuls(k.os_string)?;
923 blk.extend(k.utf16);
924 blk.push('=' as u16);
925 blk.extend(ensure_no_nuls(v)?.encode_wide());
926 blk.push(0);
927 }
928 blk.push(0);
929 Ok((blk.as_mut_ptr() as *mut c_void, blk))
930 } else {
931 Ok((ptr::null_mut(), Vec::new()))
932 }
933}
934
935fn make_dirp(d: Option<&OsString>) -> io::Result<(*const u16, Vec<u16>)> {
936 match d {
937 Some(dir) => {
938 let mut dir_str: Vec<u16> = ensure_no_nuls(dir)?.encode_wide().chain([0]).collect();
939 let ptr = if dir_str.starts_with(utf16!(r"\\?\UNC")) {
943 let start = r"\\?\UN".len();
945 dir_str[start] = b'\\' as u16;
946 if path::is_absolute_exact(&dir_str[start..]) {
947 dir_str[start..].as_ptr()
948 } else {
949 dir_str[start] = b'C' as u16;
951 dir_str.as_ptr()
952 }
953 } else if dir_str.starts_with(utf16!(r"\\?\")) {
954 let start = r"\\?\".len();
956 if path::is_absolute_exact(&dir_str[start..]) {
957 dir_str[start..].as_ptr()
958 } else {
959 dir_str.as_ptr()
960 }
961 } else {
962 dir_str.as_ptr()
963 };
964 Ok((ptr, dir_str))
965 }
966 None => Ok((ptr::null(), Vec::new())),
967 }
968}
969
970pub struct CommandArgs<'a> {
971 iter: crate::slice::Iter<'a, Arg>,
972}
973
974impl<'a> Iterator for CommandArgs<'a> {
975 type Item = &'a OsStr;
976 fn next(&mut self) -> Option<&'a OsStr> {
977 self.iter.next().map(|arg| match arg {
978 Arg::Regular(s) | Arg::Raw(s) => s.as_ref(),
979 })
980 }
981 fn size_hint(&self) -> (usize, Option<usize>) {
982 self.iter.size_hint()
983 }
984}
985
986impl<'a> ExactSizeIterator for CommandArgs<'a> {
987 fn len(&self) -> usize {
988 self.iter.len()
989 }
990 fn is_empty(&self) -> bool {
991 self.iter.is_empty()
992 }
993}
994
995impl<'a> fmt::Debug for CommandArgs<'a> {
996 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
997 f.debug_list().entries(self.iter.clone()).finish()
998 }
999}
1000
1001pub fn getpid() -> u32 {
1002 unsafe { c::GetCurrentProcessId() }
1003}