use alloc::string::String;
use core::fmt;
#[cfg(feature = "std")]
use std::io;
pub type Result<T, E = Error> = core::result::Result<T, E>;
#[derive(Debug, Clone, Default)]
pub struct ErrorContext {
offset: Option<u64>,
vaddr: Option<u64>,
structure: Option<String>,
}
impl ErrorContext {
#[must_use]
pub fn at_offset(mut self, offset: u64) -> Self {
self.offset = Some(offset);
self
}
#[must_use]
pub fn at_vaddr(mut self, vaddr: u64) -> Self {
self.vaddr = Some(vaddr);
self
}
#[must_use]
pub fn in_structure(mut self, name: impl Into<String>) -> Self {
self.structure = Some(name.into());
self
}
#[must_use]
pub const fn offset(&self) -> Option<u64> {
self.offset
}
#[must_use]
pub const fn vaddr(&self) -> Option<u64> {
self.vaddr
}
#[must_use]
pub fn structure(&self) -> Option<&str> {
self.structure.as_deref()
}
}
impl fmt::Display for ErrorContext {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut separated = false;
let mut write_part = |formatter: &mut fmt::Formatter<'_>, part: fmt::Arguments<'_>| {
if separated {
formatter.write_str(", ")?;
}
separated = true;
formatter.write_fmt(part)
};
if let Some(structure) = &self.structure {
write_part(formatter, format_args!("in {structure}"))?;
}
if let Some(offset) = self.offset {
write_part(formatter, format_args!("at file offset {offset:#x}"))?;
}
if let Some(vaddr) = self.vaddr {
write_part(formatter, format_args!("at virtual address {vaddr:#x}"))?;
}
Ok(())
}
}
#[derive(Debug)]
#[non_exhaustive]
pub enum ErrorKind {
#[cfg(feature = "std")]
Io(io::Error),
InvalidMagic,
InvalidClass(u8),
InvalidDataEncoding(u8),
InvalidType(u16),
UnsupportedMachine(u16),
BufferTooSmall {
expected: usize,
actual: usize,
},
InvalidSection(String),
OffsetOutOfBounds {
offset: u64,
size: u64,
},
InvalidVaddr(u64),
InvalidUtf8,
Generic(String),
}
#[derive(Debug)]
pub struct Error {
kind: ErrorKind,
context: Option<ErrorContext>,
}
impl Error {
#[must_use]
pub const fn new(kind: ErrorKind) -> Self {
Self {
kind,
context: None,
}
}
#[must_use]
pub fn with_context(mut self, context: ErrorContext) -> Self {
self.context = Some(context);
self
}
#[must_use]
pub fn at_offset(mut self, offset: u64) -> Self {
let context = self.context.take().unwrap_or_default();
self.context = Some(context.at_offset(offset));
self
}
#[must_use]
pub fn at_vaddr(mut self, vaddr: u64) -> Self {
let context = self.context.take().unwrap_or_default();
self.context = Some(context.at_vaddr(vaddr));
self
}
#[must_use]
pub fn in_structure(mut self, name: impl Into<String>) -> Self {
let context = self.context.take().unwrap_or_default();
self.context = Some(context.in_structure(name));
self
}
#[must_use]
pub const fn kind(&self) -> &ErrorKind {
&self.kind
}
#[must_use]
pub const fn context(&self) -> Option<&ErrorContext> {
self.context.as_ref()
}
#[must_use]
pub const fn invalid_magic() -> Self {
Self::new(ErrorKind::InvalidMagic)
}
#[must_use]
pub const fn invalid_class(class: u8) -> Self {
Self::new(ErrorKind::InvalidClass(class))
}
#[must_use]
pub const fn invalid_data_encoding(data: u8) -> Self {
Self::new(ErrorKind::InvalidDataEncoding(data))
}
#[must_use]
pub const fn invalid_type(object_type: u16) -> Self {
Self::new(ErrorKind::InvalidType(object_type))
}
#[must_use]
pub const fn unsupported_machine(machine: u16) -> Self {
Self::new(ErrorKind::UnsupportedMachine(machine))
}
#[must_use]
pub const fn buffer_too_small(expected: usize, actual: usize) -> Self {
Self::new(ErrorKind::BufferTooSmall { expected, actual })
}
#[must_use]
pub fn invalid_section(message: impl Into<String>) -> Self {
Self::new(ErrorKind::InvalidSection(message.into()))
}
#[must_use]
pub const fn offset_out_of_bounds(offset: u64, size: u64) -> Self {
Self::new(ErrorKind::OffsetOutOfBounds { offset, size })
}
#[must_use]
pub const fn invalid_vaddr(vaddr: u64) -> Self {
Self::new(ErrorKind::InvalidVaddr(vaddr))
}
#[must_use]
pub const fn invalid_utf8() -> Self {
Self::new(ErrorKind::InvalidUtf8)
}
#[must_use]
pub fn generic(message: impl Into<String>) -> Self {
Self::new(ErrorKind::Generic(message.into()))
}
}
impl fmt::Display for ErrorKind {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
#[cfg(feature = "std")]
Self::Io(cause) => write!(formatter, "input or output error: {cause}"),
Self::InvalidMagic => formatter.write_str("invalid ELF magic number"),
Self::InvalidClass(class) => write!(formatter, "invalid ELF class {class:#x}"),
Self::InvalidDataEncoding(data) => {
write!(formatter, "invalid ELF data encoding {data:#x}")
}
Self::InvalidType(object_type) => {
write!(formatter, "invalid ELF object type {object_type:#x}")
}
Self::UnsupportedMachine(machine) => {
write!(formatter, "unsupported ELF machine {machine:#x}")
}
Self::BufferTooSmall { expected, actual } => write!(
formatter,
"buffer too small: expected {expected} bytes, found {actual}"
),
Self::InvalidSection(message) => write!(formatter, "invalid section: {message}"),
Self::OffsetOutOfBounds { offset, size } => write!(
formatter,
"offset {offset:#x} is out of bounds for size {size:#x}"
),
Self::InvalidVaddr(vaddr) => {
write!(formatter, "virtual address {vaddr:#x} is not in the image")
}
Self::InvalidUtf8 => formatter.write_str("invalid UTF-8 in ELF string"),
Self::Generic(message) => formatter.write_str(message),
}
}
}
impl fmt::Display for Error {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "{}", self.kind)?;
if let Some(context) = &self.context {
write!(formatter, " ({context})")?;
}
Ok(())
}
}
impl core::error::Error for Error {
fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
match &self.kind {
#[cfg(feature = "std")]
ErrorKind::Io(cause) => Some(cause),
_ => None,
}
}
}
impl From<ErrorKind> for Error {
fn from(kind: ErrorKind) -> Self {
Self::new(kind)
}
}
#[cfg(feature = "std")]
impl From<io::Error> for Error {
fn from(cause: io::Error) -> Self {
Self::new(ErrorKind::Io(cause))
}
}