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
use std::collections::BTreeMap;

use super::Memory;
use crate::addr::Addr;

type Page = Vec<u8>;

/// [`PagedMemory`](crate::memory::PagedMemory) is the implementation of the
/// [`Memory`](crate::Memory) interfaced used by the `riscy` binary.
///
/// Whenever an address is first accessed, it will allocate a 4KiB page containing that address.
/// The pages are stored in a
/// [`BTreeMap`](https://doc.rust-lang.org/stable/std/collections/struct.BTreeMap.html)
/// which making finding the correct page fast and efficient. Each page is represented by contiguous
/// block of memory.
///
/// The full 32-bit address space of a RISC-V machine is 4GiB in size. Using on-demand pages like
/// this means that the host system usually only allocates a bit more memory than it actually uses.
///
/// Once a page is allocated, it is never de-allocated.
///
/// When reading from uninitilized memory, `PagedMemory` will return a value of `0x00` for that byte.
/// This is unrealistic in physical memory, where you get whatever junk the operating system or
/// the hardware had left over. However, getting zeroed-out memory makes it easier to debug
/// when there is a problem.
#[derive(Debug)]
pub struct PagedMemory {
    pages: BTreeMap<Addr, Page>,
}

impl PagedMemory {
    /// Create a new `PagedMemory` with no allocated pages.
    pub fn new() -> PagedMemory {
        PagedMemory { pages: BTreeMap::new() }
    }

    fn page_boundary(addr: Addr) -> Addr {
        Addr::new(u32::from(addr) & 0xffff_f000)
    }

    fn page_offset(addr: Addr) -> usize {
        usize::from(addr) & 0x0000_0fff
    }

    fn page_for(&self, addr: Addr) -> Option<&Page> {
        let page_boundary = PagedMemory::page_boundary(addr);
        self.pages.get(&page_boundary)
    }

    fn page_for_mut(&mut self, addr: Addr) -> &mut Page {
        let page_boundary = PagedMemory::page_boundary(addr);
        if !self.pages.contains_key(&page_boundary) {
            self.pages.insert(page_boundary, vec![0; 4096]);
        }
        self.pages.get_mut(&page_boundary).unwrap()
    }
}

impl Memory for PagedMemory {
    fn store_byte(&mut self, addr: Addr, value: u8) {
        let offset = PagedMemory::page_offset(addr);
        let page = self.page_for_mut(addr);
        page[offset] = value;
    }

    fn load_byte(&self, addr: Addr) -> u8 {
        let offset = PagedMemory::page_offset(addr);
        match self.page_for(addr) {
            Some(page) => (page[offset] & 0x0000_00ff) as u8,
            None => 0,
        }
    }
}