oscall 0.0.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
//! `mem` on Linux and fullrust: `mmap` and its family, as raw system calls.
//!
//! The constants are those of `include/uapi/asm-generic/mman-common.h`,
//! `asm-generic/mman.h` and `linux/mman.h`, which every architecture oscall
//! supports uses unchanged.

use core::sync::atomic::{AtomicUsize, Ordering};

use crate::mem::linux::{Advice as LinuxAdvice, LockAll};
use crate::mem::unix::AccessPattern;
use crate::mem::{Advice, MapOptions, Place, Protection, Sharing};
use crate::sys::syscall;
use crate::{AsHandle, BorrowedHandle, ErrorKind, OwnedHandle, Result};

const PROT_NONE: usize = 0;
const PROT_READ: usize = 1;
const PROT_WRITE: usize = 2;
const PROT_EXEC: usize = 4;

const MAP_SHARED: usize = 0x01;
const MAP_PRIVATE: usize = 0x02;
const MAP_FIXED: usize = 0x10;
const MAP_ANONYMOUS: usize = 0x20;
const MAP_NORESERVE: usize = 0x4000;
const MAP_FIXED_NOREPLACE: usize = 0x10_0000;

const MS_SYNC: usize = 4;

const MAP_POPULATE: usize = 0x8000;
const MAP_HUGETLB: usize = 0x4_0000;

const MADV_NORMAL: usize = 0;
const MADV_RANDOM: usize = 1;
const MADV_SEQUENTIAL: usize = 2;
const MADV_WILLNEED: usize = 3;
const MADV_FREE: usize = 8;
const MADV_DONTFORK: usize = 10;
const MADV_DOFORK: usize = 11;
const MADV_HUGEPAGE: usize = 14;
const MADV_NOHUGEPAGE: usize = 15;
const MADV_DONTDUMP: usize = 16;
const MADV_DODUMP: usize = 17;
const MADV_POPULATE_READ: usize = 22;
const MADV_POPULATE_WRITE: usize = 23;

const MLOCK_ONFAULT: usize = 1;
const MCL_CURRENT: usize = 1;
const MCL_FUTURE: usize = 2;
const MCL_ONFAULT: usize = 4;

/// `include/uapi/linux/memfd.h`
const MFD_CLOEXEC: usize = 1;

/// The options of `mem::linux::MapOptionsExt`, in the `extra` of
/// `MapOptions`.
pub(crate) const EXTRA_POPULATE: u32 = 1;
pub(crate) const EXTRA_HUGE_TLB: u32 = 2;
pub(crate) const EXTRA_NO_RESERVE: u32 = 4;

/// The `mmap` flags of the options that only Linux has.
fn extra(options: &MapOptions) -> usize {
    let mut flags = 0;
    if options.extra & EXTRA_POPULATE != 0 {
        flags |= MAP_POPULATE;
    }
    if options.extra & EXTRA_HUGE_TLB != 0 {
        flags |= MAP_HUGETLB;
    }
    if options.extra & EXTRA_NO_RESERVE != 0 {
        flags |= MAP_NORESERVE;
    }
    flags
}

const MREMAP_MAYMOVE: usize = 1;

/// `__ARM_NR_cacheflush` (`arch/arm/include/uapi/asm/unistd.h`): the second
/// of the system calls private to arm, which start at 0x0f0000.
#[cfg(target_arch = "arm")]
const ARM_NR_CACHEFLUSH: usize = 0x0f_0002;

/// The smallest and the largest page size of the architectures supported.
const MIN_PAGE_SIZE: usize = 1 << 12;
const MAX_PAGE_SIZE: usize = 1 << 16;

/// The page size, once known: it cannot change while the process runs.
static PAGE_SIZE: AtomicUsize = AtomicUsize::new(0);

pub(crate) fn page_size() -> usize {
    match PAGE_SIZE.load(Ordering::Relaxed) {
        0 => {
            // Racing threads find the same value.
            let size = auxv_page_size()
                .or_else(probe_page_size)
                .unwrap_or(MIN_PAGE_SIZE);
            PAGE_SIZE.store(size, Ordering::Relaxed);
            size
        }
        size => size,
    }
}

