oscall 0.1.1

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
//! Overlapped I/O and completion ports: what `io::windows` is made of.
//!
//! An operation started with an `OVERLAPPED` on a handle open for
//! overlapped operation returns at once; the system writes the status
//! block at the head of the structure, and the buffers, when the operation
//! completes, then sets the event the structure names and queues a packet
//! to the completion port of the handle, if it has one.

// Without `alloc` there is no `Operation`, and nothing starts an operation.
#![cfg_attr(not(feature = "alloc"), allow(dead_code))]

use core::ffi::c_void;
use core::mem::MaybeUninit;
use core::ptr;
use core::sync::atomic::{AtomicU32, Ordering};
use core::time::Duration;

use crate::sys::io::{
    IoStatusBlock, NtReadFile, NtWriteFile, Overlapped, OverlappedEntry, STATUS_PENDING, Sleep,
    WaitForSingleObject,
};
use crate::sys::time::{to_units, unbiased};
use crate::sys::{RawHandle, cvt, dll, last_error};
use crate::{BorrowedHandle, Error, OwnedHandle, Result};

dll!("kernel32.dll" {
    fn CreateIoCompletionPort(
        file: *mut c_void,
        port: *mut c_void,
        key: usize,
        threads: u32,
    ) -> *mut c_void;
    fn GetQueuedCompletionStatusEx(
        port: *mut c_void,
        entries: *mut OverlappedEntry,
        count: u32,
        removed: *mut u32,
        milliseconds: u32,
        alertable: i32,
    ) -> i32;
    fn PostQueuedCompletionStatus(
        port: *mut c_void,
        bytes: u32,
        key: usize,
        overlapped: *const c_void,
    ) -> i32;
    fn CancelIoEx(handle: *mut c_void, overlapped: *const Overlapped) -> i32;
    fn CreateEventW(
        security: *const c_void,
        manual_reset: i32,
        initial_state: i32,
        name: *const u16,
    ) -> *mut c_void;
    fn CreateNamedPipeW(
        name: *const u16,
        open_mode: u32,
        pipe_mode: u32,
        max_instances: u32,
        out_buffer_size: u32,
        in_buffer_size: u32,
        default_timeout: u32,
        security: *const c_void,
    ) -> *mut c_void;
    fn GetCurrentProcessId() -> u32;
    fn SetFileCompletionNotificationModes(handle: *mut c_void, flags: u8) -> i32;
    fn ConnectNamedPipe(pipe: *mut c_void, overlapped: *mut Overlapped) -> i32;
    fn DisconnectNamedPipe(pipe: *mut c_void) -> i32;
    fn WaitNamedPipeW(name: *const u16, milliseconds: u32) -> i32;
    fn SetNamedPipeHandleState(
        handle: *mut c_void,
        mode: *const u32,
        max_collection: *const u32,
        collect_timeout: *const u32,
    ) -> i32;
});

dll!("ntdll.dll" {
    // As `NtReadFile` and `NtWriteFile`, with an array of pages
    // (`FILE_SEGMENT_ELEMENT`, eight bytes each) in the place of the buffer.
    fn NtReadFileScatter(
        handle: *mut c_void,
        event: *mut c_void,
        apc_routine: *const c_void,
        apc_context: *const c_void,
        status: *mut IoStatusBlock,
        segments: *const u64,
        len: u32,
        offset: *const i64,
        key: *const u32,
    ) -> i32;
    fn NtWriteFileGather(
        handle: *mut c_void,
        event: *mut c_void,
        apc_routine: *const c_void,
        apc_context: *const c_void,
        status: *mut IoStatusBlock,
        segments: *const u64,
        len: u32,
        offset: *const i64,
        key: *const u32,
    ) -> i32;
    // What `ReadDirectoryChangesW` is made of, which does not tell an
    // operation that is pending from one that is complete.
    fn NtNotifyChangeDirectoryFile(
        handle: *mut c_void,
        event: *mut c_void,
        apc_routine: *const c_void,
        apc_context: *const c_void,
        status: *mut IoStatusBlock,
        buf: *mut c_void,
        len: u32,
        filter: u32,
        subtree: u8,
    ) -> i32;
});

