oscall 0.0.2

Low-level cross-platform interface to operating system services: files, memory mapping, networking and more, with no libc on Linux
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
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
//! `process` on Windows.

use core::ffi::c_void;

pub(crate) mod signal;

use core::time::Duration;

use crate::process::ResourceUsage;
use crate::sys::{cvt, dll, last_error};
use crate::{Error, OwnedHandle, Result};

dll!("kernel32.dll" {
    fn GetCurrentProcessId() -> u32;
    fn GetCurrentProcess() -> *mut c_void;
    fn ExitProcess(code: u32) -> !;
    fn TerminateProcess(process: *mut c_void, code: u32) -> i32;
    fn OpenProcess(access: u32, inherit: i32, pid: u32) -> *mut c_void;
    fn WaitForSingleObject(handle: *mut c_void, milliseconds: u32) -> u32;
});

const PROCESS_TERMINATE: u32 = 0x0001;
const SYNCHRONIZE: u32 = 0x0010_0000;

const WAIT_OBJECT_0: u32 = 0;
const WAIT_TIMEOUT: u32 = 258;

const ERROR_ACCESS_DENIED: i32 = 5;
const ERROR_INVALID_PARAMETER: i32 = 87;

dll!("ntdll.dll" {
    fn NtQueryInformationProcess(
        process: *mut c_void,
        class: u32,
        info: *mut c_void,
        len: u32,
        returned: *mut u32,
    ) -> i32;
    fn RtlNtStatusToDosError(status: i32) -> u32;
});

/// `ProcessBasicInformation`, which fills a `PROCESS_BASIC_INFORMATION`:
/// six fields, each pointer-sized or padded to it (`ExitStatus`,
/// `PebBaseAddress`, `AffinityMask`, `BasePriority`, `UniqueProcessId`,
/// `InheritedFromUniqueProcessId`).
const PROCESS_BASIC_INFORMATION: u32 = 0;
const INHERITED_FROM_UNIQUE_PROCESS_ID: usize = 5;

/// `STATUS_STACK_BUFFER_OVERRUN`, the exit code of a fail-fast.
#[cfg(not(any(target_arch = "x86", target_arch = "x86_64", target_arch = "aarch64")))]
const FAIL_FAST_EXIT_CODE: u32 = 0xc000_0409;

pub(crate) fn id() -> u32 {
    // SAFETY: no argument, and the call cannot fail.
    unsafe { GetCurrentProcessId() }
}

pub(crate) fn parent_id() -> u32 {
    let mut info = [0usize; 6];
    // SAFETY: `info` is writable for the length given; the pseudo-handle of
    // the current process is always valid.
    let status = unsafe {
        NtQueryInformationProcess(
            GetCurrentProcess(),
            PROCESS_BASIC_INFORMATION,
            info.as_mut_ptr().cast(),
            size_of_val(&info) as u32,
            core::ptr::null_mut(),
        )
    };
    if status < 0 {
        return 0;
    }
    info[INHERITED_FROM_UNIQUE_PROCESS_ID] as u32
}

/// `ProcessVmCounters`, which fills a `VM_COUNTERS`: eleven fields, each
/// pointer-sized or padded to it; the fourth is `PeakWorkingSetSize`.
const PROCESS_VM_COUNTERS: u32 = 3;
const PEAK_WORKING_SET_SIZE: usize = 3;
/// `ProcessTimes`, which fills a `KERNEL_USER_TIMES`: four 64-bit counts
/// of 100 nanoseconds (creation, exit, kernel time, user time).
const PROCESS_TIMES: u32 = 4;