pub(crate) fn allocation_granularity() -> usize {
    page_size()
}

/// The page size the kernel gave the process at startup, in the auxiliary
/// vector.
fn auxv_page_size() -> Option<usize> {
    crate::sys::auxv::get(crate::sys::auxv::AT_PAGESZ).filter(|size| size.is_power_of_two())
}

/// The page size found by experiment, for when `/proc` is not there (a
/// chroot, a sandbox, a process that is not dumpable): the kernel refuses to
/// change the protection of a range that does not start on a page boundary,
/// so the smallest power of two that it accepts as an offset into a mapping
/// is the size of a page.
fn probe_page_size() -> Option<usize> {
    let len = 2 * MAX_PAGE_SIZE;
    // SAFETY: a new mapping, wherever the kernel likes.
    let base = unsafe {
        mmap(
            0,
            len,
            PROT_NONE,
            MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE,
            -1,
            0,
        )
    }
    .ok()? as usize;
    let mut found = None;
    let mut size = MIN_PAGE_SIZE;
    while size <= MAX_PAGE_SIZE {
        // SAFETY: the range is inside the mapping made above, which nothing
        // else knows of, and its protection does not change.
        if unsafe { syscall!(MPROTECT, base + size, size, PROT_NONE) }.is_ok() {
            found = Some(size);
            break;
        }
        size <<= 1;
    }
    // SAFETY: unmapping the mapping made above.
    let _ = unsafe { syscall!(MUNMAP, base, len) };
    found
}

/// `mmap`, with a 64-bit offset on every target.
///
/// # Safety
///
/// As `mmap`: with `MAP_FIXED`, the range must be the caller's to replace.
unsafe fn mmap(
    addr: usize,
    len: usize,
    prot: usize,
    flags: usize,
    fd: i32,
    offset: u64,
) -> Result<*mut u8> {
    // 32-bit targets only have `mmap2`, whose offset is in units of 4096
    // bytes whatever the page size, which lets it reach 2^44 bytes.
    #[cfg(target_pointer_width = "32")]
    let ret = {
        let units = offset >> 12;
        if offset & 0xfff != 0 || units > u32::MAX as u64 {
            return Err(ErrorKind::InvalidInput.into());
        }
        // SAFETY: the caller's contract.
        unsafe { syscall!(MMAP2, addr, len, prot, flags, fd, units) }
    };
    #[cfg(target_pointer_width = "64")]
    // SAFETY: the caller's contract.
    let ret = unsafe { syscall!(MMAP, addr, len, prot, flags, fd, offset) };
    ret.map(|addr| addr as *mut u8)
}

fn prot(protection: Protection) -> usize {
    let mut prot = PROT_NONE;
    if protection.contains(Protection::READ) {
        prot |= PROT_READ;
    }
    if protection.contains(Protection::WRITE) {
        prot |= PROT_WRITE;
    }
    if protection.contains(Protection::EXECUTE) {
        prot |= PROT_EXEC;
    }
    prot
}

