chore(audit): reconcile fixes with current main
This commit is contained in:
commit
a3c4eb91c8
255 files changed
+13395
-3460
No files matched your search
@@ -1138,6 +1138,113 @@ unsafe impl GlobalAlloc for Heap {
|
||||
unsafe { release(state, pointer) };
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn realloc(&self, pointer: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
|
||||
// SAFETY: GlobalAlloc's realloc contract guarantees that this size
|
||||
// rounded to the original alignment fits in isize.
|
||||
let new_layout = unsafe { Layout::from_size_align_unchecked(new_size, layout.align()) };
|
||||
if layout.size() == new_size {
|
||||
return pointer;
|
||||
}
|
||||
let (old_class, new_class) = (class(layout), class(new_layout));
|
||||
if old_class.is_some() && old_class == new_class {
|
||||
// The live block already has the full size-class capacity, and
|
||||
// this resize leaves all class accounting and ownership intact.
|
||||
return pointer;
|
||||
}
|
||||
if old_class.is_none() && new_class.is_none() {
|
||||
let resized = {
|
||||
let _guard = self.lock();
|
||||
// SAFETY: the guard excludes other accesses to the state.
|
||||
let state = unsafe { &mut *self.state.get() };
|
||||
// SAFETY: the old layout identifies a live free-list block
|
||||
// exclusively owned by the caller, and the lock is held.
|
||||
let resized = unsafe { resize_large(state, pointer, new_size) };
|
||||
if resized {
|
||||
state.live = state.live - layout.size() + new_size;
|
||||
state.count_large(layout.size(), false);
|
||||
state.count_large(new_size, true);
|
||||
}
|
||||
resized
|
||||
};
|
||||
if resized {
|
||||
self.count_own(layout, false);
|
||||
self.count_own(new_layout, true);
|
||||
return pointer;
|
||||
}
|
||||
}
|
||||
// SAFETY: both layouts meet GlobalAlloc's realloc contract. A new
|
||||
// successful allocation is disjoint, and only then can the old one
|
||||
// be freed. On failure the old owner keeps its block.
|
||||
unsafe {
|
||||
let next = self.alloc(new_layout);
|
||||
if !next.is_null() {
|
||||
ptr::copy_nonoverlapping(pointer, next, layout.size().min(new_size));
|
||||
self.dealloc(pointer, layout);
|
||||
}
|
||||
next
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Resize a free-list allocation without moving its payload, using or
|
||||
/// returning the following free space in the same pool.
|
||||
///
|
||||
/// # Safety
|
||||
/// The heap's lock is held. `pointer` identifies a live free-list block,
|
||||
/// exclusively owned by the caller, and `new_size` is nonzero.
|
||||
unsafe fn resize_large(state: &mut State, pointer: *mut u8, new_size: usize) -> bool {
|
||||
let Some(wanted) = aligned(new_size, GRANULE).and_then(|bytes| bytes.checked_add(HEADER_BYTES))
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
// SAFETY: the old block and its neighbours have live headers, and the
|
||||
// lock protects both the boundary tags and bins. The replacement header
|
||||
// lies beyond the retained payload and inside the old or joined block.
|
||||
unsafe {
|
||||
let block = pointer.sub(HEADER_BYTES).cast::<Header>();
|
||||
let old_bytes = size(block);
|
||||
if wanted == old_bytes {
|
||||
return true;
|
||||
}
|
||||
let following = block as usize + old_bytes;
|
||||
let next = following as *mut Header;
|
||||
let join = following < state.end && following != state.floor && (*next).size & FREE != 0;
|
||||
let available = if join {
|
||||
old_bytes + size(next)
|
||||
} else {
|
||||
old_bytes
|
||||
};
|
||||
if wanted > available {
|
||||
return false;
|
||||
}
|
||||
let new_bytes = if available - wanted >= MIN_BLOCK {
|
||||
wanted
|
||||
} else {
|
||||
available
|
||||
};
|
||||
if join {
|
||||
state.remove(next);
|
||||
}
|
||||
(*block).size = new_bytes | ((*block).size & PREVIOUS_FREE);
|
||||
if new_bytes < available {
|
||||
let rest = (block as usize + new_bytes) as *mut Header;
|
||||
rest.write(Header {
|
||||
previous: block as usize,
|
||||
size: (available - new_bytes) | FREE,
|
||||
});
|
||||
state.tell_following(rest);
|
||||
state.insert(rest);
|
||||
} else {
|
||||
state.tell_following(block);
|
||||
}
|
||||
state.carved = state.carved - old_bytes + new_bytes;
|
||||
if block as usize >= state.floor {
|
||||
state.carved_reserve = state.carved_reserve - old_bytes + new_bytes;
|
||||
}
|
||||
state.peak = state.peak.max(state.carved);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Where a payload of `payload` bytes aligned to `alignment` fits in free
|
||||
|
||||
@@ -391,6 +391,129 @@ fn size_class_reuse_preserves_other_live_bytes() {
|
||||
assert_eq!(heap.usage().live, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resizing_within_a_size_class_keeps_the_allocation() {
|
||||
let heap = Heap::new();
|
||||
let mut ram = backing();
|
||||
let layout = Layout::from_size_align(50, 16).unwrap();
|
||||
let smaller = Layout::from_size_align(34, 16).unwrap();
|
||||
let larger = Layout::from_size_align(62, 16).unwrap();
|
||||
let next_class = Layout::from_size_align(65, 16).unwrap();
|
||||
// SAFETY: exclusive backing, valid nonzero layouts, and each resize
|
||||
// receives the immediately preceding live allocation and layout.
|
||||
unsafe {
|
||||
heap.initialize(ram.0.as_mut_ptr(), ram.0.len());
|
||||
let before = heap.alloc(layout);
|
||||
assert!(!before.is_null());
|
||||
before.write_bytes(0x5a, layout.size());
|
||||
let usage = usage_values(&heap);
|
||||
let after = heap.realloc(before, layout, larger.size());
|
||||
assert_eq!(after, before);
|
||||
assert_eq!(usage_values(&heap), usage);
|
||||
let shrunk = heap.realloc(after, larger, smaller.size());
|
||||
assert_eq!(shrunk, after);
|
||||
assert_eq!(usage_values(&heap), usage);
|
||||
let moved = heap.realloc(shrunk, smaller, next_class.size());
|
||||
assert!(!moved.is_null() && moved != shrunk);
|
||||
assert_eq!(
|
||||
core::slice::from_raw_parts(moved, smaller.size()),
|
||||
&[0x5a; 34]
|
||||
);
|
||||
heap.dealloc(moved, next_class);
|
||||
}
|
||||
assert_eq!(heap.usage().live, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn large_resize_uses_the_right_extent_and_preserves_live_neighbours() {
|
||||
let heap = Heap::new();
|
||||
let mut ram = backing();
|
||||
let layout = |kib: usize| Layout::from_size_align(kib * 1024, 16).unwrap();
|
||||
let (original, gap, guard) = (layout(28), layout(68), layout(28));
|
||||
let (grown, shrunk, reused) = (layout(90), layout(20), layout(70));
|
||||
// SAFETY: the backing stays exclusive, and each operation uses a live
|
||||
// allocation with the layout most recently assigned to it.
|
||||
unsafe {
|
||||
heap.initialize(ram.0.as_mut_ptr(), ram.0.len());
|
||||
let block = heap.alloc(original);
|
||||
let neighbour = heap.alloc(gap);
|
||||
let sentinel = heap.alloc(guard);
|
||||
assert!(!block.is_null() && !neighbour.is_null() && !sentinel.is_null());
|
||||
block.write_bytes(0x5a, original.size());
|
||||
sentinel.write_bytes(0xa5, guard.size());
|
||||
heap.dealloc(neighbour, gap);
|
||||
|
||||
let before = heap.usage();
|
||||
assert!(before.largest < grown.size());
|
||||
let larger = heap.realloc(block, original, grown.size());
|
||||
assert_eq!(larger, block);
|
||||
let after = heap.usage();
|
||||
assert_eq!(after.carves, before.carves);
|
||||
assert_eq!(after.live, grown.size() + guard.size());
|
||||
assert_eq!(after.large[large_bucket(grown.size())], (1, grown.size()));
|
||||
assert!(
|
||||
core::slice::from_raw_parts(larger, original.size())
|
||||
.iter()
|
||||
.all(|&byte| byte == 0x5a)
|
||||
);
|
||||
|
||||
let smaller = heap.realloc(larger, grown, shrunk.size());
|
||||
assert_eq!(smaller, larger);
|
||||
assert_eq!(heap.usage().live, shrunk.size() + guard.size());
|
||||
let reuse = heap.alloc(reused);
|
||||
assert!(!reuse.is_null());
|
||||
assert!(reuse.addr() > smaller.addr() && reuse.addr() < sentinel.addr());
|
||||
reuse.write_bytes(0xc3, reused.size());
|
||||
assert!(
|
||||
core::slice::from_raw_parts(smaller, shrunk.size())
|
||||
.iter()
|
||||
.all(|&byte| byte == 0x5a)
|
||||
);
|
||||
assert!(
|
||||
core::slice::from_raw_parts(sentinel, guard.size())
|
||||
.iter()
|
||||
.all(|&byte| byte == 0xa5)
|
||||
);
|
||||
heap.dealloc(smaller, shrunk);
|
||||
heap.dealloc(sentinel, guard);
|
||||
heap.dealloc(reuse, reused);
|
||||
}
|
||||
let after = heap.usage();
|
||||
assert_eq!((after.live, after.carved, after.extents), (0, 0, 1));
|
||||
assert_eq!(after.largest, ram.0.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_large_growth_preserves_the_owner_and_the_reserve_boundary() {
|
||||
let heap = Heap::new();
|
||||
let mut ram = backing();
|
||||
let reserve = 32 * 1024;
|
||||
let original = Layout::from_size_align(ram.0.len() - reserve - HEADER_BYTES, 16).unwrap();
|
||||
// SAFETY: exclusive backing, with one main-pool allocation held through
|
||||
// the failed growth and returned using its unchanged layout.
|
||||
unsafe {
|
||||
heap.initialize(ram.0.as_mut_ptr(), ram.0.len());
|
||||
heap.reserve_tail(reserve);
|
||||
let block = heap.alloc(original);
|
||||
assert!(!block.is_null());
|
||||
block.write_bytes(0x96, original.size());
|
||||
let before = usage_values(&heap);
|
||||
assert!(
|
||||
heap.realloc(block, original, original.size() + GRANULE)
|
||||
.is_null()
|
||||
);
|
||||
assert_eq!(usage_values(&heap), before);
|
||||
assert!(
|
||||
core::slice::from_raw_parts(block, original.size())
|
||||
.iter()
|
||||
.all(|&byte| byte == 0x96)
|
||||
);
|
||||
heap.dealloc(block, original);
|
||||
}
|
||||
let after = heap.usage();
|
||||
assert_eq!((after.live, after.carved, after.extents), (0, 0, 2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_class_lists_return_to_the_bins_when_a_request_needs_them() {
|
||||
let mut ram = backing();
|
||||
|
||||
@@ -4,6 +4,10 @@ const PAGE: u64 = 4096;
|
||||
const MIB: u64 = 1024 * 1024;
|
||||
const MINIMUM: u64 = 16 * MIB;
|
||||
const MAXIMUM: u64 = 384 * MIB;
|
||||
|
||||
/// Largest persistent translation pack the mount reads into firmware RAM.
|
||||
pub const MAX_TRANSLATION_PACK_BYTES: u64 = 1024 * MIB;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct InsufficientMemory;
|
||||
impl fmt::Display for InsufficientMemory {
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
//! shadow pool. Each executor owns its own ranges; none is shared.
|
||||
use crate::Result;
|
||||
use crate::topology::MAX_CORES;
|
||||
use alloc::vec::Vec;
|
||||
use core::ops::Range;
|
||||
use stela_contracts::refuse;
|
||||
|
||||
const PAGE: u64 = 4096;
|
||||
@@ -9,6 +11,60 @@ const PAGE: u64 = 4096;
|
||||
pub const STACK_BYTES: u64 = 2 * 1024 * 1024;
|
||||
pub const STACK_STRIDE: u64 = STACK_BYTES + PAGE;
|
||||
pub const INVOCATION_STACK_BYTES: u64 = 128 * 1024;
|
||||
pub const CODE_INSTALL_ALIGNMENT: u64 = 16;
|
||||
|
||||
/// Initialized code extents of one private arena part, stored by exclusive
|
||||
/// end. Installs start at the aligned end of the preceding one, so retaining
|
||||
/// that start as well would duplicate information.
|
||||
#[derive(Default)]
|
||||
pub struct CodeExtents(Vec<u32>);
|
||||
|
||||
impl CodeExtents {
|
||||
/// Reserve one ledger entry, initialize its code, then record the extent.
|
||||
/// A refusal leaves both the ledger and its code unchanged.
|
||||
pub fn append(
|
||||
&mut self,
|
||||
part_bytes: u64,
|
||||
code_bytes: usize,
|
||||
initialize: impl FnOnce(u64),
|
||||
) -> Option<Range<u64>> {
|
||||
let previous = u64::from(self.0.last().copied().unwrap_or(0));
|
||||
let start = previous.next_multiple_of(CODE_INSTALL_ALIGNMENT);
|
||||
let end = start.checked_add(code_bytes as u64)?;
|
||||
if code_bytes == 0 || end > part_bytes {
|
||||
return None;
|
||||
}
|
||||
let finish = u32::try_from(end).ok()?;
|
||||
self.0.try_reserve(1).ok()?;
|
||||
initialize(start);
|
||||
self.0.push(finish);
|
||||
Some(start..end)
|
||||
}
|
||||
|
||||
/// Whether one install owns the whole part-relative interval. Alignment
|
||||
/// gaps and spans across separately initialized installs are refused.
|
||||
pub fn contains(&self, range: Range<u64>) -> bool {
|
||||
if range.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let index = self.0.partition_point(|&end| u64::from(end) <= range.start);
|
||||
self.0.get(index).is_some_and(|&end| {
|
||||
let previous = if index == 0 { 0 } else { self.0[index - 1] };
|
||||
let start = u64::from(previous).next_multiple_of(CODE_INSTALL_ALIGNMENT);
|
||||
start <= range.start && range.end <= u64::from(end)
|
||||
})
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.0.is_empty()
|
||||
}
|
||||
|
||||
/// Forget a part's code when the ring reuses it, keeping the ledger's
|
||||
/// capacity ready for new code.
|
||||
pub fn clear(&mut self) {
|
||||
self.0.clear();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn invocation_stacks(
|
||||
cores: usize,
|
||||
@@ -113,6 +169,50 @@ pub fn partition(
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn installed_code_extents_cover_only_individual_initialized_ranges() {
|
||||
let mut ledger = CodeExtents::default();
|
||||
let mut exact = Vec::new();
|
||||
for bytes in [13, 16, 2, 9, 25, 1] {
|
||||
let start = exact.last().map_or(0, |range: &Range<u64>| {
|
||||
range.end.next_multiple_of(CODE_INSTALL_ALIGNMENT)
|
||||
});
|
||||
let range = ledger
|
||||
.append(128, bytes, |at| assert_eq!(at, start))
|
||||
.unwrap();
|
||||
assert_eq!(range, start..start + bytes as u64);
|
||||
exact.push(range);
|
||||
}
|
||||
for start in 0..=128 {
|
||||
for end in start..=129 {
|
||||
let expected = start < end
|
||||
&& exact
|
||||
.iter()
|
||||
.any(|extent| extent.start <= start && end <= extent.end);
|
||||
assert_eq!(ledger.contains(start..end), expected, "{start}..{end}");
|
||||
}
|
||||
}
|
||||
ledger.clear();
|
||||
assert!(ledger.is_empty());
|
||||
assert!(!ledger.contains(0..1));
|
||||
assert_eq!(ledger.append(64, 7, |_| {}), Some(0..7));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refused_code_installs_leave_the_end_and_backing_untouched() {
|
||||
let mut ledger = CodeExtents::default();
|
||||
assert_eq!(ledger.append(32, 13, |_| {}), Some(0..13));
|
||||
assert_eq!(ledger.append(32, 0, |_| panic!("empty code")), None);
|
||||
assert_eq!(ledger.append(32, 17, |_| panic!("over the part")), None);
|
||||
assert_eq!(
|
||||
ledger.append(u64::MAX, u32::MAX as usize, |_| panic!("over the ledger")),
|
||||
None
|
||||
);
|
||||
assert_eq!(ledger.append(32, 16, |_| {}), Some(16..32));
|
||||
assert!(!ledger.contains(13..16));
|
||||
assert!(ledger.contains(16..32));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn task_plan_keeps_exact_payload_padding_guards_and_classes() {
|
||||
let layout = task_stacks(0x8_0000_0000).unwrap();
|
||||
|
||||
@@ -338,6 +338,8 @@ pub struct System {
|
||||
pub traces: Vec<u64>,
|
||||
/// Log raw guarded entries, exits, exceptions and returns (`--monitor-trace`).
|
||||
pub monitor_trace: bool,
|
||||
/// Log every display swap's DCP calls, present and callback (`--display-trace`).
|
||||
pub display_trace: bool,
|
||||
/// Log every device access in these physical ranges (`--watch BASE,BYTES`).
|
||||
pub watches: Vec<(u64, u64)>,
|
||||
/// Guest virtual ranges the stop's report shows (`--dump BASE,BYTES`).
|
||||
@@ -408,6 +410,7 @@ impl Default for System {
|
||||
breakpoints: Vec::new(),
|
||||
traces: Vec::new(),
|
||||
monitor_trace: false,
|
||||
display_trace: false,
|
||||
watches: Vec::new(),
|
||||
dumps: Vec::new(),
|
||||
}
|
||||
@@ -757,6 +760,7 @@ impl fmt::Display for System {
|
||||
line.flag("--serialized", !self.parallel && !implied_serial)?;
|
||||
line.flag("--profile", self.profile)?;
|
||||
line.flag("--monitor-trace", self.monitor_trace)?;
|
||||
line.flag("--display-trace", self.display_trace)?;
|
||||
line.value("--network-check", self.network_check.as_deref())?;
|
||||
line.value("--audio-check", self.audio_check.map(AudioCheck::name))?;
|
||||
if self.dram_explicit {
|
||||
|
||||
@@ -38,6 +38,7 @@ impl ParseState<'_> {
|
||||
"--profile" => options.profile = true,
|
||||
MAINTENANCE_WRITE => options.maintenance_write = true,
|
||||
"--monitor-trace" => options.monitor_trace = true,
|
||||
"--display-trace" => options.display_trace = true,
|
||||
"--native-shared-check" => flag(
|
||||
&mut options.native_shared_check,
|
||||
Error::DuplicateNativeShared,
|
||||
|
||||
@@ -99,13 +99,15 @@ fn every_option_survives_a_round_trip() {
|
||||
"--system --storage {DISK} --nor {DISK} --bundle b --install p.json \
|
||||
--install-source 11111111-2222-3333-4444-555555555555 --tss --verify-on-read \
|
||||
--usb-storage A --usb-storage B --input --idle-skip --sep-observe --native-cores 3 \
|
||||
--native-artifacts --serialized --profile --monitor-trace \
|
||||
--native-artifacts --serialized --profile --monitor-trace --display-trace \
|
||||
--network-check http://h/p --audio-check transport-duplex --dram-base 0x10000000000 \
|
||||
--load 0x10000004000 --entry 0x10000008000 --x0 7 --budget 99 --break 0x10 \
|
||||
--trace 0x20 --watch 0x30,0x40 --dump x21-0x8,0x10 --dump 0x50,0x60"
|
||||
));
|
||||
assert_eq!(options.usb_storage, ["A", "B"]);
|
||||
assert_eq!(options.audio_check, Some(AudioCheck::TransportDuplex));
|
||||
assert!(options.display_trace);
|
||||
assert!(!System::default().display_trace);
|
||||
assert!(!options.parallel);
|
||||
assert_eq!(options.dumps[0], (Base::Register(21, -8), 0x10));
|
||||
let restore = round_trip(&format!(
|
||||
|
||||
@@ -99,6 +99,20 @@ pub fn indices(address: u64) -> [usize; 3] {
|
||||
]
|
||||
}
|
||||
|
||||
/// Group the leaf slots of a validated page range by their parent table.
|
||||
pub fn leaf_runs(address: u64, pages: usize) -> impl Iterator<Item = (usize, usize, Range<usize>)> {
|
||||
let mut offset = 0;
|
||||
core::iter::from_fn(move || {
|
||||
if offset == pages {
|
||||
return None;
|
||||
}
|
||||
let [pointer, directory, first] = indices(address + offset as u64 * PAGE);
|
||||
let count = (ENTRIES as usize - first).min(pages - offset);
|
||||
offset += count;
|
||||
Some((pointer, directory, first..first + count))
|
||||
})
|
||||
}
|
||||
|
||||
/// The page window of the engine's window at `base`: the rest of the
|
||||
/// directory-pointer table its fixed parts start.
|
||||
pub fn span(base: u64) -> core::ops::Range<u64> {
|
||||
@@ -188,6 +202,20 @@ mod tests {
|
||||
|
||||
const GIB: u64 = 1 << 30;
|
||||
|
||||
#[test]
|
||||
fn leaf_runs_cover_exactly_the_requested_slots_across_table_boundaries() {
|
||||
let address = GIB - 2 * PAGE;
|
||||
assert_eq!(
|
||||
leaf_runs(address, 516).collect::<Vec<_>>(),
|
||||
[(0, 511, 510..512), (1, 0, 0..512), (1, 1, 0..2)]
|
||||
);
|
||||
assert_eq!(leaf_runs(address, 0).next(), None);
|
||||
assert_eq!(
|
||||
leaf_runs(!(PAGE - 1), 1).collect::<Vec<_>>(),
|
||||
[(511, 511, 511..512)]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retiring_ranges_remain_excluded_until_acknowledged() {
|
||||
let mut retiring = Retirements::default();
|
||||
|
||||
@@ -336,13 +336,17 @@ pub fn common_native_target(
|
||||
const POPCNT: u32 = 1 << 23;
|
||||
const AES: u32 = 1 << 25;
|
||||
const SHA: u32 = 1 << 29;
|
||||
const GFNI: u32 = 1 << 8;
|
||||
const LZCNT: u32 = 1 << 5;
|
||||
const CX8: u32 = 1 << 8;
|
||||
const CX16: u32 = 1 << 13;
|
||||
if observations.is_empty() || observations.len() > MAX_CORES {
|
||||
return Err(CapabilityRefusal::InvalidSnapshot);
|
||||
}
|
||||
let (mut ecx, mut edx, mut structured) = (u32::MAX, u32::MAX, u32::MAX);
|
||||
let (mut ecx, mut edx, mut structured_ebx, mut structured_ecx) =
|
||||
(u32::MAX, u32::MAX, u32::MAX, u32::MAX);
|
||||
let mut atomic16 = true;
|
||||
let mut lzcnt = true;
|
||||
for snapshot in observations {
|
||||
let vendor = snapshot
|
||||
.get(0, 0)
|
||||
@@ -353,11 +357,19 @@ pub fn common_native_target(
|
||||
.ok_or(CapabilityRefusal::InvalidSnapshot)?;
|
||||
ecx &= basic.ecx;
|
||||
edx &= basic.edx;
|
||||
structured &= if vendor.eax >= 7 {
|
||||
snapshot.get(7, 0).map_or(0, |record| record.ebx)
|
||||
let structured = if vendor.eax >= 7 {
|
||||
snapshot.get(7, 0).unwrap_or_default()
|
||||
} else {
|
||||
0
|
||||
Cpuid::default()
|
||||
};
|
||||
structured_ebx &= structured.ebx;
|
||||
structured_ecx &= structured.ecx;
|
||||
lzcnt &= snapshot
|
||||
.get(0x8000_0000, 0)
|
||||
.is_some_and(|maximum| maximum.eax >= 0x8000_0001)
|
||||
&& snapshot
|
||||
.get(0x8000_0001, 0)
|
||||
.is_some_and(|record| record.ecx & LZCNT != 0);
|
||||
atomic16 &=
|
||||
TargetCpu::atomic_load16_guaranteed([vendor.ebx, vendor.edx, vendor.ecx], basic.ecx);
|
||||
}
|
||||
@@ -374,7 +386,9 @@ pub fn common_native_target(
|
||||
),
|
||||
(ecx & POPCNT != 0, TargetCpu::with_popcnt),
|
||||
(ecx & AES != 0, TargetCpu::with_aes),
|
||||
(structured & SHA != 0, TargetCpu::with_sha),
|
||||
(structured_ebx & SHA != 0, TargetCpu::with_sha),
|
||||
(structured_ecx & GFNI != 0, TargetCpu::with_gfni),
|
||||
(lzcnt, TargetCpu::with_lzcnt),
|
||||
(edx & CX8 != 0, TargetCpu::with_cx8),
|
||||
(ecx & CX16 != 0, TargetCpu::with_cx16),
|
||||
(atomic16, TargetCpu::with_atomic_load16),
|
||||
|
||||
@@ -675,6 +675,43 @@ fn common_target_obeys_leaf_maxima_vendor_atomicity_and_complete_sse_tiers() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn common_target_keeps_legacy_extensions_independently_and_checks_both_leaf_maxima() {
|
||||
use stela_compiler::TargetCpu;
|
||||
let mut rich = target_snapshot(TargetCpu::INTEL_VENDOR);
|
||||
rich.records[0].ecx &= !((1 << 19) | (1 << 20) | (1 << 28));
|
||||
rich.records[1].ecx |= 1 << 5;
|
||||
rich.records[2].ecx |= 1 << 8;
|
||||
rich.records[4] = Cpuid {
|
||||
leaf: 0x8000_0000,
|
||||
eax: 0x8000_0001,
|
||||
..Cpuid::default()
|
||||
};
|
||||
rich.count = 5;
|
||||
let mut older = rich;
|
||||
for (maximum, feature_lost, feature_kept) in [
|
||||
(3, TargetCpu::Gfni, TargetCpu::Lzcnt),
|
||||
(4, TargetCpu::Lzcnt, TargetCpu::Gfni),
|
||||
] {
|
||||
older.records[maximum].eax -= 1;
|
||||
let common = common_native_target(&[&rich, &older]).unwrap();
|
||||
assert!(common.supports(TargetCpu::Ssse3));
|
||||
assert!(!common.supports(TargetCpu::Sse41));
|
||||
assert!(common.supports(feature_kept));
|
||||
assert!(!common.supports(feature_lost));
|
||||
assert!(!common.supports(TargetCpu::Fma));
|
||||
older = rich;
|
||||
}
|
||||
let common = common_native_target(&[&rich, &older]).unwrap();
|
||||
assert!(common.supports(TargetCpu::Gfni.with_lzcnt()));
|
||||
older.count -= 1;
|
||||
assert!(
|
||||
!common_native_target(&[&rich, &older])
|
||||
.unwrap()
|
||||
.supports(TargetCpu::Lzcnt)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn core_floor_and_la57_are_required_independently_of_bsp() {
|
||||
let baseline = native_snapshot();
|
||||
|
||||
@@ -277,6 +277,7 @@ mod tests {
|
||||
fn each_entry_accounts_for_its_own_image_metadata_and_alignment_slop() {
|
||||
// Private layout/extent model only, not a CPU owner or save.
|
||||
let owner = XstateOwner {
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
processor: 0,
|
||||
layout: layout(),
|
||||
_local: PhantomData,
|
||||
|
||||
@@ -220,6 +220,10 @@ fn development_hardware_model(tree: &mut DeviceTree) -> Result<String> {
|
||||
"the selected Apple board hardware model is not first in compatible"
|
||||
));
|
||||
}
|
||||
// A prepared bundle may already carry the development identity.
|
||||
if value.ends_with(b"DEV") {
|
||||
return Ok(target);
|
||||
}
|
||||
let mut development_compatible = Vec::with_capacity(compatible.len());
|
||||
development_compatible.extend_from_slice(target.as_bytes());
|
||||
development_compatible.push(0);
|
||||
@@ -701,6 +705,14 @@ fn run_machine<H: Host>(
|
||||
if !options.breakpoints.is_empty() {
|
||||
machine.set_breakpoints(&options.breakpoints);
|
||||
}
|
||||
machine
|
||||
.devices
|
||||
.with(|devices| devices.set_display_swap_tracing(options.display_trace));
|
||||
if options.display_trace {
|
||||
output::arguments(format_args!(
|
||||
"DISPLAY TRACE enabled: per-swap DCP reports\n"
|
||||
));
|
||||
}
|
||||
machine.set_monitor_tracing(options.monitor_trace);
|
||||
if options.monitor_trace {
|
||||
output::arguments(format_args!(
|
||||
|
||||
@@ -486,7 +486,7 @@ pub(super) fn entropy(buffer: &mut [u8]) -> Result<()> {
|
||||
|
||||
/// The bundle's `bundle.json`, from the files the loader read or a bundle
|
||||
/// built in the heap.
|
||||
fn manifest(files: &[File], built: Option<&[(String, Vec<u8>)]>) -> Result<Manifest> {
|
||||
pub(super) fn manifest(files: &[File], built: Option<&[(String, Vec<u8>)]>) -> Result<Manifest> {
|
||||
let json = match built {
|
||||
Some(built) => built
|
||||
.iter()
|
||||
@@ -501,18 +501,6 @@ fn manifest(files: &[File], built: Option<&[(String, Vec<u8>)]>) -> Result<Manif
|
||||
Manifest::parse(json).map_err(|error| refuse!("bundle manifest: {error}", %error))
|
||||
}
|
||||
|
||||
/// The guest DRAM base the bundle was prepared for (`bundle.json`).
|
||||
pub fn dram_base(files: &[File], built: Option<&[(String, Vec<u8>)]>) -> Result<u64> {
|
||||
Ok(manifest(files, built)?.options.dram_base)
|
||||
}
|
||||
|
||||
/// Whether the bundle's system was personalized for a development board.
|
||||
pub fn development_board(files: &[File], built: Option<&[(String, Vec<u8>)]>) -> Result<bool> {
|
||||
Ok(manifest(files, built)?
|
||||
.target
|
||||
.is_some_and(|target| target.device_class.ends_with("dev")))
|
||||
}
|
||||
|
||||
/// The guest's DRAM: `backed` bytes of host RAM from `base`, within the
|
||||
/// `installed` bytes the Mac reports.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
|
||||
@@ -9,7 +9,7 @@ use crate::{Result, output};
|
||||
use alloc::{boxed::Box, format};
|
||||
use core::{cell::UnsafeCell, ffi::c_int, ffi::c_void, ptr::NonNull};
|
||||
use stela_contracts::refuse;
|
||||
use stela_drivers::gpu::metal::kms::{Display, Drm};
|
||||
use stela_drivers::gpu::metal::kms::{Display, Drm, Error as DisplayError};
|
||||
use stela_soc::machine::{Scanout, ScanoutFormat, ScanoutMode};
|
||||
|
||||
/// A GPU's primary node, the DRM master.
|
||||
@@ -47,6 +47,23 @@ impl Scanout for KmsScanout {
|
||||
fn present(&mut self, rows: &[u8]) -> Result<()> {
|
||||
console::release();
|
||||
let presented = self.0.present(rows);
|
||||
self.finish_present(presented)
|
||||
}
|
||||
|
||||
fn try_present_rows(
|
||||
&mut self,
|
||||
fill: &mut dyn FnMut(usize, &mut [u8]) -> Result<()>,
|
||||
) -> Result<bool> {
|
||||
let prepared = self.0.prepare_rows(fill)?;
|
||||
console::release();
|
||||
let presented = prepared.present();
|
||||
self.finish_present(presented)?;
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
|
||||
impl KmsScanout {
|
||||
fn finish_present(&self, presented: Result<(), DisplayError>) -> Result<()> {
|
||||
// A stop's reason shows on the buffer that does.
|
||||
console::parked_on(screen(&self.0));
|
||||
presented.map_err(|error| {
|
||||
|
||||
@@ -33,6 +33,7 @@ use crate::{
|
||||
};
|
||||
use alloc::{sync::Arc, vec::Vec};
|
||||
use core::arch::{asm, global_asm};
|
||||
use stela_boot_core::native_resources::{CODE_INSTALL_ALIGNMENT, CodeExtents};
|
||||
use stela_compiler::{GuestState, block::BlockExit};
|
||||
use stela_contracts::refuse;
|
||||
use stela_engine::machine::FaultCause;
|
||||
@@ -234,6 +235,8 @@ struct Bank {
|
||||
used: u64,
|
||||
}
|
||||
const ROOTS: usize = 2 * VIEWS;
|
||||
const SHADOW_ROOTS: usize = ROOTS * (BANKS + 1);
|
||||
const _: () = assert!(SHADOW_ROOTS <= u64::BITS as usize);
|
||||
|
||||
/// Root `view`'s TLB context while PCIDE is set.
|
||||
const fn view_context(view: usize) -> u64 {
|
||||
@@ -301,22 +304,29 @@ impl Contexts {
|
||||
fn forget(&mut self, page: u64, current: usize) {
|
||||
invlpg(page);
|
||||
for view in 0..ROOTS {
|
||||
if view == current || self.stale[view] {
|
||||
continue;
|
||||
}
|
||||
if self.invpcid {
|
||||
let descriptor = [view_context(view), page];
|
||||
// SAFETY: a valid single-address INVPCID of a tagged context:
|
||||
// a context is fresh only under PCIDE ([`State::load_view`]).
|
||||
unsafe {
|
||||
asm!("invpcid {}, [{}]", in(reg) 0u64, in(reg) &descriptor,
|
||||
options(nostack, preserves_flags))
|
||||
};
|
||||
} else {
|
||||
self.stale[view] = true;
|
||||
if view != current {
|
||||
self.forget_inactive(page, view);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Drop a page from one inactive view, whose context can be retained
|
||||
/// across CR3 loads only while tagged and fresh.
|
||||
fn forget_inactive(&mut self, page: u64, view: usize) {
|
||||
if !self.tagged || self.stale[view] {
|
||||
return;
|
||||
}
|
||||
if self.invpcid {
|
||||
let descriptor = [view_context(view), page];
|
||||
// SAFETY: a valid single-address INVPCID of an inactive PCID.
|
||||
unsafe {
|
||||
asm!("invpcid {}, [{}]", in(reg) 0u64, in(reg) &descriptor,
|
||||
options(nostack, preserves_flags))
|
||||
};
|
||||
} else {
|
||||
self.stale[view] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Frames reserved for roots and other permanent tables.
|
||||
const PERMANENT_FRAMES: u64 = 64;
|
||||
@@ -397,13 +407,11 @@ pub struct State {
|
||||
code_virtual: u64,
|
||||
code_physical: u64,
|
||||
code_bytes: u64,
|
||||
/// The arena's part new code goes to, and the offset after the code
|
||||
/// installed last.
|
||||
/// The arena part new code goes to.
|
||||
code_unit: u64,
|
||||
code_used: u64,
|
||||
/// Successful initialized installs in each arena unit, from its start.
|
||||
/// These metadata ranges require this State's backing/root/CPU owner.
|
||||
installed_ranges: [Vec<(u32, u32)>; CODE_UNITS as usize],
|
||||
/// These extents require this State's backing, root and CPU owner.
|
||||
installed_extents: [CodeExtents; CODE_UNITS as usize],
|
||||
/// The furthest the arena's code has reached: what the run needed of it
|
||||
/// until it first filled and new code reclaimed the oldest.
|
||||
code_peak: u64,
|
||||
@@ -440,6 +448,9 @@ pub struct State {
|
||||
/// The lower half's root entries any root may hold, by index: a switch
|
||||
/// of TTBR0 visits these, a few, rather than every entry of the half.
|
||||
lower_used: [u64; ROOT_ENTRIES / 64],
|
||||
/// Physical shadow roots that may hold any lower entry, indexed by
|
||||
/// their permanent pool frame after the host root.
|
||||
lower_roots: u64,
|
||||
/// Switches of the lower half to another TTBR0, those that found its
|
||||
/// half kept, and the kept halves a TLBI or a bank's replacement
|
||||
/// dropped.
|
||||
@@ -552,16 +563,17 @@ pub unsafe fn install(config: Config) -> Result<HostOwner> {
|
||||
};
|
||||
let host_root = root()?;
|
||||
let mut roots = [0; ROOTS];
|
||||
for slot in &mut roots {
|
||||
*slot = root()?;
|
||||
}
|
||||
let mut banks = [Bank {
|
||||
rights: None,
|
||||
roots: [0; ROOTS],
|
||||
used: 0,
|
||||
}; BANKS];
|
||||
for slot in banks.iter_mut().flat_map(|bank| &mut bank.roots) {
|
||||
let shadow_roots = roots
|
||||
.iter_mut()
|
||||
.chain(banks.iter_mut().flat_map(|bank| &mut bank.roots));
|
||||
for (index, slot) in shadow_roots.enumerate() {
|
||||
*slot = root()?;
|
||||
assert_eq!(*slot, host_root + (index as u64 + 1) * PAGE);
|
||||
}
|
||||
load_root(host_root);
|
||||
let apic = Apic::new(
|
||||
@@ -596,8 +608,7 @@ pub unsafe fn install(config: Config) -> Result<HostOwner> {
|
||||
code_physical: config.code_physical,
|
||||
code_bytes: config.code_bytes,
|
||||
code_unit: 0,
|
||||
code_used: 0,
|
||||
installed_ranges: core::array::from_fn(|_| Vec::new()),
|
||||
installed_extents: core::array::from_fn(|_| CodeExtents::default()),
|
||||
code_peak: 0,
|
||||
installed_immutable: InstalledCodeCache::default(),
|
||||
recorded: None,
|
||||
@@ -624,6 +635,7 @@ pub unsafe fn install(config: Config) -> Result<HostOwner> {
|
||||
lower_globals: None,
|
||||
kept: Kept::new(),
|
||||
lower_used: [0; ROOT_ENTRIES / 64],
|
||||
lower_roots: 0,
|
||||
lower_switches: 0,
|
||||
lower_found: 0,
|
||||
kept_dropped: 0,
|
||||
@@ -840,15 +852,11 @@ impl State {
|
||||
if unit == 0 || end > self.code_bytes {
|
||||
return false;
|
||||
}
|
||||
let Some(ranges) = self.installed_ranges.get((offset / unit) as usize) else {
|
||||
let Some(extents) = self.installed_extents.get((offset / unit) as usize) else {
|
||||
return false;
|
||||
};
|
||||
let base = offset / unit * unit;
|
||||
let (offset, end) = (offset - base, end - base);
|
||||
let index = ranges.partition_point(|&(_, finish)| u64::from(finish) <= offset);
|
||||
ranges
|
||||
.get(index)
|
||||
.is_some_and(|&(start, finish)| u64::from(start) <= offset && end <= u64::from(finish))
|
||||
extents.contains(offset - base..end - base)
|
||||
}
|
||||
|
||||
fn host_physical(&self, guest: u64) -> Option<u64> {
|
||||
@@ -868,6 +876,8 @@ impl State {
|
||||
|
||||
fn reset_shadow(&mut self, cause: Cause) {
|
||||
if !self.legacy_translations_dirty {
|
||||
// Device translations can exist without any populated RAM view.
|
||||
self.tlb.clear_devices();
|
||||
return;
|
||||
}
|
||||
self.clear(LOWER);
|
||||
@@ -889,12 +899,18 @@ impl State {
|
||||
|
||||
/// TTBR0 or the lower half's TCR fields changed from `from` to `to`:
|
||||
/// detach the lower half from every root and keep it, and attach the
|
||||
/// half kept for `to`, if any.
|
||||
fn switch_lower(&mut self, from: (u64, u64), to: (u64, u64)) {
|
||||
/// half kept for `to`, if any. Return the views the caller must flush.
|
||||
fn switch_lower(&mut self, from: (u64, u64), to: (u64, u64)) -> [bool; ROOTS] {
|
||||
self.lower_switches += 1;
|
||||
let mut entries = Vec::new();
|
||||
for root in self.all_roots() {
|
||||
for entry in self.lower_entries() {
|
||||
let mut changed = 0;
|
||||
let lower_roots = core::mem::take(&mut self.lower_roots);
|
||||
for entry in self.lower_entries() {
|
||||
let mut roots = lower_roots;
|
||||
while roots != 0 {
|
||||
let index = roots.trailing_zeros();
|
||||
roots &= roots - 1;
|
||||
let root = self.host_root + (u64::from(index) + 1) * PAGE;
|
||||
// SAFETY: permanent root frames through the physmap.
|
||||
let slot = unsafe { (layout::physical(root) as *mut u64).add(entry) };
|
||||
// SAFETY: as above.
|
||||
@@ -903,6 +919,7 @@ impl State {
|
||||
entries.push((root, entry, value));
|
||||
// SAFETY: as above.
|
||||
unsafe { slot.write(0) };
|
||||
changed |= 1 << index;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -913,13 +930,29 @@ impl State {
|
||||
for &(root, entry, value) in &half.entries {
|
||||
// SAFETY: as above; the half's tables are still the pool's.
|
||||
unsafe { (layout::physical(root) as *mut u64).add(entry).write(value) };
|
||||
self.lower_used[entry / 64] |= 1 << (entry % 64);
|
||||
self.record_lower(root, entry);
|
||||
changed |= self.lower_root_bit(root);
|
||||
}
|
||||
self.extents[LOWER] = half.extents;
|
||||
}
|
||||
// The software TLB is tagged by view, not root.
|
||||
self.tlb.clear();
|
||||
self.reload();
|
||||
if changed == 0 {
|
||||
[false; ROOTS]
|
||||
} else {
|
||||
// Inactive bank roots have no PCID; selecting a bank flushes it.
|
||||
self.roots
|
||||
.map(|root| changed & self.lower_root_bit(root) != 0)
|
||||
}
|
||||
}
|
||||
|
||||
fn lower_root_bit(&self, root: u64) -> u64 {
|
||||
let index = (root - self.host_root) / PAGE - 1;
|
||||
debug_assert!(root.is_multiple_of(PAGE) && index < SHADOW_ROOTS as u64);
|
||||
1 << index
|
||||
}
|
||||
|
||||
fn record_lower(&mut self, root: u64, entry: usize) {
|
||||
self.lower_used[entry / 64] |= 1 << (entry % 64);
|
||||
self.lower_roots |= self.lower_root_bit(root);
|
||||
}
|
||||
|
||||
/// The lower half's root entries [`State::lower_used`] names.
|
||||
@@ -945,7 +978,7 @@ impl State {
|
||||
|
||||
/// Take the roots of rights `to` from their bank, leaving those of
|
||||
/// `from` there: a bank of `to`, or else the least recently used,
|
||||
/// emptied.
|
||||
/// emptied. The caller must flush the views.
|
||||
fn switch_bank(&mut self, from: Rights, to: Rights) {
|
||||
self.bank_switches += 1;
|
||||
let index = match self.banks.iter().position(|bank| bank.rights == Some(to)) {
|
||||
@@ -972,9 +1005,6 @@ impl State {
|
||||
core::mem::swap(&mut bank.roots, &mut self.roots);
|
||||
bank.rights = Some(from);
|
||||
bank.used = self.bank_switches;
|
||||
// The software TLB is tagged by view, not root.
|
||||
self.tlb.clear();
|
||||
self.reload();
|
||||
}
|
||||
|
||||
/// Every root the shadow fills: the current ones and the banks'.
|
||||
@@ -993,6 +1023,7 @@ impl State {
|
||||
}
|
||||
if half == LOWER {
|
||||
self.lower_used = [0; ROOT_ENTRIES / 64];
|
||||
self.lower_roots = 0;
|
||||
self.drop_kept();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ pub struct BareHost<'a> {
|
||||
pub(super) const CODE_UNITS: u64 = 32;
|
||||
|
||||
pub(super) fn code_unit_bytes(state: &State) -> u64 {
|
||||
state.code_bytes / CODE_UNITS / 16 * 16
|
||||
state.code_bytes / CODE_UNITS / CODE_INSTALL_ALIGNMENT * CODE_INSTALL_ALIGNMENT
|
||||
}
|
||||
|
||||
impl Host for BareHost<'_> {
|
||||
@@ -83,6 +83,21 @@ impl Host for BareHost<'_> {
|
||||
})
|
||||
}
|
||||
|
||||
fn read_ram_descriptor(&mut self, physical: u64) -> Option<u64> {
|
||||
super::super::speculation::fence();
|
||||
if let Some(ram) = &state().registered_ram {
|
||||
return ram.read_descriptor(physical).ok();
|
||||
}
|
||||
let (host, bytes) = state().run(physical)?;
|
||||
if bytes < 8 || !host.is_multiple_of(8) {
|
||||
return None;
|
||||
}
|
||||
// SAFETY: this aligned descriptor fits in one live RAM run and
|
||||
// the physical window maps the entire run. No Rust reference to
|
||||
// guest memory is formed.
|
||||
Some(unsafe { (layout::physical(host) as *const u64).read_volatile() })
|
||||
}
|
||||
|
||||
fn write_ram(&mut self, physical: u64, data: &[u8]) -> bool {
|
||||
if let Some(ram) = &state().registered_ram {
|
||||
// SAFETY: private copyout staging; the canonical owner performs
|
||||
@@ -168,34 +183,29 @@ impl Host for BareHost<'_> {
|
||||
}
|
||||
fn install(&mut self, code: &[u8]) -> Result<NativeCode, InstallError> {
|
||||
let state = state();
|
||||
let offset = state.code_used.next_multiple_of(16);
|
||||
let end = offset + code.len() as u64;
|
||||
if end > (state.code_unit + 1) * code_unit_bytes(state) {
|
||||
return Err(InstallError::Full);
|
||||
}
|
||||
state.installed_ranges[state.code_unit as usize]
|
||||
.try_reserve(1)
|
||||
.map_err(|_| InstallError::Full)?;
|
||||
if code.is_empty() {
|
||||
return Err(InstallError::Full);
|
||||
}
|
||||
// SAFETY: arena bytes through the writable physmap alias.
|
||||
unsafe {
|
||||
core::ptr::copy_nonoverlapping(
|
||||
code.as_ptr(),
|
||||
layout::physical(state.code_physical + offset) as *mut u8,
|
||||
code.len(),
|
||||
);
|
||||
}
|
||||
serialize_code();
|
||||
let unit = state.code_unit * code_unit_bytes(state);
|
||||
state.installed_ranges[state.code_unit as usize]
|
||||
.push(((offset - unit) as u32, (end - unit) as u32));
|
||||
state.code_used = end;
|
||||
state.code_peak = state.code_peak.max(end);
|
||||
let part_bytes = code_unit_bytes(state);
|
||||
let part_offset = state.code_unit * part_bytes;
|
||||
let physical = state.code_physical + part_offset;
|
||||
let extent = state.installed_extents[state.code_unit as usize]
|
||||
.append(part_bytes, code.len(), |start| {
|
||||
// SAFETY: the ledger reserves this nonoverlapping extent in
|
||||
// the owned arena. The writable physmap reaches it.
|
||||
unsafe {
|
||||
core::ptr::copy_nonoverlapping(
|
||||
code.as_ptr(),
|
||||
layout::physical(physical + start) as *mut u8,
|
||||
code.len(),
|
||||
);
|
||||
}
|
||||
serialize_code();
|
||||
})
|
||||
.ok_or(InstallError::Full)?;
|
||||
state.code_peak = state.code_peak.max(part_offset + extent.end);
|
||||
#[cfg(feature = "native-profile")]
|
||||
state.native_profile.copied(code.len());
|
||||
Ok(NativeCode((state.code_virtual + offset) as usize))
|
||||
Ok(NativeCode(
|
||||
(state.code_virtual + part_offset + extent.start) as usize,
|
||||
))
|
||||
}
|
||||
|
||||
fn install_immutable(&mut self, code: &Arc<Vec<u8>>) -> Result<NativeCode, InstallError> {
|
||||
@@ -257,20 +267,27 @@ impl Host for BareHost<'_> {
|
||||
let state = state();
|
||||
state.installed_immutable.clear();
|
||||
state.code_unit = 0;
|
||||
state.code_used = 0;
|
||||
for ranges in &mut state.installed_ranges {
|
||||
ranges.clear();
|
||||
for extents in &mut state.installed_extents {
|
||||
extents.clear();
|
||||
}
|
||||
}
|
||||
|
||||
fn code_partitions(&self) -> Option<stela_engine::machine::engine::CodePartitions> {
|
||||
let state = state();
|
||||
Some(stela_engine::machine::engine::CodePartitions {
|
||||
base: state.code_virtual as usize,
|
||||
bytes_per_part: code_unit_bytes(state) as usize,
|
||||
parts: CODE_UNITS as usize,
|
||||
})
|
||||
}
|
||||
|
||||
fn reclaim_code(&mut self) -> Option<core::ops::Range<usize>> {
|
||||
let state = state();
|
||||
state.installed_immutable.clear();
|
||||
let unit = code_unit_bytes(state);
|
||||
state.code_unit = (state.code_unit + 1) % CODE_UNITS;
|
||||
state.installed_ranges[state.code_unit as usize].clear();
|
||||
state.code_used = state.code_unit * unit;
|
||||
let start = (state.code_virtual + state.code_used) as usize;
|
||||
state.installed_extents[state.code_unit as usize].clear();
|
||||
let start = (state.code_virtual + state.code_unit * unit) as usize;
|
||||
Some(start..start + unit as usize)
|
||||
}
|
||||
|
||||
@@ -283,12 +300,13 @@ impl Host for BareHost<'_> {
|
||||
// blocks again.
|
||||
let Some(part) = (1..CODE_UNITS)
|
||||
.map(|step| (state.code_unit + step) % CODE_UNITS)
|
||||
.find(|&part| !state.installed_ranges[part as usize].is_empty())
|
||||
.find(|&part| !state.installed_extents[part as usize].is_empty())
|
||||
else {
|
||||
return Some(0..0);
|
||||
};
|
||||
state.installed_immutable.clear();
|
||||
state.installed_ranges[part as usize].clear();
|
||||
// This reclaim is for heap pressure, so give back the ledger too.
|
||||
state.installed_extents[part as usize] = CodeExtents::default();
|
||||
let unit = code_unit_bytes(state);
|
||||
let start = (state.code_virtual + part * unit) as usize;
|
||||
Some(start..start + unit as usize)
|
||||
@@ -352,6 +370,7 @@ impl Host for BareHost<'_> {
|
||||
|
||||
fn set_regime(&mut self, regime: &Regime) {
|
||||
let state = state();
|
||||
let mut changed_roots = None;
|
||||
if let Some(current) = state.regime
|
||||
&& current.controls != regime.controls
|
||||
{
|
||||
@@ -386,12 +405,18 @@ impl Host for BareHost<'_> {
|
||||
if rest == to && (!lower || asid || !state.extents[UPPER].private()) {
|
||||
if lower {
|
||||
let key = |c: &mmu::Controls| (c.ttbr0, c.tcr & lower_tcr);
|
||||
state.switch_lower(key(&from), key(&to));
|
||||
changed_roots = Some(state.switch_lower(key(&from), key(&to)));
|
||||
}
|
||||
let rights = |c: &mmu::Controls| (c.sprr.el0, c.sprr.el1, c.tcr & user_tcr);
|
||||
let (from, to) = (rights(&from), rights(&to));
|
||||
if from != to {
|
||||
let bank = from != to;
|
||||
if bank {
|
||||
state.switch_bank(from, to);
|
||||
changed_roots = Some([true; ROOTS]);
|
||||
}
|
||||
// The helper's software TLB keys neither TTBR0 nor the bank.
|
||||
if lower || bank {
|
||||
state.tlb.clear();
|
||||
}
|
||||
} else {
|
||||
let ttbr0 = mmu::Controls {
|
||||
@@ -438,13 +463,21 @@ impl Host for BareHost<'_> {
|
||||
(_, false, false) => EL1_VIEW,
|
||||
(_, true, false) => PAN_VIEW,
|
||||
} + if regime.tag_checked() { VIEWS } else { 0 };
|
||||
if state.current != view {
|
||||
let load = state.root_of(view) != state.root_of(state.current);
|
||||
state.current = view;
|
||||
if load {
|
||||
state.view_switches += 1;
|
||||
state.load_view(view);
|
||||
let root = state.root_of(view);
|
||||
let switch_view = root != state.root_of(state.current);
|
||||
state.current = view;
|
||||
state.view_switches += u64::from(switch_view);
|
||||
// Lower-half and bank changes, and a switch of the active view,
|
||||
// can coincide. Load the final view after applying all of them.
|
||||
let mut load = switch_view;
|
||||
if let Some(changed) = changed_roots {
|
||||
for (stale, changed) in state.contexts.stale.iter_mut().zip(changed) {
|
||||
*stale |= changed;
|
||||
}
|
||||
load |= changed[root];
|
||||
}
|
||||
if load {
|
||||
state.load_view(view);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -482,38 +515,66 @@ impl Host for BareHost<'_> {
|
||||
return state.reset_shadow(Cause::Maintained);
|
||||
}
|
||||
state.tlb.clear();
|
||||
let mut unmapped = Vec::new();
|
||||
// Most maintenance addresses reach a single extent, without a
|
||||
// large overlapping leaf or a second half.
|
||||
let mut first_range = None;
|
||||
let mut extra_ranges = Vec::new();
|
||||
let mut pages = 0u64;
|
||||
let mut whole = false;
|
||||
for half in [LOWER, UPPER] {
|
||||
match state.extents[half].ranges(reach, state.half_range(half)) {
|
||||
None => {
|
||||
state.clear(half);
|
||||
whole = true;
|
||||
let bounds = state.half_range(half);
|
||||
if !state.extents[half].visit_ranges(reach, bounds, |first, last| {
|
||||
pages = pages.saturating_add(((last >> 12) - (first >> 12)) + 1);
|
||||
if first_range.is_none() {
|
||||
first_range = Some((first, last));
|
||||
} else {
|
||||
extra_ranges.push((first, last));
|
||||
}
|
||||
Some(ranges) => unmapped.extend(ranges),
|
||||
}) {
|
||||
state.clear(half);
|
||||
whole = true;
|
||||
}
|
||||
}
|
||||
let mut pages = 0u64;
|
||||
for &(first, last) in &unmapped {
|
||||
for root in state.all_roots() {
|
||||
tables::unmap(&state.pool, root, first, last);
|
||||
}
|
||||
pages = pages.saturating_add(((last - first) >> 12) + 1);
|
||||
}
|
||||
if whole || pages > INVLPG_PAGES {
|
||||
state.reload();
|
||||
} else {
|
||||
for &(first, last) in &unmapped {
|
||||
let mut page = first & !(PAGE - 1);
|
||||
loop {
|
||||
let current = state.root_of(state.current);
|
||||
state.contexts.forget(page, current);
|
||||
if page >= last & !(PAGE - 1) {
|
||||
break;
|
||||
const { assert!(INVLPG_PAGES <= u16::BITS as u64) };
|
||||
let precise = !whole && pages <= INVLPG_PAGES;
|
||||
let current = state.root_of(state.current);
|
||||
let mut reload_current = false;
|
||||
for (first, last) in first_range.into_iter().chain(extra_ranges) {
|
||||
let base = first & !(PAGE - 1);
|
||||
for (view, root) in state.roots.into_iter().enumerate() {
|
||||
let mut removed = 0u16;
|
||||
tables::unmap(&state.pool, root, first, last, |address| {
|
||||
let bit = if precise { (address - base) / PAGE } else { 0 };
|
||||
removed |= 1 << bit;
|
||||
});
|
||||
if whole || removed == 0 {
|
||||
continue;
|
||||
}
|
||||
if !precise {
|
||||
state.contexts.stale[view] = true;
|
||||
reload_current |= view == current;
|
||||
continue;
|
||||
}
|
||||
while removed != 0 {
|
||||
let page = base + u64::from(removed.trailing_zeros()) * PAGE;
|
||||
removed &= removed - 1;
|
||||
if view == current {
|
||||
invlpg(page);
|
||||
} else {
|
||||
state.contexts.forget_inactive(page, view);
|
||||
}
|
||||
page += PAGE;
|
||||
}
|
||||
}
|
||||
// A bank has no PCID while it is inactive. Switching to it
|
||||
// flushes the views before they can use its entries again.
|
||||
for root in state.banks.iter().flat_map(|bank| bank.roots) {
|
||||
tables::unmap(&state.pool, root, first, last, |_| {});
|
||||
}
|
||||
}
|
||||
if whole {
|
||||
state.reload();
|
||||
} else if reload_current {
|
||||
state.load_view(state.current);
|
||||
}
|
||||
if whole {
|
||||
state.resets += 1;
|
||||
|
||||
@@ -154,12 +154,22 @@ pub(super) fn resolve(
|
||||
write: bool,
|
||||
unprivileged: bool,
|
||||
) -> Result<(mmu::Translation, u64), FaultCause> {
|
||||
let regime = state.regime.ok_or(FaultCause::NonCanonical)?;
|
||||
let regime = state.regime.as_ref().ok_or(FaultCause::NonCanonical)?;
|
||||
let access = if write { Access::Write } else { Access::Read };
|
||||
let requester = mmu::Requester {
|
||||
unprivileged: regime.requester.unprivileged || unprivileged,
|
||||
..regime.requester
|
||||
};
|
||||
let virtual_page = address & !(PAGE - 1);
|
||||
if let Some(physical) = state.tlb.device_physical(address, requester, write) {
|
||||
// The cached translation already passed both stages and data
|
||||
// permissions. Watchpoint passes can change without a new walk.
|
||||
return Err(if regime.watch.blocks(virtual_page) {
|
||||
FaultCause::Watched
|
||||
} else {
|
||||
FaultCause::Device { physical }
|
||||
});
|
||||
}
|
||||
let translation = match mmu::translate(
|
||||
®ime.controls,
|
||||
address,
|
||||
@@ -171,16 +181,20 @@ pub(super) fn resolve(
|
||||
Outcome::Fault(fault) => return Err(FaultCause::Guest(fault)),
|
||||
Outcome::Unsupported(unsupported) => return Err(FaultCause::Translation(unsupported)),
|
||||
};
|
||||
if regime.watch.blocks(address & !(PAGE - 1)) {
|
||||
if regime.watch.blocks(virtual_page) {
|
||||
return Err(FaultCause::Watched);
|
||||
}
|
||||
if regime.tag_blocks(address, translation.attributes) {
|
||||
return Err(FaultCause::TagChecked);
|
||||
}
|
||||
let page = translation.physical & !(PAGE - 1);
|
||||
let host = state.host_physical(page).ok_or(FaultCause::Device {
|
||||
physical: translation.physical,
|
||||
})?;
|
||||
let Some(host) = state.host_physical(page) else {
|
||||
// This walker makes no AF or dirty descriptor updates.
|
||||
state.tlb.record_device(address, requester, translation);
|
||||
return Err(FaultCause::Device {
|
||||
physical: translation.physical,
|
||||
});
|
||||
};
|
||||
Ok((translation, host))
|
||||
}
|
||||
|
||||
@@ -200,7 +214,7 @@ pub(crate) fn page_fault(
|
||||
super::super::interrupts::fatal(frame);
|
||||
}
|
||||
state.follow_pan(frame.rflags & RFLAGS_AC == 0);
|
||||
let Some(regime) = state.regime else {
|
||||
let Some(tag_checks) = state.regime.as_ref().map(|regime| regime.tag_checks) else {
|
||||
super::super::interrupts::fatal(frame);
|
||||
};
|
||||
// Only the native ranges are shadow; the rest is the engine's. An
|
||||
@@ -221,23 +235,11 @@ pub(crate) fn page_fault(
|
||||
Ok(resolved) => resolved,
|
||||
Err(cause) => return abandon(state, frame, address, write, cause, saved),
|
||||
};
|
||||
// Filled for EL1 without PAN, a leaf is one PAN guards unless it would
|
||||
// translate the same with PAN set; one filled with PAN set never is.
|
||||
// EL1 and PAN share a root. SMAP guards a leaf if a read with PAN set
|
||||
// would be denied by either stage, or by stage 1's PAN rules.
|
||||
let guarded = state.contexts.pan_flag
|
||||
&& state.current % VIEWS == EL1_VIEW
|
||||
&& !matches!(
|
||||
mmu::translate(
|
||||
®ime.controls,
|
||||
address,
|
||||
Access::Read,
|
||||
mmu::Requester {
|
||||
pan: true,
|
||||
..regime.requester
|
||||
},
|
||||
&mut GuestTables(state),
|
||||
),
|
||||
Outcome::Mapped(same) if same.writable == translation.writable
|
||||
);
|
||||
&& (!translation.readable || translation.pan_sensitive);
|
||||
let rights = PRESENT
|
||||
| NX
|
||||
| if translation.writable { WRITABLE } else { 0 }
|
||||
@@ -276,17 +278,22 @@ pub(crate) fn page_fault(
|
||||
}
|
||||
}
|
||||
};
|
||||
invlpg(virtual_page);
|
||||
// A not-present fault has no cached translation to invalidate. Every
|
||||
// shadow removal already invalidates that view or marks it stale.
|
||||
// A protection fault can replace a present mapping.
|
||||
if frame.error & 1 != 0 {
|
||||
invlpg(virtual_page);
|
||||
}
|
||||
if half == LOWER {
|
||||
let entry = tables::index(virtual_page, layout::top_level());
|
||||
state.lower_used[entry / 64] |= 1 << (entry % 64);
|
||||
state.record_lower(root, entry);
|
||||
}
|
||||
state.extents[half].record(address, translation.size, translation.global);
|
||||
// The rest of the leaf's window has the same translation and rights:
|
||||
// map its RAM pages that are not watched now, as a TLB entry covers
|
||||
// the whole leaf. Pages that were absent need no flush. A Tagged leaf
|
||||
// whose tags are checked maps only the passed page.
|
||||
if regime.tag_checks[half] && translation.attributes == mmu::attributes::TAGGED {
|
||||
if tag_checks[half] && translation.attributes == mmu::attributes::TAGGED {
|
||||
state.fills += 1;
|
||||
return;
|
||||
}
|
||||
@@ -301,9 +308,10 @@ pub(crate) fn page_fault(
|
||||
// fall back to page lookups past the end of that physical run.
|
||||
let (first_host, available) = state.run(physical).unwrap_or((0, 0));
|
||||
let table = slot.wrapping_sub(tables::index(virtual_page, 0));
|
||||
let watch = &state.regime.as_ref().expect("checked above").watch;
|
||||
let mut page = first;
|
||||
loop {
|
||||
if page != virtual_page && !regime.watch.blocks(page) {
|
||||
if page != virtual_page && !watch.blocks(page) {
|
||||
let offset = page - first;
|
||||
let host = if offset < available {
|
||||
first_host.checked_add(offset)
|
||||
|
||||
@@ -97,6 +97,17 @@ impl Remote {
|
||||
}
|
||||
}
|
||||
|
||||
/// Release the restore-only range and ring after the protocol has ended.
|
||||
pub(super) fn retire(&mut self) {
|
||||
self.stop();
|
||||
self.ahead = false;
|
||||
let bytes = self.buffer.capacity();
|
||||
self.buffer = VecDeque::new();
|
||||
output::arguments(format_args!(
|
||||
"REMOTE IMAGE retired read-ahead capacity={bytes}\n"
|
||||
));
|
||||
}
|
||||
|
||||
/// Takes what has arrived, opening a range at the buffer's end first
|
||||
/// when none is open.
|
||||
fn step(&mut self) -> Result<(), NetError> {
|
||||
|
||||
@@ -738,8 +738,16 @@ impl Experiment {
|
||||
}
|
||||
/// Read ahead from the host's storage, without the guest's devices.
|
||||
pub fn pump(&mut self) {
|
||||
if !self.terminal {
|
||||
self.driver.answers.store.reader_mut().pump();
|
||||
let source = self.driver.answers.store.reader_mut();
|
||||
if self.terminal {
|
||||
// The service owns the restore and its network here. Retire the
|
||||
// remote range outside the device lock and leave queued disk I/O
|
||||
// to its existing owner.
|
||||
if let Some(remote) = source.remote.take() {
|
||||
remote.borrow_mut().retire();
|
||||
}
|
||||
} else {
|
||||
source.pump();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -799,7 +807,7 @@ impl Experiment {
|
||||
if let Some(proxy) = &mut self.proxy {
|
||||
proxy.poll(&mut client);
|
||||
}
|
||||
let result = self.driver.poll_ports(&mut client);
|
||||
let result = self.driver.poll_prefetched(&mut client);
|
||||
self.backpressure = client.backpressure();
|
||||
for message in &self.driver.session.ledger()[self.ledger..] {
|
||||
output::arguments(format_args!("{label} ledger={message:?}\n"));
|
||||
|
||||
@@ -340,25 +340,23 @@ fn open_host(
|
||||
.map(|partition| from_disk(partition, options, bluetooth));
|
||||
// A system boots as the board it was installed on: libignition finds its
|
||||
// Cryptex1 tickets by that board's model.
|
||||
if built.is_some() {
|
||||
if options.bundle || built.is_some() {
|
||||
let files = &handoff.files[..handoff.file_count];
|
||||
options.development_board = bundle::development_board(files, built.as_deref())
|
||||
.unwrap_or_else(|error| {
|
||||
output::arguments(format_args!("bundle refusal: {error}\n"));
|
||||
output::fatal("the boot bundle's board could not be read")
|
||||
});
|
||||
}
|
||||
// A bundle runs at the DRAM base it was prepared for, its SoC's.
|
||||
if options.bundle && !options.dram_explicit {
|
||||
let files = &handoff.files[..handoff.file_count];
|
||||
options.dram_base = match bundle::dram_base(files, built.as_deref()) {
|
||||
Ok(base) if base.is_multiple_of(LARGE) => base,
|
||||
Ok(_) => output::fatal("the bundle's DRAM base is not 2 MiB aligned"),
|
||||
Err(error) => {
|
||||
output::arguments(format_args!("bundle refusal: {error}\n"));
|
||||
output::fatal("the boot bundle's DRAM base could not be read")
|
||||
let manifest = bundle::manifest(files, built.as_deref()).unwrap_or_else(|error| {
|
||||
output::arguments(format_args!("bundle refusal: {error}\n"));
|
||||
output::fatal("the boot bundle's manifest could not be read")
|
||||
});
|
||||
options.development_board = manifest
|
||||
.target
|
||||
.is_some_and(|target| target.device_class.ends_with("dev"));
|
||||
// A bundle runs at the DRAM base it was prepared for, its SoC's.
|
||||
if options.bundle && !options.dram_explicit {
|
||||
let base = manifest.options.dram_base;
|
||||
if !base.is_multiple_of(LARGE) {
|
||||
output::fatal("the bundle's DRAM base is not 2 MiB aligned");
|
||||
}
|
||||
};
|
||||
options.dram_base = base;
|
||||
}
|
||||
}
|
||||
ram::place(&mut ram, options.dram_base);
|
||||
host_owner
|
||||
@@ -727,7 +725,7 @@ fn run_guest(boot: Boot<'_>, host: OpenedHost, storage: Storage, processors: Pro
|
||||
"ENTRY pc={entry:#x} x0={x0:#x} el={el} mmu=off profile={} target={} apic_hz={apic_hz} \
|
||||
prediction_isolation={} faulting_data_barrier={}\n",
|
||||
profile.name,
|
||||
target.id(),
|
||||
canonical_ram.target().id(),
|
||||
speculation.contexts,
|
||||
speculation.faulting_data,
|
||||
));
|
||||
@@ -1418,6 +1416,7 @@ fn check_processors(
|
||||
let OpenedHost {
|
||||
owner: ref mut host_owner,
|
||||
mmio: native_mmio,
|
||||
ram: ref worker_ram,
|
||||
..
|
||||
} = *host;
|
||||
for processor in executors.processors() {
|
||||
@@ -1447,15 +1446,29 @@ fn check_processors(
|
||||
doorbells,
|
||||
));
|
||||
}
|
||||
if let Some(mmio) = &native_mmio {
|
||||
// SAFETY: the check owns the host's devices; bus 0's first
|
||||
// function is only read here.
|
||||
let generation = unsafe { mmio.check_shootdown() }.unwrap_or_else(|error| {
|
||||
if handoff.native_resources.cores == 1 && executors.processors().is_empty() {
|
||||
output::arguments(format_args!(
|
||||
"CHECK native-shootdown SKIP reason=no-remote-processor\n"
|
||||
));
|
||||
} else if let Some(mmio) = &native_mmio {
|
||||
let waiter = executors
|
||||
.processors()
|
||||
.first()
|
||||
.unwrap_or_else(|| output::fatal("the shootdown check requires a started AP"));
|
||||
// SAFETY: both processors keep the live loader root. This diagnostic
|
||||
// owns the host's devices and only reads bus 0's first function.
|
||||
let generation = unsafe {
|
||||
waiter.check_driver_wait(handoff.root, sender, handoff.tsc_hz, || {
|
||||
mmio.check_shootdown()
|
||||
})
|
||||
}
|
||||
.unwrap_or_else(|error| output::fatal(error))
|
||||
.unwrap_or_else(|error| {
|
||||
output::arguments(format_args!("CHECK native-shootdown FAIL {error:?}\n"));
|
||||
output::fatal("the MMIO aperture's shootdown failed")
|
||||
});
|
||||
output::arguments(format_args!(
|
||||
"CHECK native-shootdown PASS generation={generation} processors={}\n",
|
||||
"CHECK native-shootdown PASS generation={generation} processors={} waiter=driver-lock-if0\n",
|
||||
executors.processors().len()
|
||||
));
|
||||
}
|
||||
@@ -1469,6 +1482,7 @@ fn check_processors(
|
||||
executors,
|
||||
host_owner,
|
||||
sender,
|
||||
worker_ram,
|
||||
)
|
||||
}
|
||||
.unwrap_or_else(|error| output::fatal(error));
|
||||
|
||||
@@ -148,6 +148,9 @@ fn lock_host_drivers() {
|
||||
.compare_exchange_weak(false, true, Ordering::Acquire, Ordering::Relaxed)
|
||||
.is_err()
|
||||
{
|
||||
// A driver holding this lock can be retiring an aperture mapping.
|
||||
// An interrupt cannot reach this waiter if it entered with IF clear.
|
||||
crate::native_mmio::shootdown::service();
|
||||
core::hint::spin_loop();
|
||||
}
|
||||
let waited = super::host::rdtsc().wrapping_sub(started);
|
||||
@@ -180,7 +183,8 @@ impl RestoreRoot {
|
||||
/// driver never calls back into the engine's host interfaces.
|
||||
///
|
||||
/// # Safety
|
||||
/// `root` is the live loader root, keeping the engine window.
|
||||
/// `root` is the live loader root, keeping the engine window. The
|
||||
/// processor's pinned local record is active.
|
||||
pub(super) unsafe fn enter(root: u64) -> Self {
|
||||
lock_host_drivers();
|
||||
let (previous, flags): (u64, u64);
|
||||
@@ -247,6 +251,17 @@ impl Drop for RestoreRoot {
|
||||
}
|
||||
}
|
||||
|
||||
/// Enter the real host-driver lock for the native contention diagnostic.
|
||||
///
|
||||
/// # Safety
|
||||
/// `root` is the kept loader root, with the current processor installed.
|
||||
#[cfg(feature = "diagnostics")]
|
||||
pub(crate) unsafe fn with_driver_root<T>(root: u64, operation: impl FnOnce() -> T) -> T {
|
||||
// SAFETY: the caller supplies the live root and local owner.
|
||||
let _guard = unsafe { RestoreRoot::enter(root) };
|
||||
operation()
|
||||
}
|
||||
|
||||
struct Service {
|
||||
inner: Box<dyn BlockDevice>,
|
||||
root: u64,
|
||||
|
||||
@@ -21,8 +21,9 @@ use alloc::{boxed::Box, format, string::String, vec};
|
||||
use core::{
|
||||
cell::UnsafeCell,
|
||||
ptr::NonNull,
|
||||
sync::atomic::{AtomicBool, Ordering},
|
||||
sync::atomic::{AtomicBool, AtomicU8, AtomicUsize, Ordering},
|
||||
};
|
||||
use stela_boot_core::memory_budget::MAX_TRANSLATION_PACK_BYTES;
|
||||
use stela_drivers::block::BlockDevice;
|
||||
use stela_engine::machine::Offer;
|
||||
use stela_engine::machine::Translations;
|
||||
@@ -30,8 +31,8 @@ use stela_engine::translations;
|
||||
use stela_engine::translations::Digest;
|
||||
use stela_engine::translations::Record;
|
||||
use stela_engine::translations::pack;
|
||||
use stela_engine::translations::pack::Pack;
|
||||
use stela_engine::translations::pack::Store;
|
||||
use stela_engine::translations::pack::{DecodedRecord, Pack, StagedOffer};
|
||||
use stela_runtime::pc::fat32::Fat32;
|
||||
use stela_runtime::pc::gpt::Guid;
|
||||
use uefi::{
|
||||
@@ -62,9 +63,6 @@ const PACK_EXTENSION: &str = "pak";
|
||||
const SPARE: &str = "spare.bin";
|
||||
/// The pack is read in steps of this many bytes, each shown as progress.
|
||||
const PROGRESS_STEP: usize = 16 << 20;
|
||||
/// The largest pack the boot holds in memory and writes: the bound of
|
||||
/// `store.cfg` is cut to it.
|
||||
const MAX_PACK_BYTES: u64 = 1 << 30;
|
||||
/// The placement record at the start of the handoff file: magic, bound,
|
||||
/// partition GUID, flags, pack bytes; the pack follows.
|
||||
const PLACEMENT_MAGIC: [u8; 8] = *b"STLTSTOR";
|
||||
@@ -163,7 +161,7 @@ pub fn read() -> Option<(Region, bool)> {
|
||||
let Some(bound) = bound(&mut root) else {
|
||||
continue;
|
||||
};
|
||||
let bound = bound.min(MAX_PACK_BYTES);
|
||||
let bound = bound.min(MAX_TRANSLATION_PACK_BYTES);
|
||||
let path = pack_path(&translator, "\\");
|
||||
if open(&mut root, &path, FileMode::Read).is_none() {
|
||||
claim_spare(&mut root, &translator);
|
||||
@@ -322,11 +320,26 @@ static BOOT: Cell = Cell {
|
||||
boot: UnsafeCell::new(None),
|
||||
};
|
||||
|
||||
/// Availability rarely changes. Keep it off the lock's cache line so a PE
|
||||
/// checking for a store does not contend with a PE using it.
|
||||
/// Keep the store's capabilities off the lock's cache line so a PE can
|
||||
/// skip operations that have no backing without contending with its users.
|
||||
#[repr(align(64))]
|
||||
struct Available(AtomicBool);
|
||||
static AVAILABLE: Available = Available(AtomicBool::new(false));
|
||||
struct Available {
|
||||
capabilities: AtomicU8,
|
||||
/// A preflight limit for staging. Admission checks the live store bound.
|
||||
shared_bound: AtomicUsize,
|
||||
}
|
||||
|
||||
static AVAILABLE: Available = Available {
|
||||
capabilities: AtomicU8::new(0),
|
||||
shared_bound: AtomicUsize::new(0),
|
||||
};
|
||||
const READ_PACK: u8 = 1 << 0;
|
||||
const WRITE_PACK: u8 = 1 << 1;
|
||||
const SHARE_BLOCKS: u8 = 1 << 2;
|
||||
|
||||
fn available(capabilities: u8) -> bool {
|
||||
AVAILABLE.capabilities.load(Ordering::Acquire) & capabilities != 0
|
||||
}
|
||||
|
||||
/// Run `f` on the boot's store, alone. No interrupt handler reaches it.
|
||||
fn with_boot<R>(f: impl FnOnce(&mut Option<Boot>) -> R) -> R {
|
||||
@@ -348,27 +361,49 @@ fn with_boot<R>(f: impl FnOnce(&mut Option<Boot>) -> R) -> R {
|
||||
/// The engine's view of the boot's store, from any PE's machine.
|
||||
pub struct Shared;
|
||||
|
||||
impl Shared {
|
||||
fn publish_shared(offer: Offer) {
|
||||
let bound = AVAILABLE.shared_bound.load(Ordering::Acquire);
|
||||
let Some(mut staged) = StagedOffer::new(offer, bound) else {
|
||||
return;
|
||||
};
|
||||
let retired = with_boot(|boot| boot.as_mut()?.store.accept_shared(&mut staged));
|
||||
drop(retired);
|
||||
}
|
||||
}
|
||||
|
||||
impl Translations for Shared {
|
||||
/// The record, decoded while the other PEs reach the store: the pack's
|
||||
/// bytes outlive the lock.
|
||||
/// The pack bytes outlive the lock, so other PEs can reach the store
|
||||
/// while a record is decoded. A writer also tracks absent keys.
|
||||
fn record(&mut self, key: &Digest) -> Option<alloc::sync::Arc<Record>> {
|
||||
let (bytes, translator) = with_boot(|boot| {
|
||||
if !available(READ_PACK | WRITE_PACK) {
|
||||
return None;
|
||||
}
|
||||
let lookup = with_boot(|boot| {
|
||||
let store = &mut boot.as_mut()?.store;
|
||||
if let Some(record) = store.cached_record(key) {
|
||||
return Some(Ok(record));
|
||||
}
|
||||
match store.stored(key) {
|
||||
Some(bytes) => Some((bytes, *store.translator())),
|
||||
Some(bytes) => Some(Err((bytes, *store.translator()))),
|
||||
None => {
|
||||
store.looked_up(key, false, false);
|
||||
None
|
||||
}
|
||||
}
|
||||
})?;
|
||||
let record = Record::decode(bytes, &translator, key).ok();
|
||||
with_boot(|boot| {
|
||||
if let Some(boot) = boot {
|
||||
boot.store.looked_up(key, true, record.is_some());
|
||||
}
|
||||
let (bytes, translator) = match lookup {
|
||||
Ok(record) => return Some(record),
|
||||
Err(source) => source,
|
||||
};
|
||||
let decoded = DecodedRecord::decode(bytes, &translator, key);
|
||||
let evicted = with_boot(|boot| {
|
||||
let store = &mut boot.as_mut()?.store;
|
||||
store.looked_up(key, true, decoded.is_some());
|
||||
store.remember_record(decoded.as_ref()?)
|
||||
});
|
||||
record.map(alloc::sync::Arc::new)
|
||||
drop(evicted);
|
||||
decoded.map(DecodedRecord::into_record)
|
||||
}
|
||||
|
||||
fn prepared(
|
||||
@@ -377,32 +412,39 @@ impl Translations for Shared {
|
||||
pc: u64,
|
||||
context: &Digest,
|
||||
) -> Option<alloc::sync::Arc<stela_engine::machine::engine::SharedTranslation>> {
|
||||
if !available(SHARE_BLOCKS) {
|
||||
return None;
|
||||
}
|
||||
with_boot(|boot| boot.as_mut()?.store.prepared(key, pc, context))
|
||||
}
|
||||
|
||||
fn offer(&mut self, offer: Offer) {
|
||||
with_boot(|boot| {
|
||||
if let Some(boot) = boot {
|
||||
boot.store.offer(offer);
|
||||
}
|
||||
});
|
||||
let capabilities = AVAILABLE.capabilities.load(Ordering::Acquire);
|
||||
if capabilities & WRITE_PACK != 0 {
|
||||
with_boot(|boot| {
|
||||
if let Some(boot) = boot {
|
||||
if boot.partition.is_some() {
|
||||
boot.store.offer(offer);
|
||||
} else {
|
||||
boot.store.lend(offer);
|
||||
}
|
||||
}
|
||||
});
|
||||
} else if capabilities & SHARE_BLOCKS != 0 {
|
||||
Self::publish_shared(offer);
|
||||
}
|
||||
}
|
||||
|
||||
fn lend(&mut self, offer: Offer) {
|
||||
with_boot(|boot| {
|
||||
if let Some(boot) = boot {
|
||||
boot.store.lend(offer);
|
||||
}
|
||||
});
|
||||
if available(SHARE_BLOCKS) {
|
||||
Self::publish_shared(offer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The store the engine uses, if the loader read one or the PEs share one.
|
||||
pub fn store() -> Option<&'static mut Shared> {
|
||||
AVAILABLE
|
||||
.0
|
||||
.load(Ordering::Acquire)
|
||||
.then(|| Box::leak(Box::new(Shared)))
|
||||
available(READ_PACK | WRITE_PACK | SHARE_BLOCKS).then(|| Box::leak(Box::new(Shared)))
|
||||
}
|
||||
|
||||
/// Share compiled blocks between PEs, keeping up to `bound` bytes of buffers
|
||||
@@ -417,7 +459,16 @@ pub fn share(bound: usize) {
|
||||
partition: None,
|
||||
});
|
||||
boot.store.share(bound);
|
||||
AVAILABLE.0.store(true, Ordering::Release);
|
||||
AVAILABLE.shared_bound.store(bound, Ordering::Release);
|
||||
if bound != 0 {
|
||||
AVAILABLE
|
||||
.capabilities
|
||||
.fetch_or(SHARE_BLOCKS, Ordering::Release);
|
||||
} else {
|
||||
AVAILABLE
|
||||
.capabilities
|
||||
.fetch_and(!SHARE_BLOCKS, Ordering::Release);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -446,13 +497,15 @@ pub fn install(contents: &'static [u8]) -> Option<Guid> {
|
||||
(None, None) => output::arguments(format_args!("TRANSLATIONS no pack yet\n")),
|
||||
}
|
||||
with_boot(|boot| {
|
||||
let readable = if store.pack().is_some() { READ_PACK } else { 0 };
|
||||
*boot = Some(Boot {
|
||||
store,
|
||||
bound,
|
||||
path: pack_path(&translator, "/"),
|
||||
partition: None,
|
||||
});
|
||||
AVAILABLE.0.store(true, Ordering::Release);
|
||||
AVAILABLE.shared_bound.store(0, Ordering::Release);
|
||||
AVAILABLE.capabilities.store(readable, Ordering::Release);
|
||||
});
|
||||
let partition = Guid(contents[16..32].try_into().expect("a GUID"));
|
||||
(flags & WRITABLE != 0).then_some(partition)
|
||||
@@ -463,6 +516,9 @@ pub fn set_partition(partition: Box<dyn BlockDevice>) {
|
||||
with_boot(|boot| {
|
||||
if let Some(boot) = boot {
|
||||
boot.partition = Some(partition);
|
||||
AVAILABLE
|
||||
.capabilities
|
||||
.fetch_or(WRITE_PACK, Ordering::Release);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -476,7 +532,8 @@ pub fn write() {
|
||||
path,
|
||||
partition: Some(partition),
|
||||
}) = with_boot(|boot| {
|
||||
AVAILABLE.0.store(false, Ordering::Release);
|
||||
AVAILABLE.capabilities.store(0, Ordering::Release);
|
||||
AVAILABLE.shared_bound.store(0, Ordering::Release);
|
||||
boot.take()
|
||||
})
|
||||
else {
|
||||
|
||||
@@ -160,8 +160,9 @@ impl HostUsb {
|
||||
}
|
||||
}
|
||||
|
||||
/// Poll each signalling controller that has work, and the others when
|
||||
/// the interval has passed; the keyboards and pointers that arrived.
|
||||
/// Poll controllers with work or a due attachment timer, and check
|
||||
/// non-signalling controllers on the fallback interval. Return the
|
||||
/// keyboards and pointers that arrived.
|
||||
pub fn poll(&mut self) -> Vec<InputDevice> {
|
||||
let mut inputs = Vec::new();
|
||||
let now = super::host::rdtsc();
|
||||
@@ -176,7 +177,11 @@ impl HostUsb {
|
||||
// SAFETY: the loader root `storage::open` captured maps the
|
||||
// controller and DMA pages used by both readiness and polling.
|
||||
let _root = unsafe { RestoreRoot::enter(self.root) };
|
||||
if !(if host.signals() { host.due() } else { timed }) {
|
||||
if !(if host.signals() {
|
||||
host.due()
|
||||
} else {
|
||||
timed || host.attachment_due()
|
||||
}) {
|
||||
continue;
|
||||
}
|
||||
host.poll(&mut self.dma, &firmware)
|
||||
|
||||
@@ -113,7 +113,7 @@ static HOST_FIRMWARE_INTERFACE: [u8; 21] = stela_loader::host_firmware::MOUNT_CA
|
||||
#[uefi::entry]
|
||||
fn main() -> Status {
|
||||
// Before any Rust state exists: the system engine runs from this copy.
|
||||
system::take_snapshot();
|
||||
let snapshot = system::take_snapshot();
|
||||
// Referenced, so the linker keeps the marker setup reads.
|
||||
core::hint::black_box(&MOUNT_INTERFACE);
|
||||
core::hint::black_box(&HOST_FIRMWARE_INTERFACE);
|
||||
@@ -151,8 +151,9 @@ fn main() -> Status {
|
||||
let options = choice::choose(&mut volume, options, held);
|
||||
status::take_screen(console::Framebuffer::from_firmware());
|
||||
if options.starts_with(b"--system") {
|
||||
system::boot(options, volume, log, host_firmware);
|
||||
system::boot(options, volume, log, host_firmware, snapshot);
|
||||
}
|
||||
drop(snapshot);
|
||||
if options.starts_with(stela_boot_core::options::HOST_CHECK.as_bytes()) {
|
||||
drop(volume);
|
||||
#[cfg(feature = "diagnostics")]
|
||||
|
||||
@@ -8,7 +8,7 @@ use crate::{
|
||||
apic::{self, Apic},
|
||||
engine::{host, interrupts},
|
||||
};
|
||||
use alloc::sync::Arc;
|
||||
use alloc::{boxed::Box, sync::Arc};
|
||||
use core::{
|
||||
arch::asm,
|
||||
cell::{Cell, UnsafeCell},
|
||||
@@ -421,6 +421,16 @@ unsafe impl stela_linux::owner::MinimumDeadline for MinimumDeadline {
|
||||
}
|
||||
}
|
||||
|
||||
impl stela_drivers::bus::pci::power::Interval for MinimumDeadline {
|
||||
fn elapsed(&self) -> Result<bool, stela_drivers::bus::pci::power::Error> {
|
||||
use stela_drivers::bus::pci::power::Error;
|
||||
if self.epoch.cpu.in_interrupt() {
|
||||
return Err(Error::Clock);
|
||||
}
|
||||
stela_linux::owner::MinimumDeadline::ready(self).map_err(|_| Error::Clock)
|
||||
}
|
||||
}
|
||||
|
||||
// SAFETY: the epoch retains and checks the actual HPET/CPU/root on every
|
||||
// sample, derives the target from the outward lower bound, and does not wait
|
||||
// in PCI interrupt context.
|
||||
@@ -445,6 +455,22 @@ unsafe impl stela_drivers::bus::pci::power::Timer for CounterEpoch {
|
||||
self.minimum_delay_us(microseconds)
|
||||
.map_err(|_| Error::Clock)
|
||||
}
|
||||
|
||||
fn begin_interval(
|
||||
&self,
|
||||
microseconds: u64,
|
||||
) -> Result<
|
||||
Option<Box<dyn stela_drivers::bus::pci::power::Interval>>,
|
||||
stela_drivers::bus::pci::power::Error,
|
||||
> {
|
||||
use stela_drivers::bus::pci::power::Error;
|
||||
if self.cpu.in_interrupt() {
|
||||
return Err(Error::Clock);
|
||||
}
|
||||
let ns = microseconds.checked_mul(1_000).ok_or(Error::Clock)?;
|
||||
let interval = self.minimum_deadline(ns).map_err(|_| Error::Clock)?;
|
||||
Ok(Some(Box::new(interval)))
|
||||
}
|
||||
}
|
||||
|
||||
struct Counter {
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
//! Source selection. No nominal TSC/frequency or bootstrap Cpu.
|
||||
use super::{WorkError, counter::Counter, pm};
|
||||
use alloc::{rc::Rc, sync::Arc};
|
||||
use alloc::{boxed::Box, rc::Rc, sync::Arc};
|
||||
pub(crate) use stela_boot_core::hpet::ElapsedBounds;
|
||||
pub(super) use stela_boot_core::source_health::Health;
|
||||
use stela_drivers::bus::pci::power::{Error as TimerError, Timer};
|
||||
use stela_drivers::bus::pci::power::{Error as TimerError, Interval, Timer};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) enum Prepared {
|
||||
@@ -13,6 +13,26 @@ pub(crate) enum Prepared {
|
||||
/// Process-only physical minimum from a retained native HPET handoff.
|
||||
struct HpetMinimum(Arc<Counter>);
|
||||
|
||||
struct HpetInterval {
|
||||
counter: Arc<Counter>,
|
||||
start: u64,
|
||||
ticks: u64,
|
||||
}
|
||||
|
||||
impl Interval for HpetInterval {
|
||||
fn elapsed(&self) -> Result<bool, TimerError> {
|
||||
self.counter
|
||||
.check_process()
|
||||
.map_err(|_| TimerError::Clock)?;
|
||||
let now = self.counter.read_irq().map_err(|_| TimerError::Clock)?;
|
||||
let elapsed = now.wrapping_sub(self.start);
|
||||
if elapsed > u64::MAX / 2 {
|
||||
return Err(TimerError::Clock);
|
||||
}
|
||||
Ok(elapsed >= self.ticks)
|
||||
}
|
||||
}
|
||||
|
||||
impl HpetMinimum {
|
||||
fn target(&self, microseconds: u64) -> Result<u64, WorkError> {
|
||||
self.0.check_process()?;
|
||||
@@ -62,6 +82,16 @@ unsafe impl Timer for HpetMinimum {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn begin_interval(&self, microseconds: u64) -> Result<Option<Box<dyn Interval>>, TimerError> {
|
||||
let ticks = self.target(microseconds).map_err(|_| TimerError::Clock)?;
|
||||
let start = self.0.read_irq().map_err(|_| TimerError::Clock)?;
|
||||
Ok(Some(Box::new(HpetInterval {
|
||||
counter: self.0.clone(),
|
||||
start,
|
||||
ticks,
|
||||
})))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
|
||||
@@ -171,10 +171,14 @@ unsafe fn check_native_hpet(
|
||||
let counter = prepared.hpet_counter().ok_or(Error::Unavailable)?.clone();
|
||||
{
|
||||
let minimum = prepared.pci_minimum()?;
|
||||
let interval = minimum
|
||||
.begin_interval(20)
|
||||
.map_err(|_| Error::Unavailable)?
|
||||
.ok_or(Error::Unavailable)?;
|
||||
let start = counter.read_irq()?;
|
||||
minimum.wait_us(20).map_err(|_| Error::Unavailable)?;
|
||||
let elapsed = counter.elapsed_bounds(counter.read_irq()?.wrapping_sub(start))?;
|
||||
if elapsed.lower_ns < 20_000 {
|
||||
if elapsed.lower_ns < 20_000 || !interval.elapsed().map_err(|_| Error::Unavailable)? {
|
||||
return Err(Error::InvalidPlatformReply.into());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -77,6 +77,9 @@ fn flush() {
|
||||
/// has not flushed it yet. Cheap when nothing is requested: two loads.
|
||||
pub(crate) fn service() {
|
||||
let requested = PROCESSORS.requested();
|
||||
if requested == 0 {
|
||||
return;
|
||||
}
|
||||
let (slot, flushed) = crate::engine::host::shootdown();
|
||||
if flushed.load(Ordering::Relaxed) >= requested {
|
||||
return;
|
||||
@@ -85,7 +88,9 @@ pub(crate) fn service() {
|
||||
return;
|
||||
};
|
||||
flush();
|
||||
flushed.store(requested, Ordering::Relaxed);
|
||||
// A waiter may have IF set. An interrupt between the flush and this
|
||||
// publication must not let its newer local acknowledgement regress.
|
||||
flushed.fetch_max(requested, Ordering::Relaxed);
|
||||
PROCESSORS.acknowledge(slot, requested);
|
||||
}
|
||||
|
||||
|
||||
@@ -207,9 +207,7 @@ impl Window {
|
||||
if !guard.state().retiring.begin(range.clone()) {
|
||||
return false;
|
||||
}
|
||||
for page in 0..count as u64 {
|
||||
let at = address + page * PAGE;
|
||||
let [pointer, directory, _] = page_window::indices(at);
|
||||
for (pointer, directory, slots) in page_window::leaf_runs(address, count) {
|
||||
// SAFETY: the aperture's table, a bounded index.
|
||||
let upper = unsafe { self.pointers.add(pointer).read_volatile() };
|
||||
if upper & PRESENT == 0 {
|
||||
@@ -220,9 +218,11 @@ impl Window {
|
||||
if middle & PRESENT == 0 {
|
||||
continue;
|
||||
}
|
||||
if let Some(leaf) = self.leaf(guard.state(), at) {
|
||||
// SAFETY: a leaf this window owns, under its lock.
|
||||
unsafe { leaf.write_volatile(0) };
|
||||
let table = entry_table(middle);
|
||||
for slot in slots {
|
||||
// SAFETY: each slot belongs to this existing leaf table and
|
||||
// the held guard excludes other edits.
|
||||
unsafe { table.add(slot).write_volatile(0) };
|
||||
}
|
||||
}
|
||||
drop(guard);
|
||||
|
||||
@@ -268,6 +268,63 @@ impl Processor {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "diagnostics")]
|
||||
impl Processor {
|
||||
/// Run `check` with this AP spinning for the driver's real loader-root
|
||||
/// lock. The mailbox command cannot acknowledge a new shootdown at a
|
||||
/// native return or take an IPI while the BSP keeps the lock.
|
||||
///
|
||||
/// # Safety
|
||||
/// `root` is the live loader root shared by the BSP and this installed AP.
|
||||
pub(crate) unsafe fn check_driver_wait<T>(
|
||||
&self,
|
||||
root: u64,
|
||||
sender: &Apic,
|
||||
tsc_hz: u64,
|
||||
check: impl FnOnce() -> T,
|
||||
) -> Result<T> {
|
||||
let ready = alloc::sync::Arc::new(AtomicU8::new(0));
|
||||
let observed = ready.clone();
|
||||
let work = Spawned(Box::new(move |_| {
|
||||
let flags: u64;
|
||||
// SAFETY: observes the AP mailbox's real interrupt mask.
|
||||
unsafe { asm!("pushfq", "pop {}", out(reg) flags) };
|
||||
if flags & (1 << 9) != 0 {
|
||||
observed.store(2, Ordering::Release);
|
||||
return;
|
||||
}
|
||||
observed.store(1, Ordering::Release);
|
||||
// SAFETY: the live loader root and this AP's pinned local owner.
|
||||
unsafe { crate::engine::storage::with_driver_root(root, || ()) };
|
||||
}));
|
||||
// SAFETY: the same live root belongs to this BSP. Keep the lock
|
||||
// through the check and release it before collecting the AP.
|
||||
let (pending, value) = unsafe {
|
||||
crate::engine::storage::with_driver_root(root, || -> Result<_> {
|
||||
let pending = self
|
||||
.send(work, sender, tsc_hz)
|
||||
.map_err(|_| refuse!("AP driver wait mailbox busy"))?;
|
||||
let started = apic::rdtsc();
|
||||
let value = loop {
|
||||
match ready.load(Ordering::Acquire) {
|
||||
1 => break Ok(check()),
|
||||
2 => {
|
||||
break Err(refuse!("AP driver waiter entered with interrupts enabled"));
|
||||
}
|
||||
_ if apic::rdtsc().wrapping_sub(started) >= tsc_hz => {
|
||||
break Err(refuse!("AP did not enter the driver wait"));
|
||||
}
|
||||
_ => core::hint::spin_loop(),
|
||||
}
|
||||
};
|
||||
Ok((pending, value))
|
||||
})
|
||||
}?;
|
||||
pending.finish();
|
||||
value
|
||||
}
|
||||
}
|
||||
|
||||
struct Spawned(Box<dyn FnOnce(&mut host::HostOwner) + Send>);
|
||||
impl Command for Spawned {
|
||||
type Output = ();
|
||||
|
||||
@@ -9,7 +9,6 @@ use stela_compiler::{GuestState, TargetCpu};
|
||||
use stela_contracts::Chip;
|
||||
use stela_contracts::identity::Identity;
|
||||
use stela_contracts::refuse;
|
||||
use stela_drivers::bus::dma::memory::{CacheAttribute, CpuMapping, PageSource, PinnedPages};
|
||||
use stela_engine::machine::Cpu;
|
||||
use stela_engine::machine::CpuProfile;
|
||||
use stela_engine::machine::DeviceError;
|
||||
@@ -22,15 +21,10 @@ use stela_engine::machine::Stop;
|
||||
use stela_engine::machine::engine;
|
||||
use stela_engine::machine::engine::publication::WorkerBinding;
|
||||
use stela_engine::machine::engine::publication::WorkerId;
|
||||
use stela_engine::machine::exception::Pstate;
|
||||
use stela_engine::machine::exception::{DAIF_I, Pstate};
|
||||
use stela_engine::memory::RegisteredSystemRam;
|
||||
use stela_engine::memory::ReservedSystemRamRange;
|
||||
use stela_soc::machine;
|
||||
|
||||
struct Reservation {
|
||||
pages: PinnedPages,
|
||||
mapping: CpuMapping,
|
||||
}
|
||||
struct TestDevices {
|
||||
starts: Vec<engine::Start>,
|
||||
ready: Vec<bool>,
|
||||
@@ -156,43 +150,62 @@ impl TestDevices {
|
||||
Ok(engine::ConsumedWrite::Complete { settlement: Ok(()) })
|
||||
}
|
||||
}
|
||||
fn reservation() -> Result<Arc<RegisteredSystemRam>> {
|
||||
let pages = crate::native_memory::SOURCE
|
||||
.allocate(source::BYTES, 4096, CacheAttribute::WriteBack)
|
||||
.map_err(|_| refuse!("native kernel actual WB page allocation refused"))?;
|
||||
let mapping = pages
|
||||
.cpu_mapping(CacheAttribute::WriteBack)
|
||||
.map_err(|_| refuse!("native kernel CPU mapping refused"))?;
|
||||
let owner = Arc::new(Reservation { pages, mapping });
|
||||
let physical = owner.pages.physical_pages();
|
||||
if physical.windows(2).any(|pages| pages[1] != pages[0] + 4096) {
|
||||
return Err(refuse!(
|
||||
"native kernel actual page allocation is not contiguous"
|
||||
));
|
||||
}
|
||||
let range = ReservedSystemRamRange {
|
||||
source_pa: source::BASE,
|
||||
host_pa: physical[0],
|
||||
host_base: owner
|
||||
.mapping
|
||||
.address(0, source::BYTES)
|
||||
.map_err(|_| refuse!("native kernel mapping extent refused"))?,
|
||||
bytes: source::BYTES,
|
||||
/// # Safety
|
||||
/// `loader_ram` is the complete loader backing, reserved exclusively for
|
||||
/// the guest. No guest, direct publisher or DMA accesses it during the check.
|
||||
unsafe fn reservation(
|
||||
handoff: &'static Handoff,
|
||||
loader_ram: &[host::RamRange],
|
||||
) -> Result<Arc<RegisteredSystemRam>> {
|
||||
const UNUSED_GUEST_BASE: u64 = 0x8_0000_0000;
|
||||
const { assert!(source::BASE + source::BYTES as u64 <= source::READY) };
|
||||
let bytes = source::BYTES as u64;
|
||||
let mut ranges = loader_ram.to_vec();
|
||||
let index = ranges
|
||||
.iter()
|
||||
.position(|range| range.bytes >= bytes)
|
||||
.ok_or(refuse!(
|
||||
"native kernel has no contiguous loader RAM for its fixture"
|
||||
))?;
|
||||
let mut backing = ranges.remove(index);
|
||||
let fixture = host::RamRange {
|
||||
guest: source::BASE,
|
||||
host: backing.host,
|
||||
bytes,
|
||||
};
|
||||
// SAFETY: exclusive heap page pin and checked WB CPU mapping. No
|
||||
// DMA/direct writer is admitted. Arc keeps both through all native frames,
|
||||
// callbacks, fault recovery and source-PC/publication settlement.
|
||||
let ram = Arc::new(
|
||||
unsafe {
|
||||
RegisteredSystemRam::register(
|
||||
&[range],
|
||||
owner,
|
||||
stela_engine::machine::cpu::RESERVATION_GRANULE,
|
||||
64,
|
||||
)
|
||||
}
|
||||
.map_err(|_| refuse!("native kernel canonical RAM registration refused"))?,
|
||||
);
|
||||
if backing.bytes > bytes {
|
||||
backing.host = backing
|
||||
.host
|
||||
.checked_add(bytes)
|
||||
.ok_or(refuse!("native kernel loader RAM extent wraps"))?;
|
||||
backing.bytes -= bytes;
|
||||
ranges.insert(index, backing);
|
||||
}
|
||||
// Keep the retained physical union while leaving the fixture's MMIO
|
||||
// addresses unbacked. The authored guest only touches its low extent.
|
||||
let mut guest = UNUSED_GUEST_BASE;
|
||||
for range in &mut ranges {
|
||||
range.guest = guest;
|
||||
guest = guest
|
||||
.checked_add(range.bytes)
|
||||
.ok_or(refuse!("native kernel guest RAM extent wraps"))?;
|
||||
}
|
||||
ranges.insert(0, fixture);
|
||||
// SAFETY: only the guest addresses changed. The loader's complete
|
||||
// physical reservation and the closed writer contract remain held.
|
||||
let ram = unsafe { super::canonical::reserve(handoff, &ranges) }?;
|
||||
let zeros = [0; 4096];
|
||||
for offset in (0..source::BYTES).step_by(zeros.len()) {
|
||||
let length = (source::BYTES - offset).min(zeros.len());
|
||||
// SAFETY: the validated loader RAM has no other writer, and this
|
||||
// source slice is disjoint from it. Clear only the fixture.
|
||||
unsafe { ram.publish_physical(source::BASE + offset as u64, &zeros[..length]) }
|
||||
.map_err(|_| refuse!("native kernel fixture zeroing failed"))?;
|
||||
}
|
||||
Ok(ram)
|
||||
}
|
||||
|
||||
fn publish_scheduler(ram: &RegisteredSystemRam) -> Result<()> {
|
||||
for (address, descriptor) in source::tables() {
|
||||
// SAFETY: the source bytes are private locals, disjoint from the registered RAM, and `ram`
|
||||
// keeps its registration live.
|
||||
@@ -204,7 +217,7 @@ fn reservation() -> Result<Arc<RegisteredSystemRam>> {
|
||||
// keeps its registration live.
|
||||
unsafe { ram.publish_physical(source::CODE, &program) }
|
||||
.map_err(|_| refuse!("native kernel source publication failed"))?;
|
||||
Ok(ram)
|
||||
Ok(())
|
||||
}
|
||||
fn profile(cores: usize) -> Result<CpuProfile> {
|
||||
let chip = Chip::AppleM1;
|
||||
@@ -264,13 +277,17 @@ pub(crate) unsafe fn check(
|
||||
executors: &Executors,
|
||||
host_owner: &mut host::HostOwner,
|
||||
sender: &Apic,
|
||||
loader_ram: &[host::RamRange],
|
||||
) -> Result<()> {
|
||||
let cores = handoff.native_resources.cores as usize;
|
||||
// SAFETY: this diagnostic owns the complete loader backing and will stop
|
||||
// before the normal guest or any asynchronous producer can use it.
|
||||
let ram = unsafe { reservation(handoff, loader_ram) }?;
|
||||
if cores == 1 {
|
||||
// SAFETY: same bootstrap/physical-owner fixture contract.
|
||||
return unsafe { cold::check(handoff, capture, executors, host_owner, sender) };
|
||||
return unsafe { cold::check(handoff, capture, executors, host_owner, sender, ram) };
|
||||
}
|
||||
let ram = reservation()?;
|
||||
publish_scheduler(&ram)?;
|
||||
// Preserve a nonzero guest boot PE while the physical BSP
|
||||
// remains worker0. Other identities and their source affinity stay ordered.
|
||||
let boot_processor = cores - 1;
|
||||
@@ -432,6 +449,9 @@ pub(crate) unsafe fn check(
|
||||
let after = states(&machine)?;
|
||||
for (old, actual) in before.iter().zip(&after) {
|
||||
let mut expected = old.clone();
|
||||
// Both READY writes leave the fixture's IRQ asserted. The timer FIQ
|
||||
// was disabled by its handler, so only IRQ remains in the frame.
|
||||
expected.pending = u32::from(DAIF_I);
|
||||
for register in [0, 1, 2, 3, 4, 5, 6, 7, 10, 19, 20, 22, 23, 24] {
|
||||
expected.x[register] = actual.x[register];
|
||||
}
|
||||
|
||||
@@ -148,28 +148,8 @@ pub(super) unsafe fn check(
|
||||
executors: &Executors,
|
||||
owner: &mut host::HostOwner,
|
||||
sender: &Apic,
|
||||
ram: Arc<RegisteredSystemRam>,
|
||||
) -> Result<()> {
|
||||
let reservation = handoff.guest[..handoff.guest_count]
|
||||
.iter()
|
||||
.find(|region| region.bytes >= source::BYTES as u64)
|
||||
.ok_or(refuse!("cold fixture has no actual loader RAM reservation"))?;
|
||||
let range = host::RamRange {
|
||||
guest: source::BASE,
|
||||
host: reservation.physical,
|
||||
bytes: source::BYTES as u64,
|
||||
};
|
||||
// SAFETY: bounded loader-owned scratch reservation, before registration or
|
||||
// any guest frame/publisher; this check does not enter original macOS.
|
||||
unsafe {
|
||||
core::ptr::write_bytes(
|
||||
crate::layout::physical(range.host) as *mut u8,
|
||||
0,
|
||||
source::BYTES,
|
||||
)
|
||||
};
|
||||
// SAFETY: the loader reserved this scratch range for the boot and zeroed it above; nothing else
|
||||
// reaches it.
|
||||
let ram = unsafe { super::super::canonical::reserve(handoff, &[range]) }?;
|
||||
// SAFETY: before any frame, guest entry or other publisher; this exact
|
||||
// registered allocation is held by the following Machine.
|
||||
unsafe { tree::check(&ram) }?;
|
||||
|
||||
@@ -4,8 +4,9 @@
|
||||
//! this image (taken before any Rust state exists), chooses the host
|
||||
//! placement, places a relocated copy in the Stela window, allocates the
|
||||
//! engine's memory, builds its page tables (five-level under LA57, else
|
||||
//! four-level), leaves boot services, loads them, through the LA57
|
||||
//! trampoline when five-level, and calls the engine phase in the window. See
|
||||
//! four-level), releases the pristine copy, and leaves boot services. It
|
||||
//! loads the tables through the LA57 trampoline when five-level and calls
|
||||
//! the engine phase in the window. See
|
||||
//! `docs/design/system.md#host-placement`.
|
||||
use crate::Result;
|
||||
use crate::{
|
||||
@@ -20,8 +21,8 @@ use crate::{
|
||||
use alloc::{format, string::String, vec::Vec};
|
||||
use core::{
|
||||
arch::asm,
|
||||
cell::UnsafeCell,
|
||||
ops::{Range, RangeInclusive},
|
||||
ptr::NonNull,
|
||||
};
|
||||
use stela_boot_core::options::{DEFAULT_WIFI_KEY, System};
|
||||
use stela_contracts::refuse;
|
||||
@@ -62,36 +63,39 @@ const RELOCATION_DIRECTORY: usize = 5;
|
||||
const IMAGE_REL_BASED_ABSOLUTE: u16 = 0;
|
||||
const IMAGE_REL_BASED_DIR64: u16 = 10;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Snapshot {
|
||||
copy: usize,
|
||||
/// Private firmware pages owned only while boot services are active.
|
||||
pub(crate) struct Snapshot {
|
||||
copy: NonNull<u8>,
|
||||
start: usize,
|
||||
bytes: usize,
|
||||
}
|
||||
|
||||
struct Pristine(UnsafeCell<Option<Snapshot>>);
|
||||
// SAFETY: written once by the boot processor before anything else runs.
|
||||
unsafe impl Sync for Pristine {}
|
||||
static PRISTINE: Pristine = Pristine(UnsafeCell::new(None));
|
||||
impl Drop for Snapshot {
|
||||
fn drop(&mut self) {
|
||||
let physical = self.copy.as_ptr() as usize;
|
||||
// SAFETY: this owner holds exactly the pages allocated in take_snapshot.
|
||||
// The entry and system loader both drop it before exiting boot services.
|
||||
let result = unsafe { boot::free_pages(self.copy, self.bytes / PAGE as usize) };
|
||||
output::arguments(format_args!(
|
||||
"BOOT IMAGE snapshot physical={physical:#x} bytes={:#x} release={result:?}\n",
|
||||
self.bytes,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/// Copy this image as the firmware loaded it, before Rust state changes it.
|
||||
/// Only the firmware entry glue has run; its statics are not used later.
|
||||
pub fn take_snapshot() {
|
||||
let Ok(image) = boot::open_protocol_exclusive::<LoadedImage>(boot::image_handle()) else {
|
||||
return;
|
||||
};
|
||||
pub(crate) fn take_snapshot() -> Option<Snapshot> {
|
||||
let image = boot::open_protocol_exclusive::<LoadedImage>(boot::image_handle()).ok()?;
|
||||
let (base, bytes) = image.info();
|
||||
let Ok(extent) = firmware::loaded_extent(base as usize, bytes) else {
|
||||
return;
|
||||
};
|
||||
let extent = firmware::loaded_extent(base as usize, bytes).ok()?;
|
||||
let bytes = extent.mapped_bytes;
|
||||
let Ok(copy) = boot::allocate_pages(
|
||||
let copy = boot::allocate_pages(
|
||||
AllocateType::AnyPages,
|
||||
MemoryType::LOADER_DATA,
|
||||
bytes / PAGE as usize,
|
||||
) else {
|
||||
return;
|
||||
};
|
||||
)
|
||||
.ok()?;
|
||||
// SAFETY: exact checked firmware source extent and distinct fresh owned
|
||||
// pages. Zero only the destination tail, without reading source padding.
|
||||
unsafe {
|
||||
@@ -99,12 +103,12 @@ pub fn take_snapshot() {
|
||||
copy.as_ptr()
|
||||
.add(extent.bytes)
|
||||
.write_bytes(0, bytes - extent.bytes);
|
||||
*PRISTINE.0.get() = Some(Snapshot {
|
||||
copy: copy.as_ptr() as usize,
|
||||
start: base as usize,
|
||||
bytes,
|
||||
});
|
||||
}
|
||||
Some(Snapshot {
|
||||
copy,
|
||||
start: base as usize,
|
||||
bytes,
|
||||
})
|
||||
}
|
||||
|
||||
fn low_page(kind: MemoryType) -> Result<u64> {
|
||||
@@ -602,11 +606,12 @@ pub fn held_at_start(options: &[u8]) -> Option<&'static str> {
|
||||
/// Run the engine; never returns.
|
||||
/// `log` is the partition holding the USB's boot log, when the loader keeps
|
||||
/// one there (`log_file`).
|
||||
pub fn boot(
|
||||
pub(crate) fn boot(
|
||||
mut options: Vec<u8>,
|
||||
mut volume: FileSystem,
|
||||
log: Option<Guid>,
|
||||
host_firmware: crate::host_firmware::Resources,
|
||||
snapshot: Option<Snapshot>,
|
||||
) -> ! {
|
||||
// NVRAM chooses macOS or recoveryOS before any input is read. A machine
|
||||
// NVRAM holds in recovery mode waits at the startup choices, as LLB
|
||||
@@ -635,15 +640,13 @@ pub fn boot(
|
||||
// `inputs` closes the volume: protocols must be closed before boot
|
||||
// services end.
|
||||
let inputs = inputs(&options, volume);
|
||||
let result = inputs.and_then(|(source, files, storage, wifi_key)| {
|
||||
let result = inputs.and_then(|inputs| {
|
||||
load(
|
||||
options,
|
||||
source,
|
||||
files,
|
||||
storage,
|
||||
wifi_key,
|
||||
inputs,
|
||||
log,
|
||||
host_firmware,
|
||||
snapshot.ok_or(refuse!("no pristine image copy"))?,
|
||||
)
|
||||
});
|
||||
match result {
|
||||
@@ -654,15 +657,14 @@ pub fn boot(
|
||||
|
||||
fn load(
|
||||
options: Vec<u8>,
|
||||
source: Vec<u8>,
|
||||
bundle: BundleFiles,
|
||||
storage: Option<stela_drivers::Handoff>,
|
||||
wifi_key: Vec<u8>,
|
||||
inputs: Inputs,
|
||||
log: Option<Guid>,
|
||||
host_firmware: crate::host_firmware::Resources,
|
||||
snapshot: Snapshot,
|
||||
) -> Result<core::convert::Infallible> {
|
||||
let (source, bundle, storage, wifi_key) = inputs;
|
||||
crate::status::begin("Setting up Stela's memory");
|
||||
let image = memory::prepare_image()?;
|
||||
let image = memory::prepare_image(&snapshot)?;
|
||||
let text = core::str::from_utf8(&options).map_err(|_| refuse!("stela.cfg is not UTF-8"))?;
|
||||
let system = System::parse(text).map_err(stela_boot_core::options::Error::message)?;
|
||||
let (native_processors, cores) =
|
||||
@@ -750,6 +752,9 @@ fn load(
|
||||
boot_heap.live >> 20,
|
||||
));
|
||||
release_loader_heap();
|
||||
// Reservations have already been sized and the relocated image owns its
|
||||
// bytes. The final firmware map can now offer the pristine pages to macOS.
|
||||
drop(snapshot);
|
||||
// SAFETY: the fresh immutable MP observation is held LOADER_DATA. Identity
|
||||
// mappings and the calibrated local APIC remain valid across EBS.
|
||||
let capture = unsafe {
|
||||
|
||||
@@ -15,7 +15,6 @@ fn allocate_large(bytes: u64) -> Result<Region> {
|
||||
|
||||
/// The relocated engine image and the host ranges its mappings must reach.
|
||||
pub(super) struct EngineImage {
|
||||
pub snapshot: Snapshot,
|
||||
pub image: firmware::Image,
|
||||
pub engine: Region,
|
||||
pub resident: crate::native_image::ResidentImage,
|
||||
@@ -41,9 +40,7 @@ pub(super) struct EngineMemory {
|
||||
}
|
||||
|
||||
/// Copy and relocate the pristine image into the selected host window.
|
||||
pub(super) fn prepare_image() -> Result<EngineImage> {
|
||||
// SAFETY: written once at entry, read here.
|
||||
let snapshot = unsafe { *PRISTINE.0.get() }.ok_or(refuse!("no pristine image copy"))?;
|
||||
pub(super) fn prepare_image(snapshot: &Snapshot) -> Result<EngineImage> {
|
||||
let image = firmware::Image::loaded()?;
|
||||
if image.start != snapshot.start || image.end - image.start != snapshot.bytes {
|
||||
return Err(refuse!("image layout changed after the snapshot"));
|
||||
@@ -71,7 +68,7 @@ pub(super) fn prepare_image() -> Result<EngineImage> {
|
||||
// are distinct and each covers exactly snapshot.bytes.
|
||||
unsafe {
|
||||
core::ptr::copy_nonoverlapping(
|
||||
snapshot.copy as *const u8,
|
||||
snapshot.copy.as_ptr(),
|
||||
engine.physical as *mut u8,
|
||||
snapshot.bytes,
|
||||
);
|
||||
@@ -82,7 +79,6 @@ pub(super) fn prepare_image() -> Result<EngineImage> {
|
||||
layout::image().wrapping_sub(image.start as u64),
|
||||
)?;
|
||||
Ok(EngineImage {
|
||||
snapshot,
|
||||
image,
|
||||
engine,
|
||||
resident,
|
||||
@@ -195,7 +191,6 @@ pub(super) fn map(
|
||||
host_firmware: &crate::host_firmware::Resources,
|
||||
) -> Result<Storage> {
|
||||
let EngineImage {
|
||||
snapshot,
|
||||
image,
|
||||
engine,
|
||||
ram,
|
||||
@@ -254,7 +249,7 @@ pub(super) fn map(
|
||||
)?;
|
||||
}
|
||||
// The window: the engine image with section rights, heap, stack, code.
|
||||
let bytes = snapshot.bytes as u64;
|
||||
let bytes = engine.bytes;
|
||||
let mut page = 0;
|
||||
while page < bytes {
|
||||
let rights = image.rights(image.start + page as usize);
|
||||
|
||||
@@ -140,14 +140,11 @@ pub fn map_range(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Unmap `first..=last`, a canonical address range in one half: clear the
|
||||
/// pages it holds, descending into every table it reaches. The tables stay
|
||||
/// linked, empty where the range covers them, so a later map of the range
|
||||
/// takes no new frame: clearing their entries instead would leave their
|
||||
/// frames taken and unreachable until the whole pool resets. The TLB is the
|
||||
/// caller's.
|
||||
pub fn unmap(frames: &dyn Frames, root: u64, first: u64, last: u64) {
|
||||
clear(frames, root, layout::top_level(), first, last);
|
||||
/// Unmap `first..=last`, a canonical address range in one half, reporting
|
||||
/// an address in each present leaf removed. Intermediate tables stay linked
|
||||
/// for reuse. The caller invalidates any cached translations of those leaves.
|
||||
pub fn unmap(frames: &dyn Frames, root: u64, first: u64, last: u64, mut removed: impl FnMut(u64)) {
|
||||
clear(frames, root, layout::top_level(), first, last, &mut removed);
|
||||
}
|
||||
|
||||
/// [`unmap`] the part of `first..=last` that the root entry `entry` maps,
|
||||
@@ -160,33 +157,44 @@ pub fn unmap_under(frames: &dyn Frames, entry: u64, first: u64, last: u64) {
|
||||
layout::top_level() - 1,
|
||||
first,
|
||||
last,
|
||||
&mut |_| {},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn clear(frames: &dyn Frames, table: u64, level: u32, first: u64, last: u64) {
|
||||
fn clear(
|
||||
frames: &dyn Frames,
|
||||
table: u64,
|
||||
level: u32,
|
||||
first: u64,
|
||||
last: u64,
|
||||
removed: &mut impl FnMut(u64),
|
||||
) {
|
||||
let shift = 12 + 9 * level;
|
||||
// The table maps the aligned region holding the range.
|
||||
let region = first & !((1u64 << (shift + 9)) - 1);
|
||||
let entries = frames.table(table);
|
||||
for slot in index(first, level)..=index(last, level) {
|
||||
let start = region | (slot as u64) << shift;
|
||||
let end = start | ((1u64 << shift) - 1);
|
||||
let entry = frames.table(table).wrapping_add(slot);
|
||||
let entry = entries.wrapping_add(slot);
|
||||
// SAFETY: `table` is a live table page of these frames.
|
||||
let value = unsafe { entry.read_volatile() };
|
||||
if value & PRESENT == 0 {
|
||||
continue;
|
||||
}
|
||||
let start = region | (slot as u64) << shift;
|
||||
if level == 0 || value & HUGE != 0 {
|
||||
// SAFETY: as above.
|
||||
unsafe { entry.write_volatile(0) };
|
||||
removed(start.max(first));
|
||||
} else {
|
||||
let end = start | ((1u64 << shift) - 1);
|
||||
clear(
|
||||
frames,
|
||||
value & ADDRESS,
|
||||
level - 1,
|
||||
first.max(start),
|
||||
last.min(end),
|
||||
removed,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -68,8 +68,6 @@ windows-sys = { version = "0.61", features = [
|
||||
|
||||
[dev-dependencies]
|
||||
miniz_oxide = { version = "0.9", default-features = false, features = ["with-alloc"] }
|
||||
# `block::RamDisk`, the disk setup's erase layout is written to in tests.
|
||||
stela-drivers = { workspace = true, features = ["ram-disk"] }
|
||||
|
||||
|
||||
[lints]
|
||||
|
||||
@@ -9,7 +9,8 @@ use std::{fs::OpenOptions, io::Write, path::PathBuf};
|
||||
use stela_formats::payload::Purpose;
|
||||
use stela_loader::aux_kc::{Linked, TRUSTED_CODE_FILE};
|
||||
use stela_loader::boot_bundle::{
|
||||
self, Input, Inputs, Options, OverlayProperty, RootHash, Source, Target,
|
||||
self, Input, Inputs, Options, OverlayProperty, OwnedRamdisk, RAMDISK_FILE, RootHash, Source,
|
||||
Target,
|
||||
};
|
||||
use stela_loader::boot_policy::{
|
||||
KextGrant, OsEnvironment, SealedVolume, SecurityMode, SecurityPolicy,
|
||||
@@ -776,29 +777,43 @@ impl Prepare {
|
||||
} else {
|
||||
format!("{name} ({})", owner.variant)
|
||||
};
|
||||
let (bytes, receipt) = match payload_type {
|
||||
Some(expected) => {
|
||||
let (bytes, receipt) = stela_loader::im4p::decode(&container, limit)?;
|
||||
if receipt.payload_type != expected {
|
||||
bail!(
|
||||
"{name} is IM4P type {}, expected {expected}",
|
||||
receipt.payload_type
|
||||
);
|
||||
let (bytes, container_sha256, payload_type, description, decoded_sha256) =
|
||||
match payload_type {
|
||||
Some(expected) => {
|
||||
let (bytes, receipt) = stela_loader::im4p::decode_owned(container, limit)?;
|
||||
if receipt.payload_type != expected {
|
||||
bail!(
|
||||
"{name} is IM4P type {}, expected {expected}",
|
||||
receipt.payload_type
|
||||
);
|
||||
}
|
||||
(
|
||||
bytes,
|
||||
receipt.container_sha256,
|
||||
receipt.payload_type,
|
||||
receipt.description,
|
||||
receipt.decoded_sha256,
|
||||
)
|
||||
}
|
||||
(bytes, Some(receipt))
|
||||
}
|
||||
None => (container.clone(), None),
|
||||
};
|
||||
None => {
|
||||
let digest = stela_formats::sha256(&container);
|
||||
(
|
||||
container,
|
||||
digest.clone(),
|
||||
"opaque".into(),
|
||||
String::new(),
|
||||
digest,
|
||||
)
|
||||
}
|
||||
};
|
||||
let source = Source {
|
||||
component: label,
|
||||
member: entry.path.clone(),
|
||||
container_sha256: stela_formats::sha256(&container),
|
||||
payload_type: receipt
|
||||
.as_ref()
|
||||
.map_or_else(|| "opaque".into(), |r| r.payload_type.clone()),
|
||||
description: receipt.map(|r| r.description).unwrap_or_default(),
|
||||
container_sha256,
|
||||
payload_type,
|
||||
description,
|
||||
decoded_bytes: bytes.len() as u64,
|
||||
decoded_sha256: stela_formats::sha256(&bytes),
|
||||
decoded_sha256,
|
||||
};
|
||||
Ok(Decoded {
|
||||
bytes,
|
||||
@@ -840,6 +855,7 @@ impl Prepare {
|
||||
return Ok(None);
|
||||
}
|
||||
let bytes = restore::archive::read_member(&ipsw, &member, COMPONENT_LIMIT)?;
|
||||
let digest = stela_formats::sha256(&bytes);
|
||||
let source = Source {
|
||||
component: if cryptex1 {
|
||||
"Cryptex1 manifest"
|
||||
@@ -848,11 +864,11 @@ impl Prepare {
|
||||
}
|
||||
.into(),
|
||||
member,
|
||||
container_sha256: stela_formats::sha256(&bytes),
|
||||
container_sha256: digest.clone(),
|
||||
payload_type: "im4m".into(),
|
||||
description: String::new(),
|
||||
decoded_bytes: bytes.len() as u64,
|
||||
decoded_sha256: stela_formats::sha256(&bytes),
|
||||
decoded_sha256: digest,
|
||||
};
|
||||
Ok(Some(Decoded {
|
||||
bytes,
|
||||
@@ -897,13 +913,13 @@ impl Prepare {
|
||||
cryptex_trust_caches.push(component(name, None, COMPONENT_LIMIT).and_then(
|
||||
|raw| {
|
||||
let (bytes, receipt) =
|
||||
stela_loader::im4p::decode(&raw.bytes, COMPONENT_LIMIT)?;
|
||||
stela_loader::im4p::decode_owned(raw.bytes, COMPONENT_LIMIT)?;
|
||||
Ok(Decoded {
|
||||
source: Source {
|
||||
payload_type: receipt.payload_type,
|
||||
description: receipt.description,
|
||||
decoded_bytes: bytes.len() as u64,
|
||||
decoded_sha256: stela_formats::sha256(&bytes),
|
||||
decoded_sha256: receipt.decoded_sha256,
|
||||
..raw.source
|
||||
},
|
||||
bytes,
|
||||
@@ -967,10 +983,7 @@ impl Prepare {
|
||||
let extensions = kexts(&bundles);
|
||||
let (auxiliary, kexts) = Self::auxiliary_collection(&kernel.bytes, &extensions)?.unzip();
|
||||
let kext_code = Self::kext_code(&extensions)?;
|
||||
// Set below when the images come from the restore ramdisk.
|
||||
let sourced: Vec<(String, Decoded)>;
|
||||
let ramdisk_component: Decoded;
|
||||
let mut inputs = Inputs {
|
||||
let inputs = Inputs {
|
||||
target: Target {
|
||||
product_type: model.clone(),
|
||||
device_class: identity.device_class.clone(),
|
||||
@@ -980,7 +993,7 @@ impl Prepare {
|
||||
chip_id: parse_id(identity.ap_chip_id.as_deref())?,
|
||||
board_id: parse_id(identity.ap_board_id.as_deref())?,
|
||||
},
|
||||
kernel_collection: input(&kernel),
|
||||
kernel_collection: input(&kernel).into(),
|
||||
auxiliary_collection: auxiliary.as_ref().map(input),
|
||||
sptm: input(&sptm),
|
||||
txm: input(&txm),
|
||||
@@ -994,7 +1007,7 @@ impl Prepare {
|
||||
.chain(&kext_code)
|
||||
.map(input)
|
||||
.collect(),
|
||||
ramdisk: ramdisk.as_ref().map(input),
|
||||
ramdisk: None,
|
||||
root_hash: root_hash.as_ref().map(|(volume, decoded)| RootHash {
|
||||
volume: *volume,
|
||||
im4p: decoded.as_ref().map(input),
|
||||
@@ -1009,7 +1022,13 @@ impl Prepare {
|
||||
};
|
||||
let mut options = self.options(inputs.dram_base()?)?;
|
||||
options.security.kexts = kexts;
|
||||
let mut bundle = boot_bundle::prepare(&inputs, &options)?;
|
||||
let ramdisk_source = ramdisk.as_ref().map(|ramdisk| ramdisk.source.clone());
|
||||
let mut bundle = match ramdisk {
|
||||
Some(Decoded { bytes, source, .. }) => {
|
||||
boot_bundle::prepare_owned(&inputs, OwnedRamdisk { bytes, source }, &options)?
|
||||
}
|
||||
None => boot_bundle::prepare(&inputs, &options)?,
|
||||
};
|
||||
let mut unresolved = vec![];
|
||||
// The board the bundle's DeviceTree describes names its images, each
|
||||
// die the one its own node or its flash's names; the same IPSW's
|
||||
@@ -1021,29 +1040,34 @@ impl Prepare {
|
||||
.filter(|name| !board_firmware.iter().any(|(given, _)| given == name))
|
||||
.collect();
|
||||
if !names.is_empty() {
|
||||
let ramdisk = match &ramdisk {
|
||||
Some(ramdisk)
|
||||
if ramdisk.source.component == components::RESTORE_RAMDISK =>
|
||||
{
|
||||
ramdisk
|
||||
let separate_ramdisk;
|
||||
let (bytes, source) = match &ramdisk_source {
|
||||
Some(source) if source.component == components::RESTORE_RAMDISK => {
|
||||
let (_, bytes) = bundle
|
||||
.files
|
||||
.iter()
|
||||
.find(|(name, _)| name == RAMDISK_FILE)
|
||||
.context("the bundle has no restore ramdisk")?;
|
||||
(bytes.as_slice(), source)
|
||||
}
|
||||
_ => {
|
||||
ramdisk_component = component(
|
||||
separate_ramdisk = component(
|
||||
components::RESTORE_RAMDISK,
|
||||
Some("rdsk"),
|
||||
RAMDISK_LIMIT,
|
||||
)?;
|
||||
&ramdisk_component
|
||||
(separate_ramdisk.bytes.as_slice(), &separate_ramdisk.source)
|
||||
}
|
||||
};
|
||||
sourced =
|
||||
board_firmware::from_ramdisk(ramdisk, board_firmware::DIRECTORY, &names)?;
|
||||
inputs.board_firmware.extend(
|
||||
sourced
|
||||
.iter()
|
||||
.map(|(name, decoded)| (name.clone(), input(decoded))),
|
||||
);
|
||||
bundle = boot_bundle::prepare(&inputs, &options)?;
|
||||
let sourced = board_firmware::from_ramdisk(
|
||||
bytes,
|
||||
source,
|
||||
board_firmware::DIRECTORY,
|
||||
&names,
|
||||
)?;
|
||||
for (name, Decoded { bytes, source, .. }) in sourced {
|
||||
bundle.append_board_firmware(name, bytes, source)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(error) if board_firmware.is_empty() => unresolved.push(format!(
|
||||
|
||||
@@ -54,12 +54,13 @@ impl ReadAt for Slice<'_> {
|
||||
/// Each of `names` from `directory` of the decoded restore ramdisk's APFS
|
||||
/// volumes, with its source.
|
||||
pub(super) fn from_ramdisk(
|
||||
ramdisk: &Decoded,
|
||||
ramdisk: &[u8],
|
||||
ramdisk_source: &Source,
|
||||
directory: &str,
|
||||
names: &[String],
|
||||
) -> Result<Vec<(String, Decoded)>> {
|
||||
let member = &ramdisk.source.member;
|
||||
let mut source = Slice(&ramdisk.bytes);
|
||||
let member = &ramdisk_source.member;
|
||||
let mut source = Slice(ramdisk);
|
||||
let offsets = apfs::containers(&mut source)
|
||||
.with_context(|| format!("the restore ramdisk {member} holds no APFS container"))?;
|
||||
let [offset] = offsets[..] else {
|
||||
@@ -93,11 +94,11 @@ pub(super) fn from_ramdisk(
|
||||
let source = Source {
|
||||
component: "BoardFirmware".into(),
|
||||
member: member.clone(),
|
||||
container_sha256: ramdisk.source.container_sha256.clone(),
|
||||
container_sha256: ramdisk_source.container_sha256.clone(),
|
||||
payload_type: "raw".into(),
|
||||
description: format!(
|
||||
"board device firmware /{path} in the {} (decoded SHA-256 {})",
|
||||
ramdisk.source.component, ramdisk.source.decoded_sha256
|
||||
ramdisk_source.component, ramdisk_source.decoded_sha256
|
||||
),
|
||||
decoded_bytes: bytes.len() as u64,
|
||||
decoded_sha256: digest,
|
||||
@@ -145,7 +146,8 @@ mod tests {
|
||||
#[test]
|
||||
fn named_images_come_from_the_ramdisk_with_their_source() {
|
||||
let ramdisk = ramdisk();
|
||||
let found = from_ramdisk(&ramdisk, "", &["pattern.bin".into()]).unwrap();
|
||||
let found =
|
||||
from_ramdisk(&ramdisk.bytes, &ramdisk.source, "", &["pattern.bin".into()]).unwrap();
|
||||
let [(name, image)] = &found[..] else {
|
||||
panic!("one image");
|
||||
};
|
||||
@@ -165,7 +167,12 @@ mod tests {
|
||||
image.source.description
|
||||
);
|
||||
|
||||
let Err(error) = from_ramdisk(&ramdisk, DIRECTORY, &["USB-C_HPM,47.bin".into()]) else {
|
||||
let Err(error) = from_ramdisk(
|
||||
&ramdisk.bytes,
|
||||
&ramdisk.source,
|
||||
DIRECTORY,
|
||||
&["USB-C_HPM,47.bin".into()],
|
||||
) else {
|
||||
panic!("an image the ramdisk lacks is refused");
|
||||
};
|
||||
assert_eq!(
|
||||
|
||||
@@ -332,8 +332,8 @@ struct Create {
|
||||
#[arg(long)]
|
||||
install_volume: Option<PathBuf>,
|
||||
/// The bound of each translation pack `stela.efi` keeps on the USB, in
|
||||
/// bytes (64 MiB to 4 GiB; 0 for none). By default 2 GiB, or what the
|
||||
/// USB's FAT32 volumes have room for.
|
||||
/// bytes (64 MiB to the FAT32 file limit; 0 for none). Defaults to 1 GiB
|
||||
/// or what fits. The mount uses up to 1 GiB of each allocation.
|
||||
#[arg(long, value_name = "BYTES")]
|
||||
translation_store_bytes: Option<u64>,
|
||||
/// The model or size, as setup shows it, of the whole disk `--usb`
|
||||
|
||||
@@ -245,39 +245,106 @@ fn volume_label(label: &str) -> Result<[u8; 11]> {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use stela_drivers::block::RamDisk;
|
||||
use std::ops::Range;
|
||||
use stela_drivers::block::{BlockDevice, BlockError, Identity, Transport};
|
||||
use {stela_formats::payload::ReadAt, stela_runtime::pc::fat32::Fat32};
|
||||
|
||||
/// A disk holding the layout's writes over bytes that are not zero.
|
||||
fn image(bytes: u64, block_size: u32, layout: &Layout) -> RamDisk {
|
||||
let mut disk = RamDisk::new("USB", bytes / u64::from(block_size), block_size);
|
||||
disk.bytes.fill(0xa5);
|
||||
for write in &layout.writes {
|
||||
match write {
|
||||
Write::Bytes(at, data) => {
|
||||
let at = *at as usize;
|
||||
disk.bytes[at..at + data.len()].copy_from_slice(data);
|
||||
/// A dirty disk with the layout's ordered writes applied only to reads.
|
||||
struct Image<'a> {
|
||||
identity: Identity,
|
||||
writes: Vec<(Range<u64>, Option<&'a [u8]>)>,
|
||||
}
|
||||
|
||||
impl<'a> Image<'a> {
|
||||
fn new(bytes: u64, block_size: u32, layout: &'a Layout) -> Self {
|
||||
let block = u64::from(block_size);
|
||||
assert!(bytes.is_multiple_of(block));
|
||||
let writes = layout
|
||||
.writes
|
||||
.iter()
|
||||
.map(|write| {
|
||||
let (start, length, data) = match write {
|
||||
Write::Bytes(at, data) => (*at, data.len() as u64, Some(data.as_slice())),
|
||||
Write::Zeros(at, length) => (*at, *length, None),
|
||||
};
|
||||
let end = start.checked_add(length).expect("layout write overflows");
|
||||
assert!(end <= bytes, "layout write exceeds disk capacity");
|
||||
(start..end, data)
|
||||
})
|
||||
.collect();
|
||||
Self {
|
||||
identity: Identity {
|
||||
transport: Transport::Ram,
|
||||
location: "test".into(),
|
||||
model: "layout".into(),
|
||||
serial: "USB".into(),
|
||||
blocks: bytes / block,
|
||||
block_size,
|
||||
read_only: true,
|
||||
features: Default::default(),
|
||||
},
|
||||
writes,
|
||||
}
|
||||
}
|
||||
|
||||
fn read_bytes(&self, offset: u64, buffer: &mut [u8]) {
|
||||
let end = offset + buffer.len() as u64;
|
||||
assert!(end <= self.identity.bytes());
|
||||
buffer.fill(0xa5);
|
||||
for (write, data) in &self.writes {
|
||||
let start = offset.max(write.start);
|
||||
let end = end.min(write.end);
|
||||
if start >= end {
|
||||
continue;
|
||||
}
|
||||
Write::Zeros(at, length) => {
|
||||
disk.bytes[*at as usize..(*at + *length) as usize].fill(0);
|
||||
let output = &mut buffer[(start - offset) as usize..(end - offset) as usize];
|
||||
if let Some(data) = data {
|
||||
output.copy_from_slice(
|
||||
&data[(start - write.start) as usize..(end - write.start) as usize],
|
||||
);
|
||||
} else {
|
||||
output.fill(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
disk
|
||||
}
|
||||
|
||||
impl BlockDevice for Image<'_> {
|
||||
fn identity(&self) -> &Identity {
|
||||
&self.identity
|
||||
}
|
||||
|
||||
fn read(&mut self, lba: u64, buffer: &mut [u8]) -> Result<(), BlockError> {
|
||||
self.identity.check(lba, buffer.len())?;
|
||||
self.read_bytes(lba * u64::from(self.identity.block_size), buffer);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write(&mut self, _lba: u64, _data: &[u8]) -> Result<(), BlockError> {
|
||||
Err(BlockError::ReadOnly)
|
||||
}
|
||||
}
|
||||
|
||||
/// One partition's bytes, as the FAT reader reads them.
|
||||
struct Volume<'a>(&'a [u8]);
|
||||
struct Volume<'a> {
|
||||
disk: &'a Image<'a>,
|
||||
start: u64,
|
||||
bytes: u64,
|
||||
}
|
||||
|
||||
impl ReadAt for Volume<'_> {
|
||||
type Error = &'static str;
|
||||
fn len(&self) -> u64 {
|
||||
self.0.len() as u64
|
||||
self.bytes
|
||||
}
|
||||
fn read_at(&mut self, offset: u64, buffer: &mut [u8]) -> Result<(), Self::Error> {
|
||||
let at = usize::try_from(offset).map_err(|_| "offset")?;
|
||||
let bytes = self.0.get(at..at + buffer.len()).ok_or("past the end")?;
|
||||
buffer.copy_from_slice(bytes);
|
||||
if offset
|
||||
.checked_add(buffer.len() as u64)
|
||||
.is_none_or(|end| end > self.bytes)
|
||||
{
|
||||
return Err("past the end");
|
||||
}
|
||||
self.disk.read_bytes(self.start + offset, buffer);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -297,7 +364,7 @@ mod tests {
|
||||
fn erase_creates_bootable_fat32_layout() {
|
||||
let bytes = 2u64 << 30;
|
||||
let layout = layout(bytes, 512, "STELA", &mut counter()).unwrap();
|
||||
let mut disk = image(bytes, 512, &layout);
|
||||
let mut disk = Image::new(bytes, 512, &layout);
|
||||
let table = gpt::read(&mut disk).unwrap();
|
||||
let [esp, data] = &table.partitions[..] else {
|
||||
panic!("{:?}", table.partitions)
|
||||
@@ -310,22 +377,34 @@ mod tests {
|
||||
assert_eq!(data.first_lba * 512 % ALIGNMENT, 0);
|
||||
// The backup GPT ends the disk.
|
||||
assert!((data.last_lba + 1) * 512 <= bytes - 33 * 512);
|
||||
let mut sector = [0; 512];
|
||||
disk.read_bytes(bytes - 512, &mut sector);
|
||||
assert_eq!(§or[..8], b"EFI PART");
|
||||
assert_ne!(esp.unique, data.unique);
|
||||
// The gap before the ESP is zeroed but for the GPT.
|
||||
assert!(
|
||||
disk.bytes[34 * 512..ALIGNMENT as usize]
|
||||
.iter()
|
||||
.all(|b| *b == 0)
|
||||
);
|
||||
let mut buffer = [0; 4096];
|
||||
for start in (34 * 512..ALIGNMENT).step_by(buffer.len()) {
|
||||
let len = (ALIGNMENT - start).min(buffer.len() as u64) as usize;
|
||||
disk.read_bytes(start, &mut buffer[..len]);
|
||||
assert!(buffer[..len].iter().all(|&byte| byte == 0));
|
||||
}
|
||||
disk.read_bytes(data.last_lba * 512, &mut sector);
|
||||
assert_eq!(sector, [0xa5; 512]);
|
||||
for (partition, label) in [(esp, b"EFI "), (data, b"STELA ")] {
|
||||
let first = (partition.first_lba * 512) as usize;
|
||||
let end = ((partition.last_lba + 1) * 512) as usize;
|
||||
let volume = &disk.bytes[first..end];
|
||||
assert_eq!(&volume[71..82], label);
|
||||
assert_eq!(&volume[82..90], b"FAT32 ");
|
||||
let first = partition.first_lba * 512;
|
||||
disk.read_bytes(first, &mut sector);
|
||||
assert_eq!(§or[71..82], label);
|
||||
assert_eq!(§or[82..90], b"FAT32 ");
|
||||
// The backup boot sector, and an empty root directory.
|
||||
assert_eq!(volume[..512], volume[6 * 512..7 * 512]);
|
||||
let mut fat = Fat32::open(Volume(volume)).unwrap();
|
||||
let mut backup = [0; 512];
|
||||
disk.read_bytes(first + 6 * 512, &mut backup);
|
||||
assert_eq!(sector, backup);
|
||||
let mut fat = Fat32::open(Volume {
|
||||
disk: &disk,
|
||||
start: first,
|
||||
bytes: partition.blocks() * 512,
|
||||
})
|
||||
.unwrap();
|
||||
assert!(fat.file("EFI/BOOT/BOOTX64.EFI").is_err());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,10 +13,10 @@
|
||||
//! 4 GiB limit, so their concatenation is the IPSW byte for byte. Each piece
|
||||
//! is written as `ipsw.NNN.partial`, read back, and renamed; a rerun keeps
|
||||
//! every complete piece whose bytes still match the IPSW and writes only
|
||||
//! the rest. The IPSW's SHA-256 and SHA-1 are taken while its pieces are
|
||||
//! written, and compared with its download receipt and Apple's catalog
|
||||
//! digest; `payload.json` is written only when they match, so a medium
|
||||
//! without it is never taken for a complete one.
|
||||
//! the rest. While writing the IPSW, setup checks its SHA-256 and any
|
||||
//! catalog SHA-1 supplied by the download receipt. It writes
|
||||
//! `payload.json` after verification, so a medium without it is never
|
||||
//! taken for a complete one.
|
||||
//!
|
||||
//! A remote medium ([`write_remote`]) holds only `payload.json` and
|
||||
//! `blocks.bin`: `stela.efi` streams the IPSW from Apple's servers during
|
||||
@@ -331,27 +331,35 @@ fn stream(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn stream_file(
|
||||
path: &Path,
|
||||
size: u64,
|
||||
progress: &crate::progress::Phase,
|
||||
mut consume: impl FnMut(&[u8]),
|
||||
) -> Result<()> {
|
||||
let mut file =
|
||||
fs::File::open(path).with_context(|| format!("cannot read {}", path.display()))?;
|
||||
stream(&mut file, size, |bytes| {
|
||||
consume(bytes);
|
||||
progress.advance(bytes.len() as u64);
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
fn hash_file(
|
||||
path: &Path,
|
||||
size: u64,
|
||||
progress: &crate::progress::Phase,
|
||||
) -> Result<(String, Vec<u8>)> {
|
||||
let mut file =
|
||||
fs::File::open(path).with_context(|| format!("cannot read {}", path.display()))?;
|
||||
let mut hashes = Hashes::default();
|
||||
stream(&mut file, size, |bytes| {
|
||||
hashes.update(bytes);
|
||||
progress.advance(bytes.len() as u64);
|
||||
Ok(())
|
||||
})?;
|
||||
stream_file(path, size, progress, |bytes| hashes.update(bytes))?;
|
||||
Ok(hashes.finish())
|
||||
}
|
||||
|
||||
/// The whole IPSW's SHA-256 and catalog SHA-1.
|
||||
#[derive(Default)]
|
||||
struct Whole {
|
||||
/// The whole IPSW's SHA-256 and its SHA-1 if the catalog supplies one.
|
||||
struct Whole<'a> {
|
||||
sha256: Sha256,
|
||||
sha1: Sha1,
|
||||
catalog: Option<(&'a str, Sha1)>,
|
||||
}
|
||||
|
||||
/// Read `size` bytes of `ipsw` from `offset` and return their hashes;
|
||||
@@ -362,7 +370,7 @@ fn piece(
|
||||
offset: u64,
|
||||
size: u64,
|
||||
partial: Option<&Path>,
|
||||
mut whole: Option<&mut Whole>,
|
||||
mut whole: Option<&mut Whole<'_>>,
|
||||
progress: &crate::progress::Phase,
|
||||
) -> Result<(String, Vec<u8>)> {
|
||||
ipsw.seek(SeekFrom::Start(offset))?;
|
||||
@@ -376,7 +384,9 @@ fn piece(
|
||||
hashes.update(bytes);
|
||||
if let Some(whole) = whole.as_deref_mut() {
|
||||
whole.sha256.update(bytes);
|
||||
whole.sha1.update(bytes);
|
||||
if let Some((_, hash)) = &mut whole.catalog {
|
||||
hash.update(bytes);
|
||||
}
|
||||
}
|
||||
match (&mut out, partial) {
|
||||
(Some(out), Some(path)) => out
|
||||
@@ -445,7 +455,10 @@ pub(super) fn write(options: WriteOptions<'_>) -> Result<Written> {
|
||||
ipsw.display(),
|
||||
sizes.len()
|
||||
);
|
||||
let mut whole = Whole::default();
|
||||
let mut whole = Whole {
|
||||
sha256: Sha256::new(),
|
||||
catalog: expected.sha1.as_deref().map(|digest| (digest, Sha1::new())),
|
||||
};
|
||||
let mut pieces = Vec::new();
|
||||
let mut piece_blocks = Vec::new();
|
||||
let mut written = Written::default();
|
||||
@@ -506,7 +519,6 @@ pub(super) fn write(options: WriteOptions<'_>) -> Result<Written> {
|
||||
}
|
||||
}
|
||||
let sha256 = hex::encode(whole.sha256.finalize());
|
||||
let sha1 = hex::encode(whole.sha1.finalize());
|
||||
ensure!(
|
||||
manifest.source.sha256.as_ref() == Some(&sha256),
|
||||
"{} changed while setup read it: its SHA-256 is now {sha256}",
|
||||
@@ -520,14 +532,17 @@ pub(super) fn write(options: WriteOptions<'_>) -> Result<Written> {
|
||||
ipsw.display()
|
||||
);
|
||||
}
|
||||
if let Some(catalog) = &expected.sha1 {
|
||||
manifest.source.catalog_sha1 = if let Some((catalog, hash)) = whole.catalog {
|
||||
let sha1 = hex::encode(hash.finalize());
|
||||
ensure!(
|
||||
sha1.eq_ignore_ascii_case(catalog),
|
||||
"{}'s SHA-1 {sha1} differs from Apple's catalog digest {catalog}; download it again",
|
||||
ipsw.display()
|
||||
);
|
||||
}
|
||||
manifest.source.catalog_sha1 = expected.sha1.as_ref().map(|_| sha1);
|
||||
Some(sha1)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
manifest.layout = Layout::Pieces {
|
||||
piece_bytes,
|
||||
pieces,
|
||||
@@ -722,6 +737,20 @@ pub(super) mod tests {
|
||||
.flat_map(|index| fs::read(directory.join(piece_name(index))).unwrap())
|
||||
.collect();
|
||||
assert_eq!(joined, bytes);
|
||||
|
||||
let manual = write(WriteOptions {
|
||||
volume: &volume,
|
||||
ipsw: &ipsw,
|
||||
inventory: inventory(&ipsw),
|
||||
expected: &Expected::default(),
|
||||
piece_bytes: PIECE_BYTES,
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!((manual.kept, manual.wrote), (count, 0));
|
||||
let manual_manifest =
|
||||
PayloadManifest::parse(&fs::read(directory.join(MANIFEST_FILE)).unwrap()).unwrap();
|
||||
assert_eq!(manual_manifest.source.sha256, manifest.source.sha256);
|
||||
assert!(manual_manifest.source.catalog_sha1.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -74,7 +74,8 @@ fn write_from(
|
||||
}
|
||||
let mut pieces = Vec::new();
|
||||
let mut piece_blocks = Vec::new();
|
||||
let mut whole = Whole::default();
|
||||
let mut whole_sha256 = Sha256::new();
|
||||
let mut whole_sha1 = Sha1::new();
|
||||
let progress = crate::progress::Phase::bytes("Downloading macOS onto USB", total);
|
||||
for (index, &size) in sizes.iter().enumerate() {
|
||||
let mut file = fs::File::create(directory.join(format!("{}.partial", piece_name(index))))?;
|
||||
@@ -82,8 +83,8 @@ fn write_from(
|
||||
stream(&mut source, size, |bytes| {
|
||||
file.write_all(bytes)?;
|
||||
hashes.update(bytes);
|
||||
whole.sha256.update(bytes);
|
||||
whole.sha1.update(bytes);
|
||||
whole_sha256.update(bytes);
|
||||
whole_sha1.update(bytes);
|
||||
progress.advance(bytes.len() as u64);
|
||||
Ok(())
|
||||
})?;
|
||||
@@ -99,8 +100,8 @@ fn write_from(
|
||||
source.read(&mut [0])? == 0,
|
||||
"download exceeds the expected image size"
|
||||
);
|
||||
let sha256 = hex::encode(whole.sha256.finalize());
|
||||
let sha1 = hex::encode(whole.sha1.finalize());
|
||||
let sha256 = hex::encode(whole_sha256.finalize());
|
||||
let sha1 = hex::encode(whole_sha1.finalize());
|
||||
ensure!(
|
||||
image
|
||||
.sha1
|
||||
@@ -113,8 +114,14 @@ fn write_from(
|
||||
for (index, piece) in pieces.iter().enumerate() {
|
||||
let path = directory.join(piece_name(index));
|
||||
let partial = directory.join(format!("{}.partial", piece_name(index)));
|
||||
// The download already recorded the per-block hashes. Readback
|
||||
// verifies the piece's digest before publishing it.
|
||||
let mut readback = Sha256::new();
|
||||
stream_file(&partial, piece.bytes, &progress, |bytes| {
|
||||
readback.update(bytes);
|
||||
})?;
|
||||
ensure!(
|
||||
hash_file(&partial, piece.bytes, &progress)?.0 == piece.sha256,
|
||||
hex::encode(readback.finalize()) == piece.sha256,
|
||||
"USB data does not read back as written"
|
||||
);
|
||||
if path.exists() {
|
||||
@@ -255,11 +262,38 @@ mod tests {
|
||||
written.wrote > 1,
|
||||
"the fixture must exercise joined-piece reads"
|
||||
);
|
||||
let manifest = fs::read(directory(&volume, &image.build).join(MANIFEST_FILE))?;
|
||||
let written_dir = directory(&volume, &image.build);
|
||||
let manifest = fs::read(written_dir.join(MANIFEST_FILE))?;
|
||||
let manifest = stela_formats::payload::PayloadManifest::parse(&manifest)
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
assert!(matches!(manifest.layout, Layout::Pieces { .. }));
|
||||
assert_eq!(manifest.source.sha256, Some(stela_formats::sha256(&bytes)));
|
||||
let Layout::Pieces {
|
||||
pieces,
|
||||
block_hashes,
|
||||
..
|
||||
} = manifest.layout
|
||||
else {
|
||||
panic!("download did not publish a pieces layout");
|
||||
};
|
||||
let mut expected_blocks = Vec::new();
|
||||
assert_eq!(
|
||||
pieces.len(),
|
||||
bytes.len().div_ceil(HASH_BLOCK_BYTES as usize)
|
||||
);
|
||||
for (index, (piece, expected)) in pieces
|
||||
.iter()
|
||||
.zip(bytes.chunks(HASH_BLOCK_BYTES as usize))
|
||||
.enumerate()
|
||||
{
|
||||
let digest = Sha256::digest(expected);
|
||||
expected_blocks.extend_from_slice(&digest);
|
||||
assert_eq!(piece.sha256, hex::encode(digest));
|
||||
assert_eq!(fs::read(written_dir.join(piece_name(index)))?, expected);
|
||||
}
|
||||
assert_eq!(
|
||||
fs::read(written_dir.join(block_hashes.file))?,
|
||||
expected_blocks
|
||||
);
|
||||
let mut damaged = bytes.clone();
|
||||
damaged[0] ^= 1;
|
||||
let mut oversized = bytes.clone();
|
||||
|
||||
@@ -1770,6 +1770,16 @@ fn additional_disk_gets_separate_machine_identity() {
|
||||
assert!(!f.esp.join("EFI/stela").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn translation_store_defaults_to_the_firmware_pack_limit() {
|
||||
let f = fixture(64 * GIB, true);
|
||||
let (store, _) = translations::choose(&f.host, &[&f.data], |_| 0, None).unwrap();
|
||||
assert_eq!(store.unwrap().pack_bytes, GIB);
|
||||
|
||||
let (store, _) = translations::choose(&f.host, &[&f.data], |_| 0, Some(2 * GIB)).unwrap();
|
||||
assert_eq!(store.unwrap().pack_bytes, 2 * GIB);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn same_revision_update_preserves_options() {
|
||||
let mut f = fixture(64 * GIB, false);
|
||||
|
||||
@@ -36,6 +36,7 @@ use std::{
|
||||
path::{Path, PathBuf},
|
||||
time::SystemTime,
|
||||
};
|
||||
use stela_boot_core::memory_budget::MAX_TRANSLATION_PACK_BYTES;
|
||||
|
||||
/// The store's directory on its volume.
|
||||
pub(super) const DIRECTORY: &str = "stela/store";
|
||||
@@ -54,7 +55,7 @@ const ID_BYTES: usize = 32;
|
||||
const HEADER_BYTES: usize = PACK_MAGIC.len() + 4 + 4 + ID_BYTES;
|
||||
const MIB: u64 = 1024 * 1024;
|
||||
/// One pack's bound by default.
|
||||
pub(super) const DEFAULT_PACK_BYTES: u64 = 2 * 1024 * MIB;
|
||||
pub(super) const DEFAULT_PACK_BYTES: u64 = MAX_TRANSLATION_PACK_BYTES;
|
||||
/// The smallest bound worth keeping a store for.
|
||||
pub(super) const MIN_PACK_BYTES: u64 = 64 * MIB;
|
||||
/// FAT32's largest file, on a 1 MiB boundary.
|
||||
|
||||
@@ -96,6 +96,10 @@ pub enum Operation {
|
||||
}
|
||||
|
||||
pub fn decode(word: u32) -> Option<Operation> {
|
||||
// All the modeled hint, barrier and timed-wait forms share this class.
|
||||
if word >> 16 != 0xd503 {
|
||||
return None;
|
||||
}
|
||||
if word & BARRIER_MASK == DSB_CLASS {
|
||||
let option = ((word >> OPTION_SHIFT) & OPTION_MASK) as u8;
|
||||
if option == SSBB_OPTION || option == PSSBB_OPTION {
|
||||
|
||||
@@ -562,7 +562,12 @@ impl CompilationPlan {
|
||||
checked.emit(parsed.terminal.as_ref(), parsed.next_pc, target, recipes)?
|
||||
} else if let Some(resident) = resident {
|
||||
resident
|
||||
.emit(&parsed.instructions)
|
||||
.emit(
|
||||
&parsed.instructions,
|
||||
parsed.terminal.as_ref(),
|
||||
parsed.next_pc,
|
||||
target,
|
||||
)
|
||||
.map_err(CompileError::from)?
|
||||
} else if profile.has(Features::RESIDENT_LOOPS) {
|
||||
crate::x86_64::block::emit_resident_fallback_for_target(
|
||||
|
||||
@@ -318,15 +318,12 @@ pub(super) fn parse(
|
||||
});
|
||||
continue;
|
||||
}
|
||||
if let Some(decoded) =
|
||||
system::decode_system_mode_instruction(pc, word).map_err(|error| {
|
||||
BlockAnalysisError {
|
||||
pc,
|
||||
encoding: Some(word),
|
||||
kind: error.kind,
|
||||
}
|
||||
})?
|
||||
{
|
||||
if let Some(decoded) = system::decode_system_mode_with_sync(pc, word, synchronization)
|
||||
.map_err(|error| BlockAnalysisError {
|
||||
pc,
|
||||
encoding: Some(word),
|
||||
kind: error.kind,
|
||||
})? {
|
||||
// The shared lane executes these through the existing typed
|
||||
// all-writer memory service, not the single-agent CPU monitor.
|
||||
let checked = checked_memory
|
||||
|
||||
@@ -125,6 +125,11 @@ pub fn decode_pointer_authentication(
|
||||
.at_instruction(pc, word),
|
||||
);
|
||||
}
|
||||
// The PAuth and PAuth_LR forms below occupy these encoding classes.
|
||||
// Reject other words before probing the exact forms and operand masks.
|
||||
if !matches!(word >> 24, 0x55 | 0x9a | 0xd5..=0xd7 | 0xda | 0xf3 | 0xf8) {
|
||||
return Ok(None);
|
||||
}
|
||||
let operation = if let Some(instruction) = pauth_lr::decode(word) {
|
||||
PointerAuthenticationOperation::LinkRegister(instruction)
|
||||
} else {
|
||||
|
||||
@@ -110,7 +110,8 @@ impl FaultRecovery {
|
||||
state: &mut crate::GuestState,
|
||||
) -> Result<Option<RecoverySettlement>, FaultRecoveryError> {
|
||||
let mut settlement: Option<RecoverySettlement> = None;
|
||||
let mut values = [None; 32];
|
||||
let mut values = [0; 32];
|
||||
let mut present = 0u32;
|
||||
for entry in table {
|
||||
if entry.start >= entry.end {
|
||||
return Err(FaultRecoveryError::InvalidNativeRange {
|
||||
@@ -166,21 +167,23 @@ impl FaultRecovery {
|
||||
.ok_or(FaultRecoveryError::NativeSpillUnavailable { offset })?,
|
||||
};
|
||||
let slot = &mut values[usize::from(binding.guest)];
|
||||
if slot.is_some_and(|previous| previous != value) {
|
||||
let bit = 1 << binding.guest;
|
||||
if present & bit != 0 && *slot != value {
|
||||
return Err(FaultRecoveryError::ConflictingGuestBinding {
|
||||
register: binding.guest,
|
||||
});
|
||||
}
|
||||
*slot = Some(value);
|
||||
*slot = value;
|
||||
present |= bit;
|
||||
}
|
||||
}
|
||||
for (guest, value) in values.into_iter().enumerate() {
|
||||
if let Some(value) = value {
|
||||
if guest == 31 {
|
||||
state.sp = value;
|
||||
} else {
|
||||
state.x[guest] = value;
|
||||
}
|
||||
while present != 0 {
|
||||
let guest = present.trailing_zeros() as usize;
|
||||
present &= present - 1;
|
||||
if guest == 31 {
|
||||
state.sp = values[guest];
|
||||
} else {
|
||||
state.x[guest] = values[guest];
|
||||
}
|
||||
}
|
||||
Ok(settlement)
|
||||
|
||||
@@ -7,10 +7,15 @@ use super::{
|
||||
SpillOffset,
|
||||
};
|
||||
use crate::GuestAddress;
|
||||
use alloc::{boxed::Box, vec::Vec};
|
||||
use alloc::{borrow::Cow, boxed::Box, vec::Vec};
|
||||
|
||||
const AFTER_FALLTHROUGH: u8 = 1 << 2;
|
||||
const TRANSLATED: u8 = 1 << 3;
|
||||
const SEPARATE_PC_DELTA: u8 = 1 << 4;
|
||||
const BINDINGS_SHIFT: u32 = 5;
|
||||
const LONG_BINDINGS: usize = 7;
|
||||
const RETAINED_ROWS: usize = 4;
|
||||
const RETAINED_BINDINGS: usize = 32;
|
||||
|
||||
fn zigzag(value: i64) -> u64 {
|
||||
((value << 1) ^ (value >> 63)) as u64
|
||||
@@ -53,10 +58,31 @@ impl Reader<'_> {
|
||||
shift += 7;
|
||||
}
|
||||
}
|
||||
|
||||
fn skip_bindings(&mut self, count: usize) {
|
||||
// A guest byte and a single-byte source, as for every host GPR.
|
||||
let (head, tail) = self.bytes.split_at(2 * count);
|
||||
if head
|
||||
.as_chunks::<2>()
|
||||
.0
|
||||
.iter()
|
||||
.all(|binding| binding[1] < 0x80)
|
||||
{
|
||||
self.bytes = tail;
|
||||
return;
|
||||
}
|
||||
for _ in 0..count {
|
||||
self.byte();
|
||||
self.value();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PackedRecovery {
|
||||
pub fn new(rows: &[FaultRecovery]) -> Self {
|
||||
if rows.is_empty() {
|
||||
return Self(Box::default());
|
||||
}
|
||||
let mut out = Vec::with_capacity(rows.len() * 12 + 2);
|
||||
put(&mut out, rows.len() as u64);
|
||||
let (mut end, mut pc, mut retired) = (0, 0, 0);
|
||||
@@ -64,27 +90,42 @@ impl PackedRecovery {
|
||||
let point = row.retirement;
|
||||
let at = point.instruction_pc().0;
|
||||
let site = row.site;
|
||||
put(&mut out, zigzag(row.start as i64 - end));
|
||||
put(&mut out, (row.end - row.start) as u64);
|
||||
put(&mut out, zigzag(at.wrapping_sub(pc) as i64));
|
||||
put(
|
||||
&mut out,
|
||||
zigzag(i64::from(point.retired_before()) - retired),
|
||||
);
|
||||
let pc_delta = at.wrapping_sub(pc) as i64;
|
||||
let retired_delta = i64::from(point.retired_before()) - retired;
|
||||
let separate_pc = pc_delta != retired_delta * 4;
|
||||
let inline_bindings = row.bindings.len().min(LONG_BINDINGS);
|
||||
let start = zigzag(row.start as i64 - end);
|
||||
let span = (row.end - row.start) as u64;
|
||||
let delta = zigzag(retired_delta);
|
||||
let translated = site.translated_access();
|
||||
out.push(
|
||||
site.kind() as u8
|
||||
| if point.phase() == RetirementPhase::AfterFallthrough {
|
||||
AFTER_FALLTHROUGH
|
||||
} else {
|
||||
0
|
||||
}
|
||||
| if translated.is_some() { TRANSLATED } else { 0 },
|
||||
);
|
||||
let tag = site.kind() as u8
|
||||
| if point.phase() == RetirementPhase::AfterFallthrough {
|
||||
AFTER_FALLTHROUGH
|
||||
} else {
|
||||
0
|
||||
}
|
||||
| if translated.is_some() { TRANSLATED } else { 0 }
|
||||
| if separate_pc { SEPARATE_PC_DELTA } else { 0 }
|
||||
| (inline_bindings as u8) << BINDINGS_SHIFT;
|
||||
if (start | span | delta) < 0x80 {
|
||||
out.extend_from_slice(&[start as u8, span as u8, delta as u8, tag]);
|
||||
} else {
|
||||
put(&mut out, start);
|
||||
put(&mut out, span);
|
||||
put(&mut out, delta);
|
||||
out.push(tag);
|
||||
}
|
||||
// The PC normally advances by four bytes for each instruction
|
||||
// retired. Keep a separate delta only when the row differs.
|
||||
if separate_pc {
|
||||
put(&mut out, zigzag(pc_delta));
|
||||
}
|
||||
if let Some(access) = translated {
|
||||
out.extend_from_slice(&[access.bytes, access.flags]);
|
||||
}
|
||||
put(&mut out, row.bindings.len() as u64);
|
||||
if inline_bindings == LONG_BINDINGS {
|
||||
put(&mut out, row.bindings.len() as u64);
|
||||
}
|
||||
for binding in &row.bindings {
|
||||
out.push(binding.guest);
|
||||
put(
|
||||
@@ -107,36 +148,100 @@ impl PackedRecovery {
|
||||
|
||||
/// The rows given to [`Self::new`].
|
||||
pub fn rows(&self) -> Vec<FaultRecovery> {
|
||||
let mut rows = Vec::new();
|
||||
self.decode(None, &mut rows);
|
||||
rows
|
||||
}
|
||||
|
||||
/// Rows that apply at this native offset, plus any malformed ranges that
|
||||
/// the caller must reject regardless of where the fault occurred.
|
||||
pub fn rows_at(&self, offset: usize) -> Vec<FaultRecovery> {
|
||||
let mut rows = Vec::new();
|
||||
self.decode(Some(offset), &mut rows);
|
||||
rows
|
||||
}
|
||||
|
||||
/// Like [`Self::rows_at`], reusing storage across fault lookups. Large
|
||||
/// tables are owned by this lookup alone, so the scratch retains only
|
||||
/// enough space for a few rows and a register file's worth of bindings
|
||||
/// in each.
|
||||
pub fn rows_at_reusing<'a>(
|
||||
&self,
|
||||
offset: usize,
|
||||
scratch: &'a mut Vec<FaultRecovery>,
|
||||
) -> Cow<'a, [FaultRecovery]> {
|
||||
let count = self.decode(Some(offset), scratch);
|
||||
if scratch.capacity() > RETAINED_ROWS
|
||||
|| scratch
|
||||
.iter()
|
||||
.any(|row| row.bindings.capacity() > RETAINED_BINDINGS)
|
||||
{
|
||||
let mut rows = core::mem::take(scratch);
|
||||
rows.truncate(count);
|
||||
Cow::Owned(rows)
|
||||
} else {
|
||||
Cow::Borrowed(&scratch[..count])
|
||||
}
|
||||
}
|
||||
|
||||
fn decode(&self, offset: Option<usize>, rows: &mut Vec<FaultRecovery>) -> usize {
|
||||
if self.0.is_empty() {
|
||||
return 0;
|
||||
}
|
||||
let mut reader = Reader { bytes: &self.0 };
|
||||
let count = reader.value() as usize;
|
||||
let mut rows = Vec::with_capacity(count);
|
||||
if offset.is_none() {
|
||||
rows.reserve(count);
|
||||
}
|
||||
let mut kept = 0;
|
||||
let (mut end, mut pc, mut retired) = (0, 0, 0);
|
||||
for _ in 0..count {
|
||||
let start = end + unzigzag(reader.value());
|
||||
let row_end = start + reader.value() as i64;
|
||||
pc = u64::wrapping_add(pc, unzigzag(reader.value()) as u64);
|
||||
retired += unzigzag(reader.value());
|
||||
let retired_delta = unzigzag(reader.value());
|
||||
retired += retired_delta;
|
||||
let tag = reader.byte();
|
||||
let pc_delta = if tag & SEPARATE_PC_DELTA == 0 {
|
||||
retired_delta * 4
|
||||
} else {
|
||||
unzigzag(reader.value())
|
||||
};
|
||||
pc = u64::wrapping_add_signed(pc, pc_delta);
|
||||
let translated = (tag & TRANSLATED != 0).then(|| (reader.byte(), reader.byte()));
|
||||
let bindings = (0..reader.value())
|
||||
.map(|_| {
|
||||
let guest = reader.byte();
|
||||
let source = reader.value();
|
||||
RecoveryBinding {
|
||||
guest,
|
||||
source: if source & 1 == 0 {
|
||||
RecoverySource::HostRegister((source >> 1) as u8)
|
||||
} else {
|
||||
RecoverySource::NativeSpill(
|
||||
SpillOffset::new((source >> 1) as u16).expect("packed by new"),
|
||||
)
|
||||
},
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
rows.push(FaultRecovery {
|
||||
start: start as usize,
|
||||
end: row_end as usize,
|
||||
let inline_bindings = usize::from(tag >> BINDINGS_SHIFT);
|
||||
let binding_count = if inline_bindings == LONG_BINDINGS {
|
||||
reader.value() as usize
|
||||
} else {
|
||||
inline_bindings
|
||||
};
|
||||
let range = start as usize..row_end as usize;
|
||||
end = row_end;
|
||||
if offset.is_some_and(|at| range.start < range.end && !range.contains(&at)) {
|
||||
reader.skip_bindings(binding_count);
|
||||
continue;
|
||||
}
|
||||
let mut bindings = rows.get_mut(kept).map_or_else(Vec::new, |row| {
|
||||
let mut bindings = core::mem::take(&mut row.bindings);
|
||||
bindings.clear();
|
||||
bindings
|
||||
});
|
||||
bindings.extend((0..binding_count).map(|_| {
|
||||
let guest = reader.byte();
|
||||
let source = reader.value();
|
||||
RecoveryBinding {
|
||||
guest,
|
||||
source: if source & 1 == 0 {
|
||||
RecoverySource::HostRegister((source >> 1) as u8)
|
||||
} else {
|
||||
RecoverySource::NativeSpill(
|
||||
SpillOffset::new((source >> 1) as u16).expect("packed by new"),
|
||||
)
|
||||
},
|
||||
}
|
||||
}));
|
||||
let row = FaultRecovery {
|
||||
start: range.start,
|
||||
end: range.end,
|
||||
bindings,
|
||||
retirement: RetirementPoint::packed(
|
||||
GuestAddress(pc),
|
||||
@@ -148,10 +253,15 @@ impl PackedRecovery {
|
||||
},
|
||||
),
|
||||
site: RecoverySite::packed(tag & 3, translated),
|
||||
});
|
||||
end = row_end;
|
||||
};
|
||||
if let Some(prior) = rows.get_mut(kept) {
|
||||
*prior = row;
|
||||
} else {
|
||||
rows.push(row);
|
||||
}
|
||||
kept += 1;
|
||||
}
|
||||
rows
|
||||
kept
|
||||
}
|
||||
}
|
||||
|
||||
@@ -160,6 +270,78 @@ mod tests {
|
||||
use super::*;
|
||||
use alloc::vec;
|
||||
|
||||
#[test]
|
||||
fn empty_tables_keep_no_payload() {
|
||||
let packed = PackedRecovery::new(&[]);
|
||||
assert_eq!(packed.bytes(), 0);
|
||||
assert!(packed.rows().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_large_binding_count_round_trips_with_a_separate_pc_delta() {
|
||||
let row = FaultRecovery {
|
||||
start: 10,
|
||||
end: 15,
|
||||
bindings: (0..12)
|
||||
.map(|register| RecoveryBinding::gpr(register, register))
|
||||
.collect(),
|
||||
retirement: RetirementPoint::before(GuestAddress(0x1234_8000), 26).unwrap(),
|
||||
site: RecoverySite::guest_access(),
|
||||
};
|
||||
let packed = PackedRecovery::new(core::slice::from_ref(&row));
|
||||
assert_eq!(packed.rows(), [row]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selected_rows_keep_overlaps_and_malformed_ranges() {
|
||||
let row = |start, end| FaultRecovery {
|
||||
start,
|
||||
end,
|
||||
bindings: vec![RecoveryBinding::gpr(1, 2)],
|
||||
retirement: RetirementPoint::before(GuestAddress(0x4000), 0).unwrap(),
|
||||
site: RecoverySite::guest_access(),
|
||||
};
|
||||
let rows = [row(0, 4), row(8, 16), row(9, 11), row(100, 100)];
|
||||
let packed = PackedRecovery::new(&rows);
|
||||
assert_eq!(
|
||||
packed.rows_at(10),
|
||||
[rows[1].clone(), rows[2].clone(), rows[3].clone()],
|
||||
);
|
||||
assert_eq!(packed.rows_at(16), [rows[3].clone()]);
|
||||
|
||||
let mut scratch = Vec::new();
|
||||
let selected = packed.rows_at_reusing(10, &mut scratch);
|
||||
assert_eq!(selected.as_ref(), packed.rows_at(10));
|
||||
let bindings = selected[0].bindings.as_ptr();
|
||||
let selected = packed.rows_at_reusing(16, &mut scratch);
|
||||
assert_eq!(selected.as_ref(), packed.rows_at(16));
|
||||
assert_eq!(selected[0].bindings.as_ptr(), bindings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oversized_fault_tables_do_not_grow_the_scratch() {
|
||||
let row = FaultRecovery {
|
||||
start: 0,
|
||||
end: 4,
|
||||
bindings: vec![RecoveryBinding::gpr(1, 2)],
|
||||
retirement: RetirementPoint::before(GuestAddress(0x4000), 0).unwrap(),
|
||||
site: RecoverySite::guest_access(),
|
||||
};
|
||||
let rows = vec![row.clone(); RETAINED_ROWS + 1];
|
||||
let bindings = FaultRecovery {
|
||||
bindings: vec![RecoveryBinding::gpr(1, 2); RETAINED_BINDINGS + 1],
|
||||
..row
|
||||
};
|
||||
for table in [&rows[..], &[bindings][..]] {
|
||||
let packed = PackedRecovery::new(table);
|
||||
let mut scratch = Vec::new();
|
||||
let selected = packed.rows_at_reusing(0, &mut scratch);
|
||||
assert!(matches!(selected, Cow::Owned(_)));
|
||||
assert_eq!(selected.as_ref(), table);
|
||||
assert_eq!(scratch.capacity(), 0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rows_survive_packing_exactly_and_in_order() {
|
||||
let pc = 0xffff_fe00_0912_3000;
|
||||
@@ -172,7 +354,7 @@ mod tests {
|
||||
end: 47,
|
||||
bindings: vec![
|
||||
RecoveryBinding::gpr(3, 9),
|
||||
RecoveryBinding::spill(30, SpillOffset::new(8).unwrap()),
|
||||
RecoveryBinding::spill(30, SpillOffset::new(96).unwrap()),
|
||||
],
|
||||
retirement: point(8, 2),
|
||||
site: RecoverySite::guest_access(),
|
||||
@@ -202,6 +384,7 @@ mod tests {
|
||||
];
|
||||
let packed = PackedRecovery::new(&rows);
|
||||
assert_eq!(packed.rows(), rows);
|
||||
assert_eq!(packed.rows_at(13), [rows[1].clone()]);
|
||||
assert!(packed.0.len() < 64);
|
||||
assert_eq!(PackedRecovery::new(&[]).rows(), []);
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
//!
|
||||
//! Native blocks return only the instruction's PC and exit kind; the runtime
|
||||
//! re-decodes the source word before applying the effect.
|
||||
use crate::aarch64::Unsupported;
|
||||
|
||||
use crate::{
|
||||
CompileError, GuestAddress,
|
||||
@@ -225,6 +224,53 @@ fn serialize_family<S: Serializer>(
|
||||
pub fn decode_system_instruction(
|
||||
pc: GuestAddress,
|
||||
word: u32,
|
||||
) -> Result<Option<SystemInstruction>, CompileError> {
|
||||
decode_instruction(pc, word, synchronization::decode(word), false)
|
||||
}
|
||||
|
||||
/// Decode the EL1 system instructions the platform completes. NOP, PAuth
|
||||
/// aliases and other hints keep their existing decoding.
|
||||
pub(super) fn decode_el1_system_instruction(
|
||||
pc: GuestAddress,
|
||||
word: u32,
|
||||
) -> Result<Option<SystemInstruction>, CompileError> {
|
||||
let sync = synchronization::decode(word);
|
||||
if let Some(instruction) = decode_instruction(pc, word, sync, false)? {
|
||||
return Ok(Some(instruction));
|
||||
}
|
||||
let Some(operation @ synchronization::Operation::DataCompletion { .. }) = sync else {
|
||||
return Ok(None);
|
||||
};
|
||||
request(pc, word, SystemOperation::Synchronization(operation)).map(Some)
|
||||
}
|
||||
|
||||
/// Decode every instruction the system-mode profile hands to the runtime: the
|
||||
/// [`decode_el1_system_instruction`] families, SYS/SYSL, and the barriers and
|
||||
/// hints that the ordinary decoder does not own (DSB, SSBB/PSSBB, ESB,
|
||||
/// TSB and unallocated hints), Apple's GXF instructions, SDSB, WKDMC and
|
||||
/// WKDMD, the Debug-state-only MOVT GPR/ZT0 forms, and the FEAT_CPA pointer
|
||||
/// arithmetic. YIELD, CSDB, SB and DMB stay ordinary and BTI compiles as NOP;
|
||||
/// PAuth hints belong to the PAuth decoder, which the profile consults first.
|
||||
pub fn decode_system_mode_instruction(
|
||||
pc: GuestAddress,
|
||||
word: u32,
|
||||
) -> Result<Option<SystemInstruction>, CompileError> {
|
||||
decode_system_mode_with_sync(pc, word, synchronization::decode(word))
|
||||
}
|
||||
|
||||
pub(super) fn decode_system_mode_with_sync(
|
||||
pc: GuestAddress,
|
||||
word: u32,
|
||||
sync: Option<synchronization::Operation>,
|
||||
) -> Result<Option<SystemInstruction>, CompileError> {
|
||||
decode_instruction(pc, word, sync, true)
|
||||
}
|
||||
|
||||
fn decode_instruction(
|
||||
pc: GuestAddress,
|
||||
word: u32,
|
||||
sync: Option<synchronization::Operation>,
|
||||
system_mode: bool,
|
||||
) -> Result<Option<SystemInstruction>, CompileError> {
|
||||
if !pc.0.is_multiple_of(INSTRUCTION_BYTES) {
|
||||
return Err(
|
||||
@@ -232,7 +278,76 @@ pub fn decode_system_instruction(
|
||||
.at_instruction(pc, word),
|
||||
);
|
||||
}
|
||||
let synchronization = match synchronization::decode(word) {
|
||||
// Route by the fixed high byte of the encoding classes. Ordinary ALU,
|
||||
// branch and memory words outside these classes need no family probes.
|
||||
// The family decoders still own every fixed bit and operand check.
|
||||
let operation = match word >> 24 {
|
||||
0x00 => exception::decode(word)
|
||||
.map(SystemOperation::Exception)
|
||||
.or_else(|| {
|
||||
if !system_mode {
|
||||
return None;
|
||||
}
|
||||
GuardedOperation::decode(word)
|
||||
.map(SystemOperation::Guarded)
|
||||
.or_else(|| {
|
||||
AppleMaintenance::decode(word).map(SystemOperation::AppleMaintenance)
|
||||
})
|
||||
.or_else(|| decode_sdsb(word).map(SystemOperation::Synchronization))
|
||||
.or_else(|| crate::wkdm::decode(word).map(SystemOperation::Compression))
|
||||
}),
|
||||
0x08 | 0x48 | 0x88 | 0xc8 if system_mode => {
|
||||
crate::aarch64::exclusive::decode(word).map(SystemOperation::Exclusive)
|
||||
}
|
||||
0x38 | 0x78 | 0xb8 | 0xf8 if system_mode => {
|
||||
// Reserved sizes and opcodes stay with the ordinary decoder.
|
||||
crate::aarch64::unprivileged::decode(word)
|
||||
.and_then(Result::ok)
|
||||
.map(SystemOperation::Unprivileged)
|
||||
}
|
||||
0x68 | 0x69 | 0xd9 => tag_memory::decode(word).map(SystemOperation::TagMemory),
|
||||
0x91 | 0xd1 if system_mode => match tag_arithmetic::decode(word) {
|
||||
Some(
|
||||
operand @ tag_arithmetic::Operand {
|
||||
kind: tag_arithmetic::Kind::Offset { .. },
|
||||
..
|
||||
},
|
||||
) => Some(SystemOperation::TagOffset(operand)),
|
||||
_ => None,
|
||||
},
|
||||
0x9a => tag_memory::decode(word)
|
||||
.map(SystemOperation::TagMemory)
|
||||
.or_else(|| {
|
||||
if system_mode {
|
||||
decode_checked_pointer(word)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}),
|
||||
0x9b | 0xda if system_mode => decode_checked_pointer(word),
|
||||
0xc0 if system_mode => {
|
||||
DebugStateOperation::decode(word).map(SystemOperation::DebugStateOnly)
|
||||
}
|
||||
0xd4 | 0xd6 => exception::decode(word).map(SystemOperation::Exception),
|
||||
0xd5 => decode_system_class(word, sync, system_mode)?,
|
||||
_ => None,
|
||||
};
|
||||
operation
|
||||
.map(|operation| request(pc, word, operation))
|
||||
.transpose()
|
||||
}
|
||||
|
||||
fn decode_checked_pointer(word: u32) -> Option<SystemOperation> {
|
||||
crate::aarch64::checked_pointer::decode(word).map(SystemOperation::CheckedPointer)
|
||||
}
|
||||
|
||||
/// Hints, barriers, CLREX, system registers, PSTATE and SYS/SYSL share 0xd5.
|
||||
fn decode_system_class(
|
||||
word: u32,
|
||||
sync: Option<synchronization::Operation>,
|
||||
system_mode: bool,
|
||||
) -> Result<Option<SystemOperation>, CompileError> {
|
||||
let terminal_sync = match sync {
|
||||
Some(synchronization::Operation::SendEvent { local }) => {
|
||||
Some(SystemOperation::SendEvent { local })
|
||||
}
|
||||
@@ -249,128 +364,53 @@ pub fn decode_system_instruction(
|
||||
_ => None,
|
||||
};
|
||||
let mut operations = [
|
||||
exception::decode(word).map(SystemOperation::Exception),
|
||||
tag_memory::decode(word).map(SystemOperation::TagMemory),
|
||||
synchronization,
|
||||
terminal_sync,
|
||||
registers::decode(word).map(SystemOperation::Register),
|
||||
registers::decode_pstate_immediate(word).map(SystemOperation::PstateImmediate),
|
||||
]
|
||||
.into_iter()
|
||||
.flatten();
|
||||
let Some(operation) = operations.next() else {
|
||||
return Ok(None);
|
||||
};
|
||||
if operations.next().is_some() {
|
||||
return Err(CompileError::new(
|
||||
crate::CompileErrorKind::AmbiguousSystemInstruction,
|
||||
));
|
||||
}
|
||||
let next_pc = GuestAddress(
|
||||
pc.0.checked_add(INSTRUCTION_BYTES)
|
||||
.ok_or_else(|| CompileError::new(crate::CompileErrorKind::GuestAddressOverflow))?,
|
||||
);
|
||||
Ok(Some(SystemInstruction {
|
||||
instruction_pc: pc,
|
||||
next_pc,
|
||||
word,
|
||||
operation,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Decode the EL1 system instructions the platform completes. NOP, PAuth
|
||||
/// aliases and other hints keep their existing decoding.
|
||||
pub(super) fn decode_el1_system_instruction(
|
||||
pc: GuestAddress,
|
||||
word: u32,
|
||||
) -> Result<Option<SystemInstruction>, CompileError> {
|
||||
if let Some(instruction) = decode_system_instruction(pc, word)? {
|
||||
return Ok(Some(instruction));
|
||||
}
|
||||
let Some(operation @ synchronization::Operation::DataCompletion { .. }) =
|
||||
synchronization::decode(word)
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
let next_pc = GuestAddress(
|
||||
pc.0.checked_add(INSTRUCTION_BYTES)
|
||||
.ok_or_else(|| CompileError::new(crate::CompileErrorKind::GuestAddressOverflow))?,
|
||||
);
|
||||
Ok(Some(SystemInstruction {
|
||||
instruction_pc: pc,
|
||||
next_pc,
|
||||
word,
|
||||
operation: SystemOperation::Synchronization(operation),
|
||||
}))
|
||||
}
|
||||
|
||||
/// Decode every instruction the system-mode profile hands to the runtime: the
|
||||
/// [`decode_el1_system_instruction`] families, SYS/SYSL, and the barriers and
|
||||
/// hints that the ordinary decoder does not own (DSB, SSBB/PSSBB, ESB,
|
||||
/// TSB and unallocated hints), Apple's GXF instructions, SDSB, WKDMC and
|
||||
/// WKDMD, the Debug-state-only MOVT
|
||||
/// GPR/ZT0 forms, and
|
||||
/// the FEAT_CPA pointer arithmetic.
|
||||
/// YIELD, CSDB, SB and DMB stay ordinary and BTI compiles as NOP; PAuth hints belong to the PAuth
|
||||
/// decoder, which the profile consults first.
|
||||
pub fn decode_system_mode_instruction(
|
||||
pc: GuestAddress,
|
||||
word: u32,
|
||||
) -> Result<Option<SystemInstruction>, CompileError> {
|
||||
if let Some(instruction) = decode_system_instruction(pc, word)? {
|
||||
return Ok(Some(instruction));
|
||||
}
|
||||
let operation = if let Some(operation) = GuardedOperation::decode(word) {
|
||||
SystemOperation::Guarded(operation)
|
||||
} else if let Some(operation) = AppleMaintenance::decode(word) {
|
||||
SystemOperation::AppleMaintenance(operation)
|
||||
} else if let Some(operation) = decode_sdsb(word) {
|
||||
SystemOperation::Synchronization(operation)
|
||||
} else if let Some(instruction) = crate::wkdm::decode(word) {
|
||||
SystemOperation::Compression(instruction)
|
||||
} else if let Some(operation) = DebugStateOperation::decode(word) {
|
||||
SystemOperation::DebugStateOnly(operation)
|
||||
} else if let Some(decoded) = crate::aarch64::exclusive::decode(word) {
|
||||
SystemOperation::Exclusive(decoded)
|
||||
} else if let Some(operand) = crate::aarch64::checked_pointer::decode(word) {
|
||||
SystemOperation::CheckedPointer(operand)
|
||||
} else if let Some(
|
||||
operand @ tag_arithmetic::Operand {
|
||||
kind: tag_arithmetic::Kind::Offset { .. },
|
||||
..
|
||||
},
|
||||
) = tag_arithmetic::decode(word)
|
||||
{
|
||||
SystemOperation::TagOffset(operand)
|
||||
} else if let Some(decoded) = crate::aarch64::unprivileged::decode(word) {
|
||||
// Reserved sizes and opcodes stay with the ordinary decoder.
|
||||
match decoded {
|
||||
Ok(operand) => SystemOperation::Unprivileged(operand),
|
||||
Err(Unsupported) => return Ok(None),
|
||||
if let Some(operation) = operations.next() {
|
||||
if operations.next().is_some() {
|
||||
return Err(CompileError::new(
|
||||
crate::CompileErrorKind::AmbiguousSystemInstruction,
|
||||
));
|
||||
}
|
||||
} else if let Some(access) = registers::decode_sys(word) {
|
||||
SystemOperation::Maintenance(access)
|
||||
} else {
|
||||
match synchronization::decode(word) {
|
||||
return Ok(Some(operation));
|
||||
}
|
||||
if !system_mode {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(crate::aarch64::exclusive::decode(word)
|
||||
.map(SystemOperation::Exclusive)
|
||||
.or_else(|| registers::decode_sys(word).map(SystemOperation::Maintenance))
|
||||
.or(match sync {
|
||||
Some(
|
||||
operation @ (synchronization::Operation::DataCompletion { .. }
|
||||
| synchronization::Operation::StoreBypassBarrier { .. }
|
||||
| synchronization::Operation::ErrorSynchronization
|
||||
| synchronization::Operation::TraceSynchronization
|
||||
| synchronization::Operation::OtherHint { .. }),
|
||||
) if word != NOP => SystemOperation::Synchronization(operation),
|
||||
_ => return Ok(None),
|
||||
}
|
||||
};
|
||||
) if word != NOP => Some(SystemOperation::Synchronization(operation)),
|
||||
_ => None,
|
||||
}))
|
||||
}
|
||||
|
||||
fn request(
|
||||
pc: GuestAddress,
|
||||
word: u32,
|
||||
operation: SystemOperation,
|
||||
) -> Result<SystemInstruction, CompileError> {
|
||||
let next_pc = GuestAddress(
|
||||
pc.0.checked_add(INSTRUCTION_BYTES)
|
||||
.ok_or_else(|| CompileError::new(crate::CompileErrorKind::GuestAddressOverflow))?,
|
||||
);
|
||||
Ok(Some(SystemInstruction {
|
||||
Ok(SystemInstruction {
|
||||
instruction_pc: pc,
|
||||
next_pc,
|
||||
word,
|
||||
operation,
|
||||
}))
|
||||
})
|
||||
}
|
||||
|
||||
const NOP: u32 = 0xd503_201f;
|
||||
|
||||
@@ -203,8 +203,16 @@ fn system_mode_claims_cpa_arithmetic_with_its_operands() {
|
||||
fn system_mode_claims_exclusives_and_their_undefined_overlaps() {
|
||||
use crate::aarch64::exclusive::{ConstrainedUndefined, Operand};
|
||||
let pc = GuestAddress(0x1000);
|
||||
// LDXR X1, [X2]; STXR W3, X1, [X2]; LDAXP X1, X4, [X2]; CLREX.
|
||||
for word in [0xc85f_7c41, 0xc803_7c41, 0xc87f_9041, 0xd503_305f] {
|
||||
// LDXRB/H, LDXR W/X, STXR, LDAXP and CLREX.
|
||||
for word in [
|
||||
0x085f_7c41,
|
||||
0x485f_7c41,
|
||||
0x885f_7c41,
|
||||
0xc85f_7c41,
|
||||
0xc803_7c41,
|
||||
0xc87f_9041,
|
||||
0xd503_305f,
|
||||
] {
|
||||
let instruction = decode_system_mode_instruction(pc, word).unwrap().unwrap();
|
||||
assert!(
|
||||
matches!(instruction.operation, SystemOperation::Exclusive(Ok(_))),
|
||||
@@ -231,8 +239,8 @@ fn system_mode_claims_exclusives_and_their_undefined_overlaps() {
|
||||
#[test]
|
||||
fn system_mode_claims_unprivileged_transfers_but_not_reserved_forms() {
|
||||
let pc = GuestAddress(0x1000);
|
||||
// LDTR X1, [X2, #8]; STTR W1, [X2]; LDTRSB W3, [X2].
|
||||
for word in [0xf840_8841, 0xb800_0841, 0x38c0_0843] {
|
||||
// LDTR X1, [X2, #8]; STTR W1, [X2]; LDTRSH and LDTRSB W3, [X2].
|
||||
for word in [0xf840_8841, 0xb800_0841, 0x78c0_0843, 0x38c0_0843] {
|
||||
let instruction = decode_system_mode_instruction(pc, word).unwrap().unwrap();
|
||||
assert!(
|
||||
matches!(instruction.operation, SystemOperation::Unprivileged(_)),
|
||||
|
||||
@@ -1009,8 +1009,19 @@ pub(super) enum Rax {
|
||||
}
|
||||
|
||||
/// What RAX holds after `operation`'s emission by [`emit_instruction`].
|
||||
pub(super) fn rax_after(operation: &Operation) -> Rax {
|
||||
pub(super) fn rax_after(operation: &Operation, pinned: bool) -> Rax {
|
||||
match *operation {
|
||||
Operation::Memory {
|
||||
transfer: MemoryTransfer::Load { .. },
|
||||
data,
|
||||
mode: AddressMode::Offset,
|
||||
..
|
||||
}
|
||||
| Operation::MemoryRegisterOffset(crate::aarch64::register_offset::Operand {
|
||||
transfer: MemoryTransfer::Load { .. },
|
||||
data,
|
||||
..
|
||||
}) if pinned && data != Register::Zero => Rax::Guest(data),
|
||||
Operation::AddSub { flags: true, .. }
|
||||
| Operation::AddSubRegister { flags: true, .. }
|
||||
| Operation::AddSubExtended { flags: true, .. }
|
||||
@@ -1038,18 +1049,26 @@ pub(super) fn rax_after(operation: &Operation) -> Rax {
|
||||
}
|
||||
}
|
||||
|
||||
/// [`load`]'s bytes for a register in code like `like`, but for XZR.
|
||||
pub(super) fn register_load(like: &Code, register: Register) -> Option<Code> {
|
||||
let mut code = like.alike();
|
||||
load(&mut code, register);
|
||||
offset(register).map(|_| code)
|
||||
/// [`load`]'s bytes for a register, but for XZR.
|
||||
pub(super) fn register_load(scratch: &mut Code, register: Register, pinned: bool) -> Option<&[u8]> {
|
||||
offset(register)?;
|
||||
scratch.clear();
|
||||
scratch.set_pinned(pinned);
|
||||
load(scratch, register);
|
||||
Some(scratch)
|
||||
}
|
||||
|
||||
/// [`store`]'s bytes for a register in code like `like`, but for XZR.
|
||||
pub(super) fn register_store(like: &Code, register: Register) -> Option<Code> {
|
||||
let mut code = like.alike();
|
||||
store(&mut code, register);
|
||||
offset(register).map(|_| code)
|
||||
/// [`store`]'s bytes for a register, but for XZR.
|
||||
pub(super) fn register_store(
|
||||
scratch: &mut Code,
|
||||
register: Register,
|
||||
pinned: bool,
|
||||
) -> Option<&[u8]> {
|
||||
offset(register)?;
|
||||
scratch.clear();
|
||||
scratch.set_pinned(pinned);
|
||||
store(scratch, register);
|
||||
Some(scratch)
|
||||
}
|
||||
|
||||
/// `movabs rax,value`.
|
||||
@@ -1127,10 +1146,16 @@ pub(crate) fn emit_instruction(
|
||||
Alu,
|
||||
Gpr::{Rax, Rcx},
|
||||
};
|
||||
if pinned::emit_direct(code, &instruction.operation) {
|
||||
if pinned::emit_direct(code, &instruction.operation, target) {
|
||||
return;
|
||||
}
|
||||
match instruction.operation {
|
||||
Operation::AddSub { .. }
|
||||
| Operation::AddSubRegister { .. }
|
||||
| Operation::LogicalImmediate { .. }
|
||||
| Operation::LogicalRegister { .. } => {
|
||||
unreachable!("common integer emitter handled the operation")
|
||||
}
|
||||
Operation::FloatingPoint(_) => {
|
||||
unreachable!("numerical instructions require block emission")
|
||||
}
|
||||
@@ -1139,7 +1164,9 @@ pub(crate) fn emit_instruction(
|
||||
Operation::Bitfield(operand) => bitfield::emit(code, &operand),
|
||||
Operation::PcRelative(operand) => pc_relative::emit(code, &operand),
|
||||
Operation::ConditionalSelect(operand) => conditional_select::emit(code, &operand, false),
|
||||
Operation::ConditionalCompare(operand) => conditional_select::emit_compare(code, &operand),
|
||||
Operation::ConditionalCompare(operand) => {
|
||||
conditional_select::emit_compare(code, &operand, false)
|
||||
}
|
||||
Operation::Crc(operand) => crc::emit(code, &operand, target),
|
||||
Operation::Flags(operand) => flags::emit(code, &operand),
|
||||
Operation::Synchronization(operand) => system::synchronization::emit(code, &operand)
|
||||
@@ -1246,24 +1273,6 @@ pub(crate) fn emit_instruction(
|
||||
nzcv(code, false);
|
||||
}
|
||||
}
|
||||
Operation::AddSubRegister {
|
||||
width,
|
||||
subtract,
|
||||
flags,
|
||||
destination,
|
||||
left,
|
||||
right,
|
||||
shift,
|
||||
amount,
|
||||
} => {
|
||||
load(code, left);
|
||||
right_operand(code, right, width, shift, amount);
|
||||
add_sub(code, width, subtract);
|
||||
store(code, destination);
|
||||
if flags {
|
||||
nzcv(code, subtract);
|
||||
}
|
||||
}
|
||||
Operation::AddSubExtended {
|
||||
width,
|
||||
subtract,
|
||||
@@ -1276,17 +1285,22 @@ pub(crate) fn emit_instruction(
|
||||
} => {
|
||||
// Read both operands before a possibly overlapping destination/SP write.
|
||||
load(code, left);
|
||||
right_operand(code, right, Width::X64, Shift::Lsl, 0);
|
||||
use asm::Size::{Byte, Dword, Qword, Word};
|
||||
let mut asm = code.asm();
|
||||
match extend {
|
||||
RegisterExtend::Uxtb => asm.movzx(Dword, Rcx, Byte, Rcx),
|
||||
RegisterExtend::Uxth => asm.movzx(Dword, Rcx, Word, Rcx),
|
||||
RegisterExtend::Uxtw => asm.mov(Dword, Rcx, Rcx),
|
||||
RegisterExtend::Sxtb => asm.movsx(Qword, Rcx, Byte, Rcx),
|
||||
RegisterExtend::Sxth => asm.movsx(Qword, Rcx, Word, Rcx),
|
||||
RegisterExtend::Sxtw => asm.movsxd(Rcx, Rcx),
|
||||
RegisterExtend::Uxtx | RegisterExtend::Sxtx => {}
|
||||
if let Some(storage) = asm.guest(right) {
|
||||
match extend {
|
||||
RegisterExtend::Uxtb => asm.movzx(Dword, Rcx, Byte, storage),
|
||||
RegisterExtend::Uxth => asm.movzx(Dword, Rcx, Word, storage),
|
||||
RegisterExtend::Uxtw => asm.mov_load(Dword, Rcx, storage),
|
||||
RegisterExtend::Sxtb => asm.movsx(Qword, Rcx, Byte, storage),
|
||||
RegisterExtend::Sxth => asm.movsx(Qword, Rcx, Word, storage),
|
||||
RegisterExtend::Sxtw => asm.movsxd(Rcx, storage),
|
||||
RegisterExtend::Uxtx | RegisterExtend::Sxtx => {
|
||||
asm.mov_load(Qword, Rcx, storage)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
asm.alu(Alu::Xor, Dword, Rcx, Rcx);
|
||||
}
|
||||
if amount != 0 {
|
||||
asm.shift_imm(asm::ShiftOp::Shl, Qword, Rcx, amount);
|
||||
@@ -1305,47 +1319,6 @@ pub(crate) fn emit_instruction(
|
||||
Operation::Atomic(operand) => atomic::emit(code, &operand, target, checks),
|
||||
Operation::Ordered(operand) => ordered::emit(code, &operand, target, checks),
|
||||
Operation::Prefetch(operand) => prefetch::emit(code, &operand),
|
||||
Operation::LogicalImmediate {
|
||||
width,
|
||||
kind,
|
||||
flags,
|
||||
destination,
|
||||
source,
|
||||
immediate,
|
||||
} => {
|
||||
load(code, source);
|
||||
let mut asm = code.asm();
|
||||
asm.mov_imm64(Rcx, immediate);
|
||||
asm.alu(logical(kind), asm::Size::of(width == Width::X64), Rax, Rcx);
|
||||
store(code, destination); // MOV preserves the logical result flags.
|
||||
if flags {
|
||||
nzcv(code, false); // AND clears CF/OF, matching ARM C/V=0.
|
||||
}
|
||||
}
|
||||
Operation::LogicalRegister {
|
||||
width,
|
||||
kind,
|
||||
invert,
|
||||
flags,
|
||||
destination,
|
||||
left,
|
||||
right,
|
||||
shift,
|
||||
amount,
|
||||
} => {
|
||||
load(code, left);
|
||||
right_operand(code, right, width, shift, amount);
|
||||
let size = asm::Size::of(width == Width::X64);
|
||||
let mut asm = code.asm();
|
||||
if invert {
|
||||
asm.unary(asm::Unary::Not, size, Rcx);
|
||||
}
|
||||
asm.alu(logical(kind), size, Rax, Rcx);
|
||||
store(code, destination);
|
||||
if flags {
|
||||
nzcv(code, false);
|
||||
} // AND clears host CF/OF, matching ARM C/V=0.
|
||||
}
|
||||
Operation::Return => code.asm().ret(),
|
||||
Operation::Exclusive(_) => unreachable!("exclusive requires checked context emitter"),
|
||||
Operation::CheckedPointer(_) => {
|
||||
@@ -1379,26 +1352,6 @@ pub(crate) fn emit_instruction(
|
||||
}
|
||||
store(code, destination);
|
||||
}
|
||||
Operation::AddSub {
|
||||
width,
|
||||
subtract,
|
||||
flags,
|
||||
destination,
|
||||
source,
|
||||
immediate,
|
||||
} => {
|
||||
load(code, source);
|
||||
code.asm().alu_imm32(
|
||||
if subtract { Alu::Sub } else { Alu::Add },
|
||||
asm::Size::of(width == Width::X64),
|
||||
Rax,
|
||||
immediate as i32,
|
||||
);
|
||||
store(code, destination); // MOV leaves arithmetic flags unchanged.
|
||||
if flags {
|
||||
nzcv(code, subtract);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -94,14 +94,6 @@ impl Code {
|
||||
..Self::new()
|
||||
}
|
||||
}
|
||||
/// Empty code of this one's kind.
|
||||
pub(crate) fn alike(&self) -> Self {
|
||||
Self {
|
||||
pinned: self.pinned,
|
||||
constant_time: self.constant_time,
|
||||
..Self::new()
|
||||
}
|
||||
}
|
||||
/// The instructions from here on have `index` in the block's source map.
|
||||
pub(crate) fn set_instruction(&mut self, index: usize) {
|
||||
self.instruction = index;
|
||||
@@ -318,25 +310,33 @@ impl Code {
|
||||
pub(crate) fn remove_instruction(&mut self, range: core::ops::Range<usize>) {
|
||||
assert!(!range.is_empty());
|
||||
let removed = range.len();
|
||||
self.sites.retain_mut(|site| {
|
||||
// Sites and check jumps are appended in code order. Forwarding
|
||||
// removes an instruction near the end, so visit only the suffix.
|
||||
let mut removed_site = None;
|
||||
for (index, site) in self.sites.iter_mut().enumerate().rev() {
|
||||
if site.end <= range.start {
|
||||
true
|
||||
} else if site.start >= range.end {
|
||||
break;
|
||||
}
|
||||
if site.start >= range.end {
|
||||
site.start -= removed;
|
||||
site.end -= removed;
|
||||
true
|
||||
} else {
|
||||
assert!(
|
||||
site.start == range.start && site.end == range.end,
|
||||
"remove one complete faulting instruction"
|
||||
);
|
||||
false
|
||||
removed_site = Some(index);
|
||||
break;
|
||||
}
|
||||
});
|
||||
for (jump, _) in &mut self.failures {
|
||||
if jump.at >= range.end {
|
||||
jump.at -= removed;
|
||||
}
|
||||
if let Some(index) = removed_site {
|
||||
self.sites.remove(index);
|
||||
}
|
||||
for (jump, _) in self.failures.iter_mut().rev() {
|
||||
if jump.at < range.end {
|
||||
break;
|
||||
}
|
||||
jump.at -= removed;
|
||||
}
|
||||
self.bytes.drain(range);
|
||||
self.instructions = self
|
||||
@@ -345,11 +345,12 @@ impl Code {
|
||||
.expect("counted instruction");
|
||||
}
|
||||
/// Remove every byte and instruction.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn clear(&mut self) {
|
||||
self.bytes.clear();
|
||||
self.instructions = 0;
|
||||
self.sites.clear();
|
||||
self.instruction = 0;
|
||||
self.failures.clear();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -97,6 +97,21 @@ impl Asm<'_> {
|
||||
self.legacy(size, None, &[0x0f, 0xa4], source as u8, false, rm.into());
|
||||
self.data(&[amount]);
|
||||
}
|
||||
/// `andn dst, inverted, rm`: `~inverted & rm` (BMI1).
|
||||
pub(crate) fn andn(&mut self, size: Size, destination: Gpr, inverted: Gpr, rm: Rm) {
|
||||
self.vex(
|
||||
Vex {
|
||||
map: Map::M0f38,
|
||||
pp: Pp::None,
|
||||
w: size == Size::Qword,
|
||||
l: false,
|
||||
},
|
||||
0xf2,
|
||||
destination.number(),
|
||||
inverted.number(),
|
||||
rm,
|
||||
);
|
||||
}
|
||||
/// A BMI1 group 17 form (VEX.0F38 F3 /digit) writing `destination`.
|
||||
fn bmi1_group(&mut self, digit: u8, size: Size, destination: Gpr, rm: Rm) {
|
||||
self.vex(
|
||||
|
||||
@@ -90,6 +90,32 @@ fn guest_site_markers_follow_span_copy_split_and_instruction_elision() {
|
||||
assert!(copied.sites().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_an_access_preserves_sites_on_both_sides() {
|
||||
let mut code = Code::new();
|
||||
code.asm().guest_check();
|
||||
let start = code.len();
|
||||
code.asm()
|
||||
.guest_access(|asm| asm.mov_load(Size::Qword, Gpr::Rcx, Mem::base(Gpr::Rax, 0)));
|
||||
let end = code.len();
|
||||
code.asm().guest_check();
|
||||
let before = code.sites()[0];
|
||||
let after = code.sites()[2];
|
||||
code.remove_instruction(start..end);
|
||||
assert_eq!(code.instructions(), 2);
|
||||
assert_eq!(
|
||||
code.sites(),
|
||||
&[
|
||||
before,
|
||||
EmissionSite {
|
||||
start: 2,
|
||||
end: 4,
|
||||
..after
|
||||
}
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lock_prefix_is_part_of_the_guest_operand_site() {
|
||||
let mut code = Code::new();
|
||||
|
||||
@@ -9,7 +9,7 @@ pub(crate) use super::region::ResidentLoopPlan;
|
||||
use super::chain::ExitWord;
|
||||
use crate::{
|
||||
GuestAddress, NativeBlock,
|
||||
aarch64::{Instruction, Operation, Register},
|
||||
aarch64::{Instruction, Operation, Register, Width, integer_math, integer_unary, pc_relative},
|
||||
block::{ExitKind, Terminator},
|
||||
};
|
||||
|
||||
@@ -89,6 +89,31 @@ pub(crate) fn emit_ordinary_for_target(
|
||||
optimize: true,
|
||||
fault_table: false,
|
||||
pinned: false,
|
||||
frame_loop: None,
|
||||
},
|
||||
super::MemoryChecks::DEFAULT,
|
||||
super::NativeSystem::NONE,
|
||||
)
|
||||
.0
|
||||
}
|
||||
|
||||
pub(crate) fn emit_frame_loop(
|
||||
instructions: &[Instruction],
|
||||
terminal: Option<&(GuestAddress, Terminator)>,
|
||||
fallthrough: GuestAddress,
|
||||
target: crate::TargetCpu,
|
||||
entry: GuestAddress,
|
||||
) -> NativeBlock {
|
||||
emit_selected(
|
||||
instructions,
|
||||
terminal,
|
||||
fallthrough,
|
||||
target,
|
||||
RegionPolicy {
|
||||
optimize: true,
|
||||
fault_table: false,
|
||||
pinned: false,
|
||||
frame_loop: Some(entry),
|
||||
},
|
||||
super::MemoryChecks::DEFAULT,
|
||||
super::NativeSystem::NONE,
|
||||
@@ -129,6 +154,7 @@ pub(crate) fn emit_for_target(
|
||||
optimize: false,
|
||||
fault_table: false,
|
||||
pinned: false,
|
||||
frame_loop: None,
|
||||
},
|
||||
checks,
|
||||
super::NativeSystem::NONE,
|
||||
@@ -162,6 +188,7 @@ pub(crate) fn emit_system_mode(
|
||||
optimize: false,
|
||||
fault_table: true,
|
||||
pinned: true,
|
||||
frame_loop: None,
|
||||
},
|
||||
super::MemoryChecks {
|
||||
guest_range: true,
|
||||
@@ -178,6 +205,32 @@ struct RegionPolicy {
|
||||
fault_table: bool,
|
||||
/// Keep guest registers in host registers ([`super::pinned`]).
|
||||
pinned: bool,
|
||||
frame_loop: Option<GuestAddress>,
|
||||
}
|
||||
|
||||
/// The final address of a flagless ADD that overwrites its adjacent ADR(P).
|
||||
pub(super) fn fold_address_pair(
|
||||
first: &Operation,
|
||||
second: &Operation,
|
||||
) -> Option<pc_relative::Operand> {
|
||||
let Operation::PcRelative(address) = *first else {
|
||||
return None;
|
||||
};
|
||||
let Operation::AddSub {
|
||||
width: Width::X64,
|
||||
subtract: false,
|
||||
flags: false,
|
||||
destination: destination @ Register::X(_),
|
||||
source,
|
||||
immediate,
|
||||
} = *second
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
(destination == address.destination && source == destination).then_some(pc_relative::Operand {
|
||||
destination,
|
||||
address: address.address.wrapping_add(u64::from(immediate)),
|
||||
})
|
||||
}
|
||||
|
||||
/// With `fault_table`, region accesses keep dirty values in registers and
|
||||
@@ -195,6 +248,7 @@ fn emit_selected(
|
||||
optimize: optimize_regions,
|
||||
fault_table,
|
||||
pinned,
|
||||
frame_loop,
|
||||
} = regions;
|
||||
let mut fault_recovery = vec![];
|
||||
let mut block = super::Emitted::default();
|
||||
@@ -209,10 +263,12 @@ fn emit_selected(
|
||||
code.set_linked_block(first.0);
|
||||
}
|
||||
code.set_constant_time(target.data_independent_timing());
|
||||
let frame_loop = frame_loop.map(|entry| super::region::FrameLoop::begin(code, entry));
|
||||
let mut fixups = vec![];
|
||||
// The DIT audit covers each instruction's own lowering, not the
|
||||
// register-allocated and clean-load regions' recipes.
|
||||
let optimize_regions = optimize_regions && !target.data_independent_timing();
|
||||
let fuse_pairs = optimize_regions && frame_loop.is_none() && !fault_table && !pinned;
|
||||
// Which accesses check the guest range (`guest_range`), and each
|
||||
// instruction's checks.
|
||||
let ranges = if checks.guest_range && checks.checks_every_access() {
|
||||
@@ -240,6 +296,9 @@ fn emit_selected(
|
||||
// What the last instruction emitted left in registers.
|
||||
let mut after = Held::NOTHING;
|
||||
let mut out_of_line = OutOfLine::default();
|
||||
// Forwarding probes encode one expected MOV at a time. Keep their
|
||||
// bytes in one buffer across the block and its temporary candidates.
|
||||
let mut scratch = Code::default();
|
||||
// Each branch the block runs past: its jump to a side exit, its target
|
||||
// and the instructions up to it.
|
||||
let mut side_exits = vec![];
|
||||
@@ -283,7 +342,7 @@ fn emit_selected(
|
||||
{
|
||||
let count = region.consumed_instructions;
|
||||
let chunk = &instructions[cursor..cursor + count];
|
||||
let baseline = |checks_at: &dyn Fn(usize) -> super::MemoryChecks| {
|
||||
let mut baseline = |checks_at: &dyn Fn(usize) -> super::MemoryChecks| {
|
||||
let mut code = Code::new();
|
||||
let mut map = vec![];
|
||||
let mut fixups = vec![];
|
||||
@@ -292,11 +351,14 @@ fn emit_selected(
|
||||
map.push((instruction.pc, code.len()));
|
||||
after = emit_single(
|
||||
&mut code,
|
||||
&mut scratch,
|
||||
None,
|
||||
instruction,
|
||||
&mut fixups,
|
||||
target,
|
||||
checks_at(cursor + index),
|
||||
SingleOptions {
|
||||
target,
|
||||
checks: checks_at(cursor + index),
|
||||
},
|
||||
after,
|
||||
);
|
||||
}
|
||||
@@ -351,6 +413,58 @@ fn emit_selected(
|
||||
continue;
|
||||
}
|
||||
let instruction = &instructions[cursor];
|
||||
// System chains only enter and poll at block boundaries. Neither
|
||||
// operation has a guest fault site, and an independent entry at ADD
|
||||
// still compiles from its own source. Preserve both retirement rows.
|
||||
if pinned
|
||||
&& !code.constant_time()
|
||||
&& let Some(second) = instructions.get(cursor + 1)
|
||||
&& instruction.pc.0.checked_add(4) == Some(second.pc.0)
|
||||
&& let Some(address) = fold_address_pair(&instruction.operation, &second.operation)
|
||||
{
|
||||
block.source_map.push((instruction.pc, code.len()));
|
||||
code.set_instruction(block.source_map.len() - 1);
|
||||
code.asm().nop();
|
||||
block.source_map.push((second.pc, code.len()));
|
||||
code.set_instruction(block.source_map.len() - 1);
|
||||
super::pinned::emit_pc_relative(code, address);
|
||||
if code.host(address.destination).is_none() {
|
||||
after.rax = super::Rax::Guest(address.destination);
|
||||
}
|
||||
cursor += 2;
|
||||
continue;
|
||||
}
|
||||
// An ordinary block runs the pair together. A truncated block or
|
||||
// an entry at CLZ still emits its original operation.
|
||||
if fuse_pairs
|
||||
&& let Operation::IntegerMath(reverse) = instruction.operation
|
||||
&& let integer_math::Kind::ReverseBits { width } = reverse.kind
|
||||
&& let Some(second) = instructions.get(cursor + 1)
|
||||
&& let Operation::IntegerMath(count) = second.operation
|
||||
&& count.kind == (integer_math::Kind::LeadingZeros { width })
|
||||
&& reverse.destination != Register::Zero
|
||||
&& count.left == reverse.destination
|
||||
&& count.destination == reverse.destination
|
||||
&& instruction.pc.0.checked_add(4) == Some(second.pc.0)
|
||||
{
|
||||
block.source_map.push((instruction.pc, code.len()));
|
||||
code.set_instruction(block.source_map.len() - 1);
|
||||
code.asm().nop();
|
||||
block.source_map.push((second.pc, code.len()));
|
||||
code.set_instruction(block.source_map.len() - 1);
|
||||
super::integer_unary::emit(
|
||||
code,
|
||||
&integer_unary::Operand {
|
||||
kind: integer_unary::Kind::TrailingZeros,
|
||||
width,
|
||||
destination: count.destination,
|
||||
source: reverse.left,
|
||||
},
|
||||
target,
|
||||
);
|
||||
cursor += 2;
|
||||
continue;
|
||||
}
|
||||
block.source_map.push((instruction.pc, code.len()));
|
||||
code.set_instruction(block.source_map.len() - 1);
|
||||
if let Some(target) = instruction.operation.conditional_target() {
|
||||
@@ -367,11 +481,14 @@ fn emit_selected(
|
||||
}
|
||||
after = emit_single(
|
||||
code,
|
||||
&mut scratch,
|
||||
Some(&mut out_of_line),
|
||||
instruction,
|
||||
&mut fixups,
|
||||
target,
|
||||
checks_at(cursor),
|
||||
SingleOptions {
|
||||
target,
|
||||
checks: checks_at(cursor),
|
||||
},
|
||||
held,
|
||||
);
|
||||
if frame_bound {
|
||||
@@ -385,18 +502,30 @@ fn emit_selected(
|
||||
"ordinary instruction prefix cannot branch"
|
||||
);
|
||||
out_of_line.place(code);
|
||||
emit_terminal(
|
||||
code,
|
||||
&mut block.source_map,
|
||||
terminal,
|
||||
TerminalContext {
|
||||
fallthrough,
|
||||
native,
|
||||
checks,
|
||||
rax: after.rax,
|
||||
target,
|
||||
},
|
||||
);
|
||||
if let Some(frame_loop) = frame_loop {
|
||||
let Some((pc, Terminator::Branch(operation))) = terminal else {
|
||||
unreachable!("a frame loop has a validated direct branch")
|
||||
};
|
||||
debug_assert!(side_exits.is_empty());
|
||||
block.source_map[0].1 = 0;
|
||||
block.source_map.push((*pc, code.len()));
|
||||
code.set_instruction(block.source_map.len() - 1);
|
||||
let taken = branch_condition(code, operation, after.rax);
|
||||
frame_loop.finish(code, taken, fallthrough);
|
||||
} else {
|
||||
emit_terminal(
|
||||
code,
|
||||
&mut block.source_map,
|
||||
terminal,
|
||||
TerminalContext {
|
||||
fallthrough,
|
||||
native,
|
||||
checks,
|
||||
rax: after.rax,
|
||||
target,
|
||||
},
|
||||
);
|
||||
}
|
||||
// After the terminal, whose direct exits end the code before them.
|
||||
let instructions_run = block.source_map.len();
|
||||
for (jump, target, run) in side_exits {
|
||||
@@ -432,6 +561,11 @@ impl Held {
|
||||
};
|
||||
}
|
||||
|
||||
struct SingleOptions {
|
||||
target: crate::TargetCpu,
|
||||
checks: super::MemoryChecks,
|
||||
}
|
||||
|
||||
/// One instruction outside the regions, after an emission that left
|
||||
/// `held`; returns what it leaves. An instruction that first loads the
|
||||
/// register the previous one just stored from RAX finds it there, and one
|
||||
@@ -439,13 +573,14 @@ impl Held {
|
||||
/// `out_of_line`, numerical instructions move their slow paths there.
|
||||
fn emit_single(
|
||||
code: &mut Code,
|
||||
scratch: &mut Code,
|
||||
out_of_line: Option<&mut OutOfLine>,
|
||||
instruction: &Instruction,
|
||||
fixups: &mut Vec<(GuestAddress, GuestAddress, usize)>,
|
||||
target: crate::TargetCpu,
|
||||
checks: super::MemoryChecks,
|
||||
options: SingleOptions,
|
||||
held: Held,
|
||||
) -> Held {
|
||||
let SingleOptions { target, checks } = options;
|
||||
if let Operation::FloatingPoint(operand) = &instruction.operation {
|
||||
let Some(out_of_line) = out_of_line else {
|
||||
super::simd::emit_numerical(code, operand, instruction.pc, target);
|
||||
@@ -469,8 +604,8 @@ fn emit_single(
|
||||
super::simd::emit_after(code, operand, target, checks, held.xmm0);
|
||||
// A first load of the vector XMM0 holds changes nothing.
|
||||
if let Some(vector) = held.xmm0 {
|
||||
let load = super::simd::xmm0_load(vector);
|
||||
if code[start..].starts_with(&load) && code.len() > start + load.len() {
|
||||
let load = super::simd::xmm0_load(scratch, vector);
|
||||
if code[start..].starts_with(load) && code.len() > start + load.len() {
|
||||
code.remove_instruction(start..start + load.len());
|
||||
}
|
||||
}
|
||||
@@ -481,29 +616,65 @@ fn emit_single(
|
||||
&& matches!(
|
||||
operand.otherwise,
|
||||
crate::aarch64::conditional_select::Otherwise::Unchanged
|
||||
| crate::aarch64::conditional_select::Otherwise::Increment
|
||||
| crate::aarch64::conditional_select::Otherwise::Invert
|
||||
)
|
||||
{
|
||||
// The preceding pinned capture preserves the host flags. MOV and
|
||||
// NOT keep them live while preparing these select operands.
|
||||
// The preceding pinned capture preserves the host flags. The
|
||||
// select keeps them live while preparing its operands.
|
||||
super::conditional_select::emit(code, operand, true);
|
||||
} else if let Operation::ConditionalCompare(operand) = &instruction.operation
|
||||
&& code.is_pinned()
|
||||
&& !code.constant_time()
|
||||
&& held.rax == super::Rax::Nzcv
|
||||
{
|
||||
super::conditional_select::emit_compare(code, operand, true);
|
||||
} else if let super::Rax::Guest(register) = held.rax
|
||||
&& let Operation::AddSub {
|
||||
width,
|
||||
subtract: true,
|
||||
flags: true,
|
||||
destination: Register::Zero,
|
||||
source,
|
||||
immediate,
|
||||
} = instruction.operation
|
||||
&& source == register
|
||||
{
|
||||
super::pinned::compare_held_immediate(code, width, immediate);
|
||||
} else if code.is_pinned()
|
||||
&& !code.constant_time()
|
||||
&& let super::Rax::Guest(register) = held.rax
|
||||
&& let Operation::AddSubRegister {
|
||||
width,
|
||||
subtract: true,
|
||||
flags: true,
|
||||
destination: Register::Zero,
|
||||
left: left @ Register::X(_),
|
||||
right,
|
||||
amount: 0,
|
||||
..
|
||||
} = instruction.operation
|
||||
&& right == register
|
||||
&& left != right
|
||||
{
|
||||
super::pinned::compare_held_right(code, width, left);
|
||||
} else {
|
||||
super::emit_instruction(code, instruction, fixups, target, checks);
|
||||
}
|
||||
// The instruction keeps a non-empty native range for its source map.
|
||||
if let super::Rax::Guest(register) = held.rax
|
||||
&& let Some(load) = super::register_load(code, register)
|
||||
&& code[start..].starts_with(&load)
|
||||
&& let Some(load) = super::register_load(scratch, register, code.is_pinned())
|
||||
&& code[start..].starts_with(load)
|
||||
&& code.len() > start + load.len()
|
||||
{
|
||||
code.remove_instruction(start..start + load.len());
|
||||
}
|
||||
let rax = match super::rax_after(&instruction.operation) {
|
||||
let rax = match super::rax_after(&instruction.operation, code.is_pinned()) {
|
||||
// A direct form may leave the result only in its host register.
|
||||
super::Rax::Guest(register)
|
||||
if code.is_pinned()
|
||||
&& !super::register_store(code, register)
|
||||
.is_some_and(|store| code.ends_with(&store)) =>
|
||||
&& !super::register_store(scratch, register, true)
|
||||
.is_some_and(|store| code.ends_with(store)) =>
|
||||
{
|
||||
super::Rax::Unknown
|
||||
}
|
||||
@@ -512,11 +683,13 @@ fn emit_single(
|
||||
debug_assert!(match rax {
|
||||
super::Rax::Unknown => true,
|
||||
super::Rax::Nzcv => code.ends_with(&nzcv_store(code.is_pinned())),
|
||||
super::Rax::Guest(register) =>
|
||||
super::register_store(code, register).is_some_and(|store| code.ends_with(&store)),
|
||||
super::Rax::Guest(register) => super::register_store(scratch, register, code.is_pinned())
|
||||
.is_some_and(|store| code.ends_with(store)),
|
||||
});
|
||||
let xmm0 = match &instruction.operation {
|
||||
Operation::Simd(operand) => super::simd::xmm0_after(operand, &code[start..], held.xmm0),
|
||||
Operation::Simd(operand) => {
|
||||
super::simd::xmm0_after(scratch, operand, &code[start..], held.xmm0)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
Held { rax, xmm0 }
|
||||
|
||||
@@ -4,18 +4,114 @@ use crate::block::{SynchronousTrap, TrapKind};
|
||||
use alloc::vec;
|
||||
use alloc::vec::Vec;
|
||||
|
||||
#[test]
|
||||
fn system_address_pair_keeps_source_rows_and_the_following_fault_boundary() {
|
||||
use crate::{Lifter, TargetCpu, aarch64::Decoder, block::RecoverySiteKind};
|
||||
|
||||
let entry = GuestAddress(0x1030);
|
||||
let add_pc = GuestAddress(entry.0 + 4);
|
||||
let load_pc = GuestAddress(entry.0 + 8);
|
||||
let fallthrough = GuestAddress(entry.0 + 12);
|
||||
let checks = super::super::MemoryChecks::DEFAULT;
|
||||
for (register, opcode) in [(0, [0x49, 0xbf]), (20, [0x48, 0xb8])] {
|
||||
let instructions = [
|
||||
Decoder.lift(entry, 0xb000_0000 | register).unwrap(),
|
||||
Decoder
|
||||
.lift(add_pc, 0x9140_2000 | register << 5 | register)
|
||||
.unwrap(),
|
||||
Decoder.lift(load_pc, 0xf940_0002 | register << 5).unwrap(),
|
||||
]; // adrp; add #8, lsl #12; ldr x2,[register]
|
||||
let system = |input: &[Instruction], next, target| {
|
||||
emit_system_mode(
|
||||
input,
|
||||
None,
|
||||
next,
|
||||
target,
|
||||
checks,
|
||||
super::super::NativeSystem::NONE,
|
||||
)
|
||||
};
|
||||
let (native, recovery) = system(&instructions, fallthrough, TargetCpu::Baseline);
|
||||
let (dit, _) = system(
|
||||
&instructions,
|
||||
fallthrough,
|
||||
TargetCpu::Baseline.with_data_independent_timing(),
|
||||
);
|
||||
let expected_end = if register == 0 { 11 } else { 18 };
|
||||
assert_eq!(
|
||||
native.source_map,
|
||||
[(entry, 0), (add_pc, 1), (load_pc, expected_end)]
|
||||
);
|
||||
assert_eq!(native.x86_64_code[0], 0x90);
|
||||
assert_eq!(native.x86_64_code[1..3], opcode);
|
||||
assert_eq!(native.x86_64_code[3..11], 0xa000_u64.to_le_bytes());
|
||||
assert!(dit.source_map[1].1 > 1);
|
||||
assert!(native.x86_64_code.len() < dit.x86_64_code.len());
|
||||
assert!(!recovery.is_empty());
|
||||
assert!(recovery.iter().all(|row| row.start >= expected_end));
|
||||
let access = recovery
|
||||
.iter()
|
||||
.find(|row| row.site.kind() == RecoverySiteKind::GuestAccess)
|
||||
.unwrap();
|
||||
assert_eq!(access.retirement.instruction_pc(), load_pc);
|
||||
assert_eq!(access.retirement.retired_before(), 2);
|
||||
|
||||
let (truncated, _) = system(&instructions[..1], add_pc, TargetCpu::Baseline);
|
||||
assert_eq!(truncated.source_map, [(entry, 0)]);
|
||||
assert_eq!(truncated.x86_64_code[2..10], 0x2000_u64.to_le_bytes());
|
||||
let (standalone, _) = system(&instructions[1..2], load_pc, TargetCpu::Baseline);
|
||||
assert_eq!(standalone.source_map, [(add_pc, 0)]);
|
||||
assert_ne!(standalone.x86_64_code[0], 0x90);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn system_address_pair_requires_an_adjacent_flagless_x64_overwrite() {
|
||||
use crate::{Lifter, TargetCpu, aarch64::Decoder};
|
||||
|
||||
let entry = GuestAddress(0x1000);
|
||||
let first = Decoder.lift(entry, 0xb000_0000).unwrap();
|
||||
for (pc, word) in [
|
||||
(0x1008, 0x9100_2000), // Gap.
|
||||
(0x1004, 0x1100_2000), // W destination.
|
||||
(0x1004, 0xb100_2000), // Flag-setting ADD.
|
||||
(0x1004, 0xd100_2000), // SUB.
|
||||
(0x1004, 0x9100_2001), // Different destination.
|
||||
(0x1004, 0x9100_2020), // Different source.
|
||||
] {
|
||||
let second = Decoder.lift(GuestAddress(pc), word).unwrap();
|
||||
let (native, _) = emit_system_mode(
|
||||
&[first.clone(), second],
|
||||
None,
|
||||
GuestAddress(pc + 4),
|
||||
TargetCpu::Baseline,
|
||||
super::super::MemoryChecks::DEFAULT,
|
||||
super::super::NativeSystem::NONE,
|
||||
);
|
||||
assert_eq!(native.source_map, [(entry, 0), (GuestAddress(pc), 10)]);
|
||||
assert_eq!(native.x86_64_code[2..10], 0x2000_u64.to_le_bytes());
|
||||
}
|
||||
}
|
||||
|
||||
/// A reload removed before a check takes the check's jump along.
|
||||
#[test]
|
||||
fn removed_instructions_move_the_check_failures_after_them() {
|
||||
use super::super::asm::{Cond, Gpr, Mem, Size};
|
||||
let mut code = Code::new();
|
||||
code.check_failure(Cond::E);
|
||||
let start = code.len();
|
||||
code.asm()
|
||||
.mov_load(Size::Qword, Gpr::Rax, Mem::base(Gpr::Rdi, 0));
|
||||
let load = code.len();
|
||||
let end = code.len();
|
||||
code.check_failure(Cond::Ne);
|
||||
code.remove_instruction(0..load);
|
||||
code.remove_instruction(start..end);
|
||||
code.place_failures();
|
||||
assert_eq!(code[..], [0x0f, 0x85, 0, 0, 0, 0, 0x0f, 0x0b]);
|
||||
assert_eq!(
|
||||
code[..],
|
||||
[
|
||||
0x0f, 0x84, 6, 0, 0, 0, 0x0f, 0x85, 2, 0, 0, 0, 0x0f, 0x0b, 0x0f, 0x0b
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/// A conditional exit's branch skips its fallthrough exit, and each of
|
||||
@@ -37,6 +133,122 @@ fn conditional_exits_branch_over_the_fallthrough_exit() {
|
||||
assert_eq!(code.instructions(), 15);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hosted_trailing_zero_pair_preserves_instruction_boundaries() {
|
||||
use crate::{Lifter, TargetCpu, aarch64::Decoder};
|
||||
|
||||
let entry = GuestAddress(0x1000);
|
||||
for words in [[0xdac0_0020_u32, 0xdac0_1000], [0x5ac0_0020, 0x5ac0_1000]] {
|
||||
let instructions = [
|
||||
Decoder.lift(entry, words[0]).unwrap(),
|
||||
Decoder.lift(GuestAddress(entry.0 + 4), words[1]).unwrap(),
|
||||
];
|
||||
let end = GuestAddress(entry.0 + 8);
|
||||
for target in [TargetCpu::Baseline, TargetCpu::Baseline.with_bmi1()] {
|
||||
let ordinary = emit_ordinary_for_target(&instructions, None, end, target);
|
||||
let separate = emit_for_target(
|
||||
&instructions,
|
||||
None,
|
||||
end,
|
||||
target,
|
||||
super::super::MemoryChecks::DEFAULT,
|
||||
);
|
||||
assert_eq!(ordinary.source_map, [(entry, 0), (instructions[1].pc, 1)]);
|
||||
assert_eq!(ordinary.x86_64_code[0], 0x90);
|
||||
assert!(ordinary.x86_64_code.len() < separate.x86_64_code.len());
|
||||
let tzcnt = if words[0] >> 31 == 1 {
|
||||
&[0xf3, 0x48, 0x0f, 0xbc][..]
|
||||
} else {
|
||||
&[0xf3, 0x0f, 0xbc][..]
|
||||
};
|
||||
assert_eq!(
|
||||
ordinary
|
||||
.x86_64_code
|
||||
.windows(tzcnt.len())
|
||||
.any(|window| window == tzcnt),
|
||||
target.supports(TargetCpu::Bmi1)
|
||||
);
|
||||
}
|
||||
let dit = TargetCpu::Baseline.with_data_independent_timing();
|
||||
assert_eq!(
|
||||
emit_ordinary_for_target(&instructions, None, end, dit).x86_64_code,
|
||||
emit_for_target(
|
||||
&instructions,
|
||||
None,
|
||||
end,
|
||||
dit,
|
||||
super::super::MemoryChecks::DEFAULT,
|
||||
)
|
||||
.x86_64_code
|
||||
);
|
||||
let (system, _) = emit_system_mode(
|
||||
&instructions,
|
||||
None,
|
||||
end,
|
||||
TargetCpu::Baseline,
|
||||
super::super::MemoryChecks::DEFAULT,
|
||||
super::super::NativeSystem::NONE,
|
||||
);
|
||||
assert!(system.source_map[1].1 > 1);
|
||||
}
|
||||
|
||||
// A different width, source or destination leaves the original pair.
|
||||
let first = Decoder.lift(entry, 0xdac0_0020).unwrap();
|
||||
for word in [0x5ac0_1000, 0xdac0_1020, 0xdac0_1001] {
|
||||
let second = Decoder.lift(GuestAddress(entry.0 + 4), word).unwrap();
|
||||
let instructions = [first.clone(), second];
|
||||
assert_eq!(
|
||||
emit_ordinary_for_target(
|
||||
&instructions,
|
||||
None,
|
||||
GuestAddress(entry.0 + 8),
|
||||
TargetCpu::Baseline
|
||||
)
|
||||
.x86_64_code,
|
||||
emit(&instructions, None, GuestAddress(entry.0 + 8)).x86_64_code
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))]
|
||||
#[test]
|
||||
fn hosted_trailing_zero_pair_matches_both_scalar_widths_and_aliases() {
|
||||
use crate::{GuestState, Lifter, TargetCpu, aarch64::Decoder, x86_64::native};
|
||||
|
||||
let entry = GuestAddress(0x1000);
|
||||
let end = GuestAddress(entry.0 + 8);
|
||||
for (reverse, count) in [(0xdac0_0000, 0xdac0_1000), (0x5ac0_0000, 0x5ac0_1000)] {
|
||||
for source in [0, 1, 31] {
|
||||
let instructions = [
|
||||
Decoder.lift(entry, reverse | source << 5).unwrap(),
|
||||
Decoder.lift(GuestAddress(entry.0 + 4), count).unwrap(),
|
||||
];
|
||||
for target in [TargetCpu::Baseline, TargetCpu::Baseline.with_bmi1()] {
|
||||
if !TargetCpu::detect().supports(target) {
|
||||
continue;
|
||||
}
|
||||
let block = emit_ordinary_for_target(&instructions, None, end, target);
|
||||
assert_eq!(block.source_map[1].1, 1);
|
||||
for input in [0, 1, 0x1234_5678_0000_0000, 1 << 31, 1 << 63, u64::MAX] {
|
||||
let mut state = GuestState::default();
|
||||
state.x[0] = input;
|
||||
state.x[1] = input;
|
||||
state.nzcv = 0xa000_0000;
|
||||
let mut expected = state.clone();
|
||||
let input = if source == 31 { 0 } else { input };
|
||||
expected.x[0] = u64::from(if reverse >> 31 == 1 {
|
||||
input.trailing_zeros()
|
||||
} else {
|
||||
(input as u32).trailing_zeros()
|
||||
});
|
||||
assert_eq!(native::run(&block.x86_64_code, &mut state), end.0);
|
||||
assert_eq!(state, expected);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// add x10, x10, #4; cmp x10, #0x600; b.ne: the CMP takes X10 from
|
||||
/// RAX where the ADD stored it, and the branch tests the NZCV word the
|
||||
/// CMP left in EAX, so neither reloads from the frame.
|
||||
@@ -63,7 +275,8 @@ fn values_left_in_rax_are_not_reloaded() {
|
||||
condition: 1,
|
||||
}),
|
||||
);
|
||||
let code = emit(&instructions, Some(&terminal), GuestAddress(branch.0 + 4)).x86_64_code;
|
||||
let native = emit(&instructions, Some(&terminal), GuestAddress(branch.0 + 4));
|
||||
let code = &native.x86_64_code;
|
||||
let count = |pattern: &[u8]| {
|
||||
code.windows(pattern.len())
|
||||
.filter(|w| *w == pattern)
|
||||
@@ -71,6 +284,205 @@ fn values_left_in_rax_are_not_reloaded() {
|
||||
};
|
||||
assert_eq!(count(&LOAD_X10), 1);
|
||||
assert_eq!(count(&LOAD_NZCV), 0);
|
||||
let compare = native.source_map[1].1;
|
||||
assert_eq!(&code[compare..compare + 3], &[0x48, 0x81, 0xf8]); // CMP RAX,imm32.
|
||||
}
|
||||
|
||||
#[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))]
|
||||
#[test]
|
||||
fn pinned_compare_reuses_the_preceding_unshifted_right_operand() {
|
||||
use crate::{GuestState, Lifter, TargetCpu, aarch64::Decoder, x86_64::native};
|
||||
|
||||
let pc = GuestAddress(0x1000);
|
||||
let compare = GuestAddress(pc.0 + 4);
|
||||
let branch = GuestAddress(pc.0 + 8);
|
||||
let next = GuestAddress(pc.0 + 12);
|
||||
let terminal = (
|
||||
branch,
|
||||
Terminator::Branch(Operation::BranchCondition {
|
||||
target: pc,
|
||||
condition: 3, // LO: borrow.
|
||||
}),
|
||||
);
|
||||
for (sf, mask) in [(0, u64::from(u32::MAX)), (1 << 31, u64::MAX)] {
|
||||
for left in [1, 9] {
|
||||
let instructions = [
|
||||
Decoder.lift(pc, sf | 0x1100_0694).unwrap(), // ADD R20,R20,#1
|
||||
Decoder.lift(compare, sf | 0x6b14_001f | left << 5).unwrap(), // CMP Rleft,R20
|
||||
];
|
||||
let system = |input: &[Instruction], target| {
|
||||
emit_system_mode(
|
||||
input,
|
||||
Some(&terminal),
|
||||
next,
|
||||
target,
|
||||
super::super::MemoryChecks::DEFAULT,
|
||||
super::super::NativeSystem::NONE,
|
||||
)
|
||||
.0
|
||||
};
|
||||
let native = system(&instructions, TargetCpu::Baseline);
|
||||
let dit = system(
|
||||
&instructions,
|
||||
TargetCpu::Baseline.with_data_independent_timing(),
|
||||
);
|
||||
let standalone = system(&instructions[1..], TargetCpu::Baseline);
|
||||
let code = &native.x86_64_code;
|
||||
let at = native.source_map[1].1;
|
||||
let opcode = if sf == 0 { at } else { at + 1 };
|
||||
let cmp = if left == 1 {
|
||||
&[0x39, 0xc5][..] // CMP EBP/RBP,EAX/RAX.
|
||||
} else {
|
||||
&[0x39, 0x47, 72][..] // CMP [frame+X9],EAX/RAX.
|
||||
};
|
||||
assert_eq!(&code[opcode..opcode + cmp.len()], cmp);
|
||||
assert!(
|
||||
!dit.x86_64_code[dit.source_map[1].1..].starts_with(&code[at..opcode + cmp.len()])
|
||||
);
|
||||
assert!(
|
||||
!standalone
|
||||
.x86_64_code
|
||||
.starts_with(&code[at..opcode + cmp.len()])
|
||||
);
|
||||
assert_eq!(
|
||||
native
|
||||
.source_map
|
||||
.iter()
|
||||
.map(|row| row.0)
|
||||
.collect::<Vec<_>>(),
|
||||
[pc, compare, branch]
|
||||
);
|
||||
|
||||
let entered = super::super::pinned::entered(code);
|
||||
let sign = (mask >> 1) + 1;
|
||||
for (a, before) in [
|
||||
(1, 0),
|
||||
(0, 0),
|
||||
(mask, 0),
|
||||
(sign - 1, mask - 1),
|
||||
(0, sign - 1),
|
||||
] {
|
||||
let mut state = GuestState::default();
|
||||
state.x[left as usize] = a;
|
||||
state.x[20] = before | !mask;
|
||||
let mut expected = state.clone();
|
||||
let b = before.wrapping_add(1) & mask;
|
||||
let difference = a.wrapping_sub(b) & mask;
|
||||
expected.x[20] = b;
|
||||
expected.nzcv = (u32::from(difference & sign != 0) << 31)
|
||||
| (u32::from(difference == 0) << 30)
|
||||
| (u32::from(a >= b) << 29)
|
||||
| (u32::from((a ^ b) & (a ^ difference) & sign != 0) << 28);
|
||||
assert_eq!(
|
||||
native::run(&entered, &mut state),
|
||||
if a < b { pc.0 } else { next.0 }
|
||||
);
|
||||
assert_eq!(state, expected);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ordinary_integer_operations_read_frame_operands_directly() {
|
||||
use crate::{Lifter, aarch64::Decoder};
|
||||
let pc = GuestAddress(0x1000);
|
||||
// MOV W5,W1; AND W1,W1,W14; CMP W13,W1; CMP W13,#7; ADD X6,X4,W12,SXTW.
|
||||
let instructions: Vec<_> = [
|
||||
0x2a01_03e5_u32,
|
||||
0x0a0e_0021,
|
||||
0x6b01_01bf,
|
||||
0x7100_1dbf,
|
||||
0x8b2c_c086,
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(index, word)| {
|
||||
Decoder
|
||||
.lift(GuestAddress(pc.0 + 4 * index as u64), word)
|
||||
.unwrap()
|
||||
})
|
||||
.collect();
|
||||
let native = emit(&instructions, None, GuestAddress(0x1014));
|
||||
let code = &native.x86_64_code;
|
||||
let map = &native.source_map;
|
||||
assert_eq!(
|
||||
&code[..map[1].1],
|
||||
&[0x8b, 0x87, 8, 0, 0, 0, 0x48, 0x89, 0x87, 40, 0, 0, 0],
|
||||
); // MOV EAX,[RDI+8]; MOV [RDI+40],RAX.
|
||||
assert_eq!(
|
||||
&code[map[1].1 + 7..map[1].1 + 13],
|
||||
&[0x23, 0x87, 112, 0, 0, 0]
|
||||
);
|
||||
assert_eq!(
|
||||
&code[map[2].1 + 7..map[2].1 + 13],
|
||||
&[0x3b, 0x87, 8, 0, 0, 0]
|
||||
);
|
||||
assert_eq!(
|
||||
&code[map[3].1..map[3].1 + 7],
|
||||
&[0x83, 0xbf, 104, 0, 0, 0, 7]
|
||||
);
|
||||
assert_eq!(
|
||||
&code[map[4].1 + 7..map[4].1 + 14],
|
||||
&[0x48, 0x63, 0x8f, 96, 0, 0, 0],
|
||||
); // MOVSXD RCX,[RDI+96].
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pinned_scalar_loads_forward_through_the_block() {
|
||||
use crate::{Lifter, aarch64::Decoder, block::RecoverySiteKind};
|
||||
const FRAME_LOAD: [u8; 4] = [0x48, 0x8b, 0x47, 0x50];
|
||||
let pc = GuestAddress(0x1000);
|
||||
let second = GuestAddress(0x1004);
|
||||
let branch = GuestAddress(0x1008);
|
||||
// LDR X10,[X10]; LDR X10,[X10,X2]; CBZ X10,entry.
|
||||
let instructions = [
|
||||
Decoder.lift(pc, 0xf940_014a).unwrap(),
|
||||
Decoder.lift(second, 0xf862_694a).unwrap(),
|
||||
];
|
||||
let terminal = (
|
||||
branch,
|
||||
Terminator::Branch(Operation::BranchZero {
|
||||
source: Register::X(10),
|
||||
width: crate::aarch64::Width::X64,
|
||||
nonzero: false,
|
||||
target: pc,
|
||||
}),
|
||||
);
|
||||
let (native, recovery) = emit_system_mode(
|
||||
&instructions,
|
||||
Some(&terminal),
|
||||
GuestAddress(0x100c),
|
||||
crate::TargetCpu::Baseline,
|
||||
super::super::MemoryChecks::DEFAULT,
|
||||
super::super::NativeSystem::NONE,
|
||||
);
|
||||
let code = &native.x86_64_code;
|
||||
assert_eq!(native.source_map.len(), 3);
|
||||
let [(pc1, at1), (pc2, at2), (pc3, at3)] = native.source_map.as_slice() else {
|
||||
unreachable!()
|
||||
};
|
||||
assert_eq!([*pc1, *pc2, *pc3], [pc, second, branch]);
|
||||
assert!(at1 < at2 && at2 < at3);
|
||||
assert_eq!(
|
||||
code.windows(FRAME_LOAD.len())
|
||||
.filter(|w| *w == FRAME_LOAD)
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
assert_eq!(&code[*at3..*at3 + 3], &[0x48, 0x85, 0xc0]); // TEST RAX,RAX
|
||||
let accesses: Vec<_> = recovery
|
||||
.iter()
|
||||
.filter(|row| row.site.kind() == RecoverySiteKind::GuestAccess)
|
||||
.collect();
|
||||
assert_eq!(accesses.len(), 2);
|
||||
for (index, access) in accesses.into_iter().enumerate() {
|
||||
let (pc, start) = native.source_map[index];
|
||||
assert!(start <= access.start && access.end <= native.source_map[index + 1].1);
|
||||
let position = access.retirement.position().unwrap();
|
||||
assert_eq!(position.pc, pc);
|
||||
assert_eq!(usize::from(position.retired_instructions), index);
|
||||
}
|
||||
}
|
||||
|
||||
/// ldr x0, [sp, #8]; ldr x1, [sp, #16]; sub sp, sp, #8; ldr x2, [sp]:
|
||||
@@ -753,3 +1165,160 @@ fn pinned_select_consumes_the_preceding_compare_flags() {
|
||||
assert_eq!(state.nzcv, nzcv);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))]
|
||||
#[test]
|
||||
fn pinned_conditional_increment_consumes_the_preceding_compare_flags() {
|
||||
use crate::{
|
||||
GuestState,
|
||||
block::{BlockProfile, Features},
|
||||
x86_64::{native, pinned},
|
||||
};
|
||||
// CMP X0, #1; CSET W2, EQ; RET.
|
||||
let cset = 0x1a9f_17e2;
|
||||
// CMP X0, #1; CSINC W8, W2, W8, HI; RET.
|
||||
let csinc = 0x1a88_8448;
|
||||
for (select, prefix) in [
|
||||
(cset, &[0x0f, 0x94, 0xc0][..]), // SETE AL
|
||||
(csinc, &[0x44, 0x8b, 0xc6, 0x45, 0x8d, 0x40, 0x01, 0xf5]), // MOV, LEA, CMC
|
||||
] {
|
||||
let source: Vec<_> = [0xf100_041fu32, select, 0xd65f_03c0]
|
||||
.into_iter()
|
||||
.flat_map(u32::to_le_bytes)
|
||||
.collect();
|
||||
let code = crate::testing::block_with(
|
||||
&source,
|
||||
GuestAddress(0x1000),
|
||||
BlockProfile::new(Features::SYSTEM_MODE),
|
||||
)
|
||||
.unwrap()
|
||||
.native;
|
||||
let selected = &code.x86_64_code[code.source_map[1].1..code.source_map[2].1];
|
||||
assert!(selected.starts_with(prefix), "{selected:02x?}");
|
||||
let entry = pinned::entered(&code.x86_64_code);
|
||||
for (compared, equal, higher, nzcv) in [
|
||||
(0, 0, false, 0x8000_0000),
|
||||
(1, 1, false, 0x6000_0000),
|
||||
(2, 0, true, 0x2000_0000),
|
||||
] {
|
||||
let mut state = GuestState::default();
|
||||
state.x[0] = compared;
|
||||
state.x[2] = 0xaabb_ccdd_0000_0016;
|
||||
state.x[8] = u64::MAX;
|
||||
state.x[30] = 0x2000;
|
||||
let mut expected = state.x;
|
||||
if select == cset {
|
||||
expected[2] = equal;
|
||||
} else {
|
||||
expected[8] = if higher { 22 } else { 0 };
|
||||
}
|
||||
assert_eq!(native::run(&entry, &mut state), 0x2000);
|
||||
assert_eq!(state.x, expected);
|
||||
assert_eq!(state.nzcv, nzcv);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))]
|
||||
#[test]
|
||||
fn pinned_conditional_compare_consumes_the_preceding_flags() {
|
||||
use crate::{
|
||||
GuestState, Lifter, TargetCpu,
|
||||
aarch64::{Decoder, conditional_select::decode_compare},
|
||||
x86_64::{native, pinned},
|
||||
};
|
||||
|
||||
let pc = GuestAddress(0x1000);
|
||||
let compare_pc = GuestAddress(pc.0 + 4);
|
||||
let end = GuestAddress(pc.0 + 8);
|
||||
for wide in [0, 1] {
|
||||
for producer_subtract in [0, 1] {
|
||||
// CMP or CMN of X0/W0 and X4/W4.
|
||||
let producer = 0x2b04_001f | wide << 31 | producer_subtract << 30;
|
||||
for subtract in [0, 1] {
|
||||
for right in [2 << 16, (1 << 11) | (31 << 16)] {
|
||||
for condition in 0..16 {
|
||||
// CCMP or CCMN of X1/W1 and X2/W2 or immediate 31.
|
||||
let compare =
|
||||
0x3a40_0025 | wide << 31 | subtract << 30 | right | condition << 12;
|
||||
let instructions = [
|
||||
Decoder.lift(pc, producer).unwrap(),
|
||||
Decoder.lift(compare_pc, compare).unwrap(),
|
||||
];
|
||||
let (system, _) = emit_system_mode(
|
||||
&instructions,
|
||||
None,
|
||||
end,
|
||||
TargetCpu::Baseline,
|
||||
super::super::MemoryChecks::DEFAULT,
|
||||
super::super::NativeSystem::NONE,
|
||||
);
|
||||
assert_eq!(system.source_map[0], (pc, 0));
|
||||
let (at, offset) = system.source_map[1];
|
||||
assert_eq!(at, compare_pc);
|
||||
let (single, _) = emit_system_mode(
|
||||
&instructions[1..],
|
||||
None,
|
||||
end,
|
||||
TargetCpu::Baseline,
|
||||
super::super::MemoryChecks::DEFAULT,
|
||||
super::super::NativeSystem::NONE,
|
||||
);
|
||||
let bytes = &system.x86_64_code[offset..];
|
||||
if condition < 14 {
|
||||
assert!(bytes.len() < single.x86_64_code.len(), "{compare:08x}");
|
||||
let predicate_at = usize::from(matches!(condition, 8 | 9));
|
||||
assert_eq!(bytes[predicate_at..predicate_at + 2], [0x41, 0x0f]);
|
||||
} else {
|
||||
assert_eq!(bytes, single.x86_64_code);
|
||||
}
|
||||
|
||||
let dit = TargetCpu::Baseline.with_data_independent_timing();
|
||||
let (system_dit, _) = emit_system_mode(
|
||||
&instructions,
|
||||
None,
|
||||
end,
|
||||
dit,
|
||||
super::super::MemoryChecks::DEFAULT,
|
||||
super::super::NativeSystem::NONE,
|
||||
);
|
||||
let mut baseline = Code::pinned();
|
||||
baseline.set_constant_time(true);
|
||||
super::super::conditional_select::emit_compare(
|
||||
&mut baseline,
|
||||
&decode_compare(compare).unwrap(),
|
||||
false,
|
||||
);
|
||||
assert!(
|
||||
system_dit.x86_64_code[system_dit.source_map[1].1..]
|
||||
.starts_with(&baseline)
|
||||
);
|
||||
|
||||
let frame = emit(&instructions, None, end);
|
||||
let entered = pinned::entered(&system.x86_64_code);
|
||||
for (left, right) in [
|
||||
(0, 0),
|
||||
(1, 0),
|
||||
(0, 1),
|
||||
(1 << 31, 1),
|
||||
(1 << 63, 1),
|
||||
(u64::MAX, 1),
|
||||
(u64::MAX, u64::MAX),
|
||||
] {
|
||||
let mut initial = GuestState::default();
|
||||
initial.x[0] = left;
|
||||
initial.x[1] = left ^ 1;
|
||||
initial.x[2] = right;
|
||||
initial.x[4] = right;
|
||||
initial.nzcv = 0xf000_0000;
|
||||
let mut expected = initial.clone();
|
||||
assert_eq!(native::run(&frame.x86_64_code, &mut expected), end.0);
|
||||
assert_eq!(native::run(&entered, &mut initial), end.0);
|
||||
assert_eq!(initial, expected, "{producer:08x} {compare:08x}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -233,13 +233,15 @@ impl LookupTable {
|
||||
|
||||
/// The entry of `pc` in `context`'s set for `slot`: one in `context` if
|
||||
/// there is one, as a thunk would find it, else one in another context.
|
||||
#[inline]
|
||||
pub fn find(&self, slot: usize, pc: u64, context: u64) -> LookupEntry {
|
||||
let (first, second) = (self[slot], self[neighbour(slot)]);
|
||||
if second.pc == pc && (first.pc != pc || first.context != context) {
|
||||
second
|
||||
} else {
|
||||
first
|
||||
let set = &self.0[slot / 2].0;
|
||||
let first = &set[slot % 2];
|
||||
if first.pc == pc && first.context == context {
|
||||
return *first;
|
||||
}
|
||||
let second = &set[(slot % 2) ^ 1];
|
||||
if second.pc == pc { *second } else { *first }
|
||||
}
|
||||
|
||||
/// Put `entry` in the slot its PC and context pick, and what held it
|
||||
|
||||
@@ -1,35 +1,45 @@
|
||||
//! Branchless conditional select from the saved guest NZCV.
|
||||
use super::{capture_nzcv, condition_holds, flag_word, load, right_operand, store, store_nzcv};
|
||||
//! Branchless conditional select and compare using guest NZCV.
|
||||
use super::{capture_nzcv, condition_holds, flag_word, load_with, pinned, store, store_nzcv};
|
||||
use crate::aarch64::{
|
||||
Register, Shift, Width,
|
||||
Register, Width,
|
||||
conditional_select::{CompareOperand, CompareRight, Operand, Otherwise},
|
||||
};
|
||||
use crate::x86_64::asm::{
|
||||
Alu, Asm, Code, Cond,
|
||||
Gpr::{R8, Rax, Rcx, Rdx},
|
||||
Rm, Size, Unary,
|
||||
Gpr::{R8, Rax, Rdx},
|
||||
Mem, Rm, Size, Unary,
|
||||
};
|
||||
|
||||
const NZCV_SHIFT: u8 = 28;
|
||||
|
||||
/// The comparison runs on both arms and a CMOV picks its flags or the
|
||||
/// fallback, so the timing depends on neither the condition nor the data.
|
||||
pub(super) fn emit_compare(code: &mut Code, operand: &CompareOperand) {
|
||||
let predicate = condition_holds(code, operand.condition, false);
|
||||
/// fallback. A preceding pinned capture can supply the predicate directly.
|
||||
pub(super) fn emit_compare(code: &mut Code, operand: &CompareOperand, live_nzcv: bool) {
|
||||
let predicate = condition_holds(code, operand.condition, live_nzcv);
|
||||
if let Some(cond) = predicate {
|
||||
// R8 is scratch under the native leaf ABI.
|
||||
code.asm().setcc(cond, R8);
|
||||
}
|
||||
load(code, operand.left);
|
||||
let size = Size::of(operand.width == Width::X64);
|
||||
let op = if operand.subtract { Alu::Cmp } else { Alu::Add };
|
||||
match operand.right {
|
||||
CompareRight::Register(register) => {
|
||||
right_operand(code, register, operand.width, Shift::Lsl, 0)
|
||||
let emitted =
|
||||
pinned::unshifted_binary(&mut code.asm(), op, size, Rax, operand.left, register);
|
||||
debug_assert!(emitted, "RAX is scratch for conditional compare");
|
||||
}
|
||||
CompareRight::Immediate(value) => {
|
||||
let mut asm = code.asm();
|
||||
let destination = match asm.guest(operand.left) {
|
||||
Some(left) if operand.subtract => left,
|
||||
_ => {
|
||||
load_with(&mut asm, operand.left);
|
||||
Rax.into()
|
||||
}
|
||||
};
|
||||
asm.alu_imm(op, size, destination, i32::from(value));
|
||||
}
|
||||
CompareRight::Immediate(value) => code.asm().mov_imm32(Rcx, u32::from(value)),
|
||||
}
|
||||
let op = if operand.subtract { Alu::Sub } else { Alu::Add };
|
||||
code.asm()
|
||||
.alu(op, Size::of(operand.width == Width::X64), Rax, Rcx);
|
||||
let pinned = code.is_pinned();
|
||||
if pinned {
|
||||
flag_word::capture_in_rax(code, operand.subtract);
|
||||
@@ -53,6 +63,25 @@ pub(super) fn emit_compare(code: &mut Code, operand: &CompareOperand) {
|
||||
|
||||
pub(super) fn emit(code: &mut Code, operand: &Operand, live_nzcv: bool) {
|
||||
let size = Size::of(operand.width == Width::X64);
|
||||
let destination = code.host(operand.destination);
|
||||
let output = destination.unwrap_or(Rax);
|
||||
if operand.left == Register::Zero
|
||||
&& operand.right == Register::Zero
|
||||
&& matches!(operand.otherwise, Otherwise::Increment | Otherwise::Invert)
|
||||
&& let Some(predicate) = condition_holds(code, operand.condition, live_nzcv)
|
||||
{
|
||||
// CSET and CSETM materialize the condition as a bit or a mask.
|
||||
let mut asm = code.asm();
|
||||
asm.setcc(predicate.negate(), output);
|
||||
asm.movzx(Size::Dword, output, Size::Byte, output);
|
||||
if operand.otherwise == Otherwise::Invert {
|
||||
asm.unary(Unary::Neg, size, output);
|
||||
}
|
||||
if destination.is_none() {
|
||||
store(code, operand.destination);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let otherwise = if operand.condition >= 14 {
|
||||
// AL and NV always select Rn.
|
||||
None
|
||||
@@ -66,6 +95,7 @@ pub(super) fn emit(code: &mut Code, operand: &Operand, live_nzcv: bool) {
|
||||
let mut asm = code.asm();
|
||||
select_input(&mut asm, R8, size, operand.right);
|
||||
match operand.otherwise {
|
||||
Otherwise::Increment if live_nzcv => asm.lea(size, R8, Mem::base(R8, 1)),
|
||||
Otherwise::Increment => asm.inc(size, R8),
|
||||
Otherwise::Invert => asm.unary(Unary::Not, size, R8),
|
||||
Otherwise::Negate => asm.unary(Unary::Neg, size, R8),
|
||||
@@ -73,13 +103,40 @@ pub(super) fn emit(code: &mut Code, operand: &Operand, live_nzcv: bool) {
|
||||
}
|
||||
Some(Rm::Reg(R8))
|
||||
};
|
||||
// If the unchanged false arm already lives in the result register,
|
||||
// keep it there and conditionally move the true arm instead.
|
||||
let keep_false = operand.left != operand.destination
|
||||
&& matches!(otherwise, Some(Rm::Reg(source)) if source == output);
|
||||
let (initial, alternate) = if keep_false {
|
||||
let mut asm = code.asm();
|
||||
let source = asm.guest(operand.left).unwrap_or_else(|| {
|
||||
asm.mov_imm32(R8, 0);
|
||||
Rm::Reg(R8)
|
||||
});
|
||||
(operand.destination, Some(source))
|
||||
} else {
|
||||
(operand.left, otherwise)
|
||||
};
|
||||
let predicate = condition_holds(code, operand.condition, live_nzcv);
|
||||
let mut asm = code.asm();
|
||||
select_input(&mut asm, Rax, size, operand.left);
|
||||
if let Some((predicate, otherwise)) = predicate.zip(otherwise) {
|
||||
asm.cmov(predicate.negate(), size, Rax, otherwise);
|
||||
let selected = predicate.zip(alternate);
|
||||
let already_placed = destination.is_some() && initial == operand.destination;
|
||||
// CMOVcc r32 in 64-bit mode clears the upper half even when its
|
||||
// predicate is false (Intel SDM, CMOVcc).
|
||||
if selected.is_none() || !already_placed {
|
||||
select_input(&mut asm, output, size, initial);
|
||||
}
|
||||
if let Some((predicate, alternate)) = selected {
|
||||
let take_alternate = if keep_false {
|
||||
predicate
|
||||
} else {
|
||||
predicate.negate()
|
||||
};
|
||||
asm.cmov(take_alternate, size, output, alternate);
|
||||
}
|
||||
if destination.is_none() {
|
||||
store(code, operand.destination);
|
||||
}
|
||||
store(code, operand.destination);
|
||||
}
|
||||
|
||||
/// A W source is zero-extended by the sized MOV. XZR uses an immediate
|
||||
@@ -101,13 +158,78 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::GuestState;
|
||||
|
||||
#[test]
|
||||
fn compares_registers_and_immediates_without_changing_operands() {
|
||||
for width in [Width::W32, Width::X64] {
|
||||
let sign = match width {
|
||||
Width::W32 => 1 << 31,
|
||||
Width::X64 => 1 << 63,
|
||||
};
|
||||
let initial = {
|
||||
let mut state = GuestState::default();
|
||||
state.x[1] = sign;
|
||||
state.x[2] = u64::MAX;
|
||||
state.x[3] = sign;
|
||||
state.x[8] = u64::MAX;
|
||||
state
|
||||
};
|
||||
use CompareRight::{Immediate, Register as FromRegister};
|
||||
use Register::{X, Zero};
|
||||
for (left, right, sub_flags, add_flags) in [
|
||||
(X(1), FromRegister(X(2)), 8, 3),
|
||||
(X(3), FromRegister(X(8)), 8, 3),
|
||||
(X(1), FromRegister(X(1)), 6, 7),
|
||||
(X(1), FromRegister(Zero), 10, 8),
|
||||
(X(3), Immediate(0), 10, 8),
|
||||
(X(3), Immediate(31), 3, 8),
|
||||
(Zero, Immediate(31), 8, 0),
|
||||
] {
|
||||
for (subtract, flags) in [(true, sub_flags), (false, add_flags)] {
|
||||
for condition in [0, 14, 15] {
|
||||
let operand = CompareOperand {
|
||||
width,
|
||||
subtract,
|
||||
left,
|
||||
right,
|
||||
condition,
|
||||
fallback: 5,
|
||||
};
|
||||
let mut frame = Code::new();
|
||||
let mut pinned = Code::pinned();
|
||||
emit_compare(&mut frame, &operand, false);
|
||||
emit_compare(&mut pinned, &operand, false);
|
||||
pinned.asm().ret();
|
||||
let pinned = super::super::pinned::entered(&pinned);
|
||||
for nzcv in [0, 4] {
|
||||
let expected = if condition == 0 && nzcv == 0 {
|
||||
5
|
||||
} else {
|
||||
flags
|
||||
};
|
||||
for bytes in [&frame[..], &pinned[..]] {
|
||||
let mut state = initial.clone();
|
||||
state.nzcv = nzcv << NZCV_SHIFT;
|
||||
super::super::native::run(bytes, &mut state);
|
||||
assert_eq!(state.x, initial.x, "{operand:?}");
|
||||
assert_eq!(state.nzcv, expected << NZCV_SHIFT, "{operand:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selects_preserve_nzcv_and_zero_extend_w_results() {
|
||||
const LEFT: u64 = 0x1234_5678_9abc_def0;
|
||||
const RIGHT: u64 = 0xfedc_ba98_7654_3210;
|
||||
for width in [Width::W32, Width::X64] {
|
||||
let cases = [Width::W32, Width::X64]
|
||||
.into_iter()
|
||||
.flat_map(|width| [1, 2, 8].map(|destination| (width, destination)));
|
||||
for (width, destination) in cases {
|
||||
for (left, lhs) in [(Register::X(1), LEFT), (Register::Zero, 0)] {
|
||||
for (right, rhs) in [(Register::X(2), RIGHT), (Register::Zero, 0)] {
|
||||
for (right, rhs) in [(Register::X(8), RIGHT), (Register::Zero, 0)] {
|
||||
for (otherwise, alternate) in [
|
||||
(Otherwise::Unchanged, rhs),
|
||||
(Otherwise::Increment, rhs.wrapping_add(1)),
|
||||
@@ -117,7 +239,7 @@ mod tests {
|
||||
for condition in [0, 1, 10, 12, 14, 15] {
|
||||
let operand = Operand {
|
||||
width,
|
||||
destination: Register::X(1),
|
||||
destination: Register::X(destination),
|
||||
left,
|
||||
right,
|
||||
condition,
|
||||
@@ -152,9 +274,13 @@ mod tests {
|
||||
..Default::default()
|
||||
};
|
||||
state.x[1] = LEFT;
|
||||
state.x[2] = RIGHT;
|
||||
state.x[8] = RIGHT;
|
||||
super::super::native::run(code, &mut state);
|
||||
assert_eq!(state.x[1], expected, "{operand:?}");
|
||||
let mut expected_registers = [0; 31];
|
||||
expected_registers[1] = LEFT;
|
||||
expected_registers[8] = RIGHT;
|
||||
expected_registers[usize::from(destination)] = expected;
|
||||
assert_eq!(state.x, expected_registers, "{operand:?}");
|
||||
assert_eq!(state.nzcv, flags << 28);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -280,7 +280,15 @@ pub(super) fn scalar(
|
||||
accessed()
|
||||
};
|
||||
// A fault leaves a host destination as it was.
|
||||
let host = code.host(data).unwrap_or(Gpr::Rcx);
|
||||
// Offset loads have no pending writeback. Keep an unpinned
|
||||
// result in RAX so the following instruction can use it
|
||||
// without reloading it from the frame.
|
||||
let scratch = if code.is_pinned() && mode == AddressMode::Offset {
|
||||
Gpr::Rax
|
||||
} else {
|
||||
Gpr::Rcx
|
||||
};
|
||||
let host = code.host(data).unwrap_or(scratch);
|
||||
let checkpoint = code.checkpoint();
|
||||
{
|
||||
let mut asm = code.asm();
|
||||
@@ -302,14 +310,14 @@ pub(super) fn scalar(
|
||||
code,
|
||||
checkpoint,
|
||||
Kind::Load { element: 0, host },
|
||||
mask(Gpr::Rcx),
|
||||
mask(host),
|
||||
);
|
||||
// A discarded load still performs its faultable access.
|
||||
if host == Gpr::Rcx
|
||||
if host == scratch
|
||||
&& let Some(data) = code.asm().guest(data)
|
||||
{
|
||||
let start = code.checkpoint();
|
||||
code.asm().mov_store(Size::Qword, data, Gpr::Rcx);
|
||||
code.asm().mov_store(Size::Qword, data, host);
|
||||
mark(&mut recipe, code, start, Kind::Commit, 0);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,8 +15,8 @@
|
||||
use super::asm::{Alu, Asm, Code, Gpr, Mem, Rm, ShiftOp, Size};
|
||||
use super::{flag_word, logical, nzcv, right_operand, store};
|
||||
use crate::{
|
||||
GuestState,
|
||||
aarch64::{Logical, Operation, Register, Shift, WideMove, Width, simd},
|
||||
GuestState, TargetCpu,
|
||||
aarch64::{Logical, Operation, Register, Shift, WideMove, Width, pc_relative, simd},
|
||||
block::HostGprSnapshot,
|
||||
};
|
||||
|
||||
@@ -129,13 +129,65 @@ fn right(
|
||||
}
|
||||
}
|
||||
|
||||
/// `operation` straight in the host registers of its operands: the few forms
|
||||
/// that make up most of a program. Any other, and the ones here in frame
|
||||
/// code, go through their emitters.
|
||||
pub(super) fn emit_direct(code: &mut Code, operation: &Operation) -> bool {
|
||||
if !code.is_pinned() {
|
||||
return false;
|
||||
/// A binary operation without a shifted operand can read a frame slot
|
||||
/// directly. A commutative operation can start with the right operand
|
||||
/// when it already lives in the destination.
|
||||
pub(super) fn unshifted_binary(
|
||||
asm: &mut Asm,
|
||||
op: Alu,
|
||||
size: Size,
|
||||
work: Gpr,
|
||||
mut left: Register,
|
||||
mut right: Register,
|
||||
) -> bool {
|
||||
if asm.guest(right) == Some(Rm::Reg(work)) && right != left {
|
||||
if op == Alu::Sub {
|
||||
return false;
|
||||
}
|
||||
debug_assert_ne!(op, Alu::Cmp, "CMP has no destination register");
|
||||
core::mem::swap(&mut left, &mut right);
|
||||
}
|
||||
let destination = match asm.guest(left) {
|
||||
Some(Rm::Reg(host)) if op == Alu::Cmp => host,
|
||||
_ => {
|
||||
// The ALU operation itself clears the upper half of a W result.
|
||||
take(asm, Size::Qword, work, left);
|
||||
work
|
||||
}
|
||||
};
|
||||
match asm.guest(right) {
|
||||
Some(Rm::Reg(host)) => asm.alu(op, size, destination, host),
|
||||
Some(frame) => asm.alu_load(op, size, destination, frame),
|
||||
None => asm.alu_imm8(op, size, destination, 0),
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Compare the left operand against the prior instruction's result in RAX.
|
||||
pub(super) fn compare_held_right(code: &mut Code, width: Width, left: Register) {
|
||||
let mut asm = code.asm();
|
||||
let left = asm.guest(left).expect("CMP left register");
|
||||
asm.alu(Alu::Cmp, Size::of(width == Width::X64), left, Gpr::Rax);
|
||||
nzcv(code, true);
|
||||
}
|
||||
|
||||
/// Compare the guest value that the previous instruction left in RAX.
|
||||
pub(super) fn compare_held_immediate(code: &mut Code, width: Width, immediate: u32) {
|
||||
let size = Size::of(width == Width::X64);
|
||||
code.asm()
|
||||
.alu_imm(Alu::Cmp, size, Gpr::Rax, immediate as i32);
|
||||
nzcv(code, true);
|
||||
}
|
||||
|
||||
pub(super) fn emit_pc_relative(code: &mut Code, operand: pc_relative::Operand) {
|
||||
// Fixed in size at every address, for a stored block's rebase.
|
||||
let work = working(code, operand.destination);
|
||||
code.asm().mov_imm64(work, operand.address);
|
||||
finish(code, work, operand.destination, false, false);
|
||||
}
|
||||
|
||||
/// Common integer operations on their native register or frame operands.
|
||||
pub(super) fn emit_direct(code: &mut Code, operation: &Operation, target: TargetCpu) -> bool {
|
||||
match *operation {
|
||||
Operation::AddSub {
|
||||
width,
|
||||
@@ -146,13 +198,17 @@ pub(super) fn emit_direct(code: &mut Code, operation: &Operation) -> bool {
|
||||
immediate,
|
||||
} => {
|
||||
let size = Size::of(width == Width::X64);
|
||||
let op = if subtract { Alu::Sub } else { Alu::Add };
|
||||
let op = match (subtract, destination) {
|
||||
(true, Register::Zero) => Alu::Cmp,
|
||||
(true, _) => Alu::Sub,
|
||||
(false, _) => Alu::Add,
|
||||
};
|
||||
let work = working(code, destination);
|
||||
let immediate = immediate as i32;
|
||||
let mut asm = code.asm();
|
||||
match asm.guest(source) {
|
||||
Some(Rm::Reg(host)) if destination == Register::Zero && subtract => {
|
||||
asm.alu_imm(Alu::Cmp, size, host, immediate);
|
||||
Some(operand) if op == Alu::Cmp => {
|
||||
asm.alu_imm(op, size, operand, immediate);
|
||||
}
|
||||
Some(Rm::Reg(host)) if !flags && host != work => {
|
||||
let distance = if subtract { -immediate } else { immediate };
|
||||
@@ -176,17 +232,27 @@ pub(super) fn emit_direct(code: &mut Code, operation: &Operation) -> bool {
|
||||
amount,
|
||||
} => {
|
||||
let size = Size::of(width == Width::X64);
|
||||
let op = if subtract { Alu::Sub } else { Alu::Add };
|
||||
let op = match (subtract, destination) {
|
||||
(true, Register::Zero) => Alu::Cmp,
|
||||
(true, _) => Alu::Sub,
|
||||
(false, _) => Alu::Add,
|
||||
};
|
||||
let work = working(code, destination);
|
||||
let second = right(code, operand, width, shift, amount, work);
|
||||
let mut asm = code.asm();
|
||||
match asm.guest(left) {
|
||||
Some(Rm::Reg(host)) if destination == Register::Zero && subtract => {
|
||||
asm.alu(Alu::Cmp, size, host, second);
|
||||
if amount != 0 || !unshifted_binary(&mut code.asm(), op, size, work, left, operand) {
|
||||
let frame = !code.is_pinned();
|
||||
if frame {
|
||||
take(&mut code.asm(), Size::Qword, work, left);
|
||||
}
|
||||
_ => {
|
||||
take(&mut asm, Size::Qword, work, left);
|
||||
asm.alu(op, size, work, second);
|
||||
let second = right(code, operand, width, shift, amount, work);
|
||||
let mut asm = code.asm();
|
||||
match asm.guest(left) {
|
||||
Some(Rm::Reg(host)) if op == Alu::Cmp => asm.alu(op, size, host, second),
|
||||
_ => {
|
||||
if !frame {
|
||||
take(&mut asm, Size::Qword, work, left);
|
||||
}
|
||||
asm.alu(op, size, work, second);
|
||||
}
|
||||
}
|
||||
}
|
||||
finish(code, work, destination, flags, subtract);
|
||||
@@ -204,10 +270,37 @@ pub(super) fn emit_direct(code: &mut Code, operation: &Operation) -> bool {
|
||||
} => {
|
||||
let size = Size::of(width == Width::X64);
|
||||
let work = working(code, destination);
|
||||
if kind == Logical::Or && left == Register::Zero && !invert && amount == 0 && !flags {
|
||||
if kind == Logical::And
|
||||
&& invert
|
||||
&& target.supports(TargetCpu::Bmi1)
|
||||
&& !target.data_independent_timing()
|
||||
&& let Some(left) = code.asm().guest(left)
|
||||
{
|
||||
let inverted = match code.host(operand) {
|
||||
Some(host) if amount == 0 => host,
|
||||
_ => {
|
||||
right_operand(code, operand, width, shift, amount);
|
||||
Gpr::Rcx
|
||||
}
|
||||
};
|
||||
// ANDN folds a frame operand and sets N/Z with C/V clear.
|
||||
code.asm().andn(size, work, inverted, left);
|
||||
} else if kind == Logical::Or
|
||||
&& left == Register::Zero
|
||||
&& !invert
|
||||
&& amount == 0
|
||||
&& !flags
|
||||
{
|
||||
// MOV.
|
||||
take(&mut code.asm(), size, work, operand);
|
||||
} else {
|
||||
} else if invert
|
||||
|| amount != 0
|
||||
|| !unshifted_binary(&mut code.asm(), logical(kind), size, work, left, operand)
|
||||
{
|
||||
let frame = !code.is_pinned();
|
||||
if frame {
|
||||
take(&mut code.asm(), Size::Qword, work, left);
|
||||
}
|
||||
let second = if invert {
|
||||
right_operand(code, operand, width, shift, amount);
|
||||
code.asm().unary(super::asm::Unary::Not, size, Gpr::Rcx);
|
||||
@@ -216,7 +309,9 @@ pub(super) fn emit_direct(code: &mut Code, operation: &Operation) -> bool {
|
||||
right(code, operand, width, shift, amount, work)
|
||||
};
|
||||
let mut asm = code.asm();
|
||||
take(&mut asm, Size::Qword, work, left);
|
||||
if !frame {
|
||||
take(&mut asm, Size::Qword, work, left);
|
||||
}
|
||||
asm.alu(logical(kind), size, work, second);
|
||||
}
|
||||
finish(code, work, destination, flags, false);
|
||||
@@ -248,7 +343,7 @@ pub(super) fn emit_direct(code: &mut Code, operation: &Operation) -> bool {
|
||||
destination,
|
||||
immediate,
|
||||
shift,
|
||||
} => {
|
||||
} if code.is_pinned() => {
|
||||
let work = working(code, destination);
|
||||
let value = u64::from(immediate) << shift;
|
||||
let mut asm = code.asm();
|
||||
@@ -276,11 +371,10 @@ pub(super) fn emit_direct(code: &mut Code, operation: &Operation) -> bool {
|
||||
}
|
||||
finish(code, work, destination, false, false);
|
||||
}
|
||||
Operation::PcRelative(operand) if operand.destination != Register::Zero => {
|
||||
// Fixed in size at every address, for a stored block's rebase.
|
||||
let work = working(code, operand.destination);
|
||||
code.asm().mov_imm64(work, operand.address);
|
||||
finish(code, work, operand.destination, false, false);
|
||||
Operation::PcRelative(operand)
|
||||
if code.is_pinned() && operand.destination != Register::Zero =>
|
||||
{
|
||||
emit_pc_relative(code, operand);
|
||||
}
|
||||
_ => return false,
|
||||
}
|
||||
@@ -395,9 +489,51 @@ mod tests {
|
||||
assert_eq!(&frame[..], [0x48, 0x8b, 0x87, 0, 0, 0, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn immediate_cmp_reads_the_frame_and_preserves_its_operand() {
|
||||
let mut initial = GuestState {
|
||||
sp: 0xfff000,
|
||||
..GuestState::default()
|
||||
};
|
||||
for width in [Width::W32, Width::X64] {
|
||||
initial.x[2] = match width {
|
||||
Width::W32 => 0x1234_5678_8000_0000,
|
||||
Width::X64 => 1 << 63,
|
||||
};
|
||||
for (source, immediate, expected) in
|
||||
[(Register::X(2), 31, 3), (Register::Sp, 0xfff000, 6)]
|
||||
{
|
||||
let operation = Operation::AddSub {
|
||||
width,
|
||||
subtract: true,
|
||||
flags: true,
|
||||
destination: Register::Zero,
|
||||
source,
|
||||
immediate,
|
||||
};
|
||||
let mut frame = Code::new();
|
||||
assert!(emit_direct(&mut frame, &operation, TargetCpu::Baseline));
|
||||
let start = usize::from(width == Width::X64);
|
||||
assert_eq!(frame[start], if immediate <= 127 { 0x83 } else { 0x81 });
|
||||
assert_eq!(frame[start + 1], 0xbf); // CMP with a frame displacement.
|
||||
|
||||
let mut pinned = direct(operation);
|
||||
pinned.asm().ret();
|
||||
let pinned = entered(&pinned);
|
||||
for bytes in [&frame[..], &pinned[..]] {
|
||||
let mut state = initial.clone();
|
||||
super::super::native::run(bytes, &mut state);
|
||||
assert_eq!(state.x, initial.x);
|
||||
assert_eq!(state.sp, initial.sp);
|
||||
assert_eq!(state.nzcv, expected << 28);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn direct(operation: Operation) -> Code {
|
||||
let mut code = Code::pinned();
|
||||
assert!(emit_direct(&mut code, &operation));
|
||||
assert!(emit_direct(&mut code, &operation, TargetCpu::Baseline));
|
||||
code
|
||||
}
|
||||
|
||||
@@ -441,6 +577,153 @@ mod tests {
|
||||
assert!(!narrow.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bmi1_bic_folds_the_frame_operand_and_keeps_older_targets() {
|
||||
// BIC X8,X9,X10 from archived desktop code (8a2a0128).
|
||||
let operation = Operation::LogicalRegister {
|
||||
width: Width::X64,
|
||||
kind: Logical::And,
|
||||
invert: true,
|
||||
flags: false,
|
||||
destination: Register::X(8),
|
||||
left: Register::X(9),
|
||||
right: Register::X(10),
|
||||
shift: Shift::Lsl,
|
||||
amount: 0,
|
||||
};
|
||||
let emit = |target| {
|
||||
let mut code = Code::pinned();
|
||||
assert!(emit_direct(&mut code, &operation, target));
|
||||
code
|
||||
};
|
||||
let fast = emit(TargetCpu::Bmi1);
|
||||
// mov rcx,[rdi+80]; andn rsi,rcx,[rdi+72].
|
||||
assert_eq!(
|
||||
&fast[..],
|
||||
[0x48, 0x8b, 0x4f, 0x50, 0xc4, 0xe2, 0xf0, 0xf2, 0x77, 0x48]
|
||||
);
|
||||
let baseline = emit(TargetCpu::Baseline);
|
||||
assert_eq!(baseline.instructions(), 4);
|
||||
assert_eq!(fast.instructions(), 2);
|
||||
for target in [
|
||||
TargetCpu::Sse42,
|
||||
TargetCpu::Bmi2,
|
||||
TargetCpu::Bmi1.with_data_independent_timing(),
|
||||
] {
|
||||
assert_eq!(emit(target), baseline);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bmi1_bic_preserves_aliases_and_bics_flags() {
|
||||
if !TargetCpu::detect().supports(TargetCpu::Bmi1) {
|
||||
return;
|
||||
}
|
||||
let mut initial = GuestState::default();
|
||||
initial.x[0] = 0x89ab_cdef_8000_0000;
|
||||
initial.x[8] = 0x5555_5555_0000_0000;
|
||||
initial.x[9] = u64::MAX;
|
||||
initial.nzcv = 0xf000_0000;
|
||||
for width in [Width::W32, Width::X64] {
|
||||
for (shift, amount) in [(Shift::Lsl, 0), (Shift::Asr, 1), (Shift::Ror, 3)] {
|
||||
for (destination, left, right) in [
|
||||
(Register::X(8), Register::X(8), Register::X(0)),
|
||||
(Register::X(8), Register::X(0), Register::X(8)),
|
||||
(Register::X(8), Register::X(9), Register::X(9)),
|
||||
(Register::Zero, Register::X(0), Register::X(8)),
|
||||
] {
|
||||
let operation = Operation::LogicalRegister {
|
||||
width,
|
||||
kind: Logical::And,
|
||||
invert: true,
|
||||
flags: true,
|
||||
destination,
|
||||
left,
|
||||
right,
|
||||
shift,
|
||||
amount,
|
||||
};
|
||||
let run = |target, pinned| {
|
||||
let mut code = if pinned { Code::pinned() } else { Code::new() };
|
||||
assert!(emit_direct(&mut code, &operation, target));
|
||||
code.asm().ret();
|
||||
let bytes = if pinned {
|
||||
entered(&code)
|
||||
} else {
|
||||
code.into_bytes()
|
||||
};
|
||||
let mut state = initial.clone();
|
||||
super::super::native::run(&bytes, &mut state);
|
||||
state
|
||||
};
|
||||
for pinned in [false, true] {
|
||||
let state = run(TargetCpu::Bmi1, pinned);
|
||||
assert_eq!(state, run(TargetCpu::Baseline, pinned));
|
||||
assert_eq!(state.nzcv & 0x3000_0000, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn binary_operands_keep_aliases_widths_and_flags() {
|
||||
use crate::{
|
||||
GuestAddress, Options, TargetCpu,
|
||||
block::{BlockProfile, Features},
|
||||
};
|
||||
const BASE: GuestAddress = GuestAddress(0x1000);
|
||||
let pinned = Options::new(
|
||||
BlockProfile::new(Features::SYSTEM_MODE),
|
||||
TargetCpu::Baseline,
|
||||
);
|
||||
let frame = Options::new(BlockProfile::ORDINARY, TargetCpu::Baseline);
|
||||
let mut initial = GuestState::default();
|
||||
initial.x[0] = 0x1234_5678_7fff_fffe;
|
||||
initial.x[1] = 0xfedc_ba98_0000_0003;
|
||||
initial.x[3] = 0x9182_7364_ffff_ffff;
|
||||
initial.x[16] = 0xaaff_5500_8000_0000;
|
||||
initial.x[17] = 0x0246_8ace_ffff_ff00;
|
||||
initial.nzcv = 0x3000_0000;
|
||||
for base in [
|
||||
0x0b00_0000, // ADD
|
||||
0x0b00_0800, // ADD, LSL #2
|
||||
0x2b00_0000, // ADDS
|
||||
0x4b00_0000, // SUB
|
||||
0x6b00_0000, // SUBS
|
||||
0x4a00_0000, // EOR
|
||||
0x6a00_0000, // ANDS
|
||||
] {
|
||||
for (rd, rn, rm) in [
|
||||
(1, 0, 1),
|
||||
(16, 17, 1),
|
||||
(17, 1, 16),
|
||||
(0, 3, 0),
|
||||
(3, 0, 3),
|
||||
(1, 1, 1),
|
||||
(31, 16, 3),
|
||||
(1, 31, 1),
|
||||
(16, 17, 31),
|
||||
] {
|
||||
for width in [0u32, 1 << 31] {
|
||||
let word = base | width | rm << 16 | rn << 5 | rd;
|
||||
let run = |options, wrap| {
|
||||
let native = crate::compile(&word.to_le_bytes(), BASE, options).unwrap();
|
||||
let code = if wrap {
|
||||
entered(&native.native.x86_64_code)
|
||||
} else {
|
||||
native.native.x86_64_code
|
||||
};
|
||||
let mut state = initial.clone();
|
||||
crate::x86_64::native::run(&code, &mut state);
|
||||
state
|
||||
};
|
||||
assert_eq!(run(&pinned, true), run(&frame, false), "{word:08x}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Random(u64);
|
||||
impl Random {
|
||||
fn next(&mut self) -> u32 {
|
||||
|
||||
@@ -13,7 +13,7 @@ mod apx;
|
||||
mod self_loop;
|
||||
pub(super) use analysis::MAX_INSTRUCTIONS;
|
||||
pub(crate) use self_loop::Plan as ResidentLoopPlan;
|
||||
pub(super) use self_loop::prefix_with_budget;
|
||||
pub(super) use self_loop::{FrameLoop, prefix_with_budget};
|
||||
mod constant;
|
||||
mod encoding;
|
||||
mod flags;
|
||||
@@ -698,6 +698,59 @@ impl Emitter<'_> {
|
||||
self.instruction_with_constant(instruction, None)
|
||||
}
|
||||
|
||||
fn emit_constant_write(
|
||||
&mut self,
|
||||
write: constant::ConstantWrite,
|
||||
immediate_width: Width,
|
||||
continuation: Option<GuestAddress>,
|
||||
) {
|
||||
let guest = slot(write.destination).expect("known constant has a real destination");
|
||||
if next_use(self.effects, self.current + 1, guest) != usize::MAX {
|
||||
let index = self.allocate(guest);
|
||||
self.emit(|code| encoding::immediate(code, POOL[index], write.value, immediate_width));
|
||||
self.locations[guest] = Location::Host(POOL[index]);
|
||||
self.resident[index] = Some(Resident { guest, dirty: true });
|
||||
self.output.stats.commits += 1;
|
||||
if let Some(pc) = continuation {
|
||||
// A resident value needs no separate frame store here.
|
||||
self.output.source_map.push((pc, self.output.code.len()));
|
||||
self.emit(encoding::nop);
|
||||
}
|
||||
} else {
|
||||
self.emit(|code| encoding::immediate(code, RESULT, write.value, immediate_width));
|
||||
if let Some(pc) = continuation {
|
||||
self.output.source_map.push((pc, self.output.code.len()));
|
||||
}
|
||||
self.commit(write.destination, Width::X64);
|
||||
}
|
||||
self.output.stats.constant_writes += 1;
|
||||
}
|
||||
|
||||
fn emit_constant_group(
|
||||
&mut self,
|
||||
group: &[Instruction],
|
||||
write: constant::ConstantWrite,
|
||||
immediate_width: Width,
|
||||
) {
|
||||
let [markers @ .., materialization, last] = group else {
|
||||
unreachable!("constant group needs two source rows");
|
||||
};
|
||||
self.pinned_hosts = 0;
|
||||
self.coalesced = None;
|
||||
for instruction in markers {
|
||||
self.output
|
||||
.source_map
|
||||
.push((instruction.pc, self.output.code.len()));
|
||||
self.emit(encoding::nop);
|
||||
}
|
||||
self.output
|
||||
.source_map
|
||||
.push((materialization.pc, self.output.code.len()));
|
||||
self.current += group.len() - 1;
|
||||
self.emit_constant_write(write, immediate_width, Some(last.pc));
|
||||
self.output.stats.commits += group.len() - 1;
|
||||
}
|
||||
|
||||
fn instruction_with_constant(
|
||||
&mut self,
|
||||
instruction: &Instruction,
|
||||
@@ -709,18 +762,7 @@ impl Emitter<'_> {
|
||||
.source_map
|
||||
.push((instruction.pc, self.output.code.len()));
|
||||
if let Some(write) = constant {
|
||||
let guest = slot(write.destination).expect("known constant has a real destination");
|
||||
if next_use(self.effects, self.current + 1, guest) != usize::MAX {
|
||||
let index = self.allocate(guest);
|
||||
self.emit(|code| encoding::immediate(code, POOL[index], write.value, Width::X64));
|
||||
self.locations[guest] = Location::Host(POOL[index]);
|
||||
self.resident[index] = Some(Resident { guest, dirty: true });
|
||||
self.output.stats.commits += 1;
|
||||
} else {
|
||||
self.emit(|code| encoding::immediate(code, RESULT, write.value, Width::X64));
|
||||
self.commit(write.destination, Width::X64);
|
||||
}
|
||||
self.output.stats.constant_writes += 1;
|
||||
self.emit_constant_write(write, Width::X64, None);
|
||||
return Ok(());
|
||||
}
|
||||
match instruction.operation {
|
||||
@@ -1235,8 +1277,41 @@ fn emit_prefix_selected<'a>(
|
||||
fault_table,
|
||||
full: false,
|
||||
};
|
||||
for instruction in instructions.iter().take(consumed) {
|
||||
emitter.instruction(instruction)?;
|
||||
let span = &instructions[..consumed];
|
||||
while let Some(instruction) = span.get(emitter.current) {
|
||||
// A hosted block enters at a guest block head and runs these
|
||||
// non-faulting groups as units. A compile starting inside a group,
|
||||
// or ending before its tail, still sees only the original slice.
|
||||
let rest = &span[emitter.current..];
|
||||
let group = if clean_loads && !fault_table {
|
||||
match instruction.operation {
|
||||
Operation::PcRelative(_) => rest.get(1).and_then(|second| {
|
||||
emitter
|
||||
.constants
|
||||
.fold_address_pair(&instruction.operation, &second.operation)
|
||||
.map(|write| (2, write, Width::X64))
|
||||
}),
|
||||
Operation::MoveWide { .. } => {
|
||||
emitter.constants.fold_wide_run(rest).map(|(count, write)| {
|
||||
// A numeric literal has no AOT relocation field.
|
||||
let width = if u32::try_from(write.value).is_ok() {
|
||||
Width::W32
|
||||
} else {
|
||||
Width::X64
|
||||
};
|
||||
(count, write, width)
|
||||
})
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some((count, write, immediate_width)) = group {
|
||||
emitter.emit_constant_group(&rest[..count], write, immediate_width);
|
||||
} else {
|
||||
emitter.instruction(instruction)?;
|
||||
}
|
||||
emitter.current += 1;
|
||||
}
|
||||
for index in 0..POOL.len() {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Compile-time constant facts for non-faulting scalar sequences. Each separately
|
||||
//! entered region starts with no facts.
|
||||
use crate::aarch64::{Operation, Register, WideMove, Width};
|
||||
use crate::aarch64::{Instruction, Operation, Register, WideMove, Width};
|
||||
|
||||
const REGISTER_SLOTS: usize = 32;
|
||||
const SP_SLOT: usize = 31;
|
||||
@@ -59,6 +59,55 @@ impl ConstantRegisters {
|
||||
value.map(|value| ConstantWrite { destination, value })
|
||||
}
|
||||
|
||||
pub(super) fn fold_address_pair(
|
||||
&mut self,
|
||||
first: &Operation,
|
||||
second: &Operation,
|
||||
) -> Option<ConstantWrite> {
|
||||
let folded = super::super::block::fold_address_pair(first, second)?;
|
||||
self.write(folded.destination, Some(folded.address))
|
||||
}
|
||||
|
||||
pub(super) fn fold_wide_run(
|
||||
&mut self,
|
||||
instructions: &[Instruction],
|
||||
) -> Option<(usize, ConstantWrite)> {
|
||||
let (first, rest) = instructions.split_first()?;
|
||||
let Operation::MoveWide {
|
||||
width,
|
||||
kind: WideMove::Zero | WideMove::Not,
|
||||
destination: destination @ Register::X(_),
|
||||
..
|
||||
} = first.operation
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
let mut keeps = rest.iter().take_while(|instruction| {
|
||||
matches!(
|
||||
instruction.operation,
|
||||
Operation::MoveWide {
|
||||
width: next_width,
|
||||
kind: WideMove::Keep,
|
||||
destination: next_destination,
|
||||
..
|
||||
} if next_width == width && next_destination == destination
|
||||
)
|
||||
});
|
||||
let second = keeps.next()?;
|
||||
self.step(&first.operation);
|
||||
let mut write = self
|
||||
.step(&second.operation)
|
||||
.expect("wide move initializer supplies the destination");
|
||||
let mut count = 2;
|
||||
for instruction in keeps {
|
||||
write = self
|
||||
.step(&instruction.operation)
|
||||
.expect("wide move continuation retains its constant destination");
|
||||
count += 1;
|
||||
}
|
||||
Some((count, write))
|
||||
}
|
||||
|
||||
/// Observe exactly one guest instruction. Returned writes can replace only
|
||||
/// that instruction's value computation; they never authorize removing its
|
||||
/// native commit, source-map entry, or observable intermediate guest value.
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
//! Register residency for non-faulting scalar self-loops. Every exit writes back
|
||||
//! the full guest register bank.
|
||||
//! Bounded native self-loops. Every return settles the guest register bank.
|
||||
use super::{
|
||||
AllocationStats, Effects, Emitter, FRAME_LOCATIONS, GPR_SLOTS, HostGpr, Location,
|
||||
MAX_INSTRUCTIONS, OptimizedRegion, POOL, Resident, analysis, constant, encoding, flags,
|
||||
};
|
||||
use crate::x86_64::asm::Code;
|
||||
use crate::x86_64::asm::{Code, Cond, Gpr, Mem, Patch, Size};
|
||||
use crate::{
|
||||
GuestAddress, NativeBlock,
|
||||
aarch64::{Instruction, Operation},
|
||||
aarch64::{AddressMode, Instruction, MemoryTransfer, Operation, Register},
|
||||
block::{ExitKind, Terminator},
|
||||
};
|
||||
use alloc::vec;
|
||||
@@ -15,6 +14,139 @@ use alloc::vec::Vec;
|
||||
|
||||
const ARM_CONDITION_INVERSE_BIT: u8 = 1;
|
||||
const INSTRUCTION_BYTES: u64 = core::mem::size_of::<u32>() as u64;
|
||||
const MAX_FRAME_LOOP_INSTRUCTIONS: usize = 32;
|
||||
const FRAME_LOOP_COUNTER: Gpr = Gpr::R12;
|
||||
|
||||
/// The existing ordinary body finishes with a settled frame. Its regions
|
||||
/// preserve callee-saved registers, including the native budget counter.
|
||||
/// This wrapper is only used for reviewed direct-RAM bodies with no helper
|
||||
/// exits, stack checks or fault-recoverable execution context.
|
||||
pub(crate) struct FrameLoop {
|
||||
entry: GuestAddress,
|
||||
header: usize,
|
||||
zero_budget: Patch,
|
||||
}
|
||||
|
||||
impl FrameLoop {
|
||||
pub(crate) fn begin(code: &mut Code, entry: GuestAddress) -> Self {
|
||||
const _: () = assert!(crate::block::loop_budget::REMAINING_OFFSET == 0);
|
||||
let mut asm = code.asm();
|
||||
asm.push(FRAME_LOOP_COUNTER);
|
||||
asm.push(Gpr::Rsi);
|
||||
asm.mov_load(Size::Qword, FRAME_LOOP_COUNTER, Mem::base(Gpr::Rsi, 0));
|
||||
asm.test(Size::Qword, FRAME_LOOP_COUNTER, FRAME_LOOP_COUNTER);
|
||||
let zero_budget = asm.jcc(Cond::E);
|
||||
let header = asm.len();
|
||||
Self {
|
||||
entry,
|
||||
header,
|
||||
zero_budget,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn finish(self, code: &mut Code, taken: Option<Cond>, fallthrough: GuestAddress) {
|
||||
let mut asm = code.asm();
|
||||
let normal = taken.map(|condition| asm.jcc(condition.negate()));
|
||||
// The guest predicate is already consumed and NZCV is settled. A
|
||||
// single decrement both accounts for this iteration and gates the
|
||||
// native backedge.
|
||||
asm.dec(Size::Qword, FRAME_LOOP_COUNTER);
|
||||
let again = asm.jcc(Cond::Ne);
|
||||
asm.bind_back(again, self.header);
|
||||
asm.bind(self.zero_budget);
|
||||
settle_frame_budget(&mut asm);
|
||||
super::super::block::direct_exit_with(&mut asm, self.entry, ExitKind::Direct);
|
||||
if let Some(normal) = normal {
|
||||
asm.bind(normal);
|
||||
asm.dec(Size::Qword, FRAME_LOOP_COUNTER);
|
||||
settle_frame_budget(&mut asm);
|
||||
super::super::block::direct_exit_with(&mut asm, fallthrough, ExitKind::Fallthrough);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn settle_frame_budget(asm: &mut crate::x86_64::asm::Asm<'_>) {
|
||||
asm.pop(Gpr::Rsi);
|
||||
asm.mov_store(Size::Qword, Mem::base(Gpr::Rsi, 0), FRAME_LOOP_COUNTER);
|
||||
asm.pop(FRAME_LOOP_COUNTER);
|
||||
}
|
||||
|
||||
fn direct_ram_loop(
|
||||
instructions: &[Instruction],
|
||||
terminal: Option<&(GuestAddress, Terminator)>,
|
||||
fallthrough: GuestAddress,
|
||||
) -> Option<GuestAddress> {
|
||||
let entry = instructions.first()?.pc;
|
||||
let (branch_pc, Terminator::Branch(Operation::BranchCondition { target, .. })) = terminal?
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
if *target != entry
|
||||
|| instructions.len() > MAX_FRAME_LOOP_INSTRUCTIONS
|
||||
|| branch_pc.0
|
||||
!= entry
|
||||
.0
|
||||
.checked_add(instructions.len() as u64 * INSTRUCTION_BYTES)?
|
||||
|| fallthrough.0 != branch_pc.0.checked_add(INSTRUCTION_BYTES)?
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let mut loads = 0;
|
||||
for (index, instruction) in instructions.iter().enumerate() {
|
||||
if instruction.pc.0 != entry.0.checked_add(index as u64 * INSTRUCTION_BYTES)? {
|
||||
return None;
|
||||
}
|
||||
let operation = &instruction.operation;
|
||||
match operation {
|
||||
Operation::Memory {
|
||||
transfer: MemoryTransfer::Load { signed: false, .. },
|
||||
base: Register::X(_),
|
||||
mode: AddressMode::Offset,
|
||||
..
|
||||
}
|
||||
| Operation::MemoryPair {
|
||||
transfer: MemoryTransfer::Load { signed: false, .. },
|
||||
base: Register::X(_),
|
||||
mode: AddressMode::Offset,
|
||||
..
|
||||
} if analysis::clean_load_effects(operation).is_some() => loads += 1,
|
||||
operation if flags::analyze_value(operation).is_some() => {}
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
// Prefer dense read loops over adding an ABI wrapper to short, occasional
|
||||
// memory edges. Register-only loops have the earlier residency plans.
|
||||
(loads >= 2).then_some(entry)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[test]
|
||||
fn direct_ram_admission_excludes_stack_checks_and_stores() {
|
||||
use crate::{
|
||||
Options, TargetCpu,
|
||||
block::{BlockProfile, CompilationPlan, Features},
|
||||
};
|
||||
|
||||
let options = Options::new(BlockProfile::ORDINARY, TargetCpu::Baseline);
|
||||
let second_load = 0xf940_0423_u32;
|
||||
let subtract = 0xf100_0400;
|
||||
let branch = 0x54ff_ffa1;
|
||||
for (first_load, resident) in [
|
||||
(0xf940_0022_u32, true), // LDR X2, [X1]
|
||||
(0xf940_03e2, false), // LDR X2, [SP]
|
||||
(0xf900_0022, false), // STR X2, [X1]
|
||||
(0xb980_0022, false), // LDRSW X2, [X1]
|
||||
] {
|
||||
let source: Vec<_> = [first_load, second_load, subtract, branch]
|
||||
.into_iter()
|
||||
.flat_map(u32::to_le_bytes)
|
||||
.collect();
|
||||
let plan = CompilationPlan::new(&source, GuestAddress(0x1000), &options)
|
||||
.unwrap()
|
||||
.with_resident_loops();
|
||||
assert_eq!(plan.profile().has(Features::RESIDENT_LOOPS), resident);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn prefix_with_budget(mut native: NativeBlock, base: GuestAddress) -> NativeBlock {
|
||||
let mut code = Code::new();
|
||||
@@ -47,6 +179,7 @@ pub(crate) struct Plan {
|
||||
|
||||
enum Choice {
|
||||
Legacy(LegacyPlan),
|
||||
DirectRam(GuestAddress),
|
||||
Allocated {
|
||||
instructions: Vec<Instruction>,
|
||||
native: NativeBlock,
|
||||
@@ -64,21 +197,40 @@ impl Plan {
|
||||
choice: Choice::Legacy(plan),
|
||||
});
|
||||
}
|
||||
let native = allocated_loop(instructions, terminal, fallthrough)?;
|
||||
Some(Self {
|
||||
choice: Choice::Allocated {
|
||||
let choice = if let Some(native) = allocated_loop(instructions, terminal, fallthrough) {
|
||||
Choice::Allocated {
|
||||
instructions: instructions.to_vec(),
|
||||
native,
|
||||
},
|
||||
})
|
||||
}
|
||||
} else {
|
||||
Choice::DirectRam(direct_ram_loop(instructions, terminal, fallthrough)?)
|
||||
};
|
||||
Some(Self { choice })
|
||||
}
|
||||
|
||||
pub(crate) fn emit(
|
||||
self,
|
||||
instructions: &[Instruction],
|
||||
terminal: Option<&(GuestAddress, Terminator)>,
|
||||
fallthrough: GuestAddress,
|
||||
target: crate::TargetCpu,
|
||||
) -> Result<NativeBlock, super::RegionError> {
|
||||
match self.choice {
|
||||
Choice::Legacy(plan) => plan.emit(instructions),
|
||||
Choice::DirectRam(entry) => {
|
||||
// The caller's immutable parse and source identity own the
|
||||
// words. Recheck the emitter's no-helper contract here too.
|
||||
if direct_ram_loop(instructions, terminal, fallthrough) != Some(entry) {
|
||||
return Err(super::RegionError::ChangedInstructions);
|
||||
}
|
||||
Ok(super::super::block::emit_frame_loop(
|
||||
instructions,
|
||||
terminal,
|
||||
fallthrough,
|
||||
target,
|
||||
entry,
|
||||
))
|
||||
}
|
||||
Choice::Allocated {
|
||||
instructions: planned,
|
||||
native,
|
||||
|
||||
@@ -19,6 +19,96 @@ fn add(destination: Register, source: Register) -> Operation {
|
||||
immediate: 1,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn address_pair_shares_one_literal_and_preserves_distinct_source_rows() {
|
||||
let x0 = Register::X(0);
|
||||
let instructions = [
|
||||
instruction(
|
||||
0,
|
||||
Operation::PcRelative(crate::aarch64::pc_relative::Operand {
|
||||
destination: x0,
|
||||
address: u64::MAX,
|
||||
}),
|
||||
),
|
||||
instruction(1, add(x0, x0)),
|
||||
instruction(2, add(Register::X(3), x0)),
|
||||
];
|
||||
for span in [&instructions[..2], &instructions[..]] {
|
||||
let separate = emit_prefix(span).unwrap();
|
||||
let fused = emit_clean_load_prefix(span, true, None).unwrap();
|
||||
let precise =
|
||||
emit_clean_load_prefix_with(span, crate::x86_64::MemoryChecks::DEFAULT, true, None)
|
||||
.unwrap();
|
||||
assert_eq!(&precise.code[..], &separate.code[..]);
|
||||
assert_eq!(fused.consumed_instructions, span.len());
|
||||
assert_eq!(fused.stats.commits, span.len());
|
||||
assert_eq!(fused.stats.constant_writes, span.len() - 1);
|
||||
assert_eq!(&fused.code[2..10], &[0; 8]); // wrapped address
|
||||
assert_eq!(fused.source_map[..2], [(span[0].pc, 0), (span[1].pc, 10)]);
|
||||
assert!(
|
||||
fused
|
||||
.source_map
|
||||
.windows(2)
|
||||
.all(|pair| pair[0].1 < pair[1].1)
|
||||
);
|
||||
assert!(fused.code.len() < separate.code.len());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hosted_wide_constants_use_one_literal_and_keep_all_source_rows() {
|
||||
let wide = |index, width, kind, immediate, shift| {
|
||||
instruction(
|
||||
index,
|
||||
Operation::MoveWide {
|
||||
width,
|
||||
kind,
|
||||
destination: Register::X(0),
|
||||
immediate,
|
||||
shift,
|
||||
},
|
||||
)
|
||||
};
|
||||
let narrow = [
|
||||
wide(0, Width::W32, WideMove::Zero, 0x1234, 0),
|
||||
wide(1, Width::W32, WideMove::Keep, 0x5678, 16),
|
||||
];
|
||||
let narrow_fused = emit_clean_load_prefix(&narrow, true, None).unwrap();
|
||||
assert_eq!(
|
||||
narrow_fused.source_map,
|
||||
[(narrow[0].pc, 0), (narrow[1].pc, 5)]
|
||||
);
|
||||
assert_eq!(&narrow_fused.code[..5], &[0xb8, 0x34, 0x12, 0x78, 0x56]);
|
||||
assert_eq!(narrow_fused.stats.commits, 2);
|
||||
assert_eq!(narrow_fused.stats.constant_writes, 1);
|
||||
|
||||
let wide = [
|
||||
wide(0, Width::X64, WideMove::Not, 0xabcd, 32),
|
||||
wide(1, Width::X64, WideMove::Keep, 0x1234, 16),
|
||||
wide(2, Width::X64, WideMove::Keep, 0x5678, 48),
|
||||
];
|
||||
let fused = emit_clean_load_prefix(&wide, true, None).unwrap();
|
||||
let precise =
|
||||
emit_clean_load_prefix_with(&wide, crate::x86_64::MemoryChecks::DEFAULT, true, None)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
fused.source_map,
|
||||
[(wide[0].pc, 0), (wide[1].pc, 1), (wide[2].pc, 11)]
|
||||
);
|
||||
assert_eq!(&fused.code[..3], &[0x90, 0x48, 0xb8]);
|
||||
assert_eq!(&fused.code[3..11], &0x5678_5432_1234_ffff_u64.to_le_bytes());
|
||||
assert_eq!(fused.stats.commits, 3);
|
||||
assert_eq!(fused.stats.constant_writes, 1);
|
||||
assert_eq!(precise.stats.constant_writes, 3);
|
||||
assert!(fused.code.len() < precise.code.len());
|
||||
assert!(fused.stats.native_instructions < precise.stats.native_instructions);
|
||||
|
||||
let different_width = [narrow[0].clone(), wide[1].clone()];
|
||||
let separate = emit_clean_load_prefix(&different_width, true, None).unwrap();
|
||||
assert_eq!(separate.stats.constant_writes, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chain_reuses_value_and_settles_once() {
|
||||
let instructions: Vec<_> = (0..256)
|
||||
@@ -1605,14 +1695,18 @@ fn wider_loop_admission_uses_capacity_not_five_participants() {
|
||||
condition: 1,
|
||||
}),
|
||||
);
|
||||
let plan = self_loop::Plan::new(&instructions, Some(&terminal), GuestAddress(0x1024)).unwrap();
|
||||
let native = plan.emit(&instructions).unwrap();
|
||||
let fallthrough = GuestAddress(0x1024);
|
||||
let target = crate::TargetCpu::Baseline;
|
||||
let plan = self_loop::Plan::new(&instructions, Some(&terminal), fallthrough).unwrap();
|
||||
let native = plan
|
||||
.emit(&instructions, Some(&terminal), fallthrough, target)
|
||||
.unwrap();
|
||||
assert_eq!(native.source_map.len(), instructions.len() + 1);
|
||||
assert_eq!(native.source_map[0].1, 0);
|
||||
let changed = [instruction(0, Operation::Nop)];
|
||||
let plan = self_loop::Plan::new(&instructions, Some(&terminal), GuestAddress(0x1024)).unwrap();
|
||||
let plan = self_loop::Plan::new(&instructions, Some(&terminal), fallthrough).unwrap();
|
||||
assert!(matches!(
|
||||
plan.emit(&changed),
|
||||
plan.emit(&changed, Some(&terminal), fallthrough, target),
|
||||
Err(RegionError::ChangedInstructions)
|
||||
));
|
||||
}
|
||||
|
||||
@@ -145,7 +145,10 @@ fn transfer(code: &mut Code, operand: &Operand) {
|
||||
MemoryTransfer::Load { signed, width } => {
|
||||
let size = Size::of(width == Width::X64);
|
||||
let address = Mem::base(Gpr::Rax, 0);
|
||||
let host = code.host(operand.data).unwrap_or(Gpr::Rcx);
|
||||
// The result may replace the address in RAX. This leaves it
|
||||
// available to the next instruction, with no base writeback.
|
||||
let scratch = if code.is_pinned() { Gpr::Rax } else { Gpr::Rcx };
|
||||
let host = code.host(operand.data).unwrap_or(scratch);
|
||||
let mut asm = code.asm();
|
||||
asm.guest_access(|asm| match (operand.bytes, signed) {
|
||||
(1, false) => asm.movzx(size, host, Size::Byte, address),
|
||||
@@ -160,10 +163,10 @@ fn transfer(code: &mut Code, operand: &Operand) {
|
||||
_ => unreachable!("decoder validates signed register-offset size"),
|
||||
});
|
||||
// A load to ZR still accesses memory and can fault.
|
||||
if host == Gpr::Rcx
|
||||
if host == scratch
|
||||
&& let Some(data) = asm.guest(operand.data)
|
||||
{
|
||||
asm.mov_store(Size::Qword, data, Gpr::Rcx);
|
||||
asm.mov_store(Size::Qword, data, host);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@ use super::isa::SimdOpcode as Host;
|
||||
use super::{MemoryChecks, memory_address, memory_writeback};
|
||||
use crate::aarch64::simd::{Comparison, IntegerOperation, Operand};
|
||||
use crate::x86_64::asm::{Code, Gpr, Mem, vector_extensions};
|
||||
use alloc::vec::Vec;
|
||||
pub(in crate::x86_64) mod absolute_selection;
|
||||
mod aes;
|
||||
pub(super) mod arithmetic;
|
||||
@@ -671,11 +670,16 @@ pub(super) fn emit_after(
|
||||
/// destination of a branch-free emission that ends with its commit from
|
||||
/// XMM0; or, after a lane move to a general register, which leaves XMM0
|
||||
/// alone, what it held.
|
||||
pub(super) fn xmm0_after(operand: &Operand, code: &[u8], held: Option<u8>) -> Option<u8> {
|
||||
let committed = |vector: u8| {
|
||||
let mut store = Code::new();
|
||||
commit(&mut store, vector, 0);
|
||||
code.ends_with(&store).then_some(vector)
|
||||
pub(super) fn xmm0_after(
|
||||
scratch: &mut Code,
|
||||
operand: &Operand,
|
||||
code: &[u8],
|
||||
held: Option<u8>,
|
||||
) -> Option<u8> {
|
||||
let mut committed = |vector: u8| {
|
||||
scratch.clear();
|
||||
commit(scratch, vector, 0);
|
||||
code.ends_with(scratch).then_some(vector)
|
||||
};
|
||||
match *operand {
|
||||
Operand::Immediate(crate::aarch64::simd::immediates::Operand::LaneMove(
|
||||
@@ -706,10 +710,10 @@ pub(super) fn xmm0_after(operand: &Operand, code: &[u8], held: Option<u8>) -> Op
|
||||
|
||||
/// [`read_vector`]'s bytes for `vector` into XMM0, which an emission that
|
||||
/// begins with them does not need where XMM0 holds the vector already.
|
||||
pub(super) fn xmm0_load(vector: u8) -> Vec<u8> {
|
||||
let mut load = Code::new();
|
||||
read_vector(&mut load, vector, 0);
|
||||
load.into_bytes()
|
||||
pub(super) fn xmm0_load(scratch: &mut Code, vector: u8) -> &[u8] {
|
||||
scratch.clear();
|
||||
read_vector(scratch, vector, 0);
|
||||
scratch
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -488,6 +488,19 @@ fn emit_predicate(code: &mut Code, operand: &Operand, pc: GuestAddress) {
|
||||
};
|
||||
let mut helper = Vec::new();
|
||||
exception_guard(code, &mut helper);
|
||||
if shape != Shape::Scalar
|
||||
&& operation == Predicate::Equal
|
||||
&& right == CompareSource::Register(left)
|
||||
{
|
||||
// Normal values, both zero signs and infinities equal themselves
|
||||
// without changing FPSR. One guard suffices for the shared source.
|
||||
read_numerical_vector(code, shape, left, LEFT_VECTOR);
|
||||
vector_zero_guard(code, format, shape, &mut helper);
|
||||
helper_section(code, &helper, pc);
|
||||
packed(code, Host::EqualDword, LEFT_VECTOR, LEFT_VECTOR);
|
||||
commit_predicate(code, format, shape, destination, LEFT_VECTOR, false, false);
|
||||
return;
|
||||
}
|
||||
let zero = right == CompareSource::Zero;
|
||||
let merge = shape == Shape::Scalar
|
||||
&& !zero
|
||||
|
||||
@@ -18,7 +18,7 @@ use crate::{
|
||||
aarch64::{
|
||||
Register,
|
||||
floating::{
|
||||
FPCR_EXCEPTION_ENABLE_MASK, FPCR_NEP, Format, INEXACT,
|
||||
FPCR_EXCEPTION_ENABLE_MASK, FPCR_FIZ, FPCR_FZ, FPCR_NEP, Format, INEXACT,
|
||||
integer::{IntegerFormat, IntegerRounding, IntegerWidth},
|
||||
},
|
||||
simd::{
|
||||
@@ -344,9 +344,8 @@ pub(in crate::x86_64) fn from_integer(
|
||||
finish_float(code, operand);
|
||||
}
|
||||
|
||||
fn guard_float_source(code: &mut Code, operand: &IntegerConversion) -> usize {
|
||||
fn guard_float_input(code: &mut Code, operand: &IntegerConversion) -> usize {
|
||||
let shape = operand.integer.shape();
|
||||
read_numerical_vector(code, shape, operand.float, RESULT_VECTOR);
|
||||
if shape == Shape::Scalar {
|
||||
exponent_range(code, operand.format, RESULT_VECTOR, INPUT_MINIMUM_EXPONENT);
|
||||
branch(code, Condition::AboveOrEqual)
|
||||
@@ -526,10 +525,26 @@ pub(in crate::x86_64) fn to_integer(
|
||||
let packed_result = shape != Shape::Scalar
|
||||
&& (signed_single
|
||||
|| vector_extensions::packed_conversion_supported(operand.format, integer, target));
|
||||
let packed_truncate = signed_single
|
||||
&& packed_result
|
||||
&& mode == IntegerRounding::TowardZero
|
||||
&& operand.frac_bits == 0;
|
||||
let mut helper_patches = Vec::new();
|
||||
test_control(code, FPCR_EXCEPTION_ENABLE_MASK);
|
||||
helper_patches.push(branch(code, Condition::NotZero));
|
||||
helper_patches.push(guard_float_source(code, operand));
|
||||
let other_controls = if packed_truncate {
|
||||
read_numerical_vector(code, shape, operand.float, RESULT_VECTOR);
|
||||
// With input flushing disabled, CVTTPS2DQ reports inexact for
|
||||
// fractional inputs and invalid for NaNs or out-of-range values.
|
||||
// Its status distinguishes those cases before any guest commit.
|
||||
test_control(code, FPCR_EXCEPTION_ENABLE_MASK | FPCR_FIZ | FPCR_FZ);
|
||||
Some(branch(code, Condition::NotZero))
|
||||
} else {
|
||||
test_control(code, FPCR_EXCEPTION_ENABLE_MASK);
|
||||
helper_patches.push(branch(code, Condition::NotZero));
|
||||
read_numerical_vector(code, shape, operand.float, RESULT_VECTOR);
|
||||
helper_patches.push(guard_float_input(code, operand));
|
||||
None
|
||||
};
|
||||
let convert = code.len();
|
||||
environment_round(code, rounding(mode));
|
||||
let mut environment_failures = Vec::new();
|
||||
if packed_result {
|
||||
@@ -578,6 +593,15 @@ pub(in crate::x86_64) fn to_integer(
|
||||
}
|
||||
restore_environment(code);
|
||||
}
|
||||
if let Some(other_controls) = other_controls {
|
||||
let check_controls = code.len();
|
||||
resolve(code, other_controls, check_controls);
|
||||
test_control(code, FPCR_EXCEPTION_ENABLE_MASK);
|
||||
helper_patches.push(branch(code, Condition::NotZero));
|
||||
helper_patches.push(guard_float_input(code, operand));
|
||||
let resume = jump(code);
|
||||
resolve(code, resume, convert);
|
||||
}
|
||||
let helper_start = code.len();
|
||||
for patch in helper_patches {
|
||||
resolve(code, patch, helper_start);
|
||||
|
||||
@@ -3,13 +3,13 @@
|
||||
use super::super::isa::ShiftOpcode;
|
||||
use super::numerical::helper_section;
|
||||
use super::numerical::{
|
||||
Condition, INPUT_MINIMUM_EXPONENT, MINIMUM_EXPONENT_VECTOR, RESULT_MINIMUM_EXPONENT, Rounding,
|
||||
branch, clear_scalar, commit_inexact, environment_round, exponent_range,
|
||||
prepare_half_result_range, prepare_vector_input_range, prepare_vector_result_range,
|
||||
read_numerical_vector, reject_other_status, resolve, restore_environment, test_control,
|
||||
vector_exponent_range,
|
||||
ArithmeticOpcode, Condition, INPUT_MINIMUM_EXPONENT, MINIMUM_EXPONENT_VECTOR,
|
||||
RESULT_MINIMUM_EXPONENT, Rounding, branch, clear_scalar, commit_inexact, environment_round,
|
||||
exponent_range, jump, prepare_half_result_range, prepare_vector_input_range,
|
||||
prepare_vector_result_range, read_numerical_vector, reject_other_status, resolve,
|
||||
restore_environment, single_vector_arithmetic, test_control, vector_exponent_range,
|
||||
};
|
||||
use super::{Host, commit, packed, read_vector};
|
||||
use super::{Host, commit, encode::guest, packed, read_vector, vector_offset};
|
||||
use crate::x86_64::asm::FloatLanes;
|
||||
use crate::x86_64::asm::{Alu, Code, Cond, Gpr, Rm, ShiftOp, Size, vector_extensions};
|
||||
use crate::{
|
||||
@@ -52,11 +52,16 @@ const HALF_FIELD_TO_DWORD_TOP: u8 = u32::BITS as u8 - HALF_TO_SINGLE_SIGN_SHIFT
|
||||
const HALF_EXPONENT_TO_DWORD_BOTTOM: u8 = u32::BITS as u8 - HALF_EXPONENT_BITS;
|
||||
const HALF_MAXIMUM_TO_BIAS_BITS: u8 = 2;
|
||||
const SINGLE_BIAS_POSITION: u8 = HALF_TO_SINGLE_BIAS.trailing_zeros() as u8;
|
||||
const HALF_VALIDITY_MASK: u8 = 0x0f;
|
||||
const HALF_EXPONENT_VECTOR: u8 = 2;
|
||||
const HALF_VALIDITY_VECTOR: u8 = 3;
|
||||
const HALF_VALIDITY_MASK: i8 = 0x0f;
|
||||
const HALF_NORMAL_VECTOR: u8 = 2;
|
||||
const HALF_FINITE_VECTOR: u8 = 3;
|
||||
const HALF_MAXIMUM_VECTOR: u8 = 4;
|
||||
const HALF_MINIMUM_VECTOR: u8 = 5;
|
||||
const HALF_ZERO_VECTOR: u8 = 5;
|
||||
const HALF_SCALED_VECTOR: u8 = 6;
|
||||
const HALF_SUBNORMAL_SCALE: u32 = (Format::Single.exponent_bias() + 1
|
||||
- Format::Half.exponent_bias()
|
||||
- Format::Half.fraction_bits())
|
||||
<< Format::Single.fraction_bits();
|
||||
const DOUBLE_TO_SINGLE_DISCARDED_BITS: u8 = 29;
|
||||
const DOUBLE_TO_SINGLE_DISCARDED_MASK: u32 = (1 << DOUBLE_TO_SINGLE_DISCARDED_BITS) - 1;
|
||||
const COMPACT_QWORD_LOW_DWORDS: u8 = 0x88;
|
||||
@@ -211,7 +216,9 @@ fn emit_scalar(
|
||||
scalar_commit(code, operand.destination, destination);
|
||||
}
|
||||
|
||||
fn half_vector_guard(code: &mut Code, helper: &mut Vec<usize>) {
|
||||
/// Branch if any exponent is outside the normal IEEE half range. Keep the
|
||||
/// normal and finite lane masks for the zero and subnormal path.
|
||||
fn half_normal_widening_guard(code: &mut Code) -> usize {
|
||||
packed(
|
||||
code,
|
||||
Host::EqualDword,
|
||||
@@ -219,63 +226,103 @@ fn half_vector_guard(code: &mut Code, helper: &mut Vec<usize>) {
|
||||
HALF_MAXIMUM_VECTOR,
|
||||
);
|
||||
ShiftOpcode::RightDword.emit(code, HALF_MAXIMUM_VECTOR, HALF_EXPONENT_TO_DWORD_BOTTOM);
|
||||
packed(code, Host::Xor, HALF_MINIMUM_VECTOR, HALF_MINIMUM_VECTOR);
|
||||
packed(code, Host::MoveAligned, HALF_EXPONENT_VECTOR, SOURCE_VECTOR);
|
||||
ShiftOpcode::LeftDword.emit(code, HALF_EXPONENT_VECTOR, HALF_FIELD_TO_DWORD_TOP);
|
||||
ShiftOpcode::RightDword.emit(code, HALF_EXPONENT_VECTOR, HALF_EXPONENT_TO_DWORD_BOTTOM);
|
||||
packed(code, Host::MoveAligned, HALF_NORMAL_VECTOR, SOURCE_VECTOR);
|
||||
ShiftOpcode::LeftDword.emit(code, HALF_NORMAL_VECTOR, HALF_FIELD_TO_DWORD_TOP);
|
||||
ShiftOpcode::RightDword.emit(code, HALF_NORMAL_VECTOR, HALF_EXPONENT_TO_DWORD_BOTTOM);
|
||||
packed(
|
||||
code,
|
||||
Host::MoveAligned,
|
||||
HALF_VALIDITY_VECTOR,
|
||||
HALF_FINITE_VECTOR,
|
||||
HALF_MAXIMUM_VECTOR,
|
||||
);
|
||||
packed(
|
||||
code,
|
||||
Host::GreaterDword,
|
||||
HALF_VALIDITY_VECTOR,
|
||||
HALF_EXPONENT_VECTOR,
|
||||
HALF_FINITE_VECTOR,
|
||||
HALF_NORMAL_VECTOR,
|
||||
);
|
||||
packed(
|
||||
code,
|
||||
Host::GreaterDword,
|
||||
HALF_EXPONENT_VECTOR,
|
||||
HALF_MINIMUM_VECTOR,
|
||||
HALF_NORMAL_VECTOR,
|
||||
HALF_ZERO_VECTOR,
|
||||
);
|
||||
packed(code, Host::And, HALF_EXPONENT_VECTOR, HALF_VALIDITY_VECTOR);
|
||||
Host::DwordSignMask.register(code, 0, HALF_EXPONENT_VECTOR, crate::TargetCpu::Baseline);
|
||||
packed(code, Host::And, HALF_NORMAL_VECTOR, HALF_FINITE_VECTOR);
|
||||
Host::DwordSignMask.register(code, 0, HALF_NORMAL_VECTOR, TargetCpu::Baseline);
|
||||
code.asm()
|
||||
.alu_imm8(Alu::Cmp, Size::Dword, Rax, HALF_VALIDITY_MASK as i8);
|
||||
.alu_imm8(Alu::Cmp, Size::Dword, Rax, HALF_VALIDITY_MASK);
|
||||
branch(code, Condition::NotZero)
|
||||
}
|
||||
|
||||
fn add_half_widening_bias(code: &mut Code) {
|
||||
// The guard keeps exponent mask 31; 31 >> 2 gives 7, and 7 << 27 is
|
||||
// exactly the S-vs-H exponent bias adjustment. Reuse that constant.
|
||||
ShiftOpcode::RightDword.emit(code, HALF_MAXIMUM_VECTOR, HALF_MAXIMUM_TO_BIAS_BITS);
|
||||
ShiftOpcode::LeftDword.emit(code, HALF_MAXIMUM_VECTOR, SINGLE_BIAS_POSITION);
|
||||
packed(code, Host::AddDword, SOURCE_VECTOR, HALF_MAXIMUM_VECTOR);
|
||||
}
|
||||
|
||||
fn widen_finite_half(code: &mut Code, helper: &mut Vec<usize>) {
|
||||
// Exponent 31 needs exact completion for AHP, infinity, and NaNs.
|
||||
Host::DwordSignMask.register(code, 0, HALF_FINITE_VECTOR, TargetCpu::Baseline);
|
||||
code.asm()
|
||||
.alu_imm8(Alu::Cmp, Size::Dword, Rax, HALF_VALIDITY_MASK);
|
||||
helper.push(branch(code, Condition::NotZero));
|
||||
// Every 15-bit integer converts exactly to single, and scaling by 2^-24
|
||||
// produces a normal single or +0. The temporary leaves MXCSR untouched
|
||||
// even in lanes where the result comes from the normal representation.
|
||||
ShiftOpcode::LeftDword.emit(code, SOURCE_VECTOR, HALF_FIELD_TO_DWORD_TOP);
|
||||
ShiftOpcode::RightDword.emit(code, SOURCE_VECTOR, HALF_FIELD_TO_DWORD_TOP);
|
||||
packed(
|
||||
code,
|
||||
Host::ConvertPackedDwordToSingle,
|
||||
HALF_SCALED_VECTOR,
|
||||
SOURCE_VECTOR,
|
||||
);
|
||||
code.asm().mov_imm32(Rax, HALF_SUBNORMAL_SCALE);
|
||||
code.asm().movd_to_xmm(HALF_FINITE_VECTOR, Rax);
|
||||
super::shuffle(code, HALF_FINITE_VECTOR, HALF_FINITE_VECTOR, 0);
|
||||
single_vector_arithmetic(
|
||||
code,
|
||||
ArithmeticOpcode::Multiply,
|
||||
HALF_SCALED_VECTOR,
|
||||
HALF_FINITE_VECTOR,
|
||||
);
|
||||
ShiftOpcode::LeftDword.emit(code, SOURCE_VECTOR, HALF_TO_SINGLE_FRACTION_SHIFT);
|
||||
add_half_widening_bias(code);
|
||||
packed(code, Host::And, SOURCE_VECTOR, HALF_NORMAL_VECTOR);
|
||||
packed(code, Host::AndNot, HALF_NORMAL_VECTOR, HALF_SCALED_VECTOR);
|
||||
packed(code, Host::Or, SOURCE_VECTOR, HALF_NORMAL_VECTOR);
|
||||
}
|
||||
|
||||
fn emit_widen_half(code: &mut Code, operand: &PrecisionOperand, upper: bool, pc: GuestAddress) {
|
||||
let mut helper = Vec::new();
|
||||
exception_guard(code, &mut helper);
|
||||
read_vector(code, operand.source, SOURCE_VECTOR);
|
||||
if upper {
|
||||
ShiftOpcode::RightBytes.emit(code, SOURCE_VECTOR, UPPER_QWORD_BYTES);
|
||||
}
|
||||
packed(code, Host::Xor, RESULT_VECTOR, RESULT_VECTOR);
|
||||
packed(code, Host::UnpackLowWord, SOURCE_VECTOR, RESULT_VECTOR);
|
||||
half_vector_guard(code, &mut helper);
|
||||
let part = vector_offset(operand.source) + u32::from(upper) * u32::from(UPPER_QWORD_BYTES);
|
||||
Host::MoveQword.emit(code, SOURCE_VECTOR, guest(part), TargetCpu::Baseline);
|
||||
packed(code, Host::Xor, HALF_ZERO_VECTOR, HALF_ZERO_VECTOR);
|
||||
packed(code, Host::UnpackLowWord, SOURCE_VECTOR, HALF_ZERO_VECTOR);
|
||||
packed(code, Host::MoveAligned, RESULT_VECTOR, SOURCE_VECTOR);
|
||||
// Strip each half sign, align the remaining fields and adjust the bias.
|
||||
let needs_scaling = half_normal_widening_guard(code);
|
||||
// Normal half lanes need only an exponent bias and a field shift.
|
||||
ShiftOpcode::LeftDword.emit(code, SOURCE_VECTOR, HALF_FIELD_TO_DWORD_TOP);
|
||||
ShiftOpcode::RightDword.emit(
|
||||
code,
|
||||
SOURCE_VECTOR,
|
||||
HALF_FIELD_TO_DWORD_TOP - HALF_TO_SINGLE_FRACTION_SHIFT,
|
||||
);
|
||||
// The guard keeps exponent mask 31; 31 >> 2 gives 7, and 7 << 27 is
|
||||
// exactly the S-vs-H exponent bias adjustment. Reuse that constant.
|
||||
ShiftOpcode::RightDword.emit(code, HALF_MAXIMUM_VECTOR, HALF_MAXIMUM_TO_BIAS_BITS);
|
||||
ShiftOpcode::LeftDword.emit(code, HALF_MAXIMUM_VECTOR, SINGLE_BIAS_POSITION);
|
||||
packed(code, Host::AddDword, SOURCE_VECTOR, HALF_MAXIMUM_VECTOR);
|
||||
add_half_widening_bias(code);
|
||||
let normal = jump(code);
|
||||
let other = code.len();
|
||||
resolve(code, needs_scaling, other);
|
||||
widen_finite_half(code, &mut helper);
|
||||
helper_section(code, &helper, pc);
|
||||
let complete = code.len();
|
||||
resolve(code, normal, complete);
|
||||
ShiftOpcode::LeftDword.emit(code, RESULT_VECTOR, HALF_TO_SINGLE_SIGN_SHIFT);
|
||||
ShiftOpcode::RightDword.emit(code, RESULT_VECTOR, DWORD_SIGN_TO_LSB_SHIFT);
|
||||
ShiftOpcode::LeftDword.emit(code, RESULT_VECTOR, DWORD_SIGN_TO_LSB_SHIFT);
|
||||
packed(code, Host::Or, RESULT_VECTOR, SOURCE_VECTOR);
|
||||
helper_section(code, &helper, pc);
|
||||
commit(code, operand.destination, RESULT_VECTOR);
|
||||
}
|
||||
|
||||
|
||||
@@ -93,6 +93,15 @@ struct AbsentGroup {
|
||||
forms: &'static [AbsentForm],
|
||||
}
|
||||
|
||||
/// The slice of one mask's sorted forms that contains its absent
|
||||
/// candidates for one instruction prefix.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
struct AdmitRange {
|
||||
group: u16,
|
||||
first: u16,
|
||||
end: u16,
|
||||
}
|
||||
|
||||
/// `UDF #0`: an absent form's word is UNDEFINED as UDF is (EC 0x00, ISS 0).
|
||||
const UDF: u32 = 0;
|
||||
const NOP: u32 = 0xd503_201f;
|
||||
@@ -116,14 +125,16 @@ pub struct AdmitTable {
|
||||
withheld: u64,
|
||||
/// The chip's features without them.
|
||||
presented: u64,
|
||||
/// The range of `groups` for each prefix, and its end.
|
||||
starts: Vec<u32>,
|
||||
groups: Vec<u16>,
|
||||
/// One packed start and end in `groups` per prefix. Zero preserves the
|
||||
/// word, and `UNALLOCATED` returns UDF without searching any groups.
|
||||
spans: Vec<u32>,
|
||||
groups: Vec<AdmitRange>,
|
||||
}
|
||||
|
||||
impl AdmitTable {
|
||||
const SHIFT: u32 = 21;
|
||||
const PREFIXES: usize = 1 << (32 - Self::SHIFT);
|
||||
const UNALLOCATED: u32 = u32::MAX;
|
||||
|
||||
/// The immutable chip policy used to construct this table.
|
||||
pub fn chip(&self) -> Chip {
|
||||
@@ -133,17 +144,22 @@ impl AdmitTable {
|
||||
/// [`Chip::admit`] of the table's chip, where the forms of the features
|
||||
/// its PE withholds are absent too.
|
||||
pub fn admit(&self, word: u32) -> u32 {
|
||||
if unallocated_group(word) {
|
||||
return UDF;
|
||||
}
|
||||
let prefix = (word >> Self::SHIFT) as usize;
|
||||
let groups = &self.groups[self.starts[prefix] as usize..self.starts[prefix + 1] as usize];
|
||||
let span = match self.spans[prefix] {
|
||||
0 => return word,
|
||||
Self::UNALLOCATED => return UDF,
|
||||
span => span,
|
||||
};
|
||||
let start = (span & u32::from(u16::MAX)) as usize;
|
||||
let end = (span >> u16::BITS) as usize;
|
||||
self.chip.admit_in(
|
||||
word,
|
||||
self.presented,
|
||||
groups
|
||||
.iter()
|
||||
.map(|&group| &forms::ABSENT[usize::from(group)]),
|
||||
self.groups[start..end].iter().map(|range| {
|
||||
let group = &forms::ABSENT[usize::from(range.group)];
|
||||
let forms = &group.forms[usize::from(range.first)..usize::from(range.end)];
|
||||
(group.mask, forms)
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -229,14 +245,30 @@ impl Chip {
|
||||
// Every prefix that agrees with a form on the group's mask.
|
||||
let free = !(group.mask >> AdmitTable::SHIFT) & PREFIX;
|
||||
let absent =
|
||||
|form: &&AbsentForm| form.chips & bit != 0 || !met(form.requires, presented);
|
||||
for form in group.forms.iter().filter(absent) {
|
||||
|form: &AbsentForm| form.chips & bit != 0 || !met(form.requires, presented);
|
||||
for (position, form) in group
|
||||
.forms
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, form)| absent(form))
|
||||
{
|
||||
let end = u16::try_from(position + 1).expect("form ranges fit in u16");
|
||||
let fixed = form.value >> AdmitTable::SHIFT & !free;
|
||||
let mut varying = free;
|
||||
loop {
|
||||
let groups: &mut Vec<u16> = &mut by_prefix[(fixed | varying) as usize];
|
||||
if groups.last() != Some(&index) {
|
||||
groups.push(index);
|
||||
let groups: &mut Vec<AdmitRange> = &mut by_prefix[(fixed | varying) as usize];
|
||||
if let Some(last) = groups.last_mut()
|
||||
&& last.group == index
|
||||
{
|
||||
// The slice can include present forms between its
|
||||
// first and last absent candidates.
|
||||
last.end = end;
|
||||
} else {
|
||||
groups.push(AdmitRange {
|
||||
group: index,
|
||||
first: end - 1,
|
||||
end,
|
||||
});
|
||||
}
|
||||
if varying == 0 {
|
||||
break;
|
||||
@@ -245,18 +277,26 @@ impl Chip {
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut starts = Vec::with_capacity(AdmitTable::PREFIXES + 1);
|
||||
let mut spans = Vec::with_capacity(AdmitTable::PREFIXES);
|
||||
let mut groups = Vec::new();
|
||||
for prefix in by_prefix {
|
||||
starts.push(groups.len() as u32);
|
||||
groups.extend(prefix);
|
||||
for (prefix, matches) in by_prefix.into_iter().enumerate() {
|
||||
let span = if unallocated_group((prefix as u32) << AdmitTable::SHIFT) {
|
||||
AdmitTable::UNALLOCATED
|
||||
} else if matches.is_empty() {
|
||||
0
|
||||
} else {
|
||||
let start = groups.len() as u32;
|
||||
groups.extend(matches);
|
||||
let end = u16::try_from(groups.len()).expect("absent-form group spans fit in u16");
|
||||
start | (u32::from(end) << u16::BITS)
|
||||
};
|
||||
spans.push(span);
|
||||
}
|
||||
starts.push(groups.len() as u32);
|
||||
Ok(AdmitTable {
|
||||
chip: self,
|
||||
withheld,
|
||||
presented,
|
||||
starts,
|
||||
spans,
|
||||
groups,
|
||||
})
|
||||
}
|
||||
@@ -268,7 +308,11 @@ impl Chip {
|
||||
if unallocated_group(word) {
|
||||
return UDF;
|
||||
}
|
||||
self.admit_in(word, self.features(), forms::ABSENT.iter())
|
||||
self.admit_in(
|
||||
word,
|
||||
self.features(),
|
||||
forms::ABSENT.iter().map(|group| (group.mask, group.forms)),
|
||||
)
|
||||
}
|
||||
|
||||
/// The first of `groups` holding a form that `word` is and that this
|
||||
@@ -277,17 +321,14 @@ impl Chip {
|
||||
self,
|
||||
word: u32,
|
||||
presented: u64,
|
||||
groups: impl Iterator<Item = &'a AbsentGroup>,
|
||||
groups: impl Iterator<Item = (u32, &'a [AbsentForm])>,
|
||||
) -> u32 {
|
||||
let bit = 1u8 << self as u8;
|
||||
for group in groups {
|
||||
let Ok(index) = group
|
||||
.forms
|
||||
.binary_search_by_key(&(word & group.mask), |form| form.value)
|
||||
else {
|
||||
for (mask, forms) in groups {
|
||||
let Ok(index) = forms.binary_search_by_key(&(word & mask), |form| form.value) else {
|
||||
continue;
|
||||
};
|
||||
let form = &group.forms[index];
|
||||
let form = &forms[index];
|
||||
let kept = form.unless.iter().any(|(mask, value, chips, requires)| {
|
||||
chips & bit != 0 && word & mask == *value && met(requires, presented)
|
||||
});
|
||||
@@ -319,7 +360,6 @@ impl Chip {
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let single = ((word & checks::IMM5) >> checks::IMM5.trailing_zeros()).count_ones() == 1;
|
||||
return group.forms[index]
|
||||
.variants
|
||||
.iter()
|
||||
@@ -327,7 +367,9 @@ impl Chip {
|
||||
variant.chips & bit != 0
|
||||
&& match variant.class {
|
||||
WordClass::Any => true,
|
||||
WordClass::SingleImm5(wanted) => wanted == single,
|
||||
WordClass::SingleImm5(wanted) => {
|
||||
wanted == (word & checks::IMM5).is_power_of_two()
|
||||
}
|
||||
}
|
||||
})
|
||||
.map_or(&[], |variant| variant.checks);
|
||||
|
||||
@@ -68,6 +68,9 @@ pub struct InterruptLatch {
|
||||
asserted: BTreeSet<Wire>,
|
||||
aic_inputs: Vec<(AicInput, bool)>,
|
||||
}
|
||||
/// Retain space for ordinary wire traffic without keeping a large burst.
|
||||
const RETAINED_AIC_INPUTS: usize = 32;
|
||||
|
||||
impl InterruptLatch {
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
@@ -76,6 +79,21 @@ impl InterruptLatch {
|
||||
pub fn take_aic_inputs(&mut self) -> Vec<(AicInput, bool)> {
|
||||
core::mem::take(&mut self.aic_inputs)
|
||||
}
|
||||
|
||||
/// Move queued AIC input changes in order into an existing destination.
|
||||
pub fn append_aic_inputs<T>(
|
||||
&mut self,
|
||||
destination: &mut Vec<T>,
|
||||
map: impl FnMut((AicInput, bool)) -> T,
|
||||
) {
|
||||
if self.aic_inputs.is_empty() {
|
||||
return;
|
||||
}
|
||||
destination.extend(self.aic_inputs.drain(..).map(map));
|
||||
if self.aic_inputs.capacity() > RETAINED_AIC_INPUTS {
|
||||
self.aic_inputs = Vec::new();
|
||||
}
|
||||
}
|
||||
#[cfg(any(test, feature = "test-support"))]
|
||||
pub fn is_asserted(&self, wire: Wire) -> bool {
|
||||
self.asserted.contains(&wire)
|
||||
@@ -147,4 +165,30 @@ mod tests {
|
||||
assert_eq!(latch.take_aic_inputs(), vec![(uart, true), (uart, false)]);
|
||||
assert!(latch.take_aic_inputs().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn appending_aic_inputs_reuses_small_buffers_and_releases_large_ones() {
|
||||
let mut latch = InterruptLatch::new();
|
||||
let input = AicInput::new(0, 739);
|
||||
let mut output = vec![(input, false)];
|
||||
latch.set_level(Wire::Aic(input), true);
|
||||
let capacity = latch.aic_inputs.capacity();
|
||||
assert_ne!(capacity, 0);
|
||||
latch.append_aic_inputs(&mut output, core::convert::identity);
|
||||
assert_eq!(output, [(input, false), (input, true)]);
|
||||
assert_eq!(latch.aic_inputs.capacity(), capacity);
|
||||
|
||||
for index in 0..=RETAINED_AIC_INPUTS {
|
||||
latch.set_level(Wire::Aic(input), index % 2 != 0);
|
||||
}
|
||||
output.clear();
|
||||
latch.append_aic_inputs(&mut output, core::convert::identity);
|
||||
assert!(
|
||||
output
|
||||
.iter()
|
||||
.copied()
|
||||
.eq((0..=RETAINED_AIC_INPUTS).map(|index| (input, index % 2 != 0)))
|
||||
);
|
||||
assert_eq!(latch.aic_inputs.capacity(), 0);
|
||||
}
|
||||
}
|
||||
@@ -727,7 +727,26 @@ impl Iterator for Plan {
|
||||
}
|
||||
}
|
||||
|
||||
type Commands = core::iter::Peekable<core::iter::Flatten<alloc::vec::IntoIter<Plan>>>;
|
||||
/// The current request's plan lives inline. Only a batch has further plans
|
||||
/// to allocate, and no caller consumes plans from the back.
|
||||
struct Plans {
|
||||
current: Option<Plan>,
|
||||
rest: alloc::vec::IntoIter<Plan>,
|
||||
}
|
||||
|
||||
impl Iterator for Plans {
|
||||
type Item = (usize, Command);
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
while let Some(plan) = &mut self.current {
|
||||
if let Some(command) = plan.next() {
|
||||
return Some(command);
|
||||
}
|
||||
self.current = self.rest.next();
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
impl Request {
|
||||
/// The commands that carry out `self` on a device with `identity`'s
|
||||
@@ -769,28 +788,80 @@ pub type Finished = Result<Option<Vec<u8>>, BlockError>;
|
||||
/// flush alone once they completed, as Linux's flush sequence orders them.
|
||||
/// A device that runs no queued commands runs each where it is polled.
|
||||
pub struct Submission {
|
||||
commands: Commands,
|
||||
/// The started commands: each tag, a read's offset in the data, and
|
||||
/// whether it is a flush.
|
||||
running: Vec<(u32, usize, bool)>,
|
||||
data: Option<Vec<u8>>,
|
||||
commands: core::iter::Peekable<Plans>,
|
||||
running: Running,
|
||||
read: Option<ReadData>,
|
||||
failed: Option<BlockError>,
|
||||
}
|
||||
|
||||
/// A started command's tag, a read's offset in the data, and whether the
|
||||
/// command is a flush.
|
||||
type InFlight = (u32, usize, bool);
|
||||
|
||||
/// One command is enough for a request that fits the device's transfer
|
||||
/// limit. Only overlapping commands require a queue allocation.
|
||||
enum Running {
|
||||
One(Option<InFlight>),
|
||||
Many(Vec<InFlight>),
|
||||
}
|
||||
|
||||
impl Running {
|
||||
fn as_slice(&self) -> &[InFlight] {
|
||||
match self {
|
||||
Self::One(command) => command.as_slice(),
|
||||
Self::Many(commands) => commands,
|
||||
}
|
||||
}
|
||||
|
||||
fn push(&mut self, command: InFlight) {
|
||||
match self {
|
||||
Self::One(Some(first)) => *self = Self::Many(vec![*first, command]),
|
||||
Self::One(slot) => *slot = Some(command),
|
||||
Self::Many(commands) => commands.push(command),
|
||||
}
|
||||
}
|
||||
|
||||
fn remove(&mut self, index: usize) {
|
||||
match self {
|
||||
Self::One(slot) => {
|
||||
debug_assert_eq!(index, 0);
|
||||
*slot = None;
|
||||
}
|
||||
Self::Many(commands) => {
|
||||
commands.swap_remove(index);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A read can take ownership of a whole command result. Only a split read
|
||||
/// needs an assembly buffer.
|
||||
struct ReadData {
|
||||
bytes: usize,
|
||||
data: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
/// New commands admitted by one polling call, including synchronous execution.
|
||||
const POLL_ADMISSIONS: usize = 64;
|
||||
|
||||
impl Submission {
|
||||
pub fn new(request: Request, identity: &Identity) -> Result<Self, BlockError> {
|
||||
let plan = Plan::new(request, identity)?;
|
||||
let data = match &plan.request {
|
||||
Request::Read { bytes, .. } => Some(vec![0; *bytes]),
|
||||
let read = match &plan.request {
|
||||
Request::Read { bytes, .. } => Some(ReadData {
|
||||
bytes: *bytes,
|
||||
data: None,
|
||||
}),
|
||||
_ => None,
|
||||
};
|
||||
Ok(Self {
|
||||
commands: vec![plan].into_iter().flatten().peekable(),
|
||||
running: Vec::new(),
|
||||
data,
|
||||
commands: Plans {
|
||||
current: Some(plan),
|
||||
rest: Default::default(),
|
||||
}
|
||||
.peekable(),
|
||||
running: Running::One(None),
|
||||
read,
|
||||
failed: None,
|
||||
})
|
||||
}
|
||||
@@ -801,24 +872,33 @@ impl Submission {
|
||||
if let [Request::Read { .. }] = requests.as_slice() {
|
||||
return Self::new(requests.into_iter().next().unwrap(), identity);
|
||||
}
|
||||
let mut plans = Vec::with_capacity(requests.len());
|
||||
for request in requests {
|
||||
let plan = |request| {
|
||||
if let Request::Read { .. } = request {
|
||||
return Err(BlockError::Protocol("a read in a batch of requests"));
|
||||
}
|
||||
plans.push(Plan::new(request, identity)?);
|
||||
Plan::new(request, identity)
|
||||
};
|
||||
let mut requests = requests.into_iter();
|
||||
let current = requests.next().map(plan).transpose()?;
|
||||
let mut rest = Vec::with_capacity(requests.len());
|
||||
for request in requests {
|
||||
rest.push(plan(request)?);
|
||||
}
|
||||
Ok(Self {
|
||||
commands: plans.into_iter().flatten().peekable(),
|
||||
running: Vec::new(),
|
||||
data: None,
|
||||
commands: Plans {
|
||||
current,
|
||||
rest: rest.into_iter(),
|
||||
}
|
||||
.peekable(),
|
||||
running: Running::One(None),
|
||||
read: None,
|
||||
failed: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The commands the device runs for this submission now.
|
||||
pub fn started(&self) -> usize {
|
||||
self.running.len()
|
||||
self.running.as_slice().len()
|
||||
}
|
||||
|
||||
/// Collect the device's completions of this request's commands and
|
||||
@@ -831,13 +911,12 @@ impl Submission {
|
||||
/// entered synchronous execution may take longer than the caller's slice.
|
||||
pub fn poll(&mut self, device: &mut (impl BlockDevice + ?Sized)) -> Option<Finished> {
|
||||
let mut index = 0;
|
||||
while index < self.running.len() {
|
||||
let (tag, offset, _) = self.running[index];
|
||||
while let Some(&(tag, offset, _)) = self.running.as_slice().get(index) {
|
||||
let Some(result) = device.finish(tag) else {
|
||||
index += 1;
|
||||
continue;
|
||||
};
|
||||
self.running.swap_remove(index);
|
||||
self.running.remove(index);
|
||||
self.completed(offset, result);
|
||||
}
|
||||
let depth = device.depth();
|
||||
@@ -848,11 +927,12 @@ impl Submission {
|
||||
break;
|
||||
};
|
||||
let flush = matches!(command, Command::Flush);
|
||||
if (flush && !self.running.is_empty()) || self.running.iter().any(|run| run.2) {
|
||||
let running = self.running.as_slice();
|
||||
if (flush && !running.is_empty()) || running.iter().any(|run| run.2) {
|
||||
break;
|
||||
}
|
||||
if depth == 0 {
|
||||
if !self.running.is_empty() {
|
||||
if !running.is_empty() {
|
||||
break;
|
||||
}
|
||||
let (offset, command) = self.commands.next().unwrap();
|
||||
@@ -861,7 +941,7 @@ impl Submission {
|
||||
self.completed(offset, result);
|
||||
continue;
|
||||
}
|
||||
if self.running.len() >= capacity || !device.room() {
|
||||
if running.len() >= capacity || !device.room() {
|
||||
break;
|
||||
}
|
||||
let (offset, command) = self.commands.next().unwrap();
|
||||
@@ -871,20 +951,30 @@ impl Submission {
|
||||
Err(error) => self.failed = Some(error),
|
||||
}
|
||||
}
|
||||
if !self.running.is_empty() || (self.failed.is_none() && self.commands.peek().is_some()) {
|
||||
if !self.running.as_slice().is_empty()
|
||||
|| (self.failed.is_none() && self.commands.peek().is_some())
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some(match self.failed.take() {
|
||||
Some(error) => Err(error),
|
||||
None => Ok(self.data.take()),
|
||||
None => Ok(self
|
||||
.read
|
||||
.take()
|
||||
.map(|read| read.data.unwrap_or_else(|| vec![0; read.bytes]))),
|
||||
})
|
||||
}
|
||||
|
||||
fn completed(&mut self, offset: usize, result: Finished) {
|
||||
match result {
|
||||
Ok(Some(bytes)) => {
|
||||
if let Some(data) = self.data.as_mut() {
|
||||
data[offset..offset + bytes.len()].copy_from_slice(&bytes);
|
||||
if let Some(read) = &mut self.read {
|
||||
if read.data.is_none() && offset == 0 && bytes.len() == read.bytes {
|
||||
read.data = Some(bytes);
|
||||
} else {
|
||||
let data = read.data.get_or_insert_with(|| vec![0; read.bytes]);
|
||||
data[offset..offset + bytes.len()].copy_from_slice(&bytes);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(None) => {}
|
||||
|
||||
@@ -38,12 +38,13 @@ pub(super) struct Requests {
|
||||
pub(super) busy_since: u64,
|
||||
}
|
||||
|
||||
/// A device command and the tickets merged into it: each ticket's offset
|
||||
/// and length in a read's data. What the accounting counts it as, and when
|
||||
/// its first ticket was submitted.
|
||||
/// A device command and its first ticket and read length. Additional tickets
|
||||
/// carry their offset and length in the read's data. What the accounting
|
||||
/// counts the command as, and when its first ticket was submitted.
|
||||
pub(super) struct Merged {
|
||||
pub(super) tag: u32,
|
||||
pub(super) tickets: Vec<(u32, usize, usize)>,
|
||||
pub(super) first: (u32, usize),
|
||||
pub(super) more: Vec<(u32, usize, usize)>,
|
||||
pub(super) accounted: (Direction, u64),
|
||||
pub(super) submitted: u64,
|
||||
}
|
||||
@@ -231,14 +232,30 @@ impl Held<'_> {
|
||||
work.finishes = work.finishes.saturating_add(1);
|
||||
let merged = self.requests().running.swap_remove(index);
|
||||
let now = crate::Clock::ticks();
|
||||
let merges = merged.tickets.len() as u64 - 1;
|
||||
let merges = merged.more.len() as u64;
|
||||
self.account(merged.accounted, merges, merged.submitted, now);
|
||||
let requests = self.requests();
|
||||
if requests.running.is_empty() {
|
||||
requests.stats.busy += now.wrapping_sub(requests.busy_since);
|
||||
}
|
||||
let finished = &mut self.requests().finished;
|
||||
for (ticket, offset, bytes) in merged.tickets {
|
||||
let (ticket, bytes) = merged.first;
|
||||
if merged.more.is_empty() {
|
||||
let result = result.and_then(|data| match data {
|
||||
Some(data) if data.len() < bytes => {
|
||||
Err(BlockError::Protocol("a read returned too little data"))
|
||||
}
|
||||
Some(mut data) => {
|
||||
data.truncate(bytes);
|
||||
Ok(Some(data))
|
||||
}
|
||||
None => Ok(None),
|
||||
});
|
||||
finished.insert(ticket, result);
|
||||
continue;
|
||||
}
|
||||
let tickets = core::iter::once((ticket, 0, bytes)).chain(merged.more);
|
||||
for (ticket, offset, bytes) in tickets {
|
||||
let part = match &result {
|
||||
Ok(Some(data)) => Ok(Some(data[offset..offset + bytes].to_vec())),
|
||||
other => other.clone(),
|
||||
@@ -246,6 +263,9 @@ impl Held<'_> {
|
||||
finished.insert(ticket, part);
|
||||
}
|
||||
}
|
||||
if self.requests().waiting.is_empty() {
|
||||
return;
|
||||
}
|
||||
let queued = self.depth() > 0;
|
||||
let (block, limit) = {
|
||||
let identity = self.identity();
|
||||
@@ -268,13 +288,13 @@ impl Held<'_> {
|
||||
Command::Read { bytes, .. } => *bytes,
|
||||
_ => 0,
|
||||
};
|
||||
let mut tickets = vec![(ticket, 0, first)];
|
||||
let mut more = Vec::new();
|
||||
let mut offset = first;
|
||||
while let Some((next, following, _)) = self.requests().waiting.front() {
|
||||
let Some(bytes) = merge(&mut command, following, block, limit) else {
|
||||
break;
|
||||
};
|
||||
tickets.push((*next, offset, bytes));
|
||||
more.push((*next, offset, bytes));
|
||||
offset += bytes;
|
||||
self.requests().waiting.pop_front();
|
||||
}
|
||||
@@ -288,14 +308,17 @@ impl Held<'_> {
|
||||
}
|
||||
requests.running.push(Merged {
|
||||
tag,
|
||||
tickets,
|
||||
first: (ticket, first),
|
||||
more,
|
||||
accounted,
|
||||
submitted,
|
||||
});
|
||||
requests.stats.deepest = requests.stats.deepest.max(requests.running.len());
|
||||
}
|
||||
Err(error) => {
|
||||
for (ticket, ..) in tickets {
|
||||
for ticket in
|
||||
core::iter::once(ticket).chain(more.into_iter().map(|(id, ..)| id))
|
||||
{
|
||||
self.requests().finished.insert(ticket, Err(error.clone()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@ struct Delayed {
|
||||
released: Rc<Cell<usize>>,
|
||||
reads: Rc<Cell<usize>>,
|
||||
given: Rc<core::cell::RefCell<Vec<Command>>>,
|
||||
last_read_address: Rc<Cell<usize>>,
|
||||
}
|
||||
|
||||
type Probes = (
|
||||
@@ -37,6 +38,7 @@ impl Delayed {
|
||||
released: probes.0.clone(),
|
||||
reads: probes.1.clone(),
|
||||
given: probes.2.clone(),
|
||||
last_read_address: Default::default(),
|
||||
};
|
||||
(delayed, probes)
|
||||
}
|
||||
@@ -48,6 +50,9 @@ impl Delayed {
|
||||
};
|
||||
self.released.set(self.released.get() - 1);
|
||||
let result = self.disk.execute(command);
|
||||
if let Ok(Some(data)) = &result {
|
||||
self.last_read_address.set(data.as_ptr() as usize);
|
||||
}
|
||||
self.done.insert(tag, result);
|
||||
}
|
||||
}
|
||||
@@ -211,6 +216,31 @@ fn windows_queue_commands_and_whichever_looks_moves_the_queue_on() {
|
||||
assert!(a.start(outside).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_single_queued_read_returns_the_devices_original_buffer() {
|
||||
let data: Vec<u8> = (0..4096).map(|byte| (byte % 251) as u8).collect();
|
||||
let mut ram = RamDisk::new("single", 16, 512);
|
||||
ram.write(1, &data).unwrap();
|
||||
let (delayed, (released, _, _)) = Delayed::new(ram, 1);
|
||||
let address = delayed.last_read_address.clone();
|
||||
let disk = Shared::new(Box::new(delayed));
|
||||
let mut window = disk.whole();
|
||||
let mut read = Submission::new(
|
||||
Request::Read {
|
||||
lba: 1,
|
||||
bytes: data.len(),
|
||||
},
|
||||
window.identity(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(read.poll(&mut window), None);
|
||||
released.set(1);
|
||||
let result = read.poll(&mut window).unwrap().unwrap().unwrap();
|
||||
assert_eq!(result, data);
|
||||
assert_eq!(result.as_ptr() as usize, address.get());
|
||||
assert_eq!(read.poll(&mut window), Some(Ok(None)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bulk_submission_respects_window_capacity() {
|
||||
let blocks = 2 * WINDOW_DEPTH + 3;
|
||||
|
||||
@@ -75,6 +75,19 @@ pub enum WakeState {
|
||||
pub unsafe trait Timer {
|
||||
fn check(&self) -> Result<(), Error>;
|
||||
fn wait_us(&self, microseconds: u64) -> Result<(), Error>;
|
||||
/// Start a nonblocking minimum interval, when the same source can retain
|
||||
/// and revalidate it. A returned interval has the same physical guarantee
|
||||
/// as `wait_us` and owns the source through every poll.
|
||||
fn begin_interval(
|
||||
&self,
|
||||
_microseconds: u64,
|
||||
) -> Result<Option<alloc::boxed::Box<dyn Interval>>, Error> {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
pub trait Interval {
|
||||
/// True only after the retained source proves the requested real interval.
|
||||
fn elapsed(&self) -> Result<bool, Error>;
|
||||
}
|
||||
// SAFETY: a shared timer is the same timer.
|
||||
unsafe impl<T: Timer + ?Sized> Timer for alloc::rc::Rc<T> {
|
||||
@@ -84,6 +97,12 @@ unsafe impl<T: Timer + ?Sized> Timer for alloc::rc::Rc<T> {
|
||||
fn wait_us(&self, microseconds: u64) -> Result<(), Error> {
|
||||
(**self).wait_us(microseconds)
|
||||
}
|
||||
fn begin_interval(
|
||||
&self,
|
||||
microseconds: u64,
|
||||
) -> Result<Option<alloc::boxed::Box<dyn Interval>>, Error> {
|
||||
(**self).begin_interval(microseconds)
|
||||
}
|
||||
}
|
||||
/// The original endpoint configuration, platform power/exclusion and timing
|
||||
/// owners. Access is withheld throughout D3hot or an uncertain transition.
|
||||
|
||||
@@ -124,6 +124,16 @@ called(LLVMValueRef fn)
|
||||
return false;
|
||||
}
|
||||
|
||||
bool
|
||||
stela_air_has_defined_calls(LLVMModuleRef module)
|
||||
{
|
||||
for (LLVMValueRef fn = LLVMGetFirstFunction(module); fn; fn = LLVMGetNextFunction(fn)) {
|
||||
if (stela_air_defined_function(fn) && called(fn))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static unsigned
|
||||
attribute(const char *name)
|
||||
{
|
||||
@@ -288,19 +298,39 @@ unroll(struct stela_air_metadata *m, LLVMValueRef entry, unsigned depth, unsigne
|
||||
}
|
||||
}
|
||||
|
||||
bool
|
||||
stela_air_inline_calls(struct stela_air_metadata *m, LLVMValueRef entry,
|
||||
unsigned max_call_stack_depth, unsigned max_instructions)
|
||||
/* A branch can make a direct call unreachable after specialization. */
|
||||
static bool
|
||||
can_prune_calls(LLVMValueRef entry)
|
||||
{
|
||||
bool branch = false, call = false;
|
||||
for (LLVMBasicBlockRef block = LLVMGetFirstBasicBlock(entry); block;
|
||||
block = LLVMGetNextBasicBlock(block)) {
|
||||
LLVMOpcode opcode = LLVMGetInstructionOpcode(LLVMGetBasicBlockTerminator(block));
|
||||
branch |= opcode == LLVMCondBr || opcode == LLVMSwitch;
|
||||
for (LLVMValueRef inst = LLVMGetFirstInstruction(block); inst && !call;
|
||||
inst = LLVMGetNextInstruction(inst))
|
||||
call = defined_callee(inst) != NULL;
|
||||
if (branch && call)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static bool
|
||||
inline_calls(struct stela_air_metadata *m, LLVMValueRef entry, unsigned max_call_stack_depth,
|
||||
unsigned max_instructions, LLVMValueRef specialized, bool *folded)
|
||||
{
|
||||
struct hash_table *states = _mesa_pointer_hash_table_create(NULL);
|
||||
if (!states)
|
||||
return fail(m, STELA_AIR_ALLOCATION, "call graph allocation failed");
|
||||
bool walked = true, inlined = false, recursive = false;
|
||||
for (LLVMValueRef fn = LLVMGetFirstFunction(m->module); fn && walked; fn = LLVMGetNextFunction(fn)) {
|
||||
bool cyclic;
|
||||
m->unoptimized |= LLVMGetEnumAttributeAtIndex(fn, LLVMAttributeFunctionIndex,
|
||||
attribute("optnone")) != NULL;
|
||||
walked = !stela_air_defined_function(fn) || visit(m, states, fn, true, 0, &cyclic);
|
||||
if (!stela_air_defined_function(fn))
|
||||
continue;
|
||||
bool cyclic;
|
||||
walked = visit(m, states, fn, true, 0, &cyclic);
|
||||
recursive |= walked && fn == entry && cyclic;
|
||||
}
|
||||
for (LLVMValueRef fn = LLVMGetFirstFunction(m->module); fn && walked; fn = LLVMGetNextFunction(fn)) {
|
||||
@@ -310,12 +340,36 @@ stela_air_inline_calls(struct stela_air_metadata *m, LLVMValueRef entry,
|
||||
inline_always(fn);
|
||||
inlined = true;
|
||||
}
|
||||
/* Keep the original graph's depth and cycle checks before pruning calls. */
|
||||
struct hash_entry *state = walked && inlined && specialized && !m->unoptimized ?
|
||||
_mesa_hash_table_search(states, specialized) : NULL;
|
||||
bool fold = state && (uintptr_t)state->data == ACYCLIC && can_prune_calls(specialized);
|
||||
_mesa_hash_table_destroy(states, NULL);
|
||||
if (!walked || (inlined && !run_inliner(m)))
|
||||
if (!walked)
|
||||
return false;
|
||||
if (fold) {
|
||||
*folded = true;
|
||||
if (!stela_air_fold_constants(m, specialized))
|
||||
return false;
|
||||
}
|
||||
if (inlined && !run_inliner(m))
|
||||
return false;
|
||||
return !recursive || unroll(m, entry, max_call_stack_depth, max_instructions);
|
||||
}
|
||||
|
||||
bool
|
||||
stela_air_inline_calls(struct stela_air_metadata *m, LLVMValueRef entry,
|
||||
unsigned max_call_stack_depth, unsigned max_instructions)
|
||||
{
|
||||
return inline_calls(m, entry, max_call_stack_depth, max_instructions, NULL, NULL);
|
||||
}
|
||||
|
||||
bool
|
||||
stela_air_inline_specialized_calls(struct stela_air_metadata *m, LLVMValueRef entry, bool *folded)
|
||||
{
|
||||
return inline_calls(m, NULL, 0, 0, entry, folded);
|
||||
}
|
||||
|
||||
/* Apple's compiler declares a visible function another module defines as
|
||||
* NAME.MTL_VISIBLE_FN_REF, and lists the NAME it means. Under that name the
|
||||
* linker resolves it as it does any declaration. */
|
||||
|
||||
@@ -10,6 +10,9 @@
|
||||
* refuses its calls as AIR's. */
|
||||
bool stela_air_defined_function(LLVMValueRef fn);
|
||||
|
||||
/* Whether module has a direct call to one of its defined AIR functions. */
|
||||
bool stela_air_has_defined_calls(LLVMModuleRef module);
|
||||
|
||||
/* Links modules into m's, after checking each is AIR compiled as m's was,
|
||||
* so one profile translates them, and specializing each with its own
|
||||
* function constant values. m's own are specialized first, since linking
|
||||
@@ -33,4 +36,9 @@ bool stela_air_dispatch_tables(struct stela_air_metadata *m,
|
||||
* recursion stay. */
|
||||
bool stela_air_inline_calls(struct stela_air_metadata *m, LLVMValueRef entry,
|
||||
unsigned max_call_stack_depth, unsigned max_instructions);
|
||||
/* The first inlining pass with an optional specialized entry. After checking
|
||||
* the original graph, it folds constants in an acyclic entry before expanding
|
||||
* its calls, setting *folded when that pass runs. */
|
||||
bool stela_air_inline_specialized_calls(struct stela_air_metadata *m, LLVMValueRef entry,
|
||||
bool *folded);
|
||||
#endif
|
||||
@@ -22,6 +22,7 @@
|
||||
* paths a false constant disables are removed rather than translated. */
|
||||
#define STELA_AIR_METADATA_INTERNAL
|
||||
#include "air_constants.h"
|
||||
#include "air_calls.h"
|
||||
#include "llvm-c/Transforms/PassBuilder.h"
|
||||
#include "util/macros.h"
|
||||
#include "util/set.h"
|
||||
@@ -283,55 +284,140 @@ constructed(LLVMModuleRef clone)
|
||||
!LLVMGetArrayLength2(LLVMTypeOf(entries)));
|
||||
}
|
||||
|
||||
/* The clone and original have their globals in the same order. Keep the
|
||||
* constructor's destinations externally visible so LLVM commits their
|
||||
* initializers instead of forwarding their values and removing them. */
|
||||
static bool
|
||||
evaluate_constants(LLVMModuleRef original, LLVMModuleRef clone,
|
||||
struct stela_air_constructed_constants *result)
|
||||
{
|
||||
LLVMValueRef copies[AIR_MAX_ARGUMENTS];
|
||||
result->count = 0;
|
||||
LLVMValueRef global = LLVMGetFirstGlobal(original);
|
||||
for (LLVMValueRef copy = LLVMGetFirstGlobal(clone); copy && global;
|
||||
copy = LLVMGetNextGlobal(copy), global = LLVMGetNextGlobal(global)) {
|
||||
if (LLVMIsGlobalConstant(copy) || !stela_air_metadata_constructed(global))
|
||||
continue;
|
||||
if (result->count == AIR_MAX_ARGUMENTS)
|
||||
return false;
|
||||
result->globals[result->count] = global;
|
||||
copies[result->count++] = copy;
|
||||
LLVMSetLinkage(copy, LLVMExternalLinkage);
|
||||
}
|
||||
cast_conversions(clone);
|
||||
LLVMPassBuilderOptionsRef options = LLVMCreatePassBuilderOptions();
|
||||
if (!options)
|
||||
return false;
|
||||
LLVMErrorRef error = LLVMRunPasses(clone, "globalopt", NULL, options);
|
||||
LLVMDisposePassBuilderOptions(options);
|
||||
if (error) {
|
||||
LLVMDisposeErrorMessage(LLVMGetErrorMessage(error));
|
||||
return false;
|
||||
}
|
||||
if (!constructed(clone))
|
||||
return false;
|
||||
for (unsigned i = 0; i < result->count; i++) {
|
||||
result->values[i] = LLVMGetInitializer(copies[i]);
|
||||
if (!plain(result->values[i], 0))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/* An unassociated constructor whose only reference is its list entry and
|
||||
* whose calls reach only declarations is independent of shader inlining. */
|
||||
static bool
|
||||
leaf_constructor(LLVMValueRef entry)
|
||||
{
|
||||
LLVMValueRef fn = LLVMGetOperand(entry, 1);
|
||||
LLVMUseRef use = LLVMGetFirstUse(fn);
|
||||
if (!LLVMIsAConstantPointerNull(LLVMGetOperand(entry, 2)) ||
|
||||
!use || LLVMGetUser(use) != entry || LLVMGetNextUse(use))
|
||||
return false;
|
||||
for (LLVMBasicBlockRef block = LLVMGetFirstBasicBlock(fn); block; block = LLVMGetNextBasicBlock(block)) {
|
||||
for (LLVMValueRef inst = LLVMGetFirstInstruction(block); inst; inst = LLVMGetNextInstruction(inst)) {
|
||||
if (LLVMIsAInvokeInst(inst) || LLVMIsACallBrInst(inst))
|
||||
return false;
|
||||
if (LLVMIsACallInst(inst)) {
|
||||
LLVMValueRef callee = LLVMGetCalledValue(inst);
|
||||
if (!LLVMIsAFunction(callee) || !LLVMIsDeclaration(callee))
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool
|
||||
stela_air_construct_constants(struct stela_air_metadata *m)
|
||||
stela_air_prepare_constants(struct stela_air_metadata *m, const struct stela_air_constants *constants,
|
||||
struct stela_air_constructed_constants *prepared)
|
||||
{
|
||||
LLVMValueRef constructors = stela_air_metadata_constructors(m->module);
|
||||
if (!constructors || !stela_air_has_defined_calls(m->module))
|
||||
return false;
|
||||
LLVMValueRef entries = LLVMGetInitializer(constructors);
|
||||
uint64_t functions = LLVMGetArrayLength2(LLVMTypeOf(entries));
|
||||
if (functions > AIR_MAX_ARGUMENTS)
|
||||
return false;
|
||||
for (unsigned i = 0; i < functions; i++) {
|
||||
if (!leaf_constructor(LLVMGetAggregateElement(entries, i)))
|
||||
return false;
|
||||
}
|
||||
LLVMModuleRef clone = LLVMCloneModule(m->module);
|
||||
if (!clone)
|
||||
return false;
|
||||
struct stela_air_error prior = *m->error;
|
||||
struct stela_air_metadata copy = *m;
|
||||
copy.module = clone;
|
||||
bool ready = stela_air_specialize_constants(©, constants->values, constants->count) &&
|
||||
evaluate_constants(m->module, clone, prepared) && m->error->kind == STELA_AIR_OK;
|
||||
LLVMDisposeModule(clone);
|
||||
/* A compact clone that cannot evaluate uses the ordinary path and its diagnostic. */
|
||||
*m->error = prior;
|
||||
return ready;
|
||||
}
|
||||
|
||||
/* Inlining can change whether a global is used only by AIR logging. Match
|
||||
* the destinations of the post-inline module before using the staged values. */
|
||||
static bool
|
||||
prepared_matches(LLVMModuleRef module, const struct stela_air_constructed_constants *prepared)
|
||||
{
|
||||
unsigned index = 0;
|
||||
for (LLVMValueRef global = LLVMGetFirstGlobal(module); global; global = LLVMGetNextGlobal(global)) {
|
||||
if (!stela_air_metadata_constructed(global))
|
||||
continue;
|
||||
if (index == prepared->count || prepared->globals[index++] != global)
|
||||
return false;
|
||||
}
|
||||
return index == prepared->count;
|
||||
}
|
||||
|
||||
bool
|
||||
stela_air_construct_prepared_constants(struct stela_air_metadata *m,
|
||||
const struct stela_air_constructed_constants *prepared)
|
||||
{
|
||||
LLVMValueRef constructors = stela_air_metadata_constructors(m->module);
|
||||
if (!constructors)
|
||||
return true;
|
||||
LLVMValueRef entries = LLVMGetInitializer(constructors);
|
||||
unsigned functions = LLVMGetArrayLength2(LLVMTypeOf(entries));
|
||||
uint64_t functions = LLVMGetArrayLength2(LLVMTypeOf(entries));
|
||||
if (functions > AIR_MAX_ARGUMENTS)
|
||||
return fail(m, STELA_AIR_LIMIT, "constructor count exceeded");
|
||||
/* The globals constructors may store, paired with the clone's; those stay
|
||||
* defined there, so the optimizer keeps them and only commits their
|
||||
* values. */
|
||||
LLVMModuleRef clone = LLVMCloneModule(m->module);
|
||||
if (!clone)
|
||||
return fail(m, STELA_AIR_ALLOCATION, "module clone allocation failed");
|
||||
LLVMValueRef originals[AIR_MAX_ARGUMENTS], copies[AIR_MAX_ARGUMENTS];
|
||||
unsigned count = 0;
|
||||
bool evaluated = true;
|
||||
for (LLVMValueRef global = LLVMGetFirstGlobal(m->module), copy = LLVMGetFirstGlobal(clone);
|
||||
global && copy && evaluated; global = LLVMGetNextGlobal(global), copy = LLVMGetNextGlobal(copy)) {
|
||||
if (!stela_air_metadata_constructed(global))
|
||||
continue;
|
||||
evaluated = count < AIR_MAX_ARGUMENTS;
|
||||
originals[count] = global;
|
||||
copies[count++] = copy;
|
||||
LLVMSetLinkage(copy, LLVMExternalLinkage);
|
||||
struct stela_air_constructed_constants evaluated;
|
||||
if (!prepared || !prepared_matches(m->module, prepared)) {
|
||||
LLVMModuleRef clone = LLVMCloneModule(m->module);
|
||||
if (!clone)
|
||||
return fail(m, STELA_AIR_ALLOCATION, "module clone allocation failed");
|
||||
bool ready = evaluate_constants(m->module, clone, &evaluated);
|
||||
LLVMDisposeModule(clone);
|
||||
if (!ready)
|
||||
return fail(m, STELA_AIR_INSTRUCTION,
|
||||
"program-scope constants depend on more than function constants");
|
||||
prepared = &evaluated;
|
||||
}
|
||||
cast_conversions(clone);
|
||||
LLVMPassBuilderOptionsRef options = evaluated ? LLVMCreatePassBuilderOptions() : NULL;
|
||||
LLVMErrorRef error = options ? LLVMRunPasses(clone, "globalopt", NULL, options) : NULL;
|
||||
if (options)
|
||||
LLVMDisposePassBuilderOptions(options);
|
||||
if (error) {
|
||||
LLVMDisposeErrorMessage(LLVMGetErrorMessage(error));
|
||||
evaluated = false;
|
||||
}
|
||||
evaluated &= options && constructed(clone);
|
||||
LLVMValueRef values[AIR_MAX_ARGUMENTS];
|
||||
for (unsigned i = 0; evaluated && i < count; i++)
|
||||
evaluated = plain(values[i] = LLVMGetInitializer(copies[i]), 0);
|
||||
/* The values are the context's, which outlives the clone. */
|
||||
LLVMDisposeModule(clone);
|
||||
if (!evaluated)
|
||||
return fail(m, STELA_AIR_INSTRUCTION,
|
||||
"program-scope constants depend on more than function constants");
|
||||
for (unsigned i = 0; i < count; i++) {
|
||||
LLVMSetInitializer(originals[i], values[i]);
|
||||
LLVMSetGlobalConstant(originals[i], true);
|
||||
for (unsigned i = 0; i < prepared->count; i++) {
|
||||
LLVMSetInitializer(prepared->globals[i], prepared->values[i]);
|
||||
LLVMSetGlobalConstant(prepared->globals[i], true);
|
||||
}
|
||||
LLVMValueRef dropped[AIR_MAX_ARGUMENTS];
|
||||
for (unsigned i = 0; i < functions; i++)
|
||||
@@ -347,6 +433,12 @@ stela_air_construct_constants(struct stela_air_metadata *m)
|
||||
return true;
|
||||
}
|
||||
|
||||
bool
|
||||
stela_air_construct_constants(struct stela_air_metadata *m)
|
||||
{
|
||||
return stela_air_construct_prepared_constants(m, NULL);
|
||||
}
|
||||
|
||||
static bool
|
||||
fold(struct stela_air_metadata *m, LLVMValueRef fn)
|
||||
{
|
||||
|
||||
@@ -12,10 +12,24 @@ bool stela_air_specialize_constants(struct stela_air_metadata *m,
|
||||
const struct stela_air_constant_value *values,
|
||||
unsigned count);
|
||||
|
||||
/* Initializers captured from a compact copy of a module before reflection
|
||||
* inlines its shader functions. LLVM constants belong to the shared context. */
|
||||
struct stela_air_constructed_constants {
|
||||
unsigned count;
|
||||
LLVMValueRef globals[AIR_MAX_ARGUMENTS], values[AIR_MAX_ARGUMENTS];
|
||||
};
|
||||
|
||||
/* Prepares initialization when inlining cannot change the constructors. */
|
||||
bool stela_air_prepare_constants(struct stela_air_metadata *m,
|
||||
const struct stela_air_constants *constants,
|
||||
struct stela_air_constructed_constants *prepared);
|
||||
|
||||
/* Evaluates the specialized module's air.static_init constructors, making the
|
||||
* program-scope constants they compute constant data, and removes them;
|
||||
* refuses constructors that depend on more than function constants. */
|
||||
bool stela_air_construct_constants(struct stela_air_metadata *m);
|
||||
bool stela_air_construct_prepared_constants(struct stela_air_metadata *m,
|
||||
const struct stela_air_constructed_constants *prepared);
|
||||
|
||||
/* Folds what the constructed module's function constants decide in fn, its
|
||||
* entry with its callees inlined: the loads of constant data, the branches
|
||||
|
||||
@@ -181,7 +181,8 @@ stela_air_metadata_constructors(LLVMModuleRef module)
|
||||
return NULL;
|
||||
for (unsigned i = 0; i < LLVMGetArrayLength2(type); i++) {
|
||||
LLVMValueRef entry = LLVMGetAggregateElement(entries, i);
|
||||
if (!entry || LLVMGetNumOperands(entry) != 3 || !static_init(LLVMGetOperand(entry, 1)))
|
||||
if (!entry || LLVMGetNumOperands(entry) != 3 || !LLVMIsAConstantInt(LLVMGetOperand(entry, 0)) ||
|
||||
!static_init(LLVMGetOperand(entry, 1)))
|
||||
return NULL;
|
||||
}
|
||||
return list;
|
||||
@@ -370,6 +371,8 @@ stela_air_metadata_validate(struct stela_air_metadata *t)
|
||||
{
|
||||
/* Debug info says nothing a function does, and Xcode's Debug builds carry it. */
|
||||
LLVMStripModuleDebugInfo(t->module);
|
||||
if (LLVMGetNamedGlobal(t->module, "llvm.global_ctors") && !stela_air_metadata_constructors(t->module))
|
||||
return fail(t, STELA_AIR_METADATA, "invalid AIR constructor list");
|
||||
for (LLVMNamedMDNodeRef node = LLVMGetFirstNamedMetadata(t->module); node;
|
||||
node = LLVMGetNextNamedMetadata(node)) {
|
||||
size_t size;
|
||||
@@ -2621,21 +2624,53 @@ command_use(LLVMModuleRef module)
|
||||
return use;
|
||||
}
|
||||
|
||||
/* In enum stela_air_stage order after the kernels. */
|
||||
static const char *const entry_lists[] = {"air.kernel", "air.vertex", "air.fragment",
|
||||
"air.object", "air.mesh", "air.visible"};
|
||||
|
||||
static bool
|
||||
entry_stage(struct stela_air_metadata *m, const char *entry, unsigned *stage)
|
||||
{
|
||||
bool found = false;
|
||||
LLVMValueRef fn = LLVMGetNamedFunction(m->module, entry);
|
||||
for (unsigned list = 0; fn && list < ARRAY_SIZE(entry_lists); list++) {
|
||||
LLVMValueRef nodes[AIR_MAX_METADATA_OPERANDS];
|
||||
unsigned count;
|
||||
if (!stela_air_named_md(m, entry_lists[list], nodes, &count))
|
||||
return false;
|
||||
for (unsigned i = 0; i < count; i++) {
|
||||
LLVMValueRef fields[AIR_MAX_METADATA_OPERANDS];
|
||||
unsigned fields_count;
|
||||
if (!stela_air_md_node(m, nodes[i], fields, &fields_count) || !fields_count)
|
||||
return false;
|
||||
if (fields[0] != fn)
|
||||
continue;
|
||||
if (found)
|
||||
return fail(m, STELA_AIR_METADATA, "entry listed more than once");
|
||||
found = true;
|
||||
*stage = list;
|
||||
}
|
||||
}
|
||||
return found || fail(m, STELA_AIR_ARGUMENT, "entry is not a listed AIR function");
|
||||
}
|
||||
|
||||
static bool
|
||||
inspect(const void *bitcode, size_t size, const struct stela_air_constants *constants,
|
||||
unsigned max_entries,
|
||||
stela_air_visit_entry visit, void *data, struct stela_air_error *error,
|
||||
const char *render_name, enum stela_air_stage stage, stela_air_visit_stage render_visit)
|
||||
stela_air_visit_entry visit, void *data, struct stela_air_error *error,
|
||||
const char *entry_name, enum stela_air_stage stage, stela_air_visit_stage render_visit,
|
||||
unsigned *listed_stage)
|
||||
{
|
||||
struct stela_air_error local = {0};
|
||||
if (!error)
|
||||
error = &local;
|
||||
*error = (struct stela_air_error){0};
|
||||
struct stela_air_metadata m = {.error = error, .render = render_name != NULL};
|
||||
struct stela_air_metadata m = {.error = error};
|
||||
if (!bitcode || size < 4 || size > AIR_MAX_BITCODE_BYTES ||
|
||||
memcmp(bitcode, "BC\xc0\xde", 4) || !max_entries ||
|
||||
max_entries > AIR_MAX_METADATA_OPERANDS || (!render_name && !visit) ||
|
||||
(render_name && (!render_visit || !stage_text(render_name, strlen(render_name)))))
|
||||
max_entries > AIR_MAX_METADATA_OPERANDS ||
|
||||
(entry_name && (!render_visit || !stage_text(entry_name, strlen(entry_name)))) ||
|
||||
((!entry_name || listed_stage) && !visit))
|
||||
return fail(&m, STELA_AIR_INPUT, "invalid AIR inspection input/budget");
|
||||
unsigned major, minor, patch;
|
||||
LLVMGetVersion(&major, &minor, &patch);
|
||||
@@ -2663,6 +2698,12 @@ inspect(const void *bitcode, size_t size, const struct stela_air_constants *cons
|
||||
fail(&m, STELA_AIR_BITCODE, "LLVM refused AIR bitcode");
|
||||
goto done;
|
||||
}
|
||||
if (listed_stage) {
|
||||
if (!entry_stage(&m, entry_name, listed_stage))
|
||||
goto done;
|
||||
stage = (enum stela_air_stage)*listed_stage;
|
||||
}
|
||||
m.render = stage != 0;
|
||||
char *verification = NULL;
|
||||
if (LLVMVerifyModule(m.module, LLVMReturnStatusAction, &verification)) {
|
||||
fail(&m, STELA_AIR_VERIFY, "%s", verification ? verification : "invalid LLVM module");
|
||||
@@ -2678,8 +2719,11 @@ inspect(const void *bitcode, size_t size, const struct stela_air_constants *cons
|
||||
fail(&m, STELA_AIR_TARGET, "unsupported target/globals/inline assembly");
|
||||
goto done;
|
||||
}
|
||||
if (!stela_air_metadata_layout(&m) || !stela_air_metadata_validate(&m) ||
|
||||
!stela_air_inline_calls(&m, NULL, 0, 0))
|
||||
if (!stela_air_metadata_layout(&m) || !stela_air_metadata_validate(&m))
|
||||
goto done;
|
||||
struct stela_air_constructed_constants prepared;
|
||||
bool ready = constants && stela_air_prepare_constants(&m, constants, &prepared);
|
||||
if (!stela_air_inline_calls(&m, NULL, 0, 0))
|
||||
goto done;
|
||||
if (!stela_air_metadata_target(&m, target)) {
|
||||
fail(&m, STELA_AIR_TARGET, "AIR version and target triple disagree");
|
||||
@@ -2689,7 +2733,7 @@ inspect(const void *bitcode, size_t size, const struct stela_air_constants *cons
|
||||
unsigned constant_count;
|
||||
if (!stela_air_metadata_function_constants(&m, function_constants, NULL, &constant_count) ||
|
||||
(constants && (!stela_air_specialize_constants(&m, constants->values, constants->count) ||
|
||||
!stela_air_construct_constants(&m))))
|
||||
!stela_air_construct_prepared_constants(&m, ready ? &prepared : NULL))))
|
||||
goto done;
|
||||
struct stela_air_inspection info = {
|
||||
.target = target, .target_bytes = strlen(target), .air_minor = m.air_minor,
|
||||
@@ -2700,10 +2744,10 @@ inspect(const void *bitcode, size_t size, const struct stela_air_constants *cons
|
||||
.commands = command_use(m.module),
|
||||
.metadata = &m,
|
||||
};
|
||||
if (render_name) {
|
||||
if (m.render) {
|
||||
struct stela_air_render render = {.entry = {.stage = stage}};
|
||||
if (stage != STELA_AIR_VISIBLE &&
|
||||
!stela_air_metadata_stage(&m, LLVMGetNamedFunction(m.module, render_name), stage, &render)) goto done;
|
||||
!stela_air_metadata_stage(&m, LLVMGetNamedFunction(m.module, entry_name), stage, &render)) goto done;
|
||||
success = render_visit(&info, &render.entry, data);
|
||||
if (!success) fail(&m, STELA_AIR_LIMIT, "AIR stage receiver refused entry");
|
||||
goto done;
|
||||
@@ -2791,7 +2835,7 @@ stela_air_inspect(const void *bitcode, size_t size, const struct stela_air_const
|
||||
unsigned max_entries, stela_air_visit_entry visit, void *data,
|
||||
struct stela_air_error *error)
|
||||
{
|
||||
return inspect(bitcode, size, constants, max_entries, visit, data, error, NULL, 0, NULL);
|
||||
return inspect(bitcode, size, constants, max_entries, visit, data, error, NULL, 0, NULL, NULL);
|
||||
}
|
||||
|
||||
bool
|
||||
@@ -2805,13 +2849,26 @@ stela_air_inspect_stage(const void *bitcode, size_t size, const struct stela_air
|
||||
return false;
|
||||
}
|
||||
return inspect(bitcode, size, constants, AIR_MAX_METADATA_OPERANDS, NULL, data, error, entry,
|
||||
stage, visit);
|
||||
stage, visit, NULL);
|
||||
}
|
||||
|
||||
/* Parses AIR bitcode into m->module, in *context; false after reporting
|
||||
* why. close_module disposes of both. */
|
||||
bool
|
||||
stela_air_inspect_entry(const void *bitcode, size_t size, const struct stela_air_constants *constants,
|
||||
const char *entry, unsigned *stage, stela_air_visit_entry kernel_visit,
|
||||
stela_air_visit_stage stage_visit, void *data, struct stela_air_error *error)
|
||||
{
|
||||
if (!entry || !stage) {
|
||||
if (error) *error = (struct stela_air_error){.kind = STELA_AIR_INPUT};
|
||||
return false;
|
||||
}
|
||||
return inspect(bitcode, size, constants, AIR_MAX_METADATA_OPERANDS, kernel_visit, data, error,
|
||||
entry, 0, stage_visit, stage);
|
||||
}
|
||||
|
||||
/* Discovery needs globals and named metadata. Leave function bodies to the
|
||||
* eager parser and verifier used by inspection and lowering. */
|
||||
static bool
|
||||
parse_module(struct stela_air_metadata *m, const void *bitcode, size_t size,
|
||||
parse_metadata(struct stela_air_metadata *m, const void *bitcode, size_t size,
|
||||
LLVMContextRef *context)
|
||||
{
|
||||
*context = LLVMContextCreate();
|
||||
@@ -2819,8 +2876,9 @@ parse_module(struct stela_air_metadata *m, const void *bitcode, size_t size,
|
||||
return fail(m, STELA_AIR_ALLOCATION, "LLVM context unavailable");
|
||||
LLVMContextSetDiagnosticHandler(*context, inspection_diagnostic, m);
|
||||
LLVMMemoryBufferRef buffer = LLVMCreateMemoryBufferWithMemoryRangeCopy(bitcode, size, "Metal input");
|
||||
bool parsed = buffer && !LLVMParseBitcodeInContext2(*context, buffer, &m->module);
|
||||
if (buffer)
|
||||
bool parsed = buffer && !LLVMGetBitcodeModuleInContext2(*context, buffer, &m->module);
|
||||
/* LLVM owns the buffer once it creates the lazy module. */
|
||||
if (buffer && !parsed)
|
||||
LLVMDisposeMemoryBuffer(buffer);
|
||||
return (parsed && m->error->kind == STELA_AIR_OK) ||
|
||||
fail(m, STELA_AIR_BITCODE, "LLVM refused AIR bitcode");
|
||||
@@ -2842,10 +2900,6 @@ valid_bitcode(const void *bitcode, size_t size)
|
||||
!memcmp(bitcode, "BC\xc0\xde", 4);
|
||||
}
|
||||
|
||||
/* In enum stela_air_stage order after the kernels. */
|
||||
static const char *const entry_lists[] = {"air.kernel", "air.vertex", "air.fragment",
|
||||
"air.object", "air.mesh", "air.visible"};
|
||||
|
||||
bool
|
||||
stela_air_functions(const void *bitcode, size_t size, stela_air_visit_function visit, void *data,
|
||||
struct stela_air_error *error)
|
||||
@@ -2856,9 +2910,7 @@ stela_air_functions(const void *bitcode, size_t size, stela_air_visit_function v
|
||||
if (!valid_bitcode(bitcode, size) || !visit)
|
||||
return fail(&m, STELA_AIR_INPUT, "invalid AIR function list query");
|
||||
LLVMContextRef context;
|
||||
if (!parse_module(&m, bitcode, size, &context))
|
||||
return false;
|
||||
bool visited = true;
|
||||
bool visited = parse_metadata(&m, bitcode, size, &context);
|
||||
for (unsigned list = 0; visited && list < ARRAY_SIZE(entry_lists); list++) {
|
||||
LLVMValueRef nodes[AIR_MAX_METADATA_OPERANDS];
|
||||
unsigned count;
|
||||
@@ -2866,7 +2918,8 @@ stela_air_functions(const void *bitcode, size_t size, stela_air_visit_function v
|
||||
for (unsigned i = 0; visited && i < count; i++) {
|
||||
LLVMValueRef fields[AIR_MAX_METADATA_OPERANDS];
|
||||
unsigned fields_count;
|
||||
visited = stela_air_md_node(&m, nodes[i], fields, &fields_count) && fields_count;
|
||||
visited = stela_air_md_node(&m, nodes[i], fields, &fields_count) && fields_count &&
|
||||
fields[0] && LLVMIsAFunction(fields[0]);
|
||||
if (visited) {
|
||||
size_t name_bytes;
|
||||
const char *name = LLVMGetValueName2(fields[0], &name_bytes);
|
||||
@@ -2880,47 +2933,6 @@ stela_air_functions(const void *bitcode, size_t size, stela_air_visit_function v
|
||||
return visited;
|
||||
}
|
||||
|
||||
bool
|
||||
stela_air_entry_stage(const void *bitcode, size_t size, const char *entry, unsigned *stage,
|
||||
struct stela_air_error *error)
|
||||
{
|
||||
struct stela_air_error local = {0};
|
||||
struct stela_air_metadata m = {.error = error ? error : &local};
|
||||
*m.error = (struct stela_air_error){0};
|
||||
if (!valid_bitcode(bitcode, size) || !entry || !stage_text(entry, strlen(entry)))
|
||||
return fail(&m, STELA_AIR_INPUT, "invalid AIR entry query");
|
||||
LLVMContextRef context;
|
||||
bool found = false;
|
||||
if (!parse_module(&m, bitcode, size, &context))
|
||||
goto done;
|
||||
LLVMValueRef fn = LLVMGetNamedFunction(m.module, entry);
|
||||
for (unsigned list = 0; fn && list < ARRAY_SIZE(entry_lists); list++) {
|
||||
LLVMValueRef nodes[AIR_MAX_METADATA_OPERANDS];
|
||||
unsigned count;
|
||||
if (!stela_air_named_md(&m, entry_lists[list], nodes, &count))
|
||||
goto done;
|
||||
for (unsigned i = 0; i < count; i++) {
|
||||
LLVMValueRef fields[AIR_MAX_METADATA_OPERANDS];
|
||||
unsigned fields_count;
|
||||
if (!stela_air_md_node(&m, nodes[i], fields, &fields_count) || !fields_count)
|
||||
goto done;
|
||||
if (fields[0] != fn)
|
||||
continue;
|
||||
if (found) {
|
||||
fail(&m, STELA_AIR_METADATA, "entry listed more than once");
|
||||
goto done;
|
||||
}
|
||||
found = true;
|
||||
*stage = list;
|
||||
}
|
||||
}
|
||||
if (!found)
|
||||
fail(&m, STELA_AIR_ARGUMENT, "entry is not a listed AIR function");
|
||||
done:
|
||||
close_module(&m, context);
|
||||
return found && m.error->kind == STELA_AIR_OK;
|
||||
}
|
||||
|
||||
bool
|
||||
stela_air_sampler_states(const void *bitcode, size_t size, uint64_t *states, unsigned *count,
|
||||
struct stela_air_error *error)
|
||||
@@ -2933,7 +2945,7 @@ stela_air_sampler_states(const void *bitcode, size_t size, uint64_t *states, uns
|
||||
return fail(&m, STELA_AIR_INPUT, "invalid AIR sampler state query");
|
||||
LLVMContextRef context;
|
||||
LLVMValueRef globals[AIR_MAX_SAMPLER_STATES];
|
||||
bool listed = parse_module(&m, bitcode, size, &context) &&
|
||||
bool listed = parse_metadata(&m, bitcode, size, &context) &&
|
||||
stela_air_metadata_sampler_states(&m, globals, states, count);
|
||||
close_module(&m, context);
|
||||
return listed;
|
||||
|
||||
@@ -386,12 +386,13 @@ bool stela_air_inspect_stage(const void *, size_t, const struct stela_air_consta
|
||||
const char *entry,
|
||||
enum stela_air_stage, stela_air_visit_stage, void *,
|
||||
struct stela_air_error *);
|
||||
/* The stage whose entry list names entry: *stage is zero for air.kernel.
|
||||
* Only the lists are read; inspection validates the rest. */
|
||||
bool stela_air_entry_stage(const void *, size_t, const char *entry, unsigned *stage,
|
||||
struct stela_air_error *);
|
||||
/* Calls visit with each function the entry lists name and its list, zero for
|
||||
* air.kernel, as stela_air_entry_stage numbers them, until it refuses one. */
|
||||
/* Looks up the entry's stage on the module being inspected. Zero names
|
||||
* air.kernel, whose visitor still receives every validated kernel. */
|
||||
bool stela_air_inspect_entry(const void *, size_t, const struct stela_air_constants *,
|
||||
const char *entry, unsigned *stage, stela_air_visit_entry,
|
||||
stela_air_visit_stage, void *, struct stela_air_error *);
|
||||
/* Calls visit with each function the entry lists name and its stage,
|
||||
* zero for air.kernel, until it refuses one. */
|
||||
typedef bool (*stela_air_visit_function)(void *, const char *name, size_t name_bytes,
|
||||
unsigned stage);
|
||||
bool stela_air_functions(const void *, size_t, stela_air_visit_function, void *,
|
||||
|
||||
@@ -4725,7 +4725,8 @@ static nir_shader *
|
||||
translate(const void *bitcode, size_t size, const char *entry,
|
||||
const nir_shader_compiler_options *nir_options,
|
||||
const struct stela_air_options *options,
|
||||
struct stela_air_error *error, const struct stela_air_stage_options *stage)
|
||||
struct stela_air_error *error, const struct stela_air_stage_options *stage,
|
||||
bool *folded_early)
|
||||
{
|
||||
struct stela_air_error local_error = {0};
|
||||
if (!error)
|
||||
@@ -4816,13 +4817,29 @@ translate(const void *bitcode, size_t size, const char *entry,
|
||||
if (!stela_air_metadata_layout(&t.metadata) || !stela_air_metadata_validate(&t.metadata) ||
|
||||
!stela_air_specialize_constants(&t.metadata, options->constants, options->constant_count) ||
|
||||
!stela_air_construct_constants(&t.metadata) ||
|
||||
!stela_air_link_modules(&t.metadata, options->modules, options->module_count) ||
|
||||
/* A table's pointer may pass through functions to the call it makes. */
|
||||
!stela_air_inline_calls(&t.metadata, NULL, 0, 0) ||
|
||||
!stela_air_link_modules(&t.metadata, options->modules, options->module_count))
|
||||
goto done;
|
||||
LLVMValueRef specialized = NULL;
|
||||
/* Calls through tables may depend on inlining, and logging admission uses
|
||||
* the use lists of its globals. Keep those modules on the original path. */
|
||||
if (folded_early && stage && stage->stage == STELA_AIR_FRAGMENT && options->constant_count &&
|
||||
!options->module_count && !options->linked_function_count &&
|
||||
stela_air_metadata_target(&t.metadata, LLVMGetTarget(t.module)) &&
|
||||
LLVMGetNamedMetadataNumOperands(t.module, "air.function_constants") &&
|
||||
!LLVMGetNamedMetadataNumOperands(t.module, "air.visible") &&
|
||||
!LLVMGetNamedMetadataNumOperands(t.module, "air.visible_function_references") &&
|
||||
!LLVMGetNamedFunction(t.module, "air.get_size_visible_function_table") &&
|
||||
!LLVMGetNamedFunction(t.module, "air.get_function_pointer_visible_function_table") &&
|
||||
!LLVMGetNamedFunction(t.module, "air.os_log"))
|
||||
specialized = LLVMGetNamedFunction(t.module, entry);
|
||||
/* A table's pointer may pass through functions to the call it makes. */
|
||||
if (!stela_air_inline_specialized_calls(&t.metadata, specialized, folded_early) ||
|
||||
!stela_air_dispatch_tables(&t.metadata, options->linked_functions,
|
||||
options->linked_function_count) ||
|
||||
!stela_air_inline_calls(&t.metadata, LLVMGetNamedFunction(t.module, entry),
|
||||
options->max_call_stack_depth, options->max_instructions))
|
||||
/* Walk again only for calls the first pass left or table lowering added. */
|
||||
(stela_air_has_defined_calls(t.module) &&
|
||||
!stela_air_inline_calls(&t.metadata, LLVMGetNamedFunction(t.module, entry),
|
||||
options->max_call_stack_depth, options->max_instructions)))
|
||||
goto done;
|
||||
t.layout = t.metadata.layout;
|
||||
t.air_minor = t.metadata.air_minor;
|
||||
@@ -4945,7 +4962,7 @@ stela_air_to_nir(const void *bitcode, size_t size, const char *entry,
|
||||
const nir_shader_compiler_options *nir_options,
|
||||
const struct stela_air_options *options, struct stela_air_error *error)
|
||||
{
|
||||
return translate(bitcode, size, entry, nir_options, options, error, NULL);
|
||||
return translate(bitcode, size, entry, nir_options, options, error, NULL, NULL);
|
||||
}
|
||||
|
||||
nir_shader *
|
||||
@@ -4957,5 +4974,27 @@ stela_air_stage_to_nir(const void *bitcode, size_t size, const char *entry,
|
||||
if (error) *error = (struct stela_air_error){.kind = STELA_AIR_INPUT};
|
||||
return NULL;
|
||||
}
|
||||
return translate(bitcode, size, entry, nir_options, &options->resources, error, options);
|
||||
return translate(bitcode, size, entry, nir_options, &options->resources, error, options, NULL);
|
||||
}
|
||||
|
||||
nir_shader *
|
||||
stela_air_metal_stage_to_nir(const void *bitcode, size_t size, const char *entry,
|
||||
const nir_shader_compiler_options *nir_options,
|
||||
const struct stela_air_stage_options *options,
|
||||
struct stela_air_error *error)
|
||||
{
|
||||
if (!options)
|
||||
return stela_air_stage_to_nir(bitcode, size, entry, nir_options, options, error);
|
||||
struct stela_air_error local_error;
|
||||
if (!error)
|
||||
error = &local_error;
|
||||
bool folded_early = false;
|
||||
nir_shader *shader = translate(bitcode, size, entry, nir_options, &options->resources, error,
|
||||
options, &folded_early);
|
||||
/* Only a fragment that attempted the early pass can retry. Its temporary
|
||||
* LLVM module and NIR are already gone, and the second call cannot fold
|
||||
* early again. Avoid extra work after an allocation refusal. */
|
||||
if (!shader && folded_early && error->kind != STELA_AIR_ALLOCATION)
|
||||
return stela_air_stage_to_nir(bitcode, size, entry, nir_options, options, error);
|
||||
return shader;
|
||||
}
|
||||
@@ -378,6 +378,13 @@ nir_shader *stela_air_stage_to_nir(const void *, size_t, const char *entry,
|
||||
const struct stela_air_stage_options *,
|
||||
struct stela_air_error *);
|
||||
|
||||
/* Metal's stage callbacks write only to the temporary NIR, so translation
|
||||
* can retry the ordinary lowering order when early specialization fails. */
|
||||
nir_shader *stela_air_metal_stage_to_nir(const void *, size_t, const char *entry,
|
||||
const nir_shader_compiler_options *,
|
||||
const struct stela_air_stage_options *,
|
||||
struct stela_air_error *);
|
||||
|
||||
/* Input is the hash-checked raw AIR bitcode selected by the archive reader.
|
||||
* Success transfers ownership of a real NIR shader to the caller (ralloc_free).
|
||||
* Failure returns NULL, destroys partial NIR, and reports an explicit error.
|
||||
|
||||
@@ -46,7 +46,7 @@ fail(struct stela_air_error *error, enum stela_air_error_kind kind, const char *
|
||||
return false;
|
||||
}
|
||||
|
||||
/* The function stages of stela_air_entry_stage's stages: kernels, then
|
||||
/* AIR entry stages: kernels, then
|
||||
* enum stela_air_stage. */
|
||||
static const enum stela_metal_function_stage function_stages[] = {
|
||||
STELA_METAL_KERNEL, STELA_METAL_VERTEX, STELA_METAL_FRAGMENT, STELA_METAL_OBJECT,
|
||||
@@ -313,13 +313,8 @@ inspect_entry(const void *air, size_t size, const char *entry,
|
||||
stela_air_visit_stage stage_entry, void *data, const bool *found, unsigned *stage,
|
||||
struct stela_air_error *error)
|
||||
{
|
||||
if (!stela_air_entry_stage(air, size, entry, stage, error))
|
||||
return false;
|
||||
bool inspected = *stage ? stela_air_inspect_stage(air, size, constants, entry,
|
||||
(enum stela_air_stage)*stage, stage_entry,
|
||||
data, error) :
|
||||
stela_air_inspect(air, size, constants, AIR_MAX_METADATA_OPERANDS,
|
||||
kernel, data, error);
|
||||
bool inspected = stela_air_inspect_entry(air, size, constants, entry, stage, kernel, stage_entry,
|
||||
data, error);
|
||||
/* A receiver's refusal is reported as the inspector's; keep the cause. */
|
||||
return inspected ? *found || fail(error, STELA_AIR_ARGUMENT, "entry is not an AIR kernel") :
|
||||
false;
|
||||
@@ -684,10 +679,11 @@ varying_rows(const struct stela_metal_reflection *reflection,
|
||||
}
|
||||
|
||||
nir_shader *
|
||||
stela_metal_compile(const void *air, size_t size, const char *entry,
|
||||
const struct stela_metal_target *target,
|
||||
const struct stela_metal_specialization *specialization,
|
||||
struct stela_air_error *error)
|
||||
stela_metal_compile_reflected(const void *air, size_t size, const char *entry,
|
||||
const struct stela_metal_target *target,
|
||||
const struct stela_metal_specialization *specialization,
|
||||
const struct stela_metal_reflection *reflection,
|
||||
struct stela_air_error *error)
|
||||
{
|
||||
struct stela_air_error local = {0};
|
||||
if (!error)
|
||||
@@ -703,17 +699,21 @@ stela_metal_compile(const void *air, size_t size, const char *entry,
|
||||
fail(error, STELA_AIR_INPUT, "invalid compilation request");
|
||||
return NULL;
|
||||
}
|
||||
struct stela_metal_reflection *reflection = malloc(sizeof(*reflection));
|
||||
if (!reflection) {
|
||||
fail(error, STELA_AIR_ALLOCATION, "reflection allocation failed");
|
||||
return NULL;
|
||||
}
|
||||
struct reflecting r = {.entry = entry, .out = reflection, .error = error};
|
||||
struct stela_metal_reflection *owned_reflection = NULL;
|
||||
nir_shader *shader = NULL;
|
||||
struct stela_air_constants constants = {specialization->constants,
|
||||
specialization->constant_count};
|
||||
if (!reflect(air, size, entry, &constants, &r))
|
||||
goto done;
|
||||
if (!reflection) {
|
||||
owned_reflection = malloc(sizeof(*owned_reflection));
|
||||
if (!owned_reflection) {
|
||||
fail(error, STELA_AIR_ALLOCATION, "reflection allocation failed");
|
||||
return NULL;
|
||||
}
|
||||
struct reflecting r = {.entry = entry, .out = owned_reflection, .error = error};
|
||||
struct stela_air_constants constants = {specialization->constants,
|
||||
specialization->constant_count};
|
||||
if (!reflect(air, size, entry, &constants, &r))
|
||||
goto done;
|
||||
reflection = owned_reflection;
|
||||
}
|
||||
enum stela_metal_function_stage stage = reflection->stage;
|
||||
if (stage == STELA_METAL_VISIBLE) {
|
||||
fail(error, STELA_AIR_ARGUMENT, "visible functions compile into the functions that link them");
|
||||
@@ -812,12 +812,21 @@ stela_metal_compile(const void *air, size_t size, const char *entry,
|
||||
.max_mesh_vertices = target->max_mesh_vertices,
|
||||
.max_mesh_primitives = target->max_mesh_primitives,
|
||||
};
|
||||
shader = stela_air_stage_to_nir(air, size, entry, target->nir, &options, error);
|
||||
shader = stela_air_metal_stage_to_nir(air, size, entry, target->nir, &options, error);
|
||||
done:
|
||||
free(reflection);
|
||||
free(owned_reflection);
|
||||
return shader;
|
||||
}
|
||||
|
||||
nir_shader *
|
||||
stela_metal_compile(const void *air, size_t size, const char *entry,
|
||||
const struct stela_metal_target *target,
|
||||
const struct stela_metal_specialization *specialization,
|
||||
struct stela_air_error *error)
|
||||
{
|
||||
return stela_metal_compile_reflected(air, size, entry, target, specialization, NULL, error);
|
||||
}
|
||||
|
||||
void
|
||||
stela_metal_tessellation_stages(const struct stela_metal_target *target,
|
||||
const struct stela_metal_tessellation *tessellation,
|
||||
|
||||
@@ -230,8 +230,8 @@ bool stela_metal_reflect_bindings(const void *air, size_t size, const char *entr
|
||||
struct stela_air_error *error);
|
||||
|
||||
/* Calls visit with the name and stage of each function the AIR module lists,
|
||||
* for a library of source, whose container has no list. False after reporting
|
||||
* why, or when visit refuses one. */
|
||||
* for a library of source, whose container has no list. This reads only module
|
||||
* metadata. False after reporting why, or when visit refuses one. */
|
||||
typedef bool (*stela_metal_visit_function)(void *data, const char *name, size_t name_bytes,
|
||||
enum stela_metal_function_stage stage);
|
||||
bool stela_metal_functions(const void *air, size_t size, stela_metal_visit_function visit,
|
||||
@@ -246,7 +246,8 @@ bool stela_metal_stitch(const struct stela_air_stitch_source *sources, uint32_t
|
||||
#define STELA_METAL_SAMPLER_STATES 256u
|
||||
|
||||
/* The constexpr sampler states the AIR module declares, each Apple's
|
||||
* encoding, which metal/sampler.rs decodes. False after reporting why. */
|
||||
* encoding, which metal/sampler.rs decodes. This reads only module metadata.
|
||||
* False after reporting why. */
|
||||
bool stela_metal_sampler_states(const void *air, size_t size,
|
||||
uint64_t states[STELA_METAL_SAMPLER_STATES], uint32_t *count,
|
||||
struct stela_air_error *error);
|
||||
@@ -259,6 +260,16 @@ nir_shader *stela_metal_compile(const void *air, size_t size, const char *entry,
|
||||
const struct stela_metal_specialization *specialization,
|
||||
struct stela_air_error *error);
|
||||
|
||||
/* As stela_metal_compile, with the compiler's own successful reflection of
|
||||
* this exact AIR, entry and constant values. This reads only the stage, patch,
|
||||
* threadgroup bytes and varying descriptors with their identifiers. The
|
||||
* caller owns the reflection through the call. NULL asks it to reflect. */
|
||||
nir_shader *stela_metal_compile_reflected(const void *air, size_t size, const char *entry,
|
||||
const struct stela_metal_target *target,
|
||||
const struct stela_metal_specialization *specialization,
|
||||
const struct stela_metal_reflection *reflection,
|
||||
struct stela_air_error *error);
|
||||
|
||||
/* The vertex and control stages a tessellated pipeline runs ahead of its
|
||||
* post-tessellation vertex function (metal_abi.h), each with entry point
|
||||
* main, which stela_metal_release frees. */
|
||||
|
||||
@@ -2335,9 +2335,35 @@ undefined_phi_values(void)
|
||||
ralloc_free(nir);
|
||||
}
|
||||
|
||||
/* An unrelated recursive function does not give a declared entry a body
|
||||
* or make its recursion limit relevant. */
|
||||
static void
|
||||
reject_declared_entry_in_a_recursive_module(void)
|
||||
{
|
||||
LLVMMemoryBufferRef input = stela_air_test_custom_bitcode(
|
||||
"target datalayout = \"e-p:64:64-i64:64-n8:16:32\"\n"
|
||||
"target triple = \"air64_v28-apple-macosx26.7.0\"\n",
|
||||
"define internal void @cycle() {\ncall void @cycle()\nret void\n}\n"
|
||||
"declare void @kernel()\n",
|
||||
"!air.version = !{!0}\n!air.language_version = !{!1}\n!air.kernel = !{!2}\n"
|
||||
"!0 = !{i32 2, i32 8, i32 0}\n!1 = !{!\"Metal\", i32 4, i32 0, i32 0}\n"
|
||||
"!2 = !{ptr @kernel, !3, !3}\n!3 = !{}\n", "");
|
||||
const struct stela_air_options options = {
|
||||
.workgroup_size = {1, 1, 1}, .max_instructions = 100, .max_call_stack_depth = UINT32_MAX,
|
||||
};
|
||||
struct stela_air_error error;
|
||||
nir_shader *nir = stela_air_to_nir(LLVMGetBufferStart(input), LLVMGetBufferSize(input), "kernel",
|
||||
&test_nir_options, &options, &error);
|
||||
if (nir || error.kind != STELA_AIR_ARGUMENT)
|
||||
fprintf(stderr, "declared entry: %u %s\n", error.kind, error.detail);
|
||||
CHECK(!nir && error.kind == STELA_AIR_ARGUMENT && strstr(error.detail, "entry must be a defined"));
|
||||
LLVMDisposeMemoryBuffer(input);
|
||||
}
|
||||
|
||||
static void
|
||||
tests(void)
|
||||
{
|
||||
reject_declared_entry_in_a_recursive_module();
|
||||
struct stela_air_error error;
|
||||
LLVMMemoryBufferRef input = stela_air_test_bitcode(stela_air_test_store_body, "");
|
||||
nir_shader *nir = translate(input, &test_nir_options, 100, &error);
|
||||
|
||||
@@ -6,6 +6,8 @@
|
||||
#include "../metal_compiler.h"
|
||||
#include "air_effect_oracle.h"
|
||||
#include "air_test_fixture.h"
|
||||
#include "compiler/nir/nir_serialize.h"
|
||||
#include "util/blob.h"
|
||||
#include "util/ralloc.h"
|
||||
#include <assert.h>
|
||||
#include <stdio.h>
|
||||
@@ -171,6 +173,9 @@ static const char *derived = DERIVED("%x = shl nsw i32 %w, 1\n");
|
||||
static const char *converted = DERIVED("%f = call float @air.convert.f.f32.s.i32(i32 %w)\n"
|
||||
"%d = fmul fast float %f, 2.000000e+00\n"
|
||||
"%x = call i32 @air.convert.s.i32.f.f32(float %d)\n");
|
||||
/* A constructor whose helper needs the ordinary inlining path. */
|
||||
static const char *derived_with_helper = DERIVED("%x = call i32 @twice(i32 %w)\n")
|
||||
"define internal i32 @twice(i32 %w) {\n%x = shl nsw i32 %w, 1\nret i32 %x\n}\n";
|
||||
/* A constructor that calls an AIR function, which no constant folds. */
|
||||
static const char *called = DERIVED("%x = call i32 @air.unknown(i32 %w)\n");
|
||||
|
||||
@@ -229,6 +234,14 @@ static const char *called = DERIVED("%x = call i32 @air.unknown(i32 %w)\n");
|
||||
|
||||
static const char *conditional =
|
||||
CONDITIONAL("br i1 %on, label %tinted, label %untinted\n", "bool");
|
||||
/* A shader helper uses the same function constant as its leaf constructor. */
|
||||
static const char *conditional_with_helper =
|
||||
CONDITIONAL("%choose = call i1 @choose_tint(i1 %on)\n"
|
||||
"br i1 %choose, label %tinted, label %untinted\n", "bool")
|
||||
"define internal i1 @choose_tint(i1 %enabled) {\n"
|
||||
"%raw = load i8, ptr addrspace(2) @use_tint.init, align 1\n"
|
||||
"%selected = icmp ne i8 %raw, 0\n"
|
||||
"%both = and i1 %selected, %enabled\nret i1 %both\n}\n";
|
||||
/* One reading tint whatever use_tint is. */
|
||||
static const char *unguarded = CONDITIONAL("br label %tinted\n", "bool");
|
||||
/* One whose read Apple's compiler hoists ahead of what decides it. */
|
||||
@@ -898,6 +911,48 @@ modules_list_their_functions(void)
|
||||
assert(count == 1);
|
||||
}
|
||||
|
||||
static void
|
||||
discovery_reports_malformed_metadata(void)
|
||||
{
|
||||
struct stela_air_error error;
|
||||
unsigned listed = 0;
|
||||
const char header[] = "BC\xc0\xde";
|
||||
assert(!stela_metal_functions(header, sizeof(header) - 1, count_function, &listed, &error));
|
||||
assert(error.kind == STELA_AIR_BITCODE && !listed);
|
||||
uint64_t states[STELA_METAL_SAMPLER_STATES];
|
||||
uint32_t count = 1;
|
||||
assert(!stela_metal_sampler_states(header, sizeof(header) - 1, states, &count, &error));
|
||||
assert(error.kind == STELA_AIR_BITCODE && !count);
|
||||
|
||||
char *fixture = ralloc_asprintf(NULL, "%s!air.visible = !{!90}\n!90 = !{null}\n", kernel);
|
||||
LLVMMemoryBufferRef input = bitcode(fixture);
|
||||
ralloc_free(fixture);
|
||||
assert(!stela_metal_functions(LLVMGetBufferStart(input), LLVMGetBufferSize(input),
|
||||
count_function, &listed, &error));
|
||||
assert(error.kind == STELA_AIR_METADATA);
|
||||
LLVMDisposeMemoryBuffer(input);
|
||||
}
|
||||
|
||||
static void
|
||||
reflection_requires_a_unique_listed_entry(void)
|
||||
{
|
||||
struct stela_metal_reflection reflection;
|
||||
struct stela_air_error error;
|
||||
char *fixture = ralloc_asprintf(NULL, "%s!air.visible = !{!2}\n", kernel);
|
||||
LLVMMemoryBufferRef input = bitcode(fixture);
|
||||
ralloc_free(fixture);
|
||||
assert(!stela_metal_reflect(LLVMGetBufferStart(input), LLVMGetBufferSize(input),
|
||||
"kernel", NULL, 0, &reflection, &error));
|
||||
assert(error.kind == STELA_AIR_METADATA && strstr(error.detail, "entry listed more than once"));
|
||||
LLVMDisposeMemoryBuffer(input);
|
||||
|
||||
input = bitcode(kernel);
|
||||
assert(!stela_metal_reflect(LLVMGetBufferStart(input), LLVMGetBufferSize(input),
|
||||
"air.wg.barrier", NULL, 0, &reflection, &error));
|
||||
assert(error.kind == STELA_AIR_ARGUMENT);
|
||||
LLVMDisposeMemoryBuffer(input);
|
||||
}
|
||||
|
||||
static void
|
||||
render_stages_compile_at_their_linked_locations(void)
|
||||
{
|
||||
@@ -1102,6 +1157,23 @@ function_constants_reflect_and_specialize(void)
|
||||
fprintf(stderr, "constants: %u %s\n", error.kind, error.detail);
|
||||
/* Every read folds to its value; none is left in constant data. */
|
||||
assert(shader && shader->constant_data_size == 0);
|
||||
assert(reflect_specialized(constants, "constants", values, 3, &reflection, &error));
|
||||
LLVMMemoryBufferRef input = bitcode(constants);
|
||||
nir_shader *prepared = stela_metal_compile_reflected(
|
||||
LLVMGetBufferStart(input), LLVMGetBufferSize(input), "constants",
|
||||
&target, &specialization, &reflection, &error);
|
||||
LLVMDisposeMemoryBuffer(input);
|
||||
assert(prepared);
|
||||
struct blob normal, reused;
|
||||
blob_init(&normal);
|
||||
blob_init(&reused);
|
||||
nir_serialize(&normal, shader, true);
|
||||
nir_serialize(&reused, prepared, true);
|
||||
assert(!normal.out_of_memory && !reused.out_of_memory);
|
||||
assert(normal.size == reused.size && !memcmp(normal.data, reused.data, normal.size));
|
||||
blob_finish(&normal);
|
||||
blob_finish(&reused);
|
||||
stela_metal_release(prepared);
|
||||
stela_metal_release(shader);
|
||||
|
||||
/* scale is optional, and its definedness test folds to false. */
|
||||
@@ -1170,6 +1242,11 @@ derived_constants_are_constructed_from_their_function_constants(void)
|
||||
assert(shader && stores_constant(shader, 10));
|
||||
stela_metal_release(shader);
|
||||
|
||||
assert(reflect_specialized(derived_with_helper, "derived", values, 1, &reflection, &error));
|
||||
shader = compile(derived_with_helper, "derived", &specialization, &error);
|
||||
assert(shader && stores_constant(shader, 10));
|
||||
stela_metal_release(shader);
|
||||
|
||||
/* Without width, its definedness test selects eight. */
|
||||
specialization.constant_count = 0;
|
||||
shader = compile(derived, "derived", &specialization, &error);
|
||||
@@ -1182,6 +1259,43 @@ derived_constants_are_constructed_from_their_function_constants(void)
|
||||
strstr(error.detail, "program-scope constants"));
|
||||
}
|
||||
|
||||
static void
|
||||
constructed_globals_are_bounded(void)
|
||||
{
|
||||
char *fixture = ralloc_strdup(NULL, derived);
|
||||
for (unsigned i = 0; i < AIR_MAX_ARGUMENTS; i++)
|
||||
assert(ralloc_asprintf_append(&fixture, "@extra%u = internal addrspace(2) global i32 0\n", i));
|
||||
LLVMMemoryBufferRef input = bitcode(fixture);
|
||||
ralloc_free(fixture);
|
||||
struct stela_metal_reflection reflection;
|
||||
struct stela_air_error error;
|
||||
const struct stela_air_constant_value unused = {0};
|
||||
assert(!stela_metal_reflect(LLVMGetBufferStart(input), LLVMGetBufferSize(input),
|
||||
"derived", &unused, 0, &reflection, &error));
|
||||
assert(error.kind == STELA_AIR_INSTRUCTION && strstr(error.detail, "program-scope constants"));
|
||||
LLVMDisposeMemoryBuffer(input);
|
||||
}
|
||||
|
||||
static void
|
||||
constructor_priorities_are_integer_literals(void)
|
||||
{
|
||||
const char *priority = strstr(derived, "65535");
|
||||
assert(priority);
|
||||
const char *invalid[] = {"undef", "poison"};
|
||||
for (unsigned i = 0; i < ARRAY_SIZE(invalid); i++) {
|
||||
char *fixture = ralloc_asprintf(NULL, "%.*s%s%s", (int)(priority - derived), derived,
|
||||
invalid[i], priority + strlen("65535"));
|
||||
LLVMMemoryBufferRef input = bitcode(fixture);
|
||||
ralloc_free(fixture);
|
||||
struct stela_metal_reflection reflection;
|
||||
struct stela_air_error error;
|
||||
assert(!stela_metal_reflect(LLVMGetBufferStart(input), LLVMGetBufferSize(input),
|
||||
"derived", NULL, 0, &reflection, &error));
|
||||
assert(error.kind == STELA_AIR_METADATA && strstr(error.detail, "invalid AIR constructor list"));
|
||||
LLVMDisposeMemoryBuffer(input);
|
||||
}
|
||||
}
|
||||
|
||||
static unsigned
|
||||
count_intrinsic(nir_shader *shader, nir_intrinsic_op op)
|
||||
{
|
||||
@@ -1215,6 +1329,10 @@ function_constants_select_arguments(void)
|
||||
STELA_METAL_ACCESS_READ | STELA_METAL_ACCESS_WRITE;
|
||||
assert(reflection.buffer_count == 2 && reflection.buffers[1].index == 1 &&
|
||||
reflection.buffers[1].access == access);
|
||||
assert(reflect_specialized(conditional_with_helper, "conditional", &value, 1,
|
||||
&reflection, &error));
|
||||
assert(reflection.buffer_count == 2 && reflection.buffers[1].index == 1 &&
|
||||
reflection.buffers[1].access == access);
|
||||
const struct stela_metal_specialization specialization = {
|
||||
.workgroup_size = {64, 1, 1}, .constants = &value, .constant_count = 1,
|
||||
};
|
||||
@@ -1250,6 +1368,85 @@ function_constants_select_arguments(void)
|
||||
}
|
||||
}
|
||||
|
||||
/* The false constant makes the helper unreachable, but admission of the
|
||||
* original call graph still precedes early specialization. */
|
||||
static void
|
||||
specialized_fragment_calls_preserve_graph_admission(void)
|
||||
{
|
||||
const char *body =
|
||||
"@enabled = external addrspace(2) constant i8\n"
|
||||
"define <4 x float> @entry() {\n"
|
||||
"%value = load i8, ptr addrspace(2) @enabled\n"
|
||||
"%on = icmp ne i8 %value, 0\n"
|
||||
"br i1 %on, label %active, label %inactive\n"
|
||||
"active:\n%result = call <4 x float> @helper()\nret <4 x float> %result\n"
|
||||
"inactive:\nret <4 x float> zeroinitializer\n}\n"
|
||||
"!air.fragment = !{!2}\n!2 = !{ptr @entry, !3, !4}\n!3 = !{!30}\n!4 = !{}\n"
|
||||
"!30 = !{!\"air.render_target\", i32 0, i32 0, !\"air.arg_type_name\", !\"float4\","
|
||||
" !\"air.arg_name\", !\"color\"}\n"
|
||||
"!air.function_constants = !{!50}\n!50 = !{ptr addrspace(2) @enabled, !\"bool\", !\"enabled\", i32 0}\n";
|
||||
const char *unsupported = "declare <4 x float> @unsupported()\n"
|
||||
"define internal <4 x float> @helper() {\n"
|
||||
"%result = call <4 x float> @unsupported()\nret <4 x float> %result\n}\n";
|
||||
char *fixture = ralloc_asprintf(NULL, "%s%s", body, unsupported);
|
||||
struct stela_air_error error;
|
||||
const struct stela_metal_specialization defaults = {0};
|
||||
uint8_t enabled = 0;
|
||||
const struct stela_air_constant_value value = {0, &enabled, sizeof(enabled)};
|
||||
const struct stela_metal_specialization explicit = {.constants = &value, .constant_count = 1};
|
||||
nir_shader *a = compile(fixture, "entry", &defaults, &error);
|
||||
nir_shader *b = compile(fixture, "entry", &explicit, &error);
|
||||
assert(a && b);
|
||||
struct blob original, folded;
|
||||
blob_init(&original);
|
||||
blob_init(&folded);
|
||||
nir_serialize(&original, a, true);
|
||||
nir_serialize(&folded, b, true);
|
||||
assert(!original.out_of_memory && !folded.out_of_memory && original.size == folded.size &&
|
||||
!memcmp(original.data, folded.data, original.size));
|
||||
blob_finish(&original);
|
||||
blob_finish(&folded);
|
||||
stela_metal_release(a);
|
||||
stela_metal_release(b);
|
||||
|
||||
enabled = 1;
|
||||
assert(!compile(fixture, "entry", &explicit, &error));
|
||||
assert(error.kind == STELA_AIR_INSTRUCTION && strstr(error.detail, "unresolved external function"));
|
||||
const struct stela_air_error failure = error;
|
||||
assert(ralloc_asprintf_append(&fixture,
|
||||
"declare i32 @air.get_size_visible_function_table(ptr addrspace(1))\n"));
|
||||
assert(!compile(fixture, "entry", &explicit, &error));
|
||||
assert(error.kind == failure.kind && error.instruction == failure.instruction &&
|
||||
!strcmp(error.detail, failure.detail));
|
||||
ralloc_free(fixture);
|
||||
|
||||
enabled = 0;
|
||||
fixture = ralloc_asprintf(NULL, "%s%s", body, "define internal <4 x float> @helper() {\n"
|
||||
"%result = call <4 x float> @helper()\nret <4 x float> %result\n}\n");
|
||||
assert(!compile(fixture, "entry", &explicit, &error));
|
||||
assert(error.kind == STELA_AIR_INSTRUCTION && strstr(error.detail, "recursive calls outside"));
|
||||
ralloc_free(fixture);
|
||||
|
||||
fixture = ralloc_asprintf(NULL, "%s%s", body, "define internal <4 x float> @helper() {\n"
|
||||
"%result = call <4 x float> @chain0()\nret <4 x float> %result\n}\n");
|
||||
for (unsigned i = 0; i < 256; i++) {
|
||||
assert(ralloc_asprintf_append(&fixture, "define internal <4 x float> @chain%u() {\n"
|
||||
"%%result = call <4 x float> @chain%u()\nret <4 x float> %%result\n}\n", i, i + 1));
|
||||
}
|
||||
assert(ralloc_asprintf_append(&fixture,
|
||||
"define internal <4 x float> @chain256() {\nret <4 x float> zeroinitializer\n}\n"));
|
||||
LLVMMemoryBufferRef input = bitcode(fixture);
|
||||
ralloc_free(fixture);
|
||||
const struct stela_air_stage_options stage = {
|
||||
.stage = STELA_AIR_FRAGMENT, .resources = {.max_instructions = 10000, .constants = &value,
|
||||
.constant_count = 1},
|
||||
};
|
||||
assert(!stela_air_metal_stage_to_nir(LLVMGetBufferStart(input), LLVMGetBufferSize(input),
|
||||
"entry", &nir_options, &stage, &error));
|
||||
assert(error.kind == STELA_AIR_LIMIT && strstr(error.detail, "call depth exceeded"));
|
||||
LLVMDisposeMemoryBuffer(input);
|
||||
}
|
||||
|
||||
/* An output a false function constant makes absent is not one. */
|
||||
static void
|
||||
function_constants_select_outputs(void)
|
||||
@@ -1420,6 +1617,24 @@ defined_functions_inline_into_their_callers(void)
|
||||
error.kind == STELA_AIR_INSTRUCTION && strstr(error.detail, "recursive"));
|
||||
}
|
||||
|
||||
/* A module with no direct call edges still checks unsupported calls during lowering. */
|
||||
static void
|
||||
unresolved_calls_are_rejected_without_a_call_graph(void)
|
||||
{
|
||||
const char *callees[] = {"@external", "null"};
|
||||
const char *errors[] = {"unresolved external function external", "only from visible function tables"};
|
||||
const struct stela_metal_specialization specialization = {.workgroup_size = {64, 1, 1}};
|
||||
for (unsigned i = 0; i < ARRAY_SIZE(callees); i++) {
|
||||
char *fixture = ralloc_asprintf(NULL,
|
||||
"declare void @external()\ndefine void @unresolved() {\ncall void %s()\nret void\n}\n"
|
||||
"!air.kernel = !{!2}\n!2 = !{ptr @unresolved, !3, !3}\n!3 = !{}\n", callees[i]);
|
||||
struct stela_air_error error;
|
||||
assert(!compile(fixture, "unresolved", &specialization, &error));
|
||||
assert(error.kind == STELA_AIR_INSTRUCTION && strstr(error.detail, errors[i]));
|
||||
ralloc_free(fixture);
|
||||
}
|
||||
}
|
||||
|
||||
/* os_log.log_error("hi %d %f %ld", ...) through the method Apple's compiler
|
||||
* defines for it, in a kernel, with a float its call promotes and a long. */
|
||||
static const char *logging =
|
||||
@@ -1873,6 +2088,8 @@ main(void)
|
||||
{
|
||||
glsl_type_singleton_init_or_ref();
|
||||
modules_list_their_functions();
|
||||
discovery_reports_malformed_metadata();
|
||||
reflection_requires_a_unique_listed_entry();
|
||||
kernels_reflect_and_compile_their_threadgroup_memory();
|
||||
dynamic_kernels_take_their_dispatch_shape();
|
||||
render_stages_compile_at_their_linked_locations();
|
||||
@@ -1881,14 +2098,18 @@ main(void)
|
||||
mesh_stages_compile_with_their_launch();
|
||||
function_constants_reflect_and_specialize();
|
||||
derived_constants_are_constructed_from_their_function_constants();
|
||||
constructed_globals_are_bounded();
|
||||
constructor_priorities_are_integer_literals();
|
||||
function_constants_select_outputs();
|
||||
older_kernels_compile();
|
||||
unoptimized_kernels_compile();
|
||||
undefined_lanes_read_as_anything();
|
||||
function_constants_select_arguments();
|
||||
specialized_fragment_calls_preserve_graph_admission();
|
||||
arrays_reflect_each_slot();
|
||||
bindings_reflect_their_structures();
|
||||
defined_functions_inline_into_their_callers();
|
||||
unresolved_calls_are_rejected_without_a_call_graph();
|
||||
stitched_functions_call_their_nodes_in_order();
|
||||
os_log_appends_self_contained_records();
|
||||
linked_functions_resolve_tables_and_externals();
|
||||
|
||||
@@ -204,10 +204,13 @@ impl ArgumentTable {
|
||||
|
||||
pub fn encode(&self) -> Vec<u8> {
|
||||
let mut bytes = alloc::vec![0; Self::BYTES as usize];
|
||||
let mut writer = Writer {
|
||||
bytes: &mut bytes,
|
||||
offset: 0,
|
||||
};
|
||||
self.encode_into(&mut bytes);
|
||||
bytes
|
||||
}
|
||||
|
||||
pub(super) fn encode_into(&self, bytes: &mut [u8]) {
|
||||
debug_assert_eq!(bytes.len(), Self::BYTES as usize);
|
||||
let mut writer = Writer { bytes, offset: 0 };
|
||||
self.buffers
|
||||
.iter()
|
||||
.for_each(|buffer| writer.u64(buffer.address));
|
||||
@@ -219,7 +222,6 @@ impl ArgumentTable {
|
||||
.chain(&self.samplers)
|
||||
.chain(&self.attachments)
|
||||
.for_each(|id| writer.u64(id.0));
|
||||
bytes
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ use super::{
|
||||
physical::{Features, FormatSupport, PhysicalDevice},
|
||||
},
|
||||
};
|
||||
use alloc::{string::String, vec::Vec};
|
||||
use alloc::{boxed::Box, string::String, vec::Vec};
|
||||
|
||||
pub mod block;
|
||||
|
||||
@@ -162,6 +162,32 @@ option_set! {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
enum PixelFormats {
|
||||
/// The capabilities of every known format, in `PixelFormat::ALL` order.
|
||||
Indexed(Box<IndexedPixelFormats>),
|
||||
/// A decoded list with its original omissions, order and duplicates.
|
||||
Listed(Box<[(PixelFormat, FormatCapabilities)]>),
|
||||
}
|
||||
|
||||
type IndexedPixelFormats = [FormatCapabilities; PixelFormat::ALL.len()];
|
||||
|
||||
fn indexed_format(formats: &IndexedPixelFormats, format: PixelFormat) -> FormatCapabilities {
|
||||
formats[format.index()]
|
||||
}
|
||||
|
||||
impl PixelFormats {
|
||||
fn get(&self, format: PixelFormat) -> FormatCapabilities {
|
||||
match self {
|
||||
Self::Indexed(formats) => indexed_format(formats, format),
|
||||
Self::Listed(formats) => formats
|
||||
.iter()
|
||||
.find(|(known, _)| *known == format)
|
||||
.map_or(FormatCapabilities::EMPTY, |(_, capabilities)| *capabilities),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `MTLSize`.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct Size {
|
||||
@@ -289,7 +315,7 @@ pub struct Capabilities {
|
||||
sparse_samples: Vec<(PixelFormat, SampleCounts)>,
|
||||
vertex_formats: Vec<VertexFormat>,
|
||||
families: Vec<GpuFamily>,
|
||||
formats: Vec<(PixelFormat, FormatCapabilities)>,
|
||||
formats: PixelFormats,
|
||||
gaps: Vec<Gap>,
|
||||
linear_row_alignment: u64,
|
||||
linear_offset_alignment: u64,
|
||||
@@ -340,10 +366,7 @@ impl Capabilities {
|
||||
|
||||
/// Capabilities of `format`; empty for formats this device cannot store.
|
||||
pub fn format(&self, format: PixelFormat) -> FormatCapabilities {
|
||||
self.formats
|
||||
.iter()
|
||||
.find(|(known, _)| *known == format)
|
||||
.map_or(FormatCapabilities::EMPTY, |(_, capabilities)| *capabilities)
|
||||
self.formats.get(format)
|
||||
}
|
||||
|
||||
/// Every refused capability, each listed once.
|
||||
@@ -605,12 +628,7 @@ impl Derivation<'_> {
|
||||
let features = &device.features;
|
||||
|
||||
let formats = self.formats();
|
||||
let caps = |format: PixelFormat| {
|
||||
formats
|
||||
.iter()
|
||||
.find(|(known, _)| *known == format)
|
||||
.map_or(FormatCapabilities::EMPTY, |(_, capabilities)| *capabilities)
|
||||
};
|
||||
let caps = |format| indexed_format(&formats, format);
|
||||
let float32 = [
|
||||
PixelFormat::R32Float,
|
||||
PixelFormat::Rg32Float,
|
||||
@@ -933,7 +951,7 @@ impl Derivation<'_> {
|
||||
sparse_samples,
|
||||
vertex_formats,
|
||||
families: Vec::new(),
|
||||
formats,
|
||||
formats: PixelFormats::Indexed(formats),
|
||||
gaps: Vec::new(),
|
||||
linear_row_alignment: self.platform.linear_row_alignment,
|
||||
linear_offset_alignment: self.platform.linear_offset_alignment,
|
||||
@@ -950,23 +968,26 @@ impl Derivation<'_> {
|
||||
capabilities
|
||||
}
|
||||
|
||||
fn formats(&mut self) -> Vec<(PixelFormat, FormatCapabilities)> {
|
||||
let mut formats = Vec::with_capacity(PixelFormat::ALL.len());
|
||||
for format in PixelFormat::ALL {
|
||||
fn formats(&mut self) -> Box<IndexedPixelFormats> {
|
||||
let mut formats = Box::new([FormatCapabilities::EMPTY; PixelFormat::ALL.len()]);
|
||||
for (format, capabilities) in PixelFormat::ALL.iter().zip(formats.iter_mut()) {
|
||||
let description = format.describe();
|
||||
let capabilities = match description.realization {
|
||||
*capabilities = match description.realization {
|
||||
Ok(realization) => {
|
||||
let support = self.device.formats.get(realization.format);
|
||||
self.format_capabilities(description, support, realization.is_identity())
|
||||
}
|
||||
Err(_) => FormatCapabilities::EMPTY,
|
||||
};
|
||||
formats.push((*format, capabilities));
|
||||
}
|
||||
self.compression_gaps(&formats);
|
||||
if formats.iter().any(|(format, capabilities)| {
|
||||
format.describe().realization.is_err() && capabilities.is_empty()
|
||||
}) {
|
||||
if PixelFormat::ALL
|
||||
.iter()
|
||||
.zip(formats.iter())
|
||||
.any(|(format, capabilities)| {
|
||||
format.describe().realization.is_err() && capabilities.is_empty()
|
||||
})
|
||||
{
|
||||
self.gap("extended-range and 4:2:2 pixel formats", Cause::Driver);
|
||||
}
|
||||
formats
|
||||
@@ -1016,7 +1037,7 @@ impl Derivation<'_> {
|
||||
supported
|
||||
}
|
||||
|
||||
fn compression_gaps(&mut self, formats: &[(PixelFormat, FormatCapabilities)]) {
|
||||
fn compression_gaps(&mut self, formats: &IndexedPixelFormats) {
|
||||
let groups = [
|
||||
(Compression::Bc, "BC pixel formats"),
|
||||
(Compression::Etc2Eac, "ETC2 and EAC pixel formats"),
|
||||
@@ -1025,8 +1046,9 @@ impl Derivation<'_> {
|
||||
(Compression::Pvrtc, "PVRTC pixel formats"),
|
||||
];
|
||||
for (compression, name) in groups {
|
||||
let unusable = formats
|
||||
let unusable = PixelFormat::ALL
|
||||
.iter()
|
||||
.zip(formats)
|
||||
.filter(|(format, _)| format.describe().compression == compression)
|
||||
.all(|(_, capabilities)| !capabilities.contains(FormatCapabilities::READ));
|
||||
if unusable {
|
||||
@@ -1140,10 +1162,7 @@ impl Derivation<'_> {
|
||||
|
||||
/// Tier 1 reads and writes the 32-bit single-channel formats in one
|
||||
/// function; tier 2 adds Apple's listed 8-, 16- and 32-bit formats.
|
||||
fn read_write_tier(
|
||||
&mut self,
|
||||
formats: &[(PixelFormat, FormatCapabilities)],
|
||||
) -> ReadWriteTextureTier {
|
||||
fn read_write_tier(&mut self, formats: &IndexedPixelFormats) -> ReadWriteTextureTier {
|
||||
use PixelFormat as P;
|
||||
const TIER1: [PixelFormat; 3] = [P::R32Float, P::R32Uint, P::R32Sint];
|
||||
const TIER2: [PixelFormat; 12] = [
|
||||
@@ -1162,9 +1181,7 @@ impl Derivation<'_> {
|
||||
];
|
||||
const TIER2_8BIT: [PixelFormat; 3] = [P::R8Unorm, P::R8Uint, P::R8Sint];
|
||||
let read_write = |format: &PixelFormat| {
|
||||
formats.iter().any(|(known, capabilities)| {
|
||||
known == format && capabilities.contains(FormatCapabilities::READ_WRITE)
|
||||
})
|
||||
indexed_format(formats, *format).contains(FormatCapabilities::READ_WRITE)
|
||||
};
|
||||
let tier1 = TIER1.iter().all(read_write);
|
||||
let tier2 = tier1 && TIER2.iter().chain(&TIER2_8BIT).all(read_write);
|
||||
|
||||
@@ -10,7 +10,10 @@
|
||||
//! the rest of their array zero; strings are UTF-8 with their length.
|
||||
//! Decoding accepts only a block the encoder writes, which it checks by
|
||||
//! encoding the result again.
|
||||
use super::{Capabilities, Cause, FormatCapabilities, Gap, Limits, Size, TexelBufferAlignment};
|
||||
use super::{
|
||||
Capabilities, Cause, FormatCapabilities, Gap, IndexedPixelFormats, Limits, PixelFormats, Size,
|
||||
TexelBufferAlignment,
|
||||
};
|
||||
use crate::metal::{
|
||||
abi::{
|
||||
ArgumentBuffersTier, CounterSamplingPoint, DeviceLocation, GpuFamily, ReadWriteTextureTier,
|
||||
@@ -354,9 +357,10 @@ impl Block {
|
||||
constant_vertex_step: has(Flags::CONSTANT_VERTEX_STEP),
|
||||
counter_sampling,
|
||||
sparse_volumes: has(Flags::SPARSE_VOLUMES),
|
||||
sparse_samples: formats(&self.sparse_formats, self.sparse_format_count, |value| {
|
||||
SampleCounts::from_bits(value)
|
||||
})?,
|
||||
sparse_samples: formats(
|
||||
listed(&self.sparse_formats, self.sparse_format_count)?,
|
||||
SampleCounts::from_bits,
|
||||
)?,
|
||||
vertex_formats: VertexFormat::ALL
|
||||
.iter()
|
||||
.copied()
|
||||
@@ -366,11 +370,7 @@ impl Block {
|
||||
.iter()
|
||||
.map(|&raw| GpuFamily::from_raw(raw).ok_or(MALFORMED))
|
||||
.collect::<Result<_>>()?,
|
||||
formats: formats(
|
||||
&self.formats,
|
||||
self.format_count,
|
||||
FormatCapabilities::from_bits,
|
||||
)?,
|
||||
formats: pixel_formats(listed(&self.formats, self.format_count)?)?,
|
||||
gaps,
|
||||
linear_row_alignment: self.linear_row_alignment,
|
||||
linear_offset_alignment: self.linear_offset_alignment,
|
||||
@@ -406,13 +406,12 @@ fn text(field: &[u8], offset: u32, bytes: u32) -> Result<String> {
|
||||
))
|
||||
}
|
||||
|
||||
/// The first `count` format entries, each value decoded.
|
||||
/// Format entries in wire order, each value decoded.
|
||||
fn formats<T>(
|
||||
entries: &[FormatEntry],
|
||||
count: u32,
|
||||
decode: impl Fn(u32) -> Option<T>,
|
||||
) -> Result<Vec<(PixelFormat, T)>> {
|
||||
listed(entries, count)?
|
||||
entries
|
||||
.iter()
|
||||
.map(|entry| {
|
||||
Ok((
|
||||
@@ -423,6 +422,24 @@ fn formats<T>(
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn pixel_formats(entries: &[FormatEntry]) -> Result<PixelFormats> {
|
||||
if entries.len() == PixelFormat::ALL.len()
|
||||
&& entries
|
||||
.iter()
|
||||
.zip(PixelFormat::ALL)
|
||||
.all(|(entry, format)| u64::from(entry.format) == format.raw())
|
||||
{
|
||||
let mut formats: Box<IndexedPixelFormats> =
|
||||
Box::new([FormatCapabilities::EMPTY; PixelFormat::ALL.len()]);
|
||||
for (capabilities, entry) in formats.iter_mut().zip(entries) {
|
||||
*capabilities = FormatCapabilities::from_bits(entry.value).ok_or(MALFORMED)?;
|
||||
}
|
||||
return Ok(PixelFormats::Indexed(formats));
|
||||
}
|
||||
let formats = formats(entries, FormatCapabilities::from_bits)?;
|
||||
Ok(PixelFormats::Listed(formats.into_boxed_slice()))
|
||||
}
|
||||
|
||||
/// Copies `text` into the start of `field`, returning its length.
|
||||
fn put_text(field: &mut [u8], text: &str, what: &'static str) -> Result<u32> {
|
||||
let bytes = text.as_bytes();
|
||||
@@ -456,6 +473,25 @@ fn format_entry(format: PixelFormat, value: u32) -> Result<FormatEntry> {
|
||||
})
|
||||
}
|
||||
|
||||
fn put_pixel_formats(field: &mut [FormatEntry], formats: &PixelFormats) -> Result<u32> {
|
||||
let what = "pixel format count";
|
||||
let encode = |(format, capabilities): (PixelFormat, FormatCapabilities)| {
|
||||
format_entry(format, capabilities.bits())
|
||||
};
|
||||
match formats {
|
||||
PixelFormats::Indexed(formats) => put_list(
|
||||
field,
|
||||
PixelFormat::ALL
|
||||
.iter()
|
||||
.copied()
|
||||
.zip(formats.iter().copied()),
|
||||
what,
|
||||
encode,
|
||||
),
|
||||
PixelFormats::Listed(formats) => put_list(field, formats.iter().copied(), what, encode),
|
||||
}
|
||||
}
|
||||
|
||||
impl Capabilities {
|
||||
/// The block that carries these capabilities across the boundary.
|
||||
pub fn block(&self) -> Result<Box<Block>> {
|
||||
@@ -473,12 +509,7 @@ impl Capabilities {
|
||||
"GPU family count",
|
||||
|family| Ok(family.raw()),
|
||||
)?;
|
||||
block.format_count = put_list(
|
||||
&mut block.formats,
|
||||
self.formats.iter(),
|
||||
"pixel format count",
|
||||
|&(format, capabilities)| format_entry(format, capabilities.bits()),
|
||||
)?;
|
||||
block.format_count = put_pixel_formats(&mut block.formats, &self.formats)?;
|
||||
block.sparse_format_count = put_list(
|
||||
&mut block.sparse_formats,
|
||||
self.sparse_samples.iter(),
|
||||
@@ -636,6 +667,44 @@ mod tests {
|
||||
let block = capabilities.block().unwrap();
|
||||
assert_eq!(block.capabilities().unwrap(), capabilities);
|
||||
assert!(block.family_count > 0 && block.format_count > 0 && block.gap_count > 0);
|
||||
for (format, entry) in PixelFormat::ALL.iter().zip(&block.formats) {
|
||||
assert_eq!(format.raw(), u64::from(entry.format));
|
||||
assert_eq!(capabilities.format(*format).bits(), entry.value);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nonstandard_pixel_format_lists_keep_wire_order_and_first_match() {
|
||||
let capabilities = fixture::capabilities();
|
||||
let mut block = capabilities.block().unwrap();
|
||||
let bgra = PixelFormat::Bgra8Unorm;
|
||||
let rgba = PixelFormat::Rgba8Unorm;
|
||||
let entry = |format: PixelFormat, value: FormatCapabilities| FormatEntry {
|
||||
format: format.raw() as u32,
|
||||
value: value.bits(),
|
||||
};
|
||||
block.formats.fill(FormatEntry::default());
|
||||
block.formats[..3].copy_from_slice(&[
|
||||
entry(bgra, FormatCapabilities::EMPTY),
|
||||
entry(rgba, FormatCapabilities::READ),
|
||||
entry(bgra, FormatCapabilities::WRITE),
|
||||
]);
|
||||
block.format_count = 3;
|
||||
let decoded = block.capabilities().unwrap();
|
||||
assert_eq!(decoded.format(bgra), FormatCapabilities::EMPTY);
|
||||
assert_eq!(decoded.format(rgba), FormatCapabilities::READ);
|
||||
assert_eq!(
|
||||
decoded.format(PixelFormat::Depth32Float),
|
||||
FormatCapabilities::EMPTY
|
||||
);
|
||||
assert_eq!(decoded.block().unwrap(), block);
|
||||
|
||||
block.formats[3..].fill(entry(rgba, FormatCapabilities::EMPTY));
|
||||
block.format_count = FORMATS as u32;
|
||||
assert_eq!(block.capabilities().unwrap().block().unwrap(), block);
|
||||
|
||||
block.formats[1].format = u32::MAX;
|
||||
assert_eq!(block.capabilities(), Err(MALFORMED));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -336,11 +336,12 @@ impl Bindings {
|
||||
let address = match table.address {
|
||||
Some(address) => address,
|
||||
None => {
|
||||
let upload = recorder.upload(
|
||||
let (upload, bytes) = recorder.uploads.zeroed(
|
||||
resolver,
|
||||
&table.slots.encode(),
|
||||
ArgumentTable::BYTES as usize,
|
||||
ArgumentTable::ALIGNMENT,
|
||||
)?;
|
||||
table.slots.encode_into(bytes);
|
||||
table.address = Some(upload.address);
|
||||
upload.address
|
||||
}
|
||||
|
||||
@@ -22,6 +22,7 @@
|
||||
//! call.
|
||||
mod bindings;
|
||||
pub mod ffi;
|
||||
mod library_cache;
|
||||
#[cfg(feature = "metal-linked")]
|
||||
mod linked;
|
||||
#[cfg(test)]
|
||||
@@ -31,13 +32,13 @@ use super::{
|
||||
abi::{DataType, FunctionType, IndexType, TessellationControlPointIndexType, TextureType},
|
||||
capabilities::ShaderFeatures,
|
||||
error::{Error, Result, ensure, require},
|
||||
library::{Air, Header, Library},
|
||||
library::Air,
|
||||
reflection::Binding,
|
||||
shader::{
|
||||
Access, AttributeUse, BufferUse, ColorOutput, CompiledShader, Compiler, DeclaredAttribute,
|
||||
FunctionConstant, Interface, Linking, MAX_PATCH_CONTROL_POINTS, NumericClass, Patch,
|
||||
PatchDomain, Provenance, Reflection, Refusal, Scalar, Specialization, Stage, Tessellation,
|
||||
TessellationStages, TextureUse, ThreadgroupUse, Varying,
|
||||
PatchDomain, PreparedFunction, Provenance, Reflection, Refusal, Scalar, Specialization,
|
||||
Stage, Tessellation, TessellationStages, TextureUse, ThreadgroupUse, Varying,
|
||||
},
|
||||
stitching::{StitchedGraph, StitchedNode},
|
||||
vertex::{Attribute, STRIDE_DYNAMIC, StageInputDescriptor, VertexDescriptor},
|
||||
@@ -56,6 +57,8 @@ use core::{
|
||||
slice, str,
|
||||
};
|
||||
|
||||
use library_cache::{LoadedLibrary, Selected};
|
||||
|
||||
/// The constructs the AIR frontend lowers completely (`metal/README.md`).
|
||||
const FEATURES: ShaderFeatures = ShaderFeatures::COMPUTE
|
||||
.union(ShaderFeatures::VERTEX_FRAGMENT)
|
||||
@@ -133,13 +136,15 @@ pub struct Service {
|
||||
*mut c_void,
|
||||
*mut ffi::AirError,
|
||||
) -> bool,
|
||||
/// `stela_metal_compile`.
|
||||
/// `stela_metal_compile_reflected`. Custom callbacks receive the full
|
||||
/// record. Stela's linked callbacks also accept a compilation projection.
|
||||
pub compile: unsafe extern "C" fn(
|
||||
*const c_void,
|
||||
usize,
|
||||
*const c_char,
|
||||
*const ffi::Target,
|
||||
*const ffi::Specialization,
|
||||
*const ffi::Reflection,
|
||||
*mut ffi::AirError,
|
||||
) -> *mut c_void,
|
||||
/// `stela_metal_tessellation_stages`.
|
||||
@@ -219,8 +224,9 @@ impl Drop for InternalKernelCode {
|
||||
pub struct AirCompiler {
|
||||
service: Service,
|
||||
target: ffi::Target,
|
||||
project_reflection: bool,
|
||||
/// MTLB libraries by id; ids are never reused.
|
||||
libraries: BTreeMap<u64, Vec<u8>>,
|
||||
libraries: BTreeMap<u64, LoadedLibrary>,
|
||||
next_library: u64,
|
||||
refusal: Option<Refusal>,
|
||||
}
|
||||
@@ -255,9 +261,17 @@ impl AirCompiler {
|
||||
max_mesh_vertices: mesh.map_or(0, |mesh| mesh.max_mesh_output_vertices),
|
||||
max_mesh_primitives: mesh.map_or(0, |mesh| mesh.max_mesh_output_primitives),
|
||||
};
|
||||
// The boot image mounts the linked AIR compiler. Hosted all-feature
|
||||
// builds also expose `Service::linked`, but only pull in its external
|
||||
// symbols if the caller constructs that service.
|
||||
#[cfg(all(feature = "metal-linked", target_os = "uefi"))]
|
||||
let project_reflection = service.accepts_compilation_projection();
|
||||
#[cfg(not(all(feature = "metal-linked", target_os = "uefi")))]
|
||||
let project_reflection = false;
|
||||
Self {
|
||||
service,
|
||||
target,
|
||||
project_reflection,
|
||||
libraries: BTreeMap::new(),
|
||||
next_library: 0,
|
||||
refusal: None,
|
||||
@@ -280,10 +294,10 @@ impl Compiler for AirCompiler {
|
||||
}
|
||||
|
||||
fn add_library(&mut self, data: Vec<u8>) -> Result<u64> {
|
||||
Library::parse(&data).map_err(|_| Error::Invalid("Metal library"))?;
|
||||
let loaded = LoadedLibrary::new(data)?;
|
||||
let id = self.next_library;
|
||||
self.next_library += 1;
|
||||
self.libraries.insert(id, data);
|
||||
self.libraries.insert(id, loaded);
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
@@ -349,8 +363,8 @@ impl Compiler for AirCompiler {
|
||||
let sources: Vec<_> = selected
|
||||
.iter()
|
||||
.map(|selected| ffi::StitchSource {
|
||||
bitcode: selected.air.bitcode.as_ptr().cast(),
|
||||
size: selected.air.bitcode.len(),
|
||||
bitcode: selected.bitcode.as_ptr().cast(),
|
||||
size: selected.bitcode.len(),
|
||||
name: selected.entry.as_ptr(),
|
||||
})
|
||||
.collect();
|
||||
@@ -425,7 +439,7 @@ impl Compiler for AirCompiler {
|
||||
fn library_data(&self, library: u64) -> Result<&[u8]> {
|
||||
self.libraries
|
||||
.get(&library)
|
||||
.map(Vec::as_slice)
|
||||
.map(LoadedLibrary::bytes)
|
||||
.ok_or(Error::Invalid("unknown library"))
|
||||
}
|
||||
|
||||
@@ -448,6 +462,31 @@ impl Compiler for AirCompiler {
|
||||
Ok(reflection)
|
||||
}
|
||||
|
||||
fn prepare_function(
|
||||
&mut self,
|
||||
library: u64,
|
||||
entry: &str,
|
||||
constants: Vec<(u32, Vec<u8>)>,
|
||||
) -> Result<PreparedFunction> {
|
||||
let selected = select(&self.libraries, library, entry)?;
|
||||
let specialization = Specialization {
|
||||
constants,
|
||||
..Specialization::default()
|
||||
};
|
||||
let (reflection, provenance) =
|
||||
selected.reflect(&self.service, Some(&specialization), &mut self.refusal)?;
|
||||
Ok(PreparedFunction {
|
||||
library,
|
||||
constants: specialization.constants,
|
||||
reflection,
|
||||
provenance,
|
||||
reflection_service: self
|
||||
.project_reflection
|
||||
.then_some(self.service.reflect as usize)
|
||||
.and_then(core::num::NonZeroUsize::new),
|
||||
})
|
||||
}
|
||||
|
||||
fn constants(&mut self, library: u64, entry: &str) -> Result<Vec<FunctionConstant>> {
|
||||
let selected = select(&self.libraries, library, entry)?;
|
||||
let (reflection, _) = selected.reflect(&self.service, None, &mut self.refusal)?;
|
||||
@@ -463,7 +502,7 @@ impl Compiler for AirCompiler {
|
||||
let selected = select(&self.libraries, library, entry)?;
|
||||
let mut bindings = ffi::Bindings::zeroed();
|
||||
let mut error = ffi::AirError::NONE;
|
||||
let air = selected.air.bitcode;
|
||||
let air = selected.bitcode;
|
||||
let values = constant_values(&specialization.constants);
|
||||
let count = u32::try_from(values.len()).map_err(|_| MALFORMED)?;
|
||||
// SAFETY: the AIR, entry and values outlive the call, which writes
|
||||
@@ -496,7 +535,7 @@ impl Compiler for AirCompiler {
|
||||
let linked = linked_modules(&self.libraries, &specialization.linking, own)?;
|
||||
let mut states = Vec::new();
|
||||
for bitcode in
|
||||
core::iter::once(selected.air.bitcode).chain(linked.iter().map(|module| module.bitcode))
|
||||
core::iter::once(selected.bitcode).chain(linked.iter().map(|module| module.bitcode))
|
||||
{
|
||||
let mut listed = [0; ffi::SAMPLER_STATES];
|
||||
let mut count = 0;
|
||||
@@ -528,12 +567,7 @@ impl Compiler for AirCompiler {
|
||||
entry: &str,
|
||||
specialization: &Specialization,
|
||||
) -> Result<CompiledShader> {
|
||||
let stage_in = specialization
|
||||
.stage_in
|
||||
.as_ref()
|
||||
.map(ffi::StageIn::kernel)
|
||||
.transpose()?;
|
||||
self.compile_function(library, entry, specialization, None, stage_in.as_deref())
|
||||
self.compile_entry(library, entry, specialization, None)
|
||||
}
|
||||
|
||||
fn compile_tessellation(
|
||||
@@ -542,6 +576,75 @@ impl Compiler for AirCompiler {
|
||||
entry: &str,
|
||||
specialization: &Specialization,
|
||||
tessellation: &Tessellation,
|
||||
) -> Result<TessellationStages> {
|
||||
self.compile_patch(library, entry, specialization, tessellation, None)
|
||||
}
|
||||
|
||||
fn compile_prepared(
|
||||
&mut self,
|
||||
function: &PreparedFunction,
|
||||
specialization: &Specialization,
|
||||
) -> Result<CompiledShader> {
|
||||
self.compile_entry(
|
||||
function.library,
|
||||
function.entry(),
|
||||
specialization,
|
||||
Some(function),
|
||||
)
|
||||
}
|
||||
|
||||
fn compile_prepared_tessellation(
|
||||
&mut self,
|
||||
function: &PreparedFunction,
|
||||
specialization: &Specialization,
|
||||
tessellation: &Tessellation,
|
||||
) -> Result<TessellationStages> {
|
||||
self.compile_patch(
|
||||
function.library,
|
||||
function.entry(),
|
||||
specialization,
|
||||
tessellation,
|
||||
Some(function),
|
||||
)
|
||||
}
|
||||
|
||||
fn release(&mut self, code: ShaderCode) {
|
||||
// SAFETY: the code is NIR this compiler's service compiled, which the
|
||||
// device releases once.
|
||||
unsafe { (self.service.release)(code.0 as usize as *mut c_void) }
|
||||
}
|
||||
}
|
||||
|
||||
impl AirCompiler {
|
||||
fn compile_entry(
|
||||
&mut self,
|
||||
library: u64,
|
||||
entry: &str,
|
||||
specialization: &Specialization,
|
||||
prepared: Option<&PreparedFunction>,
|
||||
) -> Result<CompiledShader> {
|
||||
let stage_in = specialization
|
||||
.stage_in
|
||||
.as_ref()
|
||||
.map(ffi::StageIn::kernel)
|
||||
.transpose()?;
|
||||
self.compile_function(
|
||||
library,
|
||||
entry,
|
||||
specialization,
|
||||
None,
|
||||
stage_in.as_deref(),
|
||||
prepared,
|
||||
)
|
||||
}
|
||||
|
||||
fn compile_patch(
|
||||
&mut self,
|
||||
library: u64,
|
||||
entry: &str,
|
||||
specialization: &Specialization,
|
||||
tessellation: &Tessellation,
|
||||
prepared: Option<&PreparedFunction>,
|
||||
) -> Result<TessellationStages> {
|
||||
if specialization.stage_in.is_some() {
|
||||
return Err(Error::Invalid("kernel stage-in of a vertex function"));
|
||||
@@ -558,6 +661,7 @@ impl Compiler for AirCompiler {
|
||||
specialization,
|
||||
Some(&properties),
|
||||
stage_in.as_deref(),
|
||||
prepared,
|
||||
)?;
|
||||
let mut stages = [ptr::null_mut(); 2];
|
||||
// SAFETY: the target and tessellation outlive the call, which writes
|
||||
@@ -573,14 +677,6 @@ impl Compiler for AirCompiler {
|
||||
})
|
||||
}
|
||||
|
||||
fn release(&mut self, code: ShaderCode) {
|
||||
// SAFETY: the code is NIR this compiler's service compiled, which the
|
||||
// device releases once.
|
||||
unsafe { (self.service.release)(code.0 as usize as *mut c_void) }
|
||||
}
|
||||
}
|
||||
|
||||
impl AirCompiler {
|
||||
/// Compiles `entry` of `library`: a post-tessellation vertex function
|
||||
/// with its pipeline's tessellation, and a kernel or post-tessellation
|
||||
/// vertex function with the stage-in layout it fetches by.
|
||||
@@ -591,12 +687,39 @@ impl AirCompiler {
|
||||
specialization: &Specialization,
|
||||
tessellation: Option<&ffi::Tessellation>,
|
||||
stage_in: Option<&ffi::StageIn>,
|
||||
prepared: Option<&PreparedFunction>,
|
||||
) -> Result<CompiledShader> {
|
||||
let selected = select(&self.libraries, library, entry)?;
|
||||
let (reflection, provenance) =
|
||||
selected.reflect(&self.service, Some(specialization), &mut self.refusal)?;
|
||||
let Reflection::Stage(interface) = reflection else {
|
||||
return Err(Error::Invalid("a visible function is not a pipeline stage"));
|
||||
let constants = constant_values(&specialization.constants);
|
||||
// Reflection uses only the module, entry and function constant values.
|
||||
// Linkage, layouts and dispatch sizes enter later at compilation.
|
||||
let prepared = prepared.filter(|function| {
|
||||
self.project_reflection
|
||||
&& function.library == library
|
||||
&& function.entry() == entry
|
||||
&& function.provenance.slice_hash == selected.slice_hash
|
||||
&& function.constants == specialization.constants
|
||||
&& function
|
||||
.reflection_service
|
||||
.is_some_and(|service| service.get() == self.service.reflect as usize)
|
||||
});
|
||||
let (reflected, interface, provenance) = if let Some(function) = prepared {
|
||||
let Reflection::Stage(interface) = &function.reflection else {
|
||||
return Err(Error::Invalid("a visible function is not a pipeline stage"));
|
||||
};
|
||||
(
|
||||
compilation_reflection(interface)?,
|
||||
interface.as_ref().clone(),
|
||||
function.provenance.clone(),
|
||||
)
|
||||
} else {
|
||||
let reflected =
|
||||
selected.reflect_raw(&self.service, Some(&constants), &mut self.refusal)?;
|
||||
let (reflection, provenance) = selected.decode_reflection(&reflected)?;
|
||||
let Reflection::Stage(interface) = reflection else {
|
||||
return Err(Error::Invalid("a visible function is not a pipeline stage"));
|
||||
};
|
||||
(reflected, *interface, provenance)
|
||||
};
|
||||
let linking = &specialization.linking;
|
||||
let own = (selected.slice_hash, specialization.constants.as_slice());
|
||||
@@ -647,7 +770,6 @@ impl AirCompiler {
|
||||
per_primitive: varying.per_primitive.into(),
|
||||
})
|
||||
.collect();
|
||||
let constants = constant_values(&specialization.constants);
|
||||
let samplers: Vec<_> = specialization
|
||||
.samplers
|
||||
.iter()
|
||||
@@ -676,10 +798,11 @@ impl AirCompiler {
|
||||
samplers: samplers.as_ptr(),
|
||||
};
|
||||
let mut error = ffi::AirError::NONE;
|
||||
let air = selected.air.bitcode;
|
||||
let air = selected.bitcode;
|
||||
// SAFETY: the AIR, entry, target and specialization, with the arrays,
|
||||
// identifiers, values, layouts, modules and names it points to,
|
||||
// outlive the call, which writes only the error.
|
||||
// outlive the call, which writes only the error. The compilation
|
||||
// fields come from this service's reflection of the same input and constants.
|
||||
let shader = unsafe {
|
||||
(self.service.compile)(
|
||||
air.as_ptr().cast(),
|
||||
@@ -687,6 +810,7 @@ impl AirCompiler {
|
||||
selected.entry.as_ptr(),
|
||||
&self.target,
|
||||
&raw,
|
||||
&*reflected,
|
||||
&mut error,
|
||||
)
|
||||
};
|
||||
@@ -695,7 +819,7 @@ impl AirCompiler {
|
||||
}
|
||||
Ok(CompiledShader {
|
||||
code: ShaderCode(shader as usize as u64),
|
||||
interface: *interface,
|
||||
interface,
|
||||
provenance,
|
||||
})
|
||||
}
|
||||
@@ -822,12 +946,12 @@ fn same_values(a: Option<&[(u32, Vec<u8>)]>, b: Option<&[(u32, Vec<u8>)]>) -> bo
|
||||
/// digest and values: each once, by digest. A module links with one set of
|
||||
/// values; a dynamic library's takes those of a function linked from it.
|
||||
fn linked_modules<'a>(
|
||||
libraries: &'a BTreeMap<u64, Vec<u8>>,
|
||||
libraries: &'a BTreeMap<u64, LoadedLibrary>,
|
||||
linking: &'a Linking,
|
||||
own: ([u8; 32], &'a [(u32, Vec<u8>)]),
|
||||
) -> Result<Vec<LinkedModule<'a>>> {
|
||||
let mut modules: Vec<LinkedModule<'a>> = Vec::new();
|
||||
let mut add = |digest: [u8; 32], air: Air<'a>, constants| {
|
||||
let mut add = |digest: [u8; 32], bitcode: &'a [u8], constants| {
|
||||
if digest == own.0 {
|
||||
return require(
|
||||
same_values(Some(own.1), constants),
|
||||
@@ -844,7 +968,7 @@ fn linked_modules<'a>(
|
||||
}
|
||||
None => modules.push(LinkedModule {
|
||||
digest,
|
||||
bitcode: air.bitcode,
|
||||
bitcode,
|
||||
constants,
|
||||
}),
|
||||
}
|
||||
@@ -853,55 +977,31 @@ fn linked_modules<'a>(
|
||||
for function in linking.functions.iter().chain(&linking.private_functions) {
|
||||
let selected = select(libraries, function.library, &function.entry)?;
|
||||
let constants = Some(function.constants.as_slice());
|
||||
add(selected.slice_hash, selected.air, constants)?;
|
||||
add(selected.slice_hash, selected.bitcode, constants)?;
|
||||
}
|
||||
let invalid = |_| Error::Invalid("Metal library");
|
||||
for library in &linking.libraries {
|
||||
let data = libraries
|
||||
let library = libraries
|
||||
.get(library)
|
||||
.ok_or(Error::Invalid("unknown library"))?;
|
||||
let parsed = Library::parse(data).map_err(invalid)?;
|
||||
ensure(
|
||||
parsed.header.kind == Header::DYNAMIC,
|
||||
"a preloaded library that is not dynamic",
|
||||
)?;
|
||||
for function in parsed.functions() {
|
||||
add(*function.digest, function.air().map_err(invalid)?, None)?;
|
||||
ensure(library.dynamic, "a preloaded library that is not dynamic")?;
|
||||
for module in library.modules() {
|
||||
let (digest, bitcode) = module?;
|
||||
add(digest, bitcode, None)?;
|
||||
}
|
||||
}
|
||||
Ok(modules)
|
||||
}
|
||||
|
||||
/// A library function selected for the service.
|
||||
struct Selected<'a> {
|
||||
air: Air<'a>,
|
||||
name: &'a str,
|
||||
entry: CString,
|
||||
slice_hash: [u8; 32],
|
||||
}
|
||||
|
||||
/// Selects `entry` of `library`.
|
||||
fn select<'a>(
|
||||
libraries: &'a BTreeMap<u64, Vec<u8>>,
|
||||
libraries: &'a BTreeMap<u64, LoadedLibrary>,
|
||||
library: u64,
|
||||
entry: &str,
|
||||
) -> Result<Selected<'a>> {
|
||||
let data = libraries
|
||||
libraries
|
||||
.get(&library)
|
||||
.ok_or(Error::Invalid("unknown library"))?;
|
||||
let invalid = |_| Error::Invalid("Metal library");
|
||||
let parsed = Library::parse(data).map_err(invalid)?;
|
||||
let function = parsed
|
||||
.functions()
|
||||
.iter()
|
||||
.find(|function| function.name == entry)
|
||||
.ok_or(Error::Invalid("no function of that name"))?;
|
||||
Ok(Selected {
|
||||
air: function.air().map_err(invalid)?,
|
||||
name: function.name,
|
||||
entry: CString::new(function.name).map_err(|_| Error::Invalid("function name"))?,
|
||||
slice_hash: *function.digest,
|
||||
})
|
||||
.ok_or(Error::Invalid("unknown library"))?
|
||||
.select(entry)
|
||||
}
|
||||
|
||||
impl Selected<'_> {
|
||||
@@ -914,11 +1014,21 @@ impl Selected<'_> {
|
||||
specialization: Option<&Specialization>,
|
||||
refusal: &mut Option<Refusal>,
|
||||
) -> Result<(Reflection, Provenance)> {
|
||||
let mut reflection = Box::new(ffi::Reflection::ZERO);
|
||||
let mut error = ffi::AirError::NONE;
|
||||
let air = self.air.bitcode;
|
||||
let values = specialization.map(|known| constant_values(&known.constants));
|
||||
let (values, count) = match &values {
|
||||
let reflection = self.reflect_raw(service, values.as_deref(), refusal)?;
|
||||
self.decode_reflection(&reflection)
|
||||
}
|
||||
|
||||
fn reflect_raw(
|
||||
&self,
|
||||
service: &Service,
|
||||
values: Option<&[ffi::ConstantValue]>,
|
||||
refusal: &mut Option<Refusal>,
|
||||
) -> Result<Box<ffi::Reflection>> {
|
||||
let mut reflection = ffi::Reflection::zeroed();
|
||||
let mut error = ffi::AirError::NONE;
|
||||
let air = self.bitcode;
|
||||
let (values, count) = match values {
|
||||
Some(values) => (
|
||||
values.as_ptr(),
|
||||
u32::try_from(values.len()).map_err(|_| MALFORMED)?,
|
||||
@@ -941,19 +1051,23 @@ impl Selected<'_> {
|
||||
if !reflected {
|
||||
return Err(refuse(refusal, self.name, &error));
|
||||
}
|
||||
Ok(reflection)
|
||||
}
|
||||
|
||||
fn decode_reflection(&self, reflection: &ffi::Reflection) -> Result<(Reflection, Provenance)> {
|
||||
let provenance = Provenance {
|
||||
build_id: name(&reflection, reflection.ident, reflection.ident_bytes)?.to_vec(),
|
||||
build_id: name(reflection, reflection.ident, reflection.ident_bytes)?.to_vec(),
|
||||
slice_hash: self.slice_hash,
|
||||
source_map: None,
|
||||
entry: self.name.to_string(),
|
||||
};
|
||||
let reflection = if u64::from(reflection.stage) == FunctionType::Visible.raw() {
|
||||
Reflection::Visible {
|
||||
constants: constants(&reflection)?,
|
||||
constants: constants(reflection)?,
|
||||
command_barriers: reflection.command_barriers != 0,
|
||||
}
|
||||
} else {
|
||||
Reflection::Stage(Box::new(interface(&reflection)?))
|
||||
Reflection::Stage(Box::new(interface(reflection)?))
|
||||
};
|
||||
Ok((reflection, provenance))
|
||||
}
|
||||
@@ -1026,6 +1140,48 @@ fn scalar(primitive: u32) -> Result<Scalar> {
|
||||
})
|
||||
}
|
||||
|
||||
/// The compilation ABI reads only these fields. Rebuild them from the
|
||||
/// validated interface to avoid retaining a full ABI record for each function.
|
||||
fn compilation_reflection(interface: &Interface) -> Result<Box<ffi::Reflection>> {
|
||||
let mut reflection = ffi::Reflection::zeroed();
|
||||
reflection.stage = interface.stage.raw() as u32;
|
||||
reflection.patch = match interface.patch.map(|patch| patch.domain) {
|
||||
None => 0,
|
||||
Some(PatchDomain::Triangle) => 1,
|
||||
Some(PatchDomain::Quad) => 2,
|
||||
};
|
||||
reflection.threadgroup_bytes = interface.static_threadgroup_bytes;
|
||||
for (index, varying) in interface.varyings.iter().enumerate() {
|
||||
let identifier = varying.identifier.as_bytes();
|
||||
let offset = reflection.names_bytes as usize;
|
||||
let end = offset.checked_add(identifier.len()).ok_or(MALFORMED)?;
|
||||
reflection
|
||||
.names
|
||||
.get_mut(offset..end)
|
||||
.ok_or(MALFORMED)?
|
||||
.copy_from_slice(identifier);
|
||||
*reflection.varyings.get_mut(index).ok_or(MALFORMED)? = ffi::Varying {
|
||||
identifier: offset as u32,
|
||||
identifier_bytes: identifier.len() as u32,
|
||||
primitive: match varying.scalar {
|
||||
Scalar::Char => ffi::primitive::CHAR,
|
||||
Scalar::Uchar => ffi::primitive::UCHAR,
|
||||
Scalar::Short => ffi::primitive::SHORT,
|
||||
Scalar::Ushort => ffi::primitive::USHORT,
|
||||
Scalar::Int => ffi::primitive::INT,
|
||||
Scalar::Uint => ffi::primitive::UINT,
|
||||
Scalar::Float => ffi::primitive::FLOAT,
|
||||
Scalar::Half => ffi::primitive::HALF,
|
||||
},
|
||||
components: varying.components.into(),
|
||||
per_primitive: varying.per_primitive.into(),
|
||||
};
|
||||
reflection.names_bytes = end as u32;
|
||||
}
|
||||
reflection.varying_count = interface.varyings.len() as u32;
|
||||
Ok(reflection)
|
||||
}
|
||||
|
||||
fn numeric(primitive: u32) -> Result<NumericClass> {
|
||||
Ok(match scalar(primitive)? {
|
||||
Scalar::Float | Scalar::Half => NumericClass::Float,
|
||||
|
||||
@@ -179,8 +179,14 @@ pub struct Reflection {
|
||||
}
|
||||
|
||||
impl Reflection {
|
||||
#[cfg(test)]
|
||||
// SAFETY: every member is an integer or an array of integers.
|
||||
pub(super) const ZERO: Self = unsafe { core::mem::zeroed() };
|
||||
|
||||
pub(super) fn zeroed() -> alloc::boxed::Box<Self> {
|
||||
// SAFETY: every member is an integer or an array of integers.
|
||||
unsafe { alloc::boxed::Box::new_zeroed().assume_init() }
|
||||
}
|
||||
}
|
||||
|
||||
/// `enum stela_metal_binding_kind`.
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
//! Selection from immutable MTLB bytes. The index holds offsets into the
|
||||
//! original library, and checks each module's digest and AIR framing once
|
||||
//! when it is first needed.
|
||||
use super::{
|
||||
super::library::{Air, Header, Library},
|
||||
Error, Result,
|
||||
};
|
||||
use alloc::{collections::BTreeMap, vec::Vec};
|
||||
use core::{cell::OnceCell, ffi::CStr, ops::Range};
|
||||
|
||||
const INVALID: Error = Error::Invalid("Metal library");
|
||||
|
||||
pub(super) struct LoadedLibrary {
|
||||
bytes: Vec<u8>,
|
||||
functions: Vec<Entry>,
|
||||
modules: Vec<Module>,
|
||||
pub(super) dynamic: bool,
|
||||
}
|
||||
|
||||
struct Entry {
|
||||
name: Range<usize>,
|
||||
module: usize,
|
||||
}
|
||||
|
||||
struct Module {
|
||||
wrapped: Range<usize>,
|
||||
digest: [u8; 32],
|
||||
/// The original bitcode range, or a failed digest/framing check.
|
||||
checked: OnceCell<Option<Range<usize>>>,
|
||||
}
|
||||
|
||||
pub(super) struct Selected<'a> {
|
||||
pub(super) bitcode: &'a [u8],
|
||||
pub(super) name: &'a str,
|
||||
pub(super) entry: &'a CStr,
|
||||
pub(super) slice_hash: [u8; 32],
|
||||
}
|
||||
|
||||
impl LoadedLibrary {
|
||||
pub(super) fn new(bytes: Vec<u8>) -> Result<Self> {
|
||||
let parsed = Library::parse(&bytes).map_err(|_| INVALID)?;
|
||||
let dynamic = parsed.header.kind == Header::DYNAMIC;
|
||||
let mut modules = Vec::new();
|
||||
let mut index = BTreeMap::new();
|
||||
let mut functions = Vec::new();
|
||||
functions
|
||||
.try_reserve_exact(parsed.functions().len())
|
||||
.map_err(|_| Error::OutOfMemory)?;
|
||||
for function in parsed.functions() {
|
||||
let wrapped = function.module_range();
|
||||
let digest = *function.digest;
|
||||
let module = *index
|
||||
.entry((wrapped.start, wrapped.end, digest))
|
||||
.or_insert_with(|| {
|
||||
let index = modules.len();
|
||||
modules.push(Module {
|
||||
wrapped,
|
||||
digest,
|
||||
checked: OnceCell::new(),
|
||||
});
|
||||
index
|
||||
});
|
||||
// The parser borrowed NAME from these bytes and verified its
|
||||
// terminator. Keep the terminator for the compiler service.
|
||||
let start = function.name.as_ptr().addr() - bytes.as_ptr().addr();
|
||||
let name = start..start + function.name.len() + 1;
|
||||
functions.push(Entry { name, module });
|
||||
}
|
||||
Ok(Self {
|
||||
bytes,
|
||||
functions,
|
||||
modules,
|
||||
dynamic,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn bytes(&self) -> &[u8] {
|
||||
&self.bytes
|
||||
}
|
||||
|
||||
pub(super) fn select(&self, name: &str) -> Result<Selected<'_>> {
|
||||
let entry = self
|
||||
.functions
|
||||
.iter()
|
||||
.find(|entry| &self.bytes[entry.name.start..entry.name.end - 1] == name.as_bytes())
|
||||
.ok_or(Error::Invalid("no function of that name"))?;
|
||||
let module = &self.modules[entry.module];
|
||||
let entry =
|
||||
CStr::from_bytes_with_nul(&self.bytes[entry.name.clone()]).map_err(|_| INVALID)?;
|
||||
Ok(Selected {
|
||||
bitcode: module.bitcode(&self.bytes)?,
|
||||
name: entry.to_str().map_err(|_| INVALID)?,
|
||||
entry,
|
||||
slice_hash: module.digest,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn modules(&self) -> impl Iterator<Item = Result<([u8; 32], &[u8])>> {
|
||||
self.modules
|
||||
.iter()
|
||||
.map(|module| Ok((module.digest, module.bitcode(&self.bytes)?)))
|
||||
}
|
||||
}
|
||||
|
||||
impl Module {
|
||||
fn bitcode<'a>(&self, data: &'a [u8]) -> Result<&'a [u8]> {
|
||||
let range = self.checked.get_or_init(|| {
|
||||
let wrapped = &data[self.wrapped.clone()];
|
||||
let bitcode = Air::verified(wrapped, &self.digest).ok()?.bitcode;
|
||||
let start = bitcode.as_ptr().addr() - data.as_ptr().addr();
|
||||
Some(start..start + bitcode.len())
|
||||
});
|
||||
range
|
||||
.as_ref()
|
||||
.map(|range| &data[range.clone()])
|
||||
.ok_or(INVALID)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::metal::library;
|
||||
|
||||
#[test]
|
||||
fn selection_caches_one_checked_module_for_entries_sharing_an_extent_and_digest() {
|
||||
let data = library::assemble(
|
||||
b"BC\xc0\xdepayload",
|
||||
&[("first", 2), ("second", 2)],
|
||||
0,
|
||||
None,
|
||||
);
|
||||
let loaded = LoadedLibrary::new(data.clone()).unwrap();
|
||||
assert_eq!(loaded.bytes(), &data);
|
||||
assert_eq!(loaded.modules.len(), 1);
|
||||
assert!(loaded.modules[0].checked.get().is_none());
|
||||
let first = loaded.select("first").unwrap();
|
||||
let second = loaded.select("second").unwrap();
|
||||
assert_eq!(first.entry.to_bytes(), b"first");
|
||||
assert_eq!(second.entry.to_bytes(), b"second");
|
||||
assert_eq!(first.bitcode, b"BC\xc0\xdepayload");
|
||||
assert_eq!(first.bitcode.as_ptr(), second.bitcode.as_ptr());
|
||||
assert_eq!(first.slice_hash, second.slice_hash);
|
||||
assert!(matches!(loaded.modules[0].checked.get(), Some(Some(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mismatched_digests_do_not_share_an_air_check() {
|
||||
let mut data = library::assemble(b"BC\xc0\xdepayload", &[("good", 2), ("bad", 2)], 0, None);
|
||||
let parsed = Library::parse(&data).unwrap();
|
||||
let digest = parsed.functions()[1].digest.as_ptr().addr() - data.as_ptr().addr();
|
||||
data[digest] ^= 1;
|
||||
let loaded = LoadedLibrary::new(data).unwrap();
|
||||
assert_eq!(loaded.modules.len(), 2);
|
||||
assert!(loaded.select("good").is_ok());
|
||||
assert!(matches!(loaded.select("bad"), Err(INVALID)));
|
||||
assert!(matches!(loaded.select("bad"), Err(INVALID)));
|
||||
assert_eq!(loaded.modules[1].checked.get(), Some(&None));
|
||||
}
|
||||
}
|
||||
@@ -47,12 +47,13 @@ unsafe extern "C" {
|
||||
data: *mut c_void,
|
||||
error: *mut ffi::AirError,
|
||||
) -> bool;
|
||||
fn stela_metal_compile(
|
||||
fn stela_metal_compile_reflected(
|
||||
air: *const c_void,
|
||||
size: usize,
|
||||
entry: *const c_char,
|
||||
target: *const ffi::Target,
|
||||
specialization: *const ffi::Specialization,
|
||||
reflection: *const ffi::Reflection,
|
||||
error: *mut ffi::AirError,
|
||||
) -> *mut c_void;
|
||||
fn stela_metal_tessellation_stages(
|
||||
@@ -68,6 +69,13 @@ unsafe extern "C" {
|
||||
}
|
||||
|
||||
impl Service {
|
||||
#[cfg(target_os = "uefi")]
|
||||
pub(super) fn accepts_compilation_projection(&self) -> bool {
|
||||
let linked = Self::linked(self.nir_options);
|
||||
core::ptr::fn_addr_eq(self.reflect, linked.reflect)
|
||||
&& core::ptr::fn_addr_eq(self.compile, linked.compile)
|
||||
}
|
||||
|
||||
/// The linked service, compiling with the driver's `nir_options`.
|
||||
pub fn linked(nir_options: NonNull<c_void>) -> Self {
|
||||
Self {
|
||||
@@ -76,7 +84,7 @@ impl Service {
|
||||
sampler_states: stela_metal_sampler_states,
|
||||
functions: stela_metal_functions,
|
||||
stitch: stela_metal_stitch,
|
||||
compile: stela_metal_compile,
|
||||
compile: stela_metal_compile_reflected,
|
||||
tessellation_stages: stela_metal_tessellation_stages,
|
||||
accumulate_kernel: stela_metal_accumulate_kernel,
|
||||
select_kernel: stela_metal_select_kernel,
|
||||
|
||||
@@ -6,7 +6,10 @@ use crate::metal::{
|
||||
IndexType, TessellationControlPointIndexType, TessellationFactorStepFunction,
|
||||
TessellationPartitionMode, Winding,
|
||||
},
|
||||
library::tests::{container, fixture},
|
||||
library::{
|
||||
Header, Library,
|
||||
tests::{container, fixture},
|
||||
},
|
||||
nvidia::{CHIPS, fixture::nvk},
|
||||
shader::{LinkedFunction, Linking, Patch, PatchDomain},
|
||||
vertex::{STRIDE_DYNAMIC, StageInputDescriptor, VertexDescriptor},
|
||||
@@ -66,6 +69,8 @@ struct Fake {
|
||||
reflection: ffi::Reflection,
|
||||
/// The function constant values of each reflection.
|
||||
reflected: Vec<Values>,
|
||||
reflected_record: usize,
|
||||
expect_projected: bool,
|
||||
refuse_reflection: Option<Refused>,
|
||||
refuse_compilation: Option<Refused>,
|
||||
compiled: Vec<Compiled>,
|
||||
@@ -83,6 +88,8 @@ std::thread_local! {
|
||||
RefCell::new(Fake {
|
||||
reflection: ffi::Reflection::ZERO,
|
||||
reflected: Vec::new(),
|
||||
reflected_record: 0,
|
||||
expect_projected: false,
|
||||
refuse_reflection: None,
|
||||
refuse_compilation: None,
|
||||
compiled: Vec::new(),
|
||||
@@ -140,6 +147,7 @@ unsafe extern "C" fn reflect(
|
||||
}
|
||||
// SAFETY: the compiler passes its reflection record.
|
||||
unsafe { *reflection = fake.reflection };
|
||||
fake.reflected_record = reflection.addr();
|
||||
true
|
||||
})
|
||||
}
|
||||
@@ -207,6 +215,7 @@ unsafe extern "C" fn compile(
|
||||
entry: *const c_char,
|
||||
target: *const ffi::Target,
|
||||
specialization: *const ffi::Specialization,
|
||||
reflection: *const ffi::Reflection,
|
||||
error: *mut ffi::AirError,
|
||||
) -> *mut c_void {
|
||||
check_input(air, size, entry);
|
||||
@@ -320,6 +329,40 @@ unsafe extern "C" fn compile(
|
||||
if refused(fake.refuse_compilation, error) {
|
||||
return ptr::null_mut();
|
||||
}
|
||||
if fake.expect_projected {
|
||||
// SAFETY: the compiler keeps the projected reflection alive for the call.
|
||||
let projection = unsafe { &*reflection };
|
||||
let original = &fake.reflection;
|
||||
assert_eq!(projection.stage, original.stage);
|
||||
assert_eq!(projection.patch, original.patch);
|
||||
assert_eq!(projection.threadgroup_bytes, original.threadgroup_bytes);
|
||||
assert_eq!(projection.varying_count, original.varying_count);
|
||||
for (projected, original_varying) in projection
|
||||
.varyings
|
||||
.iter()
|
||||
.zip(&original.varyings)
|
||||
.take(original.varying_count as usize)
|
||||
{
|
||||
assert_eq!(projected.primitive, original_varying.primitive);
|
||||
assert_eq!(projected.components, original_varying.components);
|
||||
assert_eq!(projected.per_primitive, original_varying.per_primitive);
|
||||
assert_eq!(
|
||||
name(projection, projected.identifier, projected.identifier_bytes),
|
||||
name(
|
||||
original,
|
||||
original_varying.identifier,
|
||||
original_varying.identifier_bytes
|
||||
)
|
||||
);
|
||||
}
|
||||
} else {
|
||||
assert_eq!(reflection.addr(), fake.reflected_record);
|
||||
// SAFETY: this is the live reflection record the service filled.
|
||||
let actual = unsafe { &*reflection };
|
||||
assert_eq!(actual.ident_bytes, fake.reflection.ident_bytes);
|
||||
assert_eq!(actual.names, fake.reflection.names);
|
||||
}
|
||||
assert_eq!(fake.reflected.last(), Some(&constants));
|
||||
fake.compiled.push(Compiled {
|
||||
workgroup_size: specialization.workgroup_size,
|
||||
lengths: lengths
|
||||
@@ -663,6 +706,92 @@ fn reflections_become_interfaces_with_their_provenance() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_compilation_receives_the_full_reflection_of_a_prepared_function() {
|
||||
reflecting(|r| {
|
||||
r.stage = 3;
|
||||
r.ident = add_name(r, IDENT);
|
||||
r.ident_bytes = IDENT.len() as u32;
|
||||
});
|
||||
let (mut compiler, library) = with_library();
|
||||
let function = compiler
|
||||
.prepare_function(library, "kernel", Vec::new())
|
||||
.unwrap();
|
||||
assert!(function.reflection_service.is_none());
|
||||
assert_eq!(function.entry(), "kernel");
|
||||
let shader = compiler
|
||||
.compile_prepared(&function, &Specialization::default())
|
||||
.unwrap();
|
||||
assert_eq!(shader.provenance.build_id, IDENT);
|
||||
compiler.release(shader.code);
|
||||
FAKE.with_borrow(|fake| assert_eq!(fake.reflected.len(), 2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prepared_compilation_reuses_only_the_same_specialization() {
|
||||
reflecting(|r| {
|
||||
r.stage = 1;
|
||||
r.ident = add_name(r, IDENT);
|
||||
r.ident_bytes = IDENT.len() as u32;
|
||||
add_varying(r, "user(uv)", ffi::primitive::HALF, 2);
|
||||
add_varying(r, "user(index)", ffi::primitive::UINT, 1);
|
||||
});
|
||||
let (mut compiler, library) = with_library();
|
||||
compiler.project_reflection = true;
|
||||
let mut specialization = Specialization {
|
||||
constants: vec![(4, vec![1])],
|
||||
..Specialization::default()
|
||||
};
|
||||
let prepared = compiler
|
||||
.prepare_function(library, "kernel", specialization.constants.clone())
|
||||
.unwrap();
|
||||
let reflections = FAKE.with_borrow(|fake| fake.reflected.len());
|
||||
FAKE.with_borrow_mut(|fake| fake.expect_projected = true);
|
||||
let shader = compiler
|
||||
.compile_prepared(&prepared, &specialization)
|
||||
.unwrap();
|
||||
assert_eq!(shader.provenance, prepared.provenance);
|
||||
assert_eq!(shader.provenance.build_id, IDENT);
|
||||
assert_eq!(
|
||||
Reflection::Stage(Box::new(shader.interface)),
|
||||
prepared.reflection
|
||||
);
|
||||
compiler.release(shader.code);
|
||||
FAKE.with_borrow(|fake| assert_eq!(fake.reflected.len(), reflections));
|
||||
|
||||
FAKE.with_borrow_mut(|fake| {
|
||||
fake.refuse_compilation = Some((ffi::kind::INSTRUCTION, 17, "unsupported call"))
|
||||
});
|
||||
assert_eq!(
|
||||
compiler.compile_prepared(&prepared, &specialization),
|
||||
Err(Error::Unsupported("AIR instructions"))
|
||||
);
|
||||
let refusal = compiler.take_refusal().unwrap();
|
||||
assert_eq!(
|
||||
(
|
||||
refusal.entry.as_str(),
|
||||
refusal.instruction,
|
||||
refusal.detail.as_str()
|
||||
),
|
||||
("kernel", 17, "unsupported call")
|
||||
);
|
||||
FAKE.with_borrow_mut(|fake| {
|
||||
assert_eq!(fake.reflected.len(), reflections);
|
||||
fake.expect_projected = false;
|
||||
fake.refuse_compilation = None;
|
||||
});
|
||||
|
||||
specialization.constants[0].1[0] = 2;
|
||||
let shader = compiler
|
||||
.compile_prepared(&prepared, &specialization)
|
||||
.unwrap();
|
||||
compiler.release(shader.code);
|
||||
FAKE.with_borrow(|fake| {
|
||||
assert_eq!(fake.reflected.len(), reflections + 1);
|
||||
assert_eq!(fake.reflected.last(), Some(&specialization.constants));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fragment_interpolation_is_a_feature_of_its_function() {
|
||||
reflecting(|r| {
|
||||
@@ -1165,6 +1294,7 @@ fn post_tessellation_vertex_functions_compile_with_their_stage_in() {
|
||||
r.attribute_count = 1;
|
||||
});
|
||||
let (mut compiler, library) = with_library();
|
||||
compiler.project_reflection = true;
|
||||
let patch = Patch {
|
||||
domain: PatchDomain::Quad,
|
||||
control_points: Some(4),
|
||||
@@ -1196,9 +1326,14 @@ fn post_tessellation_vertex_functions_compile_with_their_stage_in() {
|
||||
}],
|
||||
}),
|
||||
};
|
||||
let stages = compiler
|
||||
.compile_tessellation(library, "kernel", &Specialization::default(), &tessellation)
|
||||
let prepared = compiler
|
||||
.prepare_function(library, "kernel", Vec::new())
|
||||
.unwrap();
|
||||
FAKE.with_borrow_mut(|fake| fake.expect_projected = true);
|
||||
let stages = compiler
|
||||
.compile_prepared_tessellation(&prepared, &Specialization::default(), &tessellation)
|
||||
.unwrap();
|
||||
FAKE.with_borrow_mut(|fake| fake.expect_projected = false);
|
||||
assert_eq!(
|
||||
(stages.vertex, stages.control),
|
||||
(ShaderCode(0x10), ShaderCode(0x20))
|
||||
|
||||
@@ -16,7 +16,7 @@ use super::{
|
||||
object::{Memory, Semaphore},
|
||||
},
|
||||
};
|
||||
use alloc::vec::Vec;
|
||||
use alloc::{collections::VecDeque, vec::Vec};
|
||||
|
||||
mod execution_sets;
|
||||
#[cfg(test)]
|
||||
@@ -116,8 +116,9 @@ pub struct Device<B: Backend, C: Compiler> {
|
||||
lost: bool,
|
||||
quiesce: Option<lifecycle::QuiesceStatus>,
|
||||
/// Objects waiting for a serial to complete, with the allocation bytes
|
||||
/// charged until their backend memory is destroyed.
|
||||
deferred: Vec<(u64, Object, u64)>,
|
||||
/// charged until their backend memory is destroyed. Entries follow
|
||||
/// submission order.
|
||||
deferred: VecDeque<(u64, Object, u64)>,
|
||||
allocated: u64,
|
||||
resources: resources::Resources,
|
||||
pipelines: pipelines::Pipelines,
|
||||
@@ -163,7 +164,7 @@ impl<B: Backend, C: Compiler> Device<B, C> {
|
||||
completed: 0,
|
||||
lost: false,
|
||||
quiesce: None,
|
||||
deferred: Vec::new(),
|
||||
deferred: VecDeque::new(),
|
||||
allocated: 0,
|
||||
resources: resources::Resources::default(),
|
||||
pipelines: pipelines::Pipelines::default(),
|
||||
@@ -215,7 +216,7 @@ impl<B: Backend, C: Compiler> Device<B, C> {
|
||||
self.backend.destroy(object);
|
||||
self.allocated -= allocated;
|
||||
} else {
|
||||
self.deferred.push((self.submitted, object, allocated));
|
||||
self.deferred.push_back((self.submitted, object, allocated));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -56,12 +56,17 @@ pub(crate) struct MockBackend {
|
||||
pub(crate) caches: BTreeMap<u64, u8>,
|
||||
pub(crate) submissions: Vec<Vec<Segment>>,
|
||||
pub(crate) writes: Vec<(Memory, u64, Vec<u8>)>,
|
||||
pub(crate) write_error: Option<Error>,
|
||||
pub(crate) invalidated: Vec<(Memory, u64, u64)>,
|
||||
/// Host memory each imported memory is, by memory.
|
||||
pub(crate) imports: BTreeMap<u64, (Vec<MemoryRange>, NonZeroU64)>,
|
||||
pub(crate) retired: VecDeque<NonZeroU64>,
|
||||
pub(crate) semaphores: BTreeMap<u64, u64>,
|
||||
pub(crate) queries_ready: bool,
|
||||
pub(crate) query_pool_error: Option<Error>,
|
||||
pub(crate) query_pools: Vec<(QueryPool, QueryPoolInfo)>,
|
||||
pub(crate) query_resets: Vec<(QueryPool, u32, u32)>,
|
||||
pub(crate) query_reads: Vec<(QueryPool, u32, usize)>,
|
||||
pub(crate) layouts: Vec<IndirectCommandsLayoutInfo>,
|
||||
/// Each execution set's pipelines by index.
|
||||
pub(crate) execution_sets: BTreeMap<u64, BTreeMap<u32, Pipeline>>,
|
||||
@@ -212,8 +217,13 @@ impl Backend for MockBackend {
|
||||
self.compute.push(*info);
|
||||
Ok(Pipeline(self.id()))
|
||||
}
|
||||
fn create_query_pool(&mut self, _: &QueryPoolInfo) -> Result<QueryPool> {
|
||||
Ok(QueryPool(self.id()))
|
||||
fn create_query_pool(&mut self, info: &QueryPoolInfo) -> Result<QueryPool> {
|
||||
if let Some(error) = self.query_pool_error.take() {
|
||||
return Err(error);
|
||||
}
|
||||
let pool = QueryPool(self.id());
|
||||
self.query_pools.push((pool, *info));
|
||||
Ok(pool)
|
||||
}
|
||||
fn create_semaphore(&mut self, initial: u64) -> Result<Semaphore> {
|
||||
let id = self.id();
|
||||
@@ -264,6 +274,9 @@ impl Backend for MockBackend {
|
||||
self.descriptors.push((index, descriptor));
|
||||
}
|
||||
fn write_memory(&mut self, memory: Memory, offset: u64, bytes: &[u8]) -> Result<()> {
|
||||
if let Some(error) = self.write_error.take() {
|
||||
return Err(error);
|
||||
}
|
||||
self.writes.push((memory, offset, bytes.to_vec()));
|
||||
Ok(())
|
||||
}
|
||||
@@ -292,8 +305,11 @@ impl Backend for MockBackend {
|
||||
fn copy_from_image(&mut self, _: Image, _: &BufferImageCopy, _: &mut [u8]) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
fn reset_queries(&mut self, _: QueryPool, _: u32, _: u32) {}
|
||||
fn query_results(&mut self, _: QueryPool, _: u32, results: &mut [u64]) -> Result<bool> {
|
||||
fn reset_queries(&mut self, pool: QueryPool, first: u32, count: u32) {
|
||||
self.query_resets.push((pool, first, count));
|
||||
}
|
||||
fn query_results(&mut self, pool: QueryPool, first: u32, results: &mut [u64]) -> Result<bool> {
|
||||
self.query_reads.push((pool, first, results.len()));
|
||||
results
|
||||
.iter_mut()
|
||||
.enumerate()
|
||||
|
||||
Loaded 100 of 255 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user