const INVALID_HANDLE_VALUE: *mut c_void = usize::MAX as *mut c_void;
const INFINITE: u32 = u32::MAX;
const WAIT_TIMEOUT: u32 = 258;
/// The interrupt time counts in units of 100 ns.
const UNITS_PER_MS: u64 = 10_000;

const ERROR_ACCESS_DENIED: i32 = 5;
const ERROR_SEM_TIMEOUT: i32 = 121;
const ERROR_PIPE_BUSY: i32 = 231;
const ERROR_PIPE_CONNECTED: i32 = 535;
const ERROR_IO_PENDING: i32 = 997;
const ERROR_NOT_FOUND: i32 = 1168;

const PIPE_ACCESS_INBOUND: u32 = 1;
const PIPE_ACCESS_OUTBOUND: u32 = 2;
const PIPE_TYPE_MESSAGE: u32 = 4;
const PIPE_READMODE_MESSAGE: u32 = 2;
const PIPE_UNLIMITED_INSTANCES: u32 = 255;
const GENERIC_READ: u32 = 0x8000_0000;
const FILE_WRITE_ATTRIBUTES: u32 = 0x100;
/// The server of the pipe may learn who the client is, and not act as it.
const SECURITY_SQOS_PRESENT: u32 = 0x0010_0000;
const SECURITY_IDENTIFICATION: u32 = 0x0001_0000;
const NMPWAIT_WAIT_FOREVER: u32 = u32::MAX;
const FILE_FLAG_FIRST_PIPE_INSTANCE: u32 = 0x0008_0000;
const PIPE_REJECT_REMOTE_CLIENTS: u32 = 8;
const GENERIC_WRITE: u32 = 0x4000_0000;
const FILE_READ_ATTRIBUTES: u32 = 0x80;
const OPEN_EXISTING: u32 = 3;
/// What `CreatePipe` gives its pipes too.
const PIPE_BUFFER: u32 = 64 * 1024;

/// Whether a status returned by the call that starts an operation means
/// that nothing was started: an error (the two top bits set). Then no
/// event is set, no packet queued and the status block is left alone.
/// Success, a warning or "pending" all mean the operation will complete.
pub(crate) fn failed_to_start(status: i32) -> bool {
    (status as u32) >> 30 == 3
}

/// A new completion port, with as many threads running at once as there
/// are processors.
pub(crate) fn port_new() -> Result<OwnedHandle> {
    // SAFETY: no memory is involved.
    let port = unsafe { CreateIoCompletionPort(INVALID_HANDLE_VALUE, ptr::null_mut(), 0, 0) };
    if port.is_null() {
        return Err(last_error());
    }
    // SAFETY: the handle was just created.
    Ok(unsafe { OwnedHandle::from_raw(port) })
}

/// Binds a file handle (a socket is one, to this call) to the port for
/// good: the operations that complete on it queue a packet with `key`.
pub(crate) fn port_associate(
    port: BorrowedHandle<'_>,
    handle: RawHandle,
    key: usize,
) -> Result<()> {
    // SAFETY: no memory is involved.
    let bound = unsafe { CreateIoCompletionPort(handle, port.as_raw(), key, 0) };
    if bound.is_null() {
        return Err(last_error());
    }
    Ok(())
}

pub(crate) fn port_post(
    port: BorrowedHandle<'_>,
    key: usize,
    overlapped: usize,
    bytes: u32,
) -> Result<()> {
    // SAFETY: the "pointer" is a number to the port, which hands it back.
    cvt(unsafe { PostQueuedCompletionStatus(port.as_raw(), bytes, key, overlapped as *const _) })
}