/// `mmap` where `place` says.
fn mmap_placed(
    place: Place,
    len: usize,
    prot: usize,
    flags: usize,
    fd: i32,
    offset: u64,
) -> Result<*mut u8> {
    match place {
        // SAFETY: a new mapping, wherever the kernel likes.
        Place::Anywhere => unsafe { mmap(0, len, prot, flags, fd, offset) },
        Place::At(addr) => {
            // SAFETY: a new mapping, that replaces nothing: the kernel
            // refuses a range that is not free (EEXIST).
            let ptr = unsafe { mmap(addr, len, prot, flags | MAP_FIXED_NOREPLACE, fd, offset) }?;
            if ptr.addr() != addr {
                // A kernel older than 4.17, or an emulator, that does not
                // know the flag: the address was a hint, and not followed.
                // SAFETY: the mapping was made above and nothing knows it.
                let _ = unsafe { syscall!(MUNMAP, ptr, len) };
                return Err(ErrorKind::AlreadyExists.into());
            }
            Ok(ptr)
        }
        Place::In(addr) => {
            // SAFETY: the caller of `MapOptions::in_placeholder` owns the
            // range, which MAP_FIXED replaces.
            let result = unsafe { mmap(addr, len, prot, flags | MAP_FIXED, fd, offset) };
            if result.is_err() {
                // The kernel refuses nearly everything before it touches
                // the range; in case it did not, make it a placeholder
                // again rather than leave a hole for others to fall in.
                // SAFETY: as above.
                let _ = unsafe {
                    mmap(
                        addr,
                        len,
                        PROT_NONE,
                        MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE | MAP_FIXED,
                        -1,
                        0,
                    )
                };
            }
            result
        }
    }
}

pub(crate) fn map_anonymous(len: usize, options: &MapOptions) -> Result<*mut u8> {
    mmap_placed(
        options.place,
        len,
        prot(options.protection),
        MAP_PRIVATE | MAP_ANONYMOUS | extra(options),
        -1,
        0,
    )
}

pub(crate) fn map_file(
    file: BorrowedHandle<'_>,
    offset: u64,
    len: usize,
    sharing: Sharing,
    options: &MapOptions,
) -> Result<*mut u8> {
    let flags = match sharing {
        Sharing::Shared => MAP_SHARED,
        Sharing::Private => MAP_PRIVATE,
    };
    mmap_placed(
        options.place,
        len,
        prot(options.protection),
        flags | extra(options),
        file.as_raw(),
        offset,
    )
}

/// A placeholder is a reservation: any mapping can be mapped over.
pub(crate) fn reserve(len: usize, options: &MapOptions, _placeholder: bool) -> Result<*mut u8> {
    // MAP_NORESERVE keeps the mapping out of the kernel's memory accounting
    // until it is committed.
    mmap_placed(
        options.place,
        len,
        PROT_NONE,
        MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE | extra(options),
        -1,
        0,
    )
}

pub(crate) fn create_shared(len: usize) -> Result<OwnedHandle> {
    // The name only shows in `/proc`, and need not be unique.
    // SAFETY: the name is NUL-terminated; the call makes a descriptor and
    // nothing else.
    let fd = unsafe { syscall!(MEMFD_CREATE, c"oscall".as_ptr(), MFD_CLOEXEC) }?;
    // SAFETY: the descriptor was just made and belongs to nothing else.
    let handle = unsafe { OwnedHandle::from_raw(fd as i32) };
    // A new memory file is empty.
    crate::sys::fs::set_len(handle.as_handle(), len as u64)?;
    Ok(handle)
}

/// # Safety
///
/// The range must be a whole mapping that nothing uses afterwards.
pub(crate) unsafe fn unmap(ptr: *mut u8, len: usize) -> Result<()> {
    // SAFETY: the caller's contract.
    unsafe { syscall!(MUNMAP, ptr, len) }.map(drop)
}

/// # Safety
///
/// The range must be the caller's, and the new protection must suit those
/// who use it.
pub(crate) unsafe fn protect(ptr: *mut u8, len: usize, protection: Protection) -> Result<()> {
    // SAFETY: the caller's contract.
    unsafe { syscall!(MPROTECT, ptr, len, prot(protection)) }.map(drop)
}

/// # Safety
///
/// As [`protect`].
pub(crate) unsafe fn commit(ptr: *mut u8, len: usize, protection: Protection) -> Result<()> {
    // A reservation is a mapping like any other, only inaccessible: the
    // kernel provides (and accounts for) memory once it can be written.
    // SAFETY: the caller's contract.
    unsafe { protect(ptr, len, protection) }
}

