subprocess 1.1.0

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
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
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(crate) use os::env_keys_cmp;
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>>)> {
    match &*redir {
        Redirection::File(_) => Ok((None, Some(os::prepare_file(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)),
        Redirection::Merge => unreachable!(),
    }
}

fn wrap_file(file: File) -> Arc<Redirection> {
    Arc::new(Redirection::File(file))
}

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(wrap_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(wrap_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(Default)]
    pub struct OsOptions {
        pub setuid: Option<u32>,
        pub setgid: Option<u32>,
        pub setpgid: Option<u32>,
        pub pre_exec_fns: Vec<Box<dyn FnMut() -> io::Result<()> + Send + Sync>>,
    }

    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";

    /// Compares two env var names under the platform's env semantics. Unix env
    /// var names are case-sensitive, so this is byte ordering.
    pub(crate) fn env_keys_cmp(a: &OsStr, b: &OsStr) -> std::cmp::Ordering {
        a.cmp(b)
    }

    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, RawFd};

    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
    }

    // Install all three child-end fds onto stdin/stdout/stderr in fixed
    // [0, 1, 2] order. Pre-pass: for any source fd that another stream's
    // dup2 would clobber, F_DUPFD_CLOEXEC it to a fresh fd >= 3. Cycles
    // (stdout source = 2, stderr source = 1, etc.) fall out for free:
    // every node in a cycle would be overwritten, so every node gets duped.
    //
    // The fixed install order is correct because, after the pre-pass,
    // every slot i with source S satisfies one of:
    //   - S >= 3 (no slot's dup2 lands on S; targets are 0..=2 only), or
    //   - S == i (slot i does no dup2; the question doesn't arise), or
    //   - slots[S] does no dup2 either: it is None, or its source == S
    //     (so fd S is untouched by the time slot i reads it).
    // The will_be_overwritten predicate below is the precise negation of these.
    //
    // `slots` is borrowed (not mutated): the source fds remain valid for the
    // duration of this call because the caller keeps the underlying Arcs alive
    // (in a ManuallyDrop, post-fork).
    fn redirect_streams(slots: &[Option<Arc<Redirection>>; 3]) -> io::Result<()> {
        let mut sources: [Option<i32>; 3] = [
            slots[0].as_ref().map(|a| child_file(a).as_raw_fd()),
            slots[1].as_ref().map(|a| child_file(a).as_raw_fd()),
            slots[2].as_ref().map(|a| child_file(a).as_raw_fd()),
        ];

        for i in 0..3 {
            if let Some(fd) = sources[i] {
                // Will be overwritten iff fd is a low fd (a possible dup2
                // target) other than this stream's own target, AND the stream
                // owning fd as its target will actually dup2 to it (source !=
                // target there too). The normal case (sources > 2) skips this
                // entirely.
                let will_be_overwritten = (0..=2).contains(&fd)
                    && fd != i as i32
                    && sources[fd as usize].is_some_and(|s| s != fd);
                if will_be_overwritten {
                    sources[i] = Some(posix::fcntl(fd, posix::F_DUPFD_CLOEXEC, Some(3))?);
                }
            }
        }

        for (i, &source) in sources.iter().enumerate() {
            let target = i as i32;
            let Some(fd) = source else { continue };
            if fd == target {
                // dup2(fd, fd) is a no-op and doesn't clear CLOEXEC; clear it
                // so the fd survives exec.
                set_inheritable(fd, true)?;
            } else {
                posix::dup2(fd, target)?;
                // Source fd is redundant after dup2; for fd > 2, set CLOEXEC
                // so it closes at exec. (Pre-pass dups already have CLOEXEC,
                // so this is a single F_GETFD no-op for them.) fd in 0..=2 is
                // an inherited standard stream the child may still need -
                // notably the standard-stream wrapper used to back a Merge
                // against an unredirected stdout/stderr - so leave it.
                if fd >= 3 {
                    let _ = set_inheritable(fd, false);
                }
            }
        }
        Ok(())
    }

    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 slots = std::mem::ManuallyDrop::new([stdin, stdout, stderr]);
        let mut just_exec = std::mem::ManuallyDrop::new(just_exec);
        let mut os_options = std::mem::ManuallyDrop::new(os_options);

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

        redirect_streams(&slots)?;
        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)?;
        }
        for f in &mut os_options.pre_exec_fns {
            f()?;
        }
        // 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(fd: RawFd, inheritable: bool) -> io::Result<()> {
        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(redir: Arc<Redirection>) -> 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(redir)
    }

    /// 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(fd, 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";

    /// Compares two env var names under the platform's env semantics. Windows env
    /// var names are case-insensitive; this delegates to the OS via
    /// `CompareStringOrdinal(bIgnoreCase=TRUE)`, matching what the stdlib uses for
    /// `std::sys::process::windows::EnvKey`.
    pub(crate) fn env_keys_cmp(a: &OsStr, b: &OsStr) -> std::cmp::Ordering {
        let a: Vec<u16> = a.encode_wide().collect();
        let b: Vec<u16> = b.encode_wide().collect();
        win32::compare_string_ordinal(&a, &b, true)
    }

    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> {
        // Sort and dedup in one pass via BTreeMap<EnvKey, _>. EnvKey orders entries by
        // case-insensitive ordinal compare, which is exactly the order CreateProcessW
        // requires for Unicode environment blocks. Walking input in reverse with
        // or_insert means the latest occurrence of each key wins, both for value
        // (matching "last value used" semantics) and for the key's case form.
        let mut sorted = std::collections::BTreeMap::<EnvKey, &OsStr>::new();
        for (k, v) in env.iter().rev() {
            sorted.entry(EnvKey::new(k)).or_insert(v);
        }
        let mut block = vec![];
        for (k, v) in sorted {
            block.extend(k.0);
            block.push('=' as u16);
            block.extend(v.encode_wide());
            block.push(0);
        }
        block.push(0);
        block
    }

    /// `BTreeMap` key for env-block sort+dedup. Caches the UTF-16 encoding so
    /// each compare in the map hits the OS API directly without re-encoding -
    /// matches the approach in `std::sys::process::windows::EnvKey`.
    struct EnvKey(Vec<u16>);

    impl EnvKey {
        fn new(s: &OsStr) -> Self {
            EnvKey(s.encode_wide().collect())
        }
    }

    impl Ord for EnvKey {
        fn cmp(&self, other: &Self) -> std::cmp::Ordering {
            win32::compare_string_ordinal(&self.0, &other.0, true)
        }
    }

    impl PartialOrd for EnvKey {
        fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
            Some(self.cmp(other))
        }
    }

    impl PartialEq for EnvKey {
        fn eq(&self, other: &Self) -> bool {
            self.cmp(other).is_eq()
        }
    }

    impl Eq for EnvKey {}

    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.as_raw_handle(),
            win32::HANDLE_FLAG_INHERIT,
            if inheritable { 1 } else { 0 },
        )?;
        Ok(())
    }

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

    /// 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);
    }

    #[cfg(test)]
    mod tests {
        use super::*;

        // Parse a Windows env block (KEY=VALUE\0...KEY=VALUE\0\0) back to pairs.
        fn parse_block(block: &[u16]) -> Vec<(OsString, OsString)> {
            let mut entries = Vec::new();
            let mut start = 0;
            for (i, &u) in block.iter().enumerate() {
                if u == 0 {
                    if i == start {
                        break;
                    }
                    let chunk = &block[start..i];
                    let eq = chunk.iter().position(|&u| u == b'=' as u16).unwrap();
                    entries.push((
                        OsString::from_wide(&chunk[..eq]),
                        OsString::from_wide(&chunk[eq + 1..]),
                    ));
                    start = i + 1;
                }
            }
            entries
        }

        fn pair(k: &str, v: &str) -> (OsString, OsString) {
            (OsString::from(k), OsString::from(v))
        }

        #[test]
        fn format_env_block_dedup_keeps_last_occurrence() {
            let env = vec![pair("A", "1"), pair("B", "x"), pair("A", "2")];
            assert_eq!(
                parse_block(&format_env_block(&env)),
                vec![pair("A", "2"), pair("B", "x")]
            );
        }

        #[test]
        fn format_env_block_is_sorted() {
            // CreateProcessW requires Unicode env blocks to be sorted by name
            // with case-insensitive ordinal comparison.
            let env = vec![pair("Z", "1"), pair("a", "2"), pair("M", "3")];
            assert_eq!(
                parse_block(&format_env_block(&env)),
                vec![pair("a", "2"), pair("M", "3"), pair("Z", "1")]
            );
        }

        #[test]
        fn format_env_block_dedup_is_case_insensitive() {
            let env = vec![pair("Path", "old"), pair("FOO", "y"), pair("PATH", "new")];
            assert_eq!(
                parse_block(&format_env_block(&env)),
                vec![pair("FOO", "y"), pair("PATH", "new")]
            );
        }

        #[test]
        fn format_env_block_dedup_folds_non_ascii_case() {
            // Beyond ASCII: U+00C4 LATIN CAPITAL LETTER A WITH DIAERESIS vs U+00E4
            // (lowercase). Equal under Windows' case-insensitive ordinal compare;
            // unequal under a naive ASCII-only fold.
            let env = vec![pair("Ä", "old"), pair("ä", "new")];
            assert_eq!(parse_block(&format_env_block(&env)), vec![pair("ä", "new")]);
        }
    }
}