/// What `process` has consumed: the handle must allow
/// `PROCESS_QUERY_LIMITED_INFORMATION`.
fn usage_of(process: *mut c_void) -> Result<ResourceUsage> {
    let mut times = [0i64; 4];
    let mut memory = [0usize; 11];
    // SAFETY: each buffer is writable for the length given with it.
    let statuses = unsafe {
        [
            NtQueryInformationProcess(
                process,
                PROCESS_TIMES,
                times.as_mut_ptr().cast(),
                size_of_val(&times) as u32,
                core::ptr::null_mut(),
            ),
            NtQueryInformationProcess(
                process,
                PROCESS_VM_COUNTERS,
                memory.as_mut_ptr().cast(),
                size_of_val(&memory) as u32,
                core::ptr::null_mut(),
            ),
        ]
    };
    for status in statuses {
        if status < 0 {
            // SAFETY: no memory is involved.
            let code = unsafe { RtlNtStatusToDosError(status) };
            return Err(Error::from_raw_os_error(code as i32));
        }
    }
    let time = |units: i64| {
        let units = units.max(0) as u64;
        Duration::new(units / 10_000_000, (units % 10_000_000) as u32 * 100)
    };
    Ok(ResourceUsage {
        user_time: time(times[3]),
        system_time: time(times[2]),
        max_resident_memory: memory[PEAK_WORKING_SET_SIZE] as u64,
    })
}

pub(crate) fn resource_usage() -> Result<ResourceUsage> {
    // SAFETY: the pseudo-handle of the current process is always valid.
    usage_of(unsafe { GetCurrentProcess() })
}

pub(crate) fn exit(code: i32) -> ! {
    // SAFETY: ends the process.
    unsafe { ExitProcess(code as u32) }
}

pub(crate) fn abort() -> ! {
    // `__fastfail(FAST_FAIL_FATAL_APP_EXIT)`: the kernel terminates the
    // process at this instruction, with no exception handler run.
    const FAST_FAIL_FATAL_APP_EXIT: u32 = 7;
    #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
    // SAFETY: the instruction does not return.
    unsafe {
        core::arch::asm!(
            "int 0x29",
            in("ecx") FAST_FAIL_FATAL_APP_EXIT,
            options(noreturn, nostack),
        )
    }
    #[cfg(target_arch = "aarch64")]
    // SAFETY: the instruction does not return.
    unsafe {
        core::arch::asm!(
            "brk 0xf003",
            in("x0") FAST_FAIL_FATAL_APP_EXIT as u64,
            options(noreturn, nostack),
        )
    }
    #[cfg(not(any(target_arch = "x86", target_arch = "x86_64", target_arch = "aarch64")))]
    loop {
        let _ = FAST_FAIL_FATAL_APP_EXIT;
        // SAFETY: the pseudo-handle of the current process is always valid.
        unsafe { TerminateProcess(GetCurrentProcess(), FAIL_FAST_EXIT_CODE) };
    }
}

pub(crate) const HAS_PROCESSES: bool = true;
/// What separates the directories of a search path.
pub(crate) const SEARCH_SEPARATOR: u8 = b';';
/// What goes between a directory and a name.
pub(crate) const DIR_SEPARATOR: &[u8] = b"\\";
/// What a program's name ends with when it has no extension.
pub(crate) const PROGRAM_SUFFIX: &[u8] = b".exe";

/// An entry of a search path, as the directory it names: it may be
/// written between quotes.
pub(crate) fn search_dir(entry: &[u8]) -> &[u8] {
    let entry = entry.strip_prefix(b"\"").unwrap_or(entry);
    entry.strip_suffix(b"\"").unwrap_or(entry)
}

/// Whether `name` is a name to search for, and not a path: `C:name` is
/// one, relative to the current directory of a drive.
pub(crate) fn is_bare_name(name: &[u8]) -> bool {
    !name.iter().any(|&c| matches!(c, b'/' | b'\\' | b':'))
}

/// Whether `path` is a regular file: there is no permission to execute.
pub(crate) fn is_program(path: &[u8]) -> bool {
    crate::sys::fs::metadata(path, true).is_ok_and(|metadata| metadata.is_file())
}

