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
//! `io` on Windows.

use core::ffi::c_void;
use core::ptr;

use crate::io::{IoSlice, IoSliceMut, SeekFrom};
use crate::sys::{cvt, dll, nt_error};
use crate::{BorrowedHandle, ErrorKind, OwnedHandle, Result};

/// `OVERLAPPED`. Its first two members are the `IO_STATUS_BLOCK` of the
/// operation: `internal` is its status, `STATUS_PENDING` until the
/// operation is complete.
///
/// A handle may be open for overlapped (asynchronous) operation without
/// oscall knowing: a call that takes this structure can then return while
/// the operation is pending, and the system writes to the structure when it
/// completes. Whoever passes one must not return before that: see
/// [`wait_completion`].
#[repr(C)]
pub(crate) struct Overlapped {
    pub(crate) internal: usize,
    pub(crate) internal_high: usize,
    pub(crate) offset: u32,
    pub(crate) offset_high: u32,
    pub(crate) event: *mut c_void,
}

impl Overlapped {
    pub(crate) fn at(offset: u64) -> Self {
        Self {
            internal: 0,
            internal_high: 0,
            offset: offset as u32,
            offset_high: (offset >> 32) as u32,
            event: ptr::null_mut(),
        }
    }
}

/// `OVERLAPPED_ENTRY`: a packet taken from an I/O completion port.
#[repr(C)]
#[derive(Clone, Copy)]
pub(crate) struct OverlappedEntry {
    pub(crate) key: usize,
    pub(crate) overlapped: *mut c_void,
    /// The status of the operation, an `NTSTATUS`.
    pub(crate) internal: usize,
    pub(crate) bytes: u32,
}

impl OverlappedEntry {
    pub(crate) const EMPTY: Self = Self {
        key: 0,
        overlapped: ptr::null_mut(),
        internal: 0,
        bytes: 0,
    };
}

const _: () = {
    assert!(size_of::<OverlappedEntry>() == 4 * size_of::<usize>());
    assert!(size_of::<Overlapped>() == 3 * size_of::<usize>() + 8);
};

dll!("kernel32.dll" {
    pub(crate) fn WaitForSingleObject(handle: *mut c_void, milliseconds: u32) -> u32;
    pub(crate) fn Sleep(milliseconds: u32);
    fn SetFilePointerEx(handle: *mut c_void, distance: i64, pos: *mut i64, method: u32) -> i32;
    fn CreatePipe(
        read: *mut *mut c_void,
        write: *mut *mut c_void,
        attributes: *const c_void,
        size: u32,
    ) -> i32;
    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 GetCurrentProcess() -> *mut c_void;
    fn GetStdHandle(which: u32) -> *mut c_void;
    fn GetConsoleMode(handle: *mut c_void, mode: *mut u32) -> i32;
    fn SetHandleInformation(handle: *mut c_void, mask: u32, flags: u32) -> i32;
    fn GetHandleInformation(handle: *mut c_void, flags: *mut u32) -> i32;
    fn GetNamedPipeHandleStateW(
        handle: *mut c_void,
        state: *mut u32,
        instances: *mut u32,
        max_collection: *mut u32,
        collect_timeout: *mut u32,
        user_name: *mut u16,
        user_name_len: u32,
    ) -> i32;
    fn SetNamedPipeHandleState(
        handle: *mut c_void,
        mode: *const u32,
        max_collection: *const u32,
        collect_timeout: *const u32,
    ) -> i32;
});

/// `IO_STATUS_BLOCK`. Its first member is a union of the status and a
/// pointer: pointer-sized, with the status in its low 32 bits.
#[repr(C)]
pub(crate) struct IoStatusBlock {
    pub(crate) status: usize,
    pub(crate) information: usize,
}

impl IoStatusBlock {
    /// The block of an operation that is not complete.
    pub(crate) const PENDING: Self = Self {
        status: STATUS_PENDING as usize,
        information: 0,
    };
}

/// `FILE_PIPE_LOCAL_INFORMATION`.
#[derive(Default)]
#[repr(C)]
struct FilePipeLocalInformation {
    pipe_type: u32,
    configuration: u32,
    maximum_instances: u32,
    current_instances: u32,
    inbound_quota: u32,
    read_data_available: u32,
    outbound_quota: u32,
    write_quota_available: u32,
    state: u32,
    end: u32,
}