/// Takes packets from the port, waiting for the first if there is none.
/// The deadline is on the unbiased interrupt time, the clock
/// `Clock::Monotonic` reads: the port counts in milliseconds and in timer
/// ticks, and gives up early by as much as a tick.
pub(crate) fn port_wait(
    port: BorrowedHandle<'_>,
    entries: &mut [OverlappedEntry],
    timeout: Option<Duration>,
) -> Result<usize> {
    let deadline = timeout.map(|timeout| unbiased().saturating_add(to_units(timeout)));
    let want = u32::try_from(entries.len()).unwrap_or(u32::MAX);
    loop {
        let (milliseconds, last) = match deadline {
            None => (INFINITE, false),
            Some(deadline) => {
                let left = deadline.saturating_sub(unbiased()).div_ceil(UNITS_PER_MS);
                // In pieces if it is more than the port counts (49 days;
                // the largest value means no timeout).
                match u32::try_from(left) {
                    Ok(left) if left < INFINITE => (left, left == 0),
                    _ => (INFINITE - 1, false),
                }
            }
        };
        let mut removed = 0;
        // SAFETY: the function writes at most `want` entries, and how many
        // it wrote.
        let collected = unsafe {
            GetQueuedCompletionStatusEx(
                port.as_raw(),
                entries.as_mut_ptr(),
                want,
                &raw mut removed,
                milliseconds,
                0,
            )
        };
        if collected != 0 {
            return Ok((removed as usize).min(entries.len()));
        }
        let error = last_error();
        if error.raw_os_error() != WAIT_TIMEOUT as i32 {
            return Err(error);
        }
        if last {
            return Ok(0);
        }
    }
}

/// An event that stays set until it is reset, not set: what an operation
/// signals when it completes.
pub(crate) fn event_new() -> Result<OwnedHandle> {
    // SAFETY: no memory is involved.
    let event = unsafe { CreateEventW(ptr::null(), 1, 0, ptr::null()) };
    if event.is_null() {
        return Err(last_error());
    }
    // SAFETY: the handle was just created.
    Ok(unsafe { OwnedHandle::from_raw(event) })
}

/// Starts a read (`NtReadFile`, which `ReadFile` is made of) and returns
/// the status of the call: see [`failed_to_start`].
///
/// # Safety
///
/// `overlapped` must point to an `OVERLAPPED` whose status is pending and
/// whose event is an event, and that lives, with the `len` writable bytes
/// at `buf`, until the operation is complete.
pub(crate) unsafe fn read(
    handle: RawHandle,
    overlapped: *mut Overlapped,
    buf: *mut u8,
    len: u32,
    offset: Option<i64>,
) -> i32 {
    // SAFETY: the caller's contract. The structure starts with the status
    // block of the operation, and is also what the completion packet
    // names; the offset is read by the call.
    unsafe {
        NtReadFile(
            handle,
            (*overlapped).event,
            ptr::null(),
            overlapped.cast(),
            overlapped.cast::<IoStatusBlock>(),
            buf,
            len,
            offset.as_ref().map_or(ptr::null(), ptr::from_ref),
            ptr::null(),
        )
    }
}

/// Starts a write (`NtWriteFile`): as [`read`].
///
/// # Safety
///
/// As [`read`]; the bytes are read.
pub(crate) unsafe fn write(
    handle: RawHandle,
    overlapped: *mut Overlapped,
    buf: *const u8,
    len: u32,
    offset: Option<i64>,
) -> i32 {
    // SAFETY: as in `read`.
    unsafe {
        NtWriteFile(
            handle,
            (*overlapped).event,
            ptr::null(),
            overlapped.cast(),
            overlapped.cast::<IoStatusBlock>(),
            buf,
            len,
            offset.as_ref().map_or(ptr::null(), ptr::from_ref),
            ptr::null(),
        )
    }
}

/// Asks for the operation of `overlapped` on `handle` to be cancelled.
/// `false` if the system found no such operation: it is complete, or about
/// to be.
///
/// # Safety
///
/// None about memory: the pointer is only compared. It is `unsafe` for the
/// handle, which must be open or be nothing.
pub(crate) unsafe fn cancel(handle: RawHandle, overlapped: *const Overlapped) -> Result<bool> {
    // SAFETY: the caller's contract.
    if unsafe { CancelIoEx(handle, overlapped) } != 0 {
        return Ok(true);
    }
    let error = last_error();
    if error.raw_os_error() == ERROR_NOT_FOUND {
        Ok(false)
    } else {
        Err(error)
    }
}