/// Opens the process `pid`.
fn open(pid: u32, access: u32) -> Result<OwnedHandle> {
    // SAFETY: no memory is involved.
    let handle = unsafe { OpenProcess(access, 0, pid) };
    if handle.is_null() {
        return Err(last_error());
    }
    // SAFETY: the handle was just created, and is not inheritable.
    Ok(unsafe { OwnedHandle::from_raw(handle) })
}

pub(crate) fn exists(pid: u32) -> Result<bool> {
    match open(pid, SYNCHRONIZE) {
        // A process object outlives its process for as long as there are
        // handles to it: it is signaled once the process has exited.
        // SAFETY: no memory is involved.
        Ok(process) => match unsafe { WaitForSingleObject(process.as_raw(), 0) } {
            WAIT_TIMEOUT => Ok(true),
            WAIT_OBJECT_0 => Ok(false),
            _ => Err(last_error()),
        },
        Err(error) => match error.raw_os_error() {
            ERROR_INVALID_PARAMETER => Ok(false),
            // It is there, and someone else's.
            ERROR_ACCESS_DENIED => Ok(true),
            _ => Err(error),
        },
    }
}

pub(crate) fn kill(pid: u32) -> Result<()> {
    let process = open(pid, PROCESS_TERMINATE | SYNCHRONIZE)?;
    // SAFETY: no memory is involved.
    let result = cvt(unsafe { TerminateProcess(process.as_raw(), 1) });
    // A process that has exited, of which only the object remains because
    // someone holds a handle to it, is refused: it is no process any more,
    // which is the error of an identifier that names none.
    // SAFETY: no memory is involved.
    if result.is_err() && unsafe { WaitForSingleObject(process.as_raw(), 0) } == WAIT_OBJECT_0 {
        return Err(Error::from_raw_os_error(ERROR_INVALID_PARAMETER));
    }
    result
}

#[cfg(feature = "alloc")]
pub(crate) use spawn::{Child, spawn};

#[cfg(feature = "alloc")]
mod spawn {
    use alloc::vec::Vec;
    use core::ffi::c_void;
    use core::ptr;

    use super::{
        GetCurrentProcess, TerminateProcess, WAIT_OBJECT_0, WAIT_TIMEOUT, WaitForSingleObject,
        usage_of,
    };
    use crate::path::with_wide;
    use crate::process::{Command, ExitStatus, ResourceUsage, Stdio};
    use crate::sys::{cvt, dll, last_error};
    use crate::{AsHandle, BorrowedHandle, ErrorKind, OwnedHandle, Result};

    #[repr(C)]
    struct SecurityAttributes {
        len: u32,
        descriptor: *mut c_void,
        inherit: i32,
    }

    /// `STARTUPINFOEXW`: a `STARTUPINFOW` and an attribute list.
    #[repr(C)]
    struct StartupInfoEx {
        cb: u32,
        reserved: *mut u16,
        desktop: *mut u16,
        title: *mut u16,
        x: u32,
        y: u32,
        x_size: u32,
        y_size: u32,
        x_count_chars: u32,
        y_count_chars: u32,
        fill_attribute: u32,
        flags: u32,
        show_window: u16,
        reserved2_len: u16,
        reserved2: *mut u8,
        stdin: *mut c_void,
        stdout: *mut c_void,
        stderr: *mut c_void,
        attribute_list: *mut c_void,
    }

    /// `PROCESS_INFORMATION`.
    #[repr(C)]
    struct ProcessInformation {
        process: *mut c_void,
        thread: *mut c_void,
        process_id: u32,
        thread_id: u32,
    }