dll!("ntdll.dll" {
    // What `ReadFile` and `WriteFile` are made of. `offset` is null for the
    // position of the handle.
    pub(crate) fn NtReadFile(
        handle: *mut c_void,
        event: *mut c_void,
        apc_routine: *const c_void,
        apc_context: *const c_void,
        status: *mut IoStatusBlock,
        buf: *mut u8,
        len: u32,
        offset: *const i64,
        key: *const u32,
    ) -> i32;
    pub(crate) fn NtWriteFile(
        handle: *mut c_void,
        event: *mut c_void,
        apc_routine: *const c_void,
        apc_context: *const c_void,
        status: *mut IoStatusBlock,
        buf: *const u8,
        len: u32,
        offset: *const i64,
        key: *const u32,
    ) -> i32;
    fn NtQueryInformationFile(
        handle: *mut c_void,
        status: *mut IoStatusBlock,
        info: *mut c_void,
        len: u32,
        class: i32,
    ) -> i32;
});

// FILE_INFORMATION_CLASS
const FILE_PIPE_LOCAL_INFORMATION: i32 = 24;

pub(crate) const STATUS_PENDING: i32 = 0x103;
/// The buffer was too small for a whole message: it holds the start of it.
const STATUS_BUFFER_OVERFLOW: i32 = 0x8000_0005u32 as i32;

const INFINITE: u32 = u32::MAX;
const WAIT_TIMEOUT: u32 = 258;

const ERROR_HANDLE_EOF: i32 = 38;
const ERROR_BROKEN_PIPE: i32 = 109;
const ERROR_NO_DATA: i32 = 232;

const PIPE_NOWAIT: u32 = 1;
const PIPE_READMODE_MESSAGE: u32 = 2;

const DUPLICATE_SAME_ACCESS: u32 = 2;
const HANDLE_FLAG_INHERIT: u32 = 1;

const STD_INPUT_HANDLE: u32 = -10i32 as u32;
const STD_OUTPUT_HANDLE: u32 = -11i32 as u32;
const STD_ERROR_HANDLE: u32 = -12i32 as u32;

/// `WSABUF`: the length comes first, and is 32 bits wide.
#[derive(Clone, Copy)]
#[repr(C)]
pub(crate) struct RawIoSlice {
    len: u32,
    base: *mut u8,
}

impl RawIoSlice {
    #[inline]
    pub(crate) fn new(base: *mut u8, len: usize) -> Self {
        Self {
            len: len.min(u32::MAX as usize) as u32,
            base,
        }
    }

    #[inline]
    pub(crate) fn ptr(&self) -> *mut u8 {
        self.base
    }

    #[inline]
    pub(crate) fn len(&self) -> usize {
        self.len as usize
    }
}

fn len32(len: usize) -> u32 {
    len.min(u32::MAX as usize) as u32
}

/// How long a wait for the completion of an operation relies on the signal
/// of the handle the operation was made on, which other operations on the
/// handle share, before looking at the status again.
const SHARED_SIGNAL_MS: u32 = 20;

/// Waits until the operation whose status the system writes to `status` is
/// complete, and returns its status.
///
/// An operation that was started must not be left: the system writes to the
/// status block, and to the buffers of the operation, when it completes,
/// wherever the thread has gone by then. So this returns only once it is
/// complete, whatever happens to the wait itself.
///
/// `signal` is what the system signals at completion: an event given to the
/// operation alone (`own`), or the handle the operation was made on. The
/// latter is signalled by every operation that completes on the handle, and
/// reset by every one that starts: it cannot be relied upon when several
/// threads use the handle. The status is what tells, and it is polled
/// when the signal does not help: when it is set but the operation is not
/// complete, when it may have been reset after the operation completed, and
/// when it cannot be waited for at all (a handle without `SYNCHRONIZE`).
///
/// # Safety
///
/// `status` must point to the status of an `IO_STATUS_BLOCK` (or to the
/// first member of an `OVERLAPPED`) that lives until this returns, and that
/// was pending before the operation was started.
pub(crate) unsafe fn wait_completion(signal: *mut c_void, own: bool, status: *const usize) -> 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;
    loop {
        let status = current();
        if status != STATUS_PENDING {
            return status;
        }
        let timeout = if own { INFINITE } else { SHARED_SIGNAL_MS };
        // SAFETY: no memory is involved.
        let waited = unsafe { WaitForSingleObject(signal, timeout) };
        if waited != WAIT_TIMEOUT && current() == STATUS_PENDING {
            // Signalled for something else, or the wait failed: do not spin.
            // SAFETY: Sleep has no requirement; the wait is not alertable.
            unsafe { Sleep(1) };
        }
    }
}

