Skip to main content

unityrs_testkit/env/catalog/
find.rs

1// Ported from UnityPy 1.25.2 (MIT): UnityPy/files/WebFile.py. See THIRD_PARTY_LICENSES.
2//! The scene `Environment::find_file` is recorded on: every kind of file it
3//! can return, found through the CAB registry and through the resolver.
4
5use super::{Bundle, Obj, Scene, bundle, named, res_bytes, row, serialized};
6
7/// One `find_file(name, is_dependency)` call.
8#[derive(Clone, Debug, PartialEq, Eq)]
9pub struct FindAsk {
10    /// The name asked for.
11    pub name: Vec<u8>,
12    /// UnityPy's `is_dependency` (its default is `True`).
13    pub is_dependency: bool,
14}
15
16/// A scene and the `find_file` calls made on it, in order, once its files
17/// are loaded.
18#[derive(Clone, Debug, PartialEq, Eq)]
19pub struct FindScene {
20    /// The files and the resolver's.
21    pub scene: Scene,
22    /// The calls.
23    pub asks: Vec<FindAsk>,
24}
25
26/// A plain WebFile (`UnityWebData1.0`, no compression) of `entries`, as
27/// `files/WebFile.py:40-56` reads one: the signature to its NUL, the header
28/// length, an `(offset, size, name length, name)` row per entry, the data.
29#[must_use]
30pub fn web_file(entries: &[(&str, Vec<u8>)]) -> Vec<u8> {
31    let sig = b"UnityWebData1.0\0";
32    let int = |n: usize| i32::try_from(n).unwrap_or(i32::MAX).to_le_bytes();
33    let head = sig.len() + 4 + entries.iter().map(|(n, _)| 12 + n.len()).sum::<usize>();
34    let mut out = sig.to_vec();
35    out.extend_from_slice(&int(head));
36    let mut offset = head;
37    for (name, data) in entries {
38        out.extend_from_slice(&int(offset));
39        out.extend_from_slice(&int(data.len()));
40        out.extend_from_slice(&int(name.len()));
41        out.extend_from_slice(name.as_bytes());
42        offset += data.len();
43    }
44    for (_, data) in entries {
45        out.extend_from_slice(data);
46    }
47    out
48}
49
50/// Loaded: a bundle of a CAB and its `.resS`, a raw file and a
51/// `SerializedFile` at top level. The resolver (UnityPy's `env.path`): a
52/// bundle of a CAB and its `.resS`, a `SerializedFile`, a raw file, a second
53/// bundle and a WebFile of one CAB. `find_file` is asked for each loaded
54/// kind by its CAB name (the registry), for each resolver file by its name
55/// (UnityPy's `path/name` step), for a CAB a resolver load registered, for
56/// a resolver file again (now in the registry), for a name nothing answers
57/// (the walk's `FileNotFoundError`), for the second bundle with
58/// `is_dependency=False`, and last for the WebFile, which P1 refuses (plan
59/// section 1).
60#[must_use]
61pub fn find_file_kinds() -> FindScene {
62    let cab = |path_id: i64, name: &str| serialized(&[], &[Obj::named(path_id, name, &[])]);
63    let ask = |name: &str, is_dependency: bool| FindAsk {
64        name: name.as_bytes().to_vec(),
65        is_dependency,
66    };
67    FindScene {
68        scene: Scene {
69            files: vec![
70                named(
71                    "a.bundle",
72                    bundle(&[("CAB-A", cab(1, "a1")), ("CAB-A.resS", res_bytes(16, 1))]),
73                ),
74                named("top.resS", res_bytes(24, 0)),
75                named("CAB-T", cab(2, "t2")),
76            ],
77            resolver: vec![
78                named(
79                    "r.bundle",
80                    bundle(&[("CAB-R", cab(3, "r3")), ("CAB-R.resS", res_bytes(8, 5))]),
81                ),
82                named("cab-s", cab(4, "s4")),
83                named("r.resS", res_bytes(12, 7)),
84                named("q.bundle", bundle(&[("CAB-Q", cab(6, "q6"))])),
85                named("w.web", web_file(&[("CAB-W", cab(5, "w5"))])),
86            ],
87        },
88        asks: vec![
89            ask("CAB-A", true),
90            ask("CAB-A.resS", true),
91            ask("top.resS", true),
92            ask("CAB-T", true),
93            ask("r.bundle", true),
94            ask("CAB-R.resS", true),
95            ask("cab-s", true),
96            ask("cab-s", true),
97            ask("r.resS", true),
98            ask("nothing", true),
99            ask("q.bundle", false),
100            ask("w.web", true),
101        ],
102    }
103}
104
105/// What a `find_file` load lists, under each flag. Loaded: a bundle whose
106/// CAB holds a named object and an AssetBundle with one container row. The
107/// resolver: two such bundles, such a `SerializedFile` and a raw file.
108/// `find_file` is asked for the first bundle as a dependency (UnityPy's
109/// default, a dereference's), then with `is_dependency=False` for the second
110/// bundle, the `SerializedFile` and the raw file, then for the
111/// `SerializedFile` again, now the registry's. UnityPy lists each load in
112/// `env.files`, and the objects and container rows of those loaded with
113/// `is_dependency=False` in `env.objects` and `env.container`, which
114/// `EnvOptions::batch()` leaves out (`PARITY.md` section 19.3).
115#[must_use]
116pub fn find_file_listing() -> FindScene {
117    let cab = |path_id: i64, name: &str| {
118        let rows = vec![row(&format!("assets/{name}.asset"), (0, 0), (0, path_id))];
119        serialized(
120            &[],
121            &[
122                Obj::named(path_id, name, &[]),
123                Obj::asset_bundle(
124                    path_id + 1,
125                    Bundle {
126                        rows,
127                        ..Bundle::default()
128                    },
129                ),
130            ],
131        )
132    };
133    let ask = |name: &str, is_dependency: bool| FindAsk {
134        name: name.as_bytes().to_vec(),
135        is_dependency,
136    };
137    FindScene {
138        scene: Scene {
139            files: vec![named("l.bundle", bundle(&[("CAB-L", cab(1, "l1"))]))],
140            resolver: vec![
141                named("d.bundle", bundle(&[("CAB-D", cab(3, "d3"))])),
142                named("n.bundle", bundle(&[("CAB-N", cab(5, "n5"))])),
143                named("cab-m", cab(7, "m7")),
144                named("x.resS", res_bytes(8, 9)),
145            ],
146        },
147        asks: vec![
148            ask("d.bundle", true),
149            ask("n.bundle", false),
150            ask("cab-m", false),
151            ask("x.resS", false),
152            ask("cab-m", true),
153        ],
154    }
155}
156
157/// Every `find_file` scene, by name: what `tools/fixtures/env.py` records.
158#[must_use]
159pub fn find_scenes() -> Vec<(&'static str, FindScene)> {
160    vec![
161        ("find_file_kinds", find_file_kinds()),
162        ("find_file_listing", find_file_listing()),
163    ]
164}