    dll!("kernel32.dll" {
        fn CreateProcessW(
            application: *const u16,
            command_line: *mut u16,
            process_attributes: *const c_void,
            thread_attributes: *const c_void,
            inherit_handles: i32,
            flags: u32,
            environment: *const c_void,
            directory: *const u16,
            startup: *const StartupInfoEx,
            info: *mut ProcessInformation,
        ) -> i32;
        fn InitializeProcThreadAttributeList(
            list: *mut c_void,
            count: u32,
            flags: u32,
            size: *mut usize,
        ) -> i32;
        fn UpdateProcThreadAttribute(
            list: *mut c_void,
            flags: u32,
            attribute: usize,
            value: *const c_void,
            size: usize,
            previous: *mut c_void,
            returned: *const usize,
        ) -> i32;
        fn DeleteProcThreadAttributeList(list: *mut c_void);
        fn DuplicateHandle(
            source_process: *mut c_void,
            source: *mut c_void,
            target_process: *mut c_void,
            target: *mut *mut c_void,
            access: u32,
            inherit: i32,
            options: u32,
        ) -> i32;
        fn CreateFileW(
            name: *const u16,
            access: u32,
            share: u32,
            security: *const c_void,
            creation: u32,
            flags: u32,
            template: *mut c_void,
        ) -> *mut c_void;
        fn GetExitCodeProcess(process: *mut c_void, code: *mut u32) -> i32;
        fn GetFullPathNameW(
            path: *const u16,
            len: u32,
            buf: *mut u16,
            file_part: *mut *mut u16,
        ) -> u32;
        fn CompareStringOrdinal(
            a: *const u16,
            a_len: i32,
            b: *const u16,
            b_len: i32,
            ignore_case: i32,
        ) -> i32;
    });

    const DUPLICATE_SAME_ACCESS: u32 = 2;
    const GENERIC_READ: u32 = 0x8000_0000;
    const GENERIC_WRITE: u32 = 0x4000_0000;
    const FILE_SHARE_READ_WRITE: u32 = 0x1 | 0x2;
    const OPEN_EXISTING: u32 = 3;

    const CREATE_NEW_CONSOLE: u32 = 0x10;
    const CREATE_NEW_PROCESS_GROUP: u32 = 0x200;
    const CREATE_UNICODE_ENVIRONMENT: u32 = 0x400;
    const EXTENDED_STARTUPINFO_PRESENT: u32 = 0x8_0000;
    const STARTF_USESTDHANDLES: u32 = 0x100;
    const PROC_THREAD_ATTRIBUTE_HANDLE_LIST: usize = 0x2_0002;

    const INFINITE: u32 = u32::MAX;

    const ERROR_INVALID_HANDLE: i32 = 6;

    const QUOTE: u16 = b'"' as u16;
    const BACKSLASH: u16 = b'\\' as u16;

    fn reserve<T>(vec: &mut Vec<T>, additional: usize) -> Result<()> {
        vec.try_reserve(additional)
            .map_err(|_| ErrorKind::OutOfMemory.into())
    }

    /// Appends `bytes` (WTF-8) to `out` as UTF-16, with no terminator.
    /// Fails with `InvalidInput` if it is malformed or contains a NUL.
    fn push_wide(out: &mut Vec<u16>, bytes: &[u8]) -> Result<()> {
        with_wide(bytes, |wide| {
            let wide = &wide[..wide.len() - 1];
            reserve(out, wide.len())?;
            out.extend_from_slice(wide);
            Ok(())
        })
    }

    /// `bytes` as a NUL-terminated wide string.
    fn wide_string(bytes: &[u8]) -> Result<Vec<u16>> {
        let mut out = Vec::new();
        push_wide(&mut out, bytes)?;
        reserve(&mut out, 1)?;
        out.push(0);
        Ok(out)
    }

    /// Appends one argument to a command line, quoted so that
    /// `CommandLineToArgvW` and the C runtime give it back exactly: the
    /// algorithm of `std`.
    fn push_argument(line: &mut Vec<u16>, arg: &[u8]) -> Result<()> {
        let mut units = Vec::new();
        push_wide(&mut units, arg)?;
        // An empty argument would vanish, and spaces would split it.
        let quote = units.is_empty()
            || units
                .iter()
                .any(|&unit| unit == b' ' as u16 || unit == b'\t' as u16);
        // Every unit is at most doubled, plus a backslash and two quotes.
        reserve(line, 2 * units.len() + 3)?;
        if quote {
            line.push(QUOTE);
        }
        let mut backslashes = 0;
        for &unit in &units {
            if unit == BACKSLASH {
                backslashes += 1;
            } else {
                if unit == QUOTE {
                    // The n backslashes before a quote become 2n + 1: n
                    // literal ones and one that escapes the quote.
                    line.extend(core::iter::repeat_n(BACKSLASH, backslashes + 1));
                }
                backslashes = 0;
            }
            line.push(unit);
        }
        if quote {
            // The n backslashes before the closing quote become 2n, so
            // that it still closes.
            line.extend(core::iter::repeat_n(BACKSLASH, backslashes));
            line.push(QUOTE);
        }
        Ok(())
    }

