unityrs-core 1.0.0

Read and write Unity asset bundles, serialized files and typetrees.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
// 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.
//! The file-level error type.
//!
//! Object-level outcomes (the canonical dump's L2 kinds) are
//! [`crate::walk::ParseError`]; the writer's are [`crate::walk::WriteError`].
//! `Error` is `Clone` because a lazily computed result, published once into
//! a `OnceLock`, is handed to every later caller.
//!
//! Owner: the scaffold (frozen). A package that needs a new variant asks the
//! integration package; `#[non_exhaustive]` keeps that additive.

use std::sync::Arc;

use crate::budget::{AllocError, BudgetExceeded};
use crate::codec::Codec;
use crate::detect::DetectError;
use crate::limits::{ChargeError, heap_cost};
use crate::once::CellError;
use crate::raw::RawStr;
use crate::typetree::TreeError;
use crate::version::VersionError;
use crate::walk::ParseError;

/// Why loading a file failed. Never a panic.
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    /// `check_file_type` raised (the dump's `"detect"`).
    #[error("detection: {0}")]
    Detect(#[from] DetectError),
    /// A read past the end where UnityPy raises too (`struct.error`, `EOFError`).
    #[error("{what}: out of bounds at {pos} (need {need}, have {have})")]
    OutOfBounds {
        /// What was being read.
        what: &'static str,
        /// The reader's position at the read: a Python position, which may be
        /// negative or past the end ([`crate::stream::Reader::position`]).
        pos: i128,
        /// Bytes needed.
        need: u64,
        /// Bytes left.
        have: u64,
        /// Rules of the reader whose read failed.
        reader: crate::stream::ReaderKind,
        /// Size of that reader's buffer, including after decompression.
        length: usize,
    },
    /// Input UnityPy rejects with an exception other than a short read.
    #[error("malformed {what}: {detail}")]
    Malformed {
        /// What was being read.
        what: &'static str,
        /// The detail, for people. Shared, so a clone allocates nothing.
        detail: Arc<str>,
    },
    /// The decoded signature rejected by the `WebFile` constructor. Keep only
    /// a charged copy, so an error cannot retain an entire inflated input.
    #[error("malformed WebFile: invalid signature")]
    WebSignature(RawStr),
    /// The rejected bundle signature, copied into charged storage so nested
    /// failures identify their own input without retaining its whole buffer.
    #[error("malformed bundle signature: Unknown Bundle signature")]
    BundleSignature(RawStr),
    /// A format or feature unityrs does not read (yet), each named.
    #[error("unsupported: {0}")]
    Unsupported(Unsupported),
    /// UnityPy's key setter raises `ValueError` for this length.
    #[error("AssetBundle Key length is wrong. It should be 16 bytes and now is {length} bytes.")]
    UnityCnKeyLength {
        /// Supplied length in bytes.
        length: usize,
    },
    /// UnityPy raises `LookupError` after reading an encrypted header without a key.
    #[error("The BundleFile is encrypted, but no key was provided!")]
    UnityCnKeyMissing,
    /// AES raises `ValueError` for a short header key vector.
    #[error("Data must be aligned to block boundary in ECB mode (got {length} bytes)")]
    UnityCnVectorLength {
        /// Bytes read from the vector.
        length: usize,
    },
    /// UnityPy raises a plain `Exception` when the AES signature differs.
    #[error("Invalid UnityCN signature")]
    UnityCnSignature,
    /// A block failed to decode.
    #[error("{codec:?} block: {detail}")]
    Decompress {
        /// The block's codec.
        codec: Codec,
        /// The decoder's message. Shared, so a clone allocates nothing.
        detail: Arc<str>,
    },
    /// A version string did not parse, or no fallback was set.
    #[error(transparent)]
    Version(#[from] VersionError),
    /// From format 16, an object's `type_id` outside `types` (Python indexing:
    /// negative counts from the end; `ObjectReader.py:98-101`).
    #[error("type index {index} out of range ({len} types)")]
    TypeIndex {
        /// The object's `type_id`.
        index: i32,
        /// How many types the file has.
        len: usize,
    },
    /// A typetree's rows could not be built into a tree, or the tree is over a limit.
    #[error(transparent)]
    Tree(#[from] TreeError),
    /// The AssetBundle object read at load failed, which fails the file
    /// (`SerializedFile.py:316-324`; `CANONICAL_DUMP.md` section 7).
    #[error("AssetBundle: {0}")]
    AssetBundle(Arc<ParseError>),
    /// A bundle entry failed, which fails the bundle (`File.py:76-90`).
    #[error("entry {name}: {source}")]
    Entry {
        /// The entry's directory path.
        name: RawStr,
        /// Why it failed.
        source: Arc<Error>,
    },
    /// A bound from [`crate::limits::Limits`] was exceeded (the input's
    /// meter included: [`LimitKind::InputMemory`]).
    #[error(transparent)]
    Limit(#[from] LimitError),
    /// The memory budget refused a reservation, or the allocator failed.
    #[error(transparent)]
    Budget(#[from] BudgetExceeded),
    /// The host allocator refused storage; no heap-owned source is retained.
    #[error(transparent)]
    Allocator(#[from] AllocError),
    /// A CAB, external, object or resource that is not there.
    #[error("not found: {0}")]
    NotFound(NotFound),
    /// A pointer that could not be followed where the caller raises it (the
    /// container preload, `helpers/ContainerHelper.py:43-46`, plan 3.13).
    /// A failure to load the target is that load's own error, never this.
    #[error(transparent)]
    Deref(Arc<crate::env::DerefError>),
    /// An I/O error from a source.
    #[error("io: {0}")]
    Io(IoError),
}

impl Error {
    /// Whether the dependency budget refused a reservation, including when
    /// an entry or object read wraps the refusal. A refusal carried inside a
    /// `ParseError::Provider` is not recognised here; callers that retry
    /// provider reads classify that case themselves.
    #[must_use]
    pub fn is_dependency_budget_refusal(&self) -> bool {
        crate::env::registry::pool_refused(self)
    }
}

/// An I/O error, shared because [`Error`] is `Clone`. `std::io::Error` has
/// no equality, so two are equal when their kinds and OS error codes are.
#[derive(Clone, Debug, thiserror::Error)]
#[error("{0}")]
pub struct IoError(pub Arc<std::io::Error>);

impl PartialEq for IoError {
    fn eq(&self, other: &Self) -> bool {
        self.0.kind() == other.0.kind() && self.0.raw_os_error() == other.0.raw_os_error()
    }
}

impl Eq for IoError {}

const _: () = crate::send_sync::<IoError>();

impl From<ChargeError> for Error {
    fn from(e: ChargeError) -> Self {
        match e {
            ChargeError::Limit(l) => Self::Limit(l),
            ChargeError::Budget(b) => Self::Budget(b),
            ChargeError::Allocator(a) => Self::Allocator(a),
        }
    }
}

impl From<std::io::Error> for Error {
    fn from(e: std::io::Error) -> Self {
        Self::Io(IoError(Arc::new(e)))
    }
}

/// [`heap_cost`] of `n` bytes.
pub(crate) fn heap_of(n: usize) -> u64 {
    heap_cost(u64::try_from(n).unwrap_or(u64::MAX))
}

/// [`heap_cost`] of an `Arc` of `n` bytes: its two counts and the bytes.
pub(crate) fn arc_heap_of(n: usize) -> u64 {
    heap_of(n.saturating_add(2 * size_of::<usize>()))
}

impl ChargeError {
    /// Whether the refusal depends on what else is held (a budget, or the
    /// input's meter), not on the input alone ([`crate::once`]).
    #[must_use]
    pub fn is_transient(&self) -> bool {
        match self {
            Self::Budget(_) | Self::Allocator(_) => true,
            Self::Limit(l) => l.kind == LimitKind::InputMemory,
        }
    }

    /// Whether the input's own meter refused ([`LimitKind::InputMemory`]),
    /// not the budget ([`crate::once::CellError::is_meter_refusal`]).
    #[must_use]
    pub fn is_meter_refusal(&self) -> bool {
        matches!(self, Self::Limit(l) if l.kind == LimitKind::InputMemory)
    }
}

impl CellError for Error {
    fn is_transient(&self) -> bool {
        match self {
            Self::Budget(_)
            | Self::Allocator(_)
            | Self::Io(_)
            | Self::Detect(DetectError::Allocator(_)) => true,
            Self::Limit(l) => l.kind == LimitKind::InputMemory,
            Self::Tree(t) => t.is_transient(),
            Self::AssetBundle(p) => p.is_transient(),
            Self::Entry { source, .. } => source.is_transient(),
            Self::Deref(d) => d.is_transient(),
            _ => false,
        }
    }

    fn is_meter_refusal(&self) -> bool {
        match self {
            Self::Limit(l) => l.kind == LimitKind::InputMemory,
            Self::Tree(t) => t.is_meter_refusal(),
            Self::AssetBundle(p) => p.is_meter_refusal(),
            Self::Entry { source, .. } => source.is_meter_refusal(),
            Self::Deref(d) => d.is_meter_refusal(),
            _ => false,
        }
    }

    fn heap_bytes(&self) -> u64 {
        match self {
            Self::Detect(DetectError::Gzip(d) | DetectError::GzipCrc { detail: d, .. }) => {
                arc_heap_of(d.len())
            }
            Self::Malformed { detail, .. } | Self::Decompress { detail, .. } => {
                arc_heap_of(detail.len())
            }
            Self::Version(VersionError::NoMatch(r))
            | Self::WebSignature(r)
            | Self::BundleSignature(r)
            | Self::NotFound(NotFound::Cab(r) | NotFound::Resource(r)) => heap_of(r.len()),
            Self::Tree(t) => t.heap_bytes(),
            Self::AssetBundle(p) => {
                arc_heap_of(size_of::<ParseError>()).saturating_add(p.heap_bytes())
            }
            Self::Entry { name, source } => heap_of(name.len())
                .saturating_add(arc_heap_of(size_of::<Self>()))
                .saturating_add(source.heap_bytes()),
            Self::Deref(d) => {
                arc_heap_of(size_of::<crate::env::DerefError>()).saturating_add(d.heap_bytes())
            }
            _ => 0,
        }
    }

    fn work_refused(limit: LimitError) -> Self {
        Self::Limit(limit)
    }
}

/// Formats and features that are named and refused, never guessed at.
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum Unsupported {
    /// The `UnityArchive` signature; UnityPy raises too (`files/BundleFile.py:41`).
    #[error("UnityArchive bundles")]
    UnityArchive,
    /// LZHAM blocks; UnityPy raises too (`CompressionHelper.py:234-235`).
    #[error("LZHAM compression")]
    Lzham,
    /// A compression type no codec is registered for (`files/BundleFile.py:515-521`).
    #[error("compression type {0}")]
    Codec(u8),
    /// Legacy compatibility variant; UnityWeb/UnityRaw layouts are now supported.
    #[error("the UnityWeb/UnityRaw layout")]
    WebRawLayout,
    /// Legacy compatibility variant; WebFile containers are now supported.
    #[error("WebFile")]
    WebFile,
    /// Tier U: a WebFile entry name length below -1 can rewind forever.
    #[error("WebFile entry name length below -1")]
    WebFileNameLength,
    /// Legacy custom-decryptor refusal. The built-in UnityCN loader instead
    /// returns [`Error::UnityCnKeyMissing`] for a missing load-local key.
    #[error("an encrypted bundle without a decryptor")]
    Encrypted,
    /// Tier U: the token walk would read beyond Boost's trailing zero byte.
    #[error("UnityCN token walk past the trailing zero byte")]
    UnityCnWalk,
    /// A ZIP passed to the single-File parser. `Environment::load_file` and
    /// `Environment::load_zip_file` provide container loading.
    #[error("zip members")]
    Zip,
    /// The parts of a split file (`name.split0`, `name.split1`, ...), which
    /// UnityPy joins before it reads them (`environment.py:25`, `:111-116`,
    /// `:126-127`). Kept for compatibility; core path loading now joins them.
    #[error("split files (.splitN)")]
    Split,
    /// `obj.container` for an object of a dependency the Environment may
    /// evict, whose paths an eviction would drop
    /// ([`crate::env::Environment::container_path`]).
    #[error("obj.container of an evictable dependency's object")]
    EvictableContainerPath,
}

/// Which bound was exceeded.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum LimitKind {
    /// [`crate::limits::Limits::max_input_memory`]: the input's meter.
    InputMemory,
    /// [`crate::limits::Limits::max_input_bytes`].
    InputBytes,
    /// [`crate::limits::Limits::max_block_output`].
    BlockOutput,
    /// [`crate::limits::Limits::max_decode_work`]: every byte block decodes
    /// wrote since the input was opened, and what lazy computations the
    /// meter refused were granted.
    DecodeWork,
    /// [`crate::limits::Limits::max_inflate`].
    Inflate,
    /// [`crate::limits::Limits::max_container_depth`].
    ContainerDepth,
    /// [`crate::limits::Limits::max_tree_depth`].
    TreeDepth,
    /// [`crate::limits::Limits::max_value_depth`].
    ValueDepth,
    /// [`crate::limits::Limits::max_values_per_object`].
    ValuesPerObject,
    /// [`crate::limits::Limits::max_zero_size_elements`].
    ZeroSizeElements,
    /// More nodes, types, objects or ref-type trees than an index type holds.
    Count,
}

/// A bound that was exceeded.
///
/// Its fields are private, so [`Self::refused`] is the one way to build
/// one, by the core or by a caller's code: under CR8's test feature it
/// counts each (`crate::testing`; `docs/plans/batch.md` section 6, CR8).
/// Round 3 made them private (a public API change, before 1.0), after
/// three rounds each found a spelling of a literal a source scan missed.
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
#[error("limit {kind:?}: {value} > {max}")]
pub struct LimitError {
    kind: LimitKind,
    value: u64,
    max: u64,
}

impl LimitError {
    /// The refusal of `kind`'s bound by `value` past `max`. Every
    /// `LimitError` is built here, so the test feature counts each.
    #[inline]
    #[must_use]
    pub fn refused(kind: LimitKind, value: u64, max: u64) -> Self {
        crate::counters::limit(kind);
        Self { kind, value, max }
    }

    /// Which bound.
    #[must_use]
    pub const fn kind(&self) -> LimitKind {
        self.kind
    }

    /// The value that crossed it.
    #[must_use]
    pub const fn value(&self) -> u64 {
        self.value
    }

    /// The bound.
    #[must_use]
    pub const fn max(&self) -> u64 {
        self.max
    }
}

/// What was not found.
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum NotFound {
    /// No CAB or file of that name, loaded or loadable: what a
    /// [`crate::env::CabResolver::find_file`] returns where UnityPy's
    /// `find_file` walk raises `FileNotFoundError`.
    #[error("CAB {0}")]
    Cab(RawStr),
    /// No resource under any of UnityPy's candidate names (`ResourceReader.py:10-33`).
    #[error("resource {0}")]
    Resource(RawStr),
    /// A source the environment has no slot for.
    #[error("source {0}")]
    Source(u32),
}

#[cfg(test)]
mod tests {
    use super::Error;

    #[test]
    fn dependency_budget_refusal_follows_entry_and_asset_bundle_wrappers() {
        use crate::budget::{BudgetExceeded, Reservation};
        use crate::walk::{ParseError, ReadDetail, ReadError, ReadErrorKind};

        for (what, expected) in [(Reservation::Dependency, true), (Reservation::Input, false)] {
            let budget = BudgetExceeded { requested: 1, what };
            let error = Error::Entry {
                name: "assets".into(),
                source: super::Arc::new(Error::AssetBundle(super::Arc::new(ParseError::Read(
                    ReadError {
                        kind: ReadErrorKind::Other,
                        at: 0,
                        detail: ReadDetail::Charge(budget.into()),
                    },
                )))),
            };
            assert_eq!(error.is_dependency_budget_refusal(), expected);
        }
    }

    #[test]
    fn a_short_read_reports_a_negative_position() {
        // A one-byte read at -1 (`view[-1:0]` is empty) raises at position -1.
        let e = Error::OutOfBounds {
            what: "u8",
            pos: -1,
            need: 1,
            have: 0,
            reader: crate::stream::ReaderKind::Memory,
            length: 0,
        };
        assert_eq!(e.to_string(), "u8: out of bounds at -1 (need 1, have 0)");
        let far = Error::OutOfBounds {
            what: "u8",
            pos: i128::from(i64::MAX) + 144,
            need: 1,
            have: 0,
            reader: crate::stream::ReaderKind::Memory,
            length: 0,
        };
        assert!(far.to_string().contains("9223372036854775951"));
    }
}