use super::*;
#[test]
fn find_bytes_word_and_start() {
let img = [0x00u8, 0x11, 0x22, 0x33, 0x44, 0x55];
assert_eq!(find(&img, Needle::Bytes(&[0x22, 0x33]), 0), Some(2));
assert_eq!(find(&img, Needle::Word(0x3322_1100), 0), Some(0));
assert_eq!(find(&img, Needle::Bytes(&[0x22, 0x33]), 3), None);
}
#[test]
fn find_free_run_and_wrapper() {
let mut img = vec![0u8; 32];
for b in img.iter_mut().skip(10).take(8) {
*b = 0xFF;
}
assert_eq!(find_free_space(&img, 8, 1, 0), Some(10));
assert_eq!(
find(&img, Needle::FreeRun { len: 8, align: 1 }, 0),
Some(10)
);
assert_eq!(find(&img, Needle::FreeRun { len: 9, align: 1 }, 0), None);
let run = find(&img, Needle::FreeRun { len: 4, align: 1 }, 0).unwrap();
assert_eq!(
find(&img, Needle::FreeRun { len: 4, align: 1 }, run + 8),
None
);
}
#[test]
fn bl_encode_decode_roundtrip() {
let cases: &[(usize, u32)] = &[
(0x9da80, 0x9bf50),
(0x9e3f8, 0x9bf50),
(0x1000, 0x1c3810),
(0x1c3810, 0x1000),
(0x100, 0x100 + 4), ];
for &(site, target) in cases {
let bytes = encode_bl(site, target).expect("in range");
let mut img = vec![0u8; site + 8];
img[site..site + 4].copy_from_slice(&bytes);
assert_eq!(
decode_bl(&img, site),
Some(target),
"roundtrip site=0x{site:x} target=0x{target:x}"
);
}
assert_eq!(encode_bl(0, 0x0200_0000), None);
}
#[test]
fn find_bl_sites_locates_direct_calls() {
let target = 0x1_5000u32;
let mut img = vec![0u8; 0x8000];
let a = 0x1000usize;
let b = 0x2000usize;
img[a..a + 4].copy_from_slice(&encode_bl(a, target).unwrap());
img[b..b + 4].copy_from_slice(&encode_bl(b, target).unwrap());
let sites = find_bl_sites(&img, target);
assert!(sites.contains(&a) && sites.contains(&b), "sites: {sites:?}");
}
#[test]
fn asm_reproduces_kat_handler_bytes() {
const KAT: &str = "094b58780e280dd19878c0280ad1d878de2807d100b5\
0920f0210022034b9847022000bd024b1847380d00026b2d0a005bad0900";
let mut a = Asm::new();
let tail = a.label();
a.ldr_lit(3, 0x0200_0d38); a.ldrb_imm(0, 3, 1); a.cmp_imm(0, 0x0E);
a.bne(tail);
a.ldrb_imm(0, 3, 2); a.cmp_imm(0, 0xC0);
a.bne(tail);
a.ldrb_imm(0, 3, 3); a.cmp_imm(0, 0xDE);
a.bne(tail);
a.push(0x0100); a.movs_imm(0, 0x09);
a.movs_imm(1, 0xF0);
a.movs_imm(2, 0x00);
a.ldr_lit(3, 0x000a_2d6b); a.blx(3);
a.movs_imm(0, 0x02);
a.pop(0x0100); a.bind(tail);
a.ldr_lit(3, 0x0009_ad5b); a.bx(3);
let got = a.finish().expect("assemble");
let hex: String = got.iter().map(|b| format!("{b:02x}")).collect();
assert_eq!(hex, KAT, "assembled handler drifted from the KAT");
}
#[test]
fn command_table_walk_follows_chain_and_stops_at_terminator() {
let stride = 8;
let seg2 = 0x40usize;
let mut img = vec![0u8; 0x80];
img[0] = 0x12;
img[1] = 0x01;
img[4..8].copy_from_slice(&0x1111u32.to_le_bytes());
img[8] = 0x00;
img[9] = 0x04;
img[12..16].copy_from_slice(&(seg2 as u32).to_le_bytes());
img[seg2] = 0x3C;
img[seg2 + 1] = 0x01;
img[seg2 + 4..seg2 + 8].copy_from_slice(&0x2222u32.to_le_bytes());
img[seg2 + 9] = 0x03;
let t = CommandTable {
base: 0,
stride,
opcode_off: 0,
flags_off: 1,
handler_off: 4,
term_flag: 0x03,
max_records: 64,
};
let recs = t.walk(&img, 0x04);
assert_eq!(recs.len(), 2, "expected both segments' real records");
assert_eq!((recs[0].opcode, recs[0].handler), (0x12, 0x1111));
assert_eq!((recs[1].opcode, recs[1].handler), (0x3C, 0x2222));
}
#[test]
fn prologue_check_accepts_push_lr_rejects_data() {
let mut img = vec![0u8; 16];
img[4..6].copy_from_slice(&0xB5F0u16.to_le_bytes()); assert!(prologue_is_push_lr(&img, 4, 4));
assert!(!prologue_is_push_lr(&img, 8, 4));
}
#[test]
fn prologue_check_looks_past_the_first_halfword_of_its_window() {
let mut img = vec![0u8; 16];
img[0..2].copy_from_slice(&0x46C0u16.to_le_bytes()); img[2..4].copy_from_slice(&0x46C0u16.to_le_bytes()); img[4..6].copy_from_slice(&0xB5F0u16.to_le_bytes()); assert!(
prologue_is_push_lr(&img, 0, 4),
"the push two halfwords in is inside a four-halfword window"
);
assert!(!prologue_is_push_lr(&img, 0, 2));
}
#[test]
fn prologue_check_ignores_a_push_pattern_that_is_off_the_instruction_grid() {
let mut img = vec![0u8; 16];
img[1] = 0x20;
img[2] = 0xB5;
assert!(!prologue_is_push_lr(&img, 0, 4));
}
#[test]
fn prologue_check_reaches_the_last_halfword_and_reads_no_further() {
let mut img = vec![0u8; 6];
img[4..6].copy_from_slice(&0xB500u16.to_le_bytes()); assert!(prologue_is_push_lr(&img, 4, 4));
assert!(!prologue_is_push_lr(&[0u8; 6], 4, 4));
}
#[test]
fn read_modify_insert() {
let mut img = vec![0xFFu8; 16];
write(&mut img, 4, &[0xDE, 0xAD, 0xBE, 0xEF]);
assert_eq!(read_u32(&img, 4), 0xEFBE_ADDE);
assert_eq!(read_u8(&img, 4), 0xDE);
let addr = insert(&mut img, 8, &[1, 2, 3]);
assert_eq!(addr, 8);
assert_eq!(&img[8..11], &[1, 2, 3]);
}
#[test]
fn finish_bails_on_out_of_range_conditional_branch() {
let mut a = Asm::new();
let back = a.label();
a.bind(back);
for _ in 0..200 {
a.raw16(0xBF00); }
a.beq(back);
let err = a.finish().unwrap_err().to_string();
assert!(
err.contains("conditional branch out of range"),
"unexpected error: {err}"
);
}
#[test]
fn finish_accepts_in_range_conditional_branch() {
let mut a = Asm::new();
let back = a.label();
a.bind(back);
for _ in 0..50 {
a.raw16(0xBF00); }
a.beq(back);
assert!(a.finish().is_ok());
}
#[test]
fn finish_bails_on_out_of_range_unconditional_branch() {
let mut a = Asm::new();
let back = a.label();
a.bind(back);
for _ in 0..1100 {
a.raw16(0xBF00); }
a.b(back);
let err = a.finish().unwrap_err().to_string();
assert!(
err.contains("branch out of range"),
"unexpected error: {err}"
);
}
#[test]
fn finish_bails_on_out_of_range_ldr_literal() {
let mut a = Asm::new();
a.ldr_lit(0, 0xDEAD_BEEF);
for _ in 0..600 {
a.raw16(0xBF00); }
let err = a.finish().unwrap_err().to_string();
assert!(
err.contains("ldr literal out of range"),
"unexpected error: {err}"
);
}
#[test]
fn finish_bails_on_out_of_range_adr() {
let mut a = Asm::new();
let blob = a.data_blob(vec![0u8; 4]);
a.adr(0, blob);
for _ in 0..600 {
a.raw16(0xBF00); }
let err = a.finish().unwrap_err().to_string();
assert!(
err.contains("adr target out of range"),
"unexpected error: {err}"
);
}
#[test]
fn command_table_find_locates_matching_opcode_and_misses_absent_one() {
let mut img = vec![0u8; 16];
img[0] = 0x10;
img[1] = 0x01;
img[4..8].copy_from_slice(&0xAAAAu32.to_le_bytes());
img[9] = 0x03;
let t = CommandTable {
base: 0,
stride: 8,
opcode_off: 0,
flags_off: 1,
handler_off: 4,
term_flag: 0x03,
max_records: 8,
};
assert_eq!(
t.find(&img, 0x10),
Some(CommandRecord {
off: 0,
opcode: 0x10,
flags: 0x01,
handler: 0xAAAA,
})
);
assert_eq!(t.find(&img, 0x99), None);
}
#[test]
fn command_table_find_gives_up_after_max_records_without_terminator() {
let img = vec![0u8; 8]; let t = CommandTable {
base: 0,
stride: 8,
opcode_off: 0,
flags_off: 1,
handler_off: 4,
term_flag: 0x03,
max_records: 1,
};
assert_eq!(t.find(&img, 0x10), None);
}
#[test]
fn command_table_replace_overwrites_handler_and_optionally_flags() {
let mut img = vec![0u8; 16];
img[0] = 0x10;
img[1] = 0x01;
let t = CommandTable {
base: 0,
stride: 8,
opcode_off: 0,
flags_off: 1,
handler_off: 4,
term_flag: 0x03,
max_records: 8,
};
let rec = t.find(&img, 0x10).unwrap();
t.replace(&mut img, &rec, 0x2000_1001, Some(0x02));
assert_eq!(read_u32(&img, 4), 0x2000_1001);
assert_eq!(img[1], 0x02);
t.replace(&mut img, &rec, 0x3000_2002, None);
assert_eq!(read_u32(&img, 4), 0x3000_2002);
assert_eq!(img[1], 0x02);
}
#[test]
fn command_table_walk_stops_after_max_records_without_terminator_or_chain() {
let mut img = vec![0u8; 16];
img[0] = 0x11; img[1] = 0x01;
img[8] = 0x22; img[9] = 0x01;
let t = CommandTable {
base: 0,
stride: 8,
opcode_off: 0,
flags_off: 1,
handler_off: 4,
term_flag: 0x03,
max_records: 2,
};
let recs = t.walk(&img, 0x04);
assert_eq!(recs.len(), 2);
assert_eq!(recs[0].opcode, 0x11);
assert_eq!(recs[1].opcode, 0x22);
}
#[test]
fn command_table_walk_breaks_on_chain_cycle() {
let seg_b = 0x40usize;
let mut img = vec![0u8; 0x80];
img[0] = 0x12; img[1] = 0x01;
img[8] = 0x00; img[9] = 0x04;
img[12..16].copy_from_slice(&(seg_b as u32).to_le_bytes());
img[seg_b] = 0x34; img[seg_b + 1] = 0x01;
img[seg_b + 8] = 0x00; img[seg_b + 9] = 0x04;
img[seg_b + 12..seg_b + 16].copy_from_slice(&0u32.to_le_bytes());
let t = CommandTable {
base: 0,
stride: 8,
opcode_off: 0,
flags_off: 1,
handler_off: 4,
term_flag: 0x03,
max_records: 8,
};
let recs = t.walk(&img, 0x04);
assert_eq!(
recs.len(),
2,
"one real record from each segment before the cycle breaks"
);
assert_eq!((recs[0].opcode, recs[1].opcode), (0x12, 0x34));
}
#[test]
fn command_table_walk_returns_collected_records_when_run_exceeds_image_bounds() {
let mut img = vec![0u8; 12];
img[0] = 0x55;
img[1] = 0x01;
let t = CommandTable {
base: 0,
stride: 8,
opcode_off: 0,
flags_off: 1,
handler_off: 4,
term_flag: 0x03,
max_records: 8,
};
let recs = t.walk(&img, 0x04);
assert_eq!(recs.len(), 1);
assert_eq!(recs[0].opcode, 0x55);
}
#[test]
fn asm_data_processing_and_load_store_emitters_encode_expected_bits() {
let mut a = Asm::new();
assert_eq!(a.pos(), 0);
a.ldr_imm(1, 2, 4);
a.strh_imm(3, 4, 2);
a.str_imm(5, 6, 8);
a.bics(0, 1);
a.orrs(2, 3);
a.strb_imm(1, 2, 3);
a.cmp_reg(4, 5);
a.ldrb_reg(0, 1, 2);
a.adds_imm(3, 7);
a.subs_imm(2, 9);
a.lsls_imm(1, 2, 3);
a.lsrs_imm(4, 5, 6);
a.adds_reg(1, 2, 3);
a.mov_reg(6, 7);
a.movs_reg(6, 7);
assert_eq!(a.pos(), 30);
let code = a.finish().expect("nothing to range-check");
let hw = |i: usize| u16::from_le_bytes([code[i * 2], code[i * 2 + 1]]);
assert_eq!(hw(0), 0x6800 | (1 << 6) | (2 << 3) | 1);
assert_eq!(hw(1), 0x8000 | (1 << 6) | (4 << 3) | 3);
assert_eq!(hw(2), 0x6000 | (2 << 6) | (6 << 3) | 5);
assert_eq!(hw(3), 0x4380 | (1 << 3));
assert_eq!(hw(4), 0x4300 | (3 << 3) | 2);
assert_eq!(hw(5), 0x7000 | (3 << 6) | (2 << 3) | 1);
assert_eq!(hw(6), 0x4280 | (5 << 3) | 4);
assert_eq!(hw(7), 0x5C00 | (2 << 6) | (1 << 3));
assert_eq!(hw(8), 0x3000 | (3 << 8) | 7);
assert_eq!(hw(9), 0x3800 | (2 << 8) | 9);
assert_eq!(hw(10), (3 << 6) | (2 << 3) | 1);
assert_eq!(hw(11), 0x0800 | (6 << 6) | (5 << 3) | 4);
assert_eq!(hw(12), 0x1800 | (3 << 6) | (2 << 3) | 1);
assert_eq!(hw(13), 0x4600 | (7 << 3) | 6);
assert_eq!(hw(14), (7 << 3) | 6);
}
#[test]
fn asm_conditional_branch_emitters_cover_all_fourteen_conditions() {
type Emit = fn(&mut Asm, u16);
let cases: &[(u16, Emit)] = &[
(0xD000, |a, l| {
a.beq(l);
}),
(0xD100, |a, l| {
a.bne(l);
}),
(0xD200, |a, l| {
a.bhs(l);
}),
(0xD300, |a, l| {
a.blo(l);
}),
(0xD400, |a, l| {
a.bmi(l);
}),
(0xD500, |a, l| {
a.bpl(l);
}),
(0xD600, |a, l| {
a.bvs(l);
}),
(0xD700, |a, l| {
a.bvc(l);
}),
(0xD800, |a, l| {
a.bhi(l);
}),
(0xD900, |a, l| {
a.bls(l);
}),
(0xDA00, |a, l| {
a.bge(l);
}),
(0xDB00, |a, l| {
a.blt(l);
}),
(0xDC00, |a, l| {
a.bgt(l);
}),
(0xDD00, |a, l| {
a.ble(l);
}),
];
assert_eq!(cases.len(), 14);
for &(base, emit) in cases {
let mut a = Asm::new();
let here = a.label();
a.bind(here);
emit(&mut a, here);
let code = a.finish().expect("self-branch is always in range");
let hw = u16::from_le_bytes([code[0], code[1]]);
assert_eq!(hw & 0xFF00, base, "base opcode for {base:#06x}");
}
}
#[test]
fn asm_b_cond_always_lowers_to_the_unconditional_branch() {
let mut a = Asm::new();
let here = a.label();
a.bind(here);
a.b_cond(Cond::Al, here);
let code = a.finish().expect("self-branch is always in range");
let hw = u16::from_le_bytes([code[0], code[1]]);
assert_eq!(hw & 0xF800, 0xE000);
assert_ne!(hw & 0xFF00, 0xDE00);
}
#[test]
fn asm_ldr_lit_dedups_repeated_literal_values() {
let mut a = Asm::new();
a.ldr_lit(0, 0x1234_5678);
a.ldr_lit(1, 0x1234_5678); let code = a.finish().expect("small, in-range pool");
assert_eq!(code.len(), 8);
let pool = u32::from_le_bytes([code[4], code[5], code[6], code[7]]);
assert_eq!(pool, 0x1234_5678);
}
#[test]
fn decode_bl_rejects_non_bl_bytes_and_out_of_bounds_offset() {
let img = [0u8; 4]; assert_eq!(decode_bl(&img, 0), None);
assert_eq!(decode_bl(&img, 1), None); }
#[test]
fn encode_bl_rejects_odd_target_offset() {
assert_eq!(encode_bl(0, 5), None);
}
#[test]
fn encode_decode_b_wide_roundtrip_and_rejections() {
let cases: &[(usize, u32)] = &[(0x1000, 0x2000), (0x2000, 0x1000), (0x100, 0x104)];
for &(site, target) in cases {
let bytes = encode_b_wide(site, target).expect("in range");
let mut img = vec![0u8; site + 8];
img[site..site + 4].copy_from_slice(&bytes);
assert_eq!(decode_b_wide(&img, site), Some(target));
assert_eq!(decode_bl(&img, site), None);
}
assert_eq!(encode_b_wide(0, 0x0200_0000), None);
assert_eq!(encode_b_wide(0, 5), None);
assert_eq!(decode_b_wide(&[0u8; 2], 0), None);
let bl = encode_bl(0, 0x1000).unwrap();
assert_eq!(decode_b_wide(&bl, 0), None);
}
#[test]
fn find_bytes_rejects_empty_pattern_and_out_of_range_start() {
let img = [1u8, 2, 3, 4];
assert_eq!(find(&img, Needle::Bytes(&[]), 0), None);
assert_eq!(find(&img, Needle::Bytes(&[1]), 10), None);
}
#[test]
fn find_free_run_zero_length_matches_at_clamped_start() {
let img = [0u8; 8];
assert_eq!(find(&img, Needle::FreeRun { len: 0, align: 1 }, 3), Some(3));
assert_eq!(
find(&img, Needle::FreeRun { len: 0, align: 1 }, 100),
Some(8)
); }
#[test]
fn command_table_find_returns_none_when_run_exceeds_image_bounds() {
let mut img = vec![0u8; 12];
img[0] = 0x55;
img[1] = 0x01;
let t = CommandTable {
base: 0,
stride: 8,
opcode_off: 0,
flags_off: 1,
handler_off: 4,
term_flag: 0x03,
max_records: 8,
};
assert_eq!(t.find(&img, 0xAA), None);
}
#[test]
fn command_table_find_sees_a_record_that_ends_exactly_at_the_image_end() {
let mut img = vec![0u8; 16];
img[0] = 0x10;
img[1] = 0x01;
img[4..8].copy_from_slice(&0xAAAAu32.to_le_bytes());
img[8] = 0x2A;
img[9] = 0x01;
img[12..16].copy_from_slice(&0xBEEFu32.to_le_bytes());
let t = CommandTable {
base: 0,
stride: 8,
opcode_off: 0,
flags_off: 1,
handler_off: 4,
term_flag: 0x03,
max_records: 8,
};
assert_eq!(
t.find(&img, 0x2A),
Some(CommandRecord {
off: 8,
opcode: 0x2A,
flags: 0x01,
handler: 0xBEEF,
}),
"a record ending on the last byte of the image is still a record"
);
}
#[test]
fn command_table_find_refuses_a_first_record_the_image_is_too_short_to_hold() {
let mut img = vec![0u8; 4]; img[0] = 0x10;
img[1] = 0x01;
let t = CommandTable {
base: 0,
stride: 8,
opcode_off: 0,
flags_off: 1,
handler_off: 4,
term_flag: 0x03,
max_records: 8,
};
assert_eq!(t.find(&img, 0x10), None);
}
fn table_with_the_opcode_inside_the_record() -> (Vec<u8>, CommandTable) {
let mut img = vec![0u8; 40];
img[9] = 0x01;
img[10] = 0x11;
img[12..16].copy_from_slice(&0x1111u32.to_le_bytes());
img[17] = 0x01;
img[18] = 0x22;
img[20..24].copy_from_slice(&0x2222u32.to_le_bytes());
img[25] = 0x03;
let t = CommandTable {
base: 8,
stride: 8,
opcode_off: 2,
flags_off: 1,
handler_off: 4,
term_flag: 0x03,
max_records: 8,
};
(img, t)
}
#[test]
fn command_table_find_steps_one_stride_and_reads_the_opcode_from_inside_the_record() {
let (img, t) = table_with_the_opcode_inside_the_record();
assert_eq!(
t.find(&img, 0x22),
Some(CommandRecord {
off: 16,
opcode: 0x22,
flags: 0x01,
handler: 0x2222,
}),
"the second record is exactly one stride past the base"
);
assert_eq!(t.find(&img, 0x11).map(|r| r.off), Some(8));
assert_eq!(t.find(&img, 0x00), None);
}
#[test]
fn command_table_walk_reads_each_opcode_from_inside_its_own_record() {
let (img, t) = table_with_the_opcode_inside_the_record();
let recs = t.walk(&img, 0x04);
assert_eq!(recs.len(), 2);
assert_eq!(
(recs[0].off, recs[0].opcode, recs[0].handler),
(8, 0x11, 0x1111)
);
assert_eq!(
(recs[1].off, recs[1].opcode, recs[1].handler),
(16, 0x22, 0x2222)
);
}
#[test]
fn command_table_walk_spends_one_budget_across_the_whole_scan() {
let mut img = vec![0u8; 40]; img[0] = 0x10;
img[1] = 0x01;
img[8] = 0x11;
img[9] = 0x01;
img[16] = 0x12;
img[17] = 0x01;
img[24] = 0x13;
img[25] = 0x01;
img[32] = 0x14;
img[33] = 0x01;
let t = CommandTable {
base: 0,
stride: 8,
opcode_off: 0,
flags_off: 1,
handler_off: 4,
term_flag: 0x03,
max_records: 2,
};
let recs = t.walk(&img, 0x04);
assert_eq!(recs.len(), 2, "max_records caps the whole walk");
assert_eq!((recs[0].opcode, recs[1].opcode), (0x10, 0x11));
}
#[test]
fn finish_encodes_in_range_unconditional_branch() {
let mut a = Asm::new();
let target = a.label();
a.raw16(0xBF00); a.b(target);
a.bind(target);
let code = a.finish().expect("well within the +-1023 halfword range");
let hw = u16::from_le_bytes([code[2], code[3]]);
assert_eq!(hw & 0xF800, 0xE000); }
#[test]
fn finish_bails_on_unbound_branch_label() {
let mut a = Asm::new();
let never_bound = a.label();
a.beq(never_bound);
let err = a.finish().unwrap_err().to_string();
assert!(err.contains("unbound label"), "unexpected error: {err}");
}
#[test]
fn finish_bails_on_unbound_blob_label() {
let mut a = Asm::new();
let never_bound = a.label();
a.adr(0, never_bound);
let err = a.finish().unwrap_err().to_string();
assert!(
err.contains("unbound blob label"),
"unexpected error: {err}"
);
}
#[test]
fn finish_pads_each_data_blob_to_four_byte_alignment_and_resolves_adr() {
let mut a = Asm::new();
let blob1 = a.data_blob(vec![0xAA, 0xBB, 0xCC]);
let blob2 = a.data_blob(vec![0xDD, 0xEE, 0xFF, 0x11]);
a.adr(0, blob1);
a.adr(1, blob2);
let code = a.finish().expect("small, in-range adr targets");
assert_eq!(&code[4..7], &[0xAA, 0xBB, 0xCC]);
assert_eq!(&code[8..12], &[0xDD, 0xEE, 0xFF, 0x11]); }
#[test]
fn find_bl_sites_finds_a_bl_in_the_final_four_bytes() {
let target = 0x40u32;
let mut img = vec![0u8; 0x20];
let site = img.len() - 4;
let bytes = encode_bl(site, target).expect("in range");
img[site..].copy_from_slice(&bytes);
assert_eq!(find_bl_sites(&img, target), vec![site]);
assert_eq!(find_bl_sites(&img, target | 1), vec![site]);
}
#[test]
fn find_bl_sites_tolerates_images_too_short_to_hold_one() {
for len in 0..4usize {
assert!(
find_bl_sites(&vec![0xFFu8; len], 0x100).is_empty(),
"len {len}"
);
}
}
#[test]
fn read_u16_and_the_checked_read_family() {
let img = [0x78u8, 0x56, 0x34, 0x12];
assert_eq!(read_u16(&img, 0), 0x5678);
assert_eq!(read_u16(&img, 2), 0x1234);
assert_eq!(read_u8(&img, 3), 0x12);
assert_eq!(read_u32(&img, 0), 0x1234_5678);
assert_eq!(try_read_u8(&img, 0), Some(0x78));
assert_eq!(try_read_u16(&img, 2), Some(0x1234));
assert_eq!(try_read_u32(&img, 0), Some(0x1234_5678));
assert_eq!(try_read_u8(&img, 4), None);
assert_eq!(try_read_u16(&img, 3), None);
assert_eq!(try_read_u16(&img, 99), None);
assert_eq!(try_read_u32(&img, 1), None);
assert!(try_read_u8(&img, 3).is_some());
assert!(try_read_u16(&img, 2).is_some());
assert!(try_read_u32(&img, 0).is_some());
assert_eq!(try_read_u8(&[], 0), None);
assert_eq!(try_read_u16(&[], 0), None);
assert_eq!(try_read_u32(&[], 0), None);
}
#[test]
fn decode_b_cond_t1_hand_computed_vector_and_all_conditions() {
let b = decode_b_cond(&[0x0E, 0xD4], 0).expect("a bmi");
assert_eq!(b.cond, Cond::Mi);
assert_eq!(b.target, 0x20);
assert_eq!(b.len, 2);
let at = 0x100;
let mut img = vec![0u8; 0x200];
img[at..at + 2].copy_from_slice(&0xD1FEu16.to_le_bytes());
let b = decode_b_cond(&img, at).expect("a bne");
assert_eq!((b.cond, b.target, b.len), (Cond::Ne, at as u32, 2));
for bits in 0u8..=0b1101 {
let hw = 0xD000u16 | ((bits as u16) << 8);
let got = decode_b_cond(&hw.to_le_bytes(), 0).expect("a branch");
assert_eq!(got.cond, Cond::from_bits(bits).unwrap(), "cond {bits:#06b}");
assert_eq!(got.target, 4); }
}
#[test]
fn decode_b_cond_rejects_udf_and_svc() {
assert_eq!(decode_b_cond(&[0x00, 0xDE], 0), None);
assert_eq!(decode_b_cond(&[0x00, 0xDF], 0), None);
for imm8 in [0x00u8, 0x01, 0x7F, 0x80, 0xFF] {
assert_eq!(
decode_b_cond(&[imm8, 0xDE], 0),
None,
"udf imm8 {imm8:#04x}"
);
assert_eq!(
decode_b_cond(&[imm8, 0xDF], 0),
None,
"svc imm8 {imm8:#04x}"
);
}
assert_eq!(decode_b_cond(&[0x00, 0xDD], 0).unwrap().cond, Cond::Le);
}
#[test]
fn decode_b_cond_t3_hand_computed_vector() {
let at = 0x1000usize;
let mut img = vec![0u8; 0x4000];
img[at..at + 4].copy_from_slice(&[0x10, 0xF1, 0x00, 0x80]);
let b = decode_b_cond(&img, at).expect("a bmi.w");
assert_eq!(b.cond, Cond::Mi);
assert_eq!(b.target, 0x1_1004);
assert_eq!(b.len, 4);
let at = 0x2000usize;
img[at..at + 4].copy_from_slice(&[0xFF, 0xF6, 0x80, 0xAF]);
let b = decode_b_cond(&img, at).expect("a blt.w");
assert_eq!((b.cond, b.target, b.len), (Cond::Lt, 0x1F04, 4));
assert_eq!(decode_bl(&img, at), None);
assert_eq!(decode_b_wide(&img, at), None);
}
#[test]
fn decode_b_cond_rejects_non_branches_and_truncated_reads() {
assert_eq!(decode_b_cond(&0x2001u16.to_le_bytes(), 0), None);
let bl = encode_bl(0, 0x100).unwrap();
assert_eq!(decode_b_cond(&bl, 0), None);
let bw = encode_b_wide(0, 0x100).unwrap();
assert_eq!(decode_b_cond(&bw, 0), None);
for bits in [0b1110u16, 0b1111] {
let hw1 = 0xF000u16 | (bits << 6);
let mut bytes = Vec::new();
bytes.extend_from_slice(&hw1.to_le_bytes());
bytes.extend_from_slice(&0x8000u16.to_le_bytes());
assert_eq!(decode_b_cond(&bytes, 0), None, "cond {bits:#06b}");
}
assert_eq!(decode_b_cond(&0xF000u16.to_le_bytes(), 0), None);
assert_eq!(decode_b_cond(&[], 0), None);
assert_eq!(decode_b_cond(&[0x0E], 0), None);
}
#[test]
fn encode_b_cond_picks_the_narrowest_encoding_and_roundtrips() {
let site = 0x10_0000usize;
let pc = site as u32 + 4;
let cases: &[(u32, usize)] = &[
(pc, 2), (pc + 254, 2), (pc.wrapping_sub(256), 2), (pc + 256, 4), (pc.wrapping_sub(258), 4),
(pc + 1_048_574, 4), (pc.wrapping_sub(1_048_576), 4), ];
let mut img = vec![0u8; 0x40_0000];
for &(target, len) in cases {
for bits in 0u8..=0b1101 {
let cond = Cond::from_bits(bits).unwrap();
let bytes = encode_b_cond(site, cond, target)
.unwrap_or_else(|| panic!("in range: target {target:#x} cond {cond}"));
assert_eq!(bytes.len(), len, "width for target {target:#x}");
img[site..site + bytes.len()].copy_from_slice(&bytes);
let got = decode_b_cond(&img, site).expect("decodes back");
assert_eq!(got.cond, cond);
assert_eq!(got.target, target, "roundtrip target {target:#x}");
assert_eq!(got.len, len);
}
}
assert_eq!(encode_b_cond(site, Cond::Eq, pc + 1_048_576), None);
assert_eq!(
encode_b_cond(site, Cond::Eq, pc.wrapping_sub(1_048_578)),
None
);
assert_eq!(encode_b_cond(site, Cond::Eq, pc + 1), None);
assert_eq!(encode_b_cond(site, Cond::Eq, pc + 0x1001), None);
assert_eq!(encode_b_cond(site, Cond::Al, pc), None);
assert_eq!(encode_b_cond(site, Cond::Al, pc + 0x1000), None);
}
#[test]
fn encode_b_cond_matches_the_hand_computed_t1_and_t3_vectors() {
assert_eq!(encode_b_cond(0, Cond::Mi, 0x20), Some(vec![0x0E, 0xD4]));
assert_eq!(
encode_b_cond(0x1000, Cond::Mi, 0x1_1004),
Some(vec![0x10, 0xF1, 0x00, 0x80])
);
assert_eq!(
encode_b_cond(0x2000, Cond::Lt, 0x1E04),
Some(vec![0xFF, 0xF6, 0x00, 0xAF])
);
assert_eq!(
encode_b_cond(0x2000, Cond::Lt, 0x1F04),
Some(vec![0x80, 0xDB])
);
}
#[test]
fn branch_kind_dispatches_and_displays() {
assert_eq!(BranchKind::Bl.to_string(), "bl");
assert_eq!(BranchKind::BWide.to_string(), "b.w");
let site = 0x1000usize;
let target = 0x2000u32;
let mut img = vec![0u8; 0x4000];
for kind in [BranchKind::Bl, BranchKind::BWide] {
let bytes = kind.encode(site, target).expect("in range");
img[site..site + 4].copy_from_slice(&bytes);
assert_eq!(kind.decode(&img, site), Some(target));
}
let bl = BranchKind::Bl.encode(site, target).unwrap();
img[site..site + 4].copy_from_slice(&bl);
assert_eq!(BranchKind::BWide.decode(&img, site), None);
assert_eq!(BranchKind::Bl.encode(0, 0x0200_0000), None);
assert_eq!(BranchKind::BWide.encode(0, 0x0200_0000), None);
}
#[test]
fn install_branch_writes_and_verifies_both_kinds() {
let mut img = vec![0u8; 0x4000];
for (site, kind) in [(0x100usize, BranchKind::Bl), (0x200, BranchKind::BWide)] {
install_branch(&mut img, site, kind, 0x1001).expect("in range");
assert_eq!(kind.decode(&img, site), Some(0x1000));
assert!(verify_branch(&img, site, kind, 0x1000).is_ok());
assert!(verify_branch(&img, site, kind, 0x1001).is_ok()); install_branch(&mut img, site, kind, 0x1000).expect("still in range");
assert!(verify_branch(&img, site, kind, 0x1000).is_ok());
}
}
#[test]
fn verify_branch_reports_a_wrong_target_a_wrong_kind_and_no_branch_at_all() {
let mut img = vec![0u8; 0x4000];
let site = 0x100usize;
install_branch(&mut img, site, BranchKind::Bl, 0x1000).expect("in range");
let err = verify_branch(&img, site, BranchKind::Bl, 0x2000).unwrap_err();
assert_eq!(
err,
InstallMismatch {
site,
kind: BranchKind::Bl,
expected: 0x2000,
found: Some(0x1000),
}
);
assert_eq!(
err.to_string(),
"bl at 0x100: expected target 0x00002000, found 0x00001000"
);
assert_eq!(
verify_branch(&img, site, BranchKind::Bl, 0x2001).unwrap_err(),
err
);
let err = verify_branch(&img, site, BranchKind::BWide, 0x1000).unwrap_err();
assert_eq!(err.found, None);
assert_eq!(
err.to_string(),
"b.w at 0x100: expected target 0x00001000, but no b.w decodes there"
);
let err = verify_branch(&img, 0x800, BranchKind::Bl, 0x1000).unwrap_err();
assert_eq!(err.found, None);
let dynamic: &dyn std::error::Error = &err;
assert!(dynamic.to_string().contains("no bl decodes there"));
assert!(dynamic.source().is_none());
}
#[test]
fn install_branch_writes_nothing_when_it_cannot_encode() {
let mut img = vec![0u8; 0x100];
let before = img.clone();
let err = install_branch(&mut img, 0x10, BranchKind::Bl, 0x0200_0000).unwrap_err();
assert_eq!(err.found, None);
assert_eq!(err.expected, 0x0200_0000);
assert_eq!(img, before, "a failed install must not touch the image");
let mut small = vec![0u8; 6];
let err = install_branch(&mut small, 4, BranchKind::BWide, 0x0).unwrap_err();
assert_eq!(err.found, None);
assert_eq!(err.site, 4);
assert_eq!(small, vec![0u8; 6]);
let mut exact = vec![0u8; 8];
install_branch(&mut exact, 4, BranchKind::BWide, 0x8).expect("fits exactly");
assert_eq!(decode_b_wide(&exact, 4), Some(0x8));
}
#[test]
fn crate_result_alias_defaults_to_asm_error() {
fn build() -> Result<Vec<u8>> {
let mut a = Asm::new();
a.mov_reg(0, 8); a.finish()
}
assert_eq!(build().unwrap(), vec![0x40, 0x46, 0x00, 0x00]);
fn check(img: &[u8]) -> Result<(), InstallMismatch> {
verify_branch(img, 0, BranchKind::Bl, 0x10)
}
assert!(check(&[0u8; 8]).is_err());
}
#[test]
fn mov_reg_reaches_the_high_registers_and_preserves_the_flag_setting_alias() {
let mut a = Asm::new();
a.mov_reg(0, 8); a.mov_reg(9, 1); a.mov_reg(15, 14); a.movs_reg(1, 2); a.lsls_imm(1, 2, 0); let code = a.finish().expect("no fixups");
let hw = |i: usize| u16::from_le_bytes([code[i * 2], code[i * 2 + 1]]);
assert_eq!(hw(0), 0x4600 | (8 << 3)); assert_eq!(hw(1), 0x4600 | (1 << 7) | (1 << 3) | 1); assert_eq!(hw(2), 0x4600 | (1 << 7) | (14 << 3) | 7); assert_eq!(hw(3), (2 << 3) | 1); assert_eq!(hw(3), hw(4), "lsls #0 IS movs (A5-2 footnote a)");
assert_eq!(hw(0) & 0xFE00, 0x4600);
assert_ne!(hw(0) & 0xFE00, 0x1C00);
}
#[test]
fn cond_bits_roundtrip_suffixes_and_inversions() {
let all = [
(0b0000u8, Cond::Eq, "eq", Cond::Ne),
(0b0001, Cond::Ne, "ne", Cond::Eq),
(0b0010, Cond::Hs, "hs", Cond::Lo),
(0b0011, Cond::Lo, "lo", Cond::Hs),
(0b0100, Cond::Mi, "mi", Cond::Pl),
(0b0101, Cond::Pl, "pl", Cond::Mi),
(0b0110, Cond::Vs, "vs", Cond::Vc),
(0b0111, Cond::Vc, "vc", Cond::Vs),
(0b1000, Cond::Hi, "hi", Cond::Ls),
(0b1001, Cond::Ls, "ls", Cond::Hi),
(0b1010, Cond::Ge, "ge", Cond::Lt),
(0b1011, Cond::Lt, "lt", Cond::Ge),
(0b1100, Cond::Gt, "gt", Cond::Le),
(0b1101, Cond::Le, "le", Cond::Gt),
(0b1110, Cond::Al, "", Cond::Al),
];
for &(bits, cond, suffix, inverted) in &all {
assert_eq!(Cond::from_bits(bits), Some(cond), "from_bits {bits:#06b}");
assert_eq!(cond.bits(), bits);
assert_eq!(cond.suffix(), suffix);
assert_eq!(cond.to_string(), suffix);
assert_eq!(cond.invert(), inverted, "invert {suffix}");
assert_eq!(cond.invert().invert(), cond);
}
assert_eq!(Cond::from_bits(0xF0), Some(Cond::Eq));
assert_eq!(Cond::from_bits(0b1111), None);
assert_eq!(Cond::from_bits(0xFF), None);
}
#[test]
fn try_reads_refuse_an_offset_that_would_overflow_rather_than_panicking() {
let img = [0xAAu8; 8];
for at in [usize::MAX, usize::MAX - 1, usize::MAX - 3] {
assert_eq!(try_read_u8(&img, at), None, "u8 at {at:#x}");
assert_eq!(try_read_u16(&img, at), None, "u16 at {at:#x}");
assert_eq!(try_read_u32(&img, at), None, "u32 at {at:#x}");
}
assert_eq!(try_read_u16(&img, 6), Some(0xAAAA));
assert_eq!(try_read_u32(&img, 4), Some(0xAAAA_AAAA));
assert_eq!(try_read_u32(&img, 5), None);
}
#[test]
fn free_space_refuses_a_length_that_would_overflow_the_window() {
let img = [0xFFu8; 8];
assert_eq!(find_free_space(&img, usize::MAX, 1, 1), None);
assert_eq!(find_free_space(&img, usize::MAX, 1, 0), None);
assert_eq!(find_free_space(&img, usize::MAX - 1, 4, 4), None);
assert_eq!(find_free_space(&img, 8, 1, 0), Some(0));
assert_eq!(find_free_space(&img, 4, 4, 1), Some(4));
}
#[test]
fn branch_decoders_refuse_an_offset_that_would_overflow() {
let img = [0u8; 8];
for at in [usize::MAX, usize::MAX - 3] {
assert_eq!(decode_bl(&img, at), None, "decode_bl at {at:#x}");
assert_eq!(decode_b_wide(&img, at), None, "decode_b_wide at {at:#x}");
}
let mut img = vec![0u8; 8];
img[0..4].copy_from_slice(&encode_bl(0, 0x40).unwrap());
assert_eq!(decode_bl(&img, 0), Some(0x40));
}
fn rejected(build: impl FnOnce(&mut Asm)) -> String {
let mut a = Asm::new();
build(&mut a);
match a.finish() {
Ok(bytes) => panic!("expected rejection, assembled {bytes:02x?}"),
Err(e) => e.to_string(),
}
}
fn accepted(build: impl FnOnce(&mut Asm)) -> Vec<u8> {
let mut a = Asm::new();
build(&mut a);
a.finish().expect("expected this to assemble")
}
fn accepted_hw(build: impl FnOnce(&mut Asm)) -> [u8; 2] {
let b = accepted(build);
[b[0], b[1]]
}
#[test]
fn push_with_a_reglist_that_overflows_its_field_is_rejected_not_encoded() {
let e = rejected(|a| {
a.push(0x4000);
});
assert!(e.contains("push"), "{e}");
assert!(e.contains("outside R0-R7"), "{e}");
assert_eq!(
accepted_hw(|a| {
a.push(0x0100);
}),
0xB500u16.to_le_bytes()
);
assert_eq!(
accepted_hw(|a| {
a.push(0x0103);
}),
0xB503u16.to_le_bytes()
);
assert_eq!(
accepted_hw(|a| {
a.pop(0x0100);
}),
0xBD00u16.to_le_bytes()
);
assert_eq!(
accepted_hw(|a| {
a.pop(0x0103);
}),
0xBD03u16.to_le_bytes()
);
}
#[test]
fn push_and_pop_accept_the_widest_list_the_encoding_can_hold() {
assert_eq!(
accepted_hw(|a| {
a.push(0x01FF);
}),
0xB5FFu16.to_le_bytes()
);
assert_eq!(
accepted_hw(|a| {
a.pop(0x01FF);
}),
0xBDFFu16.to_le_bytes()
);
assert!(rejected(|a| {
a.push(0x0200);
})
.contains("outside R0-R7"));
assert!(rejected(|a| {
a.pop(0x0200);
})
.contains("outside R0-R7"));
}
#[test]
fn an_empty_push_or_pop_list_is_unpredictable_and_refused() {
assert!(rejected(|a| {
a.push(0);
})
.contains("empty"));
assert!(rejected(|a| {
a.pop(0);
})
.contains("empty"));
}
#[test]
fn every_low_register_operand_rejects_a_high_register() {
type Case = (&'static str, fn(&mut Asm));
let cases: Vec<Case> = vec![
("ldr_lit", |a| {
a.ldr_lit(8, 0xDEAD);
}),
("ldrb_imm", |a| {
a.ldrb_imm(8, 0, 0);
}),
("ldrb_imm", |a| {
a.ldrb_imm(0, 8, 0);
}),
("ldr_imm", |a| {
a.ldr_imm(8, 0, 0);
}),
("ldr_imm", |a| {
a.ldr_imm(0, 8, 0);
}),
("strh_imm", |a| {
a.strh_imm(8, 0, 0);
}),
("strh_imm", |a| {
a.strh_imm(0, 8, 0);
}),
("str_imm", |a| {
a.str_imm(8, 0, 0);
}),
("str_imm", |a| {
a.str_imm(0, 8, 0);
}),
("bics", |a| {
a.bics(8, 0);
}),
("bics", |a| {
a.bics(0, 8);
}),
("orrs", |a| {
a.orrs(8, 0);
}),
("orrs", |a| {
a.orrs(0, 8);
}),
("strb_imm", |a| {
a.strb_imm(8, 0, 0);
}),
("strb_imm", |a| {
a.strb_imm(0, 8, 0);
}),
("cmp_imm", |a| {
a.cmp_imm(8, 0);
}),
("cmp_reg", |a| {
a.cmp_reg(8, 0);
}),
("cmp_reg", |a| {
a.cmp_reg(0, 8);
}),
("movs_imm", |a| {
a.movs_imm(8, 0);
}),
("ldrb_reg", |a| {
a.ldrb_reg(8, 0, 0);
}),
("ldrb_reg", |a| {
a.ldrb_reg(0, 8, 0);
}),
("ldrb_reg", |a| {
a.ldrb_reg(0, 0, 8);
}),
("adds_imm", |a| {
a.adds_imm(8, 0);
}),
("subs_imm", |a| {
a.subs_imm(8, 0);
}),
("lsls_imm", |a| {
a.lsls_imm(8, 0, 0);
}),
("lsls_imm", |a| {
a.lsls_imm(0, 8, 0);
}),
("lsrs_imm", |a| {
a.lsrs_imm(8, 0, 1);
}),
("lsrs_imm", |a| {
a.lsrs_imm(0, 8, 1);
}),
("adds_reg", |a| {
a.adds_reg(8, 0, 0);
}),
("adds_reg", |a| {
a.adds_reg(0, 8, 0);
}),
("adds_reg", |a| {
a.adds_reg(0, 0, 8);
}),
("movs_reg", |a| {
a.movs_reg(8, 0);
}),
("movs_reg", |a| {
a.movs_reg(0, 8);
}),
("adr", |a| {
a.adr(8, 0);
}),
];
for (name, build) in cases {
let e = rejected(build);
assert!(
e.starts_with(name) && e.contains("low register"),
"{name}: unhelpful or missing rejection: {e}"
);
}
}
#[test]
fn immediate_fields_reject_oversized_and_unaligned_values() {
assert!(rejected(|a| {
a.ldrb_imm(0, 1, 32);
})
.contains("exceeds maximum 31"));
assert!(rejected(|a| {
a.strb_imm(0, 1, 32);
})
.contains("exceeds maximum 31"));
assert!(rejected(|a| {
a.lsls_imm(0, 1, 32);
})
.contains("exceeds maximum 31"));
assert!(rejected(|a| {
a.lsrs_imm(0, 1, 32);
})
.contains("exceeds maximum 31"));
assert!(rejected(|a| {
a.ldr_imm(0, 1, 128);
})
.contains("exceeds maximum 124"));
assert!(rejected(|a| {
a.ldr_imm(0, 1, 2);
})
.contains("multiple of 4"));
assert!(rejected(|a| {
a.str_imm(0, 1, 128);
})
.contains("exceeds maximum 124"));
assert!(rejected(|a| {
a.str_imm(0, 1, 2);
})
.contains("multiple of 4"));
assert!(rejected(|a| {
a.strh_imm(0, 1, 64);
})
.contains("exceeds maximum 62"));
assert!(rejected(|a| {
a.strh_imm(0, 1, 1);
})
.contains("multiple of 2"));
accepted(|a| {
a.ldrb_imm(0, 1, 31);
});
accepted(|a| {
a.ldr_imm(0, 1, 124);
});
accepted(|a| {
a.str_imm(0, 1, 124);
});
accepted(|a| {
a.strh_imm(0, 1, 62);
});
accepted(|a| {
a.lsls_imm(0, 1, 31);
});
accepted(|a| {
a.lsrs_imm(0, 1, 0);
});
}
#[test]
fn full_width_register_operands_reject_only_values_above_r15() {
for r in 0..=15u16 {
accepted(|a| {
a.bx(r);
});
accepted(|a| {
a.mov_reg(r, 0);
});
accepted(|a| {
a.mov_reg(0, r);
});
if r != 15 {
accepted(|a| {
a.blx(r);
});
}
}
assert!(rejected(|a| {
a.bx(16);
})
.contains("R0-R15"));
assert!(rejected(|a| {
a.blx(16);
})
.contains("R0-R15"));
assert!(rejected(|a| {
a.mov_reg(16, 0);
})
.contains("R0-R15"));
assert!(rejected(|a| {
a.mov_reg(0, 16);
})
.contains("R0-R15"));
assert!(rejected(|a| {
a.blx(15);
})
.contains("UNPREDICTABLE"));
}
#[test]
fn binding_a_label_that_was_never_reserved_is_an_error_not_a_panic() {
let e = rejected(|a| {
a.bind(7);
a.movs_imm(0, 1);
});
assert!(e.contains("never reserved"), "{e}");
}
#[test]
fn the_first_bad_operand_is_the_one_reported() {
let e = rejected(|a| {
a.movs_imm(0, 1);
a.push(0x4000);
a.bx(16);
});
assert!(e.starts_with("push"), "{e}");
}
#[test]
fn a_rejected_operand_never_reaches_the_output() {
let mut a = Asm::new();
a.movs_imm(0, 1);
a.ldrb_imm(0, 0, 99); assert!(a.finish().is_err());
}
#[test]
fn raw16_stays_raw() {
assert_eq!(
accepted_hw(|a| {
a.raw16(0xF400);
}),
0xF400u16.to_le_bytes()
);
}
fn round_trip(build: impl FnOnce(&mut Asm)) -> String {
let mut a = Asm::new();
build(&mut a);
let bytes = a.finish().expect("should assemble");
crate::isa::decode_at_with(&bytes, 0, 0, isa::Target::Union)
.expect("emitted bytes should decode")
.to_string()
}
#[test]
fn every_emitter_assembles_to_the_instruction_its_name_promises() {
type Case = (fn(&mut Asm), &'static str);
let cases: Vec<Case> = vec![
(
|a| {
a.ldrb_imm(1, 2, 5);
},
"ldrb r1, [r2, #5]",
),
(
|a| {
a.ldr_imm(1, 2, 8);
},
"ldr r1, [r2, #8]",
),
(
|a| {
a.strh_imm(1, 2, 6);
},
"strh r1, [r2, #6]",
),
(
|a| {
a.str_imm(1, 2, 8);
},
"str r1, [r2, #8]",
),
(
|a| {
a.bics(1, 2);
},
"bics r1, r2",
),
(
|a| {
a.orrs(1, 2);
},
"orrs r1, r2",
),
(
|a| {
a.strb_imm(1, 2, 5);
},
"strb r1, [r2, #5]",
),
(
|a| {
a.cmp_imm(1, 7);
},
"cmp r1, #7",
),
(
|a| {
a.cmp_reg(1, 2);
},
"cmp r1, r2",
),
(
|a| {
a.movs_imm(1, 7);
},
"movs r1, #7",
),
(
|a| {
a.push(0x105);
},
"push {r0, r2, lr}",
),
(
|a| {
a.pop(0x105);
},
"pop {r0, r2, pc}",
),
(
|a| {
a.blx(3);
},
"blx r3",
),
(
|a| {
a.bx(3);
},
"bx r3",
),
(
|a| {
a.ldrb_reg(1, 2, 3);
},
"ldrb r1, [r2, r3]",
),
(
|a| {
a.adds_imm(1, 7);
},
"adds r1, #7",
),
(
|a| {
a.subs_imm(1, 7);
},
"subs r1, #7",
),
(
|a| {
a.lsls_imm(1, 2, 3);
},
"lsls r1, r2, #3",
),
(
|a| {
a.lsrs_imm(1, 2, 3);
},
"lsrs r1, r2, #3",
),
(
|a| {
a.adds_reg(1, 2, 3);
},
"adds r1, r2, r3",
),
(
|a| {
a.mov_reg(9, 3);
},
"mov r9, r3",
),
(
|a| {
a.movs_reg(1, 2);
},
"movs r1, r2",
),
];
for (build, want) in cases {
assert_eq!(round_trip(build), want);
}
}
#[test]
fn the_register_field_of_every_emitter_that_has_one_is_actually_read() {
for r in 0..8u16 {
assert_eq!(
round_trip(|a| {
a.ldr_lit(r, 0xDEAD_BEEF);
}),
format!("ldr r{r}, [pc, #0], 0x4")
);
assert_eq!(
round_trip(|a| {
a.cmp_imm(r, 7);
}),
format!("cmp r{r}, #7")
);
assert_eq!(
round_trip(|a| {
a.movs_imm(r, 7);
}),
format!("movs r{r}, #7")
);
assert_eq!(
round_trip(|a| {
a.adds_imm(r, 7);
}),
format!("adds r{r}, #7")
);
assert_eq!(
round_trip(|a| {
a.subs_imm(r, 7);
}),
format!("subs r{r}, #7")
);
assert_eq!(
round_trip(|a| {
a.bx(r);
}),
format!("bx r{r}")
);
assert_eq!(
round_trip(|a| {
a.movs_reg(r, 7 - r);
}),
format!("movs r{r}, r{}", 7 - r)
);
}
for r in 0..16u16 {
let name = match r {
13 => "sp".to_string(),
14 => "lr".to_string(),
15 => "pc".to_string(),
n => format!("r{n}"),
};
assert_eq!(
round_trip(|a| {
a.mov_reg(r, 3);
}),
format!("mov {name}, r3")
);
}
}
#[test]
fn the_literal_pool_and_data_blobs_land_where_the_instruction_points() {
let mut a = Asm::new();
a.ldr_lit(3, 0xDEAD_BEEF);
let bytes = a.finish().unwrap();
assert_eq!(bytes, vec![0x00, 0x4B, 0x00, 0x00, 0xEF, 0xBE, 0xAD, 0xDE]);
assert_eq!(
crate::isa::decode_at_with(&bytes, 0, 0, isa::Target::Union)
.unwrap()
.to_string(),
"ldr r3, [pc, #0], 0x4"
);
let mut a = Asm::new();
a.ldr_lit(0, 0x1111_2222);
a.ldr_lit(1, 0x1111_2222);
let bytes = a.finish().unwrap();
assert_eq!(&bytes[4..], &[0x22, 0x22, 0x11, 0x11], "one word, not two");
let mut a = Asm::new();
let blob = a.data_blob(vec![1, 2, 3, 4]);
a.adr(5, blob);
let bytes = a.finish().unwrap();
assert_eq!(bytes, vec![0x00, 0xA5, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04]);
assert_eq!(
crate::isa::decode_at_with(&bytes, 0, 0, isa::Target::Union)
.unwrap()
.to_string(),
"adr r5, 0x4"
);
}
#[test]
fn a_bound_label_resolves_to_the_offset_it_was_bound_at() {
let mut a = Asm::new();
let l = a.label();
a.beq(l);
a.movs_imm(0, 1);
a.bind(l);
a.bx(14);
let bytes = a.finish().unwrap();
assert_eq!(bytes, vec![0x00, 0xD0, 0x01, 0x20, 0x70, 0x47, 0x00, 0x00]);
assert_eq!(
crate::isa::decode_at_with(&bytes, 0, 0, isa::Target::Union)
.unwrap()
.to_string(),
"beq 0x4"
);
assert_eq!(
crate::isa::decode_at_with(&bytes, 4, 4, isa::Target::Union)
.unwrap()
.to_string(),
"bx lr"
);
}
#[test]
fn masked_search_matches_dont_care_bits_and_only_on_halfword_boundaries() {
let any_bl = [(0xF000u16, 0xF800u16), (0xD000u16, 0xD000u16)];
let image = [0x01, 0x20, 0xFF, 0xF7, 0xFE, 0xFF, 0x02, 0x21];
assert_eq!(find(&image, Needle::Masked(&any_bl), 0), Some(2));
assert_eq!(find(&image, Needle::Masked(&any_bl), 4), None);
let exact = [(0x2001u16, 0xFFFFu16)];
assert_eq!(find(&image, Needle::Masked(&exact), 0), Some(0));
assert_eq!(find(&image, Needle::Masked(&[(0x2002, 0xFFFF)]), 0), None);
let straddle = [(0xFEF7u16, 0xFFFFu16)];
assert_eq!(
image[3] as u16 | ((image[4] as u16) << 8),
0xFEF7,
"the straddling value really is present at offset 3"
);
assert_eq!(find(&image, Needle::Masked(&straddle), 0), None);
assert_eq!(find(&image, Needle::Masked(&any_bl), 1), Some(2));
assert_eq!(find(&image, Needle::Masked(&any_bl), 3), None);
}
#[test]
fn an_empty_masked_pattern_matches_nothing_rather_than_everything() {
let image = [0x01, 0x20, 0x70, 0x47];
assert_eq!(find(&image, Needle::Masked(&[]), 0), None);
let long = [(0u16, 0u16); 8];
assert_eq!(find(&image, Needle::Masked(&long), 0), None);
}
#[test]
fn find_one_refuses_to_choose_between_ambiguous_matches() {
let image = [0x01, 0x20, 0x70, 0x47, 0x01, 0x20, 0x70, 0x47];
assert_eq!(
find_one(&image, Needle::Bytes(&[0x01, 0x20])),
Err(FindError::Ambiguous { count: 2, first: 0 })
);
assert_eq!(
find_one(&image, Needle::Bytes(&[0x20, 0x70, 0x47, 0x01])),
Ok(1)
);
assert_eq!(
find_one(&image, Needle::Bytes(&[0xDE, 0xAD])),
Err(FindError::NotFound)
);
let overlap = [0xAAu8, 0xAA, 0xAA, 0xAA];
assert_eq!(
find_one(&overlap, Needle::Bytes(&[0xAA, 0xAA])),
Err(FindError::Ambiguous { count: 2, first: 0 })
);
assert_eq!(
find_one(&image, Needle::Word(0x4770_2001)),
Err(FindError::Ambiguous { count: 2, first: 0 })
);
assert_eq!(
find_one(&image, Needle::Masked(&[(0x2001, 0xFFFF)])),
Err(FindError::Ambiguous { count: 2, first: 0 })
);
let free = [0xFFu8; 8];
assert_eq!(
find_one(&free, Needle::FreeRun { len: 4, align: 4 }),
Err(FindError::Ambiguous { count: 2, first: 0 })
);
}
#[test]
fn find_error_says_which_failure_it_was() {
assert_eq!(FindError::NotFound.to_string(), "no match");
assert_eq!(
FindError::Ambiguous {
count: 3,
first: 0x120
}
.to_string(),
"3 matches, first at 0x120"
);
fn as_err(e: FindError) -> Box<dyn std::error::Error> {
Box::new(e)
}
assert!(as_err(FindError::NotFound).to_string().contains("no match"));
}
fn region(r: core::ops::Range<usize>) -> [core::ops::Range<usize>; 1] {
[r]
}
fn two_holes() -> Vec<u8> {
let mut v = vec![0x00; 4];
v.extend(std::iter::repeat(0xFF).take(8));
v.extend(std::iter::repeat(0x00).take(4));
v.extend(std::iter::repeat(0xFF).take(16));
v
}
#[test]
fn free_space_search_honours_the_regions_it_was_given() {
let image = two_holes();
let all = region(0..image.len());
assert_eq!(find_free_space_in(&image, 4, 4, &all, Fit::First), Some(4));
assert_eq!(
find_free_space_in(&image, 4, 4, &all, Fit::Largest),
Some(16)
);
assert_eq!(
find_free_space_in(&image, 4, 4, ®ion(0..12), Fit::Largest),
Some(4)
);
assert_eq!(
find_free_space_in(&image, 4, 4, ®ion(0..12), Fit::First),
Some(4)
);
assert_eq!(
find_free_space_in(&image, 4, 4, ®ion(0..4), Fit::First),
None
);
assert_eq!(find_free_space_in(&image, 4, 4, &[], Fit::First), None);
assert_eq!(find_free_space_in(&image, 4, 4, &[], Fit::Largest), None);
assert_eq!(
find_free_space_in(&image, 4, 4, &[16..32, 0..12], Fit::Largest),
Some(16)
);
assert_eq!(
find_free_space_in(&image, 4, 4, ®ion(0..usize::MAX), Fit::First),
Some(4)
);
assert_eq!(
find_free_space_in(&image, 4, 4, ®ion(100..200), Fit::First),
None
);
assert_eq!(find_free_space_in(&image, 32, 4, &all, Fit::Largest), None);
assert_eq!(find_free_space_in(&image, 32, 4, &all, Fit::First), None);
}
#[test]
fn free_space_alignment_is_applied_inside_the_run_not_to_its_start() {
let mut image = vec![0x00; 3];
image.extend(std::iter::repeat(0xFF).take(9)); let all = region(0..image.len());
assert_eq!(find_free_space_in(&image, 8, 4, &all, Fit::First), Some(4));
assert_eq!(find_free_space_in(&image, 9, 4, &all, Fit::First), None);
assert_eq!(find_free_space_in(&image, 9, 1, &all, Fit::First), Some(3));
}
#[test]
#[should_panic(expected = "alignment must be at least 1 byte")]
fn free_space_in_rejects_a_zero_alignment() {
let image = two_holes();
let _ = find_free_space_in(&image, 4, 0, ®ion(0..image.len()), Fit::First);
}
#[test]
fn classify_branch_reports_the_width_that_decides_whether_a_patch_fits() {
let narrow = [0xFE, 0xE7];
assert_eq!(
classify_branch(&narrow, 0),
BranchAt::Direct {
kind: None,
width: 2,
target: 0
}
);
let bl = [0xFF, 0xF7, 0xFE, 0xFF];
assert!(matches!(
classify_branch(&bl, 0),
BranchAt::Direct {
kind: Some(BranchKind::Bl),
width: 4,
..
}
));
let bw = encode_b_wide(0, 0x100).expect("b.w +0x100");
assert!(matches!(
classify_branch(&bw, 0),
BranchAt::Direct {
kind: Some(BranchKind::BWide),
width: 4,
target: 0x100
}
));
assert_eq!(
classify_branch(&[0x70, 0x47], 0),
BranchAt::Indirect { width: 2 }
);
assert_eq!(classify_branch(&[0x01, 0x20], 0), BranchAt::NotABranch);
assert_eq!(classify_branch(&[0x00], 0), BranchAt::NotABranch);
assert_eq!(classify_branch(&[], 0), BranchAt::NotABranch);
assert!(matches!(
classify_branch(&[0x08, 0xB1], 0),
BranchAt::Direct {
kind: None,
width: 2,
..
}
));
}
#[test]
fn classify_branch_does_not_mistake_a_literal_pool_address_for_a_destination() {
let v = crate::analysis::veneer(0, 0x1234).expect("veneer at 0");
assert_eq!(classify_branch(&v, 0), BranchAt::Indirect { width: 4 });
}
#[test]
fn classify_branch_agrees_with_verify_branch_wherever_both_have_an_opinion() {
for target in [0x100u32, 0x1000, 0x10_0000] {
for kind in [BranchKind::Bl, BranchKind::BWide] {
let bytes = kind.encode(0, target).expect("encodable");
assert!(verify_branch(&bytes, 0, kind, target).is_ok());
match classify_branch(&bytes, 0) {
BranchAt::Direct {
kind: k,
width,
target: t,
} => {
assert_eq!(k, Some(kind));
assert_eq!(width, 4);
assert_eq!(t, target);
}
other => panic!("{kind:?} to {target:#x} classified as {other:?}"),
}
}
}
}
fn two_equal_holes() -> Vec<u8> {
let mut v = vec![0x00; 4];
v.extend(std::iter::repeat(0xFF).take(8));
v.extend(std::iter::repeat(0x00).take(4));
v.extend(std::iter::repeat(0xFF).take(8));
v
}
#[test]
fn free_space_placement_does_not_depend_on_the_order_the_regions_were_listed() {
let image = two_equal_holes();
let a = 0..12;
let b = 16..24;
for fit in [Fit::First, Fit::Largest] {
let forwards = find_free_space_in(&image, 4, 4, &[a.clone(), b.clone()], fit);
let backwards = find_free_space_in(&image, 4, 4, &[b.clone(), a.clone()], fit);
assert_eq!(forwards, backwards, "{fit:?} depends on region order");
assert_eq!(
forwards,
Some(4),
"{fit:?} should resolve to the lower hole"
);
}
}
#[test]
fn largest_fit_still_prefers_the_bigger_hole_and_breaks_ties_downward() {
let image = two_holes();
let small = 0..12;
let big = 16..32;
for order in [[small.clone(), big.clone()], [big.clone(), small.clone()]] {
assert_eq!(
find_free_space_in(&image, 4, 4, &order, Fit::Largest),
Some(16)
);
assert_eq!(
find_free_space_in(&image, 4, 4, &order, Fit::First),
Some(4)
);
}
}
#[test]
fn scoping_a_search_is_what_makes_an_ambiguous_signature_unique() {
let image = [0x01, 0x20, 0x70, 0x47, 0x01, 0x20, 0x70, 0x47];
let movs = Needle::Bytes(&[0x01, 0x20]);
assert_eq!(
find_one(&image, movs),
Err(FindError::Ambiguous { count: 2, first: 0 })
);
assert_eq!(find_one_in(&image, movs, 0..4), Ok(0));
assert_eq!(find_one_in(&image, movs, 4..8), Ok(4));
assert_eq!(find_one_in(&image, movs, 2..4), Err(FindError::NotFound));
assert_eq!(find_in(&image, movs, 4..5), None);
assert_eq!(find_in(&image, movs, 4..6), Some(4));
let inverted = core::ops::Range { start: 6, end: 2 };
assert_eq!(find_in(&image, movs, 4..4), None);
assert_eq!(find_in(&image, movs, inverted), None);
assert_eq!(find_in(&image, movs, 4..usize::MAX), Some(4));
assert_eq!(find_in(&image, movs, 100..200), None);
}
#[test]
fn a_window_does_not_move_what_counts_as_an_instruction_boundary() {
let image = [0x01, 0x20, 0xFF, 0xF7, 0xFE, 0xFF, 0x02, 0x21];
let straddling = Needle::Masked(&[(0xFEF7, 0xFFFF)]); assert_eq!(find_in(&image, straddling, 0..8), None);
assert_eq!(
find_in(&image, straddling, 3..8),
None,
"an odd window start is not an origin"
);
let mut free = vec![0x00, 0x00];
free.extend(std::iter::repeat(0xFF).take(8)); assert_eq!(
find_in(&free, Needle::FreeRun { len: 4, align: 4 }, 2..10),
Some(4)
);
}
#[test]
fn the_allocator_packs_and_never_hands_back_the_same_offset_twice() {
let mut image = vec![0u8; 16];
image.extend(std::iter::repeat(0xFF).take(64));
let mut space = FreeSpace::new(&image, ®ion(0..image.len()), 4, Straddle::Clip);
assert_eq!(space.remaining(), 64);
let a = space.alloc(12).unwrap();
let b = space.alloc(8).unwrap();
let c = space.alloc(4).unwrap();
assert_eq!((a, b, c), (16, 28, 36));
for (at, len) in [(a, 12), (b, 8)] {
assert_eq!(at % 4, 0);
assert!(at + len <= b.max(c));
}
assert_eq!(space.remaining(), 80 - 40);
assert!(image[16..80].iter().all(|&b| b == 0xFF));
let image2 = two_holes();
let mut many = FreeSpace::new(&image2, &[0..12, 16..32], 4, Straddle::Clip);
assert_eq!(many.remaining(), 8 + 16);
assert_eq!(many.alloc(8), Some(4)); assert_eq!(many.remaining(), 16);
assert_eq!(many.alloc(8), Some(16)); assert_eq!(many.remaining(), 8);
assert_eq!(many.alloc(usize::MAX), None);
assert_eq!(many.remaining(), 8, "a refused allocation consumes nothing");
let mut small = FreeSpace::new(&image, ®ion(0..image.len()), 4, Straddle::Clip);
assert_eq!(small.alloc(64), Some(16));
assert_eq!(small.alloc(1), None);
assert_eq!(small.remaining(), 0);
}
#[test]
fn the_allocator_steps_across_runs_and_ignores_region_order() {
let image = two_holes(); let holes = [0..12, 16..32];
let reversed = [16..32, 0..12];
let seq = |regions: &[core::ops::Range<usize>]| {
let mut sp = FreeSpace::new(&image, regions, 4, Straddle::Clip);
(0..4).map(|_| sp.alloc(8)).collect::<Vec<_>>()
};
assert_eq!(seq(&holes), vec![Some(4), Some(16), Some(24), None]);
assert_eq!(seq(&holes), seq(&reversed), "region order must not matter");
let overlapping = [0..20, 8..32];
assert_eq!(seq(&overlapping), vec![Some(4), Some(16), Some(24), None]);
}
#[test]
fn straddle_reject_drops_a_run_that_continues_past_the_region() {
let mut image = vec![0x00; 4];
image.extend(std::iter::repeat(0xFF).take(24));
image.extend(std::iter::repeat(0x00).take(4));
let clip = FreeSpace::new(&image, ®ion(4..16), 4, Straddle::Clip);
assert_eq!(
clip.runs(),
region(4..16),
"clipping offers the covered part"
);
let reject = FreeSpace::new(&image, ®ion(4..16), 4, Straddle::Reject);
assert!(
reject.runs().is_empty(),
"the run leaves the region, so it is not offered"
);
for straddle in [Straddle::Clip, Straddle::Reject] {
let whole = FreeSpace::new(&image, ®ion(0..32), 4, straddle);
assert_eq!(whole.runs(), region(4..28), "{straddle:?}");
}
let front = FreeSpace::new(&image, ®ion(8..32), 4, Straddle::Reject);
assert!(front.runs().is_empty(), "the run starts before the region");
assert_eq!(
FreeSpace::new(&image, ®ion(8..32), 4, Straddle::Clip).runs(),
region(8..28)
);
}
#[test]
fn free_space_exposes_what_it_was_built_from() {
let image = two_holes();
let sp = FreeSpace::new(&image, ®ion(0..image.len()), 4, Straddle::Clip);
assert_eq!(sp.image(), &image[..]);
assert_eq!(sp.runs(), [4..12, 16..32]);
let mut none = FreeSpace::new(&image, &[], 4, Straddle::Clip);
assert!(none.runs().is_empty());
assert_eq!(none.alloc(1), None);
assert_eq!(none.remaining(), 0);
let backwards = core::ops::Range { start: 12, end: 4 };
let inverted = FreeSpace::new(&image, &[backwards], 4, Straddle::Clip);
assert!(inverted.runs().is_empty());
}
#[test]
#[should_panic(expected = "alignment must be at least 1 byte")]
fn the_allocator_rejects_a_zero_alignment() {
let image = two_holes();
let _ = FreeSpace::new(&image, ®ion(0..image.len()), 0, Straddle::Clip);
}
#[test]
fn can_install_refuses_a_site_where_four_bytes_would_cut_an_instruction() {
assert!(can_install(&[0x01, 0x20, 0x02, 0x21], 0, BranchKind::Bl).is_ok());
assert!(can_install(&[0xFF, 0xF7, 0xFE, 0xFF], 0, BranchKind::BWide).is_ok());
let split = [0x01, 0x20, 0xFF, 0xF7, 0xFE, 0xFF];
assert_eq!(
can_install(&split, 0, BranchKind::Bl),
Err(InstallHazard::SplitsInstruction {
at: 2,
displaced: 6
})
);
assert_eq!(classify_branch(&split, 0), BranchAt::NotABranch);
assert_eq!(
can_install(&[0x01, 0x20], 0, BranchKind::Bl),
Err(InstallHazard::OutOfBounds {
site: 0,
image_len: 2
})
);
assert!(matches!(
can_install(&[0x01, 0x20, 0x02, 0x21], usize::MAX, BranchKind::Bl),
Err(InstallHazard::OutOfBounds { .. })
));
let bad = [0x00, 0x45, 0x00, 0x45];
assert!(
isa::decode_at(&bad, 0).is_none(),
"the premise of this test is that these bytes do not decode"
);
assert_eq!(
can_install(&bad, 0, BranchKind::Bl),
Err(InstallHazard::NotAnInstruction { site: 0 })
);
let late = [0x01, 0x20, 0x00, 0x45];
assert_eq!(
can_install(&late, 0, BranchKind::Bl),
Err(InstallHazard::NotAnInstruction { site: 2 })
);
}
#[test]
fn install_hazard_says_what_went_wrong() {
assert!(InstallHazard::OutOfBounds {
site: 0x10,
image_len: 0x12
}
.to_string()
.contains("runs past the end"));
assert!(InstallHazard::NotAnInstruction { site: 0x10 }
.to_string()
.contains("nothing decodes"));
assert!(InstallHazard::SplitsInstruction {
at: 2,
displaced: 6
}
.to_string()
.contains("in half"));
fn as_err(e: InstallHazard) -> Box<dyn std::error::Error> {
Box::new(e)
}
assert!(!as_err(InstallHazard::NotAnInstruction { site: 0 })
.to_string()
.is_empty());
}
#[test]
fn can_install_agrees_with_what_detour_would_displace() {
let mut image = vec![0u8; 0x2000];
for b in image[0x1000..].iter_mut() {
*b = 0xFF;
}
image[0x100..0x106].copy_from_slice(&[0x01, 0x20, 0xFF, 0xF7, 0xFE, 0xFF]);
assert!(matches!(
can_install(&image, 0x100, BranchKind::Bl),
Err(InstallHazard::SplitsInstruction { displaced: 6, .. })
));
let d = crate::detour::tramp(&mut image, 0x100, 0x80).unwrap();
assert_eq!(
d.displaced, 6,
"detour relocates exactly what can_install refused to cut"
);
}
fn fnv1a(bytes: &[u8]) -> u64 {
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
for &b in bytes {
h ^= b as u64;
h = h.wrapping_mul(0x0000_0100_0000_01b3);
}
h
}
fn encoding_digest() -> (u64, usize) {
let mut buf: Vec<u8> = Vec::new();
let mut decoded = 0usize;
for hw in 0x0000u32..=0xFFFF {
let hw = hw as u16;
if isa::insn_len(hw) != 2 {
continue;
}
let insn = match isa::decode_halfwords(hw, 0, 0, isa::Target::Union) {
Some(i) => i,
None => continue,
};
decoded += 1;
buf.extend_from_slice(&hw.to_le_bytes());
match isa::encode(&insn) {
Some((a, b)) => {
buf.push(1);
buf.extend_from_slice(&a.to_le_bytes());
buf.extend_from_slice(&b.to_le_bytes());
}
None => buf.push(0),
}
}
(fnv1a(&buf), decoded)
}
#[test]
fn the_emitted_encoding_corpus_has_not_moved() {
const DIGEST: u64 = 0x0e06_fda2_5d6b_89e8;
const DECODED: usize = 58_233;
let (digest, decoded) = encoding_digest();
assert_eq!(
(digest, decoded),
(DIGEST, DECODED),
"\nEmitted bytes changed.\n\
\x20 decoded halfwords: {decoded} (pinned {DECODED})\n\
\x20 digest: {digest:#018x} (pinned {DIGEST:#018x})\n\n\
If that was intended, update both constants and add an entry to\n\
`### Emitted bytes changed` in CHANGELOG.md naming what moved.\n\
Consumers with golden tests or signed images read that section.\n"
);
}
#[test]
fn a_masked_pattern_compares_each_halfword_at_its_own_offset() {
let image = [0x01, 0x20, 0x70, 0x47]; let in_order = [(0x2001u16, 0xFFFFu16), (0x4770u16, 0xFFFFu16)];
let reversed = [(0x4770u16, 0xFFFFu16), (0x2001u16, 0xFFFFu16)];
assert_eq!(find(&image, Needle::Masked(&in_order), 0), Some(0));
assert_eq!(
find(&image, Needle::Masked(&reversed), 0),
None,
"the order of the halfwords in the pattern has to matter"
);
}
#[test]
fn a_masked_pattern_reaches_the_last_halfword_and_no_further() {
let image = [0x01, 0x20, 0x70, 0x47];
let bx_lr = [(0x4770u16, 0xFFFFu16)];
assert_eq!(find(&image, Needle::Masked(&bx_lr), 0), Some(2));
let three = [
(0x2001u16, 0xFFFFu16),
(0x4770u16, 0xFFFFu16),
(0x0000u16, 0x0000u16),
];
assert_eq!(
find(&image, Needle::Masked(&three), 0),
None,
"six bytes of pattern cannot match in a four-byte image"
);
let longer = [0x01, 0x20, 0x70, 0x47, 0xAA, 0xBB];
assert_eq!(find(&longer, Needle::Masked(&three), 0), Some(0));
}
fn ldr_at_distance(pad: usize) -> Result<Vec<u8>, AsmError> {
let mut a = Asm::new();
a.ldr_lit(0, 0xDEAD_BEEF);
for _ in 0..pad {
a.raw16(0x46C0); }
a.finish()
}
#[test]
fn the_ldr_literal_displacement_is_bounded_exactly_at_the_field() {
let ok = ldr_at_distance(511).expect("1020 bytes away is the last reachable word");
assert_eq!(
u16::from_le_bytes([ok[0], ok[1]]),
0x48FF,
"imm8 should be 0xff"
);
assert_eq!(&ok[1024..1028], &0xDEAD_BEEFu32.to_le_bytes());
let err = ldr_at_distance(512).expect_err("one word further cannot be encoded");
assert!(
err.to_string().contains("ldr literal out of range"),
"{err}"
);
assert!(
err.to_string().contains("256"),
"the message should name the imm8: {err}"
);
}
#[test]
fn the_adr_displacement_is_bounded_too() {
let build = |pad: usize| -> Result<Vec<u8>, AsmError> {
let mut a = Asm::new();
let blob = a.data_blob(vec![0xAA; 4]);
a.adr(0, blob);
for _ in 0..pad {
a.raw16(0x46C0);
}
a.finish()
};
let ok = build(500).expect("a near blob is reachable");
assert_eq!(ok[1] & 0xF8, 0xA0, "should still be an adr");
let err = build(520).expect_err("a blob past the field cannot be addressed");
assert!(err.to_string().contains("adr target out of range"), "{err}");
let mut a = Asm::new();
let blob = a.data_blob(vec![0x11, 0x22, 0x33, 0x44]);
a.adr(3, blob);
for _ in 0..5 {
a.raw16(0x46C0);
}
let bytes = a.finish().unwrap();
assert_eq!(
&bytes[12..16],
&[0x11, 0x22, 0x33, 0x44],
"blob lands at 12"
);
assert_eq!(
u16::from_le_bytes([bytes[0], bytes[1]]),
0xA302,
"adr r3, #8 — rd in bits 10:8, (target - Align(pc,4)) / 4 in the imm8"
);
}
#[test]
fn a_literal_pool_word_is_shared_and_the_displacement_follows_the_layout() {
let mut a = Asm::new();
a.ldr_lit(0, 0x1111_2222);
a.raw16(0x46C0);
a.ldr_lit(1, 0x1111_2222);
let bytes = a.finish().unwrap();
let first = u16::from_le_bytes([bytes[0], bytes[1]]);
let second = u16::from_le_bytes([bytes[4], bytes[5]]);
assert_eq!(&bytes[8..12], &0x1111_2222u32.to_le_bytes());
let ldr_lit = |rt: u16, imm8: u16| 0x4800 | (rt << 8) | imm8;
assert_eq!(first, ldr_lit(0, 1), "first ldr: rt=r0, imm8=1");
assert_eq!(second, ldr_lit(1, 0), "second ldr: rt=r1, imm8=0");
}
#[test]
fn the_masked_needle_step_is_two_bytes_per_halfword() {
let image = [0xAAu8, 0xBB].repeat(6);
assert_eq!(image.len(), 12);
assert_eq!(
find_one(&image, Needle::Masked(&[(0xBBAA, 0xFFFF)])),
Err(FindError::Ambiguous { count: 6, first: 0 })
);
let three = [(0xBBAAu16, 0xFFFFu16); 3];
assert_eq!(
find_one(&image, Needle::Masked(&three)),
Err(FindError::Ambiguous { count: 2, first: 0 })
);
}
#[test]
fn stack_and_memory_emitters_roundtrip_decoded_operands() {
use crate::isa::{decode_at, Operand, Reg};
let mut a = Asm::new();
a.str_sp(3, 4).ldrh_reg(0, 0, 6).add_sp(4).ands(0, 2);
let bytes = a.finish().unwrap();
for (at, mnemonic) in [(0, "str"), (2, "ldrh"), (4, "add"), (6, "and")] {
let ins = decode_at(&bytes, at).unwrap();
assert_eq!(ins.mnemonic, mnemonic);
}
let store = decode_at(&bytes, 0).unwrap();
assert_eq!(store.operands.get(0), Some(Operand::Reg(Reg(3))));
assert!(
matches!(store.operands.get(1),Some(Operand::Mem(m)) if m.base==Reg::SP && m.offset==4)
);
for (register, offset) in [(8, 4), (3, 2), (3, 1024)] {
let mut a = Asm::new();
a.str_sp(register, offset);
assert!(a.finish().is_err());
}
let mut a = Asm::new();
a.add_sp(2);
assert!(a.finish().is_err());
let mut a = Asm::new();
a.ldrh_reg(0, 0, 8);
assert!(a.finish().is_err());
}
#[test]
fn native_replay_refuses_address_and_control_flow_dependencies() {
let mut original = Asm::new();
original.ldrb_imm(0, 4, 0).lsrs_imm(0, 0, 4).cmp_imm(0, 12);
let bytes = original.finish().unwrap();
let mut replay = Asm::new();
replay.replay(&bytes);
assert_eq!(replay.finish().unwrap(), bytes);
for halfwords in [
&[0x4800u16][..],
&[0xe000][..],
&[0xbf08][..],
&[0xf000][..],
&[0xbd10][..],
] {
let bytes = halfwords
.iter()
.flat_map(|op| op.to_le_bytes())
.collect::<Vec<_>>();
let mut replay = Asm::new();
replay.replay(&bytes);
assert!(replay.finish().is_err());
}
}