unityrs-core 1.0.0

Read and write Unity asset bundles, serialized files and typetrees.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
// Ported from UnityPy 1.25.2 (MIT): UnityPy/environment.py, UnityPy/files/BundleFile.py, UnityPy/files/File.py. See THIRD_PARTY_LICENSES.
//! Loads: [`Environment::load`], [`Environment::load_dependency`] and the
//! files the resolver returns, and the registration of their CABs.

use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};

use super::listing::Listing;
#[cfg(test)]
use super::registry::Hook;
use super::registry::{DepCache, Dependency, Open, Stage, open_source, with_room};
use super::{Cab, Environment, LoadMode, RawCab, Source, source_name};
use crate::budget::Reservation;
use crate::counters::LoadId;
use crate::error::Error;
use crate::files::{BundleFile, File};
use crate::limits::{Charge, Meter};
use crate::raw::RawStr;

/// Reopens a registered dependency without pinning its files in the cache.
pub struct DependencyFile(Arc<Dependency>);

const _: () = crate::send_sync::<DependencyFile>();

impl DependencyFile {
    /// Read through the registered open, retrying with room if the pool refuses.
    pub fn read<T>(&self, mut read: impl FnMut(File) -> Result<T, Error>) -> Result<T, Error> {
        self.0.with_room(|| {
            let file = self.0.handle()?;
            if self.0.unreachable()
                && let Some(cache) = self.0.cache.upgrade()
            {
                cache.forget(&self.0);
            }
            read(file)
        })
    }

    /// Whether a file belongs to this dependency, including across reopens.
    #[must_use]
    pub fn owns(&self, file: &crate::files::SerializedFile) -> bool {
        self.0.meter().same_input(file.meter())
    }
}

/// Whose CABs a registration makes: a caller's file (slots that may hold
/// it), or a dependency's (slots that reopen it), registered one at a time
/// or staged, every one charged before any is published (the registry's
/// module docs, "A failed dependency load").
pub(super) enum Target<'a> {
    Caller,
    Dependency(&'a Arc<Dependency>),
    Staged(&'a Arc<Dependency>, &'a mut Stage),
}

/// The internal error of a dependency's registration under `Lazy` made one
/// key at a time ([`Target::Dependency`]), which no load makes.
fn unstaged() -> Error {
    Error::Malformed {
        what: "registry",
        detail: "a dependency's lazy load registered unstaged".into(),
    }
}

/// Who asked the resolver for the file [`Environment::load_resolved`]
/// loads, which decides how it is loaded and keyed.
#[derive(Clone, Copy, Debug)]
pub(super) enum Asked<'a> {
    /// `find_file(name, is_dependency)`: keyed by the source's name (UnityPy
    /// keys the path it found, `load_file` keying a path by itself).
    Find {
        /// UnityPy's flag (a dereference's `find_file` takes its default,
        /// `True`).
        is_dependency: bool,
    },
    /// A resource read's fallback, `load_file(name, True)`: keyed by the
    /// name it asked for.
    Fallback(&'a RawStr),
}

impl Environment {
    /// `load_file`: detect, parse, register the CABs, add to `files` under the
    /// source's name (a repeated name replaces the value in place, as a dict).
    // The source is handed over (the frozen signature); a caller's load
    // keeps nothing of it but its name.
    #[allow(clippy::needless_pass_by_value)]
    pub fn load(&self, source: Source) -> Result<File, Error> {
        let name = source_name(&source);
        let load_id = LoadId::draw(&name);
        let file = self.load_listed(&name, &source, false, load_id)?;
        self.inner.loaded.fetch_add(1, Ordering::Relaxed);
        Ok(file)
    }

    pub(super) fn load_data(
        &self,
        name: RawStr,
        data: bytes::Bytes,
        reader: crate::stream::ReaderKind,
        meter: &Arc<Meter>,
    ) -> Result<Option<File>, Error> {
        let ty = crate::detect::check_file_type_with_reader(&data, &self.ctx().limits, reader)?;
        if ty == crate::detect::FileType::Zip {
            self.load_zip_data(data, meter)?;
            self.list_zip_none(name, meter)?;
            return Ok(None);
        }
        self.load_detected(name, data, reader, ty, meter, 0)
    }

