use crate::isa::{Decoder, Insn};
use crate::relocate::{relocate_bytes, RelocateError, Widen};
const FLAG_WALK_LIMIT: usize = 16;
use crate::{encode_b_wide, encode_bl, BranchKind};
const PUSH_LR: [u8; 2] = [0x00, 0xb5];
const LDR_LR_POP: [u8; 4] = [0x5d, 0xf8, 0x04, 0xeb];
const LDR_IP_CONTINUATION: [u8; 4] = [0xdf, 0xf8, 0x04, 0xc0];
const NOP: [u8; 2] = [0x00, 0xbf];
const CONTINUATION_WORD: usize = 8;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Detour {
pub site: usize,
pub displaced: usize,
pub stub: u32,
pub stub_len: usize,
pub kind: BranchKind,
}
impl Detour {
pub fn resume(&self) -> u32 {
(self.site + self.displaced) as u32
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Convention {
CallThenContinue,
HookDecides,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum DetourStyle {
ResumeAfter,
DiscardAndJumpTo(u32),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct DetourOptions {
pub kind: BranchKind,
pub convention: Convention,
pub style: DetourStyle,
pub search_start: usize,
pub stub_at: Option<u32>,
pub rewrite_compare_branches: bool,
pub scan_from: Option<usize>,
pub target: crate::isa::Target,
}
impl Default for DetourOptions {
fn default() -> Self {
DetourOptions {
kind: BranchKind::Bl,
convention: Convention::CallThenContinue,
style: DetourStyle::ResumeAfter,
search_start: 0,
stub_at: None,
rewrite_compare_branches: false,
scan_from: None,
target: crate::isa::Target::Union,
}
}
}
impl DetourOptions {
pub fn new() -> Self {
Self::default()
}
pub fn with_compare_branch_rewriting(mut self, yes: bool) -> Self {
self.rewrite_compare_branches = yes;
self
}
pub fn with_kind(mut self, kind: BranchKind) -> Self {
self.kind = kind;
self
}
pub fn with_convention(mut self, convention: Convention) -> Self {
self.convention = convention;
self
}
pub fn with_style(mut self, style: DetourStyle) -> Self {
self.style = style;
self
}
pub fn with_search_start(mut self, search_start: usize) -> Self {
self.search_start = search_start;
self
}
pub fn with_stub_at(mut self, stub: u32) -> Self {
self.stub_at = Some(stub);
self
}
pub fn with_scan_from(mut self, at: usize) -> Self {
self.scan_from = Some(at);
self
}
pub fn with_target(mut self, target: crate::isa::Target) -> Self {
self.target = target;
self
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum DetourError {
OutOfBounds {
site: usize,
need: usize,
len: usize,
},
Undecodable {
at: usize,
},
ScanStartAfterSite {
scan_from: usize,
site: usize,
},
SiteNotAligned {
site: usize,
scan_from: usize,
},
SiteInItBlock {
site: usize,
},
SplitsItBlock {
site: usize,
displaced: usize,
},
Relocate {
at: u32,
source: RelocateError,
},
NoFreeSpace {
need: usize,
},
StubMisaligned {
stub: u32,
},
StubOverlapsSite {
stub: u32,
site: usize,
},
StubOutOfBounds {
stub: u32,
need: usize,
len: usize,
},
SiteUnreachable {
site: usize,
stub: u32,
kind: BranchKind,
},
HookUnreachable {
from: u32,
hook: u32,
},
ResumeUnreachable {
from: u32,
resume: u32,
},
}
impl DetourError {
pub fn reason(&self) -> &'static str {
match self {
DetourError::OutOfBounds { .. } => "out-of-bounds",
DetourError::Undecodable { .. } => "undecodable",
DetourError::ScanStartAfterSite { .. } => "scan-start-after-site",
DetourError::SiteNotAligned { .. } => "site-not-aligned",
DetourError::SiteInItBlock { .. } => "site-in-it-block",
DetourError::SplitsItBlock { .. } => "splits-it-block",
DetourError::Relocate { .. } => "relocate",
DetourError::NoFreeSpace { .. } => "no-free-space",
DetourError::StubMisaligned { .. } => "stub-misaligned",
DetourError::StubOverlapsSite { .. } => "stub-overlaps-site",
DetourError::StubOutOfBounds { .. } => "stub-out-of-bounds",
DetourError::SiteUnreachable { .. } => "site-unreachable",
DetourError::HookUnreachable { .. } => "hook-unreachable",
DetourError::ResumeUnreachable { .. } => "resume-unreachable",
}
}
fn retryable(&self) -> bool {
matches!(
self,
DetourError::StubOverlapsSite { .. }
| DetourError::StubOutOfBounds { .. }
| DetourError::SiteUnreachable { .. }
| DetourError::HookUnreachable { .. }
| DetourError::ResumeUnreachable { .. }
) || matches!(
self,
DetourError::Relocate { source, .. } if source.is_address_dependent()
)
}
}
impl core::fmt::Display for DetourError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match *self {
DetourError::OutOfBounds { site, need, len } => write!(
f,
"detour at {site:#x}: needs {need} bytes, image is {len:#x} long"
),
DetourError::Undecodable { at } => {
write!(f, "detour: no instruction decodes at {at:#x}")
}
DetourError::ScanStartAfterSite { scan_from, site } => write!(
f,
"detour at {site:#x}: scan_from {scan_from:#x} is past the site"
),
DetourError::SiteNotAligned { site, scan_from } => write!(
f,
"detour at {site:#x}: decoding from {scan_from:#x} steps over it, \
so it is not an instruction boundary"
),
DetourError::SiteInItBlock { site } => {
write!(f, "detour at {site:#x}: the site is inside an IT block")
}
DetourError::SplitsItBlock { site, displaced } => write!(
f,
"detour at {site:#x}: the {displaced} displaced bytes end inside an IT block"
),
DetourError::Relocate { at, source } => {
write!(f, "detour: displaced instruction at {at:#x}: {source}")
}
DetourError::NoFreeSpace { need } => {
write!(f, "detour: no free run of {need} bytes for the stub")
}
DetourError::StubMisaligned { stub } => {
write!(f, "detour: stub address {stub:#x} is not 4-byte aligned")
}
DetourError::StubOverlapsSite { stub, site } => write!(
f,
"detour: a stub at {stub:#x} would overwrite the site at {site:#x}"
),
DetourError::StubOutOfBounds { stub, need, len } => write!(
f,
"detour: a {need}-byte stub at {stub:#x} does not fit in {len:#x} bytes"
),
DetourError::SiteUnreachable { site, stub, kind } => write!(
f,
"detour at {site:#x}: no {kind} reaches the stub at {stub:#x}"
),
DetourError::HookUnreachable { from, hook } => {
write!(
f,
"detour: no branch from {from:#x} reaches the hook {hook:#x}"
)
}
DetourError::ResumeUnreachable { from, resume } => write!(
f,
"detour: no b.w from {from:#x} reaches the resume point {resume:#x}"
),
}
}
}
impl std::error::Error for DetourError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
DetourError::Relocate { source, .. } => Some(source),
_ => None,
}
}
}
pub fn detour(
image: &mut [u8],
site: usize,
hook: u32,
opts: DetourOptions,
) -> Result<Detour, DetourError> {
let plan = plan(image, site, hook & !1, &opts, None)?;
Ok(commit(image, site, plan, &opts))
}
fn commit(image: &mut [u8], site: usize, plan: Plan, opts: &DetourOptions) -> Detour {
crate::write(image, plan.stub as usize, &plan.bytes);
crate::write(image, site, &plan.hook_branch);
debug_assert_eq!(
opts.kind.decode(image, site),
Some(plan.stub),
"the site must read back as the branch that was planned"
);
Detour {
site,
displaced: plan.displaced,
stub: plan.stub,
stub_len: plan.bytes.len(),
kind: opts.kind,
}
}
pub fn tramp(image: &mut [u8], site: usize, hook: u32) -> Result<Detour, DetourError> {
detour(image, site, hook, DetourOptions::default())
}
pub fn detour_in(
image: &mut [u8],
site: usize,
hook: u32,
within: &[core::ops::Range<usize>],
fit: crate::Fit,
opts: DetourOptions,
) -> Result<Detour, DetourError> {
let plan = plan(image, site, hook & !1, &opts, Some((within, fit)))?;
Ok(commit(image, site, plan, &opts))
}
struct Plan {
stub: u32,
bytes: Vec<u8>,
hook_branch: [u8; 4],
displaced: usize,
}
fn plan(
image: &[u8],
site: usize,
hook: u32,
opts: &DetourOptions,
within: Option<(&[core::ops::Range<usize>], crate::Fit)>,
) -> Result<Plan, DetourError> {
if site.checked_add(4).map_or(true, |end| end > image.len()) {
return Err(DetourError::OutOfBounds {
site,
need: 4,
len: image.len(),
});
}
let insns = displaced_at(image, site, opts.scan_from, opts.target)?;
let live: Vec<crate::flags::Flags> = if opts.rewrite_compare_branches {
insns
.iter()
.map(|i| crate::flags::live_after(image, i.addr as usize, opts.target, FLAG_WALK_LIMIT))
.collect()
} else {
vec![crate::flags::Flags::ALL; insns.len()]
};
let displaced: usize = insns.iter().map(|i| i.len()).sum();
let resume = (site + displaced) as u32;
if let Some(stub) = opts.stub_at {
return attempt(
image, site, hook, stub, &insns, &live, resume, displaced, opts,
);
}
let need = prologue_len(opts) + 2 + 4 * insns.len() + 4;
let mut last: Option<DetourError> = None;
let mut from = opts.search_start;
while let Some(found) = match within {
Some((regions, fit)) => {
let rest: Vec<core::ops::Range<usize>> = regions
.iter()
.filter_map(|r| {
let start = r.start.max(from);
if start < r.end {
Some(start..r.end)
} else {
None
}
})
.collect();
if rest.is_empty() {
None
} else {
crate::find_free_space_in(image, need, 4, &rest, fit)
}
}
None => crate::find_free_space(image, need, 4, from),
} {
match attempt(
image,
site,
hook,
found as u32,
&insns,
&live,
resume,
displaced,
opts,
) {
Ok(plan) => return Ok(plan),
Err(e) if e.retryable() => {
last = Some(e);
from = end_of_run(image, found);
}
Err(e) => return Err(e),
}
}
Err(last.unwrap_or(DetourError::NoFreeSpace { need }))
}
#[allow(clippy::too_many_arguments)]
fn attempt(
image: &[u8],
site: usize,
hook: u32,
stub: u32,
insns: &[Insn],
live: &[crate::flags::Flags],
resume: u32,
displaced: usize,
opts: &DetourOptions,
) -> Result<Plan, DetourError> {
if stub % 4 != 0 {
return Err(DetourError::StubMisaligned { stub });
}
let bytes = build_stub(stub, insns, live, hook, resume, site, image.len(), opts)?;
let stub_end = (stub as usize).saturating_add(bytes.len());
if (stub as usize) < site + displaced && site < stub_end {
return Err(DetourError::StubOverlapsSite { stub, site });
}
if stub_end > image.len() {
return Err(DetourError::StubOutOfBounds {
stub,
need: bytes.len(),
len: image.len(),
});
}
let hook_branch = match opts.kind.encode(site, stub) {
Some(bytes) => bytes,
None => {
return Err(DetourError::SiteUnreachable {
site,
stub,
kind: opts.kind,
})
}
};
Ok(Plan {
stub,
bytes,
hook_branch,
displaced,
})
}
fn displaced_at(
image: &[u8],
site: usize,
scan_from: Option<usize>,
target: crate::isa::Target,
) -> Result<Vec<Insn>, DetourError> {
let start = scan_from.unwrap_or(site);
if start > site {
return Err(DetourError::ScanStartAfterSite {
scan_from: start,
site,
});
}
let mut d = Decoder::at(image, start, start as u32).target(target);
while d.pos() < site {
if d.next().is_none() {
return Err(DetourError::Undecodable { at: d.pos() });
}
}
if d.pos() != site {
return Err(DetourError::SiteNotAligned {
site,
scan_from: start,
});
}
if d.it_state().active() {
return Err(DetourError::SiteInItBlock { site });
}
let mut insns = Vec::new();
while d.pos() < site + 4 {
match d.next() {
Some(insn) => insns.push(insn),
None => return Err(DetourError::Undecodable { at: d.pos() }),
}
}
if d.it_state().active() {
return Err(DetourError::SplitsItBlock {
site,
displaced: d.pos() - site,
});
}
Ok(insns)
}
fn prologue_len(opts: &DetourOptions) -> usize {
match opts.convention {
Convention::CallThenContinue => match opts.kind {
BranchKind::Bl => 4,
BranchKind::BWide => 10,
},
Convention::HookDecides => 12,
}
}
#[allow(clippy::too_many_arguments)]
fn build_stub(
stub: u32,
insns: &[Insn],
live: &[crate::flags::Flags],
hook: u32,
resume: u32,
site: usize,
image_len: usize,
opts: &DetourOptions,
) -> Result<Vec<u8>, DetourError> {
let mut out: Vec<u8> = Vec::new();
let addr = |len: usize| -> Result<u32, DetourError> {
u32::try_from(len)
.ok()
.and_then(|l| stub.checked_add(l))
.ok_or(DetourError::StubOutOfBounds {
stub,
need: len,
len: image_len,
})
};
let save_lr = opts.convention == Convention::CallThenContinue && opts.kind == BranchKind::BWide;
match opts.convention {
Convention::CallThenContinue => {
if save_lr {
out.extend_from_slice(&PUSH_LR);
}
let at = stub + out.len() as u32;
let call = encode_bl(at as usize, hook)
.ok_or(DetourError::HookUnreachable { from: at, hook })?;
out.extend_from_slice(&call);
if save_lr {
out.extend_from_slice(&LDR_LR_POP);
}
}
Convention::HookDecides => {
out.extend_from_slice(&LDR_IP_CONTINUATION);
let at = addr(out.len())?;
let jump = encode_b_wide(at as usize, hook)
.ok_or(DetourError::HookUnreachable { from: at, hook })?;
out.extend_from_slice(&jump);
out.extend_from_slice(&[0; 4]);
}
}
if (stub as usize).wrapping_add(out.len()) % 4 != site % 4 {
out.extend_from_slice(&NOP);
}
let body = addr(out.len())?;
if opts.convention == Convention::HookDecides {
let word = (body | 1).to_le_bytes();
out[CONTINUATION_WORD..CONTINUATION_WORD + 4].copy_from_slice(&word);
}
let destination = match opts.style {
DetourStyle::ResumeAfter => resume,
DetourStyle::DiscardAndJumpTo(to) => to & !1,
};
let mut at = body;
if opts.style == DetourStyle::ResumeAfter {
for (i, insn) in insns.iter().enumerate() {
let bytes = match relocate_bytes(insn, at, Widen::IfNeeded) {
Ok(b) => b,
Err(RelocateError::ForwardOnlyBranch { .. }) if opts.rewrite_compare_branches => {
crate::relocate::widen_compare_branch(
insn,
at,
live.get(i).copied().unwrap_or(crate::flags::Flags::ALL),
)
.map_err(|source| DetourError::Relocate {
at: insn.addr,
source,
})?
}
Err(source) => {
return Err(DetourError::Relocate {
at: insn.addr,
source,
})
}
};
at = at.wrapping_add(bytes.len() as u32);
out.extend_from_slice(&bytes);
}
}
let tail = encode_b_wide(at as usize, destination).ok_or(DetourError::ResumeUnreachable {
from: at,
resume: destination,
})?;
out.extend_from_slice(&tail);
Ok(out)
}
fn end_of_run(image: &[u8], from: usize) -> usize {
let tail = &image[from.min(image.len())..];
let n = tail.iter().position(|&b| b != 0xff).unwrap_or(tail.len());
from + n.max(1)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::isa::{self, Insn};
use crate::{decode_b_wide, decode_bl, read_u32, verify_branch, Cond};
const SITE: usize = 0x100;
const FREE: usize = 0x1000;
const HOOK: u32 = 0x80;
const LEN: usize = 0x2000;
fn image_with(code: &[u8]) -> Vec<u8> {
let mut image = vec![0u8; LEN];
for b in image[FREE..].iter_mut() {
*b = 0xff;
}
image[SITE..SITE + code.len()].copy_from_slice(code);
image
}
fn walk(image: &[u8], d: &Detour) -> Vec<Insn> {
Decoder::at(image, d.stub as usize, d.stub)
.take_while(|i| (i.addr as usize) < d.stub as usize + d.stub_len)
.collect()
}
fn text(image: &[u8], d: &Detour) -> Vec<String> {
walk(image, d).iter().map(|i| i.to_string()).collect()
}
#[test]
fn a_displaced_region_of_two_narrow_instructions() {
let mut image = image_with(&[0x01, 0x20, 0x02, 0x21]);
let d = tramp(&mut image, SITE, HOOK).unwrap();
assert_eq!(d.displaced, 4);
assert_eq!(d.resume(), 0x104);
assert_eq!(d.stub, FREE as u32);
assert_eq!(d.stub_len, 12);
assert_eq!(decode_bl(&image, SITE), Some(d.stub));
assert_eq!(
text(&image, &d),
["bl 0x80", "movs r0, #1", "movs r1, #2", "b.w 0x104"]
);
}
#[test]
fn a_displaced_region_of_one_wide_instruction() {
let mut image = image_with(&[0x4f, 0xf0, 0x01, 0x00]);
let d = tramp(&mut image, SITE, HOOK).unwrap();
assert_eq!(d.displaced, 4);
assert_eq!(walk(&image, &d).len(), 3);
assert_eq!(text(&image, &d)[1], "mov.w r0, #1");
assert_eq!(
&image[d.stub as usize + 4..d.stub as usize + 8],
&[0x4f, 0xf0, 0x01, 0x00]
);
}
#[test]
fn a_four_byte_window_that_would_split_an_instruction_extends_to_six() {
let code = [0x01, 0x20, 0x4f, 0xf0, 0x02, 0x01];
let mut image = image_with(&code);
let d = tramp(&mut image, SITE, HOOK).unwrap();
assert_eq!(d.displaced, 6, "the window must cover whole instructions");
assert_eq!(d.resume(), 0x106);
assert_eq!(
text(&image, &d),
["bl 0x80", "movs r0, #1", "mov.w r1, #2", "b.w 0x106"]
);
assert_eq!(
&image[d.stub as usize + 6..d.stub as usize + 10],
&[0x4f, 0xf0, 0x02, 0x01]
);
assert_eq!(decode_bl(&image, SITE), Some(d.stub));
}
#[test]
fn an_undecodable_second_instruction_is_reported() {
let mut image = image_with(&[0x01, 0x20, 0x70, 0xf8, 0x00, 0x00]);
let before = image.clone();
let err = tramp(&mut image, SITE, HOOK).unwrap_err();
assert_eq!(err.reason(), "undecodable");
assert_eq!(err, DetourError::Undecodable { at: SITE + 2 });
assert_eq!(image, before);
}
#[test]
fn a_displaced_region_that_splits_an_it_block_is_refused() {
let mut image = image_with(&[0x04, 0xbf, 0x01, 0x20, 0x02, 0x21]);
let before = image.clone();
let err = tramp(&mut image, SITE, HOOK).unwrap_err();
assert_eq!(err.reason(), "splits-it-block");
assert_eq!(
err,
DetourError::SplitsItBlock {
site: SITE,
displaced: 4
}
);
assert_eq!(image, before, "a refusal must not touch the image");
}
#[test]
fn a_complete_it_block_moves_intact() {
let mut image = image_with(&[0x08, 0xbf, 0x01, 0x20]);
let d = tramp(&mut image, SITE, HOOK).unwrap();
assert_eq!(d.displaced, 4);
let stub = walk(&image, &d);
assert_eq!(stub[1].mnemonic, "it");
assert_eq!(stub[2].cond, Some(Cond::Eq));
assert!(!stub[2].sets_flags);
assert_eq!(
text(&image, &d),
["bl 0x80", "it eq", "moveq r0, #1", "b.w 0x104"]
);
}
#[test]
fn a_site_inside_an_it_block_is_refused_when_the_decode_start_is_known() {
let mut image = image_with(&[0x04, 0xbf, 0x01, 0x20, 0x02, 0x21]);
let before = image.clone();
let opts = DetourOptions::new().with_scan_from(SITE);
let err = detour(&mut image, SITE + 2, HOOK, opts).unwrap_err();
assert_eq!(err.reason(), "site-in-it-block");
assert_eq!(err, DetourError::SiteInItBlock { site: SITE + 2 });
assert_eq!(image, before);
}
#[test]
fn a_site_inside_an_it_block_is_invisible_without_a_decode_start() {
let mut image = image_with(&[0x04, 0xbf, 0x01, 0x20, 0x02, 0x21]);
let d = tramp(&mut image, SITE + 2, HOOK).unwrap();
assert_eq!(walk(&image, &d)[1].cond, None);
}
#[test]
fn a_site_that_is_not_an_instruction_boundary_is_refused() {
let mut image = image_with(&[0x4f, 0xf0, 0x01, 0x00, 0x02, 0x21]);
let before = image.clone();
let opts = DetourOptions::new().with_scan_from(SITE);
let err = detour(&mut image, SITE + 2, HOOK, opts).unwrap_err();
assert_eq!(err.reason(), "site-not-aligned");
assert_eq!(
err,
DetourError::SiteNotAligned {
site: SITE + 2,
scan_from: SITE
}
);
assert_eq!(image, before);
let opts = DetourOptions::new().with_scan_from(SITE + 4);
assert_eq!(
detour(&mut image, SITE, HOOK, opts).unwrap_err().reason(),
"scan-start-after-site"
);
}
#[test]
fn an_unrelocatable_displaced_instruction_leaves_the_image_untouched() {
let mut image = image_with(&[0x20, 0xb1, 0x02, 0x21]);
let before = image.clone();
let err = tramp(&mut image, SITE, HOOK).unwrap_err();
assert_eq!(err.reason(), "relocate");
assert_eq!(
err,
DetourError::Relocate {
at: SITE as u32,
source: RelocateError::ForwardOnlyBranch {
mnemonic: "cbz",
from: SITE as u32,
to: FREE as u32 + 4,
target: 0x10c,
},
}
);
assert_eq!(image, before, "not one byte may change");
assert!(image[FREE..].iter().all(|&b| b == 0xff));
}
#[test]
fn a_displaced_table_branch_leaves_the_image_untouched() {
let mut image = image_with(&[0xd0, 0xe8, 0x01, 0xf0]);
let before = image.clone();
let err = tramp(&mut image, SITE, HOOK).unwrap_err();
assert_eq!(
err,
DetourError::Relocate {
at: SITE as u32,
source: RelocateError::TableBranch {
mnemonic: "tbb",
from: SITE as u32,
to: FREE as u32 + 4,
},
}
);
assert!(!err.retryable());
assert_eq!(image, before);
}
#[test]
fn every_refusal_leaves_the_image_untouched() {
let code = [0x01, 0x20, 0x02, 0x21];
let mut image = vec![0u8; LEN];
image[SITE..SITE + 4].copy_from_slice(&code);
let before = image.clone();
assert_eq!(
tramp(&mut image, SITE, HOOK).unwrap_err().reason(),
"no-free-space"
);
assert_eq!(image, before);
let mut image = image_with(&code);
let before = image.clone();
let err = tramp(&mut image, SITE, 0x4000_0000).unwrap_err();
assert_eq!(err.reason(), "hook-unreachable");
assert_eq!(image, before);
let mut image = image_with(&code);
let before = image.clone();
let opts = DetourOptions::new().with_stub_at(FREE as u32 + 2);
assert_eq!(
detour(&mut image, SITE, HOOK, opts).unwrap_err().reason(),
"stub-misaligned"
);
assert_eq!(image, before);
let mut image = image_with(&code);
let before = image.clone();
let opts = DetourOptions::new().with_stub_at(LEN as u32 - 4);
assert_eq!(
detour(&mut image, SITE, HOOK, opts).unwrap_err().reason(),
"stub-out-of-bounds"
);
assert_eq!(image, before);
let mut image = image_with(&code);
let before = image.clone();
assert_eq!(
tramp(&mut image, LEN - 2, HOOK).unwrap_err().reason(),
"out-of-bounds"
);
assert_eq!(image, before);
let mut image = image_with(&code);
let before = image.clone();
let opts = DetourOptions::new().with_stub_at(SITE as u32);
assert_eq!(
detour(&mut image, SITE, HOOK, opts).unwrap_err().reason(),
"stub-overlaps-site"
);
assert_eq!(image, before);
let mut image = image_with(&code);
let opts = DetourOptions::new().with_stub_at(SITE as u32 - 4);
assert_eq!(
detour(&mut image, SITE, HOOK, opts).unwrap_err().reason(),
"stub-overlaps-site"
);
assert_eq!(image, before);
}
#[test]
fn undecodable_bytes_before_the_site_are_reported() {
let mut image = image_with(&[0x70, 0xf8, 0x00, 0x00, 0x01, 0x20, 0x02, 0x21]);
let before = image.clone();
let opts = DetourOptions::new().with_scan_from(SITE);
let err = detour(&mut image, SITE + 4, HOOK, opts).unwrap_err();
assert_eq!(err.reason(), "undecodable");
assert_eq!(err, DetourError::Undecodable { at: SITE });
assert_eq!(image, before);
let mut image = image_with(&[0x70, 0xf8, 0x00, 0x00, 0x01, 0x20, 0x02, 0x21]);
assert!(tramp(&mut image, SITE + 4, HOOK).is_ok());
}
#[test]
fn the_hook_decides_jump_has_its_own_reach_check() {
let mut image = image_with(&[0x01, 0x20, 0x02, 0x21]);
let before = image.clone();
let opts = DetourOptions::new()
.with_kind(BranchKind::BWide)
.with_convention(Convention::HookDecides);
let err = detour(&mut image, SITE, 0x4000_0000, opts).unwrap_err();
assert_eq!(err.reason(), "hook-unreachable");
assert_eq!(
err,
DetourError::HookUnreachable {
from: FREE as u32 + 4,
hook: 0x4000_0000,
},
"the jump is the stub's second instruction, not its first"
);
assert_eq!(image, before);
let mut image = image_with(&[0x01, 0x20, 0x02, 0x21]);
assert_eq!(
tramp(&mut image, SITE, 0x4000_0000).unwrap_err(),
DetourError::HookUnreachable {
from: FREE as u32,
hook: 0x4000_0000,
}
);
}
#[test]
fn a_stub_that_cannot_branch_back_is_refused() {
let mut image = image_with(&[0x01, 0x20, 0x02, 0x21]);
let before = image.clone();
let stub = 0x0400_0000u32;
let opts = DetourOptions::new().with_stub_at(stub);
let err = detour(&mut image, SITE, stub + 0x100, opts).unwrap_err();
assert_eq!(err.reason(), "resume-unreachable");
assert_eq!(
err,
DetourError::ResumeUnreachable {
from: stub + 8,
resume: SITE as u32 + 4,
}
);
assert!(err.retryable(), "a nearer stub could work");
assert_eq!(image, before, "and nothing was written to find out");
}
#[test]
fn the_site_branch_can_be_the_one_that_does_not_reach() {
let stub = 0x1000u32;
let site = stub as usize + (1 << 24);
assert_eq!(crate::encode_bl(site, stub), None);
assert!(encode_b_wide((stub + 8) as usize, site as u32 + 4).is_some());
let mut image = vec![0u8; site + 0x10];
image[site..site + 4].copy_from_slice(&[0x01, 0x20, 0x02, 0x21]);
let before = image.clone();
let opts = DetourOptions::new().with_stub_at(stub);
let err = detour(&mut image, site, stub + 0x100, opts).unwrap_err();
assert_eq!(err.reason(), "site-unreachable");
assert_eq!(
err,
DetourError::SiteUnreachable {
site,
stub,
kind: BranchKind::Bl,
}
);
assert!(err.retryable(), "a stub four bytes nearer would do");
assert_eq!(image, before);
let mut image = vec![0u8; site + 0x10];
image[site..site + 4].copy_from_slice(&[0x01, 0x20, 0x02, 0x21]);
let opts = DetourOptions::new().with_stub_at(stub + 4);
let d = detour(&mut image, site, stub + 0x100, opts).unwrap();
assert_eq!(d.stub, stub + 4);
assert_eq!(decode_bl(&image, site), Some(stub + 4));
}
#[test]
fn a_successful_detour_is_verifiable_end_to_end() {
let mut image = image_with(&[0x01, 0x20, 0x02, 0x21, 0x03, 0x22]);
let originals = isa::disassemble(&image, SITE, SITE as u32, 2);
let d = tramp(&mut image, SITE, HOOK).unwrap();
assert_eq!(decode_bl(&image, d.site), Some(d.stub));
assert!(verify_branch(&image, d.site, BranchKind::Bl, d.stub).is_ok());
let stub = walk(&image, &d);
assert_eq!(stub[0].mnemonic, "bl");
assert!(stub[0].is_call());
assert_eq!(stub[0].branch_target(), Some(HOOK));
let moved = isa::disassemble(&image, (d.stub + 4) as usize, d.stub + 4, 2);
for (a, b) in originals.iter().zip(&moved) {
assert_eq!(a[10..], b[10..], "{a} vs {b}");
}
let tail = stub.last().unwrap();
assert_eq!((tail.mnemonic, tail.encoding), ("b", "T4"));
assert_eq!(tail.branch_target(), Some(d.resume()));
assert_eq!(decode_b_wide(&image, tail.addr as usize), Some(d.resume()));
assert_eq!(
isa::decode_at(&image, d.resume() as usize)
.unwrap()
.to_string(),
"movs r2, #3"
);
assert!(image[..SITE].iter().all(|&b| b == 0));
assert!(image[SITE + 4..FREE]
.iter()
.all(|&b| b == 0 || b == 0x22 || b == 0x03));
}
#[test]
fn the_consumer_shape_a_cmp_and_a_conditional_branch() {
let mut image = image_with(&[0x32, 0x2a, 0x1d, 0xd8]);
assert_eq!(
isa::disassemble(&image, SITE, SITE as u32, 2),
["00000100: cmp r2, #0x32", "00000102: bhi 0x140"]
);
let d = tramp(&mut image, SITE, HOOK).unwrap();
assert_eq!(d.displaced, 4);
let stub = walk(&image, &d);
assert_eq!(stub[1].to_string(), "cmp r2, #0x32");
assert_eq!(
&image[d.stub as usize + 4..d.stub as usize + 6],
&[0x32, 0x2a]
);
assert_eq!((stub[2].mnemonic, stub[2].encoding), ("b", "T3"));
assert_eq!(stub[2].cond, Some(Cond::Hi));
assert_eq!(stub[2].branch_target(), Some(0x140));
assert_eq!(stub[2].to_string(), "bhi.w 0x140");
assert_eq!(stub[3].branch_target(), Some(0x104));
assert_eq!(d.stub_len, 4 + 2 + 4 + 4);
}
#[test]
fn a_b_wide_site_makes_the_stub_preserve_lr() {
let mut image = image_with(&[0x01, 0x20, 0x02, 0x21]);
let opts = DetourOptions::new().with_kind(BranchKind::BWide);
let d = detour(&mut image, SITE, HOOK, opts).unwrap();
assert_eq!(d.kind, BranchKind::BWide);
assert_eq!(decode_b_wide(&image, SITE), Some(d.stub));
assert_eq!(decode_bl(&image, SITE), None, "a b.w is not a bl");
assert_eq!(
text(&image, &d),
[
"push {lr}",
"bl 0x80",
"ldr lr, [sp], #4",
"nop", "movs r0, #1",
"movs r1, #2",
"b.w 0x104",
]
);
let body = d.stub as usize + 12;
assert_eq!(body % 4, SITE % 4);
assert_eq!(d.stub_len, 2 + 4 + 4 + 2 + 4 + 4);
}
#[test]
fn a_bl_site_does_not_pay_to_preserve_a_dead_lr() {
let mut image = image_with(&[0x01, 0x20, 0x02, 0x21]);
let d = tramp(&mut image, SITE, HOOK).unwrap();
assert_eq!(text(&image, &d)[0], "bl 0x80");
assert_eq!(d.stub_len, 12);
}
#[test]
fn the_hook_decides_convention_hands_over_a_continuation() {
let mut image = image_with(&[0x01, 0x20, 0x02, 0x21]);
let opts = DetourOptions::new()
.with_kind(BranchKind::BWide)
.with_convention(Convention::HookDecides);
let d = detour(&mut image, SITE, HOOK, opts).unwrap();
let stub = d.stub as usize;
let load = isa::decode_at_with(&image, stub, d.stub, isa::Target::Union).unwrap();
assert_eq!(load.mnemonic, "ldr");
assert_eq!(load.branch_target(), Some(d.stub + 8));
assert_eq!(load.to_string(), "ldr.w r12, [pc, #4], 0x1008");
let continuation = d.stub + 12;
assert_eq!(read_u32(&image, stub + CONTINUATION_WORD), continuation | 1);
assert_eq!(decode_b_wide(&image, stub + 4), Some(HOOK));
assert!(
!isa::decode_at_with(&image, stub + 4, d.stub + 4, isa::Target::Union)
.unwrap()
.is_call()
);
assert_eq!(
isa::disassemble(&image, continuation as usize, continuation, 3),
[
format!("{continuation:08x}: movs r0, #1"),
format!("{:08x}: movs r1, #2", continuation + 2),
format!("{:08x}: b.w 0x104", continuation + 4),
]
);
assert_eq!(d.stub_len, 12 + 4 + 4);
}
#[test]
fn the_displaced_block_keeps_the_sites_alignment() {
for site in [SITE, SITE + 2] {
for (kind, convention) in [
(BranchKind::Bl, Convention::CallThenContinue),
(BranchKind::BWide, Convention::CallThenContinue),
(BranchKind::BWide, Convention::HookDecides),
] {
let mut image = vec![0u8; LEN];
for b in image[FREE..].iter_mut() {
*b = 0xff;
}
image[site..site + 4].copy_from_slice(&[0x01, 0x20, 0x02, 0x21]);
let opts = DetourOptions::new()
.with_kind(kind)
.with_convention(convention);
let d = detour(&mut image, site, HOOK, opts).unwrap();
let stub = walk(&image, &d);
let body = stub[stub.len() - 3].addr;
assert_eq!(
body as usize % 4,
site % 4,
"site {site:#x}, {kind}, {convention:?}"
);
}
}
}
#[test]
fn an_explicit_stub_address_is_used_as_given() {
let mut image = image_with(&[0x01, 0x20, 0x02, 0x21]);
let opts = DetourOptions::new().with_stub_at(0x1800);
let d = detour(&mut image, SITE, HOOK, opts).unwrap();
assert_eq!(d.stub, 0x1800);
assert_eq!(decode_bl(&image, SITE), Some(0x1800));
assert!(image[FREE..0x1800].iter().all(|&b| b == 0xff));
}
#[test]
fn the_free_space_search_aligns_its_answer() {
let mut image = image_with(&[0x01, 0x20, 0x02, 0x21]);
image[FREE] = 0x00;
image[FREE + 1] = 0x00;
assert_eq!(crate::find_free_space(&image, 4, 1, 0), Some(FREE + 2));
assert_eq!(crate::find_free_space(&image, 4, 4, 0), Some(FREE + 4));
let d = tramp(&mut image, SITE, HOOK).unwrap();
assert_eq!(d.stub % 4, 0);
assert_eq!(d.stub, FREE as u32 + 4);
}
#[test]
fn a_run_too_short_for_the_stub_is_skipped() {
let mut image = image_with(&[0x01, 0x20, 0x02, 0x21]);
for b in image[0x800..0x804].iter_mut() {
*b = 0xff;
}
let d = tramp(&mut image, SITE, HOOK).unwrap();
assert_eq!(d.stub, FREE as u32, "the island cannot hold a 12-byte stub");
assert!(image[0x800..0x804].iter().all(|&b| b == 0xff));
}
#[test]
fn the_free_space_search_starts_where_it_is_told() {
let code = [0x01u8, 0x20, 0x02, 0x21];
let mut image = image_with(&code);
let opts = DetourOptions::new().with_search_start(FREE + 0x40);
let d = detour(&mut image, SITE, HOOK, opts).unwrap();
assert_eq!(d.stub, FREE as u32 + 0x40);
assert_eq!(decode_bl(&image, SITE), Some(d.stub));
assert!(image[FREE..FREE + 0x40].iter().all(|&b| b == 0xff));
let mut default = image_with(&code);
assert_eq!(tramp(&mut default, SITE, HOOK).unwrap().stub, FREE as u32);
}
#[test]
fn a_wrapped_refusal_is_reachable_as_an_error_source() {
use std::error::Error;
let inner = RelocateError::TableBranch {
mnemonic: "tbb",
from: 0x100,
to: 0x1004,
};
let err = DetourError::Relocate {
at: 0x100,
source: inner,
};
let source = err.source().expect("a relocation refusal has a source");
assert_eq!(source.to_string(), inner.to_string());
assert_eq!(
source
.downcast_ref::<RelocateError>()
.map(RelocateError::reason),
Some("pc-relative-table")
);
assert!(DetourError::NoFreeSpace { need: 12 }.source().is_none());
assert!(DetourError::SiteInItBlock { site: 0x100 }
.source()
.is_none());
}
#[test]
fn end_of_run_always_advances() {
let image = [0xffu8, 0xff, 0x00, 0xff];
assert_eq!(end_of_run(&image, 0), 2);
assert_eq!(end_of_run(&image, 2), 3);
assert_eq!(end_of_run(&image, 3), 4);
assert_eq!(end_of_run(&image, 4), 5);
assert_eq!(end_of_run(&image, 99), 100);
}
#[test]
fn the_hand_written_prologue_instructions_decode_as_intended() {
assert_eq!(
isa::decode_at_with(&PUSH_LR, 0, 0x1000, isa::Target::Union)
.unwrap()
.to_string(),
"push {lr}"
);
assert_eq!(
isa::decode_at_with(&LDR_LR_POP, 0, 0x1000, isa::Target::Union)
.unwrap()
.to_string(),
"ldr lr, [sp], #4"
);
assert_eq!(
isa::decode_at_with(&NOP, 0, 0x1000, isa::Target::Union)
.unwrap()
.to_string(),
"nop"
);
let load =
isa::decode_at_with(&LDR_IP_CONTINUATION, 0, 0x1000, isa::Target::Union).unwrap();
assert_eq!(load.to_string(), "ldr.w r12, [pc, #4], 0x1008");
assert_eq!(load.branch_target(), Some(0x1008));
}
#[test]
fn reason_strings_are_stable() {
let all = [
(
DetourError::OutOfBounds {
site: 0,
need: 4,
len: 2,
},
"out-of-bounds",
),
(DetourError::Undecodable { at: 2 }, "undecodable"),
(
DetourError::ScanStartAfterSite {
scan_from: 4,
site: 2,
},
"scan-start-after-site",
),
(
DetourError::SiteNotAligned {
site: 2,
scan_from: 0,
},
"site-not-aligned",
),
(DetourError::SiteInItBlock { site: 2 }, "site-in-it-block"),
(
DetourError::SplitsItBlock {
site: 2,
displaced: 4,
},
"splits-it-block",
),
(
DetourError::Relocate {
at: 2,
source: RelocateError::TableBranch {
mnemonic: "tbb",
from: 2,
to: 4,
},
},
"relocate",
),
(DetourError::NoFreeSpace { need: 12 }, "no-free-space"),
(DetourError::StubMisaligned { stub: 2 }, "stub-misaligned"),
(
DetourError::StubOverlapsSite { stub: 2, site: 0 },
"stub-overlaps-site",
),
(
DetourError::StubOutOfBounds {
stub: 2,
need: 12,
len: 4,
},
"stub-out-of-bounds",
),
(
DetourError::SiteUnreachable {
site: 0,
stub: 2,
kind: BranchKind::Bl,
},
"site-unreachable",
),
(
DetourError::HookUnreachable { from: 0, hook: 2 },
"hook-unreachable",
),
(
DetourError::ResumeUnreachable { from: 0, resume: 2 },
"resume-unreachable",
),
];
for (err, reason) in all {
assert_eq!(err.reason(), reason);
assert!(!err.to_string().is_empty());
}
}
#[test]
fn only_address_dependent_refusals_are_retried() {
assert!(DetourError::SiteUnreachable {
site: 0,
stub: 2,
kind: BranchKind::Bl
}
.retryable());
assert!(DetourError::Relocate {
at: 0,
source: RelocateError::OutOfRange {
mnemonic: "b",
from: 0,
to: 2,
target: Some(4)
}
}
.retryable());
assert!(!DetourError::Relocate {
at: 0,
source: RelocateError::TableBranch {
mnemonic: "tbb",
from: 0,
to: 2
}
}
.retryable());
assert!(!DetourError::SplitsItBlock {
site: 0,
displaced: 4
}
.retryable());
}
#[test]
fn tramp_is_detour_with_the_defaults() {
let code = [0x01, 0x20, 0x02, 0x21];
let mut a = image_with(&code);
let mut b = image_with(&code);
let one = tramp(&mut a, SITE, HOOK).unwrap();
let two = detour(&mut b, SITE, HOOK, DetourOptions::default()).unwrap();
assert_eq!(one, two);
assert_eq!(a, b);
}
#[test]
fn the_hooks_thumb_bit_is_masked_off() {
let code = [0x01, 0x20, 0x02, 0x21];
let mut a = image_with(&code);
let mut b = image_with(&code);
assert_eq!(
tramp(&mut a, SITE, HOOK).unwrap(),
tramp(&mut b, SITE, HOOK | 1).unwrap()
);
assert_eq!(a, b);
}
#[test]
fn the_stub_prologue_is_exactly_as_long_as_the_instructions_in_it() {
let opts = |c: Convention, k: BranchKind| DetourOptions {
convention: c,
kind: k,
..DetourOptions::default()
};
assert_eq!(
prologue_len(&opts(Convention::CallThenContinue, BranchKind::Bl)),
4
);
assert_eq!(
prologue_len(&opts(Convention::CallThenContinue, BranchKind::BWide)),
10
);
assert_eq!(
prologue_len(&opts(Convention::HookDecides, BranchKind::Bl)),
12
);
assert_eq!(
prologue_len(&opts(Convention::HookDecides, BranchKind::BWide)),
12
);
}
#[test]
fn discard_and_jump_to_omits_the_displaced_instructions() {
let code = [0x01, 0x20, 0x02, 0x21];
let mut resumed = image_with(&code);
let r = detour(&mut resumed, SITE, HOOK, DetourOptions::new()).unwrap();
let resumed_text = text(&resumed, &r);
let elsewhere = (SITE + 0x40) as u32;
let mut jumped = image_with(&code);
let j = detour(
&mut jumped,
SITE,
HOOK,
DetourOptions::new().with_style(DetourStyle::DiscardAndJumpTo(elsewhere)),
)
.unwrap();
let jumped_text = text(&jumped, &j);
assert!(
resumed_text.iter().any(|t| t == "movs r0, #1"),
"resume stub should relocate the displaced instructions: {resumed_text:?}"
);
assert!(
!jumped_text.iter().any(|t| t.starts_with("movs")),
"discarding stub must not carry them: {jumped_text:?}"
);
assert!(
j.stub_len < r.stub_len,
"discarding four bytes of displaced code should make the stub shorter: \
{} vs {}",
j.stub_len,
r.stub_len
);
assert_eq!(resumed[SITE..SITE + 4], jumped[SITE..SITE + 4]);
let tail = walk(&jumped, &j).pop().expect("a tail branch");
assert_eq!(tail.branch_target(), Some(elsewhere));
assert_ne!(tail.branch_target(), Some(r.resume()));
}
#[test]
fn discard_and_jump_to_ignores_the_thumb_bit_on_its_destination() {
let code = [0x01, 0x20, 0x02, 0x21];
let to = (SITE + 0x40) as u32;
let mut a = image_with(&code);
let mut b = image_with(&code);
let da = detour(
&mut a,
SITE,
HOOK,
DetourOptions::new().with_style(DetourStyle::DiscardAndJumpTo(to)),
)
.unwrap();
let db = detour(
&mut b,
SITE,
HOOK,
DetourOptions::new().with_style(DetourStyle::DiscardAndJumpTo(to | 1)),
)
.unwrap();
assert_eq!(a, b, "the Thumb bit must not change a byte");
assert_eq!(da.stub, db.stub);
}
#[test]
fn discard_and_jump_to_refuses_a_destination_out_of_branch_range() {
let mut image = image_with(&[0x01, 0x20, 0x02, 0x21]);
let err = detour(
&mut image,
SITE,
HOOK,
DetourOptions::new().with_style(DetourStyle::DiscardAndJumpTo(0x7F00_0000)),
)
.expect_err("out of range must not encode");
assert_eq!(err.reason(), "resume-unreachable");
assert_eq!(image, image_with(&[0x01, 0x20, 0x02, 0x21]));
}
#[test]
fn with_style_defaults_to_resuming() {
assert_eq!(DetourOptions::new().style, DetourStyle::ResumeAfter);
assert_eq!(DetourOptions::default().style, DetourStyle::ResumeAfter);
let o = DetourOptions::new().with_style(DetourStyle::DiscardAndJumpTo(0x200));
assert_eq!(o.style, DetourStyle::DiscardAndJumpTo(0x200));
assert_eq!(o.kind, DetourOptions::new().kind);
assert_eq!(o.convention, DetourOptions::new().convention);
}
#[test]
fn the_space_the_search_asks_for_covers_the_stub_that_gets_written() {
let fixtures: [&[u8]; 3] = [
&[0x01, 0x20, 0x02, 0x21], &[0x32, 0x2A, 0x1D, 0xD8], &[0x01, 0x20, 0x4F, 0xF0, 0x02, 0x01], ];
for code in fixtures {
for site in [SITE, SITE + 2] {
for (kind, convention) in [
(BranchKind::Bl, Convention::CallThenContinue),
(BranchKind::BWide, Convention::CallThenContinue),
(BranchKind::BWide, Convention::HookDecides),
] {
let mut image = vec![0u8; LEN];
for b in image[FREE..].iter_mut() {
*b = 0xFF;
}
image[site..site + code.len()].copy_from_slice(code);
let opts = DetourOptions::new()
.with_kind(kind)
.with_convention(convention);
let insns =
displaced_at(&image, site, None, crate::isa::Target::Union).unwrap();
let need = prologue_len(&opts) + 2 + 4 * insns.len() + 4;
let d = detour(&mut image, site, HOOK, opts).unwrap();
assert!(
d.stub_len <= need,
"site {site:#x} {kind} {convention:?}: stub {} exceeds the \
{need} bytes the search asked for",
d.stub_len
);
}
}
}
}
#[test]
fn a_run_shorter_than_the_stub_is_never_written_into() {
let mut image = vec![0u8; LEN];
image[SITE..SITE + 4].copy_from_slice(&[0x32, 0x2A, 0x1D, 0xD8]);
for b in image[FREE..FREE + 12].iter_mut() {
*b = 0xFF;
}
let before = image.clone();
assert_eq!(
tramp(&mut image, SITE, HOOK).unwrap_err().reason(),
"no-free-space"
);
assert_eq!(image, before, "a refusal must leave every byte alone");
}
#[test]
fn a_decode_start_at_the_site_itself_is_accepted() {
let mut image = image_with(&[0x01, 0x20, 0x02, 0x21]);
let d = detour(
&mut image,
SITE,
HOOK,
DetourOptions::new().with_scan_from(SITE),
)
.expect("the site is a decode start like any other");
assert_eq!(d.displaced, 4);
let mut image = image_with(&[0x01, 0x20, 0x02, 0x21]);
assert_eq!(
detour(
&mut image,
SITE,
HOOK,
DetourOptions::new().with_scan_from(SITE + 2)
)
.unwrap_err()
.reason(),
"scan-start-after-site"
);
}
#[test]
fn a_stub_that_abuts_the_displaced_region_does_not_overlap_it() {
let mut image = vec![0u8; LEN];
image[SITE..SITE + 4].copy_from_slice(&[0x01, 0x20, 0x02, 0x21]);
for b in image[SITE + 4..].iter_mut() {
*b = 0xFF;
}
let opts = DetourOptions::new()
.with_stub_at(SITE as u32 + 4)
.with_style(DetourStyle::DiscardAndJumpTo(0x200));
let d = detour(&mut image, SITE, HOOK, opts)
.expect("abutting the displaced region is not overlapping it");
assert_eq!(d.stub, SITE as u32 + 4);
}
#[test]
fn the_planner_admits_a_site_that_ends_at_the_image_end() {
let mut image = vec![0u8; LEN];
for b in image[0x10..0x80].iter_mut() {
*b = 0xFF;
}
image[LEN - 4..].copy_from_slice(&[0x01, 0x20, 0x02, 0x21]);
let d = detour(
&mut image,
LEN - 4,
HOOK,
DetourOptions::new().with_stub_at(0x10),
)
.expect("exactly four bytes of room is enough, as install_branch says");
assert_eq!(d.resume(), LEN as u32);
}
}
#[cfg(test)]
mod stub_address_tests {
use super::*;
#[test]
fn a_stub_at_the_top_of_memory_is_refused_not_overflowed() {
for &(stub, hook) in &[(0xFFFF_FFFCu32, 0xFFFF_F800u32), (0xFFFF_F000, 0xFFFF_F800)] {
let mut image = vec![0u8; 0x20];
image[0..4].copy_from_slice(&[0x01, 0x20, 0x02, 0x21]);
let err = detour(&mut image, 0, hook, DetourOptions::new().with_stub_at(stub))
.expect_err("a near-top-of-memory stub cannot be written");
assert_eq!(err.reason(), "stub-out-of-bounds", "stub {stub:#x}");
assert_eq!(&image[0..4], &[0x01, 0x20, 0x02, 0x21]);
}
}
#[test]
fn a_top_of_memory_stub_overflows_the_hook_decides_layout_too() {
let mut image = vec![0u8; 0x20];
image[0..4].copy_from_slice(&[0x01, 0x20, 0x02, 0x21]);
let err = detour(
&mut image,
0,
0xFFFF_F800,
DetourOptions::new()
.with_stub_at(0xFFFF_FFFC)
.with_convention(Convention::HookDecides),
)
.expect_err("the continuation-load offset pushes the hook branch past u32::MAX");
assert_eq!(err.reason(), "stub-out-of-bounds");
assert_eq!(&image[0..4], &[0x01, 0x20, 0x02, 0x21]);
}
}
#[cfg(test)]
mod region_tests {
use super::*;
use crate::Fit;
fn image_with_two_runs() -> Vec<u8> {
let mut image = vec![0u8; 0x600];
image[0x100..0x104].copy_from_slice(&[0x10, 0xb5, 0x00, 0xbf]);
for b in image[0x200..0x280].iter_mut() {
*b = 0xff;
}
for b in image[0x400..0x500].iter_mut() {
*b = 0xff;
}
image
}
#[test]
fn the_stub_goes_only_where_the_caller_says_it_may() {
let mut image = image_with_two_runs();
let region = 0x400usize..0x500;
let regions = core::slice::from_ref(®ion);
let d = detour_in(
&mut image,
0x100,
0x300,
regions,
Fit::First,
DetourOptions::default(),
)
.expect("a stub should fit in the declared region");
assert!(
(0x400..0x500).contains(&(d.stub as usize)),
"stub at {:#x} is outside the declared region",
d.stub
);
let mut plain = image_with_two_runs();
let p = detour(&mut plain, 0x100, 0x300, DetourOptions::default())
.expect("the whole-image search should also succeed");
assert!(
(0x200..0x280).contains(&(p.stub as usize)),
"unconstrained search should take the first run, got {:#x}",
p.stub
);
}
#[test]
fn no_declared_region_means_no_stub_rather_than_a_different_one() {
let mut image = image_with_two_runs();
let empty = 0x300usize..0x340;
let deny = core::slice::from_ref(&empty);
let err = detour_in(
&mut image,
0x100,
0x300,
deny,
Fit::First,
DetourOptions::default(),
)
.expect_err("there is no free space in the declared region");
assert_eq!(err.reason(), "no-free-space");
assert_eq!(&image[0x100..0x104], &[0x10, 0xb5, 0x00, 0xbf]);
}
#[test]
fn an_empty_region_list_places_nothing() {
let mut image = image_with_two_runs();
let err = detour_in(
&mut image,
0x100,
0x300,
&[],
Fit::First,
DetourOptions::default(),
)
.expect_err("no regions means no placement");
assert_eq!(err.reason(), "no-free-space");
assert_eq!(&image[0x100..0x104], &[0x10, 0xb5, 0x00, 0xbf]);
}
#[test]
fn an_odd_hook_address_is_masked_to_its_halfword_boundary() {
let region = 0x400usize..0x500;
let regions = core::slice::from_ref(®ion);
let mut odd = image_with_two_runs();
let from_odd = detour_in(
&mut odd,
0x100,
0x301,
regions,
Fit::First,
DetourOptions::default(),
)
.expect("an odd hook is a Thumb function pointer, not an error");
let mut even = image_with_two_runs();
let from_even = detour_in(
&mut even,
0x100,
0x300,
regions,
Fit::First,
DetourOptions::default(),
)
.expect("the same hook, already even");
assert_eq!(
from_odd.stub, from_even.stub,
"the Thumb bit must not change where the stub goes"
);
assert_eq!(
odd, even,
"0x301 and 0x300 must produce byte-identical images"
);
}
#[test]
fn a_region_behind_the_search_start_is_skipped_not_clamped() {
let mut image = image_with_two_runs();
let d = detour_in(
&mut image,
0x100,
0x300,
&[0x200..0x280, 0x400..0x500],
Fit::First,
DetourOptions::default().with_search_start(0x300),
)
.expect("the later region is still usable");
assert!(
(0x400..0x500).contains(&(d.stub as usize)),
"stub at {:#x} should be in the region after the search start",
d.stub
);
}
#[test]
fn fit_largest_reaches_past_the_first_usable_run() {
let mut image = image_with_two_runs();
let d = detour_in(
&mut image,
0x100,
0x300,
&[0x200..0x280, 0x400..0x500],
Fit::Largest,
DetourOptions::default(),
)
.expect("a stub should fit");
assert!(
(0x400..0x500).contains(&(d.stub as usize)),
"Fit::Largest should take the 0x100-byte run, got {:#x}",
d.stub
);
}
}
#[cfg(test)]
mod compare_branch_rewrite_tests {
use super::*;
fn image_with_a_dead_flag_cbz() -> Vec<u8> {
let mut image = vec![0u8; 0x600];
image[0x100..0x10c].copy_from_slice(&[
0x10, 0xb1, 0xd1, 0x18, 0xac, 0x19, 0x00, 0xbf, 0xac, 0x19, 0x70, 0x47,
]);
for b in image[0x400..0x500].iter_mut() {
*b = 0xff;
}
image
}
#[test]
fn a_displaced_compare_branch_is_refused_unless_rewriting_is_asked_for() {
let mut image = image_with_a_dead_flag_cbz();
let err = detour(&mut image, 0x100, 0x300, DetourOptions::default())
.expect_err("cbz cannot reach a stub");
assert_eq!(err.reason(), "relocate");
let text = err.to_string();
assert!(text.contains("forward-only-branch"));
}
#[test]
fn a_dead_flag_compare_branch_is_rewritten_when_asked() {
let mut image = image_with_a_dead_flag_cbz();
let d = detour(
&mut image,
0x100,
0x300,
DetourOptions::default().with_compare_branch_rewriting(true),
)
.expect("the flags are dead, so the rewrite is sound");
let text = crate::isa::disassemble(&image, d.stub as usize, d.stub, 8).join("\n");
assert!(text.contains("cmp r0, #0"));
assert!(text.contains("beq"));
assert!(!text.contains("cbz"));
}
#[test]
fn a_live_flag_still_refuses_even_when_rewriting_is_asked_for() {
let mut image = image_with_a_dead_flag_cbz();
image[0x102..0x106].copy_from_slice(&[0x11, 0x40, 0xfd, 0xd6]);
let err = detour(
&mut image,
0x100,
0x300,
DetourOptions::default().with_compare_branch_rewriting(true),
)
.expect_err("V is live, so the rewrite is unsound");
assert_eq!(err.reason(), "relocate");
let text = err.to_string();
assert!(text.contains("flags-live"));
assert!(text.contains("v: true"));
}
}