use thumb_asm::analysis::{self, Xref, XrefKind};
use thumb_asm::{
encode_b_wide, encode_bl, find, find_bl_sites, install_branch, isa, read_u32, verify_branch,
BranchKind, Needle,
};
const TABLE: usize = 0x0080;
const CALL_A: usize = 0x1004;
const CALL_B: usize = 0x1044;
const TAIL_CALL: usize = 0x1082;
const JUMP_TABLE: usize = 0x1100;
const ADR_SITE: usize = 0x11f0;
const GATE: u32 = 0x1200;
const REPLACEMENT: u32 = 0x1300;
const SIGNATURE: [u8; 4] = [0x03, 0x48, 0x5a, 0x28];
fn main() {
let mut image = build_image();
println!("thumb-asm · redirecting a call site");
println!("==================================\n");
let (entry, policy) = locate(&image);
let refs = who_references(&image, GATE);
redirect(&mut image, &refs);
confirm(&image);
println!(
"proved: a 4-byte signature resolved to the function entry at \
{entry:#06x}, whose pc-relative load fetches {policy:#04x}; every \
reference to it found instruction-accurately, including one a \
fixed-stride scan reports and no processor will ever execute; and two \
of those references repointed to {REPLACEMENT:#06x} with the branch \
kind each site can survive, each verified by decoding the image back."
);
}
fn locate(image: &[u8]) -> (usize, u32) {
section("1. find the function");
let hit = find(image, Needle::Bytes(&SIGNATURE), 0).expect("the signature is in the image");
let again = find(image, Needle::Bytes(&SIGNATURE), hit + 1);
println!(" signature {SIGNATURE:02x?} (ldr r0, [pc, #12] · cmp r0, #0x5a)");
println!(" first match {hit:#06x}");
println!(" next match {}\n", maybe(again));
assert_eq!(hit, 0x1202);
assert_eq!(again, None);
let entry = analysis::function_start(image, hit, 64).expect("a prologue within 64 bytes");
println!(" function_start(image, {hit:#06x}, 64) -> {entry:#06x}");
show(image, entry, entry as u32, 4);
println!();
assert_eq!(entry, GATE as usize);
let handler = read_u32(image, TABLE);
let from_pointer = analysis::function_start(image, handler as usize, 64);
println!(" dispatch table at {TABLE:#06x} holds {handler:#010x} (Thumb bit set)");
println!(
" function_start(image, {handler:#06x}, 64) -> {}\n",
maybe(from_pointer)
);
assert_eq!(handler, GATE | 1);
assert_eq!(from_pointer, Some(GATE as usize));
section("2. read what the function loads");
let ldr = entry + 2;
let policy = analysis::literal_value(image, ldr).expect("a pc-relative word load");
println!(" {}", isa::disassemble(image, ldr, ldr as u32, 1)[0]);
println!(" literal_value(image, {ldr:#06x}) -> {policy:#04x}");
println!(
" the pool word lives at {:#06x} = Align({:#06x} + 4, 4) + 12\n",
isa::decode_at(image, ldr)
.and_then(|i| i.branch_target())
.expect("the decoder resolves the pool address"),
ldr,
);
assert_eq!(policy, 0x5a);
assert_eq!(
isa::decode_at(image, ldr).and_then(|i| i.branch_target()),
Some(0x1210),
"Align(0x1206, 4) is 0x1204, not 0x1206"
);
(entry, policy)
}
fn who_references(image: &[u8], target: u32) -> Vec<Xref> {
section("3. every reference to it");
let refs = analysis::xrefs(image, target);
print_xrefs(image, &refs);
let kinds: Vec<XrefKind> = refs.iter().map(|x| x.kind).collect();
assert_eq!(
kinds,
[
XrefKind::LiteralPool, XrefKind::Call, XrefKind::Call, XrefKind::Branch, XrefKind::PcRelativeAddress ]
);
assert_eq!(refs[3].via, Some("b"), "a tail call is encoded as a branch");
assert_eq!(
refs[0].via, None,
"a stored pointer is data and has no mnemonic"
);
let scanned = find_bl_sites(image, target);
let walked: Vec<usize> = refs
.iter()
.filter(|x| x.kind == XrefKind::Call)
.map(|x| x.at)
.collect();
println!(" fixed-stride scan vs instruction-accurate walk");
println!(" ----------------------------------------------");
println!(" find_bl_sites -> {}", offsets(&scanned));
println!(" xrefs (Call) -> {}\n", offsets(&walked));
for at in &scanned {
if !walked.contains(at) {
println!(" {at:#06x} is not an instruction boundary. In phase it reads:");
show(image, JUMP_TABLE, JUMP_TABLE as u32, 2);
println!(" …and out of phase, starting one halfword in:");
println!(" {}", isa::disassemble(image, *at, *at as u32, 1)[0]);
println!();
}
}
assert_eq!(walked, [CALL_A, CALL_B]);
assert_eq!(
scanned,
[CALL_A, CALL_B, JUMP_TABLE + 2],
"the blind scan reports a third site"
);
assert_eq!(
isa::decode_at(image, JUMP_TABLE).map(|i| (i.mnemonic, i.len())),
Some(("tbb", 4)),
"0x1100..0x1104 is one instruction; 0x1102 is its second halfword"
);
refs
}
fn redirect(image: &mut [u8], refs: &[Xref]) {
section("4. redirect two of them");
let call = refs
.iter()
.find(|x| x.kind == XrefKind::Call)
.expect("at least one direct call");
let before = isa::disassemble(image, call.at, call.at as u32, 1)[0].clone();
install_branch(image, call.at, BranchKind::Bl, REPLACEMENT | 1)
.expect("a 4-byte site well within ±16 MB");
println!(" {:#06x} {before}", call.at);
println!(
" -> {}\n",
isa::disassemble(image, call.at, call.at as u32, 1)[0]
);
assert!(verify_branch(image, call.at, BranchKind::Bl, REPLACEMENT).is_ok());
assert!(verify_branch(image, call.at, BranchKind::Bl, REPLACEMENT | 1).is_ok());
let tail = refs
.iter()
.find(|x| x.kind == XrefKind::Branch)
.expect("the tail call");
let before = isa::disassemble(image, tail.at, tail.at as u32, 1)[0].clone();
install_branch(image, tail.at, BranchKind::BWide, REPLACEMENT).expect("same width, same range");
println!(" {:#06x} {before}", tail.at);
println!(
" -> {} (b.w, not bl: lr is the outer function's)\n",
isa::disassemble(image, tail.at, tail.at as u32, 1)[0]
);
let as_bl = encode_bl(tail.at, REPLACEMENT).expect("in range");
let as_bw = encode_b_wide(tail.at, REPLACEMENT).expect("in range");
assert_eq!(as_bl[0..2], as_bw[0..2], "hw1 is identical");
assert_eq!(
u16::from_le_bytes([as_bl[2], as_bl[3]]) ^ u16::from_le_bytes([as_bw[2], as_bw[3]]),
0x4000,
"hw2 differs in bit 14 and nothing else"
);
assert!(verify_branch(image, tail.at, BranchKind::BWide, REPLACEMENT).is_ok());
let wrong = verify_branch(image, tail.at, BranchKind::Bl, REPLACEMENT).unwrap_err();
assert_eq!(wrong.found, None);
println!(" left alone: the dispatch-table word at {TABLE:#06x} (data, not a branch)");
println!(" the `adr` at {ADR_SITE:#06x} (±1020 bytes of Align(PC,4))\n");
}
fn confirm(image: &[u8]) {
section("5. confirm, by reading the image back");
let old = analysis::xrefs(image, GATE);
let new = analysis::xrefs(image, REPLACEMENT);
println!(" references to the gate at {GATE:#06x}:");
print_xrefs(image, &old);
println!(" references to the replacement at {REPLACEMENT:#06x}:");
print_xrefs(image, &new);
assert_eq!(
old.iter().map(|x| (x.at, x.kind)).collect::<Vec<_>>(),
[
(TABLE, XrefKind::LiteralPool),
(CALL_B, XrefKind::Call),
(ADR_SITE, XrefKind::PcRelativeAddress),
]
);
assert_eq!(
new.iter().map(|x| (x.at, x.kind)).collect::<Vec<_>>(),
[(CALL_A, XrefKind::Call), (TAIL_CALL, XrefKind::Branch)]
);
assert_eq!(find_bl_sites(image, GATE), [CALL_B, JUMP_TABLE + 2]);
println!();
}
fn section(title: &str) {
println!("{title}");
println!("{}\n", "-".repeat(title.chars().count()));
}
fn maybe(o: Option<usize>) -> String {
match o {
Some(v) => format!("{v:#06x}"),
None => "none".to_string(),
}
}
fn offsets(v: &[usize]) -> String {
if v.is_empty() {
return "none".to_string();
}
let items: Vec<String> = v.iter().map(|o| format!("{o:#06x}")).collect();
format!("[{}]", items.join(", "))
}
fn show(image: &[u8], at: usize, addr: u32, count: usize) {
for line in isa::disassemble(image, at, addr, count) {
println!(" {line}");
}
}
fn print_xrefs(image: &[u8], refs: &[Xref]) {
println!(" offset kind via what is there");
println!(" -------- ------------------ ----- --------------------------");
for x in refs {
let what = match x.kind {
XrefKind::LiteralPool => format!(".word {:#010x}", read_u32(image, x.at)),
_ => isa::decode_at(image, x.at)
.map(|i| i.to_string())
.unwrap_or_else(|| "?".to_string()),
};
println!(
" {:08x} {:<18} {:<5} {}",
x.at,
format!("{:?}", x.kind),
x.via.unwrap_or("-"),
what
);
}
println!();
}
fn build_image() -> Vec<u8> {
let mut image = vec![0u8; 0x4000];
thumb_asm::write(&mut image, TABLE, &(GATE | 1).to_le_bytes());
put(&mut image, 0x1000, &[0xb510, 0x2000]); bl(&mut image, CALL_A, GATE);
put(&mut image, 0x1008, &[0xbd10]);
put(&mut image, 0x1040, &[0xb510, 0x2001]);
bl(&mut image, CALL_B, GATE);
put(&mut image, 0x1048, &[0xbd10]);
put(&mut image, 0x1080, &[0x2002]); thumb_asm::write(
&mut image,
TAIL_CALL,
&encode_b_wide(TAIL_CALL, GATE).expect("in range"),
);
put(&mut image, JUMP_TABLE, &[0xe8d3, 0xf000]);
put(&mut image, JUMP_TABLE + 4, &[0xf87d]);
assert_eq!(
encode_bl(JUMP_TABLE + 2, GATE).expect("in range"),
image[JUMP_TABLE + 2..JUMP_TABLE + 6],
"the phantom is a real BL encoding at an address that is not one"
);
put(&mut image, ADR_SITE, &[0xa003, 0x4770]);
put(
&mut image,
GATE as usize,
&[
0xb510, 0x4803, 0x285a, 0xd001, 0x2001, 0xbd10, 0x2000, 0xbd10, ],
);
thumb_asm::write(&mut image, 0x1210, &0x5au32.to_le_bytes());
put(&mut image, REPLACEMENT as usize, &[0xb510, 0x2000, 0xbd10]);
image
}
fn bl(image: &mut [u8], at: usize, target: u32) {
thumb_asm::write(image, at, &encode_bl(at, target).expect("in range"));
}
fn put(image: &mut [u8], at: usize, halfwords: &[u16]) {
for (i, hw) in halfwords.iter().enumerate() {
thumb_asm::write(image, at + i * 2, &hw.to_le_bytes());
}
}