/// # Safety
///
/// The range must be anonymous memory of the caller's that nothing uses
/// afterwards.
pub(crate) unsafe fn decommit(ptr: *mut u8, len: usize) -> Result<()> {
    // Mapping over the range frees its pages and takes it out of the
    // memory accounting in one atomic step.
    // SAFETY: the caller owns the range, which MAP_FIXED replaces.
    unsafe {
        mmap(
            ptr as usize,
            len,
            PROT_NONE,
            MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE | MAP_FIXED,
            -1,
            0,
        )
    }
    .map(drop)
}

/// # Safety
///
/// The range must be the caller's, with contents nothing relies on if they
/// are discarded.
pub(crate) unsafe fn advise(ptr: *mut u8, len: usize, advice: Advice) -> Result<()> {
    let advice = match advice {
        Advice::WillNeed => MADV_WILLNEED,
        Advice::Discard => MADV_FREE,
    };
    // SAFETY: the caller's contract.
    unsafe { syscall!(MADVISE, ptr, len, advice) }.map(drop)
}

pub(crate) fn flush(ptr: *const u8, len: usize, _file: BorrowedHandle<'_>) -> Result<()> {
    // SAFETY: msync only writes pages to their file; a range that is not
    // mapped makes it fail.
    unsafe { syscall!(MSYNC, ptr, len, MS_SYNC) }.map(drop)
}

pub(crate) fn lock(ptr: *const u8, len: usize) -> Result<()> {
    // SAFETY: locking changes nothing a program can observe in its memory; a
    // range that is not mapped makes it fail.
    unsafe { syscall!(MLOCK, ptr, len) }.map(drop)
}

pub(crate) fn unlock(ptr: *const u8, len: usize) -> Result<()> {
    // SAFETY: as `lock`.
    unsafe { syscall!(MUNLOCK, ptr, len) }.map(drop)
}

/// # Safety
///
/// The range must be a whole mapping, of which nothing uses the old address
/// if it moves nor the end if it shrinks.
pub(crate) unsafe fn remap(
    ptr: *mut u8,
    old_len: usize,
    new_len: usize,
    may_move: bool,
) -> Result<*mut u8> {
    let flags = if may_move { MREMAP_MAYMOVE } else { 0 };
    // SAFETY: the caller's contract.
    unsafe { syscall!(MREMAP, ptr, old_len, new_len, flags) }.map(|addr| addr as *mut u8)
}

pub(crate) fn huge_pages(ptr: *const u8, len: usize, enable: bool) -> Result<()> {
    let advice = if enable {
        MADV_HUGEPAGE
    } else {
        MADV_NOHUGEPAGE
    };
    // SAFETY: the hint changes how the kernel backs the range, not its
    // contents; a range that is not mapped makes it fail.
    unsafe { syscall!(MADVISE, ptr, len, advice) }.map(drop)
}

pub(crate) fn advise_linux(ptr: *const u8, len: usize, advice: LinuxAdvice) -> Result<()> {
    let advice = match advice {
        LinuxAdvice::DontDump => MADV_DONTDUMP,
        LinuxAdvice::DoDump => MADV_DODUMP,
        LinuxAdvice::DontFork => MADV_DONTFORK,
        LinuxAdvice::DoFork => MADV_DOFORK,
        LinuxAdvice::PopulateRead => MADV_POPULATE_READ,
        LinuxAdvice::PopulateWrite => MADV_POPULATE_WRITE,
    };
    // SAFETY: none of these changes the contents of the range; a range that
    // is not mapped makes the call fail.
    unsafe { syscall!(MADVISE, ptr, len, advice) }.map(drop)
}

pub(crate) fn advise_access(ptr: *const u8, len: usize, pattern: AccessPattern) -> Result<()> {
    let advice = match pattern {
        AccessPattern::Normal => MADV_NORMAL,
        AccessPattern::Sequential => MADV_SEQUENTIAL,
        AccessPattern::Random => MADV_RANDOM,
    };
    // SAFETY: the hint changes how the kernel reads ahead, not the contents
    // of the range; a range that is not mapped makes the call fail.
    unsafe { syscall!(MADVISE, ptr, len, advice) }.map(drop)
}

