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
//! Tests of what `oscall::mem::linux` says of the memory of the process:
//! its mappings, as `/proc/self/maps` lists them and as the file answers
//! about one address, and which pages are in memory.
//!
//! Under qemu-user the file is the emulator's own account of the memory
//! of the program, and has no `ioctl`: `query` then reads the text, which
//! is the path a kernel before 6.11 takes too.
#![cfg(any(target_os = "linux", target_os = "fullrust"))]

mod common;

use std::os::unix::fs::MetadataExt;

use oscall::ErrorKind;
use oscall::mem::linux::{self, Region, Regions};
use oscall::mem::{self, Mapping, Protection, Sharing};

const RW: Protection = Protection::READ_WRITE;

/// Three pages, of which the middle one is read-only: a region nothing
/// can be merged with, its neighbours being unlike it.
fn three_pages() -> (Mapping, *mut u8) {
    let page = mem::page_size();
    let map = Mapping::anonymous(3 * page, RW).unwrap();
    let middle = map.as_ptr().wrapping_add(page);
    // SAFETY: a page of this mapping, which nothing uses.
    unsafe { mem::protect(middle, page, Protection::READ) }.unwrap();
    (map, middle)
}

#[test]
fn regions() {
    let page = mem::page_size();
    let (_map, middle) = three_pages();
    let here = regions as fn() as *const u8;

    let mut list = Regions::open().unwrap();
    assert!(format!("{list:?}").starts_with("Regions"));
    let mut end = 0;
    let mut count = 0;
    let mut found = (false, false);
    while let Some(region) = list.next().unwrap() {
        count += 1;
        let base = region.base.addr();
        // In ascending order, without overlap, on page boundaries.
        assert!(base >= end, "{region:?}");
        assert!(region.len > 0 && base % page == 0 && region.len % page == 0);
        end = base + region.len;
        if region.inode != 0 {
            assert!(!region.path.is_empty(), "{region:?}");
        }
        if base == middle.addr() {
            found.0 = true;
            assert_eq!(region.len, page, "{region:?}");
            assert_eq!(region.protection, Protection::READ, "{region:?}");
            assert_eq!(region.sharing, Sharing::Private, "{region:?}");
            assert_eq!((region.inode, region.device), (0, (0, 0)), "{region:?}");
            assert!(region.path.is_empty(), "{region:?}");
        }
        if (base..end).contains(&here.addr()) {
            found.1 = true;
            // The code of this program: read and run, from its file.
            let executable = Protection::READ | Protection::EXECUTE;
            assert!(region.protection.contains(executable), "{region:?}");
            assert!(region.path.starts_with(b"/"), "{region:?}");
        }
    }
    assert!(count >= 4 && found == (true, true), "{count} {found:?}");
    // The end is the end.
    assert!(list.next().unwrap().is_none());
}

