use core::{cmp::Ordering, marker::PhantomData, ops::Range};
use alloc::vec::Vec;
use gimli::{
CfaRule, CieOrFde, DebugFrame, DwEhPe, EhFrame, EhFrameHdr, Encoding, EndianSlice, Evaluation,
EvaluationResult, EvaluationStorage, Expression, LittleEndian, Location, ParsedEhFrameHdr,
Reader, ReaderOffset, Register, RegisterRule, UnwindContext, UnwindContextStorage,
UnwindOffset, UnwindSection, UnwindTableRow, Value, Vendor,
};
pub(crate) use gimli::BaseAddresses;
use crate::{arch::Arch, unwind_result::UnwindResult, ModuleSectionInfo};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DwarfUnwinderError {
FdeFromOffsetFailed(gimli::Error),
UnwindInfoForAddressFailed(gimli::Error),
StackPointerMovedBackwards,
DidNotAdvance,
CouldNotRecoverCfa,
CouldNotRecoverReturnAddress,
CouldNotRecoverFramePointer,
}
impl core::fmt::Display for DwarfUnwinderError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::FdeFromOffsetFailed(err) => {
write!(f, "Could not get the FDE for the supplied offset: {err}")
}
Self::UnwindInfoForAddressFailed(err) => write!(
f,
"Could not find DWARF unwind info for the requested address: {err}"
),
Self::StackPointerMovedBackwards => write!(f, "Stack pointer moved backwards"),
Self::DidNotAdvance => write!(f, "Did not advance"),
Self::CouldNotRecoverCfa => write!(f, "Could not recover the CFA"),
Self::CouldNotRecoverReturnAddress => write!(f, "Could not recover the return address"),
Self::CouldNotRecoverFramePointer => write!(f, "Could not recover the frame pointer"),
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for DwarfUnwinderError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::FdeFromOffsetFailed(e) => Some(e),
Self::UnwindInfoForAddressFailed(e) => Some(e),
_ => None,
}
}
}
pub(crate) fn register_rule_to_cfa_offset<RO: ReaderOffset>(
rule: Option<&RegisterRule<RO>>,
) -> Option<Option<i64>> {
match rule {
None | Some(RegisterRule::Undefined) | Some(RegisterRule::SameValue) => Some(None),
Some(RegisterRule::Offset(offset)) => Some(Some(*offset)),
_ => None,
}
}
pub trait DwarfUnwinding: Arch {
const CFI_VENDOR: Vendor = Vendor::Default;
fn unwind_frame<F, R, UCS, ES>(
section: &impl UnwindSection<R>,
unwind_info: &UnwindTableRow<R::Offset, UCS>,
encoding: Encoding,
regs: &mut Self::UnwindRegs,
is_first_frame: bool,
read_stack: &mut F,
) -> Result<UnwindResult<Self::UnwindRule>, DwarfUnwinderError>
where
F: FnMut(u64) -> Result<u64, ()>,
R: Reader,
UCS: UnwindContextStorage<R::Offset>,
ES: EvaluationStorage<R>;
fn rule_if_uncovered_by_fde() -> Self::UnwindRule;
}
pub enum UnwindSectionType {
EhFrame,
DebugFrame,
}
pub struct DwarfUnwinder<'a, R, A, UCS>
where
R: Reader,
A: DwarfUnwinding,
UCS: UnwindContextStorage<R::Offset>,
{
unwind_section_data: R,
unwind_section_type: UnwindSectionType,
eh_frame_hdr: Option<ParsedEhFrameHdr<EndianSlice<'a, R::Endian>>>,
unwind_context: &'a mut UnwindContext<R::Offset, UCS>,
base_svma: u64,
bases: BaseAddresses,
_arch: PhantomData<A>,
}
impl<'a, R, A, UCS> DwarfUnwinder<'a, R, A, UCS>
where
R: Reader,
A: DwarfUnwinding,
UCS: UnwindContextStorage<R::Offset>,
{
pub fn new(
unwind_section_data: R,
unwind_section_type: UnwindSectionType,
eh_frame_hdr_data: Option<&'a [u8]>,
unwind_context: &'a mut UnwindContext<R::Offset, UCS>,
bases: BaseAddresses,
base_svma: u64,
) -> Self {
let eh_frame_hdr = match eh_frame_hdr_data {
Some(eh_frame_hdr_data) => {
let hdr = EhFrameHdr::new(eh_frame_hdr_data, unwind_section_data.endian());
hdr.parse(&bases, 8).ok()
}
None => None,
};
Self {
unwind_section_data,
unwind_section_type,
eh_frame_hdr,
unwind_context,
bases,
base_svma,
_arch: PhantomData,
}
}
pub fn get_fde_offset_for_relative_address(&self, rel_lookup_address: u32) -> Option<u32> {
let lookup_svma = self.base_svma + rel_lookup_address as u64;
let eh_frame_hdr = self.eh_frame_hdr.as_ref()?;
let table = eh_frame_hdr.table()?;
let (first_address, _) = table.iter(&self.bases).next().ok()??;
if lookup_svma < first_address.direct().ok()? {
return None;
}
let fde_ptr = table.lookup(lookup_svma, &self.bases).ok()?;
let fde_offset = table.pointer_to_offset(fde_ptr).ok()?;
fde_offset.0.into_u64().try_into().ok()
}
pub fn unwind_frame_with_fde<F, ES>(
&mut self,
regs: &mut A::UnwindRegs,
is_first_frame: bool,
rel_lookup_address: u32,
fde_offset: u32,
read_stack: &mut F,
) -> Result<UnwindResult<A::UnwindRule>, DwarfUnwinderError>
where
F: FnMut(u64) -> Result<u64, ()>,
ES: EvaluationStorage<R>,
{
let lookup_svma = self.base_svma + rel_lookup_address as u64;
let unwind_section_data = self.unwind_section_data.clone();
match self.unwind_section_type {
UnwindSectionType::EhFrame => {
let mut eh_frame = EhFrame::from(unwind_section_data);
eh_frame.set_address_size(8);
eh_frame.set_vendor(A::CFI_VENDOR);
self.unwind_frame_in_section::<_, F, ES>(
&eh_frame,
lookup_svma,
fde_offset,
regs,
is_first_frame,
read_stack,
)
}
UnwindSectionType::DebugFrame => {
let mut debug_frame = DebugFrame::from(unwind_section_data);
debug_frame.set_address_size(8);
debug_frame.set_vendor(A::CFI_VENDOR);
self.unwind_frame_in_section::<_, F, ES>(
&debug_frame,
lookup_svma,
fde_offset,
regs,
is_first_frame,
read_stack,
)
}
}
}
fn unwind_frame_in_section<US, F, ES>(
&mut self,
unwind_section: &US,
lookup_svma: u64,
fde_offset: u32,
regs: &mut A::UnwindRegs,
is_first_frame: bool,
read_stack: &mut F,
) -> Result<UnwindResult<A::UnwindRule>, DwarfUnwinderError>
where
US: UnwindSection<R>,
F: FnMut(u64) -> Result<u64, ()>,
ES: EvaluationStorage<R>,
{
let fde = unwind_section.fde_from_offset(
&self.bases,
US::Offset::from(R::Offset::from_u32(fde_offset)),
US::cie_from_offset,
);
let fde = fde.map_err(DwarfUnwinderError::FdeFromOffsetFailed)?;
let encoding = fde.cie().encoding();
let unwind_info = match fde.unwind_info_for_address(
unwind_section,
&self.bases,
self.unwind_context,
lookup_svma,
) {
Ok(unwind_info) => unwind_info,
Err(error) => {
return Ok(UnwindResult::ExecRuleWithFallback(
A::rule_if_uncovered_by_fde(),
DwarfUnwinderError::UnwindInfoForAddressFailed(error).into(),
));
}
};
A::unwind_frame::<F, R, UCS, ES>(
unwind_section,
unwind_info,
encoding,
regs,
is_first_frame,
read_stack,
)
}
}
pub(crate) fn base_addresses_and_text_range<D>(
section_info: &mut impl ModuleSectionInfo<D>,
) -> (BaseAddresses, Option<Range<u64>>) {
let text_range = section_info.section_svma_range(b"__text");
let text_start = text_range
.clone()
.or_else(|| section_info.section_svma_range(b".text"))
.map(|range| range.start)
.unwrap_or_default();
let mut start_addr = |names: &[&[u8]]| -> u64 {
names
.iter()
.find_map(|name| section_info.section_svma_range(name))
.map(|r| r.start)
.unwrap_or_default()
};
let bases = BaseAddresses::default()
.set_eh_frame(start_addr(&[b"__eh_frame", b".eh_frame"]))
.set_eh_frame_hdr(start_addr(&[b"__eh_frame_hdr", b".eh_frame_hdr"]))
.set_text(text_start)
.set_got(start_addr(&[b"__got", b".got"]));
(bases, text_range)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DwarfCfiIndexError {
Gimli(gimli::Error),
CouldNotSubtractBaseAddress,
RelativeAddressTooBig,
FdeOffsetTooBig,
}
impl core::fmt::Display for DwarfCfiIndexError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::Gimli(e) => write!(f, "EhFrame processing failed: {e}"),
Self::CouldNotSubtractBaseAddress => {
write!(f, "Could not subtract base address to create relative pc")
}
Self::RelativeAddressTooBig => write!(f, "Relative address did not fit into u32"),
Self::FdeOffsetTooBig => write!(f, "FDE offset did not fit into u32"),
}
}
}
impl From<gimli::Error> for DwarfCfiIndexError {
fn from(e: gimli::Error) -> Self {
Self::Gimli(e)
}
}
#[cfg(feature = "std")]
impl std::error::Error for DwarfCfiIndexError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Gimli(e) => Some(e),
_ => None,
}
}
}
pub struct DwarfCfiIndex {
sorted_fde_pc_starts: Vec<u32>,
fde_offsets: Vec<u32>,
}
impl DwarfCfiIndex {
pub fn try_new<R, US>(
unwind_section: US,
bases: &BaseAddresses,
base_svma: u64,
) -> Result<Self, DwarfCfiIndexError>
where
R: Reader,
R::Offset: TryInto<u32>,
US: UnwindSection<R>,
{
let mut fde_pc_and_offset = Vec::new();
let mut cur_cie = None;
let mut entries_iter = unwind_section.entries(bases);
while let Some(entry) = entries_iter.next()? {
let fde = match entry {
CieOrFde::Cie(cie) => {
cur_cie = Some(cie);
continue;
}
CieOrFde::Fde(partial_fde) => {
partial_fde.parse(|unwind_section, bases, cie_offset| {
if let Some(cie) = &cur_cie {
if cie.offset()
== <US::Offset as UnwindOffset<R::Offset>>::into(cie_offset)
{
return Ok(cie.clone());
}
}
let cie = unwind_section.cie_from_offset(bases, cie_offset);
if let Ok(cie) = &cie {
cur_cie = Some(cie.clone());
}
cie
})?
}
};
let pc = fde.initial_address();
let relative_pc = pc
.checked_sub(base_svma)
.ok_or(DwarfCfiIndexError::CouldNotSubtractBaseAddress)?;
let relative_pc = u32::try_from(relative_pc)
.map_err(|_| DwarfCfiIndexError::RelativeAddressTooBig)?;
let fde_offset = <R::Offset as TryInto<u32>>::try_into(fde.offset())
.map_err(|_| DwarfCfiIndexError::FdeOffsetTooBig)?;
fde_pc_and_offset.push((relative_pc, fde_offset));
}
fde_pc_and_offset.sort_by_key(|(pc, _)| *pc);
let sorted_fde_pc_starts = fde_pc_and_offset.iter().map(|(pc, _)| *pc).collect();
let fde_offsets = fde_pc_and_offset.into_iter().map(|(_, fde)| fde).collect();
Ok(Self {
sorted_fde_pc_starts,
fde_offsets,
})
}
pub fn try_new_eh_frame(
eh_frame_data: &[u8],
bases: &BaseAddresses,
base_svma: u64,
) -> Result<Self, DwarfCfiIndexError> {
let mut eh_frame = EhFrame::from(EndianSlice::new(eh_frame_data, LittleEndian));
eh_frame.set_address_size(8);
Self::try_new(eh_frame, bases, base_svma)
}
pub fn try_new_debug_frame(
debug_frame_data: &[u8],
bases: &BaseAddresses,
base_svma: u64,
) -> Result<Self, DwarfCfiIndexError> {
let mut debug_frame = DebugFrame::from(EndianSlice::new(debug_frame_data, LittleEndian));
debug_frame.set_address_size(8);
Self::try_new(debug_frame, bases, base_svma)
}
pub fn fde_offset_for_relative_address(&self, rel_lookup_address: u32) -> Option<u32> {
let i = match self.sorted_fde_pc_starts.binary_search(&rel_lookup_address) {
Err(0) => return None,
Ok(i) => i,
Err(i) => i - 1,
};
Some(self.fde_offsets[i])
}
}
pub struct EhFrameHdrTable {
fde_count: usize,
base_svma: u64,
eh_frame_hdr_svma: u64,
eh_frame_ptr: u64,
}
impl EhFrameHdrTable {
const TABLE_OFFSET: usize = 12;
const ROW_SIZE: usize = 8;
pub fn try_new(
eh_frame_hdr_data: &[u8],
bases: &BaseAddresses,
base_svma: u64,
) -> Option<Self> {
let [1, eh_frame_ptr_enc, fde_count_enc, table_enc] = *eh_frame_hdr_data.first_chunk()?
else {
return None;
};
if !matches!(
DwEhPe(eh_frame_ptr_enc).format(),
gimli::DW_EH_PE_udata4 | gimli::DW_EH_PE_sdata4
) || DwEhPe(fde_count_enc) != gimli::DW_EH_PE_udata4
|| DwEhPe(table_enc) != DwEhPe(gimli::DW_EH_PE_datarel.0 | gimli::DW_EH_PE_sdata4.0)
{
return None;
}
let hdr = EhFrameHdr::new(eh_frame_hdr_data, LittleEndian)
.parse(bases, 8)
.ok()?;
let eh_frame_ptr = hdr.eh_frame_ptr().direct().ok()?;
let fde_count = u32::from_le_bytes(*eh_frame_hdr_data.get(8..)?.first_chunk()?);
let fde_count = usize::try_from(fde_count).ok()?;
let table_end = fde_count
.checked_mul(Self::ROW_SIZE)?
.checked_add(Self::TABLE_OFFSET)?;
if fde_count == 0 || table_end > eh_frame_hdr_data.len() {
return None;
}
Some(Self {
fde_count,
base_svma,
eh_frame_hdr_svma: bases.eh_frame_hdr.data?,
eh_frame_ptr,
})
}
pub fn fde_offset_for_relative_address(
&self,
eh_frame_hdr_data: &[u8],
rel_lookup_address: u32,
) -> Option<u32> {
let lookup_svma = self.base_svma + rel_lookup_address as u64;
let table = eh_frame_hdr_data.get(Self::TABLE_OFFSET..)?;
if lookup_svma < self.read_pointer(table, 0)? {
return None;
}
let mut row = 0;
let mut len = self.fde_count;
while len > 1 {
let pivot = row + len / 2;
match self
.read_pointer(table, pivot * Self::ROW_SIZE)?
.cmp(&lookup_svma)
{
Ordering::Equal => {
row = pivot;
break;
}
Ordering::Less => {
row = pivot;
len -= len / 2;
}
Ordering::Greater => len /= 2,
}
}
let fde_ptr = self.read_pointer(table, row * Self::ROW_SIZE + 4)?;
fde_ptr.checked_sub(self.eh_frame_ptr)?.try_into().ok()
}
fn read_pointer(&self, table: &[u8], offset: usize) -> Option<u64> {
let value = i32::from_le_bytes(*table.get(offset..)?.first_chunk()?);
Some(self.eh_frame_hdr_svma.wrapping_add(value as i64 as u64))
}
}
pub trait DwarfUnwindRegs {
fn get(&self, register: Register) -> Option<u64>;
}
pub fn eval_cfa_rule<R, F, UR, S>(
section: &impl UnwindSection<R>,
rule: &CfaRule<R::Offset>,
encoding: Encoding,
regs: &UR,
read_stack: &mut F,
) -> Option<u64>
where
R: Reader,
F: FnMut(u64) -> Result<u64, ()>,
UR: DwarfUnwindRegs,
S: EvaluationStorage<R>,
{
match rule {
CfaRule::RegisterAndOffset { register, offset } => {
let val = regs.get(*register)?;
u64::try_from(i64::try_from(val).ok()?.checked_add(*offset)?).ok()
}
CfaRule::Expression(expr) => {
let expr = expr.get(section).ok()?;
eval_expr::<R, F, UR, S>(expr, encoding, regs, read_stack)
}
}
}
const MAX_EXPRESSION_ITERATIONS: u32 = 1024;
fn eval_expr<R, F, UR, S>(
expr: Expression<R>,
encoding: Encoding,
regs: &UR,
read_stack: &mut F,
) -> Option<u64>
where
R: Reader,
F: FnMut(u64) -> Result<u64, ()>,
UR: DwarfUnwindRegs,
S: EvaluationStorage<R>,
{
let mut eval = Evaluation::<R, S>::new_in(expr.0, encoding);
eval.set_max_iterations(MAX_EXPRESSION_ITERATIONS);
let mut result = eval.evaluate().ok()?;
loop {
match result {
EvaluationResult::Complete => break,
EvaluationResult::RequiresRegister { register, .. } => {
let value = regs.get(register)?;
result = eval.resume_with_register(Value::Generic(value)).ok()?;
}
EvaluationResult::RequiresMemory {
address,
size,
space,
..
} => {
if space.is_some() || size != encoding.address_size {
return None;
}
let value = read_stack(address).ok()?;
result = eval.resume_with_memory(Value::Generic(value)).ok()?;
}
_ => return None,
}
}
let x = &eval.as_result().last()?.location;
if let Location::Address { address } = x {
Some(*address)
} else {
None
}
}
pub fn eval_register_rule<R, F, UR, S>(
section: &impl UnwindSection<R>,
rule: Option<RegisterRule<R::Offset>>,
cfa: u64,
encoding: Encoding,
val: u64,
regs: &UR,
read_stack: &mut F,
) -> Option<u64>
where
R: Reader,
F: FnMut(u64) -> Result<u64, ()>,
UR: DwarfUnwindRegs,
S: EvaluationStorage<R>,
{
let rule = rule?;
match rule {
RegisterRule::Undefined => None,
RegisterRule::SameValue => Some(val),
RegisterRule::Offset(offset) => {
let cfa_plus_offset =
u64::try_from(i64::try_from(cfa).ok()?.checked_add(offset)?).ok()?;
read_stack(cfa_plus_offset).ok()
}
RegisterRule::ValOffset(offset) => {
u64::try_from(i64::try_from(cfa).ok()?.checked_add(offset)?).ok()
}
RegisterRule::Register(register) => regs.get(register),
RegisterRule::Expression(expr) => {
let expr = expr.get(section).ok()?;
let val = eval_expr::<R, F, UR, S>(expr, encoding, regs, read_stack)?;
read_stack(val).ok()
}
RegisterRule::ValExpression(expr) => {
let expr = expr.get(section).ok()?;
eval_expr::<R, F, UR, S>(expr, encoding, regs, read_stack)
}
RegisterRule::Architectural => {
None
}
RegisterRule::Constant(value) => Some(value),
}
}
#[cfg(test)]
pub(crate) mod tests {
use alloc::vec;
use gimli::{AArch64, DebugFrame, Format, StoreOnHeap, UnwindExpression, X86_64};
use crate::{
aarch64::UnwindRegsAarch64,
x86_64::{Reg, UnwindRegsX86_64},
};
use super::*;
pub(crate) const X86_64_CIE: [u8; 10] = [
1,
0,
1,
0x78,
X86_64::RA.0 as u8,
gimli::DW_CFA_def_cfa.0,
X86_64::RSP.0 as u8,
8,
gimli::DW_CFA_offset.0 | X86_64::RA.0 as u8,
1,
];
pub(crate) const AARCH64_CIE: [u8; 8] = [
1,
0,
4,
0x78,
AArch64::X30.0 as u8,
gimli::DW_CFA_def_cfa.0,
AArch64::SP.0 as u8,
0,
];
pub(crate) fn eh_frame_with_fde(
cie: &[u8],
range: Range<u64>,
instructions: &[u8],
) -> (Vec<u8>, u32) {
let mut data = (4 + cie.len() as u32).to_le_bytes().to_vec();
data.extend(0u32.to_le_bytes());
data.extend(cie);
let fde_offset = data.len() as u32;
data.extend((20 + instructions.len() as u32).to_le_bytes());
data.extend((fde_offset + 4).to_le_bytes());
data.extend(range.start.to_le_bytes());
data.extend((range.end - range.start).to_le_bytes());
data.extend(instructions);
(data, fde_offset)
}
#[test]
fn header_lookup_rejects_addresses_before_its_first_entry() {
use crate::x86_64::ArchX86_64;
for base in [0, 0x1_0000_0000_u64] {
let encoding = gimli::DW_EH_PE_udata8.0;
let mut header = vec![1, encoding, encoding, encoding];
header.extend_from_slice(&0x9000_u64.to_le_bytes());
header.extend_from_slice(&2_u64.to_le_bytes());
for (address, fde) in [(base + 0x1000, 0x9020_u64), (base + 0x2000, 0x9040)] {
header.extend_from_slice(&address.to_le_bytes());
header.extend_from_slice(&fde.to_le_bytes());
}
let mut context = UnwindContext::<usize, StoreOnHeap>::new_in();
let unwinder = DwarfUnwinder::<_, ArchX86_64, _>::new(
EndianSlice::new(&[], LittleEndian),
UnwindSectionType::EhFrame,
Some(&header),
&mut context,
BaseAddresses::default(),
base,
);
for (address, expected) in [
(0x0fff, None),
(0x1000, Some(0x20)),
(0x1fff, Some(0x20)),
(0x2000, Some(0x40)),
] {
assert_eq!(
unwinder.get_fde_offset_for_relative_address(address),
expected
);
}
}
}
#[test]
fn eh_frame_hdr_table_matches_gimli_lookup() {
use crate::x86_64::ArchX86_64;
let mut header = vec![1, 0x1b, 0x03, 0x3b];
header.extend_from_slice(&0xfc_i32.to_le_bytes());
header.extend_from_slice(&5_u32.to_le_bytes());
for (address, fde) in [
(-0x8000_i32, 0x100_i32),
(-0x7000, 0x120),
(-0x7000, 0x140),
(-0x7000, 0x160),
(-0x6000, 0x180),
] {
header.extend_from_slice(&address.to_le_bytes());
header.extend_from_slice(&fde.to_le_bytes());
}
let bases = BaseAddresses::default().set_eh_frame_hdr(0x9000);
let table = EhFrameHdrTable::try_new(&header, &bases, 0).unwrap();
let mut context = UnwindContext::<usize, StoreOnHeap>::new_in();
let unwinder = DwarfUnwinder::<_, ArchX86_64, _>::new(
EndianSlice::new(&[], LittleEndian),
UnwindSectionType::EhFrame,
Some(&header),
&mut context,
bases.clone(),
0,
);
for address in 0..0x4000 {
assert_eq!(
table.fde_offset_for_relative_address(&header, address),
unwinder.get_fde_offset_for_relative_address(address),
"{address:#x}"
);
}
}
#[test]
fn eh_frame_and_debug_frame_preserve_unwind_and_error_outcomes() {
use crate::error::UnwinderError;
use crate::x86_64::{ArchX86_64, UnwindRuleX86_64};
for section_type in [UnwindSectionType::EhFrame, UnwindSectionType::DebugFrame] {
let cie_id = match section_type {
UnwindSectionType::EhFrame => 0u32,
UnwindSectionType::DebugFrame => u32::MAX,
};
let mut data = 14u32.to_le_bytes().to_vec();
data.extend(cie_id.to_le_bytes());
data.extend(X86_64_CIE);
let fde_offset = data.len() as u32;
let cie_pointer = match section_type {
UnwindSectionType::EhFrame => fde_offset + 4,
UnwindSectionType::DebugFrame => 0,
};
data.extend(20u32.to_le_bytes());
data.extend(cie_pointer.to_le_bytes());
data.extend(0x1000u64.to_le_bytes());
data.extend(0x10u64.to_le_bytes());
let mut context = UnwindContext::<usize, StoreOnHeap>::new_in();
let mut unwinder = DwarfUnwinder::<_, ArchX86_64, _>::new(
EndianSlice::new(&data, LittleEndian),
section_type,
None,
&mut context,
BaseAddresses::default(),
0,
);
let mut regs = UnwindRegsX86_64::new(0x1000, 0x2000, 0x3000);
let mut read_stack = |_| panic!("a cacheable rule does not read the stack");
assert!(matches!(
unwinder.unwind_frame_with_fde::<_, StoreOnHeap>(
&mut regs,
true,
0x1000,
fde_offset,
&mut read_stack,
),
Ok(UnwindResult::ExecRuleWithDwarfRegisterRules(
UnwindRuleX86_64::OffsetSp { sp_offset_by_8: 1 },
0,
))
));
assert!(matches!(
unwinder.unwind_frame_with_fde::<_, StoreOnHeap>(
&mut regs,
true,
0x2000,
fde_offset,
&mut read_stack,
),
Ok(UnwindResult::ExecRuleWithFallback(
UnwindRuleX86_64::JustReturnIfFirstFrameOtherwiseFp,
UnwinderError::Dwarf(DwarfUnwinderError::UnwindInfoForAddressFailed(_)),
))
));
assert!(matches!(
unwinder.unwind_frame_with_fde::<_, StoreOnHeap>(
&mut regs,
true,
0x1000,
u32::MAX,
&mut read_stack,
),
Err(DwarfUnwinderError::FdeFromOffsetFailed(_))
));
}
}
#[test]
fn aarch64_return_address_signing_does_not_abort_dwarf_unwinding() {
use crate::aarch64::ArchAarch64;
let (data, fde_offset) = eh_frame_with_fde(
&AARCH64_CIE,
0x1000..0x1040,
&[gimli::DW_CFA_AARCH64_negate_ra_state.0],
);
let mut context = UnwindContext::<usize, StoreOnHeap>::new_in();
let mut unwinder = DwarfUnwinder::<_, ArchAarch64, _>::new(
EndianSlice::new(&data, LittleEndian),
UnwindSectionType::EhFrame,
None,
&mut context,
BaseAddresses::default(),
0,
);
let mut regs = UnwindRegsAarch64::new(0x1024, 0x8000, 0x9000);
let result = unwinder.unwind_frame_with_fde::<_, StoreOnHeap>(
&mut regs,
true,
0x1010,
fde_offset,
&mut |_| Err(()),
);
assert!(matches!(result, Ok(UnwindResult::ExecRule(_))));
}
fn unwind_x86_64_fde(
instructions: &[u8],
address: u32,
regs: &mut UnwindRegsX86_64,
read_stack: &mut impl FnMut(u64) -> Result<u64, ()>,
) -> Result<UnwindResult<crate::x86_64::UnwindRuleX86_64>, DwarfUnwinderError> {
use crate::x86_64::ArchX86_64;
let (data, fde_offset) = eh_frame_with_fde(&X86_64_CIE, 0x1000..0x1010, instructions);
let mut context = UnwindContext::<usize, StoreOnHeap>::new_in();
DwarfUnwinder::<_, ArchX86_64, _>::new(
EndianSlice::new(&data, LittleEndian),
UnwindSectionType::EhFrame,
None,
&mut context,
BaseAddresses::default(),
0,
)
.unwind_frame_with_fde::<_, StoreOnHeap>(regs, false, address, fde_offset, read_stack)
}
#[test]
fn memory_backed_cfa_below_the_return_address_slot_is_an_error() {
let instructions = [gimli::DW_CFA_def_cfa_expression.0, 3, 0x76, 0x78, 0x06];
let mut regs = UnwindRegsX86_64::new(0x1000, 0x2000, 0x3000);
let mut read_stack = |address| match address {
0x2ff8 => Ok(4),
_ => Err(()),
};
assert!(matches!(
unwind_x86_64_fde(&instructions, 0x1004, &mut regs, &mut read_stack),
Err(DwarfUnwinderError::CouldNotRecoverReturnAddress)
));
}
#[test]
fn undefined_return_address_ends_the_stack_even_with_saved_registers() {
use crate::x86_64::UnwindRuleX86_64;
let instructions = [
gimli::DW_CFA_undefined.0,
X86_64::RA.0 as u8,
gimli::DW_CFA_offset.0 | X86_64::RBX.0 as u8,
2,
];
let mut regs = UnwindRegsX86_64::new(0x1004, 0x2000, 0x3000);
let result = unwind_x86_64_fde(&instructions, 0x1004, &mut regs, &mut |_| Ok(0x5555));
assert!(
matches!(
result,
Ok(UnwindResult::ExecRuleWithDwarfRegisterRules(
UnwindRuleX86_64::EndOfStack,
0,
))
),
"{result:?}"
);
}
fn encoding() -> Encoding {
Encoding {
address_size: 8,
format: Format::Dwarf32,
version: 4,
}
}
#[test]
fn eval_cfa_expression_can_read_memory_with_x86_64_regs() {
let expression = [0x76, 0x58, 0x06];
let mut section = DebugFrame::from(EndianSlice::new(&expression, LittleEndian));
section.set_address_size(8);
let rule = CfaRule::Expression(UnwindExpression {
offset: 0,
length: expression.len(),
});
let regs = UnwindRegsX86_64::new(0, 0, 0x1000);
let mut unreadable_stack = |_| Err(());
assert_eq!(
eval_cfa_rule::<_, _, _, StoreOnHeap>(
§ion,
&rule,
encoding(),
®s,
&mut unreadable_stack,
),
None
);
let mut read_stack = |address| {
assert_eq!(address, 0xfd8);
Ok(0x2000)
};
assert_eq!(
eval_cfa_rule::<_, _, _, StoreOnHeap>(
§ion,
&rule,
encoding(),
®s,
&mut read_stack,
),
Some(0x2000)
);
}
#[test]
fn eval_cfa_expression_can_read_memory_with_aarch64_regs() {
let expression = [0x8d, 0x70, 0x06];
let mut section = DebugFrame::from(EndianSlice::new(&expression, LittleEndian));
section.set_address_size(8);
let rule = CfaRule::Expression(UnwindExpression {
offset: 0,
length: expression.len(),
});
let regs = UnwindRegsAarch64::new(0, 0, 0x3000);
assert_eq!(DwarfUnwindRegs::get(®s, AArch64::X29), Some(0x3000));
let mut read_stack = |address| {
assert_eq!(address, 0x2ff0);
Ok(0x4000)
};
assert_eq!(
eval_cfa_rule::<_, _, _, StoreOnHeap>(
§ion,
&rule,
encoding(),
®s,
&mut read_stack,
),
Some(0x4000)
);
}
#[test]
fn eval_cfa_expression_rejects_partial_memory_reads() {
let expression = [0x76, 0x58, 0x94, 0x04];
let mut section = DebugFrame::from(EndianSlice::new(&expression, LittleEndian));
section.set_address_size(8);
let rule = CfaRule::Expression(UnwindExpression {
offset: 0,
length: expression.len(),
});
let regs = UnwindRegsX86_64::new(0, 0, 0x1000);
let mut read_stack =
|_: u64| -> Result<u64, ()> { panic!("partial memory reads are unsupported") };
assert_eq!(
eval_cfa_rule::<_, _, _, StoreOnHeap>(
§ion,
&rule,
encoding(),
®s,
&mut read_stack,
),
None
);
}
#[cfg(feature = "std")]
#[test]
fn eval_rejects_looping_expressions() {
let expression: &[u8] = &[0x2f, 0xfd, 0xff];
let mut section = DebugFrame::from(EndianSlice::new(expression, LittleEndian));
section.set_address_size(8);
let rule = CfaRule::Expression(UnwindExpression {
offset: 0,
length: expression.len(),
});
let regs = UnwindRegsX86_64::new(0x1000, 0x2000, 0x3000);
let (sender, receiver) = std::sync::mpsc::channel();
std::thread::spawn(move || {
sender.send(eval_cfa_rule::<_, _, _, StoreOnHeap>(
§ion,
&rule,
encoding(),
®s,
&mut |_| Err(()),
))
});
let result = receiver.recv_timeout(std::time::Duration::from_secs(2));
assert_eq!(result, Ok(None));
}
#[test]
fn x86_64_dwarf_regs_expose_provided_general_purpose_registers() {
let mut regs = UnwindRegsX86_64::new(0, 0, 0);
assert_eq!(DwarfUnwindRegs::get(®s, X86_64::R10), None);
regs.set(Reg::R10, 0x1234);
assert_eq!(DwarfUnwindRegs::get(®s, X86_64::R10), Some(0x1234));
assert_eq!(DwarfUnwindRegs::get(®s, X86_64::R11), None);
}
}