Skip to main content

unityrs_core/env/
resource.rs

1// Ported from UnityPy 1.25.2 (MIT): UnityPy/helpers/ResourceReader.py. See THIRD_PARTY_LICENSES.
2//! Resource lookup (`helpers/ResourceReader.py:10-38`).
3//!
4//! `get_resource_data(res_path, ...)` tries four CAB names, in order:
5//! `basename`, `name + ".resource"`, `name + ".assets.resS"`,
6//! `name + ".resS"`, where `basename = ntpath.basename(res_path)` and `name`
7//! is `ntpath.splitext(basename)[0]`. On a miss it loads the file's externals
8//! and the four candidates as dependencies, then tries again, and raises
9//! `FileNotFoundError` when all four still miss. The bytes are
10//! `reader.read_bytes(size)` from `offset`.
11//!
12//! **Memory.** `res_path` is an object's string (`m_StreamData.path`,
13//! `m_Resource.m_Source`), a slice of its file as long as the object's
14//! bytes allow. [`resource_candidates`] copies nothing: each [`Candidate`]
15//! is a slice of the path and a static suffix. A lookup that needs the whole
16//! name (the registry's lowered key, a resolver's argument) builds it with
17//! [`Candidate::joined_vec`], charged to the asking file's meter while it lives,
18//! one candidate at a time.
19//!
20//! Owner: package D ([`Candidate`] and its methods: the scaffold).
21
22use std::sync::Arc;
23
24use crate::limits::{ChargeError, Meter};
25use crate::pystr::{ntpath_basename, ntpath_splitext};
26use crate::raw::RawStr;
27
28/// The suffixes of the four candidates, in UnityPy's order.
29pub const SUFFIXES: [&[u8]; 4] = [b"", b".resource", b".assets.resS", b".resS"];
30
31/// One candidate name: a slice of the resource path followed by a suffix,
32/// built in a charged vector when a lookup needs it whole ([`Self::joined_vec`]).
33#[derive(Clone, Debug, PartialEq, Eq)]
34pub struct Candidate {
35    /// A slice of the resource path (no copy): its `basename` for the first
36    /// candidate, that basename's `splitext` root for the others.
37    pub stem: RawStr,
38    /// One of [`SUFFIXES`].
39    pub suffix: &'static [u8],
40}
41
42impl Candidate {
43    /// The name's length in bytes.
44    #[must_use]
45    pub fn len(&self) -> usize {
46        self.stem.len() + self.suffix.len()
47    }
48
49    /// Whether the name is empty.
50    #[must_use]
51    pub fn is_empty(&self) -> bool {
52        self.len() == 0
53    }
54
55    /// The whole lookup name in charged, fallibly allocated storage, without
56    /// a shared `Bytes` owner. Borrow it for registry and resolver lookups.
57    pub fn joined_vec(
58        &self,
59        meter: &Arc<Meter>,
60    ) -> Result<crate::limits::MeteredVec<u8>, ChargeError> {
61        let mut out = crate::limits::MeteredVec::with_capacity(meter, self.len())?;
62        out.extend_from_slice(self.stem.as_bytes())?;
63        out.extend_from_slice(self.suffix)?;
64        Ok(out)
65    }
66
67    /// The whole name: the stem itself when there is no suffix (no copy),
68    /// else the stem and the suffix in one buffer charged to `meter` first
69    /// ([`RawStr::charged_concat`]), which the name carries until its last
70    /// clone drops. A refusal allocates nothing.
71    pub fn joined(&self, meter: &Arc<Meter>) -> Result<RawStr, ChargeError> {
72        if self.suffix.is_empty() {
73            return Ok(self.stem.clone());
74        }
75        RawStr::charged_concat(&[self.stem.as_bytes(), self.suffix], meter)
76    }
77}
78
79const _: () = crate::send_sync::<Candidate>();
80
81/// The four candidates, in UnityPy's order, each a slice of `res_path` and a
82/// suffix (module docs): nothing is copied.
83#[must_use]
84pub fn resource_candidates(res_path: &RawStr) -> [Candidate; 4] {
85    // UnityPy helpers/ResourceReader.py:11-18
86    let path = res_path.as_bytes();
87    let basename = ntpath_basename(path);
88    let (name, _ext) = ntpath_splitext(basename);
89    let slice = |sub: &[u8]| {
90        if sub.is_empty() {
91            RawStr::default()
92        } else {
93            res_path.slice_ref(sub)
94        }
95    };
96    let (basename, name) = (slice(basename), slice(name));
97    let [a, b, c, d] = SUFFIXES;
98    [
99        Candidate {
100            stem: basename,
101            suffix: a,
102        },
103        Candidate {
104            stem: name.clone(),
105            suffix: b,
106        },
107        Candidate {
108            stem: name.clone(),
109            suffix: c,
110        },
111        Candidate {
112            stem: name,
113            suffix: d,
114        },
115    ]
116}
117
118#[cfg(test)]
119mod tests {
120    use std::sync::Arc;
121
122    use super::{Candidate, resource_candidates};
123    use crate::budget::{OWNER_COST, Reservation, Unbounded};
124    use crate::limits::{Meter, heap_cost};
125    use crate::raw::RawStr;
126
127    #[test]
128    fn candidates_are_slices_of_the_path_built_whole_only_when_charged() {
129        // Round 4: `resource_candidates(&[u8]) -> [RawStr; 4]` could only
130        // build four uncharged copies of a basename as long as the object's
131        // bytes, on every resource read.
132        let _: fn(&RawStr) -> [Candidate; 4] = resource_candidates;
133        let path = RawStr::from_shared(bytes::Bytes::from(b"archive:/a/tex.png".to_vec()));
134        let m = Meter::new(1 << 20, Arc::new(Unbounded), Reservation::Input);
135        let first = Candidate {
136            stem: RawStr::from_shared(path.clone().into_bytes().slice(11..)),
137            suffix: b"",
138        };
139        let whole = first.joined(&m).unwrap();
140        assert_eq!(whole.as_bytes(), b"tex.png");
141        assert_eq!(whole.as_bytes().as_ptr(), first.stem.as_bytes().as_ptr());
142        assert_eq!(m.used(), 0, "the basename is the path's own bytes");
143        let res = Candidate {
144            stem: RawStr::from_shared(path.into_bytes().slice(11..14)),
145            suffix: b".assets.resS",
146        };
147        assert_eq!(res.len(), 15);
148        let name = res.joined(&m).unwrap();
149        assert_eq!(name.as_bytes(), b"tex.assets.resS");
150        assert_eq!(m.used(), heap_cost(15) + OWNER_COST);
151        drop(name);
152        assert_eq!(m.used(), 0);
153        let full = Meter::new(OWNER_COST, Arc::new(Unbounded), Reservation::Input);
154        assert!(res.joined(&full).is_err());
155        assert_eq!(full.used(), 0);
156    }
157
158    #[test]
159    fn transient_candidate_names_hold_only_fallible_charged_vector_storage() {
160        let m = Meter::new(1 << 20, Arc::new(Unbounded), Reservation::Input);
161        let candidate = Candidate {
162            stem: RawStr::from_static(b"CAB-test"),
163            suffix: b".resS",
164        };
165        let name = candidate.joined_vec(&m).unwrap();
166        assert_eq!(name.as_slice(), b"CAB-test.resS");
167        assert_eq!(m.used(), heap_cost(13));
168        drop(name);
169        assert_eq!(m.used(), 0);
170        let refused = Meter::new(0, Arc::new(Unbounded), Reservation::Input);
171        assert!(candidate.joined_vec(&refused).is_err());
172        assert_eq!(refused.used(), 0);
173    }
174
175    #[test]
176    fn the_four_candidates_are_unitypys_names_and_copy_nothing() {
177        let path = RawStr::from_shared(bytes::Bytes::from(b"archive:/CAB-1/CAB-1.resS".to_vec()));
178        let c = resource_candidates(&path);
179        let m = Meter::new(1 << 20, Arc::new(Unbounded), Reservation::Input);
180        let names: Vec<Vec<u8>> = c
181            .iter()
182            .map(|c| c.joined(&m).unwrap().as_bytes().to_vec())
183            .collect();
184        assert_eq!(
185            names,
186            [
187                b"CAB-1.resS".to_vec(),
188                b"CAB-1.resource".to_vec(),
189                b"CAB-1.assets.resS".to_vec(),
190                b"CAB-1.resS".to_vec(),
191            ]
192        );
193        for cand in &c {
194            let at = cand.stem.as_bytes().as_ptr() as usize;
195            let base = path.as_bytes().as_ptr() as usize;
196            assert!(
197                (base..base + path.len()).contains(&at),
198                "a slice of the path"
199            );
200        }
201        // A name of leading dots has no extension; a drive is dropped.
202        let c = resource_candidates(&RawStr::from("c:..x"));
203        assert_eq!(c[0].stem.as_bytes(), b"..x");
204        assert_eq!(c[1].stem.as_bytes(), b"..x");
205        let c = resource_candidates(&RawStr::from("dir/"));
206        assert!(c[0].is_empty());
207        assert_eq!(c[3].len(), 5);
208    }
209
210    #[test]
211    fn a_long_path_costs_no_heap_until_one_candidate_is_joined() {
212        // A 100 MB path with no separator: the candidates are slices of it.
213        let long = RawStr::from_shared(bytes::Bytes::from(vec![b'x'; 100 << 20]));
214        let m = Meter::new(u64::MAX, Arc::new(Unbounded), Reservation::Input);
215        let c = resource_candidates(&long);
216        assert_eq!(m.used(), 0);
217        assert_eq!(c[0].stem.as_bytes().as_ptr(), long.as_bytes().as_ptr());
218        let first = c[0].joined(&m).unwrap();
219        assert_eq!(m.used(), 0, "the basename is the path itself");
220        drop(first);
221        let second = c[1].joined(&m).unwrap();
222        assert_eq!(m.used(), heap_cost((100 << 20) + 9) + OWNER_COST);
223        drop(second);
224        assert_eq!(m.used(), 0);
225    }
226}