#[test]
fn query() {
    let page = mem::page_size();
    let (map, middle) = three_pages();
    let mut path = [0u8; 4200];

    // Anywhere in the page, and for the page alone.
    for ptr in [middle, middle.wrapping_add(page - 1)] {
        let region = linux::query(ptr, &mut path).unwrap().unwrap();
        assert_eq!((region.base, region.len), (middle, page), "{region:?}");
        assert_eq!(region.protection, Protection::READ, "{region:?}");
        assert_eq!(region.sharing, Sharing::Private, "{region:?}");
        assert!(region.path.is_empty() && region.inode == 0, "{region:?}");
    }
    // Its neighbours are other regions, which hold it between them.
    let before = linux::query(map.as_ptr(), &mut []).unwrap().unwrap();
    assert_eq!(before.base.addr() + before.len, middle.addr(), "{before:?}");
    assert_eq!(before.protection, RW, "{before:?}");
    let after = linux::query(middle.wrapping_add(page), &mut [])
        .unwrap()
        .unwrap();
    assert_eq!(after.base, middle.wrapping_add(page), "{after:?}");
    // A reservation is a region with no access.
    let reserved = Mapping::reserve(2 * page).unwrap();
    let region = linux::query(reserved.as_ptr(), &mut []).unwrap().unwrap();
    assert_eq!(region.protection, Protection::empty(), "{region:?}");
    // Nothing is mapped at the first page of the address space.
    assert_eq!(linux::query(std::ptr::null(), &mut path), Ok(None));

    // A file, shared, from its second page.
    let dir = common::tmp_dir("mem_linux_query");
    let name = dir.canonicalize().unwrap().join("mapped file");
    std::fs::write(&name, vec![7u8; 3 * page]).unwrap();
    let file = std::fs::OpenOptions::new()
        .read(true)
        .write(true)
        .open(&name)
        .unwrap();
    let shared = Mapping::file(
        &common::handle_of(&file),
        page as u64,
        2 * page,
        RW,
        Sharing::Shared,
    )
    .unwrap();
    let inside = shared.as_ptr().wrapping_add(page + 5);
    let region = linux::query(inside, &mut path).unwrap().unwrap();
    let expected: Region<'_> = region;
    assert_eq!((expected.base, expected.len), (shared.as_ptr(), 2 * page));
    assert_eq!(expected.protection, RW, "{expected:?}");
    assert_eq!(expected.sharing, Sharing::Shared, "{expected:?}");
    assert_eq!(expected.offset, page as u64, "{expected:?}");
    let metadata = std::fs::metadata(&name).unwrap();
    assert_eq!(expected.inode, metadata.ino(), "{expected:?}");
    assert_eq!(expected.path, name.as_os_str().as_encoded_bytes());
    // Without a buffer the path is not asked for; with one that is too
    // short, a byte to spare included, it does not fit.
    let region = linux::query(inside, &mut []).unwrap().unwrap();
    assert!(region.path.is_empty() && region.inode == metadata.ino());
    let len = name.as_os_str().len();
    for short in [1, len - 1, len] {
        let error = linux::query(inside, &mut path[..short]).unwrap_err();
        assert_eq!(
            error.kind(),
            ErrorKind::BufferTooSmall,
            "{short}: {error:?}"
        );
    }
    let region = linux::query(inside, &mut path[..len + 1]).unwrap().unwrap();
    assert_eq!(region.path.len(), len);
    // The list says the same of it.
    let mut list = Regions::open().unwrap();
    let mut listed = false;
    while let Some(region) = list.next().unwrap() {
        if region.base == shared.as_ptr() {
            listed = true;
            assert_eq!(region.len, 2 * page);
            assert_eq!((region.offset, region.inode), (page as u64, metadata.ino()));
            assert_eq!(region.path, name.as_os_str().as_encoded_bytes());
            assert_eq!(region.sharing, Sharing::Shared);
        }
    }
    assert!(listed);
    // The file removed, its name says so.
    std::fs::remove_file(&name).unwrap();
    let region = linux::query(inside, &mut path).unwrap().unwrap();
    assert!(region.path.ends_with(b" (deleted)"), "{region:?}");
}

#[test]
fn resident_pages() {
    let page = mem::page_size();
    let map = Mapping::anonymous(4 * page, RW).unwrap();
    let ptr = map.as_ptr();
    // SAFETY: inside the writable mapping.
    unsafe {
        ptr.write(1);
        ptr.add(2 * page).write(1);
    }
    let mut pages = [0xffu8; 8];
    assert_eq!(linux::resident_pages(ptr, 4 * page, &mut pages), Ok(4));
    // What was written to is there. What was not has no page yet, which
    // an emulator of programs may see otherwise.
    assert_eq!((pages[0], pages[2]), (1, 1), "{pages:?}");
    if common::emulated() {
        assert!(pages[1] <= 1 && pages[3] <= 1, "{pages:?}");
    } else {
        assert_eq!((pages[1], pages[3]), (0, 0), "{pages:?}");
    }
    // Nothing is written past the pages of the range.
    assert_eq!(pages[4..], [0xff; 4]);
    // A length that is not whole pages is rounded up.
    assert_eq!(linux::resident_pages(ptr, page + 1, &mut pages), Ok(2));
    assert_eq!(linux::resident_pages(ptr, 1, &mut pages[..1]), Ok(1));

    let error = linux::resident_pages(ptr, 4 * page, &mut pages[..3]).unwrap_err();
    assert_eq!(error.kind(), ErrorKind::BufferTooSmall, "{error:?}");
    let error = linux::resident_pages(ptr, 0, &mut pages).unwrap_err();
    assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
    let error = linux::resident_pages(ptr.wrapping_add(1), page, &mut pages).unwrap_err();
    assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
    // What is not mapped is in no memory.
    let nowhere = std::ptr::without_provenance::<u8>(page);
    let error = linux::resident_pages(nowhere, page, &mut pages).unwrap_err();
    assert_eq!(error.kind(), ErrorKind::OutOfMemory, "{error:?}");
}