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
//! `mem` on macOS: `mmap` and its family, from `libSystem`.
//!
//! The constants are those of `<sys/mman.h>`; none of these functions has a
//! symbol variant on x86_64 or aarch64.

use core::ffi::{c_char, c_int, c_void};
use core::mem::MaybeUninit;

use crate::mem::macos::Region;
use crate::mem::unix::AccessPattern;
use crate::mem::{Advice, MapOptions, Place, Protection, Sharing};
use crate::sys::{cvt, last_error};
use crate::{AsHandle, BorrowedHandle, ErrorKind, OwnedHandle, Result};

unsafe extern "C" {
    fn getpagesize() -> c_int;
    fn mmap(
        addr: *mut c_void,
        len: usize,
        prot: c_int,
        flags: c_int,
        fd: c_int,
        offset: i64,
    ) -> *mut c_void;
    fn munmap(addr: *mut c_void, len: usize) -> c_int;
    fn mprotect(addr: *mut c_void, len: usize, prot: c_int) -> c_int;
    fn msync(addr: *mut c_void, len: usize, flags: c_int) -> c_int;
    fn madvise(addr: *mut c_void, len: usize, advice: c_int) -> c_int;
    fn mlock(addr: *const c_void, len: usize) -> c_int;
    fn munlock(addr: *const c_void, len: usize) -> c_int;
    // <libkern/OSCacheControl.h>
    fn sys_icache_invalidate(start: *mut c_void, len: usize);
    // <pthread.h>, macOS 11.0 on both architectures.
    fn pthread_jit_write_protect_supported_np() -> c_int;
    fn pthread_jit_write_protect_np(enabled: c_int);
    // <sys/mman.h>: variadic, the mode being its third argument.
    fn shm_open(name: *const c_char, flags: c_int, ...) -> c_int;
    fn shm_unlink(name: *const c_char) -> c_int;
    // <mach/mach_vm.h>
    fn mach_vm_region(
        task: u32,
        address: *mut u64,
        size: *mut u64,
        flavor: c_int,
        info: *mut c_int,
        count: *mut u32,
        object_name: *mut u32,
    ) -> c_int;
    /// What `mach_task_self()` expands to: the port of this task.
    static mach_task_self_: u32;
}

// <sys/fcntl.h>
const O_RDWR: c_int = 0x0002;
const O_CREAT: c_int = 0x0200;
const O_EXCL: c_int = 0x0800;
const F_SETFD: c_int = 2;
const FD_CLOEXEC: c_int = 1;

// <mach/vm_region.h>, <mach/kern_return.h>
const VM_REGION_BASIC_INFO_64: c_int = 9;
/// The length of `vm_region_basic_info_data_64_t` in `int`s: 36 bytes, the
/// structure being packed to 4.
const VM_REGION_BASIC_INFO_COUNT_64: usize = 9;
const KERN_SUCCESS: c_int = 0;
const KERN_INVALID_ADDRESS: c_int = 1;

const MADV_NORMAL: c_int = 0;
const MADV_RANDOM: c_int = 1;
const MADV_SEQUENTIAL: c_int = 2;

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

const MAP_SHARED: c_int = 0x0001;
const MAP_PRIVATE: c_int = 0x0002;
const MAP_FIXED: c_int = 0x0010;
const MAP_NORESERVE: c_int = 0x0040;
const MAP_JIT: c_int = 0x0800;
const MAP_ANON: c_int = 0x1000;
const MAP_FAILED: *mut c_void = !0 as *mut c_void;

const MS_SYNC: c_int = 0x0010;

/// `MapOptionsExt::jit`, in the `extra` of `MapOptions`.
pub(crate) const EXTRA_JIT: u32 = 1;

/// The `mmap` flags of the options that only macOS has.
fn extra(options: &MapOptions) -> c_int {
    if options.extra & EXTRA_JIT != 0 {
        MAP_JIT
    } else {
        0
    }
}

const MADV_WILLNEED: c_int = 3;
const MADV_FREE: c_int = 5;