    /// The command line: the program's name, always quoted (it is not
    /// escaped by the parsers, and cannot contain a quote), then the
    /// arguments.
    fn command_line(command: &Command<'_>) -> Result<Vec<u16>> {
        let mut line = Vec::new();
        if let Some(raw) = command.raw_command_line {
            push_wide(&mut line, raw)?;
        } else {
            let arg0 = command.arg0.unwrap_or(command.program);
            if arg0.contains(&b'"') {
                return Err(ErrorKind::InvalidInput.into());
            }
            reserve(&mut line, 1)?;
            line.push(QUOTE);
            push_wide(&mut line, arg0)?;
            reserve(&mut line, 1)?;
            line.push(QUOTE);
            for arg in command.args.iter() {
                reserve(&mut line, 1)?;
                line.push(b' ' as u16);
                push_argument(&mut line, arg)?;
            }
        }
        reserve(&mut line, 1)?;
        line.push(0);
        Ok(line)
    }

    /// The name of the variable `var` (`NAME=value`). A `=` in the first
    /// place is part of the name: the variables `cmd.exe` keeps the
    /// current directory of each drive in are named `=C:`.
    fn variable_name(var: &[u16]) -> &[u16] {
        let end = var
            .iter()
            .skip(1)
            .position(|&unit| unit == b'=' as u16)
            .map_or(var.len(), |at| at + 1);
        &var[..end]
    }

    /// The order the system keeps an environment in, and wants one in: by
    /// name, without regard to case, comparing UTF-16 units.
    fn compare_names(a: &[u16], b: &[u16]) -> core::cmp::Ordering {
        const CSTR_LESS_THAN: i32 = 1;
        const CSTR_GREATER_THAN: i32 = 3;

        // A string cannot be 2 GiB long and have been passed around.
        let len = |units: &[u16]| units.len().min(i32::MAX as usize) as i32;
        // SAFETY: the pointers and lengths are those of the slices.
        match unsafe { CompareStringOrdinal(a.as_ptr(), len(a), b.as_ptr(), len(b), 1) } {
            CSTR_LESS_THAN => core::cmp::Ordering::Less,
            CSTR_GREATER_THAN => core::cmp::Ordering::Greater,
            // Equal; or a failure, which valid arguments do not cause.
            _ => core::cmp::Ordering::Equal,
        }
    }

    /// The environment block: NUL-terminated strings sorted by name, then
    /// one more NUL.
    fn environment_block(command: &Command<'_>) -> Result<Option<Vec<u16>>> {
        let Some(vars) = command.env else {
            return Ok(None);
        };
        // The strings end to end, and where each one ends.
        let mut units = Vec::new();
        let mut ranges = Vec::new();
        for var in vars.iter() {
            let start = units.len();
            push_wide(&mut units, var)?;
            reserve(&mut ranges, 1)?;
            ranges.push(start..units.len());
        }
        // A stable sort: variables of the same name stay in order.
        ranges.sort_by(|a, b| {
            compare_names(
                variable_name(&units[a.clone()]),
                variable_name(&units[b.clone()]),
            )
        });
        let mut block = Vec::new();
        reserve(&mut block, units.len() + ranges.len() + 2)?;
        for range in ranges {
            block.extend_from_slice(&units[range]);
            block.push(0);
        }
        if block.is_empty() {
            // An empty block is still two NULs.
            block.push(0);
        }
        block.push(0);
        Ok(Some(block))
    }

