Skip to main content

kvmtrace/
paging.rs

1//! A software walker for x86 guest page tables.
2//!
3//! MacSim does its own address translation, so a MacSim trace only needs
4//! virtual addresses. We still walk the guest's page tables because:
5//!
6//! 1. instruction bytes live at a *linear* address and must be read from
7//!    guest-*physical* memory;
8//! 2. the extended trace records the guest-physical address of every
9//!    access, for simulators that want it;
10//! 3. a walk that fails tells us, *before* the instruction runs, that an
11//!    access is going to fault.
12//!
13//! The walker understands every paging mode an x86-64 guest can be in:
14//! none, 32-bit (with 4 MiB pages), PAE, 4-level and 5-level.
15//! It reads the tables the same way the CPU does, but does not set
16//! Accessed/Dirty bits and does not model the TLB: it always reflects the
17//! tables as they are in memory right now.
18
19use crate::memory::GuestMemory;
20use crate::state::*;
21
22/// Which page-table format is active.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub enum PagingMode {
25    /// CR0.PG = 0: linear address = physical address.
26    Disabled,
27    /// Classic 2-level 32-bit paging.
28    Bits32,
29    /// 3-level PAE paging.
30    Pae,
31    /// 4-level paging (IA-32e).
32    Level4,
33    /// 5-level paging (CR4.LA57).
34    Level5,
35}
36
37impl PagingMode {
38    /// Works out the paging mode from control registers.
39    pub fn of(s: &CpuState) -> PagingMode {
40        if s.cr0 & CR0_PG == 0 {
41            PagingMode::Disabled
42        } else if s.efer & EFER_LMA != 0 {
43            if s.cr4 & CR4_LA57 != 0 { PagingMode::Level5 } else { PagingMode::Level4 }
44        } else if s.cr4 & CR4_PAE != 0 {
45            PagingMode::Pae
46        } else {
47            PagingMode::Bits32
48        }
49    }
50}
51
52/// The result of a successful walk.
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub struct Translation {
55    /// Guest-physical address of the byte at the linear address.
56    pub physical: u64,
57    /// Size of the page that maps it (4 KiB, 2 MiB, 4 MiB or 1 GiB).
58    pub page_size: u64,
59    /// Writable at every level.
60    pub writable: bool,
61    /// User-accessible at every level.
62    pub user: bool,
63    /// Executable (no NX bit at any level, or NX disabled).
64    pub executable: bool,
65}
66
67/// Why a walk stopped.
68#[derive(Debug, Clone, Copy, PartialEq, Eq)]
69pub enum WalkError {
70    /// A paging-structure entry was not present. `level` is 1 for the PTE,
71    /// 2 for the PDE, and so on.
72    NotPresent {
73        /// Level of the missing entry.
74        level: u8,
75    },
76    /// A paging-structure entry could not be read (its physical address is
77    /// not RAM).
78    Unreadable(u64),
79}
80
81const ADDR_MASK: u64 = 0x000f_ffff_ffff_f000;
82const P: u64 = 1;
83const RW: u64 = 1 << 1;
84const US: u64 = 1 << 2;
85const PS: u64 = 1 << 7;
86const NX: u64 = 1 << 63;
87
88/// Translates one linear address using the paging structures that `state` points at.
89///
90/// # Examples
91///
92/// With paging off, translation is the identity:
93///
94/// ```
95/// use kvmtrace::{memory::MappedMemory, paging::translate, state::CpuState};
96/// let s = CpuState::default(); // CR0.PG = 0
97/// let t = translate(&s, &MappedMemory::new(), 0x1234).unwrap();
98/// assert_eq!(t.physical, 0x1234);
99/// ```
100pub fn translate(state: &CpuState, mem: &dyn GuestMemory, linear: u64) -> Result<Translation, WalkError> {
101    let nxe = state.efer & EFER_NXE != 0;
102    let rd = |a: u64| mem.read_u64(a).map_err(|_| WalkError::Unreadable(a));
103    match PagingMode::of(state) {
104        PagingMode::Disabled => Ok(Translation {
105            physical: linear & state.linear_mask(),
106            page_size: 4096,
107            writable: true,
108            user: true,
109            executable: true,
110        }),
111        PagingMode::Bits32 => {
112            let la = linear & 0xffff_ffff;
113            let rd32 = |a: u64| mem.read_u32(a).map(u64::from).map_err(|_| WalkError::Unreadable(a));
114            let pde = rd32((state.cr3 & 0xffff_f000) + ((la >> 22) << 2))?;
115            if pde & P == 0 {
116                return Err(WalkError::NotPresent { level: 2 });
117            }
118            if pde & PS != 0 && state.cr4 & CR4_PSE != 0 {
119                let base = (pde & 0xffc0_0000) | (((pde >> 13) & 0xff) << 32);
120                return Ok(Translation {
121                    physical: base | (la & 0x3f_ffff),
122                    page_size: 4 << 20,
123                    writable: pde & RW != 0,
124                    user: pde & US != 0,
125                    executable: true,
126                });
127            }
128            let pte = rd32((pde & 0xffff_f000) + (((la >> 12) & 0x3ff) << 2))?;
129            if pte & P == 0 {
130                return Err(WalkError::NotPresent { level: 1 });
131            }
132            Ok(Translation {
133                physical: (pte & 0xffff_f000) | (la & 0xfff),
134                page_size: 4096,
135                writable: pde & pte & RW != 0,
136                user: pde & pte & US != 0,
137                executable: true,
138            })
139        }
140        mode => {
141            // PAE, 4-level and 5-level share one loop; only the top differs.
142            let (mut table, levels) = match mode {
143                PagingMode::Pae => {
144                    let la = linear & 0xffff_ffff;
145                    let pdpte = rd((state.cr3 & 0xffff_ffe0) + ((la >> 30) & 3) * 8)?;
146                    if pdpte & P == 0 {
147                        return Err(WalkError::NotPresent { level: 3 });
148                    }
149                    (pdpte & ADDR_MASK, 2u8)
150                }
151                PagingMode::Level4 => (state.cr3 & ADDR_MASK, 4),
152                _ => (state.cr3 & ADDR_MASK, 5),
153            };
154            let (mut w, mut u, mut x) = (true, true, true);
155            let mut level = levels;
156            loop {
157                let shift = 12 + 9 * (level as u64 - 1);
158                let idx = (linear >> shift) & 0x1ff;
159                let e = rd(table + idx * 8)?;
160                if e & P == 0 {
161                    return Err(WalkError::NotPresent { level });
162                }
163                w &= e & RW != 0;
164                u &= e & US != 0;
165                x &= !(nxe && e & NX != 0);
166                let large = level <= 3 && level >= 2 && e & PS != 0;
167                if level == 1 || large {
168                    let size = 1u64 << shift;
169                    let base = e & ADDR_MASK & !(size - 1);
170                    return Ok(Translation {
171                        physical: base | (linear & (size - 1)),
172                        page_size: size,
173                        writable: w,
174                        user: u,
175                        executable: x,
176                    });
177                }
178                table = e & ADDR_MASK;
179                level -= 1;
180            }
181        }
182    }
183}
184
185/// What kind of access a permission check is for.
186#[derive(Debug, Clone, Copy, PartialEq, Eq)]
187pub enum Intent {
188    /// Data read.
189    Read,
190    /// Data write.
191    Write,
192    /// Instruction fetch.
193    Fetch,
194}
195
196/// Would an access with this `intent` be allowed by `t`?
197///
198/// `implicit_supervisor` marks accesses the CPU makes on its own behalf
199/// (IDT reads, interrupt frames), which are always supervisor accesses.
200/// SMAP/SMEP are honoured. Protection keys are not modelled.
201pub fn permits(state: &CpuState, t: &Translation, intent: Intent, implicit_supervisor: bool) -> bool {
202    let user_access = !implicit_supervisor && state.cpl() == 3;
203    match intent {
204        Intent::Fetch => {
205            if !t.executable {
206                return false;
207            }
208            if user_access {
209                t.user
210            } else {
211                !(t.user && state.cr4 & CR4_SMEP != 0)
212            }
213        }
214        Intent::Read | Intent::Write => {
215            if user_access && !t.user {
216                return false;
217            }
218            if !user_access
219                && t.user
220                && state.cr4 & CR4_SMAP != 0
221                && (implicit_supervisor || state.rflags & RFLAGS_AC == 0)
222            {
223                return false;
224            }
225            if intent == Intent::Write && !t.writable && (user_access || state.cr0 & CR0_WP != 0) {
226                return false;
227            }
228            true
229        }
230    }
231}
232
233/// Reads guest memory at a *linear* address, crossing page boundaries as needed.
234/// Returns the number of bytes actually read (fewer than `buf.len()` if a
235/// later page is not mapped).
236pub fn read_linear(state: &CpuState, mem: &dyn GuestMemory, linear: u64, buf: &mut [u8]) -> usize {
237    let mut done = 0;
238    while done < buf.len() {
239        let la = linear.wrapping_add(done as u64) & state.linear_mask();
240        let Ok(t) = translate(state, mem, la) else { break };
241        let in_page = (4096 - (la & 0xfff)) as usize;
242        let n = in_page.min(buf.len() - done);
243        if mem.read(t.physical, &mut buf[done..done + n]).is_err() {
244            break;
245        }
246        done += n;
247    }
248    done
249}