subprocess 1.0.3

Execution and control of child processes and pipelines.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
use std::borrow::Cow;
use std::ffi::{OsStr, OsString};
use std::fs::{File, OpenOptions};
use std::io;
use std::io::ErrorKind;
use std::sync::{Arc, OnceLock};

use crate::exec::Redirection;
#[cfg(windows)]
use crate::process::ExtProcessState;
use crate::process::Process;

pub(crate) use os::OsOptions;
pub use os::make_pipe;

/// A process argument, either regular (quoted on Windows) or raw
/// (passed verbatim).
#[derive(Clone, Debug)]
pub(crate) enum Arg {
    Regular(OsString),
    #[cfg(windows)]
    Raw(OsString),
}

impl Arg {
    /// Return the argument formatted for display in a shell-like command line. Regular
    /// arguments are escaped, while raw arguments are included as-is.
    pub fn display_escaped(&self) -> String {
        match self {
            Arg::Regular(s) => display_escape(&s.to_string_lossy()).into_owned(),
            #[cfg(windows)]
            Arg::Raw(s) => s.to_string_lossy().into_owned(),
        }
    }
}

/// Shell-escape a string for display purposes.
pub(crate) fn display_escape(s: &str) -> Cow<'_, str> {
    fn nice_char(c: char) -> bool {
        match c {
            '-' | '_' | '.' | ',' | '/' => true,
            c if c.is_ascii_alphanumeric() => true,
            _ => false,
        }
    }
    if !s.chars().all(nice_char) {
        Cow::Owned(format!("'{}'", s.replace("'", r#"'\''"#)))
    } else {
        Cow::Borrowed(s)
    }
}

pub(crate) struct SpawnResult {
    pub process: Process,
    pub stdin: Option<File>,
    pub stdout: Option<File>,
    pub stderr: Option<File>,
}

/// Spawn a subprocess.
///
/// This is the internal entry point for creating processes. It sets up stream
/// redirections, forks/creates the process, and returns the parent pipe ends along with a
/// `Process` handle.
#[allow(clippy::too_many_arguments)]
pub(crate) fn spawn(
    argv: Vec<Arg>,
    stdin: Arc<Redirection>,
    stdout: Arc<Redirection>,
    stderr: Arc<Redirection>,
    detached: bool,
    executable: Option<&OsStr>,
    env: Option<&[(OsString, OsString)]>,
    cwd: Option<&OsStr>,
    os_options: OsOptions,
) -> io::Result<SpawnResult> {
    if argv.is_empty() {
        return Err(io::Error::new(
            ErrorKind::InvalidInput,
            "argv must not be empty",
        ));
    }

    let (parent_ends, child_ends) = setup_streams(stdin, stdout, stderr)?;

    let process = os::os_start(argv, child_ends, detached, executable, env, cwd, os_options)?;

    Ok(SpawnResult {
        process,
        stdin: parent_ends.0,
        stdout: parent_ends.1,
        stderr: parent_ends.2,
    })
}

fn child_file(r: &Redirection) -> &File {
    match r {
        Redirection::File(f) => f,
        _ => unreachable!(),
    }
}

// Stream preparation for child processes.
//
// Unix and Windows have fundamentally different spawning models, which is why
// os::prepare_file() has platform-specific implementations:
//
// Unix uses fork()+exec(). Fork duplicates all fds into the child, and CLOEXEC causes
// unwanted ones to close at exec. The child can manipulate its fd table between fork
// and exec -- dup2 installs fds onto 0/1/2 and clears CLOEXEC on the target. So child
// fds need no preparation before fork, and os::prepare_file() is a no-op.
//
// Windows uses CreateProcess(), which only passes handles marked as inheritable to the
// child. There is no between-fork-and-exec window, so os::prepare_file() must call
// set_inheritable(true) before spawning.

/// Translate a single `Redirection` into the child-side fd and (for Pipe) the parent-side
/// fd. Returns `(parent_end, child_end)` where only Pipe produces a parent end and None
/// produces neither.
///
/// Merge is not handled here - the caller checks for Merge before calling this function.
fn prepare_child_stream(
    redir: Arc<Redirection>,
    is_input: bool,
) -> io::Result<(Option<File>, Option<Arc<Redirection>>)> {
    // File is the only variant holding a resource - handle specially to avoid dup() when
    // the Arc is shared.
    if matches!(&*redir, Redirection::File(_)) {
        return match Arc::try_unwrap(redir) {
            Ok(Redirection::File(f)) => Ok((None, Some(os::prepare_file(f)?))),
            Err(arc) => Ok((None, Some(os::prepare_file_shared(arc)?))),
            _ => unreachable!(),
        };
    }
    // Other variants are trivially cheap - just peek and handle.
    match &*redir {
        Redirection::Pipe => {
            let (parent, child) = prepare_pipe(is_input)?;
            Ok((Some(parent), Some(child)))
        }
        Redirection::Null => Ok((None, Some(prepare_null_file(is_input)?))),
        Redirection::None => Ok((None, None)),
        _ => unreachable!(),
    }
}

fn prepare_pipe(parent_writes: bool) -> io::Result<(File, Arc<Redirection>)> {
    let (read, write) = os::make_pipe()?;
    let (parent_end, child_end) = if parent_writes {
        (write, read)
    } else {
        (read, write)
    };
    Ok((parent_end, os::prepare_file(child_end)?))
}

fn prepare_null_file(for_read: bool) -> io::Result<Arc<Redirection>> {
    let file = if for_read {
        OpenOptions::new().read(true).open(os::NULL_DEVICE)?
    } else {
        OpenOptions::new().write(true).open(os::NULL_DEVICE)?
    };
    os::prepare_file(file)
}

// Share a child stream via Arc::clone - zero dup syscalls.
fn reuse_stream(
    dest: &mut Option<Arc<Redirection>>,
    src: &mut Option<Arc<Redirection>>,
    src_id: StandardStream,
) -> io::Result<()> {
    if src.is_none() {
        *src = Some(get_redirection_to_standard_stream(src_id)?);
    }
    *dest = src.clone();
    Ok(())
}

// Set up streams for the child process. Returns (parent_ends, child_ends).
//
// Child ends use Arc<Redirection> (always the File variant internally) so that Merge
// (e.g. 2>&1) can share an fd between stdout and stderr - reuse_stream just does
// Arc::clone.
fn setup_streams(
    stdin: Arc<Redirection>,
    stdout: Arc<Redirection>,
    stderr: Arc<Redirection>,
) -> io::Result<(
    (Option<File>, Option<File>, Option<File>),
    (
        Option<Arc<Redirection>>,
        Option<Arc<Redirection>>,
        Option<Arc<Redirection>>,
    ),
)> {
    #[derive(PartialEq, Eq, Copy, Clone)]
    enum MergeKind {
        ErrToOut, // 2>&1
        OutToErr, // 1>&2
        None,
    }

    if matches!(&*stdin, Redirection::Merge) {
        return Err(io::Error::new(
            ErrorKind::InvalidInput,
            "Redirection::Merge not valid for stdin",
        ));
    }
    let merge = match (
        matches!(&*stdout, Redirection::Merge),
        matches!(&*stderr, Redirection::Merge),
    ) {
        (false, false) => MergeKind::None,
        (false, true) => MergeKind::ErrToOut,
        (true, false) => MergeKind::OutToErr,
        (true, true) => {
            return Err(io::Error::new(
                ErrorKind::InvalidInput,
                "Redirection::Merge not valid for both stdout and stderr",
            ));
        }
    };

    let (parent_stdin, child_stdin) = prepare_child_stream(stdin, true)?;
    let (parent_stdout, mut child_stdout) = if merge == MergeKind::OutToErr {
        (None, None)
    } else {
        prepare_child_stream(stdout, false)?
    };
    let (parent_stderr, mut child_stderr) = if merge == MergeKind::ErrToOut {
        (None, None)
    } else {
        prepare_child_stream(stderr, false)?
    };

    match merge {
        MergeKind::ErrToOut => {
            reuse_stream(&mut child_stderr, &mut child_stdout, StandardStream::Output)?
        }
        MergeKind::OutToErr => {
            reuse_stream(&mut child_stdout, &mut child_stderr, StandardStream::Error)?
        }
        MergeKind::None => (),
    }

    Ok((
        (parent_stdin, parent_stdout, parent_stderr),
        (child_stdin, child_stdout, child_stderr),
    ))
}

#[derive(Debug, Copy, Clone)]
#[allow(dead_code)]
pub(crate) enum StandardStream {
    Input = 0,
    Output = 1,
    Error = 2,
}

fn get_redirection_to_standard_stream(which: StandardStream) -> io::Result<Arc<Redirection>> {
    static STREAMS: [OnceLock<Arc<Redirection>>; 3] =
        [OnceLock::new(), OnceLock::new(), OnceLock::new()];
    let lock = &STREAMS[which as usize];
    if let Some(stream) = lock.get() {
        return Ok(Arc::clone(stream));
    }
    let stream = os::make_redirection_to_standard_stream(which)?;
    Ok(Arc::clone(lock.get_or_init(|| stream)))
}

#[cfg(unix)]
pub(crate) mod os {
    use super::*;

    #[derive(Clone, Default)]
    pub struct OsOptions {
        pub setuid: Option<u32>,
        pub setgid: Option<u32>,
        pub setpgid: Option<u32>,
    }

    impl OsOptions {
        pub fn setpgid_is_set(&self) -> bool {
            self.setpgid.is_some()
        }
        pub fn set_pgid_value(&mut self, pgid: u32) {
            self.setpgid = Some(pgid);
        }
    }

    pub const NULL_DEVICE: &str = "/dev/null";

    use crate::posix;
    use std::collections::HashSet;
    use std::ffi::OsString;
    use std::fs::File;
    use std::io::{self, Read, Write};
    use std::os::fd::{AsRawFd, FromRawFd};

    pub use crate::posix::make_redirection_to_standard_stream;

    /// Read exactly N bytes, or return None on immediate EOF. Similar to
    /// read_exact(), but distinguishes between no read and partial read
    /// (which is treated as error).
    fn read_exact_or_eof<const N: usize>(source: &mut File) -> io::Result<Option<[u8; N]>> {
        let mut buf = [0u8; N];
        let mut total_read = 0;
        while total_read < N {
            let n = source.read(&mut buf[total_read..])?;
            if n == 0 {
                break;
            }
            total_read += n;
        }
        match total_read {
            0 => Ok(None),
            n if n == N => Ok(Some(buf)),
            _ => Err(io::ErrorKind::UnexpectedEof.into()),
        }
    }

    pub(crate) fn os_start(
        argv: Vec<Arg>,
        child_ends: (
            Option<Arc<Redirection>>,
            Option<Arc<Redirection>>,
            Option<Arc<Redirection>>,
        ),
        detached: bool,
        executable: Option<&OsStr>,
        env: Option<&[(OsString, OsString)]>,
        cwd: Option<&OsStr>,
        os_options: OsOptions,
    ) -> io::Result<Process> {
        let argv: Vec<OsString> = argv.into_iter().map(|Arg::Regular(s)| s).collect();
        // Both ends are created with CLOEXEC, so the read end auto-closes in the child on
        // successful exec. The write end is kept open in the child to report exec errors.
        let mut exec_fail_pipe = posix::pipe()?;

        let child_env = env.map(format_env);
        let cmd_to_exec = executable.unwrap_or(&argv[0]);
        let just_exec = posix::prep_exec(cmd_to_exec, &argv, child_env.as_deref())?;
        let do_chdir = cwd.map(posix::prep_chdir).transpose()?;

        let pid;
        unsafe {
            match posix::fork()? {
                Some(child_pid) => {
                    pid = child_pid;
                }
                None => {
                    drop(exec_fail_pipe.0);
                    let result = do_exec(just_exec, child_ends, do_chdir, &os_options);
                    let error_code = match result {
                        Ok(()) => unreachable!(),
                        Err(e) => e.raw_os_error().unwrap_or(-1),
                    } as u32;
                    exec_fail_pipe.1.write_all(&error_code.to_le_bytes()).ok();
                    posix::_exit(127);
                }
            }
        }

        // Close the parent's copies of child-end fds promptly after fork,
        // before blocking on exec_fail_pipe.
        drop(child_ends);

        drop(exec_fail_pipe.1);
        match read_exact_or_eof::<4>(&mut exec_fail_pipe.0)? {
            None => Ok(Process::new(pid, (), detached)),
            Some(error_buf) => {
                let error_code = u32::from_le_bytes(error_buf);
                Err(io::Error::from_raw_os_error(error_code as i32))
            }
        }
    }

    fn format_env(env: &[(OsString, OsString)]) -> Vec<OsString> {
        let mut seen = HashSet::<&OsStr>::new();
        let mut formatted: Vec<_> = env
            .iter()
            .rev()
            .filter(|&(k, _)| seen.insert(k))
            .map(|(k, v)| {
                let mut fmt = k.clone();
                fmt.push("=");
                fmt.push(v);
                fmt
            })
            .collect();
        formatted.reverse();
        formatted
    }

    fn install_child_fd(end: Option<Arc<Redirection>>, target_fd: i32) -> io::Result<()> {
        // Called after fork - use ManuallyDrop to prevent deallocation on
        // early return via ?.
        let mut end = std::mem::ManuallyDrop::new(end);
        if let Some(r) = &*end {
            let fd = child_file(r).as_raw_fd();
            if fd != target_fd {
                posix::dup2(fd, target_fd)?;
            } else {
                // dup2(fd, fd) is a no-op per POSIX and doesn't clear
                // CLOEXEC. Clear it so the fd survives exec.
                set_inheritable(child_file(r), true)?;
            }
        }
        if let Some(end) = end.take() {
            prevent_dealloc(end);
        }
        Ok(())
    }

    // Prevent deallocation of Arc while still closing the underlying resource if
    // necessary. Needed because this runs after fork() - see prep_exec().
    //
    // Note that this never closes system streams returned by
    // get_redirection_to_standard_stream() because it returns "leaked" Arcs which are
    // immortal.
    fn prevent_dealloc(r: Arc<Redirection>) {
        // If Arc<Redirection> we received is the last one, manually close the File
        // inside.
        if Arc::strong_count(&r) == 1
            && let Redirection::File(f) = &*r
        {
            // SAFETY: strong_count == 1 guarantees no other Arc clone will access or
            // close the fd. std::mem::forget() prevents double-close.
            let _ = unsafe { File::from_raw_fd(f.as_raw_fd()) };
        };
        std::mem::forget(r);
    }

    fn do_exec(
        just_exec: impl FnOnce() -> io::Result<()>,
        child_ends: (
            Option<Arc<Redirection>>,
            Option<Arc<Redirection>>,
            Option<Arc<Redirection>>,
        ),
        chdir: Option<impl FnOnce() -> io::Result<()>>,
        os_options: &OsOptions,
    ) -> io::Result<()> {
        // Called after fork - use ManuallyDrop to prevent deallocation on
        // early return via ?.
        let (stdin, stdout, stderr) = child_ends;
        let mut stdin = std::mem::ManuallyDrop::new(stdin);
        let mut stdout = std::mem::ManuallyDrop::new(stdout);
        let mut stderr = std::mem::ManuallyDrop::new(stderr);
        let mut just_exec = std::mem::ManuallyDrop::new(just_exec);

        if let Some(chdir) = chdir {
            chdir()?;
        }

        install_child_fd(stdin.take(), 0)?;
        install_child_fd(stdout.take(), 1)?;
        install_child_fd(stderr.take(), 2)?;
        posix::reset_sigpipe()?;

        if let Some(gid) = os_options.setgid {
            posix::setgid(gid)?;
        }
        if let Some(uid) = os_options.setuid {
            posix::setuid(uid)?;
        }
        if let Some(pgid) = os_options.setpgid {
            posix::setpgid(0, pgid)?;
        }
        // SAFETY: just_exec is taken exactly once and not accessed afterward.
        let just_exec = unsafe { std::mem::ManuallyDrop::take(&mut just_exec) };
        just_exec()?;
        unreachable!();
    }

    pub fn set_inheritable(f: &File, inheritable: bool) -> io::Result<()> {
        let fd = f.as_raw_fd();
        let old = posix::fcntl(fd, posix::F_GETFD, None)?;
        let new = if inheritable {
            old & !posix::FD_CLOEXEC
        } else {
            old | posix::FD_CLOEXEC
        };
        if new != old {
            posix::fcntl(fd, posix::F_SETFD, Some(new))?;
        }
        Ok(())
    }

    pub fn prepare_file(file: File) -> io::Result<Arc<Redirection>> {
        // On Unix, child fds don't need CLOEXEC cleared before fork.  dup2() in the child
        // atomically places them on fd 0/1/2 and clears CLOEXEC on the target.
        Ok(Arc::new(Redirection::File(file)))
    }

    pub fn prepare_file_shared(arc: Arc<Redirection>) -> io::Result<Arc<Redirection>> {
        Ok(arc)
    }

    /// Create a pipe.
    ///
    /// Child processes won't inherit these fds across exec. To pass a pipe end to a
    /// child, dup2() it to a standard fd (which clears CLOEXEC), or call
    /// `set_inheritable(f, true)`.
    pub fn make_pipe() -> io::Result<(File, File)> {
        posix::pipe()
    }
}

#[cfg(windows)]
pub(crate) mod os {
    use super::*;

    #[derive(Clone, Default)]
    pub struct OsOptions {
        pub creation_flags: u32,
    }

    pub const NULL_DEVICE: &str = "nul";

    use std::collections::HashSet;
    use std::env;
    use std::ffi::{OsStr, OsString};
    use std::fs::File;
    use std::io;
    use std::os::windows::ffi::{OsStrExt, OsStringExt};
    use std::os::windows::io::{AsRawHandle, RawHandle};

    use crate::win32;
    pub use crate::win32::make_redirection_to_standard_stream;

    pub(crate) fn os_start(
        argv: Vec<Arg>,
        child_ends: (
            Option<Arc<Redirection>>,
            Option<Arc<Redirection>>,
            Option<Arc<Redirection>>,
        ),
        detached: bool,
        executable: Option<&OsStr>,
        env: Option<&[(OsString, OsString)]>,
        cwd: Option<&OsStr>,
        os_options: OsOptions,
    ) -> io::Result<Process> {
        fn raw(opt: Option<&Arc<Redirection>>) -> Option<RawHandle> {
            opt.map(|r| child_file(r).as_raw_handle())
        }

        let (mut child_stdin, mut child_stdout, mut child_stderr) = child_ends;
        ensure_child_stream(&mut child_stdin, StandardStream::Input)?;
        ensure_child_stream(&mut child_stdout, StandardStream::Output)?;
        ensure_child_stream(&mut child_stderr, StandardStream::Error)?;
        let cmdline = assemble_cmdline(argv)?;
        let env_block = env.map(format_env_block);
        let executable_located = executable.map(|e| locate_in_path(e.to_owned()));
        let (handle, pid) = win32::CreateProcess(
            executable_located.as_ref().map(OsString::as_ref),
            &cmdline,
            env_block.as_deref(),
            cwd,
            true,
            os_options.creation_flags,
            raw(child_stdin.as_ref()),
            raw(child_stdout.as_ref()),
            raw(child_stderr.as_ref()),
            win32::STARTF_USESTDHANDLES,
        )?;
        Ok(Process::new(pid as u32, ExtProcessState(handle), detached))
    }

    fn format_env_block(env: &[(OsString, OsString)]) -> Vec<u16> {
        fn to_uppercase(s: &OsStr) -> OsString {
            OsString::from_wide(
                &s.encode_wide()
                    .map(|c| {
                        if c < 128 {
                            (c as u8).to_ascii_uppercase() as u16
                        } else {
                            c
                        }
                    })
                    .collect::<Vec<_>>(),
            )
        }
        let mut pruned: Vec<_> = {
            let mut seen = HashSet::<OsString>::new();
            env.iter()
                .rev()
                .filter(|&(k, _)| seen.insert(to_uppercase(k)))
                .collect()
        };
        pruned.reverse();
        let mut block = vec![];
        for (k, v) in pruned {
            block.extend(k.encode_wide());
            block.push('=' as u16);
            block.extend(v.encode_wide());
            block.push(0);
        }
        block.push(0);
        block
    }

    fn ensure_child_stream(
        stream: &mut Option<Arc<Redirection>>,
        which: StandardStream,
    ) -> io::Result<()> {
        if stream.is_none() {
            *stream = Some(get_redirection_to_standard_stream(which)?);
        }
        Ok(())
    }

    pub fn set_inheritable(f: &File, inheritable: bool) -> io::Result<()> {
        win32::SetHandleInformation(
            f,
            win32::HANDLE_FLAG_INHERIT,
            if inheritable { 1 } else { 0 },
        )?;
        Ok(())
    }

    pub fn prepare_file(file: File) -> io::Result<Arc<Redirection>> {
        // On Windows, child handles must be marked inheritable for CreateProcess to pass
        // them to the child.
        set_inheritable(&file, true)?;
        Ok(Arc::new(Redirection::File(file)))
    }

    pub fn prepare_file_shared(arc: Arc<Redirection>) -> io::Result<Arc<Redirection>> {
        set_inheritable(child_file(&arc), true)?;
        Ok(arc)
    }

    /// Create a pipe where both ends support overlapped I/O.
    ///
    /// Both handles are created non-inheritable.
    pub fn make_pipe() -> io::Result<(File, File)> {
        win32::make_pipe()
    }

    fn locate_in_path(executable: OsString) -> OsString {
        let Some(path_var) = env::var_os("PATH") else {
            return executable;
        };
        for dir in env::split_paths(&path_var) {
            let candidate = dir
                .join(&executable)
                .with_extension(std::env::consts::EXE_EXTENSION);
            if candidate.exists() {
                return candidate.into_os_string();
            }
        }
        executable
    }

    fn assemble_cmdline(argv: Vec<Arg>) -> io::Result<OsString> {
        let mut cmdline = vec![];
        for (i, arg) in argv.iter().enumerate() {
            if i > 0 {
                cmdline.push(' ' as u16);
            }
            let s = match arg {
                Arg::Regular(s) | Arg::Raw(s) => s,
            };
            if s.encode_wide().any(|c| c == 0) {
                return Err(io::Error::from_raw_os_error(win32::ERROR_BAD_PATHNAME as _));
            }
            match arg {
                Arg::Regular(s) => append_quoted(s, &mut cmdline),
                Arg::Raw(s) => cmdline.extend(s.encode_wide()),
            }
        }
        Ok(OsString::from_wide(&cmdline))
    }

    // Translated from ArgvQuote at
    // https://learn.microsoft.com/en-us/archive/blogs/twistylittlepassagesallalike/everyone-quotes-command-line-arguments-the-wrong-way
    fn append_quoted(arg: &OsStr, cmdline: &mut Vec<u16>) {
        if !arg.is_empty()
            && !arg.encode_wide().any(|c| {
                c == ' ' as u16
                    || c == '\t' as u16
                    || c == '\n' as u16
                    || c == '\x0b' as u16
                    || c == '\"' as u16
            })
        {
            cmdline.extend(arg.encode_wide());
            return;
        }
        cmdline.push('"' as u16);

        let arg: Vec<_> = arg.encode_wide().collect();
        let mut i = 0;
        while i < arg.len() {
            let mut num_backslashes = 0;
            while i < arg.len() && arg[i] == '\\' as u16 {
                i += 1;
                num_backslashes += 1;
            }

            if i == arg.len() {
                for _ in 0..num_backslashes * 2 {
                    cmdline.push('\\' as u16);
                }
                break;
            } else if arg[i] == b'"' as u16 {
                for _ in 0..num_backslashes * 2 + 1 {
                    cmdline.push('\\' as u16);
                }
                cmdline.push(arg[i]);
            } else {
                for _ in 0..num_backslashes {
                    cmdline.push('\\' as u16);
                }
                cmdline.push(arg[i]);
            }
            i += 1;
        }
        cmdline.push('"' as u16);
    }
}