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;
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
#[error("detection: {0}")]
Detect(#[from] DetectError),
#[error("{what}: out of bounds at {pos} (need {need}, have {have})")]
OutOfBounds {
what: &'static str,
pos: i128,
need: u64,
have: u64,
reader: crate::stream::ReaderKind,
length: usize,
},
#[error("malformed {what}: {detail}")]
Malformed {
what: &'static str,
detail: Arc<str>,
},
#[error("malformed WebFile: invalid signature")]
WebSignature(RawStr),
#[error("malformed bundle signature: Unknown Bundle signature")]
BundleSignature(RawStr),
#[error("unsupported: {0}")]
Unsupported(Unsupported),
#[error("AssetBundle Key length is wrong. It should be 16 bytes and now is {length} bytes.")]
UnityCnKeyLength {
length: usize,
},
#[error("The BundleFile is encrypted, but no key was provided!")]
UnityCnKeyMissing,
#[error("Data must be aligned to block boundary in ECB mode (got {length} bytes)")]
UnityCnVectorLength {
length: usize,
},
#[error("Invalid UnityCN signature")]
UnityCnSignature,
#[error("{codec:?} block: {detail}")]
Decompress {
codec: Codec,
detail: Arc<str>,
},
#[error(transparent)]
Version(#[from] VersionError),
#[error("type index {index} out of range ({len} types)")]
TypeIndex {
index: i32,
len: usize,
},
#[error(transparent)]
Tree(#[from] TreeError),
#[error("AssetBundle: {0}")]
AssetBundle(Arc<ParseError>),
#[error("entry {name}: {source}")]
Entry {
name: RawStr,
source: Arc<Error>,
},
#[error(transparent)]
Limit(#[from] LimitError),
#[error(transparent)]
Budget(#[from] BudgetExceeded),
#[error(transparent)]
Allocator(#[from] AllocError),
#[error("not found: {0}")]
NotFound(NotFound),
#[error(transparent)]
Deref(Arc<crate::env::DerefError>),
#[error("io: {0}")]
Io(IoError),
}
impl Error {
#[must_use]
pub fn is_dependency_budget_refusal(&self) -> bool {
crate::env::registry::pool_refused(self)
}
}
#[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)))
}
}
pub(crate) fn heap_of(n: usize) -> u64 {
heap_cost(u64::try_from(n).unwrap_or(u64::MAX))
}
pub(crate) fn arc_heap_of(n: usize) -> u64 {
heap_of(n.saturating_add(2 * size_of::<usize>()))
}
impl ChargeError {
#[must_use]
pub fn is_transient(&self) -> bool {
match self {
Self::Budget(_) | Self::Allocator(_) => true,
Self::Limit(l) => l.kind == LimitKind::InputMemory,
}
}
#[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)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum Unsupported {
#[error("UnityArchive bundles")]
UnityArchive,
#[error("LZHAM compression")]
Lzham,
#[error("compression type {0}")]
Codec(u8),
#[error("the UnityWeb/UnityRaw layout")]
WebRawLayout,
#[error("WebFile")]
WebFile,
#[error("WebFile entry name length below -1")]
WebFileNameLength,
#[error("an encrypted bundle without a decryptor")]
Encrypted,
#[error("UnityCN token walk past the trailing zero byte")]
UnityCnWalk,
#[error("zip members")]
Zip,
#[error("split files (.splitN)")]
Split,
#[error("obj.container of an evictable dependency's object")]
EvictableContainerPath,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum LimitKind {
InputMemory,
InputBytes,
BlockOutput,
DecodeWork,
Inflate,
ContainerDepth,
TreeDepth,
ValueDepth,
ValuesPerObject,
ZeroSizeElements,
Count,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
#[error("limit {kind:?}: {value} > {max}")]
pub struct LimitError {
kind: LimitKind,
value: u64,
max: u64,
}
impl LimitError {
#[inline]
#[must_use]
pub fn refused(kind: LimitKind, value: u64, max: u64) -> Self {
crate::counters::limit(kind);
Self { kind, value, max }
}
#[must_use]
pub const fn kind(&self) -> LimitKind {
self.kind
}
#[must_use]
pub const fn value(&self) -> u64 {
self.value
}
#[must_use]
pub const fn max(&self) -> u64 {
self.max
}
}
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum NotFound {
#[error("CAB {0}")]
Cab(RawStr),
#[error("resource {0}")]
Resource(RawStr),
#[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() {
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"));
}
}