/// An offset as the system takes it. Negative values have meanings of their
/// own to it (the end of the file, the position of the handle).
fn file_offset(offset: u64) -> Result<i64> {
    i64::try_from(offset).map_err(|_| ErrorKind::InvalidInput.into())
}

/// The outcome of a call that starts an operation on `handle` and was given
/// no event (`NtReadFile`, `NtWriteFile`, `NtQueryDirectoryFile`), which
/// returned `status`: the final status, once the operation is complete, and
/// the count of bytes transferred.
///
/// # Safety
///
/// `block` must be the block the call was given, pending before the call,
/// and live.
pub(crate) unsafe fn completed(
    handle: BorrowedHandle<'_>,
    status: i32,
    block: *const IoStatusBlock,
) -> (i32, usize) {
    let status = if status == STATUS_PENDING {
        // The handle is open for overlapped operation: the call does not
        // wait for the operation, so wait here. The handle is the only
        // signal there is, as the call was given no event.
        // SAFETY: the block was pending before the call, and lives.
        unsafe { wait_completion(handle.as_raw(), false, &raw const (*block).status) }
    } else {
        status
    };
    // SAFETY: the operation is complete: nothing writes to the block any
    // more. An operation that failed at once has not written to it.
    (status, unsafe {
        ptr::read_volatile(&raw const (*block).information)
    })
}

fn nt_read(handle: BorrowedHandle<'_>, buf: &mut [u8], offset: Option<u64>) -> Result<usize> {
    let offset = offset.map(file_offset).transpose()?;
    let mut block = IoStatusBlock::PENDING;
    // SAFETY: `buf` is writable for the length given, and `offset` is null
    // or points to a value that lives until the call returns, which is when
    // the system has read it. `buf` and `block` are written until the
    // operation is complete, which `completed` waits for.
    let (status, done) = unsafe {
        let status = NtReadFile(
            handle.as_raw(),
            ptr::null_mut(),
            ptr::null(),
            ptr::null(),
            &raw mut block,
            buf.as_mut_ptr(),
            len32(buf.len()),
            offset.as_ref().map_or(ptr::null(), ptr::from_ref),
            ptr::null(),
        );
        completed(handle, status, &raw const block)
    };
    // The start of a message that is longer than the buffer was read, and
    // the rest of it is for the next read: this is not a failure.
    if status >= 0 || status == STATUS_BUFFER_OVERFLOW {
        return Ok(done);
    }
    let error = nt_error(status);
    match error.raw_os_error() {
        // The end of a file or of a pipe is an error on some handles: make
        // it the `Ok(0)` it is everywhere else.
        ERROR_HANDLE_EOF | ERROR_BROKEN_PIPE => Ok(0),
        // What a pipe that does not wait answers when it is empty; a write
        // gets the same code for a pipe that is closed, which is what the
        // code is classified as.
        ERROR_NO_DATA => Err(ErrorKind::WouldBlock.into()),
        _ => Err(error),
    }
}

fn nt_write(handle: BorrowedHandle<'_>, buf: &[u8], offset: Option<u64>) -> Result<usize> {
    let offset = offset.map(file_offset).transpose()?;
    let mut block = IoStatusBlock::PENDING;
    // SAFETY: `buf` is readable for the length given, and `offset` is null
    // or points to a value that lives until the call returns, which is when
    // the system has read it. `buf` is read and `block` written until the
    // operation is complete, which `completed` waits for.
    let (status, done) = unsafe {
        let status = NtWriteFile(
            handle.as_raw(),
            ptr::null_mut(),
            ptr::null(),
            ptr::null(),
            &raw mut block,
            buf.as_ptr(),
            len32(buf.len()),
            offset.as_ref().map_or(ptr::null(), ptr::from_ref),
            ptr::null(),
        );
        completed(handle, status, &raw const block)
    };
    if status >= 0 {
        Ok(done)
    } else {
        Err(nt_error(status))
    }
}

