pub mod insn;
pub use insn::{
AddrMode, FpReg, Insn, Mem, Operand, Operands, Reg, Shift, ShiftAmount, ShiftKind, Width,
MAX_OPERANDS,
};
use crate::Cond;
mod cmse;
pub(crate) mod legality;
mod t16_branch;
mod t16_dataproc;
mod t16_loadstore;
mod t16_misc;
mod t16_shift;
mod t16_special;
mod t32_branch_misc;
mod t32_coproc;
mod t32_dp_modimm;
mod t32_dp_plainimm;
mod t32_dp_reg;
mod t32_dp_shiftreg;
mod t32_dual_excl;
mod t32_ldm_stm;
mod t32_load;
mod t32_multiply;
mod t32_simd;
mod t32_store;
mod thumbee;
pub fn insn_len(hw1: u16) -> usize {
match hw1 >> 11 {
0b11101..=0b11111 => 4,
_ => 2,
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
#[non_exhaustive]
pub enum Target {
Union,
V7M,
V7EM,
V7A,
V7R,
V7AR,
V8M,
ThumbEE,
Thumb1,
}
impl Default for Target {
fn default() -> Self {
Target::Union
}
}
impl Target {
fn thumbee(self) -> bool {
matches!(self, Target::ThumbEE)
}
fn cmse(self) -> bool {
matches!(self, Target::V8M)
}
pub fn supports_thumb2(self) -> bool {
!matches!(self, Target::Thumb1)
}
}
pub fn decode_at(image: &[u8], at: usize) -> Option<Insn> {
decode_at_with(image, at, at as u32, Target::Union)
}
pub fn decode_at_with(image: &[u8], at: usize, addr: u32, target: Target) -> Option<Insn> {
let hw1 = read_hw(image, at)?;
let len = insn_len(hw1);
let hw2 = if len == 4 { read_hw(image, at + 2)? } else { 0 };
decode_halfwords(hw1, hw2, addr, target)
}
pub fn decode_halfwords(hw1: u16, hw2: u16, addr: u32, target: Target) -> Option<Insn> {
if target.cmse() && cmse::owns(hw1, hw2) {
return cmse::decode(hw1, hw2, addr);
}
let thumbee = target.thumbee();
if insn_len(hw1) == 2 {
if thumbee && thumbee::owns(hw1) {
return thumbee::decode(hw1, hw2, addr);
}
return match hw1 >> 10 {
0b000000..=0b001111 => t16_shift::decode(hw1, hw2, addr),
0b010000 => t16_dataproc::decode(hw1, hw2, addr),
0b010001 => t16_special::decode(hw1, hw2, addr),
0b010010..=0b100111 => t16_loadstore::decode(hw1, hw2, addr),
0b101000..=0b101011 => t16_loadstore::decode(hw1, hw2, addr),
0b101100..=0b101111 => t16_misc::decode(hw1, hw2, addr),
_ => t16_branch::decode(hw1, hw2, addr),
};
}
let op1 = (hw1 >> 11) & 0b11;
let op2 = (hw1 >> 4) & 0b111_1111;
let op = (hw2 >> 15) & 1;
match op1 {
0b01 => match op2 {
o if o & 0b110_0100 == 0b000_0000 => t32_ldm_stm::decode(hw1, hw2, addr),
o if o & 0b110_0100 == 0b000_0100 => t32_dual_excl::decode(hw1, hw2, addr),
o if o & 0b110_0000 == 0b010_0000 => t32_dp_shiftreg::decode(hw1, hw2, addr),
_ => t32_coproc::decode(hw1, hw2, addr).or_else(|| t32_simd::decode(hw1, hw2, addr)),
},
0b10 => {
if op == 1 {
t32_branch_misc::decode(hw1, hw2, addr)
} else if op2 & 0b010_0000 == 0 {
t32_dp_modimm::decode(hw1, hw2, addr)
} else {
t32_dp_plainimm::decode(hw1, hw2, addr)
}
}
_ => match op2 {
o if o & 0b111_0001 == 0b000_0000 => t32_store::decode(hw1, hw2, addr),
o if o & 0b111_0001 == 0b001_0000 => t32_simd::decode(hw1, hw2, addr),
o if o & 0b110_0111 == 0b000_0001 => t32_load::decode(hw1, hw2, addr),
o if o & 0b110_0111 == 0b000_0011 => t32_load::decode(hw1, hw2, addr),
o if o & 0b110_0111 == 0b000_0101 => t32_load::decode(hw1, hw2, addr),
o if o & 0b110_0111 == 0b000_0111 => None, o if o & 0b111_0000 == 0b010_0000 => t32_dp_reg::decode(hw1, hw2, addr),
o if o & 0b111_1000 == 0b011_0000 => t32_multiply::decode(hw1, hw2, addr),
o if o & 0b111_1000 == 0b011_1000 => t32_multiply::decode(hw1, hw2, addr),
_ => t32_coproc::decode(hw1, hw2, addr).or_else(|| t32_simd::decode(hw1, hw2, addr)),
},
}
}
fn read_hw(image: &[u8], at: usize) -> Option<u16> {
let b = image.get(at..at.checked_add(2)?)?;
Some(u16::from_le_bytes([b[0], b[1]]))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ItState {
pub cond: u8,
pub mask: u8,
}
impl ItState {
pub const INACTIVE: ItState = ItState { cond: 0, mask: 0 };
pub fn active(self) -> bool {
self.mask != 0
}
pub fn current(self) -> Option<Cond> {
if !self.active() {
return None;
}
Cond::from_bits(self.cond)
}
pub fn advance(self) -> ItState {
if self.mask & 0b0111 == 0 {
ItState::INACTIVE
} else {
ItState {
cond: (self.cond & 0b1110) | ((self.mask >> 3) & 1),
mask: (self.mask << 1) & 0xF,
}
}
}
}
#[derive(Debug, Clone)]
pub struct Decoder<'a> {
image: &'a [u8],
pos: usize,
base: u32,
it: ItState,
target: Target,
}
impl<'a> Decoder<'a> {
pub fn new(image: &'a [u8]) -> Self {
Decoder {
image,
pos: 0,
base: 0,
it: ItState::INACTIVE,
target: Target::Union,
}
}
pub fn at(image: &'a [u8], at: usize, addr: u32) -> Self {
Decoder {
image,
pos: at,
base: addr.wrapping_sub(at as u32),
it: ItState::INACTIVE,
target: Target::Union,
}
}
pub fn target(mut self, target: Target) -> Self {
self.target = target;
self
}
pub fn pos(&self) -> usize {
self.pos
}
pub fn it_state(&self) -> ItState {
self.it
}
pub fn skip(&mut self, n: usize) {
self.pos = self.pos.saturating_add(n);
}
}
impl Iterator for Decoder<'_> {
type Item = Insn;
fn next(&mut self) -> Option<Insn> {
let hw1 = read_hw(self.image, self.pos)?;
let len = insn_len(hw1);
let addr = self.base.wrapping_add(self.pos as u32);
let hw2 = if len == 4 {
read_hw(self.image, self.pos + 2)?
} else {
0
};
let mut insn = decode_halfwords(hw1, hw2, addr, self.target)?;
if insn.cond.is_none() && self.it.active() {
insn.cond = self.it.current();
if insn.width == Width::Narrow {
insn.sets_flags = false;
}
}
self.it = if insn.mnemonic.starts_with("it") {
it_state_from(hw1)
} else {
self.it.advance()
};
self.pos += len;
Some(insn)
}
}
pub fn encode(insn: &Insn) -> Option<(u16, u16)> {
if let Some((hw1, hw2)) = cmse::encode(insn) {
if faithful(insn, hw1, hw2, Target::V8M) {
return Some((hw1, hw2));
}
}
if insn.width == Width::Narrow {
if let Some(hw) = thumbee::encode(insn) {
if faithful(insn, hw, 0, Target::ThumbEE) {
return Some((hw, 0));
}
}
}
type NarrowEncoder = fn(&Insn) -> Option<u16>;
type WideEncoder = fn(&Insn) -> Option<(u16, u16)>;
const NARROW: [NarrowEncoder; 6] = [
t16_shift::encode,
t16_dataproc::encode,
t16_special::encode,
t16_loadstore::encode,
t16_misc::encode,
t16_branch::encode,
];
const WIDE: [WideEncoder; 12] = [
t32_dp_modimm::encode,
t32_dp_plainimm::encode,
t32_branch_misc::encode,
t32_ldm_stm::encode,
t32_dual_excl::encode,
t32_load::encode,
t32_store::encode,
t32_dp_shiftreg::encode,
t32_dp_reg::encode,
t32_multiply::encode,
t32_coproc::encode,
t32_simd::encode,
];
match insn.width {
Width::Narrow => NARROW
.iter()
.filter_map(|f| f(insn))
.map(|hw| (hw, 0))
.find(|&(hw1, hw2)| faithful(insn, hw1, hw2, Target::Union)),
Width::Wide => WIDE
.iter()
.filter_map(|f| f(insn))
.find(|&(hw1, hw2)| faithful(insn, hw1, hw2, Target::Union)),
}
}
fn faithful(insn: &Insn, hw1: u16, hw2: u16, target: Target) -> bool {
match decode_halfwords(hw1, hw2, insn.addr, target) {
Some(back) => {
let flags_ok = back.sets_flags == insn.sets_flags
|| (insn.cond.is_some()
&& insn.width == Width::Narrow
&& back.sets_flags
&& !insn.sets_flags);
let cond_ok = back.cond == insn.cond || back.cond.is_none();
back.mnemonic == insn.mnemonic
&& back.encoding == insn.encoding
&& back.width == insn.width
&& flags_ok
&& cond_ok
&& back.explicit_width == insn.explicit_width
&& back.operands == insn.operands
}
None => false,
}
}
pub fn encode_bytes(insn: &Insn) -> Option<Vec<u8>> {
let (hw1, hw2) = encode(insn)?;
let mut out = Vec::with_capacity(insn.len());
out.extend_from_slice(&hw1.to_le_bytes());
if insn.width == Width::Wide {
out.extend_from_slice(&hw2.to_le_bytes());
}
Some(out)
}
pub(crate) fn it_state_from(hw1: u16) -> ItState {
ItState {
cond: ((hw1 >> 4) & 0xF) as u8,
mask: (hw1 & 0xF) as u8,
}
}
pub fn disassemble(image: &[u8], at: usize, addr: u32, count: usize) -> Vec<String> {
let ceiling = image.len().saturating_sub(at) / 2;
let mut out = Vec::with_capacity(count.min(ceiling));
let mut d = Decoder::at(image, at, addr);
while out.len() < count {
let pos = d.pos();
if pos.checked_add(2).map_or(true, |end| end > image.len()) {
break;
}
match d.next() {
Some(i) => out.push(format!("{:08x}: {}", i.addr, i)),
None => {
let hw = read_hw(image, pos).unwrap_or(0);
out.push(format!("{pos:08x}: .short {hw:#06x}"));
Decoder::skip(&mut d, 2);
}
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn disassemble_at_the_top_of_memory_yields_nothing_rather_than_panicking() {
let image = vec![0u8; 0x20];
assert!(disassemble(&image, usize::MAX, 0, 4).is_empty());
assert!(disassemble(&image, usize::MAX - 1, 0, 4).is_empty());
}
#[test]
fn insn_len_follows_the_top_five_bits() {
assert_eq!(insn_len(0x4770), 2); assert_eq!(insn_len(0xB500), 2); assert_eq!(insn_len(0xE7FE), 2); assert_eq!(insn_len(0xE800), 4); assert_eq!(insn_len(0xF000), 4); assert_eq!(insn_len(0xF800), 4); }
#[test]
fn it_advance_inverts_the_condition_on_else_arms() {
let it = it_state_from(0xBF0C);
assert_eq!(
it,
ItState {
cond: 0b0000,
mask: 0b1100
}
);
assert_eq!(it.current(), Some(Cond::Eq));
let it = it.advance();
assert_eq!(it.current(), Some(Cond::Ne));
assert_eq!(it.advance(), ItState::INACTIVE);
assert_eq!(it.advance().current(), None);
}
#[test]
fn it_advance_keeps_the_condition_on_then_arms() {
let it = it_state_from(0xBF04);
assert_eq!(it.current(), Some(Cond::Eq));
let it = it.advance();
assert_eq!(it.current(), Some(Cond::Eq));
assert_eq!(it.advance(), ItState::INACTIVE);
}
#[test]
fn it_advance_handles_a_mixed_three_instruction_block() {
let it = ItState {
cond: 0b0001,
mask: 0b1010,
};
assert_eq!(it.current(), Some(Cond::Ne));
let it = it.advance();
assert_eq!(it.current(), Some(Cond::Ne));
let it = it.advance();
assert_eq!(it.current(), Some(Cond::Eq));
assert_eq!(it.advance(), ItState::INACTIVE);
}
#[test]
fn thumbee_undefined_row_is_undefined_only_in_thumbee_state() {
for hw in 0xC100..=0xC1FFu16 {
assert_eq!(
decode_halfwords(hw, 0, 0x1000, Target::ThumbEE),
None,
"{hw:#06x} is UNDEFINED in ThumbEE state (Table A9-2)"
);
let plain = decode_halfwords(hw, 0, 0x1000, Target::Union);
if hw == 0xC100 {
assert_eq!(plain, None, "empty register list is UNPREDICTABLE");
} else {
assert_eq!(
plain.map(|i| i.mnemonic),
Some("stmia"),
"{hw:#06x} is STM T1 in Thumb state"
);
}
}
assert!(decode_halfwords(0xC0FF, 0, 0x1000, Target::ThumbEE).is_some());
assert!(decode_halfwords(0xC200, 0, 0x1000, Target::ThumbEE).is_some());
}
#[test]
fn thumbee_flag_changes_exactly_the_reassigned_range() {
let image = [0x70, 0x47, 0x07, 0xC2, 0x24, 0xCC, 0x10, 0xBD];
let plain: Vec<String> = Decoder::new(&image).map(|i| i.to_string()).collect();
let ee: Vec<String> = Decoder::new(&image)
.target(crate::isa::Target::ThumbEE)
.map(|i| i.to_string())
.collect();
assert_eq!(
plain,
[
"bx lr",
"stmia r2!, {r0-r2}",
"ldmia r4!, {r2, r5}",
"pop {r4, pc}"
]
);
assert_eq!(ee, ["bx lr", "hb #7", "ldr r4, [r9, #16]", "pop {r4, pc}"]);
for (n, (a, b)) in plain.iter().zip(&ee).enumerate() {
if (1..=2).contains(&n) {
assert_ne!(a, b, "instruction {n} is in the re-assigned range");
} else {
assert_eq!(a, b, "instruction {n} is not ThumbEE's to change");
}
}
}
#[test]
fn thumbee_walk_halts_on_the_undefined_row() {
let image = [0x70, 0x47, 0xC0, 0xC1, 0x70, 0x47];
let plain: Vec<&str> = Decoder::new(&image).map(|i| i.mnemonic).collect();
assert_eq!(plain, ["bx", "stmia", "bx"]);
let mut d = Decoder::new(&image).target(crate::isa::Target::ThumbEE);
assert_eq!(d.next().map(|i| i.mnemonic), Some("bx"));
assert_eq!(d.next(), None, "0xC1C0 is UNDEFINED in ThumbEE state");
assert_eq!(d.pos(), 2);
Decoder::skip(&mut d, 2);
assert_eq!(d.next().map(|i| i.mnemonic), Some("bx"));
}
#[test]
fn advanced_simd_is_reachable_through_the_dispatcher() {
let mut decoded = 0usize;
for hw1 in (0xEF00u16..=0xEFFF).chain(0xFF00u16..=0xFFFF) {
for hw2 in [0x0110u16, 0x0842, 0x0A10, 0x0F00] {
if decode_halfwords(hw1, hw2, 0x1000, Target::Union).is_some() {
decoded += 1;
}
}
}
assert!(
decoded > 1000,
"only {decoded} Advanced SIMD encodings reachable via the dispatcher \
— the coprocessor arm has stopped chaining to t32_simd"
);
}
#[test]
fn a_truncated_instruction_at_the_end_of_an_image_is_not_decoded() {
let truncated = [0x00u8, 0xF0];
assert_eq!(insn_len(0xF000), 4);
assert_eq!(decode_at(&truncated, 0), None);
assert_eq!(decode_at_with(&truncated, 0, 0x1000, Target::Union), None);
assert_eq!(Decoder::new(&truncated).next(), None);
let whole = [0x00u8, 0xF0, 0x00, 0xF8];
assert!(decode_at(&whole, 0).is_some());
assert_eq!(decode_at(&whole, 4), None);
assert_eq!(decode_at(&whole, usize::MAX), None);
let mut d = Decoder::new(&whole);
Decoder::skip(&mut d, usize::MAX);
assert_eq!(d.pos(), usize::MAX, "skip saturates rather than wrapping");
assert_eq!(d.next(), None);
let tail = [0x70u8, 0x47, 0x00, 0xF0];
let mut d = Decoder::new(&tail);
assert_eq!(d.next().map(|i| i.mnemonic), Some("bx"));
assert_eq!(d.next(), None);
assert_eq!(d.pos(), 2);
}
#[test]
fn decoder_at_separates_the_offset_from_the_address() {
let image = [0x70u8, 0x47, 0x70, 0x47];
let mut d = Decoder::at(&image, 2, 0x8002);
assert_eq!(d.pos(), 2);
assert_eq!(d.it_state(), ItState::INACTIVE);
let insn = d.next().expect("bx lr");
assert_eq!(insn.addr, 0x8002);
assert_eq!(d.pos(), 4);
assert_eq!(d.next(), None);
let literal = [0x00u8, 0x48];
let insn = Decoder::at(&literal, 0, 0x8000)
.next()
.expect("ldr literal");
assert_eq!(insn.branch_target(), Some(0x8004));
}
#[test]
fn disassemble_renders_undefined_halfwords_as_data_and_resynchronises() {
let image = [0x70u8, 0x47, 0x50, 0xBF, 0x70, 0x47];
assert_eq!(decode_at(&image, 2), None, "0xbf50 is not decoded");
assert_eq!(
disassemble(&image, 0, 0x1000, 3),
[
"00001000: bx lr",
"00000002: .short 0xbf50",
"00001004: bx lr",
]
);
assert_eq!(disassemble(&image, 0, 0x1000, 99).len(), 3);
assert_eq!(disassemble(&[0x70, 0x47, 0x00], 0, 0, 9).len(), 1);
assert_eq!(disassemble(&[], 0, 0, 9), Vec::<String>::new());
assert_eq!(disassemble(&image, 0, 0x1000, 0), Vec::<String>::new());
}
#[test]
fn encode_reproduces_a_thumbee_instruction() {
let ee = decode_halfwords(0xC207, 0, 0x1000, Target::ThumbEE).expect("hb #7");
assert_eq!(ee.mnemonic, "hb");
assert_eq!(encode(&ee), Some((0xC207, 0)));
assert_eq!(encode_bytes(&ee), Some(vec![0x07, 0xC2]));
let plain = decode_halfwords(0xC207, 0, 0x1000, Target::Union).expect("stmia");
assert_eq!(plain.mnemonic, "stmia");
assert_eq!(encode(&plain), Some((0xC207, 0)));
let aligned = Insn {
operands: [
Operand::Reg(Reg(0)),
Operand::Mem(Mem {
base: Reg(9),
index: None,
offset: 0,
add: true,
align: 64,
mode: AddrMode::Offset,
}),
]
.into_iter()
.collect(),
..decode_halfwords(0xCC10, 0, 0x1000, Target::ThumbEE).expect("ldr r0, [r9, #8]")
};
assert_eq!(aligned.to_string(), "ldr r0, [r9:64]");
assert_eq!(encode(&aligned), None);
assert_eq!(encode_bytes(&aligned), None);
let mut checked = 0usize;
for hw in 0xC000u16..=0xCFFF {
if let Some(i) = decode_halfwords(hw, 0, 0x1000, Target::ThumbEE) {
assert_eq!(encode(&i), Some((hw, 0)), "{hw:#06x} as `{i}`");
checked += 1;
}
}
assert_eq!(checked, 3840, "Table A9-2 less its 256 UNDEFINED halfwords");
}
#[test]
fn an_unencodable_instruction_yields_no_bytes() {
let mut alien = decode_halfwords(0x4770, 0, 0, Target::Union).expect("bx lr");
alien.mnemonic = "frobnicate";
assert_eq!(encode(&alien), None);
assert_eq!(encode_bytes(&alien), None);
let mut wide = decode_halfwords(0xF000, 0xF800, 0, Target::Union).expect("bl");
wide.mnemonic = "frobnicate";
assert_eq!(wide.width, Width::Wide);
assert_eq!(encode(&wide), None);
assert_eq!(encode_bytes(&wide), None);
let mut far = decode_halfwords(0xE7FE, 0, 0x1000, Target::Union).expect("b .");
far.operands = [Operand::Target(0x9000)].into_iter().collect();
assert_eq!(encode(&far), None);
}
#[test]
fn encode_bytes_is_word_invariant() {
let narrow = decode_halfwords(0x4770, 0, 0, Target::Union).expect("bx lr");
assert_eq!(encode_bytes(&narrow), Some(vec![0x70, 0x47]));
let wide = decode_halfwords(0xF000, 0xF800, 0, Target::Union).expect("bl");
assert_eq!(encode(&wide), Some((0xF000, 0xF800)));
assert_eq!(encode_bytes(&wide), Some(vec![0x00, 0xF0, 0x00, 0xF8]));
}
#[test]
fn a_candidate_that_does_not_decode_is_not_faithful() {
let insn = decode_halfwords(0x4770, 0, 0, Target::Union).expect("bx lr");
assert_eq!(decode_halfwords(0xB651, 0, 0, Target::Union), None);
assert!(!faithful(&insn, 0xB651, 0, Target::Union));
assert!(faithful(&insn, 0x4770, 0, Target::Union));
}
#[test]
fn an_it_block_clears_the_flags_of_narrow_instructions_only() {
let image = [0x04, 0xBF, 0x88, 0x00, 0x11, 0xF1, 0x01, 0x00];
let text: Vec<String> = Decoder::new(&image).map(|i| i.to_string()).collect();
assert_eq!(text, ["itt eq", "lsleq r0, r1, #2", "addseq.w r0, r1, #1"]);
let decoded: Vec<Insn> = Decoder::new(&image).collect();
assert_eq!(decoded.len(), 3);
assert_eq!(decoded[1].cond, Some(Cond::Eq));
assert_eq!(decoded[1].width, Width::Narrow);
assert!(!decoded[1].sets_flags);
let bare = decode_halfwords(0x0088, 0, 0, Target::Union).expect("lsls");
assert!(bare.sets_flags);
assert_eq!(decoded[2].cond, Some(Cond::Eq));
assert_eq!(decoded[2].width, Width::Wide);
assert!(
decoded[2].sets_flags,
"the wide encodings carry their own S bit"
);
assert_eq!(encode(&decoded[1]), Some((0x0088, 0)));
assert_eq!(encode(&decoded[2]), Some((0xF111, 0x0001)));
}
#[test]
fn inactive_it_state_yields_no_condition() {
assert!(!ItState::INACTIVE.active());
assert_eq!(ItState::INACTIVE.current(), None);
assert_eq!(ItState::INACTIVE.advance(), ItState::INACTIVE);
}
#[test]
fn every_row_of_the_wide_dispatch_table_reaches_its_group() {
for (hw1, hw2, text) in [
(0xF841u16, 0x0B04u16, Some("str r0, [r1], #4")),
(0xF8C1, 0x0004, Some("str.w r0, [r1, #4]")),
(0xF920, 0x070F, Some("vld1.8 {d0}, [r0]")),
(0xF811, 0x0002, Some("ldrb.w r0, [r1, r2]")),
(0xF831, 0x0002, Some("ldrh.w r0, [r1, r2]")),
(0xF851, 0x0002, Some("ldr.w r0, [r1, r2]")),
(0xF870, 0x0000, None),
(0xF9F0, 0x0000, None),
(0xFAB1, 0xF181, Some("clz r1, r1")),
(0xFB01, 0xF002, Some("mul r0, r1, r2")),
(0xFB91, 0xF0F2, Some("sdiv r0, r1, r2")),
(0xFD80, 0x0E01, Some("stc2 p14, c0, [r0, #4]")),
(0xFE00, 0x0E10, Some("mcr2 p14, #0, r0, c0, c0, #0")),
(0xFE10, 0x0E10, Some("mrc2 p14, #0, r0, c0, c0, #0")),
] {
let decoded = decode_halfwords(hw1, hw2, 0x1000, Target::Union);
let op2 = (hw1 >> 4) & 0b111_1111;
assert_eq!(
decoded.map(|i| i.to_string()).as_deref(),
text,
"{hw1:#06x} {hw2:#06x} (op2 {op2:#09b}) was routed elsewhere"
);
}
}
#[test]
fn encode_refuses_a_flag_the_halfword_cannot_carry() {
for hw in [0xB510u16, 0xBD10, 0xE7FE, 0xBF00] {
let insn = decode_halfwords(hw, 0, 0x1000, Target::Union).expect("a defined halfword");
assert!(!insn.sets_flags, "{hw:#06x} has no S bit");
assert_eq!(insn.cond, None, "{hw:#06x} is unconditional");
assert_eq!(encode(&insn), Some((hw, 0)));
for cond in [None, Some(Cond::Eq)] {
let mut flagged = insn;
flagged.cond = cond;
flagged.sets_flags = true;
assert_eq!(
encode(&flagged),
None,
"`{flagged}` has no encoding: {hw:#06x} does not set the flags"
);
let mut conditional = insn;
conditional.cond = cond;
assert_eq!(encode(&conditional), Some((hw, 0)));
}
}
let bare = decode_halfwords(0x0088, 0, 0x1000, Target::Union).expect("lsls r0, r1, #2");
assert!(bare.sets_flags);
let mut in_it = bare;
in_it.cond = Some(Cond::Eq);
in_it.sets_flags = false;
assert_eq!(
encode(&in_it),
Some((0x0088, 0)),
"a conditional narrow instruction may disagree about the flags"
);
}
#[test]
fn the_flag_carve_out_excuses_an_it_block_and_nothing_else() {
let bits = decode_halfwords(0x0088, 0, 0x1000, Target::Union).expect("lsls r0, r1, #2");
assert!(bits.sets_flags);
assert_eq!(bits.cond, None);
assert_eq!(bits.width, Width::Narrow);
assert!(faithful(&bits, 0x0088, 0, Target::Union));
let mut in_it = bits;
in_it.cond = Some(Cond::Eq);
in_it.sets_flags = false;
assert!(
faithful(&in_it, 0x0088, 0, Target::Union),
"`lsleq` is `0x0088`"
);
let mut bare = bits;
bare.sets_flags = false;
assert!(
!faithful(&bare, 0x0088, 0, Target::Union),
"no enclosing `IT`, so `0x0088`'s S bit is not excusable"
);
}
#[test]
fn a_condition_in_the_bits_must_match_and_one_from_an_it_block_need_not() {
let beq = decode_halfwords(0xD0FE, 0, 0x1000, Target::Union).expect("beq .");
assert_eq!(beq.cond, Some(Cond::Eq));
assert!(faithful(&beq, 0xD0FE, 0, Target::Union));
let mut bne = beq;
bne.cond = Some(Cond::Ne);
assert!(
!faithful(&bne, 0xD0FE, 0, Target::Union),
"`bne .` is `0xD1FE`: this halfword carries its own condition"
);
let nop = decode_halfwords(0xBF00, 0, 0x1000, Target::Union).expect("nop");
assert_eq!(nop.cond, None);
let mut nopeq = nop;
nopeq.cond = Some(Cond::Eq);
assert!(
faithful(&nopeq, 0xBF00, 0, Target::Union),
"`nopeq` is `0xBF00`"
);
}
#[test]
fn disassemble_reserves_no_more_than_the_image_can_yield() {
let image = [0x00, 0xBF, 0x00, 0xBF, 0x00, 0xBF];
let out = disassemble(&image, 0, 0x1000, 100_000);
assert_eq!(out.len(), 3);
assert_eq!(out[0], "00001000: nop");
assert_eq!(out.capacity(), 3, "reserved for `count`, not for the image");
let from_middle = disassemble(&image, 4, 0x1004, 100_000);
assert_eq!(from_middle.len(), 1);
assert_eq!(from_middle.capacity(), 1);
let clipped = disassemble(&image, 0, 0x1000, 2);
assert_eq!(clipped.len(), 2);
assert_eq!(clipped.capacity(), 2);
}
}