1 个不稳定版本

0.1.0 2024年7月26日

内存管理 中排名 #132

Download history 121/week @ 2024-07-22 133/week @ 2024-07-29 45/week @ 2024-08-05

每月 299 次下载

GPL-3.0-or-later OR Apache-2…

23KB
419 代码行

memory_set

Crates.io Docs.rs CI

内存映射的数据结构和操作。

它有助于实现 mmapmunmap

示例

use memory_addr::{va, va_range, VirtAddr};
use memory_set::{MappingBackend, MemoryArea, MemorySet};

const MAX_ADDR: usize = 0x10000;

/// A mock memory flags.
type MockFlags = u8;
/// A mock page table, which is a simple array that maps addresses to flags.
type MockPageTable = [MockFlags; MAX_ADDR];

/// A mock mapping backend that manipulates the page table on `map` and `unmap`.
#[derive(Clone)]
struct MockBackend;

let mut pt = [0; MAX_ADDR];
let mut memory_set = MemorySet::<MockFlags, MockPageTable, MockBackend>::new();

// Map [0x1000..0x5000).
memory_set.map(
    /* area: */ MemoryArea::new(va!(0x1000), 0x4000, 1, MockBackend),
    /* page_table: */ &mut pt,
    /* unmap_overlap */ false,
).unwrap();
// Unmap [0x2000..0x4000), will split the area into two parts.
memory_set.unmap(va!(0x2000), 0x2000, &mut pt).unwrap();

let areas = memory_set.iter().collect::<Vec<_>>();
assert_eq!(areas.len(), 2);
assert_eq!(areas[0].va_range(), va_range!(0x1000..0x2000));
assert_eq!(areas[1].va_range(), va_range!(0x4000..0x5000));

// Underlying operations to do when manipulating mappings.
impl MappingBackend<MockFlags, MockPageTable> for MockBackend {
    fn map(&self, start: VirtAddr, size: usize, flags: MockFlags, pt: &mut MockPageTable) -> bool {
        for entry in pt.iter_mut().skip(start.as_usize()).take(size) {
            if *entry != 0 {
                return false;
            }
            *entry = flags;
        }
        true
    }

    fn unmap(&self, start: VirtAddr, size: usize, pt: &mut MockPageTable) -> bool {
        for entry in pt.iter_mut().skip(start.as_usize()).take(size) {
            if *entry == 0 {
                return false;
            }
            *entry = 0;
        }
        true
    }
}

依赖关系

~21KB