// `ReadFile` and `WriteFile` would do on a handle that is known to be
// synchronous. On one open for overlapped operation, which safe code can
// hand over (a `std` file opened with `FILE_FLAG_OVERLAPPED`, the pipe of a
// child process), they return while the operation is pending, and the
// system later writes to the buffer and to a status block that are no
// longer there. Like `std`, make the calls they are made of, and wait.

pub(crate) fn read(handle: BorrowedHandle<'_>, buf: &mut [u8]) -> Result<usize> {
    nt_read(handle, buf, None)
}

fn write_file(handle: BorrowedHandle<'_>, buf: &[u8]) -> Result<usize> {
    nt_write(handle, buf, None)
}

/// How many bytes the pipe `handle` writes to has room for, if the system
/// tells.
fn pipe_room(handle: BorrowedHandle<'_>) -> Option<usize> {
    let mut info = FilePipeLocalInformation::default();
    let mut status_block = IoStatusBlock {
        status: 0,
        information: 0,
    };
    // SAFETY: `info` is the structure of this class, of the size given.
    let status = unsafe {
        NtQueryInformationFile(
            handle.as_raw(),
            &raw mut status_block,
            (&raw mut info).cast(),
            size_of::<FilePipeLocalInformation>() as u32,
            FILE_PIPE_LOCAL_INFORMATION,
        )
    };
    (status >= 0).then_some(info.write_quota_available as usize)
}

pub(crate) fn write(handle: BorrowedHandle<'_>, buf: &[u8]) -> Result<usize> {
    let done = write_file(handle, buf)?;
    if done > 0 || buf.is_empty() {
        return Ok(done);
    }
    // Writing nothing of something, with success, is what a pipe that does
    // not wait does when the data does not fit: all of it, as the pipe
    // takes a write whole or not at all. Elsewhere such a pipe takes what
    // fits: write as much as it has room for.
    if let Some(room) = pipe_room(handle)
        && room > 0
        && room < buf.len()
    {
        let done = write_file(handle, &buf[..room])?;
        if done > 0 {
            return Ok(done);
        }
    }
    // No room, as far as the system tells. But it counts what a reader is
    // waiting for as room taken, when that is the very room a write would
    // go to: shorter and shorter writes find out, so that a writer that
    // does not wait and a reader that does cannot starve each other.
    let mut len = buf.len() / 2;
    while len > 0 {
        let done = write_file(handle, &buf[..len])?;
        if done > 0 {
            return Ok(done);
        }
        len /= 2;
    }
    Err(ErrorKind::WouldBlock.into())
}

pub(crate) fn read_at(handle: BorrowedHandle<'_>, buf: &mut [u8], offset: u64) -> Result<usize> {
    nt_read(handle, buf, Some(offset))
}

pub(crate) fn write_at(handle: BorrowedHandle<'_>, buf: &[u8], offset: u64) -> Result<usize> {
    nt_write(handle, buf, Some(offset))
}

// There is no vectored I/O on a synchronous file or pipe handle
// (`ReadFileScatter` wants page-aligned buffers and an unbuffered,
// overlapped handle). Like `std`: transfer the first buffer that is not
// empty, which is a valid short read or write.

pub(crate) fn read_vectored(
    handle: BorrowedHandle<'_>,
    bufs: &mut [IoSliceMut<'_>],
) -> Result<usize> {
    match bufs.iter_mut().find(|buf| !buf.is_empty()) {
        Some(buf) => read(handle, buf),
        None => read(handle, &mut []),
    }
}

pub(crate) fn write_vectored(handle: BorrowedHandle<'_>, bufs: &[IoSlice<'_>]) -> Result<usize> {
    match bufs.iter().find(|buf| !buf.is_empty()) {
        Some(buf) => write(handle, buf),
        None => write(handle, &[]),
    }
}