/// Waits until the status at `status` is no longer pending and returns it,
/// or `None` if `limit` passes first. `event` is what the operation sets
/// when it completes; the status is what tells.
///
/// # Safety
///
/// `status` must point to the status of an `OVERLAPPED` that lives until
/// this returns, and that was pending before its operation was started.
pub(crate) unsafe fn wait_status(
    event: RawHandle,
    status: *const usize,
    limit: Option<Duration>,
) -> Option<i32> {
    // The system writes the status from outside of what the compiler sees.
    // SAFETY: `status` is valid, as the caller promised.
    let current = || unsafe { ptr::read_volatile(status) } as i32;
    let deadline = limit.map(|limit| unbiased().saturating_add(to_units(limit)));
    loop {
        let status = current();
        if status != STATUS_PENDING {
            return Some(status);
        }
        let milliseconds = match deadline {
            None => INFINITE,
            Some(deadline) => {
                let left = deadline.saturating_sub(unbiased()).div_ceil(UNITS_PER_MS);
                if left == 0 {
                    return None;
                }
                u32::try_from(left).unwrap_or(INFINITE).min(INFINITE - 1)
            }
        };
        // SAFETY: no memory is involved.
        let waited = unsafe { WaitForSingleObject(event, milliseconds) };
        if waited != WAIT_TIMEOUT && current() == STATUS_PENDING {
            // The event of an earlier operation, or a wait that failed: do
            // not spin.
            // SAFETY: Sleep has no requirement; the wait is not alertable.
            unsafe { Sleep(1) };
        }
    }
}

/// Starts a read into whole pages (`NtReadFileScatter`): as [`read`].
///
/// # Safety
///
/// As [`read`]; `segments` must be an array of addresses of pages, ended
/// by a zero, that lives as long as the pages, which are written.
pub(crate) unsafe fn read_scatter(
    handle: RawHandle,
    overlapped: *mut Overlapped,
    segments: *const u64,
    len: u32,
    offset: i64,
) -> i32 {
    // SAFETY: as in `read`.
    unsafe {
        NtReadFileScatter(
            handle,
            (*overlapped).event,
            ptr::null(),
            overlapped.cast(),
            overlapped.cast::<IoStatusBlock>(),
            segments,
            len,
            &raw const offset,
            ptr::null(),
        )
    }
}

/// Starts a write from whole pages (`NtWriteFileGather`): as
/// [`read_scatter`].
///
/// # Safety
///
/// As [`read_scatter`]; the pages are read.
pub(crate) unsafe fn write_gather(
    handle: RawHandle,
    overlapped: *mut Overlapped,
    segments: *const u64,
    len: u32,
    offset: i64,
) -> i32 {
    // SAFETY: as in `read`.
    unsafe {
        NtWriteFileGather(
            handle,
            (*overlapped).event,
            ptr::null(),
            overlapped.cast(),
            overlapped.cast::<IoStatusBlock>(),
            segments,
            len,
            &raw const offset,
            ptr::null(),
        )
    }
}

/// Starts waiting for changes in a directory
/// (`NtNotifyChangeDirectoryFile`, which `ReadDirectoryChangesW` is made
/// of): as [`read`]. The records are written to `buf`.
///
/// # Safety
///
/// As [`read`]; `buf` must be aligned as a `u32`.
pub(crate) unsafe fn watch(
    handle: RawHandle,
    overlapped: *mut Overlapped,
    buf: *mut u32,
    len: u32,
    filter: u32,
    subtree: bool,
) -> i32 {
    // SAFETY: as in `read`.
    unsafe {
        NtNotifyChangeDirectoryFile(
            handle,
            (*overlapped).event,
            ptr::null(),
            overlapped.cast(),
            overlapped.cast::<IoStatusBlock>(),
            buf.cast(),
            len,
            filter,
            subtree.into(),
        )
    }
}

/// `SetFileCompletionNotificationModes`.
pub(crate) fn set_completion_modes(handle: RawHandle, flags: u8) -> Result<()> {
    // SAFETY: no memory is involved.
    cvt(unsafe { SetFileCompletionNotificationModes(handle, flags) })
}

/// What starting to wait for a client of a pipe came to.
pub(crate) enum PipeConnect {
    /// The operation was started and is complete.
    Complete,
    /// The operation was started.
    Pending,
    /// A client is connected already: nothing was started.
    Connected,
}