    /// A duplicate of `handle` that child processes inherit.
    fn inheritable(handle: BorrowedHandle<'_>) -> Result<OwnedHandle> {
        let mut new = ptr::null_mut();
        // SAFETY: `new` is written by the call; the pseudo-handle of the
        // current process needs no closing.
        cvt(unsafe {
            let process = GetCurrentProcess();
            DuplicateHandle(
                process,
                handle.as_raw(),
                process,
                &raw mut new,
                0,
                1,
                DUPLICATE_SAME_ACCESS,
            )
        })?;
        // SAFETY: the handle was just created.
        Ok(unsafe { OwnedHandle::from_raw(new) })
    }

    /// The null device, as an inheritable handle.
    fn null_device() -> Result<OwnedHandle> {
        let name: [u16; 4] = [b'N' as u16, b'U' as u16, b'L' as u16, 0];
        let security = SecurityAttributes {
            len: size_of::<SecurityAttributes>() as u32,
            descriptor: ptr::null_mut(),
            inherit: 1,
        };
        // SAFETY: the name is a NUL-terminated wide string and the
        // attributes are valid for the call.
        let handle = unsafe {
            CreateFileW(
                name.as_ptr(),
                GENERIC_READ | GENERIC_WRITE,
                FILE_SHARE_READ_WRITE,
                (&raw const security).cast(),
                OPEN_EXISTING,
                0,
                ptr::null_mut(),
            )
        };
        if handle as isize == -1 {
            return Err(last_error());
        }
        // SAFETY: the handle was just created.
        Ok(unsafe { OwnedHandle::from_raw(handle) })
    }

    /// The inheritable handle to give the child as one of its standard
    /// handles; `None` for no handle at all.
    fn standard_handle(index: usize, stdio: &Stdio<'_>) -> Result<Option<OwnedHandle>> {
        match stdio {
            Stdio::Null => null_device().map(Some),
            Stdio::Handle(handle) => inheritable(*handle).map(Some),
            Stdio::Inherit => {
                let own = match index {
                    0 => crate::sys::io::stdin(),
                    1 => crate::sys::io::stdout(),
                    _ => crate::sys::io::stderr(),
                };
                match own.map(inheritable) {
                    None => Ok(None),
                    Some(Ok(handle)) => Ok(Some(handle)),
                    // A standard handle that was closed is no handle.
                    Some(Err(error)) if error.raw_os_error() == ERROR_INVALID_HANDLE => Ok(None),
                    Some(Err(error)) => Err(error),
                }
            }
        }
    }

    /// An initialised attribute list, in memory aligned for it.
    struct AttributeList(Vec<usize>);

    impl AttributeList {
        fn as_ptr(&mut self) -> *mut c_void {
            self.0.as_mut_ptr().cast()
        }
    }

    impl Drop for AttributeList {
        fn drop(&mut self) {
            // SAFETY: the list was initialised, and is not used afterwards.
            unsafe { DeleteProcThreadAttributeList(self.as_ptr()) };
        }
    }

    /// An attribute list that names `handles` as the only handles a
    /// process inherits. `handles` must outlive it.
    fn handle_list(handles: &[*mut c_void]) -> Result<AttributeList> {
        let mut size = 0;
        // SAFETY: with no buffer, the call only writes the size it needs
        // (and fails).
        unsafe { InitializeProcThreadAttributeList(ptr::null_mut(), 1, 0, &raw mut size) };
        let mut buffer = Vec::new();
        let words = size.div_ceil(size_of::<usize>()).max(1);
        reserve(&mut buffer, words)?;
        buffer.resize(words, 0usize);
        // SAFETY: the buffer has the size the system asked for.
        cvt(unsafe {
            InitializeProcThreadAttributeList(buffer.as_mut_ptr().cast(), 1, 0, &raw mut size)
        })?;
        let mut list = AttributeList(buffer);
        // SAFETY: the list is initialised; the value is an array of
        // handles of the size given, which the caller keeps alive.
        cvt(unsafe {
            UpdateProcThreadAttribute(
                list.as_ptr(),
                0,
                PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
                handles.as_ptr().cast(),
                size_of_val(handles),
                ptr::null_mut(),
                ptr::null(),
            )
        })?;
        Ok(list)
    }

