Skip to main content

unityrs_core/env/
pptr.rs

1// Ported from UnityPy 1.25.2 (MIT): UnityPy/classes/PPtr.py, UnityPy/environment.py, UnityPy/files/File.py, UnityPy/helpers/ContainerHelper.py. See THIRD_PARTY_LICENSES.
2//! `PPtr` and its dereference (`classes/PPtr.py:15-107`).
3//!
4//! The rules, in UnityPy's order:
5//! 1. `m_PathID == 0` raises `ValueError`.
6//! 2. `m_FileID == 0` is the pointer's own file.
7//! 3. Else `externals[m_FileID - 1]` ([`external_index`]): computed in `i64`
8//!    so `i32::MIN - 1` does not wrap; the guard is only `external_id >= len`
9//!    (`FileNotFoundError`, [`DerefError::FileIdPastEnd`]), then Python
10//!    indexing: a negative `m_FileID` counts from the end, and one below
11//!    `-len` is an `IndexError` ([`DerefError::FileIdBelowStart`]). The two
12//!    are different exceptions. The container preload
13//!    (`helpers/ContainerHelper.py:43-46`, `except (FileNotFoundError,
14//!    KeyError): continue`) swallows [`DerefError::FileIdPastEnd`],
15//!    [`DerefError::NotFound`] and [`DerefError::MissingObject`], and
16//!    propagates [`DerefError::FileIdBelowStart`], [`DerefError::RawTarget`]
17//!    (an `AttributeError`), [`DerefError::Null`] (never reached: the
18//!    preload skips null pointers first), [`DerefError::ContainerDropped`]
19//!    and [`DerefError::Load`].
20//! 4. The file's container (`assetsfile.parent`, `PPtr.py:62-66`): a bundle
21//!    entry's is its bundle; a file loaded at top level has the
22//!    `Environment` that loaded it as its parent (`environment.py:154`,
23//!    `files/File.py:36`), so its container is that Environment. UnityPy's
24//!    "no container is set" is raised only for a `SerializedFile` built
25//!    outside any Environment, which [`super::Environment::deref`] never
26//!    sees: the core has no such refusal. (Probe: two loose files `a/CAB-A`
27//!    and `b/CAB-B`, A's external `archive:/CAB-B/CAB-B`, resolve to B's
28//!    object in UnityPy 1.25.2.) A bundle entry whose bundle has been
29//!    dropped (the `Parent`'s weak handle no longer upgrades) has no
30//!    container to scan: UnityPy cannot reach that state (an object keeps
31//!    `assets_file.parent` alive), so the core does not guess between "no
32//!    sibling" and `find_file`, and fails with
33//!    [`DerefError::ContainerDropped`].
34//! 5. The external path is cleaned ([`crate::pystr::clean_external_path`]) and
35//!    compared with each key of the container's `files` dict lower-cased with
36//!    `str.lower` (no basename): a bundle's directory paths, or the
37//!    Environment's `files` keys, the names given to `load`, dependencies
38//!    included. The first equal key wins, even when its ZIP value is None:
39//!    that raises `FileNotFoundError` without trying the CAB registry
40//!    (`classes/PPtr.py:75-88`). Else `find_file` (the CAB registry,
41//!    then the resolver), whose miss is `FileNotFoundError`: its `None`, and
42//!    the walk's own `FileNotFoundError` (a resolver's
43//!    [`super::CabResolver::find_file`] error naming
44//!    [`crate::error::NotFound::Cab`]), are [`DerefError::NotFound`].
45//! 6. The target's `objects[m_PathID]`: a missing id is a `KeyError`; a raw
46//!    target or a container (a bundle under an Environment `files` key) has no
47//!    `objects` (`AttributeError`).
48//!
49//! Owner: package D. The types and [`external_index`] are frozen (the
50//! scaffold implements [`external_index`]; `tests/fixtures/scaffold/pptr_external.json`
51//! pins it).
52
53use crate::error::Error;
54use crate::once::CellError;
55use crate::raw::RawStr;
56
57/// A pointer: `m_FileID` and `m_PathID`.
58#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
59pub struct PPtr {
60    /// `m_FileID`: 0 is the pointer's own file, `n` is `externals[n - 1]`.
61    pub file_id: i32,
62    /// `m_PathID`: 0 is null.
63    pub path_id: i64,
64}
65
66impl PPtr {
67    /// `__bool__`: whether the pointer is non-null.
68    #[must_use]
69    pub fn is_set(&self) -> bool {
70        self.path_id != 0
71    }
72}
73
74/// Why `externals[m_FileID - 1]` fails (rule 3).
75#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
76pub enum ExternalIndexError {
77    /// `m_FileID - 1 >= len`: `FileNotFoundError` (`"invalid m_FileID"`).
78    PastEnd,
79    /// `m_FileID - 1 < -len`: Python's `IndexError`.
80    BelowStart,
81}
82
83/// Rule 3: the index into `externals` that `m_FileID` names, as UnityPy
84/// computes it (`PPtr.py:56-60`): `external_id = m_FileID - 1` in a wide
85/// integer, refused when `>= len`, then indexed as a Python list (a negative
86/// id counts from the end). Callers handle `m_FileID == 0` (rule 2) first.
87/// Implemented by the scaffold.
88pub fn external_index(file_id: i32, len: usize) -> Result<usize, ExternalIndexError> {
89    let id = i64::from(file_id) - 1;
90    let len = i64::try_from(len).unwrap_or(i64::MAX);
91    if id >= len {
92        return Err(ExternalIndexError::PastEnd);
93    }
94    let i = if id < 0 { id + len } else { id };
95    usize::try_from(i).map_err(|_| ExternalIndexError::BelowStart)
96}
97
98/// Why a dereference failed, with the exception UnityPy raises.
99#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
100#[non_exhaustive]
101pub enum DerefError {
102    /// `ValueError`: `m_PathID == 0`.
103    #[error("PPtr can't deref with m_PathID == 0!")]
104    Null,
105    /// `FileNotFoundError`: `m_FileID - 1 >= len(externals)`.
106    #[error("Failed to resolve pointer - invalid m_FileID {file_id}")]
107    FileIdPastEnd {
108        /// `m_FileID`.
109        file_id: i32,
110    },
111    /// `IndexError`: `m_FileID - 1 < -len(externals)`.
112    #[error("list index out of range (m_FileID {file_id})")]
113    FileIdBelowStart {
114        /// `m_FileID`.
115        file_id: i32,
116    },
117    /// `FileNotFoundError`: no sibling, CAB or resolver hit.
118    #[error("Failed to resolve pointer - {path} not found!")]
119    NotFound {
120        /// The external's path, as stored.
121        path: RawStr,
122    },
123    /// `AttributeError`: the target is a raw file, or a container under an
124    /// Environment `files` key, neither of which has `objects`.
125    #[error("pointer target {name} is not a SerializedFile")]
126    RawTarget {
127        /// The target's name.
128        name: RawStr,
129    },
130    /// `KeyError`: no such object in the target.
131    #[error("no object {path_id} in {file}")]
132    MissingObject {
133        /// The target file's name.
134        file: RawStr,
135        /// `m_PathID`.
136        path_id: i64,
137    },
138    /// The pointer's file is a bundle entry whose bundle has been dropped,
139    /// so its siblings cannot be scanned (rule 4; UnityPy cannot reach this:
140    /// a caller that hands out a file keeps its bundle).
141    #[error("the bundle {name} of the pointer's file was dropped")]
142    ContainerDropped {
143        /// The bundle's name ([`crate::files::Parent::name`]).
144        name: RawStr,
145    },
146    /// Loading the target failed.
147    #[error(transparent)]
148    Load(#[from] Error),
149}
150
151impl From<crate::budget::AllocError> for DerefError {
152    fn from(error: crate::budget::AllocError) -> Self {
153        Self::Load(error.into())
154    }
155}
156
157impl DerefError {
158    /// Whether it depends on what else is held ([`crate::once::CellError`]):
159    /// only a load's own transient failure does.
160    pub(crate) fn is_transient(&self) -> bool {
161        matches!(self, Self::Load(e) if e.is_transient())
162    }
163
164    /// Whether the input's own meter refused the load.
165    pub(crate) fn is_meter_refusal(&self) -> bool {
166        matches!(self, Self::Load(e) if e.is_meter_refusal())
167    }
168
169    /// The heap its names (or its load's error) hold.
170    pub(crate) fn heap_bytes(&self) -> u64 {
171        match self {
172            Self::NotFound { path: n }
173            | Self::RawTarget { name: n }
174            | Self::MissingObject { file: n, .. }
175            | Self::ContainerDropped { name: n } => crate::error::heap_of(n.len()),
176            Self::Load(e) => e.heap_bytes(),
177            Self::Null | Self::FileIdPastEnd { .. } | Self::FileIdBelowStart { .. } => 0,
178        }
179    }
180}