pub fn sys_mmap(
addr: *mut (),
len: usize,
mprot_flags: i32,
map_flags: i32,
fd: i32,
offset: i64,
) -> *mut ()
Expand description
Allocates physical memory for a file, device, or anonymous-file (ie, a file that is only stored in-memory; just a memory allocation for the running process).
Typically, the data in the device (eg, disk) is loaded when the page of memory is accessed. I use the word “typically” because the implementation of the device determines how the data is populated in the physical-page, for instance you could implement the mmap functions for a device that calls out over the network to populate the physical-page when the first-access to the memory occurs (per page).
For anonomyous files: the page of memory being accessed is allocated a physical-page in RAM whenever it is accessed.
NOTE: This is the best function for allocating program memory, and is the most effecient function for loading files when the file-contents are accessed randomly; otherwise, if read sequentially once or written sequentially once, use direct-io (see open(2))
NOTE: Accessing outside of the logically-allocated-range will not result in a physical-page being allocated, to clarify.
§Example
mapping memory (not based on device or file). give it an address you want the mapping to be at, or just leave it blank (99% of the time) then set the memory protection flags and allocation flags, use ANON for in-memory only, use -1 for the file-descriptor, and 0 as the offset.
the minimum flags for map_flags
is one of either SHARED or PRIVATE.
use os_core::{unix::{sys_mmap, sys_munmap}, constants::{map, mprot}};
let mut mapping = sys_mmap(0 as *mut (), 4096, mprot::READ | mprot::WRITE, map::ANON | map::SHARED, -1, 0);
assert!(mapping != map::FAILED);
let mut data = mapping as *mut u8;
unsafe {*(data.offset(4095)) = 0xFF;}
assert_eq!(unsafe {*(data.offset(4095))}, 0xFF);
sys_munmap(mapping, 4096);
// sanity: this would also work -> sys_munmap(data, 4096); <- since it's the same address (data and mapping)