/// Starts waiting for a client to connect to the instance of a pipe
/// (`ConnectNamedPipe`).
///
/// # Safety
///
/// `overlapped` must point to an `OVERLAPPED` whose status is pending and
/// whose event is an event, and that lives until the operation is complete.
pub(crate) unsafe fn connect_pipe(
    pipe: RawHandle,
    overlapped: *mut Overlapped,
) -> Result<PipeConnect> {
    // SAFETY: the caller's contract.
    if unsafe { ConnectNamedPipe(pipe, overlapped) } != 0 {
        return Ok(PipeConnect::Complete);
    }
    let error = last_error();
    match error.raw_os_error() {
        ERROR_IO_PENDING => Ok(PipeConnect::Pending),
        ERROR_PIPE_CONNECTED => Ok(PipeConnect::Connected),
        _ => Err(error),
    }
}

/// `DisconnectNamedPipe`.
pub(crate) fn disconnect_pipe(pipe: RawHandle) -> Result<()> {
    // SAFETY: no memory is involved.
    cvt(unsafe { DisconnectNamedPipe(pipe) })
}

/// What a named pipe is opened with, on either side.
#[derive(Clone, Copy)]
pub(crate) struct PipeSettings {
    pub(crate) read: bool,
    pub(crate) write: bool,
    pub(crate) message: bool,
    pub(crate) first: bool,
    pub(crate) remote: bool,
    /// How many instances the pipe may have, 0 for no limit.
    pub(crate) instances: u8,
    pub(crate) buffer: u32,
}

/// `CreateNamedPipeW`: an instance of the pipe `name`, open for overlapped
/// operation and not inheritable.
pub(crate) fn pipe_server(name: &[u16], settings: PipeSettings) -> Result<OwnedHandle> {
    let mut open_mode = crate::sys::fs::FILE_FLAG_OVERLAPPED;
    if settings.read {
        open_mode |= PIPE_ACCESS_INBOUND;
    }
    if settings.write {
        open_mode |= PIPE_ACCESS_OUTBOUND;
    }
    if settings.first {
        open_mode |= FILE_FLAG_FIRST_PIPE_INSTANCE;
    }
    let mut pipe_mode = 0;
    if settings.message {
        pipe_mode |= PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE;
    }
    if !settings.remote {
        pipe_mode |= PIPE_REJECT_REMOTE_CLIENTS;
    }
    let instances = match settings.instances {
        0 | 255 => PIPE_UNLIMITED_INSTANCES,
        instances => instances.into(),
    };
    // SAFETY: the name is NUL-terminated. Without security attributes the
    // handle is not inheritable.
    let pipe = unsafe {
        CreateNamedPipeW(
            name.as_ptr(),
            open_mode,
            pipe_mode,
            instances,
            settings.buffer,
            settings.buffer,
            0,
            ptr::null(),
        )
    };
    if pipe == INVALID_HANDLE_VALUE {
        return Err(last_error());
    }
    // SAFETY: the handle was just created.
    Ok(unsafe { OwnedHandle::from_raw(pipe) })
}

/// Opens the client end of the pipe `name`, for overlapped operation.
pub(crate) fn pipe_client(name: &[u16], settings: PipeSettings) -> Result<OwnedHandle> {
    // The state of a pipe is asked through an end that cannot read it
    // otherwise, and its mode set through one that cannot write to it.
    let mut access = if settings.read {
        GENERIC_READ
    } else {
        FILE_READ_ATTRIBUTES
    };
    if settings.write {
        access |= GENERIC_WRITE;
    } else if settings.message {
        access |= FILE_WRITE_ATTRIBUTES;
    }
    let pipe = crate::sys::fs::create_file(
        name,
        access,
        OPEN_EXISTING,
        crate::sys::fs::FILE_FLAG_OVERLAPPED | SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION,
    )?;
    if settings.message && settings.read {
        let mode = PIPE_READMODE_MESSAGE;
        // SAFETY: the call reads the mode.
        cvt(unsafe {
            SetNamedPipeHandleState(pipe.as_raw(), &raw const mode, ptr::null(), ptr::null())
        })?;
    }
    Ok(pipe)
}