    pub(super) fn load_detected(
        &self,
        name: RawStr,
        data: bytes::Bytes,
        reader: crate::stream::ReaderKind,
        ty: crate::detect::FileType,
        meter: &Arc<Meter>,
        depth: u32,
    ) -> Result<Option<File>, Error> {
        let file = crate::files::parse_file_at_depth(
            name.clone(),
            data,
            ty,
            None,
            meter,
            self.ctx(),
            reader,
            depth,
        )?;
        let load = self.register_file(&name, &file, &mut Target::Caller)?;
        self.list(name, file.clone(), false, load, meter)?;
        self.inner.loaded.fetch_add(1, Ordering::Relaxed);
        Ok(Some(file))
    }

    /// A load UnityPy's `load_file` makes (the caller's, or a resource
    /// fallback's under `keep_resolver_loads`): its own input meter, its
    /// CABs registered as a caller's, and a `files` entry under `name` at
    /// the load's number, as its registrations are ranked, charged to the
    /// file's meter (a resolver's name copied into its key first; a
    /// caller's own name is shared, not copied). Its bundle's reads are
    /// keyed by `load_id`, which the load drew before its first attempt
    /// (CR8's test feature, `crate::testing`).
    fn load_listed(
        &self,
        name: &RawStr,
        source: &Source,
        resolved: bool,
        load_id: LoadId,
    ) -> Result<File, Error> {
        let ctx = self.ctx();
        let meter = Meter::for_input(&ctx.limits, ctx.budget.clone(), Reservation::Input);
        // UnityPy environment.py:139-160
        let file = open_source(name, source, &meter, ctx, load_id)?;
        let load = self.register_file(name, &file, &mut Target::Caller)?;
        let key = if resolved {
            RawStr::charged(name.as_bytes(), &meter)?
        } else {
            name.clone()
        };
        self.list(key, file.clone(), false, load, &meter)?;
        Ok(file)
    }

    /// Registers the CABs of a top-level `file` loaded under `name`: the
    /// file itself, or a bundle's entries (`Eager`: as UnityPy parses them;
    /// `Lazy`: every directory entry's name now, parsed on first use), or
    /// stages them ([`Target::Staged`]: room for a lazy bundle's directory
    /// reserved first). Every registration is one load's, ranked by its
    /// directory path ([`registry`]); returns the load's number, which its
    /// `files` entry takes ([`Self::list`]).
    ///
    /// [`registry`]: super::registry
    pub(super) fn register_file(
        &self,
        name: &RawStr,
        file: &File,
        target: &mut Target<'_>,
    ) -> Result<u64, Error> {
        // Never: a dependency's load under `Lazy` is staged, so that it
        // publishes nothing when it fails (`try_load_dep`); one that came
        // this way would publish one key at a time (CR1's review, round 2:
        // only a lazy bundle's entries were checked).
        if self.inner.options.load == LoadMode::Lazy && matches!(target, Target::Dependency(_)) {
            return Err(unstaged());
        }
        let reg = &self.inner.registry;
        let load = reg.next_load();
        let registered = match file {
            File::Serialized(sf) => self.register_cab(
                name,
                Cab::Serialized(sf.clone()),
                file.meter(),
                target,
                load,
                &[],
            ),
            File::Raw(raw) => self.register_cab(
                name,
                Cab::Raw(RawCab::File(raw.clone())),
                file.meter(),
                target,
                load,
                &[],
            ),
            File::Bundle(b) => match self.inner.options.load {
                LoadMode::Eager => self.register_eager(b, target, load, &mut Vec::new()),
                LoadMode::Lazy => {
                    if let Target::Staged(_, stage) = target {
                        stage.reserve(b.directory().len())?;
                    }
                    for (i, d) in b.directory().iter().enumerate() {
                        match target {
                            Target::Caller => {
                                reg.register_entry(&d.path, b.clone(), i, load, &[i], b.meter())?;
                            }
                            // Never: refused at the top.
                            Target::Dependency(_) => return Err(unstaged()),
                            Target::Staged(dep, stage) => {
                                reg.stage(stage, &d.path, dep, load, &[i], b.meter(), true)?;
                            }
                        }
                    }
                    Ok(())
                }
            },
            File::Web(w) => self.register_web(w, target, load, &mut Vec::new()),
        };
        registered.map(|()| load)
    }

