//! Exception handling and stack unwinding for x64. //! //! Exception information is exposed via the [`ExceptionData`] structure. If present in a PE file, //! it contains a list of [`RuntimeFunction`] entries that can be used to get [`UnwindInfo`] for a //! particular code location. //! //! Unwind information contains a list of unwind codes which specify the operations that are //! necessary to restore registers (including the stack pointer RSP) when unwinding out of a //! function. //! //! Depending on where the instruction pointer lies, there are three strategies to unwind: //! //! 1. If the RIP is within an epilog, then control is leaving the function, there can be no //! exception handler associated with this exception for this function, and the effects of the //! epilog must be continued to compute the context of the caller function. To determine if the //! RIP is within an epilog, the code stream from RIP on is examined. If that code stream can be //! matched to the trailing portion of a legitimate epilog, then it's in an epilog, and the //! remaining portion of the epilog is simulated, with the context record updated as each //! instruction is processed. After this, step 1 is repeated. //! //! 2. Case b) If the RIP lies within the prologue, then control has not entered the function, //! there can be no exception handler associated with this exception for this function, and the //! effects of the prolog must be undone to compute the context of the caller function. The RIP //! is within the prolog if the distance from the function start to the RIP is less than or //! equal to the prolog size encoded in the unwind info. The effects of the prolog are unwound //! by scanning forward through the unwind codes array for the first entry with an offset less //! than or equal to the offset of the RIP from the function start, then undoing the effect of //! all remaining items in the unwind code array. Step 1 is then repeated. //! //! 3. If the RIP is not within a prolog or epilog and the function has an exception handler, then //! the language-specific handler is called. The handler scans its data and calls filter //! functions as appropriate. The language-specific handler can return that the exception was //! handled or that the search is to be continued. It can also initiate an unwind directly. //! //! For more information, see [x64 exception handling]. //! //! [`ExceptionData`]: struct.ExceptionData.html //! [`RuntimeFunction`]: struct.RuntimeFunction.html //! [`UnwindInfo`]: struct.UnwindInfo.html //! [x64 exception handling]: https://docs.microsoft.com/en-us/cpp/build/exception-handling-x64?view=vs-2017
use core::cmp::Ordering; use core::fmt; use core::iter::FusedIterator;
use scroll::ctx::TryFromCtx; use scroll::{self, Pread, Pwrite};
/// The function has an exception handler that should be called when looking for functions that need /// to examine exceptions. const UNW_FLAG_EHANDLER: u8 = 0x01; /// The function has a termination handler that should be called when unwinding an exception. const UNW_FLAG_UHANDLER: u8 = 0x02; /// This unwind info structure is not the primary one for the procedure. Instead, the chained unwind /// info entry is the contents of a previous `RUNTIME_FUNCTION` entry. If this flag is set, then the /// `UNW_FLAG_EHANDLER` and `UNW_FLAG_UHANDLER` flags must be cleared. Also, the frame register and /// fixed-stack allocation fields must have the same values as in the primary unwind info. const UNW_FLAG_CHAININFO: u8 = 0x04;
/// info == register number const UWOP_PUSH_NONVOL: u8 = 0; /// no info, alloc size in next 2 slots const UWOP_ALLOC_LARGE: u8 = 1; /// info == size of allocation / 8 - 1 const UWOP_ALLOC_SMALL: u8 = 2; /// no info, FP = RSP + UNWIND_INFO.FPRegOffset*16 const UWOP_SET_FPREG: u8 = 3; /// info == register number, offset in next slot const UWOP_SAVE_NONVOL: u8 = 4; /// info == register number, offset in next 2 slots const UWOP_SAVE_NONVOL_FAR: u8 = 5; /// changes the structure of unwind codes to `struct Epilogue`. /// (was UWOP_SAVE_XMM in version 1, but deprecated and removed) const UWOP_EPILOG: u8 = 6; /// reserved /// (was UWOP_SAVE_XMM_FAR in version 1, but deprecated and removed) const UWOP_SPARE_CODE: u8 = 7; /// info == XMM reg number, offset in next slot const UWOP_SAVE_XMM128: u8 = 8; /// info == XMM reg number, offset in next 2 slots const UWOP_SAVE_XMM128_FAR: u8 = 9; /// info == 0: no error-code, 1: error-code const UWOP_PUSH_MACHFRAME: u8 = 10;
/// Size of `RuntimeFunction` entries. const RUNTIME_FUNCTION_SIZE: usize = 12; /// Size of unwind code slots. Codes take 1 - 3 slots. const UNWIND_CODE_SIZE: usize = 2;
/// An unwind entry for a range of a function. /// /// Unwind information for this function can be loaded with [`ExceptionData::get_unwind_info`]. /// /// [`ExceptionData::get_unwind_info`]: struct.ExceptionData.html#method.get_unwind_info #[repr(C)] #[derive(Copy, Clone, PartialEq, Default, Pread, Pwrite)] pubstruct RuntimeFunction { /// Function start address. pub begin_address: u32, /// Function end address. pub end_address: u32, /// Unwind info address. pub unwind_info_address: u32,
}
/// An unsigned offset to a value in the local stack frame. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pubenum StackFrameOffset { /// Offset from the current RSP, that is, the lowest address of the fixed stack allocation. /// /// To restore this register, read the value at the given offset from the RSP.
RSP(u32),
/// Offset from the value of the frame pointer register. /// /// To restore this register, read the value at the given offset from the FP register, reduced /// by the `frame_register_offset` value specified in the `UnwindInfo` structure. By definition, /// the frame pointer register is any register other than RAX (`0`).
FP(u32),
}
/// An unwind operation corresponding to code in the function prolog. /// /// Unwind operations can be used to reverse the effects of the function prolog and restore register /// values of parent stack frames that have been saved to the stack. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pubenum UnwindOperation { /// Push a nonvolatile integer register, decrementing `RSP` by 8.
PushNonVolatile(Register),
/// Allocate a fixed-size area on the stack.
Alloc(u32),
/// Establish the frame pointer register by setting the register to some offset of the current /// RSP. The use of an offset permits establishing a frame pointer that points to the middle of /// the fixed stack allocation, helping code density by allowing more accesses to use short /// instruction forms.
SetFPRegister,
/// Save a nonvolatile integer register on the stack using a MOV instead of a PUSH. This code is /// primarily used for shrink-wrapping, where a nonvolatile register is saved to the stack in a /// position that was previously allocated.
SaveNonVolatile(Register, StackFrameOffset),
/// Save the lower 64 bits of a nonvolatile XMM register on the stack.
SaveXMM(Register, StackFrameOffset),
/// Describes the function epilog. /// /// This operation has been introduced with unwind info version 2 and is not implemented yet.
Epilog,
/// Save all 128 bits of a nonvolatile XMM register on the stack.
SaveXMM128(Register, StackFrameOffset),
/// Push a machine frame. This is used to record the effect of a hardware interrupt or /// exception. Depending on the error flag, this frame has two different layouts. /// /// This unwind code always appears in a dummy prolog, which is never actually executed but /// instead appears before the real entry point of an interrupt routine, and exists only to /// provide a place to simulate the push of a machine frame. This operation records that /// simulation, which indicates the machine has conceptually done this: /// /// 1. Pop RIP return address from top of stack into `temp` /// 2. `$ss`, Push old `$rsp`, `$rflags`, `$cs`, `temp` /// 3. If error flag is `true`, push the error code /// /// Without an error code, RSP was incremented by `40` and the following was frame pushed: /// /// Offset | Value /// ---------|-------- /// RSP + 32 | `$ss` /// RSP + 24 | old `$rsp` /// RSP + 16 | `$rflags` /// RSP + 8 | `$cs` /// RSP + 0 | `$rip` /// /// With an error code, RSP was incremented by `48` and the following was frame pushed: /// /// Offset | Value /// ---------|-------- /// RSP + 40 | `$ss` /// RSP + 32 | old `$rsp` /// RSP + 24 | `$rflags` /// RSP + 16 | `$cs` /// RSP + 8 | `$rip` /// RSP + 0 | error code
PushMachineFrame(bool),
/// A reserved operation without effect.
Noop,
}
/// Context used to parse unwind operation. #[derive(Clone, Copy, Debug, PartialEq)] struct UnwindOpContext { /// Version of the unwind info.
version: u8,
/// The nonvolatile register used as the frame pointer of this function. /// /// If this register is non-zero, all stack frame offsets used in unwind operations are of type /// `StackFrameOffset::FP`. When loading these offsets, they have to be based off the value of /// this frame register instead of the conventional RSP. This allows the RSP to be modified.
frame_register: Register,
}
/// An unwind operation that is executed at a particular place in the function prolog. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pubstruct UnwindCode { /// Offset of the corresponding instruction in the function prolog. /// /// To be precise, this is the offset from the beginning of the prolog of the end of the /// instruction that performs this operation, plus 1 (that is, the offset of the start of the /// next instruction). /// /// Unwind codes are ordered by this offset in reverse order, suitable for unwinding. pub code_offset: u8,
/// The operation that was performed by the code in the prolog. pub operation: UnwindOperation,
}
impl<'a> TryFromCtx<'a, UnwindOpContext> for UnwindCode { type Error = error::Error; #[inline] fn try_from_ctx(bytes: &'a [u8], ctx: UnwindOpContext) -> Result<(Self, usize), Self::Error> { letmut read = 0; let code_offset = bytes.gread_with::<u8>(&mut read, scroll::LE)?; let operation = bytes.gread_with::<u8>(&mut read, scroll::LE)?;
let operation_code = operation & 0xf; let operation_info = operation >> 4;
let operation = match operation_code { self::UWOP_PUSH_NONVOL => { let register = Register(operation_info);
UnwindOperation::PushNonVolatile(register)
} self::UWOP_ALLOC_LARGE => { let offset = match operation_info { 0 => u32::from(bytes.gread_with::<u16>(&mut read, scroll::LE)?) * 8, 1 => bytes.gread_with::<u32>(&mut read, scroll::LE)?,
i => { let msg = format!("invalid op info ({}) for UWOP_ALLOC_LARGE", i); return Err(error::Error::Malformed(msg));
}
};
UnwindOperation::Alloc(offset)
} self::UWOP_ALLOC_SMALL => { let offset = u32::from(operation_info) * 8 + 8;
UnwindOperation::Alloc(offset)
} self::UWOP_SET_FPREG => UnwindOperation::SetFPRegister, self::UWOP_SAVE_NONVOL => { let register = Register(operation_info); let offset = u32::from(bytes.gread_with::<u16>(&mut read, scroll::LE)?) * 8;
UnwindOperation::SaveNonVolatile(register, StackFrameOffset::with_ctx(offset, ctx))
} self::UWOP_SAVE_NONVOL_FAR => { let register = Register(operation_info); let offset = bytes.gread_with::<u32>(&mut read, scroll::LE)?;
UnwindOperation::SaveNonVolatile(register, StackFrameOffset::with_ctx(offset, ctx))
} self::UWOP_EPILOG => { let data = u32::from(bytes.gread_with::<u16>(&mut read, scroll::LE)?) * 16; if ctx.version == 1 { let register = Register::xmm(operation_info);
UnwindOperation::SaveXMM(register, StackFrameOffset::with_ctx(data, ctx))
} else { // TODO: See https://weekly-geekly.github.io/articles/322956/index.html
UnwindOperation::Epilog
}
} self::UWOP_SPARE_CODE => { let data = bytes.gread_with::<u32>(&mut read, scroll::LE)?; if ctx.version == 1 { let register = Register::xmm(operation_info);
UnwindOperation::SaveXMM128(register, StackFrameOffset::with_ctx(data, ctx))
} else {
UnwindOperation::Noop
}
} self::UWOP_SAVE_XMM128 => { let register = Register::xmm(operation_info); let offset = u32::from(bytes.gread_with::<u16>(&mut read, scroll::LE)?) * 16;
UnwindOperation::SaveXMM128(register, StackFrameOffset::with_ctx(offset, ctx))
} self::UWOP_SAVE_XMM128_FAR => { let register = Register::xmm(operation_info); let offset = bytes.gread_with::<u32>(&mut read, scroll::LE)?;
UnwindOperation::SaveXMM128(register, StackFrameOffset::with_ctx(offset, ctx))
} self::UWOP_PUSH_MACHFRAME => { let is_error = match operation_info { 0 => false, 1 => true,
i => { let msg = format!("invalid op info ({}) for UWOP_PUSH_MACHFRAME", i); return Err(error::Error::Malformed(msg));
}
};
UnwindOperation::PushMachineFrame(is_error)
}
op => { let msg = format!("unknown unwind op code ({})", op); return Err(error::Error::Malformed(msg));
}
};
let code = UnwindCode {
code_offset,
operation,
};
Ok((code, read))
}
}
/// An iterator over unwind codes for a function or part of a function, returned from /// [`UnwindInfo`]. /// /// [`UnwindInfo`]: struct.UnwindInfo.html #[derive(Clone, Debug)] pubstruct UnwindCodeIterator<'a> {
bytes: &'a [u8],
offset: usize,
context: UnwindOpContext,
}
impl Iterator for UnwindCodeIterator<'_> { type Item = error::Result<UnwindCode>;
fn size_hint(&self) -> (usize, Option<usize>) { let upper = (self.bytes.len() - self.offset) / UNWIND_CODE_SIZE; // the largest codes take up three slots let lower = (upper + 3 - (upper % 3)) / 3;
(lower, Some(upper))
}
}
impl FusedIterator for UnwindCodeIterator<'_> {}
/// A language-specific handler that is called as part of the search for an exception handler or as /// part of an unwind. #[derive(Copy, Clone, Debug, PartialEq)] pubenum UnwindHandler<'a> { /// The image-relative address of an exception handler and its implementation-defined data.
ExceptionHandler(u32, &'a [u8]), /// The image-relative address of a termination handler and its implementation-defined data.
TerminationHandler(u32, &'a [u8]),
}
/// Unwind information for a function or portion of a function. /// /// The unwind info structure is used to record the effects a function has on the stack pointer and /// where the nonvolatile registers are saved on the stack. The unwind codes can be enumerated with /// [`unwind_codes`]. /// /// This unwind info might only be secondary information, and link to a [chained unwind handler]. /// For unwinding, this link shall be followed until the root unwind info record has been resolved. /// /// [`unwind_codes`]: struct.UnwindInfo.html#method.unwind_codes /// [chained unwind handler]: struct.UnwindInfo.html#structfield.chained_info #[derive(Clone)] pubstruct UnwindInfo<'a> { /// Version of this unwind info. pub version: u8,
/// Length of the function prolog in bytes. pub size_of_prolog: u8,
/// The nonvolatile register used as the frame pointer of this function. /// /// If this register is non-zero, all stack frame offsets used in unwind operations are of type /// `StackFrameOffset::FP`. When loading these offsets, they have to be based off the value of /// this frame register instead of the conventional RSP. This allows the RSP to be modified. pub frame_register: Register,
/// Offset from RSP that is applied to the FP register when it is established. /// /// When loading offsets of type `StackFrameOffset::FP` from the stack, this offset has to be /// subtracted before loading the value since the actual RSP was lower by that amount in the /// prolog. pub frame_register_offset: u32,
/// A record pointing to chained unwind information. /// /// If chained unwind info is present, then this unwind info is a secondary one and the linked /// unwind info contains primary information. Chained info is useful in two situations. First, /// it is used for noncontiguous code segments. Second, this mechanism is sometimes used to /// group volatile register saves. /// /// The referenced unwind info can itself specify chained unwind information, until it arrives /// at the root unwind info. Generally, the entire chain should be considered when unwinding. pub chained_info: Option<RuntimeFunction>,
/// An exception or termination handler called as part of the unwind. pub handler: Option<UnwindHandler<'a>>,
/// A list of unwind codes, sorted descending by code offset.
code_bytes: &'a [u8],
}
impl<'a> UnwindInfo<'a> { /// Parses unwind information from the image at the given offset. pubfn parse(bytes: &'a [u8], mut offset: usize) -> error::Result<Self> { // Read the version and flags fields, which are combined into a single byte. let version_flags: u8 = bytes.gread_with(&mut offset, scroll::LE)?; let version = version_flags & 0b111; let flags = version_flags >> 3;
if version < 1 || version > 2 { let msg = format!("unsupported unwind code version ({})", version); return Err(error::Error::Malformed(msg));
}
let size_of_prolog = bytes.gread_with::<u8>(&mut offset, scroll::LE)?; let count_of_codes = bytes.gread_with::<u8>(&mut offset, scroll::LE)?;
// Parse the frame register and frame register offset values, that are combined into a // single byte. let frame_info = bytes.gread_with::<u8>(&mut offset, scroll::LE)?; // If nonzero, then the function uses a frame pointer (FP), and this field is the number // of the nonvolatile register used as the frame pointer. The zero register value does // not need special casing since it will not be referenced by the unwind operations. let frame_register = Register(frame_info & 0xf); // The the scaled offset from RSP that is applied to the FP register when it's // established. The actual FP register is set to RSP + 16 * this number, allowing // offsets from 0 to 240. let frame_register_offset = u32::from((frame_info >> 4) * 16);
// An array of items that explains the effect of the prolog on the nonvolatile registers and // RSP. Some unwind codes require more than one slot in the array. let codes_size = count_of_codes as usize * UNWIND_CODE_SIZE; let code_bytes = bytes.gread_with(&mut offset, codes_size)?;
// For alignment purposes, the codes array always has an even number of entries, and the // final entry is potentially unused. In that case, the array is one longer than indicated // by the count of unwind codes field. if count_of_codes % 2 != 0 {
offset += 2;
}
debug_assert!(offset % 4 == 0);
// If flag UNW_FLAG_CHAININFO is set then the UNWIND_INFO structure ends with three UWORDs. // These UWORDs represent the RUNTIME_FUNCTION information for the function of the chained // unwind. if flags & UNW_FLAG_CHAININFO != 0 {
chained_info = Some(bytes.gread_with(&mut offset, scroll::LE)?);
// The relative address of the language-specific handler is present in the UNWIND_INFO // whenever flags UNW_FLAG_EHANDLER or UNW_FLAG_UHANDLER are set. The language-specific // handler is called as part of the search for an exception handler or as part of an unwind.
} elseif flags & (UNW_FLAG_EHANDLER | UNW_FLAG_UHANDLER) != 0 { let address = bytes.gread_with::<u32>(&mut offset, scroll::LE)?; let data = &bytes[offset..];
/// Returns an iterator over unwind codes in this unwind info. /// /// Unwind codes are iterated in descending `code_offset` order suitable for unwinding. If the /// optional [`chained_info`](Self::chained_info) is present, codes of that unwind info should be interpreted /// immediately afterwards. pubfn unwind_codes(&self) -> UnwindCodeIterator<'a> {
UnwindCodeIterator {
bytes: self.code_bytes,
offset: 0,
context: UnwindOpContext {
version: self.version,
frame_register: self.frame_register,
},
}
}
}
impl fmt::Debug for UnwindInfo<'_> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let count_of_codes = self.code_bytes.len() / UNWIND_CODE_SIZE;
/// Exception handling and stack unwind information for functions in the image. pubstruct ExceptionData<'a> {
bytes: &'a [u8],
offset: usize,
size: usize,
file_alignment: u32,
}
impl<'a> ExceptionData<'a> { /// Parses exception data from the image at the given offset. pubfn parse(
bytes: &'a [u8],
directory: data_directories::DataDirectory,
sections: &[section_table::SectionTable],
file_alignment: u32,
) -> error::Result<Self> { Self::parse_with_opts(
bytes,
directory,
sections,
file_alignment,
&options::ParseOptions::default(),
)
}
/// Parses exception data from the image at the given offset. pubfn parse_with_opts(
bytes: &'a [u8],
directory: data_directories::DataDirectory,
sections: &[section_table::SectionTable],
file_alignment: u32,
opts: &options::ParseOptions,
) -> error::Result<Self> { let size = directory.size as usize;
/// The number of function entries described by this exception data. pubfn len(&self) -> usize { self.size / RUNTIME_FUNCTION_SIZE
}
/// Indicating whether there are functions in this entry. pubfn is_empty(&self) -> bool { self.len() == 0
}
/// Iterates all function entries in order of their code offset. /// /// To search for a function by relative instruction address, use [`find_function`]. To resolve /// unwind information, use [`get_unwind_info`]. /// /// [`find_function`]: struct.ExceptionData.html#method.find_function /// [`get_unwind_info`]: struct.ExceptionData.html#method.get_unwind_info pubfn functions(&self) -> RuntimeFunctionIterator<'a> {
RuntimeFunctionIterator {
data: &self.bytes[self.offset..self.offset + self.size],
}
}
/// Returns the function at the given index. pubfn get_function(&self, index: usize) -> error::Result<RuntimeFunction> { self.get_function_by_offset(self.offset + index * RUNTIME_FUNCTION_SIZE)
}
/// Performs a binary search to find a function entry covering the given RVA relative to the /// image. pubfn find_function(&self, rva: u32) -> error::Result<Option<RuntimeFunction>> { // NB: Binary search implementation copied from std::slice::binary_search_by and adapted. // Theoretically, there should be nothing that causes parsing runtime functions to fail and // all access to the bytes buffer is guaranteed to be in range. However, since all other // functions also return Results, this is much more ergonomic here.
letmut base = 0; while size > 1 { let half = size / 2; let mid = base + half; let offset = self.offset + mid * RUNTIME_FUNCTION_SIZE; let addr = self.bytes.pread_with::<u32>(offset, scroll::LE)?;
base = if addr > rva { base } else { mid };
size -= half;
}
let offset = self.offset + base * RUNTIME_FUNCTION_SIZE; let addr = self.bytes.pread_with::<u32>(offset, scroll::LE)?; let function = match addr.cmp(&rva) {
Ordering::Less | Ordering::Equal => self.get_function(base)?,
Ordering::Greater if base == 0 => return Ok(None),
Ordering::Greater => self.get_function(base - 1)?,
};
/// Resolves unwind information for the given function entry. pubfn get_unwind_info(
&self,
function: RuntimeFunction,
sections: &[section_table::SectionTable],
) -> error::Result<UnwindInfo<'a>> { self.get_unwind_info_with_opts(function, sections, &options::ParseOptions::default())
}
/// Resolves unwind information for the given function entry. pubfn get_unwind_info_with_opts(
&self, mut function: RuntimeFunction,
sections: &[section_table::SectionTable],
opts: &options::ParseOptions,
) -> error::Result<UnwindInfo<'a>> { while function.unwind_info_address % 2 != 0 { let rva = (function.unwind_info_address & !1) as usize;
function = self.get_function_by_rva_with_opts(rva, sections, opts)?;
}
let rva = function.unwind_info_address as usize; let offset =
utils::find_offset(rva, sections, self.file_alignment, opts).ok_or_else(|| {
error::Error::Malformed(format!("cannot map unwind rva ({:#x}) into offset", rva))
})?;
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.