Skip to main content

unityrs_core/env/
object_tree.rs

1// Ported from UnityPy 1.25.2 (MIT): UnityPy/files/ObjectReader.py. See THIRD_PARTY_LICENSES.
2//! [`Environment::object_tree`]: the tree an object reads with, and the
3//! `MonoBehaviour` script hook.
4
5use std::sync::Arc;
6
7use super::resource_data::top_container;
8use super::{DerefError, Environment};
9use crate::container::View;
10use crate::object::ObjectRef;
11use crate::provider::{NoTree, ScriptIdent, TreeRef, TreeRequest, TreeSource};
12use crate::typetree::Tree;
13use crate::walk::{ParseError, ReadDetail, ReadError, ReadErrorKind};
14
15/// Whether a read failure is a `ValueError` in UnityPy's object mode, the
16/// one exception `generate_monobehaviour_node`'s caller swallows
17/// (`files/ObjectReader.py:301-304`). Reader errors preserve their Python
18/// categories: bounds can be `ValueError`, `EOFError` or `struct.error`, and
19/// malformed children are `ValueError` in Boost but `IndexError` in Python.
20/// Limits, refused charges and compilation failures are never swallowed.
21fn is_value_error(e: &ParseError) -> bool {
22    match e {
23        ParseError::CheckRead { .. }
24        | ParseError::Deref(DerefError::Null)
25        | ParseError::NoTypeTree {
26            why: Some(NoTree::NoEntry),
27            ..
28        } => true,
29        ParseError::Provider(p) => {
30            p.python_exception
31                .as_ref()
32                .is_some_and(crate::provider::PythonException::is_value_error)
33                && p.limit.is_none()
34                && p.memory.is_none()
35                && p.allocator.is_none()
36        }
37        ParseError::Read(r) => match &r.detail {
38            ReadDetail::Eof { exception, .. }
39            | ReadDetail::BoostEof { exception, .. }
40            | ReadDetail::Python(exception) => {
41                matches!(
42                    *exception,
43                    "ValueError"
44                        | "UnicodeError"
45                        | "UnicodeDecodeError"
46                        | "UnicodeEncodeError"
47                        | "UnicodeTranslateError"
48                )
49            }
50            ReadDetail::NegativeLength(_)
51            | ReadDetail::ArrayChildren
52            | ReadDetail::PairChildren
53            | ReadDetail::RefTypeNotFound => true,
54            ReadDetail::NoRefTypes { reader, absent } => {
55                *reader == crate::value::ReadBy::Boost || !absent
56            }
57            ReadDetail::Stream(e) => e.exception() == "ValueError",
58            ReadDetail::RefTypeNoTree
59            | ReadDetail::Limit(_)
60            | ReadDetail::Charge(_)
61            | ReadDetail::Tree(_) => false,
62        },
63        _ => false,
64    }
65}
66
67/// Failure of the explicit MonoBehaviour generator operation. Only `ValueError`
68/// failures are swallowed by automatic fallback; other failures remain visible.
69#[derive(Debug, thiserror::Error)]
70pub enum MonoBehaviourError {
71    /// No generator installed.
72    #[error("MonoBehaviour detected, but no typetree_generator set to the environment!")]
73    NoGenerator,
74    /// The generator returned no node.
75    #[error("Failed to generate MonoBehaviour node for {}{}{} of {}!", PythonStr(&.0.namespace),
76        if .0.namespace.is_empty() { "" } else { "." }, PythonStr(&.0.class), PythonStr(&.0.assembly))]
77    MissingNode(ScriptIdent),
78    /// The head, script or provider failed.
79    #[error(transparent)]
80    Parse(#[from] ParseError),
81}
82const _: () = crate::send_sync::<MonoBehaviourError>();
83
84/// Python str interpolation leaves valid Unicode, quotes and slashes literal.
85/// Rust strings cannot hold lone surrogates; show those as Unicode escapes.
86struct PythonStr<'a>(&'a crate::RawStr);
87impl std::fmt::Display for PythonStr<'_> {
88    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
89        for chunk in self.0.as_bytes().utf8_chunks() {
90            f.write_str(chunk.valid())?;
91            for &byte in chunk.invalid() {
92                write!(f, "\\u{:04x}", 0xdc00 + u16::from(byte))?;
93            }
94        }
95        Ok(())
96    }
97}
98
99impl MonoBehaviourError {
100    /// Whether UnityPy's automatic tree lookup swallows this failure.
101    #[must_use]
102    pub fn is_value_error(&self) -> bool {
103        match self {
104            Self::NoGenerator | Self::MissingNode(_) => true,
105            Self::Parse(e) => is_value_error(e),
106        }
107    }
108}
109
110impl Environment {
111    /// The tree an object reads with, as UnityPy resolves it
112    /// (`files/ObjectReader.py:285-307`): [`ObjectRef::tree`], plus the
113    /// `MonoBehaviour` script hook. When the tree came from the provider
114    /// chain (not `nodes`, not the type record's own: UnityPy calls
115    /// `generate_monobehaviour_node` only inside `if not node:`,
116    /// `files/ObjectReader.py:296-304`), its root type is `MonoBehaviour`,
117    /// and a provider accepts script requests
118    /// ([`crate::provider::TypeTreeProvider::accepts_scripts`], UnityPy's
119    /// `env.typetree_generator`), the head is read with that tree
120    /// (`check_read` off), `m_Script` is dereferenced through this
121    /// Environment and parsed, and the provider is asked with its
122    /// [`crate::provider::ScriptIdent`]. As in UnityPy only a `ValueError`
123    /// there falls back to the class tree (a null `m_Script`, a head read that
124    /// fails with a value error, the provider's miss); a dereference failure
125    /// (`FileNotFoundError`, `KeyError`, `IndexError`) is the object's error.
126    /// With no such provider nothing is dereferenced (UnityPy raises its
127    /// `ValueError` before any deref), so in P1 this equals [`ObjectRef::tree`].
128    /// Each step that reads a dependency's object through its meter (the
129    /// class tree's compile, for a type record that stores its own tree; the
130    /// head; the script), when the pool refuses it, evicts the others and
131    /// retries once, the object's top-level bundle held from the first step
132    /// on, as the dereference does (plan section 3.13; review round 8, and
133    /// round 9: the compile ran outside the retry, so a pool full of an
134    /// evictable dependency failed every call on an object with an embedded
135    /// tree). The provider chain's lookup charges no meter of the core's.
136    pub fn object_tree(
137        &self,
138        obj: &ObjectRef,
139        nodes: Option<&Arc<Tree>>,
140    ) -> Result<Option<TreeRef>, ParseError> {
141        let _top = top_container(obj.file());
142        let found = self.room(|| obj.tree(nodes))?;
143        let Some(class_tree) = found else {
144            return Ok(None);
145        };
146        let chain = &obj.file().context().providers;
147        if !matches!(class_tree.source, TreeSource::Provider(_))
148            || class_tree.tree.root_type() != b"MonoBehaviour"
149            || !chain.accepts_scripts()
150        {
151            return Ok(Some(class_tree));
152        }
153        match self.generate_monobehaviour_node(obj, Some(&class_tree.tree)) {
154            Ok(tree) => Ok(Some(tree)),
155            Err(e) if e.is_value_error() => Ok(Some(class_tree)),
156            Err(MonoBehaviourError::Parse(e)) => Err(e),
157            Err(_) => Ok(Some(class_tree)),
158        }
159    }
160
161    /// Explicit `generate_monobehaviour_node` (`files/ObjectReader.py:332-350`).
162    /// Unlike automatic fallback, a missing generator, null script or provider
163    /// miss is an error. Embedded trees do not suppress this explicit operation.
164    pub fn generate_monobehaviour_node(
165        &self,
166        obj: &ObjectRef,
167        nodes: Option<&Arc<Tree>>,
168    ) -> Result<TreeRef, MonoBehaviourError> {
169        let _top = top_container(obj.file());
170        let chain = &obj.file().context().providers;
171        if !chain.accepts_scripts() {
172            return Err(MonoBehaviourError::NoGenerator);
173        }
174        let head = self.room(|| obj.parse_monobehaviour_head(nodes))?;
175        let ident = self.script_ident(obj, &head)?;
176        // An explicit head and an embedded script need no file version in
177        // UnityPy. Script lookups use the identity; zero is only the chain's
178        // cache discriminator for files below format 7, never a TPK request.
179        let unversioned = crate::UnityVersion::from_packed(0);
180        let version = obj.file().version().map_or(&unversioned, |v| &v.version);
181        let req = TreeRequest {
182            class_id: obj.class_id(),
183            version,
184            script: Some(&ident),
185        };
186        chain
187            .lookup(&req)
188            .map_err(ParseError::from)?
189            .ok_or(MonoBehaviourError::MissingNode(ident))
190    }
191
192    /// `parse_monobehaviour_head` and `m_Script.deref_parse_as_object()`:
193    /// the script's identity, or `None` where UnityPy raises a `ValueError`
194    /// (the caller falls back to the class tree).
195    fn script_ident(
196        &self,
197        obj: &ObjectRef,
198        head: &crate::Parsed,
199    ) -> Result<ScriptIdent, ParseError> {
200        let attr_error = || {
201            ParseError::Read(ReadError {
202                kind: ReadErrorKind::Other,
203                at: 0,
204                detail: ReadDetail::Python("AttributeError"),
205            })
206        };
207        let view = View::new(head).ok_or_else(attr_error)?;
208        let script = view
209            .attr(view.root(), b"m_Script")
210            .map_err(|_| attr_error())?;
211        let pptr = view.pptr(script).map_err(|_| attr_error())?;
212        // `deref`: a null pointer is a `ValueError`.
213        let target = match self.deref(obj.file(), pptr) {
214            Ok(t) => t,
215            Err(e) => return Err(ParseError::Deref(e)),
216        };
217        // `parse_as_object()`, with check_read enforced locally below.
218        let script = self.room(|| target.read_typetree_object(None, false))?;
219        // UnityPy helpers/TypeTreeHelper.py:155-156 raises ValueError on a
220        // mismatch, swallowed by files/ObjectReader.py:301-304. Avoid
221        // allocating an Arc<Parsed> diagnostic just to discard it here.
222        if script.bytes_read != i64::from(target.info().byte_size) {
223            return Err(ParseError::Read(ReadError {
224                kind: ReadErrorKind::Other,
225                at: 0,
226                detail: ReadDetail::Python("ValueError"),
227            }));
228        }
229        let sview = View::new(&script).ok_or_else(attr_error)?;
230        let field = |name: &[u8]| {
231            sview
232                .attr(sview.root(), name)
233                .map(|n| n.value())
234                .map_err(|_| attr_error())
235        };
236        // The f-string converts numeric identity fields with Python str().
237        let text = |value: &crate::Value| {
238            use crate::Value;
239            let formatted = match value {
240                Value::Str(s) => return Ok(s.clone()),
241                Value::Int(i) => i.to_string(),
242                Value::UInt(i) => i.to_string(),
243                Value::Bool(b) => if *b { "True" } else { "False" }.to_owned(),
244                Value::F32(b) => crate::pyfloat::py_float_repr(f64::from(f32::from_bits(*b))),
245                Value::F64(b) => crate::pyfloat::py_float_repr(f64::from_bits(*b)),
246                _ => return Err(attr_error()),
247            };
248            crate::RawStr::charged(formatted.as_bytes(), target.file().meter())
249                .map_err(|e| ParseError::Read(crate::walk::charge_error(0, e)))
250        };
251        let namespace = text(field(b"m_Namespace")?)?;
252        Ok(ScriptIdent {
253            assembly: match field(b"m_AssemblyName")? {
254                crate::Value::Str(s) => s.clone(),
255                _ => return Err(attr_error()),
256            },
257            namespace,
258            class: text(field(b"m_ClassName")?)?,
259        })
260    }
261}