    #[derive(Debug)]
    pub(crate) struct Child {
        process: OwnedHandle,
        pid: u32,
    }

    /// Whether a name ends in `.bat` or `.cmd`, once the dots and spaces
    /// that end it, which the system drops, are gone.
    fn has_batch_extension(name: &[u16]) -> bool {
        let mut name = name;
        // And the separators: refusing `x.bat\`, which names nothing
        // that runs, costs nothing.
        while let [rest @ .., last] = name
            && *last < 0x80
            && b". \\/".contains(&(*last as u8))
        {
            name = rest;
        }
        let Some(extension) = name.last_chunk::<4>() else {
            return false;
        };
        let lower = extension.map(|unit| match u8::try_from(unit) {
            Ok(byte) => byte.to_ascii_lowercase(),
            Err(_) => 0,
        });
        &lower == b".bat" || &lower == b".cmd"
    }

    /// Whether the system would run `program` (NUL-terminated) as a batch
    /// file, with `cmd.exe`: by the extension of the name as the system
    /// understands it. `x.bat\.` and `x.bat/.` are `x.bat` to it:
    /// `GetFullPathNameW` says what a path comes down to, as it does for
    /// `CreateProcessW`. A path that starts with `\\?\` is taken as it
    /// is by both.
    fn is_batch_file(program: &[u16]) -> Result<bool> {
        let name = &program[..program.len() - 1];
        if has_batch_extension(name) {
            return Ok(true);
        }
        let verbatim = [b'\\' as u16, b'\\' as u16, b'?' as u16, b'\\' as u16];
        if name.starts_with(&verbatim) {
            return Ok(false);
        }
        let mut full = Vec::new();
        let mut size = name.len() + 64;
        loop {
            reserve(&mut full, size)?;
            full.resize(size, 0u16);
            // SAFETY: `program` is NUL-terminated and the buffer is
            // writable for the length given.
            let len = unsafe {
                GetFullPathNameW(
                    program.as_ptr(),
                    full.len() as u32,
                    full.as_mut_ptr(),
                    ptr::null_mut(),
                )
            } as usize;
            if len == 0 {
                // A name the system cannot make sense of is not one it
                // runs.
                return Ok(false);
            }
            if len < full.len() {
                return Ok(has_batch_extension(&full[..len]));
            }
            // Too small: the length needed, with its NUL.
            size = len + 1;
        }
    }

