Skip to main content

unityrs_core/
error.rs

1// Ported from UnityPy 1.25.2 (MIT): UnityPy/files/BundleFile.py, UnityPy/environment.py, UnityPy/files/File.py, UnityPy/files/ObjectReader.py, UnityPy/files/SerializedFile.py, UnityPy/helpers/CompressionHelper.py, UnityPy/helpers/ContainerHelper.py, UnityPy/helpers/ResourceReader.py. See THIRD_PARTY_LICENSES.
2//! The file-level error type.
3//!
4//! Object-level outcomes (the canonical dump's L2 kinds) are
5//! [`crate::walk::ParseError`]; the writer's are [`crate::walk::WriteError`].
6//! `Error` is `Clone` because a lazily computed result, published once into
7//! a `OnceLock`, is handed to every later caller.
8//!
9//! Owner: the scaffold (frozen). A package that needs a new variant asks the
10//! integration package; `#[non_exhaustive]` keeps that additive.
11
12use std::sync::Arc;
13
14use crate::budget::{AllocError, BudgetExceeded};
15use crate::codec::Codec;
16use crate::detect::DetectError;
17use crate::limits::{ChargeError, heap_cost};
18use crate::once::CellError;
19use crate::raw::RawStr;
20use crate::typetree::TreeError;
21use crate::version::VersionError;
22use crate::walk::ParseError;
23
24/// Why loading a file failed. Never a panic.
25#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
26#[non_exhaustive]
27pub enum Error {
28    /// `check_file_type` raised (the dump's `"detect"`).
29    #[error("detection: {0}")]
30    Detect(#[from] DetectError),
31    /// A read past the end where UnityPy raises too (`struct.error`, `EOFError`).
32    #[error("{what}: out of bounds at {pos} (need {need}, have {have})")]
33    OutOfBounds {
34        /// What was being read.
35        what: &'static str,
36        /// The reader's position at the read: a Python position, which may be
37        /// negative or past the end ([`crate::stream::Reader::position`]).
38        pos: i128,
39        /// Bytes needed.
40        need: u64,
41        /// Bytes left.
42        have: u64,
43        /// Rules of the reader whose read failed.
44        reader: crate::stream::ReaderKind,
45        /// Size of that reader's buffer, including after decompression.
46        length: usize,
47    },
48    /// Input UnityPy rejects with an exception other than a short read.
49    #[error("malformed {what}: {detail}")]
50    Malformed {
51        /// What was being read.
52        what: &'static str,
53        /// The detail, for people. Shared, so a clone allocates nothing.
54        detail: Arc<str>,
55    },
56    /// The decoded signature rejected by the `WebFile` constructor. Keep only
57    /// a charged copy, so an error cannot retain an entire inflated input.
58    #[error("malformed WebFile: invalid signature")]
59    WebSignature(RawStr),
60    /// The rejected bundle signature, copied into charged storage so nested
61    /// failures identify their own input without retaining its whole buffer.
62    #[error("malformed bundle signature: Unknown Bundle signature")]
63    BundleSignature(RawStr),
64    /// A format or feature unityrs does not read (yet), each named.
65    #[error("unsupported: {0}")]
66    Unsupported(Unsupported),
67    /// UnityPy's key setter raises `ValueError` for this length.
68    #[error("AssetBundle Key length is wrong. It should be 16 bytes and now is {length} bytes.")]
69    UnityCnKeyLength {
70        /// Supplied length in bytes.
71        length: usize,
72    },
73    /// UnityPy raises `LookupError` after reading an encrypted header without a key.
74    #[error("The BundleFile is encrypted, but no key was provided!")]
75    UnityCnKeyMissing,
76    /// AES raises `ValueError` for a short header key vector.
77    #[error("Data must be aligned to block boundary in ECB mode (got {length} bytes)")]
78    UnityCnVectorLength {
79        /// Bytes read from the vector.
80        length: usize,
81    },
82    /// UnityPy raises a plain `Exception` when the AES signature differs.
83    #[error("Invalid UnityCN signature")]
84    UnityCnSignature,
85    /// A block failed to decode.
86    #[error("{codec:?} block: {detail}")]
87    Decompress {
88        /// The block's codec.
89        codec: Codec,
90        /// The decoder's message. Shared, so a clone allocates nothing.
91        detail: Arc<str>,
92    },
93    /// A version string did not parse, or no fallback was set.
94    #[error(transparent)]
95    Version(#[from] VersionError),
96    /// From format 16, an object's `type_id` outside `types` (Python indexing:
97    /// negative counts from the end; `ObjectReader.py:98-101`).
98    #[error("type index {index} out of range ({len} types)")]
99    TypeIndex {
100        /// The object's `type_id`.
101        index: i32,
102        /// How many types the file has.
103        len: usize,
104    },
105    /// A typetree's rows could not be built into a tree, or the tree is over a limit.
106    #[error(transparent)]
107    Tree(#[from] TreeError),
108    /// The AssetBundle object read at load failed, which fails the file
109    /// (`SerializedFile.py:316-324`; `CANONICAL_DUMP.md` section 7).
110    #[error("AssetBundle: {0}")]
111    AssetBundle(Arc<ParseError>),
112    /// A bundle entry failed, which fails the bundle (`File.py:76-90`).
113    #[error("entry {name}: {source}")]
114    Entry {
115        /// The entry's directory path.
116        name: RawStr,
117        /// Why it failed.
118        source: Arc<Error>,
119    },
120    /// A bound from [`crate::limits::Limits`] was exceeded (the input's
121    /// meter included: [`LimitKind::InputMemory`]).
122    #[error(transparent)]
123    Limit(#[from] LimitError),
124    /// The memory budget refused a reservation, or the allocator failed.
125    #[error(transparent)]
126    Budget(#[from] BudgetExceeded),
127    /// The host allocator refused storage; no heap-owned source is retained.
128    #[error(transparent)]
129    Allocator(#[from] AllocError),
130    /// A CAB, external, object or resource that is not there.
131    #[error("not found: {0}")]
132    NotFound(NotFound),
133    /// A pointer that could not be followed where the caller raises it (the
134    /// container preload, `helpers/ContainerHelper.py:43-46`, plan 3.13).
135    /// A failure to load the target is that load's own error, never this.
136    #[error(transparent)]
137    Deref(Arc<crate::env::DerefError>),
138    /// An I/O error from a source.
139    #[error("io: {0}")]
140    Io(IoError),
141}
142
143impl Error {
144    /// Whether the dependency budget refused a reservation, including when
145    /// an entry or object read wraps the refusal. A refusal carried inside a
146    /// `ParseError::Provider` is not recognised here; callers that retry
147    /// provider reads classify that case themselves.
148    #[must_use]
149    pub fn is_dependency_budget_refusal(&self) -> bool {
150        crate::env::registry::pool_refused(self)
151    }
152}
153
154/// An I/O error, shared because [`Error`] is `Clone`. `std::io::Error` has
155/// no equality, so two are equal when their kinds and OS error codes are.
156#[derive(Clone, Debug, thiserror::Error)]
157#[error("{0}")]
158pub struct IoError(pub Arc<std::io::Error>);
159
160impl PartialEq for IoError {
161    fn eq(&self, other: &Self) -> bool {
162        self.0.kind() == other.0.kind() && self.0.raw_os_error() == other.0.raw_os_error()
163    }
164}
165
166impl Eq for IoError {}
167
168const _: () = crate::send_sync::<IoError>();
169
170impl From<ChargeError> for Error {
171    fn from(e: ChargeError) -> Self {
172        match e {
173            ChargeError::Limit(l) => Self::Limit(l),
174            ChargeError::Budget(b) => Self::Budget(b),
175            ChargeError::Allocator(a) => Self::Allocator(a),
176        }
177    }
178}
179
180impl From<std::io::Error> for Error {
181    fn from(e: std::io::Error) -> Self {
182        Self::Io(IoError(Arc::new(e)))
183    }
184}
185
186/// [`heap_cost`] of `n` bytes.
187pub(crate) fn heap_of(n: usize) -> u64 {
188    heap_cost(u64::try_from(n).unwrap_or(u64::MAX))
189}
190
191/// [`heap_cost`] of an `Arc` of `n` bytes: its two counts and the bytes.
192pub(crate) fn arc_heap_of(n: usize) -> u64 {
193    heap_of(n.saturating_add(2 * size_of::<usize>()))
194}
195
196impl ChargeError {
197    /// Whether the refusal depends on what else is held (a budget, or the
198    /// input's meter), not on the input alone ([`crate::once`]).
199    #[must_use]
200    pub fn is_transient(&self) -> bool {
201        match self {
202            Self::Budget(_) | Self::Allocator(_) => true,
203            Self::Limit(l) => l.kind == LimitKind::InputMemory,
204        }
205    }
206
207    /// Whether the input's own meter refused ([`LimitKind::InputMemory`]),
208    /// not the budget ([`crate::once::CellError::is_meter_refusal`]).
209    #[must_use]
210    pub fn is_meter_refusal(&self) -> bool {
211        matches!(self, Self::Limit(l) if l.kind == LimitKind::InputMemory)
212    }
213}
214
215impl CellError for Error {
216    fn is_transient(&self) -> bool {
217        match self {
218            Self::Budget(_)
219            | Self::Allocator(_)
220            | Self::Io(_)
221            | Self::Detect(DetectError::Allocator(_)) => true,
222            Self::Limit(l) => l.kind == LimitKind::InputMemory,
223            Self::Tree(t) => t.is_transient(),
224            Self::AssetBundle(p) => p.is_transient(),
225            Self::Entry { source, .. } => source.is_transient(),
226            Self::Deref(d) => d.is_transient(),
227            _ => false,
228        }
229    }
230
231    fn is_meter_refusal(&self) -> bool {
232        match self {
233            Self::Limit(l) => l.kind == LimitKind::InputMemory,
234            Self::Tree(t) => t.is_meter_refusal(),
235            Self::AssetBundle(p) => p.is_meter_refusal(),
236            Self::Entry { source, .. } => source.is_meter_refusal(),
237            Self::Deref(d) => d.is_meter_refusal(),
238            _ => false,
239        }
240    }
241
242    fn heap_bytes(&self) -> u64 {
243        match self {
244            Self::Detect(DetectError::Gzip(d) | DetectError::GzipCrc { detail: d, .. }) => {
245                arc_heap_of(d.len())
246            }
247            Self::Malformed { detail, .. } | Self::Decompress { detail, .. } => {
248                arc_heap_of(detail.len())
249            }
250            Self::Version(VersionError::NoMatch(r))
251            | Self::WebSignature(r)
252            | Self::BundleSignature(r)
253            | Self::NotFound(NotFound::Cab(r) | NotFound::Resource(r)) => heap_of(r.len()),
254            Self::Tree(t) => t.heap_bytes(),
255            Self::AssetBundle(p) => {
256                arc_heap_of(size_of::<ParseError>()).saturating_add(p.heap_bytes())
257            }
258            Self::Entry { name, source } => heap_of(name.len())
259                .saturating_add(arc_heap_of(size_of::<Self>()))
260                .saturating_add(source.heap_bytes()),
261            Self::Deref(d) => {
262                arc_heap_of(size_of::<crate::env::DerefError>()).saturating_add(d.heap_bytes())
263            }
264            _ => 0,
265        }
266    }
267
268    fn work_refused(limit: LimitError) -> Self {
269        Self::Limit(limit)
270    }
271}
272
273/// Formats and features that are named and refused, never guessed at.
274#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
275#[non_exhaustive]
276pub enum Unsupported {
277    /// The `UnityArchive` signature; UnityPy raises too (`files/BundleFile.py:41`).
278    #[error("UnityArchive bundles")]
279    UnityArchive,
280    /// LZHAM blocks; UnityPy raises too (`CompressionHelper.py:234-235`).
281    #[error("LZHAM compression")]
282    Lzham,
283    /// A compression type no codec is registered for (`files/BundleFile.py:515-521`).
284    #[error("compression type {0}")]
285    Codec(u8),
286    /// Legacy compatibility variant; UnityWeb/UnityRaw layouts are now supported.
287    #[error("the UnityWeb/UnityRaw layout")]
288    WebRawLayout,
289    /// Legacy compatibility variant; WebFile containers are now supported.
290    #[error("WebFile")]
291    WebFile,
292    /// Tier U: a WebFile entry name length below -1 can rewind forever.
293    #[error("WebFile entry name length below -1")]
294    WebFileNameLength,
295    /// Legacy custom-decryptor refusal. The built-in UnityCN loader instead
296    /// returns [`Error::UnityCnKeyMissing`] for a missing load-local key.
297    #[error("an encrypted bundle without a decryptor")]
298    Encrypted,
299    /// Tier U: the token walk would read beyond Boost's trailing zero byte.
300    #[error("UnityCN token walk past the trailing zero byte")]
301    UnityCnWalk,
302    /// A ZIP passed to the single-File parser. `Environment::load_file` and
303    /// `Environment::load_zip_file` provide container loading.
304    #[error("zip members")]
305    Zip,
306    /// The parts of a split file (`name.split0`, `name.split1`, ...), which
307    /// UnityPy joins before it reads them (`environment.py:25`, `:111-116`,
308    /// `:126-127`). Kept for compatibility; core path loading now joins them.
309    #[error("split files (.splitN)")]
310    Split,
311    /// `obj.container` for an object of a dependency the Environment may
312    /// evict, whose paths an eviction would drop
313    /// ([`crate::env::Environment::container_path`]).
314    #[error("obj.container of an evictable dependency's object")]
315    EvictableContainerPath,
316}
317
318/// Which bound was exceeded.
319#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
320#[non_exhaustive]
321pub enum LimitKind {
322    /// [`crate::limits::Limits::max_input_memory`]: the input's meter.
323    InputMemory,
324    /// [`crate::limits::Limits::max_input_bytes`].
325    InputBytes,
326    /// [`crate::limits::Limits::max_block_output`].
327    BlockOutput,
328    /// [`crate::limits::Limits::max_decode_work`]: every byte block decodes
329    /// wrote since the input was opened, and what lazy computations the
330    /// meter refused were granted.
331    DecodeWork,
332    /// [`crate::limits::Limits::max_inflate`].
333    Inflate,
334    /// [`crate::limits::Limits::max_container_depth`].
335    ContainerDepth,
336    /// [`crate::limits::Limits::max_tree_depth`].
337    TreeDepth,
338    /// [`crate::limits::Limits::max_value_depth`].
339    ValueDepth,
340    /// [`crate::limits::Limits::max_values_per_object`].
341    ValuesPerObject,
342    /// [`crate::limits::Limits::max_zero_size_elements`].
343    ZeroSizeElements,
344    /// More nodes, types, objects or ref-type trees than an index type holds.
345    Count,
346}
347
348/// A bound that was exceeded.
349///
350/// Its fields are private, so [`Self::refused`] is the one way to build
351/// one, by the core or by a caller's code: under CR8's test feature it
352/// counts each (`crate::testing`; `docs/plans/batch.md` section 6, CR8).
353/// Round 3 made them private (a public API change, before 1.0), after
354/// three rounds each found a spelling of a literal a source scan missed.
355#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
356#[error("limit {kind:?}: {value} > {max}")]
357pub struct LimitError {
358    kind: LimitKind,
359    value: u64,
360    max: u64,
361}
362
363impl LimitError {
364    /// The refusal of `kind`'s bound by `value` past `max`. Every
365    /// `LimitError` is built here, so the test feature counts each.
366    #[inline]
367    #[must_use]
368    pub fn refused(kind: LimitKind, value: u64, max: u64) -> Self {
369        crate::counters::limit(kind);
370        Self { kind, value, max }
371    }
372
373    /// Which bound.
374    #[must_use]
375    pub const fn kind(&self) -> LimitKind {
376        self.kind
377    }
378
379    /// The value that crossed it.
380    #[must_use]
381    pub const fn value(&self) -> u64 {
382        self.value
383    }
384
385    /// The bound.
386    #[must_use]
387    pub const fn max(&self) -> u64 {
388        self.max
389    }
390}
391
392/// What was not found.
393#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
394#[non_exhaustive]
395pub enum NotFound {
396    /// No CAB or file of that name, loaded or loadable: what a
397    /// [`crate::env::CabResolver::find_file`] returns where UnityPy's
398    /// `find_file` walk raises `FileNotFoundError`.
399    #[error("CAB {0}")]
400    Cab(RawStr),
401    /// No resource under any of UnityPy's candidate names (`ResourceReader.py:10-33`).
402    #[error("resource {0}")]
403    Resource(RawStr),
404    /// A source the environment has no slot for.
405    #[error("source {0}")]
406    Source(u32),
407}
408
409#[cfg(test)]
410mod tests {
411    use super::Error;
412
413    #[test]
414    fn dependency_budget_refusal_follows_entry_and_asset_bundle_wrappers() {
415        use crate::budget::{BudgetExceeded, Reservation};
416        use crate::walk::{ParseError, ReadDetail, ReadError, ReadErrorKind};
417
418        for (what, expected) in [(Reservation::Dependency, true), (Reservation::Input, false)] {
419            let budget = BudgetExceeded { requested: 1, what };
420            let error = Error::Entry {
421                name: "assets".into(),
422                source: super::Arc::new(Error::AssetBundle(super::Arc::new(ParseError::Read(
423                    ReadError {
424                        kind: ReadErrorKind::Other,
425                        at: 0,
426                        detail: ReadDetail::Charge(budget.into()),
427                    },
428                )))),
429            };
430            assert_eq!(error.is_dependency_budget_refusal(), expected);
431        }
432    }
433
434    #[test]
435    fn a_short_read_reports_a_negative_position() {
436        // A one-byte read at -1 (`view[-1:0]` is empty) raises at position -1.
437        let e = Error::OutOfBounds {
438            what: "u8",
439            pos: -1,
440            need: 1,
441            have: 0,
442            reader: crate::stream::ReaderKind::Memory,
443            length: 0,
444        };
445        assert_eq!(e.to_string(), "u8: out of bounds at -1 (need 1, have 0)");
446        let far = Error::OutOfBounds {
447            what: "u8",
448            pos: i128::from(i64::MAX) + 144,
449            need: 1,
450            have: 0,
451            reader: crate::stream::ReaderKind::Memory,
452            length: 0,
453        };
454        assert!(far.to_string().contains("9223372036854775951"));
455    }
456}