Skip to main content

cildec/
error.rs

1//! Error and diagnostic types.
2//!
3//! Every fallible entry point in this crate returns [`Error`], a `Copy` struct
4//! carrying a machine-readable [`ErrorKind`], the byte offset into the input
5//! that was handed to the failing `parse` call, and a short static context
6//! string naming the structure that failed to decode.
7//!
8//! Errors never allocate and never borrow from the input, so they can be
9//! propagated freely across the `'a` lifetime of a parsed image.
10
11use core::fmt;
12
13/// The classification of a decoding failure.
14#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
15#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
16#[non_exhaustive]
17pub enum ErrorKind {
18    /// The input ended before the structure being decoded was complete.
19    Truncated,
20    /// The bytes were present but do not form a legal structure.
21    Malformed,
22    /// The structure is legal but this version of the crate does not decode it.
23    Unsupported,
24    /// An index, RVA, or offset pointed outside the region it must lie in.
25    OutOfRange,
26    /// A nested structure exceeded the configured recursion limit.
27    RecursionLimit,
28    /// Text that must be UTF-8 was not.
29    InvalidUtf8,
30    /// A CIL prefix was not followed by an instruction it is legal on.
31    InvalidPrefixTarget,
32    /// The byte (or `0xFE`-escaped byte pair) is not a defined CIL opcode.
33    UnknownOpcode,
34}
35
36impl ErrorKind {
37    /// A short lowercase description, used by the [`Display`](fmt::Display) impl.
38    pub const fn as_str(self) -> &'static str {
39        match self {
40            ErrorKind::Truncated => "truncated input",
41            ErrorKind::Malformed => "malformed structure",
42            ErrorKind::Unsupported => "unsupported structure",
43            ErrorKind::OutOfRange => "value out of range",
44            ErrorKind::RecursionLimit => "recursion limit exceeded",
45            ErrorKind::InvalidUtf8 => "invalid UTF-8",
46            ErrorKind::InvalidPrefixTarget => "invalid prefix target",
47            ErrorKind::UnknownOpcode => "unknown opcode",
48        }
49    }
50}
51
52/// A decoding failure.
53///
54/// `offset`, when present, is a byte offset into the buffer passed to the
55/// `parse` call that produced this error, not into an inner slice.
56#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
57#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
58pub struct Error {
59    /// What went wrong.
60    pub kind: ErrorKind,
61    /// Byte offset into the failing `parse` call input, when known.
62    pub offset: Option<usize>,
63    /// The structure that failed to decode, e.g. `"CLI header"`.
64    pub context: &'static str,
65}
66
67impl Error {
68    /// Constructs an error with an offset.
69    pub const fn new(kind: ErrorKind, offset: usize, context: &'static str) -> Self {
70        Error { kind, offset: Some(offset), context }
71    }
72
73    /// Constructs an error with no meaningful offset.
74    pub const fn detached(kind: ErrorKind, context: &'static str) -> Self {
75        Error { kind, offset: None, context }
76    }
77
78    /// Returns a copy of this error with `base` added to any existing offset.
79    ///
80    /// Used when an inner parser reports an offset relative to a sub-slice and
81    /// the caller knows where that sub-slice began.
82    #[must_use]
83    pub const fn rebase(self, base: usize) -> Self {
84        match self.offset {
85            Some(o) => Error {
86                kind: self.kind,
87                offset: Some(o.saturating_add(base)),
88                context: self.context,
89            },
90            None => Error { kind: self.kind, offset: Some(base), context: self.context },
91        }
92    }
93}
94
95impl fmt::Display for Error {
96    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
97        write!(f, "{}: {}", self.context, self.kind.as_str())?;
98        if let Some(offset) = self.offset {
99            write!(f, " at offset {offset:#x}")?;
100        }
101        Ok(())
102    }
103}
104
105#[cfg(feature = "std")]
106impl std::error::Error for Error {}
107
108/// Shorthand for results produced by this crate.
109pub type Result<T> = core::result::Result<T, Error>;
110
111/// How tolerant a parser should be of images that deviate from ECMA-335.
112#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Default)]
113#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
114pub enum Strictness {
115    /// Reject everything ECMA-335 rejects.
116    Strict,
117    /// Accept the real-world deviations documented in the crate root, recording
118    /// each one as a [`Diagnostic`]. This is the default.
119    #[default]
120    Permissive,
121}
122
123impl Strictness {
124    /// True when this is [`Strictness::Strict`].
125    pub const fn is_strict(self) -> bool {
126        matches!(self, Strictness::Strict)
127    }
128}
129
130/// A deviation from ECMA-335 that was accepted in [`Strictness::Permissive`].
131#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
132#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
133pub struct Diagnostic {
134    /// What was tolerated.
135    pub code: DiagnosticCode,
136    /// Byte offset into the parsed input, when known.
137    pub offset: Option<usize>,
138    /// Code-specific detail: a table id, a stream index, a declared size, etc.
139    pub detail: u64,
140}
141
142impl Diagnostic {
143    pub(crate) const fn new(code: DiagnosticCode, offset: usize, detail: u64) -> Self {
144        Diagnostic { code, offset: Some(offset), detail }
145    }
146}
147
148impl fmt::Display for Diagnostic {
149    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
150        write!(f, "{} (detail {:#x})", self.code.as_str(), self.detail)?;
151        if let Some(offset) = self.offset {
152            write!(f, " at offset {offset:#x}")?;
153        }
154        Ok(())
155    }
156}
157
158/// The set of tolerated deviations this crate can report.
159///
160/// Every variant is produced by some parser; a deviation that a `&self`
161/// accessor notices instead, such as a `#US` entry with an even body length, is
162/// reported on the value itself (see [`UserString::odd_length`](crate::heaps::UserString::odd_length)).
163#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
164#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
165#[non_exhaustive]
166pub enum DiagnosticCode {
167    /// A fat method header declared a size other than 3 dwords.
168    FatHeaderSize,
169    /// A metadata stream name was not NUL-padded to a 4-byte boundary.
170    StreamNamePadding,
171    /// Two metadata streams shared a name; the first was kept.
172    DuplicateStreamName,
173    /// A stream declared range was clamped to the end of the metadata region.
174    StreamRangeClamped,
175    /// The `Valid` bitvector set a bit for a reserved table id with zero rows.
176    ReservedTablePresent,
177    /// A table the spec marks sorted was not sorted; lookups fall back to a scan.
178    TableNotSorted,
179    /// The metadata version string was not NUL-terminated inside its field.
180    VersionStringPadding,
181    /// The CLI header declared a size other than 72 bytes.
182    CliHeaderSize,
183    /// A section header raw range ran past the end of the file.
184    SectionRangeClamped,
185    /// An exception-handling section declared a size inconsistent with its clauses.
186    EhSectionSize,
187    /// `32BITPREFERRED` was set without `32BITREQUIRED`.
188    BitnessFlagsInconsistent,
189    /// The table stream declared heap-size bits this crate ignores.
190    UnknownHeapSizeBits,
191}
192
193impl DiagnosticCode {
194    /// A short static description.
195    pub const fn as_str(self) -> &'static str {
196        match self {
197            DiagnosticCode::FatHeaderSize => "fat method header size is not 3 dwords",
198            DiagnosticCode::StreamNamePadding => "stream name is not NUL-padded",
199            DiagnosticCode::DuplicateStreamName => "duplicate stream name",
200            DiagnosticCode::StreamRangeClamped => "stream range clamped to metadata region",
201            DiagnosticCode::ReservedTablePresent => "reserved table id flagged present",
202            DiagnosticCode::TableNotSorted => "table declared sorted is not sorted",
203            DiagnosticCode::VersionStringPadding => "version string is not NUL-terminated",
204            DiagnosticCode::CliHeaderSize => "CLI header size is not 72",
205            DiagnosticCode::SectionRangeClamped => "section raw range clamped to file",
206            DiagnosticCode::EhSectionSize => "exception section size is inconsistent",
207            DiagnosticCode::BitnessFlagsInconsistent => "32BITPREFERRED without 32BITREQUIRED",
208            DiagnosticCode::UnknownHeapSizeBits => "unknown HeapSizes bits",
209        }
210    }
211}