use crate::isa::{self, AddrMode, Insn, Mem, Operand, Operands, Reg, Width};
use crate::{encode_b_cond, encode_b_wide, Cond};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Widen {
Never,
IfNeeded,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum RelocateError {
Misaligned {
mnemonic: &'static str,
from: u32,
to: u32,
},
ReadsPc {
mnemonic: &'static str,
from: u32,
to: u32,
},
ForwardOnlyBranch {
mnemonic: &'static str,
from: u32,
to: u32,
target: u32,
},
TableBranch {
mnemonic: &'static str,
from: u32,
to: u32,
},
UnresolvedPcRelative {
mnemonic: &'static str,
from: u32,
to: u32,
},
LiteralAlignment {
mnemonic: &'static str,
from: u32,
to: u32,
target: u32,
},
OutOfRange {
mnemonic: &'static str,
from: u32,
to: u32,
target: Option<u32>,
},
NotEncodable {
mnemonic: &'static str,
encoding: &'static str,
from: u32,
to: u32,
},
SecureGateway {
from: u32,
to: u32,
},
FlagsLive {
mnemonic: &'static str,
from: u32,
to: u32,
live: crate::flags::Flags,
},
}
impl RelocateError {
pub fn reason(&self) -> &'static str {
match self {
RelocateError::Misaligned { .. } => "misaligned-destination",
RelocateError::ReadsPc { .. } => "reads-pc",
RelocateError::ForwardOnlyBranch { .. } => "forward-only-branch",
RelocateError::TableBranch { .. } => "pc-relative-table",
RelocateError::UnresolvedPcRelative { .. } => "unresolved-pc-relative",
RelocateError::LiteralAlignment { .. } => "literal-alignment",
RelocateError::OutOfRange { .. } => "out-of-range",
RelocateError::NotEncodable { .. } => "not-encodable",
RelocateError::SecureGateway { .. } => "secure-gateway",
RelocateError::FlagsLive { .. } => "flags-live",
}
}
pub fn mnemonic(&self) -> &'static str {
match *self {
RelocateError::Misaligned { mnemonic, .. }
| RelocateError::ReadsPc { mnemonic, .. }
| RelocateError::ForwardOnlyBranch { mnemonic, .. }
| RelocateError::TableBranch { mnemonic, .. }
| RelocateError::UnresolvedPcRelative { mnemonic, .. }
| RelocateError::LiteralAlignment { mnemonic, .. }
| RelocateError::OutOfRange { mnemonic, .. }
| RelocateError::NotEncodable { mnemonic, .. } => mnemonic,
RelocateError::SecureGateway { .. } => "sg",
RelocateError::FlagsLive { mnemonic, .. } => mnemonic,
}
}
pub fn from(&self) -> u32 {
match *self {
RelocateError::Misaligned { from, .. }
| RelocateError::ReadsPc { from, .. }
| RelocateError::ForwardOnlyBranch { from, .. }
| RelocateError::TableBranch { from, .. }
| RelocateError::UnresolvedPcRelative { from, .. }
| RelocateError::LiteralAlignment { from, .. }
| RelocateError::OutOfRange { from, .. }
| RelocateError::NotEncodable { from, .. } => from,
RelocateError::SecureGateway { from, .. } => from,
RelocateError::FlagsLive { from, .. } => from,
}
}
pub fn to(&self) -> u32 {
match *self {
RelocateError::Misaligned { to, .. }
| RelocateError::ReadsPc { to, .. }
| RelocateError::ForwardOnlyBranch { to, .. }
| RelocateError::TableBranch { to, .. }
| RelocateError::UnresolvedPcRelative { to, .. }
| RelocateError::LiteralAlignment { to, .. }
| RelocateError::OutOfRange { to, .. }
| RelocateError::NotEncodable { to, .. } => to,
RelocateError::SecureGateway { to, .. } => to,
RelocateError::FlagsLive { to, .. } => to,
}
}
pub fn is_address_dependent(&self) -> bool {
matches!(
self,
RelocateError::Misaligned { .. }
| RelocateError::ForwardOnlyBranch { .. }
| RelocateError::LiteralAlignment { .. }
| RelocateError::OutOfRange { .. }
)
}
}
impl core::fmt::Display for RelocateError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(
f,
"cannot relocate `{}` from {:#x} to {:#x}: {}",
self.mnemonic(),
self.from(),
self.to(),
self.reason()
)?;
match *self {
RelocateError::Misaligned { .. } => {
f.write_str(" (a Thumb instruction is halfword aligned)")
}
RelocateError::ReadsPc { .. } => {
f.write_str(" (the pc value it observes changes with its address)")
}
RelocateError::SecureGateway { .. } => {
f.write_str(" (a secure gateway is identified by the address it sits at)")
}
RelocateError::FlagsLive { live, .. } => write!(
f,
" (the rewrite writes flags that are still live: {live:?})"
),
RelocateError::ForwardOnlyBranch { target, .. } => write!(
f,
" (target {target:#x} is not 0..126 bytes forward; cbz/cbnz has no backward form)"
),
RelocateError::TableBranch { .. } => {
f.write_str(" (the table holds offsets from this instruction's own pc)")
}
RelocateError::UnresolvedPcRelative { .. } => {
f.write_str(" (no resolved target accompanies the pc-relative operand)")
}
RelocateError::LiteralAlignment { target, .. } => write!(
f,
" (target {target:#x} is not a multiple of 4 from Align(pc,4))"
),
RelocateError::OutOfRange {
target: Some(t), ..
} => write!(f, " (target {t:#x} no longer reaches)"),
RelocateError::OutOfRange { target: None, .. } => {
f.write_str(" (the displacement no longer fits)")
}
RelocateError::NotEncodable { encoding, .. } => {
write!(f, " (this crate cannot encode {encoding})")
}
}
}
}
impl std::error::Error for RelocateError {}
pub fn relocate(insn: &Insn, to: u32) -> Result<Insn, RelocateError> {
relocate_with(insn, to, Widen::Never)
}
pub fn relocate_with(insn: &Insn, to: u32, widen: Widen) -> Result<Insn, RelocateError> {
relocate_encoded(insn, to, widen).map(|(moved, _)| moved)
}
pub fn relocate_bytes(insn: &Insn, to: u32, widen: Widen) -> Result<Vec<u8>, RelocateError> {
relocate_encoded(insn, to, widen).map(|(_, bytes)| bytes)
}
fn relocate_encoded(insn: &Insn, to: u32, widen: Widen) -> Result<(Insn, Vec<u8>), RelocateError> {
let moved = resite(insn, to)?;
if let Some(bytes) = isa::encode_bytes(&moved) {
return Ok((moved, bytes));
}
if widen == Widen::IfNeeded {
if let Some(wide) = widened(insn, to) {
return Ok(wide);
}
}
Err(encode_failure(insn, to))
}
fn align_pc(addr: u32) -> u32 {
addr.wrapping_add(4) & !3
}
fn resite(insn: &Insn, to: u32) -> Result<Insn, RelocateError> {
let mnemonic = insn.mnemonic;
let from = insn.addr;
if to & 1 != 0 {
return Err(RelocateError::Misaligned { mnemonic, from, to });
}
if matches!(mnemonic, "tbb" | "tbh") {
return Err(RelocateError::TableBranch { mnemonic, from, to });
}
if mnemonic == "sg" {
return Err(RelocateError::SecureGateway { from, to });
}
if reads_pc(insn) {
return Err(RelocateError::ReadsPc { mnemonic, from, to });
}
let mut operands = insn.operands;
if let Some(mem) = pc_mem(insn) {
if mem.index.is_some() || mem.mode != AddrMode::Offset {
return Err(RelocateError::UnresolvedPcRelative { mnemonic, from, to });
}
let target = match first_target(insn) {
Some(t) => t,
None => return Err(RelocateError::UnresolvedPcRelative { mnemonic, from, to }),
};
let disp = i64::from(target) - i64::from(align_pc(to));
let (offset, add) = if disp > 0 {
(disp as u32, true)
} else if disp < 0 {
((-disp) as u32, false)
} else {
(0, mem.add)
};
operands = replace_pc_mem(&insn.operands, Mem { offset, add, ..mem });
}
let scaled_target = if insn.width == Width::Narrow && is_align_pc_form(insn) {
first_target(insn)
} else {
None
};
if let Some(target) = scaled_target {
if (i64::from(target) - i64::from(align_pc(to))) % 4 != 0 {
return Err(RelocateError::LiteralAlignment {
mnemonic,
from,
to,
target,
});
}
}
let mut encoding = insn.encoding;
let adr_target = if mnemonic == "adr" && insn.width == Width::Wide {
first_target(insn)
} else {
None
};
if let Some(target) = adr_target {
encoding = if target >= align_pc(to) { "T3" } else { "T2" };
}
Ok(Insn {
addr: to,
encoding,
operands,
..*insn
})
}
fn encode_failure(insn: &Insn, to: u32) -> RelocateError {
let mnemonic = insn.mnemonic;
let from = insn.addr;
if isa::encode(insn).is_none() {
return RelocateError::NotEncodable {
mnemonic,
encoding: insn.encoding,
from,
to,
};
}
if matches!(mnemonic, "cbz" | "cbnz") {
return RelocateError::ForwardOnlyBranch {
mnemonic,
from,
to,
target: first_target(insn).unwrap_or(0),
};
}
RelocateError::OutOfRange {
mnemonic,
from,
to,
target: first_target(insn),
}
}
fn widened(insn: &Insn, to: u32) -> Option<(Insn, Vec<u8>)> {
if insn.width != Width::Narrow || to & 1 != 0 {
return None;
}
let target = first_target(insn)?;
let bytes: Vec<u8> = match (insn.mnemonic, insn.encoding, insn.cond) {
("b", "T2", None) => encode_b_wide(to as usize, target)?.to_vec(),
("b", "T1", Some(cond)) if cond != Cond::Al => encode_b_cond(to as usize, cond, target)?,
_ => return None,
};
isa::decode_at_with(&bytes, 0, to, isa::Target::Union).map(|wide| (wide, bytes))
}
fn first_target(insn: &Insn) -> Option<u32> {
insn.operands.as_slice().find_map(|op| match op {
Operand::Target(t) => Some(t),
_ => None,
})
}
fn pc_mem(insn: &Insn) -> Option<Mem> {
insn.operands.as_slice().find_map(|op| match op {
Operand::Mem(m) if m.base == Reg::PC => Some(m),
_ => None,
})
}
fn is_align_pc_form(insn: &Insn) -> bool {
insn.mnemonic == "adr" || pc_mem(insn).is_some()
}
fn replace_pc_mem(operands: &Operands, mem: Mem) -> Operands {
operands
.as_slice()
.map(|op| match op {
Operand::Mem(m) if m.base == Reg::PC => Operand::Mem(mem),
other => other,
})
.collect()
}
fn reads_pc(insn: &Insn) -> bool {
let source_first = first_operand_is_source(insn.mnemonic)
|| (destructive_first_operand(insn.mnemonic) && insn.operands.len() == 2);
insn.operands
.as_slice()
.enumerate()
.any(|(i, op)| match op {
Operand::Reg(r) => r == Reg::PC && (source_first || i != 0),
Operand::RegShifted(r, _) => r == Reg::PC,
Operand::Mem(m) => matches!(m.index, Some((r, _)) if r == Reg::PC),
Operand::RegList(bits) => source_first && bits & (1 << 15) != 0,
_ => false,
})
}
fn destructive_first_operand(mnemonic: &str) -> bool {
matches!(
mnemonic,
"add"
| "adc"
| "sub"
| "sbc"
| "rsb"
| "and"
| "orr"
| "orn"
| "eor"
| "bic"
| "mul"
| "lsl"
| "lsr"
| "asr"
| "ror"
)
}
fn first_operand_is_source(mnemonic: &str) -> bool {
mnemonic.starts_with("str")
|| mnemonic.starts_with("vstr")
|| mnemonic.starts_with("vstm")
|| mnemonic.starts_with("vldm")
|| mnemonic.starts_with("stm")
|| mnemonic.starts_with("srs")
|| mnemonic.starts_with("ldm")
|| mnemonic.starts_with("rfe")
|| matches!(
mnemonic,
"push"
| "vpush"
| "cmp"
| "cmn"
| "tst"
| "teq"
| "chka"
| "bx"
| "blx"
| "bxj"
| "tbb"
| "tbh"
)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::isa::{Decoder, ShiftAmount, ShiftKind};
fn at(bytes: &[u8], addr: u32) -> Insn {
isa::decode_at_with(bytes, 0, addr, isa::Target::Union).expect("test vector must decode")
}
fn bytes_at(insn: &Insn, to: u32) -> Vec<u8> {
relocate_bytes(insn, to, Widen::Never).expect("must relocate")
}
#[test]
fn an_address_independent_instruction_only_changes_its_address() {
let insn = at(&[0x01, 0x20], 0x1000); assert_eq!(insn.to_string(), "movs r0, #1");
let moved = relocate(&insn, 0x9_0000).unwrap();
assert_eq!(moved.addr, 0x9_0000);
assert_eq!(moved.operands, insn.operands);
assert_eq!(bytes_at(&insn, 0x9_0000), vec![0x01, 0x20]);
}
#[test]
fn a_narrow_unconditional_branch_keeps_its_target() {
let insn = at(&[0x06, 0xe0], 0x1000);
assert_eq!((insn.mnemonic, insn.encoding), ("b", "T2"));
assert_eq!(insn.branch_target(), Some(0x1010));
let moved = relocate(&insn, 0x1004).unwrap();
assert_eq!(moved.branch_target(), Some(0x1010));
assert_eq!(bytes_at(&insn, 0x1004), vec![0x04, 0xe0]);
assert_eq!(bytes_at(&insn, 0x1020), vec![0xf6, 0xe7]);
assert_eq!(at(&[0xf6, 0xe7], 0x1020).branch_target(), Some(0x1010));
let err = relocate(&insn, 0x9000).unwrap_err();
assert_eq!(err.reason(), "out-of-range");
assert!(err.is_address_dependent());
}
#[test]
fn a_narrow_conditional_branch_has_an_asymmetric_range() {
let insn = at(&[0x7f, 0xd8], 0x1000);
assert_eq!(insn.mnemonic, "b");
assert_eq!(insn.cond, Some(Cond::Hi));
assert_eq!(insn.branch_target(), Some(0x1102));
assert_eq!(bytes_at(&insn, 0x1000), vec![0x7f, 0xd8]);
assert_eq!(
relocate(&insn, 0x0ffe).unwrap_err().reason(),
"out-of-range"
);
assert_eq!(bytes_at(&insn, 0x11fe), vec![0x80, 0xd8]);
assert_eq!(
relocate(&insn, 0x1200).unwrap_err().reason(),
"out-of-range"
);
for to in [0x1000, 0x1100, 0x11fe] {
let moved = relocate(&insn, to).unwrap();
let bytes = isa::encode_bytes(&moved).unwrap();
assert_eq!(at(&bytes, to).branch_target(), Some(0x1102), "from {to:#x}");
}
}
#[test]
fn a_literal_load_still_reads_the_same_pool_word() {
let insn = at(&[0x02, 0x48], 0x1000);
assert_eq!((insn.mnemonic, insn.encoding), ("ldr", "T1"));
assert_eq!(insn.branch_target(), Some(0x100c));
assert_eq!(insn.to_string(), "ldr r0, [pc, #8], 0x100c");
let cases = [
(0x0ffeu32, [0x03u8, 0x48], 12i64), (0x1000, [0x02, 0x48], 8), (0x1002, [0x02, 0x48], 8), (0x1004, [0x01, 0x48], 4), (0x1006, [0x01, 0x48], 4),
(0x1008, [0x00, 0x48], 0), (0x100a, [0x00, 0x48], 0), ];
for (to, want, want_offset) in cases {
let moved = relocate(&insn, to).unwrap();
assert_eq!(moved.branch_target(), Some(0x100c), "from {to:#x}");
let mem = pc_mem(&moved).expect("pc-relative");
assert_eq!(mem.displacement(), want_offset, "from {to:#x}");
assert_eq!(isa::encode_bytes(&moved).unwrap(), want, "from {to:#x}");
assert_eq!(at(&want, to).branch_target(), Some(0x100c), "from {to:#x}");
}
assert_eq!(
relocate(&insn, 0x100c).unwrap_err().reason(),
"out-of-range"
);
}
#[test]
fn a_wide_literal_load_relocates_in_both_directions() {
let insn = at(&[0xdf, 0xf8, 0x08, 0x00], 0x1000);
assert_eq!((insn.mnemonic, insn.encoding), ("ldr", "T2"));
assert_eq!(insn.branch_target(), Some(0x100c));
let moved = relocate(&insn, 0x2000).unwrap();
assert_eq!(moved.branch_target(), Some(0x100c));
assert_eq!(pc_mem(&moved).unwrap().displacement(), 0x100c - 0x2004);
assert!(
!pc_mem(&moved).unwrap().add,
"U must be clear below the pool"
);
let bytes = isa::encode_bytes(&moved).unwrap();
assert_eq!(bytes[0] & 0x80, 0, "U must be clear for a subtracting form");
assert_eq!(at(&bytes, 0x2000).branch_target(), Some(0x100c));
assert!(relocate(&insn, 0x2004).is_ok()); assert_eq!(
relocate(&insn, 0x2008).unwrap_err().reason(), "out-of-range"
);
assert!(relocate(&insn, 0x000c).is_ok()); assert_eq!(
relocate(&insn, 0x0008).unwrap_err().reason(), "out-of-range"
);
}
#[test]
fn a_wide_adr_flips_between_its_adding_and_subtracting_forms() {
let insn = at(&[0x0f, 0xf2, 0x00, 0x00], 0x1000);
assert_eq!((insn.mnemonic, insn.encoding), ("adr", "T3"));
assert_eq!(insn.branch_target(), Some(0x1004));
let up = relocate(&insn, 0x0f00).unwrap();
assert_eq!(up.encoding, "T3");
assert_eq!(up.branch_target(), Some(0x1004));
let down = relocate(&insn, 0x1ffc).unwrap();
assert_eq!(down.encoding, "T2");
let bytes = isa::encode_bytes(&down).unwrap();
let back = at(&bytes, 0x1ffc);
assert_eq!((back.mnemonic, back.encoding), ("adr", "T2"));
assert_eq!(back.branch_target(), Some(0x1004));
assert_eq!(
relocate(&insn, 0x2000).unwrap_err().reason(),
"out-of-range"
);
}
#[test]
fn writing_pc_is_relocatable_even_though_reading_it_is_not() {
for (bytes, text) in [
(vec![0x70, 0x47], "bx lr"),
(vec![0x10, 0xbd], "pop {r4, pc}"),
(vec![0xf7, 0x46], "mov pc, lr"),
] {
let insn = at(&bytes, 0x1000);
assert_eq!(insn.to_string(), text);
assert!(insn.writes_pc(), "{text}");
assert_eq!(bytes_at(&insn, 0x9_0000), bytes, "{text}");
}
}
#[test]
fn an_it_governed_instruction_relocates_to_the_same_halfword() {
let image = [0x08, 0xbf, 0x01, 0x20];
let mut d = Decoder::at(&image, 0, 0x1000);
let it = d.next().unwrap();
assert_eq!(it.mnemonic, "it");
let governed = d.next().unwrap();
assert_eq!(governed.cond, Some(Cond::Eq));
assert!(!governed.sets_flags);
assert_eq!(bytes_at(&governed, 0x9_0002), vec![0x01, 0x20]);
assert_eq!(bytes_at(&it, 0x9_0000), vec![0x08, 0xbf]);
}
#[test]
fn cbz_and_cbnz_are_refused_as_forward_only() {
for (bytes, mnemonic) in [([0x20, 0xb1], "cbz"), ([0x20, 0xb9], "cbnz")] {
let insn = at(&bytes, 0x1000);
assert_eq!(insn.mnemonic, mnemonic);
assert_eq!(insn.branch_target(), Some(0x100c));
let err = relocate(&insn, 0x9_0000).unwrap_err();
assert_eq!(err.reason(), "forward-only-branch");
assert_eq!(err.mnemonic(), mnemonic);
assert_eq!(
err,
RelocateError::ForwardOnlyBranch {
mnemonic,
from: 0x1000,
to: 0x9_0000,
target: 0x100c,
}
);
assert!(relocate_with(&insn, 0x9_0000, Widen::IfNeeded).is_err());
assert_eq!(
relocate(&insn, 0x100e).unwrap_err().reason(),
"forward-only-branch"
);
}
}
#[test]
fn a_table_branch_is_refused_although_it_re_encodes() {
let insn = at(&[0xd0, 0xe8, 0x01, 0xf0], 0x1000);
assert_eq!(insn.mnemonic, "tbb");
let naive = Insn {
addr: 0x9_0000,
..insn
};
assert!(
isa::encode(&naive).is_some(),
"nothing in the bits depends on the address, which is the trap"
);
let err = relocate(&insn, 0x9_0000).unwrap_err();
assert_eq!(err.reason(), "pc-relative-table");
assert!(!err.is_address_dependent());
let tbh = at(&[0xdf, 0xe8, 0x10, 0xf0], 0x1000);
assert_eq!(tbh.mnemonic, "tbh");
assert_eq!(
relocate(&tbh, 0x2000).unwrap_err().reason(),
"pc-relative-table"
);
}
#[test]
fn instructions_that_read_pc_are_refused() {
for (bytes, text) in [
(vec![0x78, 0x46], "mov r0, pc"),
(vec![0x78, 0x44], "add r0, pc"),
(vec![0x78, 0x45], "cmp r0, pc"),
(vec![0x78, 0x47], "bx pc"),
] {
let insn = at(&bytes, 0x1000);
assert_eq!(insn.to_string(), text);
let err = relocate(&insn, 0x2000).unwrap_err();
assert_eq!(err.reason(), "reads-pc", "{text}");
assert!(!err.is_address_dependent(), "{text}");
}
}
#[test]
fn a_pc_indexed_memory_operand_is_refused() {
let mut operands = Operands::new();
operands.push(Operand::Reg(Reg(0)));
operands.push(Operand::Mem(Mem {
base: Reg(1),
index: Some((
Reg::PC,
Some(crate::isa::Shift {
kind: ShiftKind::Lsl,
amount: ShiftAmount::Imm(0),
}),
)),
offset: 0,
add: true,
align: 0,
mode: AddrMode::Offset,
}));
let insn = Insn {
mnemonic: "ldr",
encoding: "T2",
addr: 0x1000,
width: Width::Wide,
cond: None,
sets_flags: false,
explicit_width: false,
operands,
};
assert_eq!(relocate(&insn, 0x2000).unwrap_err().reason(), "reads-pc");
}
#[test]
fn an_indexed_or_writing_back_pc_operand_is_refused() {
let post = at(&[0x7f, 0xe8, 0x00, 0x00], 0x1000);
assert_eq!(post.mnemonic, "ldrd");
assert_eq!(pc_mem(&post).unwrap().mode, AddrMode::PostIndex);
let err = relocate(&post, 0x2000).unwrap_err();
assert_eq!(err.reason(), "unresolved-pc-relative");
assert_eq!(err.mnemonic(), "ldrd");
assert!(!err.is_address_dependent(), "no address can fix it");
let indexed = at(&[0x0f, 0xf9, 0x00, 0x00], 0x1000);
let mem = pc_mem(&indexed).unwrap();
assert!(mem.index.is_some());
assert_eq!(
relocate(&indexed, 0x2000).unwrap_err().reason(),
"unresolved-pc-relative"
);
}
#[test]
fn a_shifted_pc_operand_is_read_as_pc() {
let insn = at(&[0x10, 0xea, 0x0f, 0x2f], 0x1000);
assert_eq!(insn.to_string(), "tst.w r0, pc, lsl #8");
assert!(reads_pc(&insn));
let err = relocate(&insn, 0x2000).unwrap_err();
assert_eq!(err.reason(), "reads-pc");
assert!(!err.is_address_dependent());
let ordinary = at(&[0x10, 0xea, 0x01, 0x2f], 0x1000);
assert_eq!(ordinary.to_string(), "tst.w r0, r1, lsl #8");
assert!(!reads_pc(&ordinary));
assert_eq!(bytes_at(&ordinary, 0x9_0000), vec![0x10, 0xea, 0x01, 0x2f]);
}
#[test]
fn a_pc_relative_operand_without_a_target_is_refused() {
let mut operands = Operands::new();
operands.push(Operand::Reg(Reg(0)));
operands.push(Operand::Mem(Mem {
base: Reg::PC,
index: None,
offset: 8,
add: true,
align: 0,
mode: AddrMode::Offset,
}));
let insn = Insn {
mnemonic: "ldr",
encoding: "T1",
addr: 0x1000,
width: Width::Narrow,
cond: None,
sets_flags: false,
explicit_width: false,
operands,
};
let err = relocate(&insn, 0x2000).unwrap_err();
assert_eq!(err.reason(), "unresolved-pc-relative");
assert!(!err.is_address_dependent());
}
#[test]
fn a_narrow_literal_with_a_misaligned_target_is_refused() {
let insn = at(&[0x02, 0x48], 0x1000); let bogus = Insn {
operands: insn
.operands
.as_slice()
.map(|op| match op {
Operand::Target(_) => Operand::Target(0x100e),
other => other,
})
.collect(),
..insn
};
let err = relocate(&bogus, 0x1000).unwrap_err();
assert_eq!(err.reason(), "literal-alignment");
assert_eq!(
err,
RelocateError::LiteralAlignment {
mnemonic: "ldr",
from: 0x1000,
to: 0x1000,
target: 0x100e,
}
);
}
#[test]
fn an_odd_destination_is_refused() {
let insn = at(&[0x01, 0x20], 0x1000);
let err = relocate(&insn, 0x2001).unwrap_err();
assert_eq!(err.reason(), "misaligned-destination");
assert_eq!(err.to(), 0x2001);
let branch = at(&[0x06, 0xe0], 0x1000);
assert_eq!(
relocate_with(&branch, 0x9001, Widen::IfNeeded)
.unwrap_err()
.reason(),
"misaligned-destination"
);
}
#[test]
fn an_unencodable_instruction_is_refused_by_name() {
let insn = Insn {
mnemonic: "frobnicate",
encoding: "T9",
addr: 0x1000,
width: Width::Narrow,
cond: None,
sets_flags: false,
explicit_width: false,
operands: Operands::new(),
};
let err = relocate(&insn, 0x2000).unwrap_err();
assert_eq!(err.reason(), "not-encodable");
assert_eq!(
err,
RelocateError::NotEncodable {
mnemonic: "frobnicate",
encoding: "T9",
from: 0x1000,
to: 0x2000,
}
);
assert_eq!(
relocate_with(&insn, 0x2000, Widen::IfNeeded).unwrap_err(),
err
);
}
#[test]
fn the_range_message_says_what_no_longer_reaches() {
let with_target = RelocateError::OutOfRange {
mnemonic: "b",
from: 0x1000,
to: 0x9000,
target: Some(0x1010),
};
assert_eq!(
with_target.to_string(),
"cannot relocate `b` from 0x1000 to 0x9000: out-of-range \
(target 0x1010 no longer reaches)"
);
let without_target = RelocateError::OutOfRange {
mnemonic: "b",
from: 0x1000,
to: 0x9000,
target: None,
};
assert_eq!(
without_target.to_string(),
"cannot relocate `b` from 0x1000 to 0x9000: out-of-range \
(the displacement no longer fits)"
);
}
#[test]
fn display_propagates_a_write_failure() {
struct Full;
impl core::fmt::Write for Full {
fn write_str(&mut self, _: &str) -> core::fmt::Result {
Err(core::fmt::Error)
}
}
let err = RelocateError::Misaligned {
mnemonic: "movs",
from: 0x1000,
to: 0x2001,
};
assert!(core::fmt::write(&mut Full, format_args!("{err}")).is_err());
}
#[test]
fn widening_an_unconditional_branch_is_opt_in_and_minimal() {
let insn = at(&[0x06, 0xe0], 0x1000);
let near = relocate_with(&insn, 0x1004, Widen::IfNeeded).unwrap();
assert_eq!((near.width, near.len()), (Width::Narrow, 2));
assert_eq!(near.encoding, "T2");
let far = relocate_with(&insn, 0x9000, Widen::IfNeeded).unwrap();
assert_eq!((far.mnemonic, far.encoding, far.len()), ("b", "T4", 4));
assert!(far.explicit_width);
assert_eq!(far.branch_target(), Some(0x1010));
let bytes = isa::encode_bytes(&far).unwrap();
assert_eq!(bytes.len(), 4);
assert_eq!(at(&bytes, 0x9000).branch_target(), Some(0x1010));
assert_eq!(
crate::encode_b_wide(0x9000, 0x1010)
.as_ref()
.map(|b| &b[..]),
Some(&bytes[..])
);
assert_eq!(
relocate_with(&insn, 0x200_0000, Widen::IfNeeded)
.unwrap_err()
.reason(),
"out-of-range"
);
}
#[test]
fn widening_a_conditional_branch_keeps_its_condition() {
let insn = at(&[0x7f, 0xd8], 0x1000); let far = relocate_with(&insn, 0x9000, Widen::IfNeeded).unwrap();
assert_eq!((far.mnemonic, far.encoding, far.len()), ("b", "T3", 4));
assert_eq!(far.cond, Some(Cond::Hi));
assert_eq!(far.branch_target(), Some(0x1102));
let bytes = isa::encode_bytes(&far).unwrap();
let back = crate::decode_b_cond(&bytes, 0).unwrap();
assert_eq!(back.cond, Cond::Hi);
assert_eq!(back.len, 4);
let decoded = at(&bytes, 0x9000);
assert_eq!(decoded.cond, Some(Cond::Hi));
assert_eq!(decoded.branch_target(), Some(0x1102));
assert!(relocate_with(&insn, 0x10_0000, Widen::IfNeeded).is_ok());
assert_eq!(
relocate_with(&insn, 0x20_0000, Widen::IfNeeded)
.unwrap_err()
.reason(),
"out-of-range"
);
}
#[test]
fn widening_is_limited_to_direct_branches() {
let image = [0x08, 0xbf, 0x06, 0xe0]; let mut d = Decoder::at(&image, 0, 0x1000);
d.next().unwrap();
let governed = d.next().unwrap();
assert_eq!((governed.mnemonic, governed.encoding), ("b", "T2"));
assert_eq!(governed.cond, Some(Cond::Eq));
assert_eq!(
relocate_with(&governed, 0x9000, Widen::IfNeeded)
.unwrap_err()
.reason(),
"out-of-range"
);
let ldr = at(&[0x02, 0x48], 0x1000);
let err = relocate_with(&ldr, 0x9000, Widen::IfNeeded).unwrap_err();
assert_eq!(err.reason(), "out-of-range");
assert_eq!(err.mnemonic(), "ldr");
let wide = at(&[0xdf, 0xf8, 0x08, 0x00], 0x1000);
assert_eq!(wide.width, Width::Wide);
assert_eq!(
relocate_with(&wide, 0x9000, Widen::IfNeeded).unwrap_err(),
relocate_with(&wide, 0x9000, Widen::Never).unwrap_err()
);
assert_eq!(
relocate_with(&wide, 0x9000, Widen::IfNeeded)
.unwrap_err()
.reason(),
"out-of-range"
);
}
#[test]
fn address_independent_instructions_relocate_byte_identically() {
let mut checked = 0usize;
for hw in 0x0000u16..=0xFFFF {
if isa::insn_len(hw) != 2 {
continue;
}
let bytes = hw.to_le_bytes();
let insn = match isa::decode_at_with(&bytes, 0, 0x1000, isa::Target::Union) {
Some(i) => i,
None => continue,
};
if first_target(&insn).is_some()
|| reads_pc(&insn)
|| pc_mem(&insn).is_some()
|| isa::encode(&insn).is_none()
{
continue;
}
checked += 1;
let moved = relocate(&insn, 0x2000);
assert!(moved.is_ok(), "{insn} ({hw:#06x}) must relocate: {moved:?}");
let moved = moved.unwrap();
assert_eq!(moved.addr, 0x2000, "{insn} ({hw:#06x})");
assert_eq!(
isa::encode_bytes(&moved).as_deref(),
Some(&bytes[..]),
"{insn} ({hw:#06x}) changed under relocation"
);
}
assert!(checked > 20_000, "only {checked} instructions swept");
}
#[test]
fn reason_strings_are_stable() {
let all = [
(
RelocateError::Misaligned {
mnemonic: "movs",
from: 0,
to: 1,
},
"misaligned-destination",
),
(
RelocateError::ReadsPc {
mnemonic: "mov",
from: 0,
to: 2,
},
"reads-pc",
),
(
RelocateError::ForwardOnlyBranch {
mnemonic: "cbz",
from: 0,
to: 2,
target: 4,
},
"forward-only-branch",
),
(
RelocateError::TableBranch {
mnemonic: "tbb",
from: 0,
to: 2,
},
"pc-relative-table",
),
(
RelocateError::UnresolvedPcRelative {
mnemonic: "ldr",
from: 0,
to: 2,
},
"unresolved-pc-relative",
),
(
RelocateError::LiteralAlignment {
mnemonic: "ldr",
from: 0,
to: 2,
target: 6,
},
"literal-alignment",
),
(
RelocateError::OutOfRange {
mnemonic: "b",
from: 0,
to: 2,
target: Some(4),
},
"out-of-range",
),
(
RelocateError::NotEncodable {
mnemonic: "x",
encoding: "T1",
from: 0,
to: 2,
},
"not-encodable",
),
];
for (err, reason) in all {
assert_eq!(err.reason(), reason);
let text = err.to_string();
assert!(text.contains(err.mnemonic()), "{text}");
assert!(text.contains(reason), "{text}");
}
}
#[test]
fn a_destructive_first_operand_reads_pc_and_cannot_be_relocated() {
for m in 0..16u16 {
let hw = 0x4487 | (m << 3);
let decoded =
crate::isa::decode_at_with(&hw.to_le_bytes(), 0, 0x102, isa::Target::Union);
assert!(decoded.is_some(), "{hw:#06x} must decode");
let insn = decoded.unwrap();
assert_eq!(insn.mnemonic, "add", "{hw:#06x}");
let err = relocate(&insn, 0x200).expect_err(&format!(
"{hw:#06x} ({insn}) must not relocate: it reads pc"
));
assert_eq!(err.reason(), "reads-pc", "{hw:#06x} ({insn})");
}
let mv = crate::isa::decode_at_with(&0x46F7u16.to_le_bytes(), 0, 0x102, isa::Target::Union)
.unwrap();
assert_eq!(mv.mnemonic, "mov");
assert!(
relocate(&mv, 0x200).is_ok(),
"`{mv}` is address-independent and must still relocate"
);
}
#[test]
fn first_operand_is_source_recognises_each_family_and_rejects_the_rest() {
for m in [
"str", "strb", "strh", "strd", "strex", "vstr", "vstm", "vldm", "stm", "stmdb", "srs",
"ldm", "ldmdb", "rfe", "push", "vpush", "cmp", "cmn", "tst", "teq", "bx", "blx", "bxj",
"tbb", "tbh",
] {
assert!(first_operand_is_source(m), "{m} names a source first");
}
for m in [
"ldr", "ldrb", "ldrd", "ldrex", "vldr", "mov", "add", "sub", "and", "orr", "eor",
"mul", "lsl", "asr", "adr", "pop", "b", "bl",
] {
assert!(!first_operand_is_source(m), "{m} names a destination first");
}
}
#[test]
fn a_register_list_holding_pc_is_read_only_where_pc_is_a_source() {
let list = |mnemonic: &'static str, bits: u16| Insn {
mnemonic,
encoding: "T2",
addr: 0,
width: Width::Wide,
cond: None,
sets_flags: false,
explicit_width: false,
operands: {
let mut o = Operands::new();
o.push(Operand::Reg(Reg::SP));
o.push(Operand::RegList(bits));
o
},
};
assert!(reads_pc(&list("stm", 1 << 15)), "stm {{pc}} reads pc");
assert!(reads_pc(&list("push", 1 << 15)), "push {{pc}} reads pc");
assert!(!reads_pc(&list("stm", 0x00FF)), "no pc in the list");
assert!(!reads_pc(&list("push", 1 << 14)), "lr is not pc");
for b in 0..15 {
assert!(
!reads_pc(&list("stm", 1 << b)),
"bit {b} is not pc and must not read as one"
);
}
assert!(!reads_pc(&list("pop", (1 << 15) | (1 << 4))));
}
#[test]
fn a_zero_displacement_keeps_the_u_bit_it_arrived_with() {
let insn = at(&[0x5F, 0xF8, 0x00, 0x00], 0x1000);
assert!(!pc_mem(&insn).expect("a pc-based memory operand").add);
for to in [0x1000u32, 0x1002] {
let moved = relocate(&insn, to).expect("address-independent");
let m = pc_mem(&moved).expect("still a pc-based operand");
assert_eq!(m.displacement(), 0, "from {to:#x}");
assert!(!m.add, "U must survive relocation to {to:#x}");
assert_eq!(
isa::encode_bytes(&moved).expect("re-encodable"),
vec![0x5F, 0xF8, 0x00, 0x00],
"the same four bytes, from {to:#x}"
);
}
}
#[test]
fn a_wide_adr_that_lands_exactly_on_its_label_stays_the_adding_form() {
let insn = at(&[0x0F, 0xF2, 0x00, 0x00], 0x1000);
assert_eq!(insn.encoding, "T3");
let label = insn.branch_target().expect("a resolved label");
for to in [0x1000u32, 0x1002] {
let moved = relocate(&insn, to).expect("address-independent");
assert_eq!(moved.branch_target(), Some(label), "from {to:#x}");
assert_eq!(moved.encoding, "T3", "the adding form, from {to:#x}");
assert_eq!(
isa::encode_bytes(&moved).expect("re-encodable"),
vec![0x0F, 0xF2, 0x00, 0x00],
"the same four bytes, from {to:#x}"
);
}
}
#[test]
fn only_a_pc_based_memory_operand_is_a_literal_access() {
let ordinary = at(&[0x48, 0x68], 0x1000);
assert!(
ordinary
.operands
.as_slice()
.any(|o| matches!(o, Operand::Mem(_))),
"{ordinary} does carry a memory operand"
);
assert!(
pc_mem(&ordinary).is_none(),
"{ordinary} is not a literal access"
);
for to in [0x9000u32, 0x2, 0x1_0000] {
assert_eq!(
bytes_at(&ordinary, to),
vec![0x48, 0x68],
"{ordinary} moved to {to:#x}"
);
}
let literal = at(&[0x01, 0x48], 0x1000);
assert!(pc_mem(&literal).is_some(), "{literal} is a literal access");
}
}
#[cfg(test)]
mod secure_gateway_tests {
use super::*;
use crate::isa::{decode_halfwords, Target};
#[test]
fn a_secure_gateway_cannot_be_relocated_to_any_address() {
let sg = decode_halfwords(0xE97F, 0xE97F, 0x1000, Target::V8M).expect("sg decodes");
for to in [0x2000u32, 0x1004, 0x0, 0xFFFF_FFFE] {
let err = relocate(&sg, to).expect_err("sg must never relocate");
assert_eq!(err.reason(), "secure-gateway", "to {to:#x}");
assert_eq!(err.mnemonic(), "sg");
assert_eq!(err.from(), 0x1000);
assert_eq!(err.to(), to);
assert!(
!err.is_address_dependent(),
"a different address cannot help: the address is the problem"
);
assert!(
err.to_string().contains("address it sits at"),
"the message should say why, got: {err}"
);
}
}
#[test]
fn the_other_security_extension_instructions_still_relocate() {
for (hw1, hw2) in [(0x4774u16, 0u16), (0xE841, 0xF000)] {
let insn = decode_halfwords(hw1, hw2, 0x1000, Target::V8M).expect("decodes");
let moved = relocate(&insn, 0x9000).expect("should relocate");
assert_eq!(moved.addr, 0x9000);
assert_eq!(moved.mnemonic, insn.mnemonic);
}
}
}
pub fn widen_compare_branch(
insn: &Insn,
to: u32,
flags: crate::flags::Flags,
) -> Result<Vec<u8>, RelocateError> {
let mnemonic = insn.mnemonic;
let from = insn.addr;
if !matches!(mnemonic, "cbz" | "cbnz") {
return Err(RelocateError::NotEncodable {
mnemonic,
encoding: insn.encoding,
from,
to,
});
}
if to & 1 != 0 {
return Err(RelocateError::Misaligned { mnemonic, from, to });
}
let target = first_target(insn).ok_or(RelocateError::NotEncodable {
mnemonic,
encoding: insn.encoding,
from,
to,
})?;
if !flags.is_empty() {
return Err(RelocateError::FlagsLive {
mnemonic,
from,
to,
live: flags,
});
}
let rn = match insn.operands.get(0) {
Some(Operand::Reg(r)) => r,
_ => {
return Err(RelocateError::NotEncodable {
mnemonic,
encoding: insn.encoding,
from,
to,
})
}
};
if rn.num() > 7 {
return Err(RelocateError::NotEncodable {
mnemonic,
encoding: insn.encoding,
from,
to,
});
}
let cmp = 0x2800u16 | (u16::from(rn.num()) << 8);
let cond = if mnemonic == "cbz" {
Cond::Eq
} else {
Cond::Ne
};
let branch_site = match to.checked_add(2) {
Some(s) => s as usize,
None => {
return Err(RelocateError::OutOfRange {
mnemonic,
from,
to,
target: Some(target),
})
}
};
let branch =
crate::encode_b_cond(branch_site, cond, target).ok_or(RelocateError::OutOfRange {
mnemonic,
from,
to,
target: Some(target),
})?;
let mut out = Vec::with_capacity(2 + branch.len());
out.extend_from_slice(&cmp.to_le_bytes());
out.extend_from_slice(&branch);
Ok(out)
}
#[cfg(test)]
mod compare_branch_tests {
use super::*;
use crate::flags::{live_after, Flags};
use crate::isa::{decode_at_with, Target};
const BOTH_PATHS_CLOBBER: [u8; 12] = [
0x10, 0xb1, 0xd1, 0x18, 0x70, 0x47, 0x00, 0xbf, 0xac, 0x19, 0x70, 0x47, ];
#[test]
fn a_compare_branch_rewrites_when_every_flag_is_dead() {
let cbz = decode_at_with(&BOTH_PATHS_CLOBBER, 0, 0, Target::Union).expect("cbz");
let live = live_after(&BOTH_PATHS_CLOBBER, 0, Target::Union, 8);
assert_eq!(live, Flags::NONE, "the fixture's whole point");
let bytes = widen_compare_branch(&cbz, 0x9000, live).expect("should rewrite");
assert_eq!(bytes.len(), 6);
assert_eq!(&bytes[..2], &0x2800u16.to_le_bytes());
let cmp = decode_at_with(&bytes, 0, 0x9000, Target::Union).expect("cmp decodes");
assert_eq!(cmp.mnemonic, "cmp");
let b = decode_at_with(&bytes, 2, 0x9002, Target::Union).expect("branch decodes");
assert_eq!(b.mnemonic, "b");
assert_eq!(b.cond, Some(Cond::Eq), "cbz branches when zero, so EQ");
assert_eq!(
b.branch_target(),
cbz.branch_target(),
"the rewrite must land on the same target the cbz had"
);
}
#[test]
fn a_compare_branch_nonzero_becomes_a_not_equal_test() {
let mut image = BOTH_PATHS_CLOBBER;
image[1] = 0xb9;
let cbnz = decode_at_with(&image, 0, 0, Target::Union).expect("cbnz");
assert_eq!(cbnz.mnemonic, "cbnz");
let live = live_after(&image, 0, Target::Union, 8);
let bytes = widen_compare_branch(&cbnz, 0x9000, live).expect("should rewrite");
let b = decode_at_with(&bytes, 2, 0x9002, Target::Union).expect("branch");
assert_eq!(b.cond, Some(Cond::Ne));
}
#[test]
fn a_live_overflow_flag_alone_is_enough_to_refuse() {
let image: [u8; 12] = [
0x10, 0xb1, 0x11, 0x40, 0xfd, 0xd6, 0x00, 0xbf, 0xac, 0x19, 0x70, 0x47,
];
let cbz = decode_at_with(&image, 0, 0, Target::Union).expect("cbz");
let live = live_after(&image, 0, Target::Union, 8);
assert!(live.v, "the bvs reads V and the ands did not write it");
let err = widen_compare_branch(&cbz, 0x9000, live).expect_err("must refuse");
assert_eq!(err.reason(), "flags-live");
assert_eq!(err.mnemonic(), "cbz");
assert!(
err.to_string().contains("still live"),
"the message should say why: {err}"
);
}
#[test]
fn only_a_compare_branch_is_rewritten() {
let b = decode_at_with(&[0x00, 0xe0], 0, 0, Target::Union).expect("b");
let err = widen_compare_branch(&b, 0x9000, Flags::NONE).expect_err("not a cbz");
assert_eq!(err.reason(), "not-encodable");
}
#[test]
fn a_compare_branch_without_a_register_is_refused() {
let cbz = decode_at_with(&BOTH_PATHS_CLOBBER, 0, 0, Target::Union).expect("cbz");
let mut no_reg = cbz;
no_reg.operands = [Operand::Target(8)].iter().copied().collect();
let err = widen_compare_branch(&no_reg, 0x9000, Flags::NONE).expect_err("no register");
assert_eq!(err.reason(), "not-encodable");
let mut no_target = cbz;
no_target.operands = [Operand::Reg(Reg(0))].iter().copied().collect();
let err = widen_compare_branch(&no_target, 0x9000, Flags::NONE).expect_err("no target");
assert_eq!(err.reason(), "not-encodable");
}
#[test]
fn a_destination_at_the_top_of_memory_is_refused_not_overflowed() {
let cbz = decode_at_with(&BOTH_PATHS_CLOBBER, 0, 0, Target::Union).expect("cbz");
let err = widen_compare_branch(&cbz, 0xFFFF_FFFE, Flags::NONE)
.expect_err("a near-u32::MAX destination cannot host a stub");
assert_eq!(err.reason(), "out-of-range");
assert_eq!(err.to(), 0xFFFF_FFFE);
}
#[test]
fn an_odd_destination_is_refused_before_anything_else() {
let cbz = decode_at_with(&BOTH_PATHS_CLOBBER, 0, 0, Target::Union).expect("cbz");
let err = widen_compare_branch(&cbz, 0x9001, Flags::NONE).expect_err("odd");
assert_eq!(err.reason(), "misaligned-destination");
}
#[test]
fn the_rewrite_needs_a_low_register() {
let cbz = decode_at_with(&BOTH_PATHS_CLOBBER, 0, 0, Target::Union).expect("cbz");
let mut high = cbz;
high.operands = [Operand::Reg(Reg(9)), Operand::Target(8)]
.iter()
.copied()
.collect();
let err = widen_compare_branch(&high, 0x9000, Flags::NONE).expect_err("r9");
assert_eq!(err.reason(), "not-encodable");
}
#[test]
fn a_target_out_of_reach_is_refused() {
let cbz = decode_at_with(&BOTH_PATHS_CLOBBER, 0, 0, Target::Union).expect("cbz");
let err = widen_compare_branch(&cbz, 0x40_0000, Flags::NONE).expect_err("too far");
assert_eq!(err.reason(), "out-of-range");
}
}