pub(crate) fn seek(handle: BorrowedHandle<'_>, pos: SeekFrom) -> Result<u64> {
    let (offset, method) = match pos {
        SeekFrom::Start(offset) => (offset as i64, 0),
        SeekFrom::Current(offset) => (offset, 1),
        SeekFrom::End(offset) => (offset, 2),
    };
    let mut pos = 0;
    // SAFETY: `pos` is the `LARGE_INTEGER` the call writes.
    cvt(unsafe { SetFilePointerEx(handle.as_raw(), offset, &raw mut pos, method) })?;
    Ok(pos as u64)
}

pub(crate) fn pipe() -> Result<(OwnedHandle, OwnedHandle)> {
    let mut read = ptr::null_mut();
    let mut write = ptr::null_mut();
    // SAFETY: the two handles are written by the call. Without security
    // attributes they are not inheritable.
    cvt(unsafe { CreatePipe(&raw mut read, &raw mut write, ptr::null(), 0) })?;
    // SAFETY: both handles were just created and are owned by nobody.
    Ok(unsafe { (OwnedHandle::from_raw(read), OwnedHandle::from_raw(write)) })
}

pub(crate) fn duplicate(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,
            0,
            DUPLICATE_SAME_ACCESS,
        )
    })?;
    // SAFETY: the handle was just created.
    Ok(unsafe { OwnedHandle::from_raw(new) })
}

fn std_handle(which: u32) -> Option<BorrowedHandle<'static>> {
    // SAFETY: no memory is involved.
    let handle = unsafe { GetStdHandle(which) };
    // NULL: the process has no such handle. INVALID_HANDLE_VALUE: the call
    // failed.
    if handle.is_null() || handle as isize == -1 {
        return None;
    }
    // SAFETY: nothing is done to the handle here; if the program closes it,
    // the calls made with it fail.
    Some(unsafe { BorrowedHandle::borrow_raw(handle) })
}

pub(crate) fn stdin() -> Option<BorrowedHandle<'static>> {
    std_handle(STD_INPUT_HANDLE)
}

pub(crate) fn stdout() -> Option<BorrowedHandle<'static>> {
    std_handle(STD_OUTPUT_HANDLE)
}

pub(crate) fn stderr() -> Option<BorrowedHandle<'static>> {
    std_handle(STD_ERROR_HANDLE)
}

pub(crate) fn is_terminal(handle: BorrowedHandle<'_>) -> bool {
    let mut mode = 0;
    // SAFETY: `mode` is written by the call, which fails on anything but a
    // console.
    unsafe { GetConsoleMode(handle.as_raw(), &raw mut mode) != 0 }
}

pub(crate) fn set_inheritable(handle: BorrowedHandle<'_>, inheritable: bool) -> Result<()> {
    let flags = if inheritable { HANDLE_FLAG_INHERIT } else { 0 };
    // SAFETY: no memory is involved.
    cvt(unsafe { SetHandleInformation(handle.as_raw(), HANDLE_FLAG_INHERIT, flags) })
}

pub(crate) fn is_inheritable(handle: BorrowedHandle<'_>) -> Result<bool> {
    let mut flags = 0;
    // SAFETY: `flags` is written by the call.
    cvt(unsafe { GetHandleInformation(handle.as_raw(), &raw mut flags) })?;
    Ok(flags & HANDLE_FLAG_INHERIT != 0)
}

pub(crate) fn set_nonblocking(handle: BorrowedHandle<'_>, nonblocking: bool) -> Result<()> {
    // The mode is set as a whole: keep how the pipe is read. A write end
    // may not be allowed to ask, and has nothing to keep.
    let mut state = 0;
    // SAFETY: `state` is written by the call; the other results are not
    // asked for.
    let known = unsafe {
        GetNamedPipeHandleStateW(
            handle.as_raw(),
            &raw mut state,
            ptr::null_mut(),
            ptr::null_mut(),
            ptr::null_mut(),
            ptr::null_mut(),
            0,
        )
    } != 0;
    let mut mode = if known {
        state & PIPE_READMODE_MESSAGE
    } else {
        0
    };
    if nonblocking {
        mode |= PIPE_NOWAIT;
    }
    // SAFETY: `mode` is read by the call; the other settings are left.
    cvt(unsafe {
        SetNamedPipeHandleState(handle.as_raw(), &raw const mode, ptr::null(), ptr::null())
    })
}