use std::cell::Cell;
use std::ffi::c_void;
use std::sync::Once;
use yaxpeax_arch::{Decoder, ReaderBuilder};
use yaxpeax_arm::armv8::a64::{self, Operand};
use super::{
Findings, branches_on_unknown_flags, condition_differs, float_bits, lifted,
register_differences, same_float_bits, unsupported, value,
};
use vlk_base::target::Isa;
use vlk_eval::eval::{self, hash};
use vlk_ir::ir::FunctionIr;
fn usable(index: u16) -> bool {
!matches!(index, 18 | 28 | 29 | 30)
}
const PROLOGUE: [u32; 27] = [
0xa9ba_7bfd,
0xa901_53f3,
0xa902_5bf5,
0xa903_63f7,
0xa904_6bf9,
0xa905_73fb,
0xaa00_03fc,
0xad47_8780,
0xad48_8f82,
0xad49_9784,
0xad4a_9f86,
0xf940_7380,
0xd51b_4200,
0xa940_0780,
0xa941_0f82,
0xa942_1784,
0xa943_1f86,
0xa944_2788,
0xa945_2f8a,
0xa946_378c,
0xa947_3f8e,
0xa948_4790,
0xa949_d393,
0xa94a_db95,
0xa94b_e397,
0xa94c_eb99,
0xf940_6f9b,
];
const EPILOGUE: [u32; 27] = [
0xad07_8780,
0xad08_8f82,
0xad09_9784,
0xad0a_9f86,
0xa900_0780,
0xa901_0f82,
0xa902_1784,
0xa903_1f86,
0xa904_2788,
0xa905_2f8a,
0xa906_378c,
0xa907_3f8e,
0xa908_4790,
0xa909_d393,
0xa90a_db95,
0xa90b_e397,
0xa90c_eb99,
0xf900_6f9b,
0xd53b_4200,
0xf900_7380,
0xa941_53f3,
0xa942_5bf5,
0xa943_63f7,
0xa944_6bf9,
0xa945_73fb,
0xa8c6_7bfd,
0xd65f_03c0,
];
const RET: u32 = 0xd65f_03c0;
const NZCV: usize = 28;
type State = [u64; 46];
const VECTORS: usize = 30;
fn registers(initial: &State) -> Vec<(u16, u64)> {
(0..28u16)
.filter(|index| usable(*index))
.map(|index| (index, initial[usize::from(index)]))
.chain((0..16).map(|half| {
(
vlk_arch::arch::aarch64::V0 + half as u16,
initial[VECTORS + half],
)
}))
.collect()
}
unsafe extern "C" {
fn mmap(
addr: *mut c_void,
len: usize,
prot: i32,
flags: i32,
fd: i32,
offset: i64,
) -> *mut c_void;
fn munmap(addr: *mut c_void, len: usize) -> i32;
fn pthread_jit_write_protect_np(enabled: i32);
fn sys_icache_invalidate(start: *mut c_void, len: usize);
fn sigaction(signal: i32, action: *const SignalAction, old: *mut SignalAction) -> i32;
}
#[repr(C)]
struct SignalAction {
handler: usize,
mask: u32,
flags: i32,
}
const SIGILL: i32 = 4;
const SIGBUS: i32 = 10;
const SIGSEGV: i32 = 11;
thread_local! {
static RUNNING: Cell<usize> = const { Cell::new(0) };
static UNDEFINED: Cell<bool> = const { Cell::new(false) };
}
extern "C" fn on_instruction_fault(signal: i32, _: *mut c_void, context: *mut c_void) {
unsafe {
let machine = *(context.cast::<u8>().add(48).cast::<*mut u8>());
let pc = machine.add(272).cast::<u64>();
let base = RUNNING.with(Cell::get) as u64;
if base != 0 && (base..base + PAGE as u64).contains(&*pc) {
*pc += 4;
UNDEFINED.with(|undefined| undefined.set(true));
} else {
let default = SignalAction {
handler: 0,
mask: 0,
flags: 0,
};
sigaction(signal, &default, std::ptr::null_mut());
}
}
}
const PAGE: usize = 1 << 14;
struct Page {
base: *mut u32,
len: usize,
}
impl Page {
fn new() -> Self {
const PROT_ALL: i32 = 1 | 2 | 4;
const MAP_PRIVATE_ANON_JIT: i32 = 0x0002 | 0x1000 | 0x0800;
let len = PAGE;
static HANDLER: Once = Once::new();
HANDLER.call_once(|| {
const SA_SIGINFO: i32 = 0x40;
let action = SignalAction {
handler: on_instruction_fault as *const () as usize,
mask: 0,
flags: SA_SIGINFO,
};
for signal in [SIGILL, SIGBUS, SIGSEGV] {
unsafe { sigaction(signal, &action, std::ptr::null_mut()) };
}
});
let base = unsafe {
mmap(
std::ptr::null_mut(),
len,
PROT_ALL,
MAP_PRIVATE_ANON_JIT,
-1,
0,
)
};
assert!(base as isize != -1, "mapping a code page");
Self {
base: base.cast(),
len,
}
}
fn run(&self, body: &[u32], state: &mut State) -> bool {
let code: Vec<u32> = PROLOGUE
.iter()
.chain(body)
.chain(&EPILOGUE)
.copied()
.collect();
assert!(code.len() * 4 <= self.len);
unsafe {
pthread_jit_write_protect_np(0);
std::ptr::copy_nonoverlapping(code.as_ptr(), self.base, code.len());
pthread_jit_write_protect_np(1);
sys_icache_invalidate(self.base.cast(), code.len() * 4);
let entry: extern "C" fn(*mut u64) = std::mem::transmute(self.base);
UNDEFINED.with(|undefined| undefined.set(false));
RUNNING.with(|running| running.set(self.base as usize));
entry(state.as_mut_ptr());
RUNNING.with(|running| running.set(0));
}
!UNDEFINED.with(Cell::get)
}
}
impl Drop for Page {
fn drop(&mut self) {
unsafe { munmap(self.base.cast(), self.len) };
}
}
fn decode(word: u32) -> Option<a64::Instruction> {
let bytes = word.to_le_bytes();
let mut reader = ReaderBuilder::<u64, u8>::read_from(&bytes[..]);
a64::InstDecoder::default().decode(&mut reader).ok()
}
fn register_only(instruction: &a64::Instruction) -> bool {
instruction.operands.iter().all(|operand| match *operand {
Operand::Nothing
| Operand::ConditionCode(_)
| Operand::Immediate(_)
| Operand::Imm64(_)
| Operand::Imm16(_)
| Operand::ImmediateDouble(_)
| Operand::ImmShift(..) => true,
Operand::SIMDRegister(_, number)
| Operand::SIMDRegisterElements(_, number, _)
| Operand::SIMDRegisterElementsLane(_, number, ..) => number < 8,
Operand::Register(_, index) | Operand::RegShift(_, _, _, index) => {
index == 31 || usable(index)
}
Operand::RegisterOrSP(_, index) => index != 31 && usable(index),
_ => false,
})
}
fn instruction(seed: u64) -> Option<(u32, a64::Instruction)> {
let bits = hash(seed, 1) as u32;
let word = match hash(seed, 2) % 6 {
4 => (bits & !(0b1111 << 25 | 1 << 31)) | (0b0111 << 25),
5 => (bits & !(0b11 << 30 | 0b1111 << 25)) | (0b01 << 30 | 0b1111 << 25),
0 => (bits & !(0b111 << 26)) | (0b100 << 26),
1 => (bits & !(0b111 << 25)) | (0b101 << 25),
2 => (bits & !(0b1_1111 << 24 | 1 << 30)) | (0b1_1110 << 24),
_ => (bits & !(0b1_1111 << 24 | 1 << 30)) | (0b1_1111 << 24),
};
let decoded = decode(word)?;
register_only(&decoded).then_some((word, decoded))
}
fn compare(seed: u64) -> u32 {
const FORMS: [u32; 6] = [
0xeb00_001f,
0x6b00_001f,
0xab00_001f,
0x2b00_001f,
0xea00_001f,
0x6a00_001f,
];
let register = |key| {
let index = (hash(seed, key) % 28) as u32;
if index == 18 { 0 } else { index }
};
FORMS[(hash(seed, 3) % 6) as usize] | register(4) << 16 | register(5) << 5
}
fn condition(code: u32, nzcv: u64) -> bool {
let (n, z, c, v) = (
nzcv >> 31 & 1 == 1,
nzcv >> 30 & 1 == 1,
nzcv >> 29 & 1 == 1,
nzcv >> 28 & 1 == 1,
);
let base = match code >> 1 {
0 => z,
1 => c,
2 => n,
3 => v,
4 => c && !z,
5 => n == v,
_ => n == v && !z,
};
if code & 1 == 1 { !base } else { base }
}
fn lift_words(words: &[u32]) -> Option<FunctionIr> {
lifted(
Isa::AArch64,
words.iter().flat_map(|word| word.to_le_bytes()).collect(),
)
}
fn check_instruction(page: &Page, seed: u64, findings: &mut Findings) {
let mut instructions = Vec::new();
for (index, salt) in [0, 0x5eed].into_iter().enumerate() {
if index == 1 && hash(seed, 7) & 1 == 0 {
break;
}
let Some(instruction) = instruction(seed ^ salt) else {
return;
};
instructions.push(instruction);
}
let setter = compare(seed);
let body: Vec<u32> = std::iter::once(setter)
.chain(instructions.iter().map(|(word, _)| *word))
.collect();
let kind = instructions
.iter()
.map(|(_, decoded)| format!("{:?}", decoded.opcode))
.collect::<Vec<_>>()
.join(" then ");
let Some(ir) = lift_words(&[body.as_slice(), &[RET]].concat()) else {
return;
};
let mut state: State = [0; 46];
for (index, slot) in state.iter_mut().enumerate().take(28) {
if usable(index as u16) {
*slot = value(seed, 0x100 + index as u64);
}
}
for half in 0..16 {
state[VECTORS + half] = float_bits(seed, 0x200 + half as u64);
}
state[NZCV] = (hash(seed, 6) & 0xf) << 28;
let initial = state;
if !page.run(&body, &mut state) {
findings.undefined += 1;
return;
}
if let Some(name) = unsupported(&ir) {
*findings.unsupported.entry(name).or_default() += 1;
return;
}
findings.tried += 1;
let registers = registers(&initial);
let processor = |index: u16| match index.checked_sub(vlk_arch::arch::aarch64::V0) {
Some(half) => state[VECTORS + usize::from(half)],
None => state[usize::from(index)],
};
let name = |index: u16| match index.checked_sub(vlk_arch::arch::aarch64::V0) {
Some(half) if half % 2 == 1 => format!("v{}_hi", half / 2),
Some(half) => format!("d{}", half / 2),
None => format!("x{index}"),
};
let describe = || {
let inputs: Vec<String> = registers
.iter()
.map(|(index, value)| format!("{}={value:#x}", name(*index)))
.collect();
let code: Vec<String> = body
.iter()
.map(|word| {
let text = decode(*word).map(|d| d.to_string()).unwrap_or_default();
format!("{text} ({word:#010x})")
})
.collect();
format!(
"{}\n in: {}\n{}",
code.join(" ; "),
inputs.join(" "),
ir.render()
)
};
if let Some(differ) = register_differences(&ir, ®isters, processor, name, |index, a, b| {
if index >= vlk_arch::arch::aarch64::V0 {
same_float_bits(a, b)
} else {
a == b
}
}) {
Findings::note(&mut findings.registers, kind, || {
format!("{}\n {differ}", describe())
});
return;
}
let setter_kind = decode(setter).map_or(String::new(), |d| format!("{:?}", d.opcode));
for code in 0..14 {
let tail = [0x5400_0060 | code, 0xd280_0000, RET, 0xd280_0020, RET];
let Some(ir) = lift_words(&[body.as_slice(), &tail].concat()) else {
continue;
};
if branches_on_unknown_flags(&ir) {
continue;
}
let expected = condition(code, state[NZCV]);
if let Some(differ) = condition_differs(&ir, ®isters, expected) {
Findings::note(
&mut findings.conditions,
format!("{setter_kind} then {kind}, condition {code}"),
|| {
format!(
"{}\n condition {code}: {differ}\n{}",
describe(),
ir.render()
)
},
);
}
}
}
#[test]
fn lifted_instructions_match_the_processor() {
let page = Page::new();
let mut findings = Findings::default();
for seed in 0..200_000 {
check_instruction(&page, seed, &mut findings);
}
findings.assert_agreement();
}
#[test]
fn sqdmulh_vector_results_match_the_processor() {
struct RestoreFpsr(u64);
impl Drop for RestoreFpsr {
fn drop(&mut self) {
unsafe {
std::arch::asm!("msr fpsr, {}", in(reg) self.0, options(nomem, nostack, preserves_flags))
};
}
}
let saved: u64;
unsafe {
std::arch::asm!("mrs {}, fpsr", out(reg) saved, options(nomem, nostack, preserves_flags))
};
let _restore = RestoreFpsr(saved);
let page = Page::new();
let mut checked = 0;
for (bits, full, base) in [
(16u32, false, 0x0e60_b400),
(16, true, 0x4e60_b400),
(32, false, 0x0ea0_b400),
(32, true, 0x4ea0_b400),
] {
let limit = 1i64 << (bits - 1);
let edges = [
-limit,
-limit + 1,
-limit / 2,
-1,
0,
1,
limit / 2,
limit - 2,
limit - 1,
];
for (d, n, m) in [
(0u16, 1u16, 2u16),
(1, 1, 2),
(2, 1, 2),
(0, 1, 1),
(1, 1, 1),
] {
let word = base | u32::from(m) << 16 | u32::from(n) << 5 | u32::from(d);
let decoded = decode(word).expect("valid SQDMULH encoding");
assert_eq!(decoded.opcode, a64::Opcode::SQDMULH);
let ir = lift_words(&[word, RET]).expect("SQDMULH lift");
assert!(unsupported(&ir).is_none(), "{}", ir.render());
for row in 0..if n == m { 9 } else { 81 } {
let mut state: State = std::array::from_fn(|index| hash(0x5eed, index as u64));
state[NZCV] = (checked as u64 & 0xf) << 28;
let mut fill = |number: u16, second: bool| {
for half in 0..if full { 2 } else { 1 } {
let mut value = 0;
for lane in 0..64 / bits as usize {
let position = half * (64 / bits as usize) + lane;
let index = if second {
row / 9 + 3 * position
} else {
row % 9 + position
};
let element = edges[index % edges.len()] as u64 & ((1u64 << bits) - 1);
value |= element << (lane * bits as usize);
}
state[VECTORS + 2 * usize::from(number) + half] = value;
}
};
fill(n, false);
if n != m {
fill(m, true);
}
let initial = state;
assert!(
page.run(&[word], &mut state),
"processor rejected {decoded} ({word:#010x})"
);
assert_eq!(state[NZCV], initial[NZCV], "{decoded}, row {row}: NZCV");
let registers = registers(&initial);
let setup = super::setup(®isters);
let (after, memory) =
eval::state_after(&ir, &setup).expect("modeled SQDMULH result");
assert!(memory.is_empty());
for &(index, start) in ®isters {
let actual = match index.checked_sub(vlk_arch::arch::aarch64::V0) {
Some(half) => state[VECTORS + usize::from(half)],
None => state[usize::from(index)],
};
assert_eq!(
after.get(&index).copied().unwrap_or(start),
actual,
"{decoded} ({word:#010x}), row {row}, register {index}"
);
}
checked += 1;
}
}
}
assert_eq!(checked, 1044);
eprintln!("{checked} SQDMULH vector result cases agree; FPSR.QC is outside the IR comparison");
}
const POINTERS: [u16; 4] = [1, 2, 3, 4];
const BUFFER: usize = 8192;
fn buffer_access(instruction: &a64::Instruction) -> bool {
use a64::Opcode as O;
let plain = matches!(
instruction.opcode,
O::LDR
| O::LDRB
| O::LDRH
| O::LDRSB
| O::LDRSH
| O::LDRSW
| O::STR
| O::STRB
| O::STRH
| O::LDUR
| O::LDURB
| O::LDURH
| O::LDURSB
| O::LDURSH
| O::LDURSW
| O::STUR
| O::STURB
| O::STURH
| O::LDP
| O::STP
| O::LDPSW
| O::LDNP
| O::STNP
| O::LD1
| O::LD2
| O::LD3
| O::LD4
| O::ST1
| O::ST2
| O::ST3
| O::ST4
| O::LD1R
| O::LD2R
| O::LD3R
| O::LD4R
);
let mut base = None;
let mut writeback = false;
let mut data_registers = Vec::new();
let operands_fit = instruction.operands.iter().all(|operand| match *operand {
Operand::Nothing => true,
Operand::Register(_, index) | Operand::RegisterOrSP(_, index) => {
data_registers.push(index);
index == 31 || usable(index) && !POINTERS.contains(&index)
}
Operand::SIMDRegister(_, number) => number < 8,
Operand::SIMDRegisterGroup(_, number, _, count)
| Operand::SIMDRegisterGroupLane(number, _, count, _) => number + u16::from(count) <= 8,
Operand::RegPreIndex(reg, offset, back) => {
base = Some(reg);
writeback = back;
offset.unsigned_abs() <= 2048
}
Operand::RegPostIndex(reg, offset) => {
base = Some(reg);
writeback = true;
offset.unsigned_abs() <= 2048
}
Operand::RegPostIndexReg(reg, index) => {
base = Some(reg);
writeback = true;
usable(index) && !POINTERS.contains(&index) && index != 31
}
Operand::RegRegOffset(reg, index, ..) => {
base = Some(reg);
usable(index) && !POINTERS.contains(&index) && index != 31
}
_ => false,
});
let pair_loads_one = matches!(instruction.opcode, O::LDP | O::LDPSW | O::LDNP)
&& data_registers.len() == 2
&& data_registers[0] == data_registers[1];
plain
&& operands_fit
&& !pair_loads_one
&& base.is_some_and(|base| POINTERS.contains(&base))
&& !(writeback && base.is_some_and(|base| data_registers.contains(&base)))
}
fn memory_instruction(seed: u64) -> Option<(u32, a64::Instruction)> {
let structures = [
0x4cdf_a140u32,
0x4dcb_8540,
0x4d9f_8540,
0x4cdf_0d40,
0x4dff_e940,
0x0d40_c140,
];
if let Some(word) = structures.get(seed as usize) {
let word = (word & !(31 << 5)) | (u32::from(POINTERS[0]) << 5);
let Some(decoded) = decode(word) else {
return None;
};
return buffer_access(&decoded).then_some((word, decoded));
}
let base = POINTERS[(hash(seed, 2) % 4) as usize] as u32;
let word = ((hash(seed, 1) as u32 | 1 << 27) & !(1 << 25) & !(0x1f << 5)) | base << 5;
let decoded = decode(word)?;
buffer_access(&decoded).then_some((word, decoded))
}
#[test]
fn lifted_memory_accesses_match_the_processor() {
let page = Page::new();
let mut findings = Findings::default();
let mut buffer = vec![0u8; BUFFER];
let middle = buffer.as_ptr() as u64 + (BUFFER / 2) as u64;
for seed in 0..60_000u64 {
let Some((word, decoded)) = memory_instruction(seed) else {
continue;
};
let Some(ir) = lift_words(&[word, RET]) else {
continue;
};
if let Some(name) = unsupported(&ir) {
*findings.unsupported.entry(name).or_default() += 1;
continue;
}
let mut state: State = [0; 46];
for (index, slot) in state.iter_mut().enumerate().take(28) {
if POINTERS.contains(&(index as u16)) {
*slot = middle + hash(seed, 0x300 + index as u64) % 256;
} else if usable(index as u16) {
*slot = hash(seed, 0x100 + index as u64) % 64;
}
}
for half in 0..16 {
state[VECTORS + half] = float_bits(seed, 0x200 + half as u64);
}
for (index, byte) in buffer.iter_mut().enumerate() {
*byte = hash(seed, 0x400 + index as u64) as u8;
}
let initial = state;
let before = buffer.clone();
if !page.run(&[word], &mut state) {
findings.undefined += 1;
continue;
}
findings.tried += 1;
let registers = registers(&initial);
let words: Vec<(u64, u64)> = before
.chunks(8)
.enumerate()
.map(|(index, chunk)| {
(
buffer.as_ptr() as u64 + index as u64 * 8,
u64::from_le_bytes(chunk.try_into().expect("8 bytes")),
)
})
.collect();
let setup = eval::Setup {
seed: 0,
convention: eval::Convention {
arguments: &[],
clobbered: &[],
},
registers: ®isters,
memory: &words,
step_limit: 100,
};
let kind = format!("{:?}", decoded.opcode);
let describe = || format!("{decoded} ({word:#010x})\n{}", ir.render());
let (after, memory) = match eval::state_after(&ir, &setup) {
Ok(state) => state,
Err(reason) => {
Findings::note(&mut findings.registers, kind, || {
format!("{}\n {reason}", describe())
});
continue;
}
};
let processor = |index: u16| match index.checked_sub(vlk_arch::arch::aarch64::V0) {
Some(half) => state[VECTORS + usize::from(half)],
None => state[usize::from(index)],
};
let mut differ: Vec<String> = registers
.iter()
.filter_map(|(index, start)| {
let lifted = after.get(index).copied().unwrap_or(*start);
(lifted != processor(*index)).then(|| {
format!(
"register {index}: lifted {lifted:#x}, processor {:#x}",
processor(*index)
)
})
})
.collect();
for (offset, real) in buffer.iter().enumerate() {
let address = buffer.as_ptr() as u64 + offset as u64;
let lifted = memory.get(&address).copied().unwrap_or(before[offset]);
if lifted != *real {
differ.push(format!(
"byte {offset:#x}: lifted {lifted:#x}, processor {real:#x}"
));
}
}
if !differ.is_empty() {
Findings::note(&mut findings.registers, kind, || {
format!("{}\n {}", describe(), differ.join("\n "))
});
}
}
findings.assert_agreement();
}
#[test]
fn scalar_half_immediate_processor_probe() {
let page = Page::new();
let mut state: State = [u64::MAX; 46];
state[NZCV] = 0;
assert!(
page.run(&[0x1eee_1000], &mut state),
"scalar half immediate did not execute; processor support or FP access is unavailable"
);
assert_eq!(state[VECTORS], 0x3c00);
assert_eq!(state[VECTORS + 1], 0);
assert_eq!(state[NZCV], 0);
}
#[test]
fn scalar_half_immediates_match_the_processor_without_status_changes() {
struct RestoreEnvironment {
control: u64,
status: u64,
}
impl Drop for RestoreEnvironment {
fn drop(&mut self) {
unsafe {
std::arch::asm!("msr fpcr, {control}", "msr fpsr, {status}",
control = in(reg) self.control, status = in(reg) self.status,
options(nomem, nostack, preserves_flags));
}
}
}
let control: u64;
let status: u64;
unsafe {
std::arch::asm!("mrs {control}, fpcr", "mrs {status}, fpsr",
control = out(reg) control, status = out(reg) status,
options(nomem, nostack, preserves_flags));
}
let _restore = RestoreEnvironment { control, status };
let modes = [
0,
1 << 22,
2 << 22,
3 << 22,
1 << 25,
1 << 19,
1 << 24,
1 << 26,
];
let mode_mask = (3 << 22) | (1 << 25) | (1 << 19) | (1 << 24) | (1 << 26);
let page = Page::new();
let mut checked = 0;
let mut observed_modes = std::collections::BTreeSet::new();
for (profile, mode) in modes.into_iter().enumerate() {
let requested = (control & !mode_mask) | mode;
let actual_control: u64;
let requested_status =
(status & !0x0800_009f) | if profile % 2 == 0 { 0x0800_009f } else { 0 };
unsafe {
std::arch::asm!("msr fpcr, {requested}", "msr fpsr, {status}", "mrs {actual}, fpcr",
requested = in(reg) requested, status = in(reg) requested_status,
actual = out(reg) actual_control,
options(nomem, nostack, preserves_flags));
}
observed_modes.insert(actual_control & mode_mask);
for immediate in 0u32..256 {
let bit = u64::from(immediate >> 6 & 1);
let expected = u64::from(immediate >> 7) << 15
| (bit ^ 1) << 14
| (bit * 3) << 12
| u64::from(immediate & 63) << 6;
for destination in 0u16..8 {
let word = 0x1ee0_1000 | immediate << 13 | u32::from(destination);
let ir = lift_words(&[word, RET]).expect("a scalar half immediate move");
assert!(unsupported(&ir).is_none(), "{}", ir.render());
let mut state: State = std::array::from_fn(|index| hash(0x5eed, index as u64));
state[NZCV] = (checked as u64 & 15) << 28;
let initial = state;
let before_status: u64;
unsafe {
std::arch::asm!("mrs {}, fpsr", out(reg) before_status,
options(nomem, nostack, preserves_flags));
}
assert!(
page.run(&[word], &mut state),
"processor rejected {word:#010x}, FPCR={actual_control:#x}"
);
let after_status: u64;
let after_control: u64;
unsafe {
std::arch::asm!("mrs {status}, fpsr", "mrs {control}, fpcr",
status = out(reg) after_status, control = out(reg) after_control,
options(nomem, nostack, preserves_flags));
}
assert_eq!(after_status, before_status, "{word:#010x}: FPSR");
assert_eq!(after_control, actual_control, "{word:#010x}: FPCR");
assert_eq!(state[NZCV], initial[NZCV], "{word:#010x}: NZCV");
let registers = registers(&initial);
let setup = super::setup(®isters);
let (after, memory) = eval::state_after(&ir, &setup).expect("a complete move");
assert!(memory.is_empty());
for &(index, start) in ®isters {
let processor = match index.checked_sub(vlk_arch::arch::aarch64::V0) {
Some(half) => state[VECTORS + usize::from(half)],
None => state[usize::from(index)],
};
let wanted = if index == vlk_arch::arch::aarch64::V0 + 2 * destination {
expected
} else if index == vlk_arch::arch::aarch64::V0 + 2 * destination + 1 {
0
} else {
start
};
assert_eq!(
processor, wanted,
"{word:#010x}, FPCR={actual_control:#x}, register {index}: processor"
);
assert_eq!(
after.get(&index).copied().unwrap_or(start),
processor,
"{word:#010x}, FPCR={actual_control:#x}, register {index}: IR"
);
}
checked += 1;
}
}
}
assert_eq!(checked, 16384);
assert!(
observed_modes
.iter()
.filter(|mode| **mode & !(3 << 22) == 0)
.count()
>= 4
);
eprintln!(
"{checked} exact scalar half immediate cases; observed FPCR mode bits {observed_modes:x?}"
);
}
#[test]
fn table_shift_and_aes_results_match_the_processor() {
let page = Page::new();
for word in [
0x6ee2_4420,
0x6e22_4420,
0x4e00_2000,
0x0e00_7020,
0x4e28_4820,
0x4e28_6800,
] {
let ir = lift_words(&[word, RET]).expect("SIMD lift");
assert!(unsupported(&ir).is_none(), "{}", ir.render());
for seed in 0..256 {
let mut state = [0; 46];
for half in 0..16 {
state[VECTORS + half] = match seed {
0 => 0,
1 => u64::MAX,
2 => 0x807f_403f_201f_100f,
_ => hash(seed, half as u64),
};
}
let registers: Vec<_> = (0..16)
.map(|half| {
(
vlk_arch::arch::aarch64::V0 + half as u16,
state[VECTORS + half],
)
})
.collect();
assert!(page.run(&[word], &mut state), "{word:08x}");
let (after, _) =
eval::state_after(&ir, &super::setup(®isters)).expect("SIMD evaluation");
for (index, initial) in registers {
assert_eq!(
after.get(&index).copied().unwrap_or(initial),
state[VECTORS + usize::from(index - vlk_arch::arch::aarch64::V0)],
"{word:08x}, seed {seed}, register {index}"
);
}
}
}
}
#[test]
fn literal_loads_match_the_processor() {
let page = Page::new();
for (word, expected) in [
(0x1800_0040, 0xd503_201fu64),
(0x5800_0040, 0xd503_201f_d503_201f),
(0x9800_0040, 0xffff_ffff_d503_201f),
] {
let body = [word, 0x1400_0003, 0xd503_201f, 0xd503_201f];
let ir = lift_words(&[body.as_slice(), &[RET]].concat()).expect("literal load lift");
assert!(unsupported(&ir).is_none(), "{}", ir.render());
let mut state = [0; 46];
assert!(page.run(&body, &mut state));
assert_eq!(state[0], expected);
let memory = [(8, 0xd503_201f_d503_201f)];
let setup = eval::Setup {
memory: &memory,
..super::setup(&[])
};
let (after, _) = eval::state_after(&ir, &setup).expect("literal load evaluation");
assert_eq!(after.get(&0), Some(&expected));
}
}