    pub(crate) fn spawn(command: &Command<'_>) -> Result<Child> {
        let application = wide_string(command.program)?;
        // `cmd.exe` does not split its command line the way the quoting
        // done here expects: an argument could run another command.
        if command.raw_command_line.is_none() && is_batch_file(&application)? {
            return Err(ErrorKind::InvalidInput.into());
        }
        let mut line = command_line(command)?;
        let environment = environment_block(command)?;
        let directory = command.current_dir.map(wide_string).transpose()?;

        // Inheritable handles, closed when this function returns: the
        // child has its own by then.
        let standard = [
            standard_handle(0, &command.stdio[0])?,
            standard_handle(1, &command.stdio[1])?,
            standard_handle(2, &command.stdio[2])?,
        ];
        let raw = |index: usize| {
            standard[index]
                .as_ref()
                .map_or(ptr::null_mut(), OwnedHandle::as_raw)
        };
        // Exactly these are inherited, whatever else in the process is
        // inheritable, and whatever other threads are spawning.
        let mut handles = [ptr::null_mut(); 3];
        let mut count = 0;
        for handle in standard.iter().flatten() {
            handles[count] = handle.as_raw();
            count += 1;
        }
        // A list cannot be empty: with no handle to pass, nothing is
        // inherited at all.
        let mut list = if count > 0 {
            Some(handle_list(&handles[..count])?)
        } else {
            None
        };

        // Without a list the structure is a plain `STARTUPINFOW`: all but
        // the last field.
        let (size, extended) = match list {
            Some(_) => (size_of::<StartupInfoEx>(), EXTENDED_STARTUPINFO_PRESENT),
            None => (size_of::<StartupInfoEx>() - size_of::<*mut c_void>(), 0),
        };
        let startup = StartupInfoEx {
            cb: size as u32,
            reserved: ptr::null_mut(),
            desktop: ptr::null_mut(),
            title: ptr::null_mut(),
            x: 0,
            y: 0,
            x_size: 0,
            y_size: 0,
            x_count_chars: 0,
            y_count_chars: 0,
            fill_attribute: 0,
            flags: STARTF_USESTDHANDLES,
            show_window: 0,
            reserved2_len: 0,
            reserved2: ptr::null_mut(),
            stdin: raw(0),
            stdout: raw(1),
            stderr: raw(2),
            attribute_list: list.as_mut().map_or(ptr::null_mut(), AttributeList::as_ptr),
        };
        let mut group = if command.new_process_group {
            CREATE_NEW_PROCESS_GROUP
        } else {
            0
        };
        if command.new_console {
            group |= CREATE_NEW_CONSOLE;
        }
        let mut info = ProcessInformation {
            process: ptr::null_mut(),
            thread: ptr::null_mut(),
            process_id: 0,
            thread_id: 0,
        };
        // SAFETY: every string is NUL-terminated, the command line is
        // writable, the environment block ends with two NULs, and the
        // structures are valid for the call. Naming the application means
        // no search path is used.
        cvt(unsafe {
            CreateProcessW(
                application.as_ptr(),
                line.as_mut_ptr(),
                ptr::null(),
                ptr::null(),
                (count > 0) as i32,
                CREATE_UNICODE_ENVIRONMENT | extended | group,
                environment
                    .as_ref()
                    .map_or(ptr::null(), |block| block.as_ptr().cast()),
                directory.as_ref().map_or(ptr::null(), |dir| dir.as_ptr()),
                &raw const startup,
                &raw mut info,
            )
        })?;
        // SAFETY: both handles were just created for us; the one of the
        // initial thread is of no use.
        let process = unsafe {
            drop(OwnedHandle::from_raw(info.thread));
            OwnedHandle::from_raw(info.process)
        };
        Ok(Child {
            process,
            pid: info.process_id,
        })
    }

    impl Child {
        pub(crate) fn id(&self) -> u32 {
            self.pid
        }

        pub(crate) fn handle(&self) -> BorrowedHandle<'_> {
            self.process.as_handle()
        }

        pub(crate) fn wait(
            &self,
            block: bool,
        ) -> Result<Option<(ExitStatus, Option<ResourceUsage>)>> {
            let timeout = if block { INFINITE } else { 0 };
            // SAFETY: no memory is involved.
            match unsafe { WaitForSingleObject(self.process.as_raw(), timeout) } {
                WAIT_OBJECT_0 => {}
                WAIT_TIMEOUT => return Ok(None),
                _ => return Err(last_error()),
            }
            let mut code = 0;
            // SAFETY: `code` is written by the call.
            cvt(unsafe { GetExitCodeProcess(self.process.as_raw(), &raw mut code) })?;
            // The object of a process that has exited still has its
            // counters.
            let usage = usage_of(self.process.as_raw()).ok();
            Ok(Some((ExitStatus::exited(code as i32), usage)))
        }

        pub(crate) fn kill(&self) -> Result<()> {
            // SAFETY: no memory is involved.
            let result = cvt(unsafe { TerminateProcess(self.process.as_raw(), 1) });
            // Terminating a process that has exited is refused.
            if result.is_err() && matches!(self.wait(false), Ok(Some(_))) {
                return Ok(());
            }
            result
        }
    }
}