fix(compiler): fault system-mode accesses outside the guest's ranges before they reach Stela's window
This commit is contained in:
1 parent
9cea8b6199
commit
a93f4307f4
18 files changed
+777
-70
No files matched your search
@@ -2,7 +2,9 @@
|
||||
//! precise native faults, the local APIC timer and the TSC counter.
|
||||
//!
|
||||
//! Shadow roots are PML5 pages whose entry 0 and 511 hold the guest's two
|
||||
//! halves and whose entry 64 is the shared window. There is one root per
|
||||
//! halves and whose entry 64 is the shared window, which native code's
|
||||
//! guest range checks keep every guest access out of; no other entry is
|
||||
//! ever mapped, which those checks rely on. There is one root per
|
||||
//! permission view (EL0, EL1, EL1 with PAN, GL1), filled on demand by the #PF
|
||||
//! handler from the software walk of the guest's tables, a window of the
|
||||
//! guest leaf per fault. Each half takes its tables from its own part of the
|
||||
|
||||
@@ -808,6 +808,82 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// Every access of a system-mode block, in a clean-load region or not,
|
||||
/// checks its address against the guest's ranges before it is made;
|
||||
/// process blocks make no such check.
|
||||
#[test]
|
||||
fn system_mode_blocks_check_every_access_against_the_guest_ranges() {
|
||||
use crate::x86_64::GUEST_RANGE_CHECK;
|
||||
let count = |code: &[u8]| {
|
||||
code.windows(GUEST_RANGE_CHECK.len())
|
||||
.filter(|bytes| *bytes == GUEST_RANGE_CHECK)
|
||||
.count()
|
||||
};
|
||||
let compile = |words: &[u32], profile, plan: fn(CompilationPlan) -> CompilationPlan| {
|
||||
let source: Vec<u8> = words.iter().copied().flat_map(u32::to_le_bytes).collect();
|
||||
CompilationPlan::new(
|
||||
&source,
|
||||
GuestAddress(0x1000),
|
||||
profile,
|
||||
crate::TargetCpu::detect(),
|
||||
)
|
||||
.map(plan)
|
||||
.and_then(CompilationPlan::compile)
|
||||
.unwrap()
|
||||
.native
|
||||
.x86_64_code
|
||||
};
|
||||
// ldr w0, [x1]; add w0, w0, #1; ldr x0, [x1, #8]; ldp w2, w3, [x1];
|
||||
// ldr h0, [x1, x2]; ld1 {v0.4s}, [x1]; ldr x4, <literal>; ldadd x4,
|
||||
// x5, [x1]; ldar w6, [x1]; stlr w6, [x1]; ldnp x8, x9, [x1];
|
||||
// str x0, [x1]; ldr q0, [x1]; stp q0, q1, [x1]; prfm pldl1keep, [x1]
|
||||
let words = [
|
||||
0xb940_0020_u32,
|
||||
0x1100_0400,
|
||||
0xf940_0420,
|
||||
0x2940_0c22,
|
||||
0x7c62_6820,
|
||||
0x4c40_7820,
|
||||
0x5800_0084,
|
||||
0xf824_0025,
|
||||
0x88df_fc26,
|
||||
0x889f_fc26,
|
||||
0xa840_2428,
|
||||
0xf900_0020,
|
||||
0x3dc0_0020,
|
||||
0xad00_0420,
|
||||
0xf980_0020,
|
||||
];
|
||||
// Alone, each access checks, but the prefetch, which never faults.
|
||||
for (index, word) in words.into_iter().enumerate() {
|
||||
let alone = compile(&[word], BlockProfile::SystemModeV1, |plan| plan);
|
||||
assert_eq!(
|
||||
count(&alone),
|
||||
usize::from(![1, 14].contains(&index)),
|
||||
"{word:#x}"
|
||||
);
|
||||
}
|
||||
// Together, an immediate-offset access through X1 after another
|
||||
// needs none (`x86_64::guest_range`): the SIMD register offset,
|
||||
// which forgets every base, makes the LD1 check again, and the
|
||||
// literal always checks.
|
||||
let system = compile(&words, BlockProfile::SystemModeV1, |plan| plan);
|
||||
assert_eq!(count(&system), 4);
|
||||
assert_eq!(
|
||||
count(&compile(&words, BlockProfile::Ordinary, |plan| plan)),
|
||||
0
|
||||
);
|
||||
// DC ZVA and DC CVAC completed natively check Xt.
|
||||
let zero = compile(&[0xd50b_7423], BlockProfile::SystemModeV1, |plan| {
|
||||
plan.with_zero_block(Some(64)).unwrap()
|
||||
});
|
||||
let clean = compile(&[0xd50b_7a20], BlockProfile::SystemModeV1, |plan| {
|
||||
plan.with_cache_clean(crate::x86_64::cache_clean::Operations::ALL)
|
||||
.unwrap()
|
||||
});
|
||||
assert_eq!((count(&zero), count(&clean)), (1, 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn system_mode_blocks_check_sctlr_a_and_the_ordered_granule_when_asked() {
|
||||
// ldr x0, [x1, #8]; ldp w2, w3, [x1]; ldr h0, [x1, x2]; ld1 {v0.4s},
|
||||
@@ -1130,7 +1206,8 @@ mod tests {
|
||||
}
|
||||
// Ordinary-only prefixes use the ordinary emitter and its regions,
|
||||
// which settle the frame before every access and exit, except under
|
||||
// SCTLR_ELx.A, whose checks their loads lack.
|
||||
// SCTLR_ELx.A, whose checks their loads lack, with each access's
|
||||
// guest range check.
|
||||
let ordinary: Vec<u8> = [ADD, LDR, ADD, ADD, ADD, 0x1400_0000]
|
||||
.into_iter()
|
||||
.flat_map(u32::to_le_bytes)
|
||||
@@ -1144,8 +1221,14 @@ mod tests {
|
||||
);
|
||||
let compiled =
|
||||
compile_for_target(&ordinary, BASE, profile, crate::TargetCpu::Baseline).unwrap();
|
||||
assert_eq!(compiled.native.x86_64_code, expected.x86_64_code);
|
||||
assert_eq!(compiled.native.source_map, expected.source_map);
|
||||
let check = crate::x86_64::GUEST_RANGE_CHECK;
|
||||
let mut unchecked = compiled.native.x86_64_code.clone();
|
||||
let at = unchecked
|
||||
.windows(check.len())
|
||||
.position(|bytes| bytes == check)
|
||||
.expect("the load checks its address");
|
||||
unchecked.drain(at..at + check.len());
|
||||
assert_eq!(unchecked, expected.x86_64_code);
|
||||
let aligned = crate::x86_64::MemoryChecks {
|
||||
alignment: true,
|
||||
..crate::x86_64::MemoryChecks::DEFAULT
|
||||
@@ -1155,7 +1238,10 @@ mod tests {
|
||||
parsed.terminal.as_ref(),
|
||||
parsed.next_pc,
|
||||
crate::TargetCpu::Baseline,
|
||||
aligned,
|
||||
crate::x86_64::MemoryChecks {
|
||||
guest_range: true,
|
||||
..aligned
|
||||
},
|
||||
);
|
||||
let compiled = CompilationPlan::new(&ordinary, BASE, profile, crate::TargetCpu::Baseline)
|
||||
.unwrap()
|
||||
|
||||
@@ -76,6 +76,7 @@ mod crc;
|
||||
pub(crate) mod exclusive;
|
||||
mod flags;
|
||||
mod fp_register;
|
||||
mod guest_range;
|
||||
mod integer_math;
|
||||
mod integer_minmax;
|
||||
mod integer_unary;
|
||||
@@ -215,6 +216,10 @@ pub struct MemoryChecks {
|
||||
/// SCTLR_ELx.nAA is clear: a load-acquire or store-release that crosses a
|
||||
/// 16-byte granule faults. Atomics always fault there (FEAT_LSE2).
|
||||
pub ordered_granule: bool,
|
||||
/// Every access checks its address against the guest's two ranges
|
||||
/// ([`GUEST_RANGE_CHECK`]). `SystemModeV1` sets it for every block,
|
||||
/// whatever the engine asks, and no other profile does.
|
||||
pub(crate) guest_range: bool,
|
||||
}
|
||||
|
||||
impl MemoryChecks {
|
||||
@@ -224,7 +229,46 @@ impl MemoryChecks {
|
||||
stack_alignment: true,
|
||||
alignment: false,
|
||||
ordered_granule: true,
|
||||
guest_range: false,
|
||||
};
|
||||
/// SCTLR_ELx's checks, as the system-mode engine selects them.
|
||||
pub const fn system(stack_alignment: bool, alignment: bool, ordered_granule: bool) -> Self {
|
||||
Self {
|
||||
stack_alignment,
|
||||
alignment,
|
||||
ordered_granule,
|
||||
guest_range: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The system-mode check of the access address in RAX against the guest's
|
||||
/// two ranges, the only parts of the host address space its shadow tables
|
||||
/// map: bits 63:48 all clear (TTBR0, PML5 entry 0) or all set (TTBR1, entry
|
||||
/// 511). Any other address raises #UD before the access, which the engine
|
||||
/// turns into the fault the guest's translation gives it. Every other PML5
|
||||
/// entry, Stela's window (entry 64) among them, is then out of a guest
|
||||
/// access's reach. RCX and host flags are scratch.
|
||||
pub(crate) const GUEST_RANGE_CHECK: [u8; 16] = [
|
||||
0x48, 0x89, 0xc1, // mov rcx,rax
|
||||
0x48, 0xc1, 0xf9, 48, // sar rcx,48: 0 or -1 in range
|
||||
0xff, 0xc1, // inc ecx: 1 or 0 in range
|
||||
0x83, 0xf9, 0x01, // cmp ecx,1
|
||||
0x76, 0x02, // jbe +2
|
||||
0x0f, 0x0b, // ud2
|
||||
];
|
||||
|
||||
fn guest_range_check(code: &mut Vec<u8>, checks: MemoryChecks) {
|
||||
if checks.guest_range {
|
||||
code.extend(GUEST_RANGE_CHECK);
|
||||
}
|
||||
}
|
||||
|
||||
/// The checks of an access's final address in RAX: the guest range, then
|
||||
/// SCTLR_ELx.A against `unit`, the bytes of each element it transfers.
|
||||
fn address_checks(code: &mut Vec<u8>, checks: MemoryChecks, unit: u8) {
|
||||
guest_range_check(code, checks);
|
||||
alignment_check(code, checks, unit);
|
||||
}
|
||||
|
||||
/// SCTLR_ELx.A's check of the effective address in RAX against `unit`, the
|
||||
@@ -257,7 +301,7 @@ fn memory_address(
|
||||
if mode != AddressMode::PostIndex {
|
||||
code.extend([0x48, 0x89, 0xd0]); // mov rax,rdx: effective address
|
||||
}
|
||||
alignment_check(code, checks, unit);
|
||||
address_checks(code, checks, unit);
|
||||
}
|
||||
|
||||
fn memory_writeback(code: &mut Vec<u8>, base: Register, mode: AddressMode) {
|
||||
@@ -835,6 +879,89 @@ mod tests {
|
||||
Operation as Synchronization, Requirement, Scope, WaitKind,
|
||||
};
|
||||
|
||||
/// The check runs on the host and passes exactly the addresses whose
|
||||
/// bits 63:48 are all clear or all set.
|
||||
#[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))]
|
||||
#[test]
|
||||
fn the_guest_range_check_passes_exactly_the_two_48_bit_ranges() {
|
||||
use core::ffi::c_void;
|
||||
unsafe extern "C" {
|
||||
fn mmap(
|
||||
address: *mut c_void,
|
||||
bytes: usize,
|
||||
protection: i32,
|
||||
flags: i32,
|
||||
fd: i32,
|
||||
offset: i64,
|
||||
) -> *mut c_void;
|
||||
fn mprotect(address: *mut c_void, bytes: usize, protection: i32) -> i32;
|
||||
fn munmap(address: *mut c_void, bytes: usize) -> i32;
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
const MAP_ANONYMOUS: i32 = 0x1000;
|
||||
#[cfg(target_os = "linux")]
|
||||
const MAP_ANONYMOUS: i32 = 0x20;
|
||||
const PAGE: usize = 4096;
|
||||
let (check, trap) = GUEST_RANGE_CHECK.split_at(GUEST_RANGE_CHECK.len() - 2);
|
||||
assert_eq!(trap, [0x0f, 0x0b]);
|
||||
// mov rax,rdi; the check with `xor eax,eax` (a failure, also two
|
||||
// bytes) where its UD2 is; ret.
|
||||
let mut code = vec![0x48, 0x89, 0xf8];
|
||||
code.extend(check);
|
||||
code.extend([0x31, 0xc0, 0xc3]);
|
||||
// SAFETY: private anonymous memory, RX after the copy and unmapped
|
||||
// after the calls; the code touches no memory.
|
||||
unsafe {
|
||||
let page = mmap(core::ptr::null_mut(), PAGE, 3, 2 | MAP_ANONYMOUS, -1, 0);
|
||||
assert_ne!(page as usize, usize::MAX);
|
||||
core::ptr::copy_nonoverlapping(code.as_ptr(), page.cast(), code.len());
|
||||
assert_eq!(mprotect(page, PAGE, 5), 0);
|
||||
let passes = |address: u64| {
|
||||
let entry: unsafe extern "sysv64" fn(u64) -> u64 = core::mem::transmute(page);
|
||||
let result = entry(address);
|
||||
assert!(result == address || result == 0);
|
||||
result == address
|
||||
};
|
||||
for (address, expected) in [
|
||||
(1, true),
|
||||
(0x0000_ffff_ffff_ffff, true),
|
||||
(0xffff_0000_0000_0000, true),
|
||||
(u64::MAX, true),
|
||||
(0x0001_0000_0000_0000, false),
|
||||
// Stela's window, PML5 entry 64.
|
||||
(0x0040_0000_0000_0000, false),
|
||||
(0x00ff_ffff_ffff_ffff, false),
|
||||
(0xff00_0000_0000_0000, false),
|
||||
(0xfffe_ffff_ffff_ffff, false),
|
||||
(0x7fff_ffff_ffff_ffff, false),
|
||||
(0x8000_0000_0000_0000, false),
|
||||
// A tagged pointer.
|
||||
(0x0f00_0000_0000_1234, false),
|
||||
] {
|
||||
assert_eq!(passes(address), expected, "{address:#x}");
|
||||
}
|
||||
let mut seed = 0x9e37_79b9_7f4a_7c15u64;
|
||||
for _ in 0..4096 {
|
||||
seed = seed
|
||||
.wrapping_mul(6364136223846793005)
|
||||
.wrapping_add(1442695040888963407);
|
||||
// Bias half the samples to the ranges' edges.
|
||||
let top = match seed >> 62 {
|
||||
0 => 0,
|
||||
1 => 0xffff,
|
||||
_ => (seed >> 16) & 0xffff,
|
||||
};
|
||||
let address = top << 48 | (seed.rotate_left(17) & 0xffff_ffff_ffff) | 1;
|
||||
assert_eq!(
|
||||
passes(address),
|
||||
matches!(address >> 48, 0 | 0xffff),
|
||||
"{address:#x}"
|
||||
);
|
||||
}
|
||||
assert_eq!(munmap(page, PAGE), 0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constructed_context_operations_return_an_explicit_error() {
|
||||
const BARRIER_OPTION_OSH: u8 = 3;
|
||||
|
||||
@@ -105,7 +105,7 @@ pub(super) fn address_offset(
|
||||
code.extend(ADD_RAX_IMM32);
|
||||
code.extend(displacement.to_le_bytes());
|
||||
}
|
||||
super::alignment_check(code, checks, bytes);
|
||||
super::address_checks(code, checks, bytes);
|
||||
if granule && bytes != BYTE_BYTES {
|
||||
if !aligned_sp {
|
||||
code.extend(MOV_ECX_EAX);
|
||||
|
||||
@@ -120,14 +120,18 @@ pub(crate) fn emit_system_mode(
|
||||
) -> NativeBlock {
|
||||
// Allocated and clean-load regions settle the frame before every
|
||||
// access and exit, so a fault inside one finds it exact. Their loads
|
||||
// carry no SCTLR_ELx.A check.
|
||||
// carry no SCTLR_ELx.A check. Accesses check the guest range
|
||||
// (`x86_64::guest_range`).
|
||||
emit_selected(
|
||||
instructions,
|
||||
terminal,
|
||||
fallthrough,
|
||||
target,
|
||||
!checks.alignment,
|
||||
checks,
|
||||
super::MemoryChecks {
|
||||
guest_range: true,
|
||||
..checks
|
||||
},
|
||||
native,
|
||||
)
|
||||
}
|
||||
@@ -147,6 +151,18 @@ fn emit_selected(
|
||||
};
|
||||
let code = &mut block.x86_64_code;
|
||||
let mut fixups = vec![];
|
||||
// Which accesses check the guest range (`guest_range`), and each
|
||||
// instruction's checks.
|
||||
let ranges = if checks.guest_range {
|
||||
super::guest_range::checks(instructions)
|
||||
} else {
|
||||
vec![]
|
||||
};
|
||||
let ranges = checks.guest_range.then_some(&ranges[..]);
|
||||
let checks_at = |index: usize| super::MemoryChecks {
|
||||
guest_range: ranges.is_some_and(|ranges| ranges[index]),
|
||||
..checks
|
||||
};
|
||||
let mut cursor = 0;
|
||||
while cursor < instructions.len() {
|
||||
// Build the new candidate privately. Rejection leaves both cursor and
|
||||
@@ -157,13 +173,13 @@ fn emit_selected(
|
||||
let count = region.consumed_instructions;
|
||||
let mut baseline = vec![];
|
||||
let mut candidate_fixups = vec![];
|
||||
for instruction in &instructions[cursor..cursor + count] {
|
||||
for (index, instruction) in instructions[cursor..cursor + count].iter().enumerate() {
|
||||
super::emit_instruction(
|
||||
&mut baseline,
|
||||
instruction,
|
||||
&mut candidate_fixups,
|
||||
target,
|
||||
checks,
|
||||
checks_at(cursor + index),
|
||||
);
|
||||
}
|
||||
if candidate_fixups.is_empty() && super::region::admits_allocated(®ion, &baseline) {
|
||||
@@ -177,21 +193,24 @@ fn emit_selected(
|
||||
}
|
||||
}
|
||||
if optimize_regions
|
||||
&& let Ok(region) = super::region::emit_clean_load_prefix(&instructions[cursor..])
|
||||
&& let Ok(region) = super::region::emit_clean_load_prefix(
|
||||
&instructions[cursor..],
|
||||
ranges.map(|ranges| &ranges[cursor..]),
|
||||
)
|
||||
&& region.consumed_instructions != 0
|
||||
{
|
||||
let count = region.consumed_instructions;
|
||||
let mut baseline_code = vec![];
|
||||
let mut baseline_map = vec![];
|
||||
let mut baseline_fixups = vec![];
|
||||
for instruction in &instructions[cursor..cursor + count] {
|
||||
for (index, instruction) in instructions[cursor..cursor + count].iter().enumerate() {
|
||||
baseline_map.push((instruction.pc, baseline_code.len()));
|
||||
super::emit_instruction(
|
||||
&mut baseline_code,
|
||||
instruction,
|
||||
&mut baseline_fixups,
|
||||
target,
|
||||
checks,
|
||||
checks_at(cursor + index),
|
||||
);
|
||||
}
|
||||
debug_assert!(baseline_fixups.is_empty());
|
||||
@@ -219,7 +238,7 @@ fn emit_selected(
|
||||
if let Operation::FloatingPoint(operand) = &instruction.operation {
|
||||
super::simd::emit_numerical(code, operand, instruction.pc, target);
|
||||
} else {
|
||||
super::emit_instruction(code, instruction, &mut fixups, target, checks);
|
||||
super::emit_instruction(code, instruction, &mut fixups, target, checks_at(cursor));
|
||||
}
|
||||
cursor += 1;
|
||||
}
|
||||
|
||||
@@ -4,9 +4,10 @@
|
||||
//! all the engine does for them is translate Xt as a read, taking the Data
|
||||
//! Abort of a failed translation (`engine::system` `check_maintenance`).
|
||||
//! Native code makes the same check by reading the byte at Xt through the
|
||||
//! same direct guest-VA access as LDRB, then falls through. A read that
|
||||
//! fails for any reason (a guest fault, Device memory, a watched page, a
|
||||
//! non-canonical x86 address) ends the block at the DC with nothing
|
||||
//! same direct guest-VA access as LDRB, after the guest range check, then
|
||||
//! falls through. A read that fails for any reason (a guest fault, Device
|
||||
//! memory, a watched page, an address outside the guest's ranges) ends the
|
||||
//! block at the DC with nothing
|
||||
//! written, and the engine then completes the instruction itself, with the
|
||||
//! syndrome of a cache maintenance fault. Code clobbers RAX and ECX.
|
||||
use crate::aarch64::{
|
||||
@@ -74,6 +75,7 @@ pub(crate) fn emit(code: &mut Vec<u8>, rt: u8) {
|
||||
Register::X(rt)
|
||||
},
|
||||
);
|
||||
code.extend(super::GUEST_RANGE_CHECK);
|
||||
code.extend([0x0f, 0xb6, 0x08]); // movzx ecx,byte [rax]
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,265 @@
|
||||
//! Which accesses of a system-mode block check their address against the
|
||||
//! guest's two ranges ([`super::GUEST_RANGE_CHECK`]).
|
||||
//!
|
||||
//! An immediate-offset access moves at most 2^16 bytes from its base, so
|
||||
//! once one through a base register has been made, the base is within
|
||||
//! 2^16 of a range. While the base keeps that value or moves from it by
|
||||
//! immediates (writeback, or ADD and SUB immediate, also into another
|
||||
//! register), every later immediate-offset access through it is within
|
||||
//! 2^35 of a range, as a block holds at most 1,024 instructions: in a
|
||||
//! range, or in PML5 entry 1 or 510, which no shadow root maps, where an
|
||||
//! x86 #PF takes the fault the guest's translation gives. Stela's window,
|
||||
//! 63 entries from either range, stays out of reach, so those accesses
|
||||
//! need no check of their own. Any other write of the register, and any
|
||||
//! instruction this analysis does not know, forgets it.
|
||||
use crate::aarch64::{
|
||||
Instruction, MemoryTransfer, Operation, Register, Width, atomic, literal, non_temporal,
|
||||
ordered, simd,
|
||||
};
|
||||
use alloc::vec::Vec;
|
||||
|
||||
/// A register's bit in a set of bases: X0-X30 and SP as bit 31.
|
||||
fn bit(register: Register) -> u32 {
|
||||
match register {
|
||||
Register::X(index) => 1 << index,
|
||||
Register::Sp => 1 << 31,
|
||||
Register::Zero => 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// For each instruction of a block, whether its access checks the guest
|
||||
/// range: all but the immediate-offset accesses through a base the block
|
||||
/// has already made such an access through, unmodified since but by
|
||||
/// immediates.
|
||||
pub(crate) fn checks(instructions: &[Instruction]) -> Vec<bool> {
|
||||
let mut bases = 0u32;
|
||||
instructions
|
||||
.iter()
|
||||
.map(|instruction| {
|
||||
let check =
|
||||
immediate_base(&instruction.operation).is_none_or(|base| bases & bit(base) == 0);
|
||||
bases = after(&instruction.operation, bases);
|
||||
check
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The base of an access whose address is the base plus an immediate.
|
||||
fn immediate_base(operation: &Operation) -> Option<Register> {
|
||||
match operation {
|
||||
Operation::Memory { base, .. }
|
||||
| Operation::MemoryPair { base, .. }
|
||||
| Operation::Simd(
|
||||
simd::Operand::Memory { base, .. } | simd::Operand::MemoryPair { base, .. },
|
||||
) => Some(*base),
|
||||
Operation::Simd(simd::Operand::StructureMemory(operand)) => Some(operand.base),
|
||||
Operation::MemoryUnprivileged(operand) => Some(operand.base),
|
||||
Operation::MemoryNonTemporal(operand) => Some(operand.base),
|
||||
Operation::Atomic(operand) => Some(operand.base),
|
||||
Operation::Ordered(ordered::Operand::Transfer { base, .. }) => Some(*base),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The bases known after `operation`, given `bases` before it.
|
||||
fn after(operation: &Operation, bases: u32) -> u32 {
|
||||
let loaded = |transfer: &MemoryTransfer| matches!(transfer, MemoryTransfer::Load { .. });
|
||||
match operation {
|
||||
Operation::Memory {
|
||||
transfer,
|
||||
data,
|
||||
base,
|
||||
..
|
||||
} => {
|
||||
let bases = bases | bit(*base);
|
||||
if loaded(transfer) {
|
||||
bases & !bit(*data)
|
||||
} else {
|
||||
bases
|
||||
}
|
||||
}
|
||||
Operation::MemoryPair {
|
||||
transfer,
|
||||
data,
|
||||
base,
|
||||
..
|
||||
} => {
|
||||
let bases = bases | bit(*base);
|
||||
if loaded(transfer) {
|
||||
bases & !bit(data[0]) & !bit(data[1])
|
||||
} else {
|
||||
bases
|
||||
}
|
||||
}
|
||||
Operation::MemoryUnprivileged(operand) => {
|
||||
let bases = bases | bit(operand.base);
|
||||
if loaded(&operand.transfer) {
|
||||
bases & !bit(operand.data)
|
||||
} else {
|
||||
bases
|
||||
}
|
||||
}
|
||||
Operation::MemoryNonTemporal(operand) => {
|
||||
let bases = bases | bit(operand.base);
|
||||
match operand.data {
|
||||
non_temporal::Data::Integer(data) if operand.load => {
|
||||
bases & !bit(data[0]) & !bit(data[1])
|
||||
}
|
||||
_ => bases,
|
||||
}
|
||||
}
|
||||
// Vector data; the base moves by an immediate if at all.
|
||||
Operation::Simd(
|
||||
simd::Operand::Memory { base, .. } | simd::Operand::MemoryPair { base, .. },
|
||||
) => bases | bit(*base),
|
||||
Operation::Simd(simd::Operand::StructureMemory(operand)) => match operand.post_index {
|
||||
simd::structure_memory::PostIndex::Register(_) => bases & !bit(operand.base),
|
||||
_ => bases | bit(operand.base),
|
||||
},
|
||||
Operation::AddSub {
|
||||
width,
|
||||
destination,
|
||||
source,
|
||||
..
|
||||
} => {
|
||||
if *width == Width::X64 && bases & bit(*source) != 0 {
|
||||
bases | bit(*destination)
|
||||
} else {
|
||||
bases & !bit(*destination)
|
||||
}
|
||||
}
|
||||
Operation::AddSubRegister { destination, .. }
|
||||
| Operation::AddSubCarry { destination, .. }
|
||||
| Operation::AddSubExtended { destination, .. }
|
||||
| Operation::LogicalRegister { destination, .. }
|
||||
| Operation::LogicalImmediate { destination, .. }
|
||||
| Operation::MoveWide { destination, .. } => bases & !bit(*destination),
|
||||
// CAS and CASP return the old value in the compared registers.
|
||||
Operation::Atomic(operand) => {
|
||||
let bases = bases | bit(operand.base);
|
||||
match operand.kind {
|
||||
atomic::Kind::CompareExchange { compare, .. } => bases & !bit(compare),
|
||||
atomic::Kind::CompareExchangePair { compare, .. } => {
|
||||
bases & !bit(compare[0]) & !bit(compare[1])
|
||||
}
|
||||
atomic::Kind::ReadModifyWrite { destination, .. } => bases & !bit(destination),
|
||||
}
|
||||
}
|
||||
Operation::Ordered(ordered::Operand::Transfer {
|
||||
kind, data, base, ..
|
||||
}) => {
|
||||
let bases = bases | bit(*base);
|
||||
if *kind == ordered::Kind::Release {
|
||||
bases
|
||||
} else {
|
||||
bases & !bit(*data)
|
||||
}
|
||||
}
|
||||
// A register offset proves nothing of its base.
|
||||
Operation::MemoryRegisterOffset(operand) => {
|
||||
if loaded(&operand.transfer) {
|
||||
bases & !bit(operand.data)
|
||||
} else {
|
||||
bases
|
||||
}
|
||||
}
|
||||
Operation::Literal(operand) => match operand.transfer {
|
||||
literal::Transfer::Integer { destination, .. } => bases & !bit(destination),
|
||||
literal::Transfer::Simd { .. } => bases,
|
||||
},
|
||||
Operation::PcRelative(operand) => bases & !bit(operand.destination),
|
||||
Operation::ConditionalSelect(operand) => bases & !bit(operand.destination),
|
||||
Operation::Bitfield(operand) => bases & !bit(operand.destination),
|
||||
Operation::IntegerMath(operand) => bases & !bit(operand.destination),
|
||||
Operation::IntegerUnary(operand) => bases & !bit(operand.destination),
|
||||
Operation::IntegerMinMax(operand) => bases & !bit(operand.destination),
|
||||
Operation::Crc(operand) => bases & !bit(operand.destination),
|
||||
// NZCV, barriers and hints only.
|
||||
Operation::Flags(_)
|
||||
| Operation::Synchronization(_)
|
||||
| Operation::Ordered(ordered::Operand::Barrier { .. })
|
||||
| Operation::Nop
|
||||
| Operation::Prefetch(_) => bases,
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{GuestAddress, Lifter, aarch64::Decoder};
|
||||
use alloc::vec::Vec;
|
||||
|
||||
fn lift(words: &[u32]) -> Vec<Instruction> {
|
||||
words
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, &word)| {
|
||||
Decoder
|
||||
.lift(GuestAddress(0x1000 + 4 * index as u64), word)
|
||||
.unwrap()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_base_is_checked_once_until_it_changes_but_by_immediates() {
|
||||
// stp x29, x30, [sp, #-16]!; mov x29, sp; ldr x0, [x29, #8];
|
||||
// str x1, [sp, #8]; sub sp, sp, #32; ldp x2, x3, [sp], #16;
|
||||
// ldr x4, [x5]; ldr x5, [x5, #8]; ldr x6, [x5]; add w5, w6, #1;
|
||||
// ldr x7, [x5]; ldr x8, [x6, x9]; ldr x10, [x6]
|
||||
let words = [
|
||||
0xa9bf_7bfd,
|
||||
0x9100_03fd,
|
||||
0xf940_07a0,
|
||||
0xf900_07e1,
|
||||
0xd100_83ff,
|
||||
0xa8c1_0fe2,
|
||||
0xf940_00a4,
|
||||
0xf940_04a5,
|
||||
0xf940_00a6,
|
||||
0x1100_04c5,
|
||||
0xf940_00a7,
|
||||
0xf869_68c8,
|
||||
0xf940_00ca,
|
||||
];
|
||||
assert_eq!(
|
||||
checks(&lift(&words)),
|
||||
[
|
||||
true, // the first access through SP
|
||||
true, // a move
|
||||
false, // X29 = SP
|
||||
false, // SP again
|
||||
true, // SUB SP, SP, #imm
|
||||
false, // SP moved by an immediate
|
||||
true, // the first through X5
|
||||
false, // X5 again, which the load replaces
|
||||
true, // X5 was loaded
|
||||
true, // an add
|
||||
true, // a W result is no address near a range
|
||||
true, // a register offset is checked at its sum
|
||||
true, // X6 was loaded and has made no access
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_instructions_and_register_post_indexes_forget_bases() {
|
||||
// ldr x0, [x1]; fmov x2, d0 (not analyzed); ldr x6, [x1];
|
||||
// ld1 {v0.16b}, [x1], x7; ldr x8, [x1]; ld1 {v0.16b}, [x1], #16;
|
||||
// ldr x9, [x1]
|
||||
let words = [
|
||||
0xf940_0020,
|
||||
0x9e66_0002,
|
||||
0xf940_0026,
|
||||
0x4cc7_7020,
|
||||
0xf940_0028,
|
||||
0x4cdf_7020,
|
||||
0xf940_0029,
|
||||
];
|
||||
assert_eq!(
|
||||
checks(&lift(&words)),
|
||||
[true, true, true, false, true, false, false]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -38,7 +38,7 @@ pub(super) fn emit(code: &mut Vec<u8>, operand: &Operand, checks: super::MemoryC
|
||||
Transfer::Integer { .. } => 4,
|
||||
Transfer::Simd { bytes, .. } => bytes,
|
||||
};
|
||||
super::alignment_check(code, checks, bytes);
|
||||
super::address_checks(code, checks, bytes);
|
||||
match operand.transfer {
|
||||
Transfer::Integer {
|
||||
destination,
|
||||
|
||||
@@ -88,6 +88,9 @@ struct Emitter<'a> {
|
||||
flag_location: flags::Location,
|
||||
coalesced: Option<usize>,
|
||||
allocating_output: bool,
|
||||
/// For each instruction, whether its clean load checks the guest range
|
||||
/// (`x86_64::guest_range`); none in process profiles.
|
||||
range_checks: Option<&'a [bool]>,
|
||||
}
|
||||
|
||||
impl Emitter<'_> {
|
||||
@@ -288,7 +291,7 @@ impl Emitter<'_> {
|
||||
let mut raw = vec![];
|
||||
super::memory(
|
||||
&mut raw,
|
||||
super::MemoryChecks::DEFAULT,
|
||||
self.memory_checks(),
|
||||
transfer,
|
||||
bytes,
|
||||
data,
|
||||
@@ -324,6 +327,17 @@ impl Emitter<'_> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The checks of the shared memory emitter whose bytes the current
|
||||
/// clean load reuses: the default ones, with its guest range check.
|
||||
fn memory_checks(&self) -> super::MemoryChecks {
|
||||
super::MemoryChecks {
|
||||
guest_range: self
|
||||
.range_checks
|
||||
.is_some_and(|ranges| ranges.get(self.current).copied().unwrap_or(true)),
|
||||
..super::MemoryChecks::DEFAULT
|
||||
}
|
||||
}
|
||||
|
||||
fn settle_before_load(&mut self, clobbers: u16, destinations: &[Register]) {
|
||||
for (index, host) in POOL.iter().copied().enumerate() {
|
||||
if let Some(resident) = self.resident[index]
|
||||
@@ -380,7 +394,7 @@ impl Emitter<'_> {
|
||||
let mut raw = vec![];
|
||||
super::memory_pair(
|
||||
&mut raw,
|
||||
super::MemoryChecks::DEFAULT,
|
||||
self.memory_checks(),
|
||||
transfer,
|
||||
bytes,
|
||||
data,
|
||||
@@ -801,7 +815,7 @@ impl Emitter<'_> {
|
||||
/// `consumed_instructions`, with the full frame written back and `exit_pc` set.
|
||||
#[cfg(test)]
|
||||
pub fn emit_prefix(instructions: &[Instruction]) -> Result<OptimizedRegion, RegionError> {
|
||||
emit_prefix_selected(instructions, false)
|
||||
emit_prefix_selected(instructions, false, None)
|
||||
}
|
||||
|
||||
/// Transactional nonfaulting GPR/NZCV span candidate.
|
||||
@@ -812,15 +826,19 @@ pub fn emit_allocated_prefix(
|
||||
}
|
||||
|
||||
/// Ordinary direct-RAM load retention; pure ALU allocation keeps six slots.
|
||||
pub fn emit_clean_load_prefix(
|
||||
instructions: &[Instruction],
|
||||
/// With `range_checks`, the loads the system-mode analysis selects check
|
||||
/// their address ([`super::GUEST_RANGE_CHECK`]).
|
||||
pub fn emit_clean_load_prefix<'a>(
|
||||
instructions: &'a [Instruction],
|
||||
range_checks: Option<&'a [bool]>,
|
||||
) -> Result<OptimizedRegion, RegionError> {
|
||||
emit_prefix_selected(instructions, true)
|
||||
emit_prefix_selected(instructions, true, range_checks)
|
||||
}
|
||||
|
||||
fn emit_prefix_selected(
|
||||
instructions: &[Instruction],
|
||||
fn emit_prefix_selected<'a>(
|
||||
instructions: &'a [Instruction],
|
||||
clean_loads: bool,
|
||||
range_checks: Option<&'a [bool]>,
|
||||
) -> Result<OptimizedRegion, RegionError> {
|
||||
if instructions.len() > MAX_INSTRUCTIONS {
|
||||
return Err(RegionError::TooLong);
|
||||
@@ -897,6 +915,7 @@ fn emit_prefix_selected(
|
||||
flag_location: flags::Location::Frame,
|
||||
coalesced: None,
|
||||
allocating_output: false,
|
||||
range_checks,
|
||||
};
|
||||
for instruction in instructions.iter().take(consumed) {
|
||||
emitter.instruction(instruction)?;
|
||||
@@ -1325,13 +1344,85 @@ mod tests {
|
||||
instruction(3, add(Register::X(9), Register::X(9))),
|
||||
instruction(4, add(Register::X(8), Register::X(8))),
|
||||
];
|
||||
let output = emit_clean_load_prefix(&instructions).unwrap();
|
||||
let output = emit_clean_load_prefix(&instructions, None).unwrap();
|
||||
assert_eq!(output.consumed_instructions, 5);
|
||||
assert_eq!(output.stats.clean_loads, 1);
|
||||
assert_eq!(output.stats.load_boundary_stores, 2);
|
||||
assert_eq!(emit_prefix(&instructions).unwrap().consumed_instructions, 2);
|
||||
}
|
||||
|
||||
/// With the system-mode guest range check, clean loads keep the same
|
||||
/// shape and check each address once, after the frame is settled.
|
||||
#[test]
|
||||
fn clean_loads_check_the_guest_range_when_asked() {
|
||||
use super::super::GUEST_RANGE_CHECK;
|
||||
let load = |pc, data, base| {
|
||||
instruction(
|
||||
pc,
|
||||
Operation::Memory {
|
||||
transfer: MemoryTransfer::Load {
|
||||
signed: false,
|
||||
width: Width::W32,
|
||||
},
|
||||
bytes: 4,
|
||||
data: Register::X(data),
|
||||
base: Register::X(base),
|
||||
displacement: 8,
|
||||
mode: AddressMode::Offset,
|
||||
},
|
||||
)
|
||||
};
|
||||
let pair = instruction(
|
||||
3,
|
||||
Operation::MemoryPair {
|
||||
transfer: MemoryTransfer::Load {
|
||||
signed: false,
|
||||
width: Width::W32,
|
||||
},
|
||||
bytes: 4,
|
||||
data: [Register::X(4), Register::X(5)],
|
||||
base: Register::X(1),
|
||||
displacement: 16,
|
||||
mode: AddressMode::Offset,
|
||||
},
|
||||
);
|
||||
let instructions = vec![
|
||||
instruction(0, add(Register::X(9), Register::X(9))),
|
||||
load(1, 2, 1),
|
||||
load(2, 3, 1),
|
||||
pair,
|
||||
instruction(4, add(Register::X(9), Register::X(9))),
|
||||
];
|
||||
let checks = |code: &[u8]| {
|
||||
code.windows(GUEST_RANGE_CHECK.len())
|
||||
.filter(|bytes| *bytes == GUEST_RANGE_CHECK)
|
||||
.count()
|
||||
};
|
||||
let unchecked = emit_clean_load_prefix(&instructions, None).unwrap();
|
||||
let checked = emit_clean_load_prefix(&instructions, Some(&[true; 5])).unwrap();
|
||||
assert_eq!(checks(&unchecked.code), 0);
|
||||
assert_eq!(checks(&checked.code), 3);
|
||||
// Each load takes its own instruction's decision.
|
||||
let second =
|
||||
emit_clean_load_prefix(&instructions, Some(&[true, false, true, false, true])).unwrap();
|
||||
assert_eq!(checks(&second.code), 1);
|
||||
assert_eq!(
|
||||
checked.consumed_instructions,
|
||||
unchecked.consumed_instructions
|
||||
);
|
||||
assert_eq!(checked.stats.clean_loads, unchecked.stats.clean_loads);
|
||||
assert_eq!(checked.stats.pair_loads, 1);
|
||||
// The second load reuses the cached X1 and still checks.
|
||||
assert_eq!(
|
||||
checked.stats.address_cache_hits,
|
||||
unchecked.stats.address_cache_hits
|
||||
);
|
||||
assert_eq!(
|
||||
checked.code.len(),
|
||||
unchecked.code.len() + 3 * GUEST_RANGE_CHECK.len()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cached_right_destination_commutes_only_plain_unshifted_operations() {
|
||||
let arithmetic = |subtract, amount| Operation::AddSubRegister {
|
||||
@@ -1387,12 +1478,15 @@ mod tests {
|
||||
displacement: 0,
|
||||
mode: AddressMode::Offset,
|
||||
};
|
||||
let output = emit_clean_load_prefix(&[
|
||||
instruction(0, load(10)),
|
||||
instruction(1, add(Register::X(10), Register::X(10))),
|
||||
instruction(2, load(11)),
|
||||
instruction(3, add(Register::X(0), Register::X(10))),
|
||||
])
|
||||
let output = emit_clean_load_prefix(
|
||||
&[
|
||||
instruction(0, load(10)),
|
||||
instruction(1, add(Register::X(10), Register::X(10))),
|
||||
instruction(2, load(11)),
|
||||
instruction(3, add(Register::X(0), Register::X(10))),
|
||||
],
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(output.stats.load_boundary_stores, 1);
|
||||
}
|
||||
@@ -1466,7 +1560,7 @@ mod tests {
|
||||
instruction(1, load(data, Register::X(15))),
|
||||
instruction(2, add(Register::X(9), Register::X(9))),
|
||||
];
|
||||
let region = emit_clean_load_prefix(&instructions).unwrap();
|
||||
let region = emit_clean_load_prefix(&instructions, None).unwrap();
|
||||
assert_eq!(region.consumed_instructions, instructions.len());
|
||||
assert_eq!(region.stats.clean_loads, 1);
|
||||
assert_eq!(region.stats.load_boundary_stores, 1);
|
||||
@@ -1554,7 +1648,7 @@ mod tests {
|
||||
instruction(2, add(Register::X(9), Register::X(16))),
|
||||
instruction(3, add(Register::X(10), Register::X(17))),
|
||||
];
|
||||
let region = emit_clean_load_prefix(&source).unwrap();
|
||||
let region = emit_clean_load_prefix(&source, None).unwrap();
|
||||
assert_eq!(region.consumed_instructions, source.len());
|
||||
assert_eq!(region.stats.pair_loads, 1);
|
||||
let mut raw = vec![];
|
||||
@@ -1792,7 +1886,7 @@ mod tests {
|
||||
instruction(2, add(Register::X(2), Register::X(2))),
|
||||
];
|
||||
assert!(emit_allocated_prefix(&instructions).unwrap().is_none());
|
||||
let legacy = emit_clean_load_prefix(&instructions).unwrap();
|
||||
let legacy = emit_clean_load_prefix(&instructions, None).unwrap();
|
||||
let target = crate::TargetCpu::Baseline;
|
||||
let fallthrough = GuestAddress(0x100c);
|
||||
let baseline = super::super::block::emit_for_target(
|
||||
|
||||
@@ -418,6 +418,7 @@ pub(super) fn emitter<'a>(
|
||||
flag_location: flags::Location::Frame,
|
||||
coalesced: None,
|
||||
allocating_output: false,
|
||||
range_checks: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -328,7 +328,13 @@ fn ordinary_address_ends(code: &[u8], base: usize, displacement: i32) -> Option<
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some(vec![7, 14, ORDINARY_ADDRESS_BYTES])
|
||||
let mut ends = vec![7, 14, ORDINARY_ADDRESS_BYTES];
|
||||
// A system-mode access checks the address against the guest's ranges.
|
||||
let checked = ORDINARY_ADDRESS_BYTES + super::super::GUEST_RANGE_CHECK.len();
|
||||
if code.get(ORDINARY_ADDRESS_BYTES..checked) == Some(&super::super::GUEST_RANGE_CHECK[..]) {
|
||||
ends.push(checked);
|
||||
}
|
||||
Some(ends)
|
||||
}
|
||||
|
||||
fn check_frame_store(code: &[u8], start: usize, guest: usize, rex: u8, modrm: u8) -> Option<usize> {
|
||||
@@ -360,8 +366,9 @@ pub fn ordinary_load_ends(
|
||||
_ => return None,
|
||||
};
|
||||
let mut ends = ordinary_address_ends(code, base, displacement)?;
|
||||
let load_end = ORDINARY_ADDRESS_BYTES + memory_recipe.len();
|
||||
if code.get(ORDINARY_ADDRESS_BYTES..load_end)? != memory_recipe {
|
||||
let address_end = *ends.last()?;
|
||||
let load_end = address_end + memory_recipe.len();
|
||||
if code.get(address_end..load_end)? != memory_recipe {
|
||||
return None;
|
||||
}
|
||||
ends.push(load_end);
|
||||
@@ -384,9 +391,10 @@ pub fn ordinary_pair_load_ends(
|
||||
displacement: i32,
|
||||
) -> Option<Vec<usize>> {
|
||||
let mut ends = ordinary_address_ends(code, base, displacement)?;
|
||||
let first_end = ORDINARY_ADDRESS_BYTES + 2;
|
||||
let address_end = *ends.last()?;
|
||||
let first_end = address_end + 2;
|
||||
let second_end = first_end + 4;
|
||||
if code.get(ORDINARY_ADDRESS_BYTES..first_end)? != [MOV_LOAD, ECX_FROM_RAX_MEMORY]
|
||||
if code.get(address_end..first_end)? != [MOV_LOAD, ECX_FROM_RAX_MEMORY]
|
||||
|| code.get(first_end..second_end)?
|
||||
!= [REX | REX_R, MOV_LOAD, R8D_FROM_RAX_DISP8, WORD_LOAD_BYTES]
|
||||
{
|
||||
|
||||
@@ -238,6 +238,7 @@ impl LegacyPlan {
|
||||
flag_location: flags::Location::Frame,
|
||||
coalesced: None,
|
||||
allocating_output: false,
|
||||
range_checks: None,
|
||||
};
|
||||
for (guest, index) in (0..GPR_SLOTS)
|
||||
.filter(|&guest| used & (1 << guest) != 0)
|
||||
|
||||
@@ -37,7 +37,12 @@ pub(super) fn address(
|
||||
const LEA_RAX_RAX_RCX: &[u8] = &[0x48, 0x8d, 0x04, 0x08];
|
||||
// Validate incoming SP before offset addition, even if the effective
|
||||
// address would be aligned. No guest register is committed before access.
|
||||
memory_address(code, checks, base, 0, AddressMode::Offset, 1);
|
||||
// Only the final address is checked against the guest's ranges.
|
||||
let base_checks = super::MemoryChecks {
|
||||
guest_range: false,
|
||||
..checks
|
||||
};
|
||||
memory_address(code, base_checks, base, 0, AddressMode::Offset, 1);
|
||||
right_operand(code, index, Width::X64, Shift::Lsl, 0);
|
||||
match extend {
|
||||
IndexExtend::Uxtw => code.extend(MOV_ECX_ECX),
|
||||
@@ -49,7 +54,7 @@ pub(super) fn address(
|
||||
code.push(shift);
|
||||
}
|
||||
code.extend(LEA_RAX_RAX_RCX); // modulo 2^64
|
||||
super::alignment_check(code, checks, bytes);
|
||||
super::address_checks(code, checks, bytes);
|
||||
}
|
||||
|
||||
fn transfer(code: &mut Vec<u8>, operand: &Operand, checks: super::MemoryChecks) {
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
//! DC ZVA in system-mode blocks the engine compiles where it neither traps
|
||||
//! nor is UNDEFINED (`CompilationPlan::with_zero_block`): Arm
|
||||
//! `AArch64_MemZero` writes zeroes to the DCZID_EL0.BS block holding Xt,
|
||||
//! aligned down, through the same direct guest-VA stores as STR. The block
|
||||
//! is at most 2 KiB and naturally aligned, so it lies in one host page and
|
||||
//! either every store completes or the first faults with nothing written;
|
||||
//! aligned down, through the same direct guest-VA stores as STR, after the
|
||||
//! guest range check. The block is at most 2 KiB and naturally aligned, so
|
||||
//! it lies in one host page and either every store completes or the check
|
||||
//! or the first store faults with nothing written;
|
||||
//! the engine then completes the instruction itself, which reports Xt as
|
||||
//! the fault address and checks watchpoints over the whole block. Code
|
||||
//! clobbers RAX, RCX and RDX.
|
||||
@@ -48,6 +49,9 @@ pub(crate) fn emit(code: &mut Vec<u8>, rt: u8, bytes: u16) {
|
||||
Register::X(rt)
|
||||
},
|
||||
);
|
||||
// Aligning down keeps bits 63:48, so Xt is in range exactly when the
|
||||
// block is.
|
||||
code.extend(super::GUEST_RANGE_CHECK);
|
||||
let mask = -i32::from(bytes);
|
||||
if let Ok(mask) = i8::try_from(mask) {
|
||||
code.extend([0x48, 0x83, 0xe0, mask as u8]); // and rax,-bytes
|
||||
|
||||
@@ -172,7 +172,8 @@ pub enum FaultCause {
|
||||
Translation(mmu::Unsupported),
|
||||
/// An x86 #GP: the address is not canonical for x86 (tags, wild pointers).
|
||||
NonCanonical,
|
||||
/// An x86 #UD from a native check (16-byte SP alignment).
|
||||
/// An x86 #UD from a native check: SP alignment, an Alignment fault, or
|
||||
/// an address outside the guest's ranges.
|
||||
InvalidOpcode,
|
||||
/// The access reached a page [`Watch`] keeps unmapped.
|
||||
Watched,
|
||||
@@ -1036,11 +1037,11 @@ impl<H: Host, D: Devices> Machine<H, D> {
|
||||
*self.memory_checks.get_or_insert_with(|| {
|
||||
let sctlr = self.cpu.regime_sctlr();
|
||||
let bit = if self.cpu.pstate.el == 0 { 4 } else { 3 };
|
||||
MemoryChecks {
|
||||
stack_alignment: sctlr & (1 << bit) != 0,
|
||||
alignment: sctlr & mmu::alignment::SCTLR_A != 0,
|
||||
ordered_granule: sctlr & mmu::alignment::SCTLR_NAA == 0,
|
||||
}
|
||||
MemoryChecks::system(
|
||||
sctlr & (1 << bit) != 0,
|
||||
sctlr & mmu::alignment::SCTLR_A != 0,
|
||||
sctlr & mmu::alignment::SCTLR_NAA == 0,
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -3342,7 +3343,8 @@ impl<H: Host, D: Devices> Machine<H, D> {
|
||||
// with the check (SCTLR_ELx.SA or SA0 set), which comes first,
|
||||
// and for an access that has an Alignment fault: unaligned under
|
||||
// SCTLR_ELx.A, or an atomic, or an ordered access with nAA
|
||||
// clear, crossing its 16-byte granule.
|
||||
// clear, crossing its 16-byte granule; and for an address outside
|
||||
// the guest's two ranges.
|
||||
FaultCause::Watched => self.watched_access(index, pc),
|
||||
FaultCause::InvalidOpcode => {
|
||||
let word = self.word(index, pc)?;
|
||||
@@ -3353,7 +3355,7 @@ impl<H: Host, D: Devices> Machine<H, D> {
|
||||
self.take(Exception::synchronous(Class::SpAlignment, 0, pc));
|
||||
Ok(())
|
||||
} else {
|
||||
self.native_alignment_fault(pc, word)
|
||||
self.native_check_fault(pc, word)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4813,6 +4815,36 @@ mod tests {
|
||||
let (outcome, checks) = run(3, BASE + 0x10e, SCTLR_NAA);
|
||||
assert!(matches!(outcome, Err(Stop::Unsupported(_))));
|
||||
assert!(!checks.unwrap().ordered_granule);
|
||||
// An address outside both ranges, such as Stela's window, takes the
|
||||
// fault of its translation: with the MMU off, an Address size fault
|
||||
// at level 0 (DFSC 0). An Alignment fault still comes first.
|
||||
const WINDOW: u64 = 0x0040_0000_0000_0000;
|
||||
for index in 0..5 {
|
||||
let write = if index == 3 { 1 << 6 } else { 0 };
|
||||
assert_eq!(
|
||||
run(index, WINDOW, 0).0.unwrap(),
|
||||
(0x9600_0000 | write, WINDOW),
|
||||
"{index}"
|
||||
);
|
||||
}
|
||||
assert_eq!(run(0, WINDOW + 4, SCTLR_A).0.unwrap(), (load, WINDOW + 4));
|
||||
}
|
||||
|
||||
/// System-mode blocks check every access against the guest's ranges,
|
||||
/// whatever SCTLR_ELx asks.
|
||||
#[test]
|
||||
fn system_mode_blocks_check_accesses_against_the_guest_ranges() {
|
||||
const CHECK: [u8; 16] = [
|
||||
0x48, 0x89, 0xc1, 0x48, 0xc1, 0xf9, 48, 0xff, 0xc1, 0x83, 0xf9, 0x01, 0x76, 0x02, 0x0f,
|
||||
0x0b,
|
||||
];
|
||||
// ldr x0, [x1]; svc #0
|
||||
let mut machine = machine(&[0xf940_0020, 0xd400_0001]);
|
||||
let Ok(Fetched::Block(index)) = machine.fetch_block(BASE, false) else {
|
||||
panic!("block")
|
||||
};
|
||||
let code = &machine.host.installed[machine.blocks[index].code.0 - 1];
|
||||
assert!(code.windows(CHECK.len()).any(|bytes| bytes == CHECK));
|
||||
}
|
||||
|
||||
impl Machine<FakeHost, NoDevices> {
|
||||
|
||||
@@ -11,7 +11,10 @@ use super::{
|
||||
use crate::machine::{
|
||||
cpu::Exception,
|
||||
exception::Class,
|
||||
mmu::alignment::{self, Kind, Shape},
|
||||
mmu::{
|
||||
self,
|
||||
alignment::{self, Kind, Shape},
|
||||
},
|
||||
};
|
||||
use alloc::{vec, vec::Vec};
|
||||
use stela_compiler::{
|
||||
@@ -24,6 +27,12 @@ use stela_compiler::{
|
||||
|
||||
const PAGE: u64 = super::FETCH_PAGE;
|
||||
|
||||
/// Whether native code accesses `address` directly: bits 63:48 all clear
|
||||
/// or all set, as `x86_64::GUEST_RANGE_CHECK` tests.
|
||||
fn in_guest_range(address: u64) -> bool {
|
||||
matches!(address >> 48, 0 | 0xffff)
|
||||
}
|
||||
|
||||
impl<H: Host, D: Devices> Machine<H, D> {
|
||||
fn index_value(&self, index: Register, extend: IndexExtend, shift: u8) -> u64 {
|
||||
let raw = self.read_register(index);
|
||||
@@ -228,25 +237,51 @@ impl<H: Host, D: Devices> Machine<H, D> {
|
||||
})
|
||||
}
|
||||
|
||||
/// A native alignment check in the block at `index` failed at `pc`:
|
||||
/// take the Alignment fault of the first access that has one (Arm
|
||||
/// `AArch64_UnalignedAccessFaults`), which comes before translation.
|
||||
pub(super) fn native_alignment_fault(&mut self, pc: u64, word: u32) -> Step {
|
||||
/// A native address check failed at `pc`. Take, in Arm's order of the
|
||||
/// instruction's accesses, the first one's Alignment fault (Arm
|
||||
/// `AArch64_UnalignedAccessFaults`, which comes before translation), or
|
||||
/// the fault its translation gives an address outside the guest's two
|
||||
/// ranges (`x86_64::GUEST_RANGE_CHECK`), which the shadow never maps.
|
||||
pub(super) fn native_check_fault(&mut self, pc: u64, word: u32) -> Step {
|
||||
let accesses = self
|
||||
.data_accesses(pc, word)
|
||||
.map_err(|detail| self.refuse_word(word, detail))?;
|
||||
let sctlr = self.cpu.regime_sctlr();
|
||||
match accesses
|
||||
.iter()
|
||||
.find(|(access, shape)| alignment::before_translation(sctlr, access.address, *shape))
|
||||
{
|
||||
for (access, shape) in accesses {
|
||||
// An atomic access reads and writes: its fault is not a write
|
||||
// (Arm `NoFault`).
|
||||
Some((access, _)) => self.alignment_fault(access.address, access.write && !access.read),
|
||||
None => Err(self.unsupported(RequirementKind::Native(
|
||||
"a native alignment check failed where no access faults",
|
||||
))),
|
||||
let write = access.write && !access.read;
|
||||
if alignment::before_translation(sctlr, access.address, shape) {
|
||||
return self.alignment_fault(access.address, write);
|
||||
}
|
||||
if !in_guest_range(access.address) {
|
||||
let kind = if write {
|
||||
mmu::Access::Write
|
||||
} else {
|
||||
mmu::Access::Read
|
||||
};
|
||||
return match self.translate_data(access.address, kind) {
|
||||
mmu::Outcome::Fault(fault) => {
|
||||
self.data_abort(access.address, fault, write, false)
|
||||
}
|
||||
mmu::Outcome::Unsupported(unsupported) => {
|
||||
Err(self.unsupported(RequirementKind::Translation(unsupported)))
|
||||
}
|
||||
// TBI, or a 52-bit range: the shadow maps 48-bit
|
||||
// untagged addresses only.
|
||||
mmu::Outcome::Mapped(_) => {
|
||||
let mut requirement = self.requirement(RequirementKind::Native(
|
||||
"a tagged or 52-bit data address in native code",
|
||||
));
|
||||
requirement.address = Some(access.address);
|
||||
Err(super::Stop::Unsupported(requirement))
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
Err(self.unsupported(RequirementKind::Native(
|
||||
"a native address check failed where no access faults",
|
||||
)))
|
||||
}
|
||||
|
||||
/// A native access reached a watched page: take the watchpoint exception
|
||||
|
||||
+7
-2
@@ -72,9 +72,9 @@ const SYNTHETIC_SLICE_BYTES: u64 = 400_000;
|
||||
const KERNEL: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/kernel.bin"));
|
||||
const KERNEL_OPTIONS: &str =
|
||||
"--system --load 0x800004000 --entry 0x800004000 --ram-bytes 0x100000000";
|
||||
/// What the test kernel must leave in X0-X7 when it idles; X1 and X2, its
|
||||
/// What the test kernel must leave in X0-X10 when it idles; X1 and X2, its
|
||||
/// tasks' SVC counts, need only be nonzero.
|
||||
const KERNEL_RESULTS: [(usize, Option<u64>); 8] = [
|
||||
const KERNEL_RESULTS: [(usize, Option<u64>); 11] = [
|
||||
(0, Some(0x5354_454c_4120_4f4b)),
|
||||
(1, None),
|
||||
(2, None),
|
||||
@@ -85,6 +85,11 @@ const KERNEL_RESULTS: [(usize, Option<u64>); 8] = [
|
||||
// EL1 SVC #0x10 and EL0 SVC #1.
|
||||
(6, Some(0x5600_0010)),
|
||||
(7, Some(0x5600_0001)),
|
||||
// EL1 load and store at the Stela window's address, outside both
|
||||
// ranges: level 0 translation faults, the store's with WnR.
|
||||
(8, Some(0x9600_0004)),
|
||||
(9, Some(0x9600_0044)),
|
||||
(10, Some(0x0040_0000_0000_0000)),
|
||||
];
|
||||
|
||||
/// System options for a boot bundle: the J473AP DRAM base and 8 GiB.
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
// x3 = timer switches
|
||||
// x4, x5 = ESR and FAR of the EL1 data abort
|
||||
// x6 = ESR of the EL1 SVC, x7 = ESR of the last EL0 SVC
|
||||
// x8, x9 = ESRs of the EL1 load and store at WINDOW_VA, x10 = its FAR
|
||||
|
||||
.set BLOCK, 0x2000000
|
||||
.set KERNEL_VA, 0xffffff8000000000
|
||||
@@ -24,6 +25,9 @@
|
||||
.set KDATA, 0x320000
|
||||
.set KSTACK_TOP, 0x310000
|
||||
.set USER_VA, 0x100000000
|
||||
// Outside both translation ranges, and the host address of the Stela window
|
||||
// (PML5 entry 64), which must fault like any other.
|
||||
.set WINDOW_VA, 0x0040000000000000
|
||||
.set SWITCHES, 6
|
||||
.set PERIOD, 240000 // 10 ms of the 24 MHz counter
|
||||
.set MAIR, 0xff // Attr0 Normal WB, Attr1 Device-nGnRnE
|
||||
@@ -50,6 +54,9 @@
|
||||
.set D_SWITCHES, 40
|
||||
.set D_CURRENT, 48
|
||||
.set D_USER_ESR, 56
|
||||
.set D_WINDOW_LOAD, 64
|
||||
.set D_WINDOW_STORE, 72
|
||||
.set D_WINDOW_FAR, 80
|
||||
.set D_CONTEXT, 0x100 // two 0x200-byte contexts
|
||||
// Context: x0-x30, then SP_EL0, ELR, SPSR.
|
||||
.set C_X8, 64
|
||||
@@ -142,6 +149,17 @@ high:
|
||||
str w3, [x2, #0x20] // UTXH
|
||||
b 3b
|
||||
5:
|
||||
// EL1 data aborts at an address no range holds: a load, then a store.
|
||||
ldr x6, =WINDOW_VA
|
||||
ldr x7, [x6]
|
||||
ldr x8, [x22, #D_ABORT_ESR]
|
||||
str x8, [x22, #D_WINDOW_LOAD]
|
||||
str xzr, [x22, #D_ABORT_ESR]
|
||||
str x7, [x6]
|
||||
ldr x8, [x22, #D_ABORT_ESR]
|
||||
str x8, [x22, #D_WINDOW_STORE]
|
||||
ldr x8, [x22, #D_ABORT_FAR]
|
||||
str x8, [x22, #D_WINDOW_FAR]
|
||||
// EL1 data abort: level 2 of TTBR1 maps only the first block.
|
||||
ldr x6, =(KERNEL_VA + 0x4000000)
|
||||
ldr x7, [x6]
|
||||
@@ -296,6 +314,9 @@ done:
|
||||
ldr x5, [x0, #D_ABORT_FAR]
|
||||
ldr x6, [x0, #D_SVC_ESR]
|
||||
ldr x7, [x0, #D_USER_ESR]
|
||||
ldr x8, [x0, #D_WINDOW_LOAD]
|
||||
ldr x9, [x0, #D_WINDOW_STORE]
|
||||
ldr x10, [x0, #D_WINDOW_FAR]
|
||||
ldr x0, =0x5354454c41204f4b
|
||||
b finish
|
||||
|
||||
|
||||
Reference in new issue
Block a user