/// Waits until an instance of the pipe `name` waits for a client
/// (`WaitNamedPipeW`): whether one does before `timeout` passes.
///
/// The deadline is on the unbiased interrupt time, as in [`port_wait`]: the
/// call counts in milliseconds and gives up early (a wait of 60 ms was seen
/// to end before 50 had passed), so it is made again for what is left.
pub(crate) fn wait_pipe(name: &[u16], timeout: Option<Duration>) -> Result<bool> {
    let deadline = timeout.map(|timeout| unbiased().saturating_add(to_units(timeout)));
    let mut first = true;
    loop {
        let milliseconds = match deadline {
            None => NMPWAIT_WAIT_FOREVER,
            Some(deadline) => {
                let left = deadline.saturating_sub(unbiased()).div_ceil(UNITS_PER_MS);
                if left == 0 && !first {
                    return Ok(false);
                }
                // Zero means the default of the pipe to this call, and the
                // largest value no limit.
                u32::try_from(left)
                    .unwrap_or(NMPWAIT_WAIT_FOREVER)
                    .clamp(1, NMPWAIT_WAIT_FOREVER - 1)
            }
        };
        first = false;
        // SAFETY: the name is NUL-terminated.
        if unsafe { WaitNamedPipeW(name.as_ptr(), milliseconds) } != 0 {
            return Ok(true);
        }
        let error = last_error();
        if error.raw_os_error() != ERROR_SEM_TIMEOUT {
            return Err(error);
        }
    }
}

/// A name for a pipe, that nothing else has: the process, a count, and
/// random bits against guessing. NUL-terminated.
fn pipe_name() -> Result<[u16; 64]> {
    static COUNT: AtomicU32 = AtomicU32::new(0);
    let mut random = [MaybeUninit::<u8>::uninit(); 8];
    crate::sys::rand::fill(&mut random)?;
    // SAFETY: `fill` wrote every byte.
    let random = u64::from_ne_bytes(random.map(|byte| unsafe { byte.assume_init() }));
    // SAFETY: takes nothing and cannot fail.
    let process = unsafe { GetCurrentProcessId() };
    let count = COUNT.fetch_add(1, Ordering::Relaxed);

    let mut name = [0u16; 64];
    let mut len = 0;
    let mut push = |unit: u8| {
        name[len] = u16::from(unit);
        len += 1;
    };
    for &unit in b"\\\\.\\pipe\\oscall." {
        push(unit);
    }
    for (value, digits) in [(u64::from(process), 8), (u64::from(count), 8), (random, 16)] {
        for digit in (0..digits).rev() {
            push(b"0123456789abcdef"[(value >> (digit * 4)) as usize & 15]);
        }
        push(b'.');
    }
    // 16 + 8 + 8 + 16 + 3 units, and the NUL the array ends with.
    Ok(name)
}

/// A pipe both ends of which are open for overlapped operation, which
/// those of `CreatePipe` are not: a named pipe with one instance, and a
/// client connected to it. The read end comes first.
pub(crate) fn pipe() -> Result<(OwnedHandle, OwnedHandle)> {
    let mut tries = 0;
    let (name, read) = loop {
        let name = pipe_name()?;
        // SAFETY: the name is NUL-terminated. Without security attributes
        // the handle is not inheritable.
        let read = unsafe {
            CreateNamedPipeW(
                name.as_ptr(),
                PIPE_ACCESS_INBOUND
                    | FILE_FLAG_FIRST_PIPE_INSTANCE
                    | crate::sys::fs::FILE_FLAG_OVERLAPPED,
                // A stream of bytes, which waits.
                PIPE_REJECT_REMOTE_CLIENTS,
                1,
                PIPE_BUFFER,
                PIPE_BUFFER,
                0,
                ptr::null(),
            )
        };
        if read != INVALID_HANDLE_VALUE {
            // SAFETY: the handle was just created.
            break (name, unsafe { OwnedHandle::from_raw(read) });
        }
        let error = last_error();
        // The name is taken, however unlikely: another one.
        tries += 1;
        if tries > 8 || !matches!(error.raw_os_error(), ERROR_ACCESS_DENIED | ERROR_PIPE_BUSY) {
            return Err(error);
        }
    };
    let write = crate::sys::fs::create_file(
        &name,
        GENERIC_WRITE | FILE_READ_ATTRIBUTES,
        OPEN_EXISTING,
        crate::sys::fs::FILE_FLAG_OVERLAPPED,
    )?;
    Ok((read, write))
}

/// The error of a status, for callers that have no use of the `sys` path.
pub(crate) fn status_error(status: i32) -> Error {
    crate::sys::nt_error(status)
}