    fn register_cab(
        &self,
        name: &RawStr,
        cab: Cab,
        meter: &Arc<Meter>,
        target: &mut Target<'_>,
        load: u64,
        path: &[usize],
    ) -> Result<(), Error> {
        let reg = &self.inner.registry;
        match target {
            Target::Caller => reg.register_ready(name, cab, load, path, meter),
            Target::Dependency(dep) => reg.register_dependency(name, dep, load, path, meter),
            Target::Staged(dep, stage) => reg.stage(stage, name, dep, load, path, meter, false),
        }
    }

    /// UnityPy's eager bundle: every block decoded, then every entry parsed
    /// in directory order and each `SerializedFile` and raw entry registered
    /// as it is parsed (`files/BundleFile.py:168-186`, `files/File.py:76-90`),
    /// a nested bundle's entries in place. A failing entry fails the bundle
    /// with the CABs before it registered; a block that fails registers
    /// nothing (plan section 3.13). [`BundleFile::load_all`] decodes and
    /// parses first, so this walk only reads its cells: when it failed with
    /// an entry's error, the blocks all decoded and the entries before the
    /// failing one are registered; any other failure is the decode's.
    fn register_eager(
        &self,
        b: &Arc<BundleFile>,
        target: &mut Target<'_>,
        load: u64,
        path: &mut Vec<usize>,
    ) -> Result<(), Error> {
        let all = b.load_all();
        if let Err(e) = &all
            && !matches!(e, Error::Entry { .. })
        {
            return all;
        }
        for (i, d) in b.directory().iter().enumerate() {
            path.push(i);
            let step = b.entry(i).and_then(|f| {
                self.inner.eager_parsed.fetch_add(1, Ordering::Relaxed);
                match f {
                    File::Bundle(nested) => self.register_eager(&nested, target, load, path),
                    File::Serialized(sf) => self.register_cab(
                        &d.path,
                        Cab::Serialized(sf),
                        b.meter(),
                        target,
                        load,
                        path,
                    ),
                    File::Raw(_) => {
                        let cab = Cab::Raw(RawCab::InBundle {
                            bundle: b.clone(),
                            dir_index: i,
                        });
                        self.register_cab(&d.path, cab, b.meter(), target, load, path)
                    }
                    File::Web(w) => self.register_web(&w, target, load, path),
                }
            });
            path.pop();
            if let Err(e) = step {
                return Err(all.err().unwrap_or(e));
            }
        }
        all
    }

    // files/File.py:76-90: WebFile members register just like bundle members.
    fn register_web(
        &self,
        w: &Arc<crate::files::WebFile>,
        target: &mut Target<'_>,
        load: u64,
        path: &mut Vec<usize>,
    ) -> Result<(), Error> {
        for (i, d) in w.directory().iter().enumerate() {
            path.push(i);
            let result = w.entry(i).and_then(|f| match f {
                File::Bundle(b) => self.register_eager(&b, target, load, path),
                File::Web(w) => self.register_web(&w, target, load, path),
                File::Serialized(sf) => {
                    self.register_cab(&d.path, Cab::Serialized(sf), w.meter(), target, load, path)
                }
                File::Raw(raw) => self.register_cab(
                    &d.path,
                    Cab::Raw(RawCab::File(raw)),
                    w.meter(),
                    target,
                    load,
                    path,
                ),
            });
            path.pop();
            result?;
        }
        Ok(())
    }

    /// Loads `source` as a dependency, as `find_file` loads one through the
    /// resolver: its own meter under [`crate::budget::Reservation::Dependency`]
    /// (so a refusal names the dependency pool), its CABs registered (lazily
    /// under [`LoadMode::Lazy`]) without a strong handle, kept in the LRU and
    /// evictable, and not added to [`Self::files`] (UnityPy has no such call;
    /// a batch engine registers its inputs this way). The returned handle is
    /// the caller's: an eviction drops only the LRU's, so while the caller
    /// holds it the slots reach the same open file through their weak handle.
    ///
    /// Under [`LoadMode::Lazy`] a load that fails publishes nothing: every
    /// registration is charged, with the LRU's entry, before the first is
    /// published, so a refusal at any of them leaves the registry as it was
    /// (the registry's module docs, "A failed dependency load"). Under
    /// [`LoadMode::Eager`] the CABs are registered as they are parsed, as
    /// UnityPy's `load_file` registers them, so a load that fails keeps
    /// those registered before its failure (the partial registration of
    /// the module docs).
    // The source is handed over (the frozen signature) and kept by a clone.
    pub fn load_dependency(&self, source: Source) -> Result<File, Error> {
        self.load_dependency_with_handle(source)
            .map(|(file, _)| file)
    }