pub(crate) fn lock_on_fault(ptr: *const u8, len: usize) -> Result<()> {
    // SAFETY: as `lock`.
    unsafe { syscall!(MLOCK2, ptr, len, MLOCK_ONFAULT) }.map(drop)
}

pub(crate) fn lock_all(what: LockAll) -> Result<()> {
    let mut flags = 0;
    if what.contains(LockAll::CURRENT) {
        flags |= MCL_CURRENT;
    }
    if what.contains(LockAll::FUTURE) {
        flags |= MCL_FUTURE;
    }
    if what.contains(LockAll::ON_FAULT) {
        flags |= MCL_ONFAULT;
    }
    // SAFETY: locking changes nothing a program can observe in its memory.
    unsafe { syscall!(MLOCKALL, flags) }.map(drop)
}

pub(crate) fn unlock_all() -> Result<()> {
    // SAFETY: as `lock_all`.
    unsafe { syscall!(MUNLOCKALL) }.map(drop)
}

/// # Safety
///
/// The range must be readable memory.
pub(crate) unsafe fn flush_instruction_cache(ptr: *const u8, len: usize) -> Result<()> {
    let start = ptr.addr();
    // The portable layer checked that the range does not wrap.
    let end = start + len;
    // x86 keeps its instruction cache coherent by itself.
    #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
    let _ = (start, end);

    // The kernel leaves cache maintenance to user space (and emulates it
    // where the cores of a machine disagree): this is what the `__clear_cache`
    // of the C runtimes does.
    #[cfg(target_arch = "aarch64")]
    // SAFETY: reading CTR_EL0 has no effect; `dc cvau` and `ic ivau` take
    // the address of a line of mapped memory, which the caller guarantees,
    // and change no state a program can observe but the caches.
    unsafe {
        use core::arch::asm;

        let ctr: u64;
        asm!("mrs {}, ctr_el0", out(reg) ctr, options(nomem, nostack, preserves_flags));
        // The line sizes are given as log2 of a number of 4-byte words.
        let data_line = 4usize << ((ctr >> 16) & 0xf);
        let code_line = 4usize << (ctr & 0xf);
        // IDC: the data cache need not be cleaned for instructions to be
        // seen.
        if ctr & (1 << 28) == 0 {
            let mut line = start & !(data_line - 1);
            while line < end {
                asm!("dc cvau, {}", in(reg) line, options(nostack, preserves_flags));
                line += data_line;
            }
            asm!("dsb ish", options(nostack, preserves_flags));
        }
        // DIC: the instruction cache need not be invalidated.
        if ctr & (1 << 29) == 0 {
            let mut line = start & !(code_line - 1);
            while line < end {
                asm!("ic ivau, {}", in(reg) line, options(nostack, preserves_flags));
                line += code_line;
            }
            asm!("dsb ish", options(nostack, preserves_flags));
        }
        asm!("isb", options(nostack, preserves_flags));
    }

    // arm cannot do it from user space: the kernel has a private system
    // call for it, `cacheflush(start, end, 0)`.
    #[cfg(target_arch = "arm")]
    // SAFETY: the call touches the caches only.
    crate::sys::check(unsafe { crate::sys::arch::syscall3(ARM_NR_CACHEFLUSH, start, end, 0) })?;

    // Nor can RISC-V; flags of 0 flush for every thread of the process.
    #[cfg(any(target_arch = "riscv32", target_arch = "riscv64"))]
    // SAFETY: the call touches the caches only.
    unsafe { syscall!(RISCV_FLUSH_ICACHE, start, end, 0) }?;

    Ok(())
}

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

    #[test]
    fn page_size_sources_agree() {
        let probed = probe_page_size().unwrap();
        assert!(probed.is_power_of_two());
        assert!((MIN_PAGE_SIZE..=MAX_PAGE_SIZE).contains(&probed));
        assert_eq!(page_size(), probed);
        // `/proc` is mounted wherever the tests run.
        assert_eq!(auxv_page_size(), Some(probed));
    }
}