pub(crate) fn page_size() -> usize {
    // SAFETY: getpagesize takes nothing, cannot fail, and only reads a
    // value the kernel shares with every process.
    unsafe { getpagesize() as usize }
}

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

/// `mmap`, with its result as a `Result`.
///
/// # Safety
///
/// As `mmap`: with `MAP_FIXED`, the range must be the caller's to replace.
unsafe fn map(
    addr: *mut u8,
    len: usize,
    prot: c_int,
    flags: c_int,
    fd: c_int,
    offset: u64,
) -> Result<*mut u8> {
    let Ok(offset) = i64::try_from(offset) else {
        return Err(ErrorKind::InvalidInput.into());
    };
    // SAFETY: the caller's contract.
    let ptr = unsafe { mmap(addr.cast(), len, prot, flags, fd, offset) };
    if ptr == MAP_FAILED {
        Err(last_error())
    } else {
        Ok(ptr.cast())
    }
}

fn prot(protection: Protection) -> c_int {
    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 map_placed(
    place: Place,
    len: usize,
    prot: c_int,
    flags: c_int,
    fd: c_int,
    offset: u64,
) -> Result<*mut u8> {
    match place {
        // SAFETY: a new mapping, wherever the kernel likes.
        Place::Anywhere => unsafe { map(core::ptr::null_mut(), len, prot, flags, fd, offset) },
        Place::At(addr) => {
            // There is no request for an address that fails when it is
            // taken, short of Mach calls that know nothing of files. The
            // address is a hint: the kernel starts looking for free space
            // there, so that a free range is the one it finds.
            // SAFETY: a new mapping, wherever the kernel likes.
            let ptr = unsafe { map(addr as *mut u8, len, prot, flags, fd, offset) }?;
            if ptr.addr() != addr {
                // SAFETY: the mapping was made above and nothing knows it.
                unsafe { munmap(ptr.cast(), 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 { map(addr as *mut u8, 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 {
                    map(
                        addr as *mut u8,
                        len,
                        PROT_NONE,
                        MAP_PRIVATE | MAP_ANON | MAP_NORESERVE | MAP_FIXED,
                        -1,
                        0,
                    )
                };
            }
            result
        }
    }
}

pub(crate) fn map_anonymous(len: usize, options: &MapOptions) -> Result<*mut u8> {
    map_placed(
        options.place,
        len,
        prot(options.protection),
        MAP_PRIVATE | MAP_ANON | 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,
    };
    map_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_placed(
        options.place,
        len,
        PROT_NONE,
        MAP_PRIVATE | MAP_ANON | MAP_NORESERVE | extra(options),
        -1,
        0,
    )
}

/// # 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.
    cvt(unsafe { munmap(ptr.cast(), 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.
    cvt(unsafe { mprotect(ptr.cast(), 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.
    // 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 in one atomic step.
    // SAFETY: the caller owns the range, which MAP_FIXED replaces.
    unsafe {
        map(
            ptr,
            len,
            PROT_NONE,
            MAP_PRIVATE | MAP_ANON | 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.
    cvt(unsafe { madvise(ptr.cast(), 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.
    cvt(unsafe { msync(ptr.cast_mut().cast(), 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.
    cvt(unsafe { mlock(ptr.cast(), len) }).map(drop)
}

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

/// # Safety
///
/// The range must be readable memory.
pub(crate) unsafe fn flush_instruction_cache(ptr: *const u8, len: usize) -> Result<()> {
    // SAFETY: the caller's contract. The function does nothing on Intel
    // processors, and cannot fail.
    unsafe { sys_icache_invalidate(ptr.cast_mut().cast(), len) };
    Ok(())
}

pub(crate) fn jit_write_protect_supported() -> bool {
    // SAFETY: the function takes nothing and only reads what the system
    // knows of the processor.
    unsafe { pthread_jit_write_protect_supported_np() != 0 }
}

/// # Safety
///
/// The thread must use the `MAP_JIT` mappings as the new state allows.
pub(crate) unsafe fn jit_write_protect(protect: bool) {
    // SAFETY: the caller's contract.
    unsafe { pthread_jit_write_protect_np(protect as c_int) };
}

pub(crate) fn create_shared(len: usize) -> Result<OwnedHandle> {
    // POSIX shared memory needs a name, of 31 bytes at most here; this one
    // is taken out of the namespace as soon as the object exists, and 64
    // random bits keep it from meeting another meanwhile (O_EXCL fails if
    // it does).
    let mut random = [MaybeUninit::<u8>::uninit(); 8];
    crate::sys::rand::fill(&mut random)?;
    let mut name = *b"/oscall-0000000000000000\0";
    for (index, byte) in random.iter().enumerate() {
        // SAFETY: `fill` succeeded, and so initialised every byte.
        let byte = unsafe { byte.assume_init() };
        name[8 + 2 * index] = b"0123456789abcdef"[(byte >> 4) as usize];
        name[9 + 2 * index] = b"0123456789abcdef"[(byte & 15) as usize];
    }
    let name = name.as_ptr().cast::<c_char>();
    // SAFETY: the name is NUL-terminated, and the mode is passed as the
    // `int` a variadic function receives.
    let fd = cvt(unsafe { shm_open(name, O_RDWR | O_CREAT | O_EXCL, 0o600 as c_int) })?;
    // SAFETY: the descriptor was just made and belongs to nothing else.
    let handle = unsafe { OwnedHandle::from_raw(fd) };
    // SAFETY: the name is the one the object was just created under.
    unsafe { shm_unlink(name) };
    // SAFETY: setting a flag of a descriptor this function owns.
    cvt(unsafe { crate::sys::io::fcntl(fd, F_SETFD, FD_CLOEXEC) })?;
    // A new object is empty, and can be given its size once.
    crate::sys::fs::set_len(handle.as_handle(), len as u64)?;
    Ok(handle)
}

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.
    cvt(unsafe { madvise(ptr.cast_mut().cast(), len, advice) }).map(drop)
}

/// The protection a `vm_prot_t` stands for: its bits are those of `mmap`.
fn protection(prot: c_int) -> Protection {
    let mut protection = Protection::NONE;
    if prot & PROT_READ != 0 {
        protection |= Protection::READ;
    }
    if prot & PROT_WRITE != 0 {
        protection |= Protection::WRITE;
    }
    if prot & PROT_EXEC != 0 {
        protection |= Protection::EXECUTE;
    }
    protection
}

pub(crate) fn query(ptr: *const u8) -> Result<Option<Region>> {
    let mut address = ptr.addr() as u64;
    let mut size = 0u64;
    // `vm_region_basic_info_64`: protection, max_protection, then fields
    // that are not used here.
    let mut info = [0 as c_int; VM_REGION_BASIC_INFO_COUNT_64];
    let mut count = VM_REGION_BASIC_INFO_COUNT_64 as u32;
    let mut object_name = 0u32;
    // SAFETY: the call fills `info`, whose length in `int`s it is told, and
    // the three other values; the port of this task is always valid.
    let result = unsafe {
        mach_vm_region(
            mach_task_self_,
            &mut address,
            &mut size,
            VM_REGION_BASIC_INFO_64,
            info.as_mut_ptr(),
            &mut count,
            &mut object_name,
        )
    };
    match result {
        KERN_SUCCESS => {}
        // Nothing is mapped at the address nor above it.
        KERN_INVALID_ADDRESS => return Ok(None),
        // A Mach error is not an `errno`.
        _ => return Err(ErrorKind::Other.into()),
    }
    // The call looks upwards for a region: one that starts above the
    // address is not one that holds it.
    if address > ptr.addr() as u64 {
        return Ok(None);
    }
    Ok(Some(Region {
        base: ptr.with_addr(address as usize).cast_mut(),
        len: size as usize,
        protection: protection(info[0]),
        max_protection: protection(info[1]),
    }))
}