    /// Load a dependency and give the caller an evictable handle to its exact
    /// occurrence, even if another dependency registers the same CAB name.
    /// Uses the same dependency pool and eviction retry as
    /// [`Self::load_dependency`].
    #[allow(clippy::needless_pass_by_value)]
    pub fn load_dependency_with_handle(
        &self,
        source: Source,
    ) -> Result<(File, DependencyFile), Error> {
        let name = source_name(&source);
        // Drawn once, so the retry keeps it (CR8's test feature).
        let load_id = LoadId::draw(&name);
        // A pool refusal evicts the others and retries once (plan 3.13); a
        // second refusal fails naming the pool, and nothing of the
        // dependency is kept (its first attempt's charges returned with its
        // handle; under `Lazy` neither attempt published a key).
        with_room(Some(&self.inner.cache), None, || {
            self.try_load_dep(&name, &source, false, load_id)
                .map(|(file, _, _, dep)| (file, DependencyFile(dep)))
        })
    }

    /// One attempt of [`Self::load_dependency_with_handle`], on a meter of its own: the file,
    /// the load's number and, with `listed` under `Lazy`, its `files`
    /// entry under `name` charged and not yet published. Under `Lazy` its
    /// registrations are staged, every one charged, and the LRU's entry and
    /// the listing charged, before the first is published
    /// ([`Self::register_staged`]); under `Eager` each is published as it
    /// is registered, and a listing is the caller's to charge. Its
    /// bundle's reads, and every reopen's, are keyed by `load_id` (CR8's
    /// test feature).
    fn try_load_dep(
        &self,
        name: &RawStr,
        source: &Source,
        listed: bool,
        load_id: LoadId,
    ) -> Result<(File, u64, Option<Listing>, Arc<Dependency>), Error> {
        let ctx = self.ctx();
        let meter = Meter::for_input(&ctx.limits, ctx.budget.clone(), Reservation::Dependency);
        let file = open_source(name, source, &meter, ctx, load_id)?;
        let dep = Arc::new(Dependency {
            name: name.clone(),
            source: source.clone(),
            open: Mutex::new(Open::of(&file, meter)),
            ctx: ctx.clone(),
            cache: Arc::downgrade(&self.inner.cache),
            slots: AtomicUsize::new(0),
            #[cfg(feature = "test-counters")]
            load_id,
        });
        let (load, room, listing) = match self.inner.options.load {
            LoadMode::Lazy => {
                let listed = listed.then_some(name);
                let (load, room, listing) = self.register_staged(&dep, &file, listed)?;
                (load, Some(room), listing)
            }
            LoadMode::Eager => {
                let load = self.register_file(&dep.name, &file, &mut Target::Dependency(&dep))?;
                (load, None, None)
            }
        };
        #[cfg(test)]
        self.inner.cache.hook(Hook::LoadRegistered);
        self.inner.cache.loaded.fetch_add(1, Ordering::Relaxed);
        match room {
            Some(room) => self.inner.cache.touch_paid(&dep, &file, room),
            None => self.inner.cache.touch(&dep, &file)?,
        }
        // Another load registered every key this one did meanwhile: no slot
        // reaches it, and the LRU lets go of it ([`registry`]). The last
        // slot to go before the touch told an LRU that did not hold it yet;
        // one that goes after it tells the LRU itself (`DepSlot`).
        if dep.unreachable() {
            self.inner.cache.forget(&dep);
        }
        #[cfg(test)]
        self.inner.cache.hook(Hook::LoadChecked);
        Ok((file, load, listing, dep))
    }

