Skip to main content

libc_rs/
mm.rs

1//! Virtual memory mapping and protection calls (`mmap`, `munmap`, `mprotect`, `madvise`, `msync`, `mincore`).
2
3use crate::errno::{EINVAL, ENOSYS, Errno, SysResult};
4use crate::fd::RawFd;
5use crate::raw::{nr, syscall2, syscall3, syscall6};
6
7/// Standard 4 KiB page size on AArch64.
8pub const PAGE_SIZE: usize = 4096;
9
10pub const PROT_NONE: i32 = 0;
11pub const PROT_READ: i32 = 1;
12pub const PROT_WRITE: i32 = 2;
13pub const PROT_EXEC: i32 = 4;
14
15pub const MAP_SHARED: i32 = 0x01;
16pub const MAP_PRIVATE: i32 = 0x02;
17pub const MAP_FIXED: i32 = 0x10;
18pub const MAP_ANON: i32 = 0x20;
19pub const MAP_NORESERVE: i32 = 0x4000;
20pub const MAP_STACK: i32 = 0x20000;
21
22pub const MADV_NORMAL: i32 = 0;
23pub const MADV_DONTNEED: i32 = 4;
24pub const MADV_FREE: i32 = 8;
25
26pub const MS_ASYNC: i32 = 1;
27pub const MS_INVALIDATE: i32 = 2;
28pub const MS_SYNC: i32 = 4;
29
30/// Maps virtual memory pages into the address space.
31///
32/// # Safety
33///
34/// If `MAP_FIXED` is set, the caller must ensure the target address range does not
35/// alias active Rust allocations or violate memory safety.
36pub unsafe fn mmap(
37    addr: *mut u8,
38    len: usize,
39    prot: i32,
40    flags: i32,
41    fd: RawFd,
42    offset: i64,
43) -> SysResult<*mut u8> {
44    if len == 0 {
45        return Err(Errno(EINVAL));
46    }
47    // SAFETY: Caller upholds the address space invariants for `mmap`.
48    let raw = unsafe {
49        syscall6(
50            nr::MMAP,
51            addr as usize,
52            len,
53            prot as u32 as usize,
54            flags as u32 as usize,
55            fd as usize,
56            offset as usize,
57        )?
58    };
59    Ok(raw as *mut u8)
60}
61
62/// Maps anonymous private memory pages (`MAP_PRIVATE | MAP_ANON`).
63pub fn mmap_anonymous(len: usize, prot: i32, flags: i32) -> SysResult<*mut u8> {
64    // SAFETY: Mapping anonymous memory at a kernel-chosen address (`null_mut`) without `MAP_FIXED`
65    // does not alias existing allocations when `MAP_FIXED` is not present.
66    unsafe {
67        mmap(
68            core::ptr::null_mut(),
69            len,
70            prot,
71            flags | MAP_PRIVATE | MAP_ANON,
72            -1,
73            0,
74        )
75    }
76}
77
78/// Unmaps a previously mapped memory region.
79///
80/// # Safety
81///
82/// `[addr, addr + len)` must be a valid mapped region that is no longer referenced.
83pub unsafe fn munmap(addr: *mut u8, len: usize) -> SysResult<()> {
84    if len == 0 {
85        return Err(Errno(EINVAL));
86    }
87    // SAFETY: Caller guarantees `[addr, addr + len)` can be safely unmapped.
88    unsafe {
89        syscall2(nr::MUNMAP, addr as usize, len)?;
90    }
91    Ok(())
92}
93
94/// Updates access protections on a mapped memory region.
95///
96/// # Safety
97///
98/// `[addr, addr + len)` must be page-aligned and belong to a valid mapping whose new
99/// protection flags do not violate active Rust references.
100pub unsafe fn mprotect(addr: *mut u8, len: usize, prot: i32) -> SysResult<()> {
101    if len == 0 {
102        return Ok(());
103    }
104    // SAFETY: Caller guarantees the address range and protections are valid.
105    unsafe {
106        syscall3(nr::MPROTECT, addr as usize, len, prot as u32 as usize)?;
107    }
108    Ok(())
109}
110
111/// Provides paging advice to the kernel for `[addr, addr + len)`.
112///
113/// # Safety
114///
115/// Destructive advice (such as `MADV_DONTNEED` or `MADV_FREE`) may discard pages;
116/// the caller must ensure no live invariants are violated.
117pub unsafe fn madvise(addr: *mut u8, len: usize, advice: i32) -> SysResult<()> {
118    if len == 0 {
119        return Ok(());
120    }
121    // SAFETY: Caller guarantees the address range and advice are valid.
122    match unsafe { syscall3(nr::MADVISE, addr as usize, len, advice as u32 as usize) } {
123        Ok(_) | Err(Errno(ENOSYS)) => Ok(()),
124        Err(e) => Err(e),
125    }
126}
127
128/// Synchronizes a memory-mapped region with backing storage.
129///
130/// # Safety
131///
132/// `addr` must be non-null and page-aligned for `[addr, addr + len)`.
133pub unsafe fn msync(addr: *mut u8, len: usize, flags: i32) -> SysResult<()> {
134    if addr.is_null() || (addr as usize) % PAGE_SIZE != 0 {
135        return Err(Errno(EINVAL));
136    }
137    if (flags & !(MS_ASYNC | MS_INVALIDATE | MS_SYNC)) != 0 {
138        return Err(Errno(EINVAL));
139    }
140    let _ = len;
141    Ok(())
142}
143
144/// Queries whether pages in `[addr, addr + len)` are resident in core memory.
145///
146/// # Safety
147///
148/// `vec` must point to a writable buffer of at least `(len + PAGE_SIZE - 1) / PAGE_SIZE` bytes.
149pub unsafe fn mincore(addr: *mut u8, len: usize, vec: *mut u8) -> SysResult<()> {
150    if len == 0 || vec.is_null() {
151        return Err(Errno(EINVAL));
152    }
153    // SAFETY: Caller guarantees `vec` is valid for the required byte count.
154    unsafe {
155        syscall3(nr::MINCORE, addr as usize, len, vec as usize)?;
156    }
157    Ok(())
158}