    /// A dependency's registrations under `Lazy`, staged ([`Stage`]: the
    /// list that holds them, room for a bundle's whole directory charged
    /// first, then each key, slot, new key's share and copy, and position's
    /// path, charged to the dependency's meter), then the LRU's entry
    /// charged ([`DepCache::room`]) and, with `listed`, the `files` entry
    /// under that name (its key's copy, its share and its lowered key,
    /// [`Self::charge_listing`]), then every registration published in the
    /// order it was staged ([`super::registry::Registry::commit`]). A
    /// refusal before the commit drops the stage, which returns every
    /// charge and was never in the registry, so no lookup, on this thread
    /// or another, can have found any of it. Nothing after the commit's
    /// start can fail the load: the `settle` each registration runs keeps a
    /// refusal to itself and leaves the slot it could not reach listed for
    /// a later call, as every `settle` does. The load's number, the LRU
    /// entry's charge for [`DepCache::touch_paid`], and the listing.
    fn register_staged(
        &self,
        dep: &Arc<Dependency>,
        file: &File,
        listed: Option<&RawStr>,
    ) -> Result<(u64, Charge, Option<Listing>), Error> {
        let mut stage = Stage::new(file.meter());
        let load = self.register_file(&dep.name, file, &mut Target::Staged(dep, &mut stage))?;
        let room = DepCache::room(file)?;
        let listing = match listed {
            Some(name) => {
                let key = RawStr::charged(name.as_bytes(), file.meter())?;
                Some(Self::charge_listing(key, file.meter())?)
            }
            None => None,
        };
        self.inner.registry.commit(stage)?;
        Ok((load, room, listing))
    }

    /// A file the resolver returned (module docs, "Resolver loads in
    /// `files`"). With `keep_resolver_loads`: `find_file`'s
    /// ([`Asked::Find`]) with `is_dependency` is a dependency, listed in
    /// `files` under the source's name (flagged a dependency unless it is a
    /// raw reader, which UnityPy gives no flag); without `is_dependency` a caller's
    /// load under that name (UnityPy's `load_file(fp, name=name,
    /// is_dependency=False)`, `environment.py:332`, `:354`); a resource
    /// fallback's ([`Asked::Fallback`]) is a caller's load under the name it
    /// asked for. Without `keep_resolver_loads` every one is a dependency in
    /// the LRU only (`PARITY.md` section 19.3's row "resolver loads under
    /// `keep_resolver_loads` false", and section 19.2's
    /// `SerializedFile.load_dependencies` row).
    ///
    /// Every one of these loads, whatever its listing, is one run of
    /// [`with_room`]: a pool refusal anywhere in it (the source's fetcher's
    /// own included, counted as it returns: `registry::from_callers`)
    /// evicts the other dependencies and loads once more, as
    /// [`Self::load_dep`] does (review round 12: a load listed as no
    /// dependency, `find_file`'s with `is_dependency` false or a resource
    /// fallback's under `keep_resolver_loads`, returned its fetcher's
    /// refusal untried, unless the fallback's candidate step around it
    /// retried it). A listing is charged to the loaded file's meter inside
    /// that run, so a second run loads and lists again (review round 8: a
    /// refused listing failed the load, whose file then stayed registered
    /// and unlisted).
    pub(super) fn load_resolved(&self, source: &Source, asked: Asked<'_>) -> Result<File, Error> {
        let keep = self.inner.options.keep_resolver_loads;
        let resolved;
        let name = match asked {
            Asked::Fallback(name) => name,
            Asked::Find { .. } => {
                resolved = source_name(source);
                &resolved
            }
        };
        // Drawn once, so the retry keeps it (CR8's test feature).
        let load_id = LoadId::draw(name);
        with_room(Some(&self.inner.cache), None, || match asked {
            _ if !keep => self
                .try_load_dep(name, source, false, load_id)
                .map(|(file, ..)| file),
            Asked::Fallback(_)
            | Asked::Find {
                is_dependency: false,
            } => self.load_listed(name, source, true, load_id),
            Asked::Find {
                is_dependency: true,
            } => {
                // Under `Lazy` the listing is charged before the keys are
                // published, so a refused one publishes none of them
                // (`register_staged`); under `Eager`, after.
                let (file, load, listing, _) = self.try_load_dep(name, source, true, load_id)?;
                let listing = if let Some(listing) = listing {
                    listing
                } else {
                    let meter = file.meter();
                    let key = RawStr::charged(name.as_bytes(), meter)?;
                    Self::charge_listing(key, meter)?
                };
                // A reader has no `is_dependency`: `parse_file` returns the
                // reader itself (`helpers/ImportHelper.py:136-156`), which
                // `getattr(f, "is_dependency", False)` reads false.
                let flag = !matches!(file, File::Raw(_));
                self.publish_listing(listing, file.clone(), flag, load);
                Ok(file)
            }
        })
    }
}