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
542
543
544
545
546
547
548
// Ported from UnityPy 1.25.2 (MIT): UnityPy/environment.py. See THIRD_PARTY_LICENSES.
//! A dependency's record ([`Dependency`]): what reopens it after an
//! eviction, and the weak handle on the file the LRU keeps open;
//! [`open_source`], which reads a source, detects it and parses it; and
//! [`with_room`], the one retry every dependency read or registration the
//! pool refuses takes.

use std::cell::Cell;
use std::ops::Deref;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, Weak};

use super::{DepCache, lock};
use crate::budget::Reservation;
use crate::counters::LoadId;
use crate::detect::check_file_type_with_reader;
use crate::env::{DerefError, Fetch, Source, within_input_bytes};
use crate::error::Error;
use crate::files::{BundleFile, File, RawFile, SerializedFile, parse_file_with_reader};
use crate::limits::{ChargeError, Meter, pool_refusals, refusal};
use crate::options::FileContext;
use crate::raw::RawStr;
use crate::stream::ReaderKind;
use crate::typetree::TreeError;
use crate::walk::{ParseError, ReadDetail};

/// A dependency the Environment loaded (through the resolver, or
/// `Environment::load_dependency`): what reopens it, and the handle the LRU
/// keeps while it is cached.
#[derive(Debug)]
pub(crate) struct Dependency {
    /// The name it was loaded under.
    pub(crate) name: RawStr,
    /// Where its bytes come from again after an eviction.
    pub(crate) source: Source,
    /// Its current open: the LRU's handle, weakly, and its meter, under one
    /// lock, so a reopen publishes both in one step and no lock is taken
    /// while another is held (plan section 3.16; review round 6: the meter
    /// had a lock of its own, taken while this one was held).
    pub(crate) open: Mutex<Open>,
    /// The context it is parsed with.
    pub(crate) ctx: Arc<FileContext>,
    /// The LRU that keeps its open handle, weakly: the LRU holds the
    /// dependency, so a strong handle back would keep both alive after the
    /// Environment drops.
    pub(crate) cache: Weak<DepCache>,
    /// How many registry slots reach it ([`DepSlot`]): when the last goes,
    /// nothing can reach it any more and the LRU lets go of it.
    pub(crate) slots: AtomicUsize,
    /// Under the test feature, the id its load drew, which every reopen
    /// ([`Self::handle`]) keys its span reads by (`crate::testing`;
    /// `docs/plans/batch.md` section 6, CR8). Only the feature has the
    /// field, so the derived `Debug` is the same without it (round 4: a
    /// field of a unit struct still printed, through `Environment::registry`).
    #[cfg(feature = "test-counters")]
    pub(crate) load_id: LoadId,
}

/// A dependency's current open ([`Dependency::open`]).
#[derive(Debug)]
pub(crate) struct Open {
    /// The LRU's handle, weakly: an eviction drops the LRU's strong one.
    pub(crate) file: Option<WeakFile>,
    /// The meter of the open. An eviction keeps it; the next open is on its
    /// [`Meter::reopen`], which charges the same memory account and has its
    /// own work allowance, so an old open's handle that someone still holds
    /// keeps counting against the old one (plan section 3.13).
    pub(crate) meter: Arc<Meter>,
}

impl Open {
    /// An open of `file` on `meter`.
    pub(crate) fn of(file: &File, meter: Arc<Meter>) -> Self {
        Self {
            file: Some(WeakFile::of(file)),
            meter,
        }
    }

    fn alive(&self) -> Option<File> {
        self.file.as_ref().and_then(WeakFile::upgrade)
    }
}

/// A registry slot's handle on its dependency, counted in
/// [`Dependency::slots`]: made with the slot's kind (before the slot, so
/// a registration refused on the way counts it out again) and dropped with
/// it. The count is decided in one atomic step, so of two slots that drop
/// at once exactly one sees itself the last and makes the LRU let go
/// (review round 2: each tested the dependency's `Arc` count, saw the
/// other's handle, and neither did, which left the dependency in an LRU
/// that never evicts).
#[derive(Debug)]
pub(crate) struct DepSlot(Arc<Dependency>);

impl DepSlot {
    pub(crate) fn new(dep: &Arc<Dependency>) -> Self {
        dep.slots.fetch_add(1, Ordering::AcqRel);
        Self(dep.clone())
    }
}

impl Deref for DepSlot {
    type Target = Arc<Dependency>;

    fn deref(&self) -> &Arc<Dependency> {
        &self.0
    }
}

impl Drop for DepSlot {
    fn drop(&mut self) {
        let last = self.0.slots.fetch_sub(1, Ordering::AcqRel) == 1;
        if let Some(cache) = self.0.cache.upgrade() {
            #[cfg(test)]
            cache.hook(super::Hook::SlotReleased);
            if last {
                cache.forget(&self.0);
            }
        }
    }
}

impl Dependency {
    /// Whether no registry slot reaches it ([`DepSlot`]).
    pub(crate) fn unreachable(&self) -> bool {
        self.slots.load(Ordering::Acquire) == 0
    }
}

#[cfg(test)]
mod batch_view_inventory {
    use super::Dependency;
    use crate::limits::{Meter, heap_cost};

    /// The directory engine uses descriptor-rooted staged paths of at most
    /// 128 bytes, including the longest generated basename. Registry/data
    /// allocations are metered separately. Leave 128 B per member for the
    /// engine's path/member/walk vectors within its 1 KiB view coefficient.
    #[test]
    fn uncharged_dependency_owners_fit_the_bounded_view_share() {
        let owner = heap_cost((size_of::<Dependency>() + 2 * size_of::<usize>()) as u64);
        let paths = 2 * heap_cost(128);
        let basename = heap_cost(16) + heap_cost(32);
        let total = owner + Meter::OWN_HEAP + paths + basename;
        println!(
            "view dependency owner {owner}, meter {}, paths {paths}, name {basename}, total {total}",
            Meter::OWN_HEAP
        );
        assert!(total <= 1024 - 128);
    }
}

/// A weak handle on a dependency's top-level file.
#[derive(Debug)]
pub(crate) enum WeakFile {
    /// A `SerializedFile`.
    Serialized(Weak<SerializedFile>),
    /// A bundle.
    Bundle(Weak<BundleFile>),
    /// A raw file.
    Raw(Weak<RawFile>),
    Web(Weak<crate::files::WebFile>),
}

impl WeakFile {
    pub(crate) fn of(file: &File) -> Self {
        match file {
            File::Serialized(f) => Self::Serialized(Arc::downgrade(f)),
            File::Bundle(f) => Self::Bundle(Arc::downgrade(f)),
            File::Raw(f) => Self::Raw(Arc::downgrade(f)),
            File::Web(f) => Self::Web(Arc::downgrade(f)),
        }
    }

    fn upgrade(&self) -> Option<File> {
        match self {
            Self::Serialized(w) => w.upgrade().map(File::Serialized),
            Self::Bundle(w) => w.upgrade().map(File::Bundle),
            Self::Raw(w) => w.upgrade().map(File::Raw),
            Self::Web(w) => w.upgrade().map(File::Web),
        }
    }
}

/// Reads a source's bytes on `meter` (a [`Source::Path`] through
/// [`crate::env::read_path`], charged first; a [`Source::Fetch`] from its
/// fetcher; [`Source::Bytes`] as they are), detects them and parses them as
/// a top-level file named `name`. A path UnityPy would read as the parts of
/// a split file is joined into one bounded memory source
/// (`environment.py:111-116`), with the terminal-suffix rule of PARITY
/// section 19.2. Other paths are
/// read by the stream reader's rules, as UnityPy reads the file it opens
/// for one (`environment.py:136-139`); bytes, fetched or given, by the
/// memory reader's ([`ReaderKind`]).
///
/// Every source is bounded by [`crate::limits::Limits::max_input_bytes`]
/// ([`within_input_bytes`]): a path by [`crate::env::read_path`], from its
/// length before anything is read; a fetch from the size its fetcher states
/// ([`Fetch::size_hint`]) before it is fetched, then from the length of the
/// bytes it returns; given bytes from their length. Bytes above the bound
/// are refused here, before anything detects, parses or keeps them, and
/// drop with whatever charge they carry (review round 10: a fetch was not
/// bounded at all).
///
/// Under the test feature a bundle the parse opens is keyed by `load`, the
/// id its load drew (`crate::testing`; `docs/plans/batch.md` section 6,
/// CR8), given to it when the parse returns: no code of a caller's runs
/// under it, so a bundle a fetcher or a codec opens itself is read under
/// the bare key.
#[cfg_attr(not(feature = "test-counters"), allow(unused_variables))]
pub(crate) fn open_source(
    name: &RawStr,
    source: &Source,
    meter: &Arc<Meter>,
    ctx: &Arc<FileContext>,
    load: LoadId,
) -> Result<File, Error> {
    let (data, reader) = read_source(source, meter, ctx)?;
    // UnityPy environment.py:139-154
    let ty = check_file_type_with_reader(&data, &ctx.limits, reader)?;
    let file = parse_file_with_reader(name.clone(), data, ty, None, meter, ctx, reader);
    if let Ok(file) = &file
        && meter.reservation() == Reservation::Dependency
    {
        file.mark_dependency_root();
    }
    // A statement only the feature builds, so a build without it is the
    // code it was before the counters.
    #[cfg(feature = "test-counters")]
    crate::testing::adopt(&file, || crate::testing::Key::load(load));
    file
}

/// Read a bounded source once, retaining the reader rules of its origin.
pub(crate) fn read_source(
    source: &Source,
    meter: &Arc<Meter>,
    ctx: &FileContext,
) -> Result<(bytes::Bytes, ReaderKind), Error> {
    let (data, reader) = match source {
        Source::Bytes { data, .. } => (data.clone(), ReaderKind::Memory),
        Source::Path(p) => crate::env::split::read_source_path(p, None, &ctx.limits, meter)?,
        Source::ConfinedPath { path, root } => {
            crate::env::split::read_source_path(path, Some(root), &ctx.limits, meter)?
        }
        Source::Fetch { fetch, .. } => {
            if let Some(stated) = fetch.size_hint() {
                within_input_bytes(stated, &ctx.limits)?;
            }
            fetched(fetch.as_ref())?
        }
    };
    within_input_bytes(data.len() as u64, &ctx.limits)?;
    Ok((data, reader))
}

/// [`open_source`] outside any load: the bare key.
#[cfg(test)]
pub(crate) fn open_bare(
    name: &RawStr,
    source: &Source,
    meter: &Arc<Meter>,
    ctx: &Arc<FileContext>,
) -> Result<File, Error> {
    open_source(name, source, meter, ctx, LoadId::BARE)
}

/// `fetch`'s bytes, a refusal of the dependency pool it returns counted
/// ([`from_callers`]).
fn fetched(fetch: &dyn Fetch) -> Result<(bytes::Bytes, ReaderKind), Error> {
    from_callers(fetch.fetch_with_reader())
}

/// What the caller's code returned to the core (a [`Fetch`]'s bytes, a
/// [`crate::codec::BlockCodec`]'s decode, a
/// [`crate::codec::BlockDecryptor`]'s decryption), a refusal of the
/// dependency pool in it ([`pool_refused`]) counted in [`pool_refusals`] as
/// it enters the core, as every refusal the core makes is counted where it
/// is made. [`with_room`] tells a refusal a retry already met from a later
/// one by that count, so a refusal the caller's code made itself (a fetcher
/// or a codec that reserves its bytes from the pool), had it moved no
/// count, would match a mark an earlier refusal left and go untried
/// (review round 9, for a fetcher's).
///
/// It is counted whatever was counted while the code ran (review round 10:
/// a fetcher's was counted only when nothing had been, so a fetcher that
/// read through the Environment, let go of the refusal its read met twice,
/// then refused the pool itself, returned a refusal that matched its
/// read's mark, and was not retried; and a codec's or a decryptor's was
/// never counted). The returned value cannot say where it came from (a
/// [`crate::budget::BudgetExceeded`] is the caller's to build), so a
/// refusal the code passes on from a call of its own into the Environment,
/// which that call's retry already met, is counted again too: the
/// [`with_room`] around the code then retries it once more, one more run of
/// the code, the price of never skipping the retry the code's own refusal
/// is owed (`room_tests.rs` pins both). The built-in codecs return through
/// the same call, so a refusal of theirs, counted where it was made, is
/// counted again there; that changes no decision, since they make no call
/// into the Environment, whose `with_room` alone sets the mark the count
/// is compared with.
pub(crate) fn from_callers<T>(returned: Result<T, Error>) -> Result<T, Error> {
    returned.inspect_err(|e| {
        if pool_refused(e) {
            // `refusal` counts the refusal it builds; the caller's own is
            // the one returned.
            let _counted = refusal(0, Reservation::Dependency);
        }
    })
}

thread_local! {
    /// The LRU (its address) a [`with_room`] running on this thread is
    /// retrying in: no `with_room` of that Environment retries inside it.
    static RETRYING: Cell<Option<usize>> = const { Cell::new(None) };
    /// The LRU, and this thread's count of pool refusals
    /// ([`pool_refusals`]), when a [`with_room`] of that Environment last
    /// returned a refusal that a retry had already met: an enclosing one
    /// that gets a refusal while the count is still there holds that one.
    /// Cleared when the outermost `with_room` running on this thread
    /// returns ([`Running`]), so it never outlives the call that set it.
    static RETRIED: Cell<Option<(usize, u64)>> = const { Cell::new(None) };
    /// How many [`with_room`]s are running on this thread, nested.
    static RUNNING: Cell<usize> = const { Cell::new(0) };
}

/// Restores [`RETRYING`] when a retry ends, a panic included.
struct Retrying(Option<usize>);

impl Retrying {
    fn enter(at: usize) -> Self {
        Self(RETRYING.replace(Some(at)))
    }
}

impl Drop for Retrying {
    fn drop(&mut self) {
        RETRYING.set(self.0);
    }
}

/// One [`with_room`] running on this thread ([`RUNNING`]). When the
/// outermost one returns, a panic included, [`RETRIED`] is cleared: no
/// `with_room` encloses it, so the mark has no one left to tell, and a
/// later call's retry depends only on that call (review round 9: the mark
/// stayed, and a later call on the thread whose refusal moved no count,
/// a fetcher's own, matched it and was not retried).
struct Running;

impl Running {
    fn enter() -> Self {
        RUNNING.set(RUNNING.get().saturating_add(1));
        Self
    }
}

impl Drop for Running {
    fn drop(&mut self) {
        let left = RUNNING.get().saturating_sub(1);
        RUNNING.set(left);
        if left == 0 {
            RETRIED.set(None);
        }
    }
}

/// Runs `f`, work an Environment call does through a dependency's meter (a
/// dependency's load, a lookup that opens or reads one, a reach of its
/// nested container, a read from its file); when the dependency pool
/// refuses it ([`pool_refused`]), evicts every cached dependency but `keep`
/// and runs it once more, the second refusal being the caller's (plan
/// section 3.13: "a dependency read the pool refuses evicts and retries
/// once"). One rule, wherever the calls nest: a refusal is retried by the
/// innermost `with_room` it reaches, once, and by no other. So a
/// `with_room` passes on, untried, a refusal one inside it already retried
/// (it knows it by this thread's count of pool refusals, which no refusal
/// has moved since: [`RETRIED`]), and none of an Environment retries inside
/// a retry of that Environment's ([`RETRYING`]): the room is made, and
/// what the second run meets is final. A refusal another one inside it met
/// and let go (a `settle` leaves a refusal for the next call) moves the
/// count, so a later one is retried (review round 8: `resource` and
/// `deref` had no retry, and calls that nest, a lookup inside a
/// dereference inside a container pass, retried one refusal at every
/// level). Every refusal moves the count, one the caller's code returns (a
/// fetcher's, a codec's, a decryptor's) included, as it returns
/// ([`from_callers`]), and the mark is cleared when the outermost `with_room`
/// returns ([`Running`]), so whether a refusal is retried depends on the
/// current call alone, never on what the thread ran before it (review
/// round 9). `f` must be work that can run twice: a lookup, a read, or a
/// whole load (whose registrations a second run makes again at its own
/// ranks).
pub(crate) fn with_room<T, E: PoolRefusal>(
    cache: Option<&DepCache>,
    keep: Option<&Arc<Dependency>>,
    mut f: impl FnMut() -> Result<T, E>,
) -> Result<T, E> {
    let at = cache.map_or(0, |c| std::ptr::from_ref(c).addr());
    let _running = Running::enter();
    let first = f();
    let Err(e) = &first else {
        return first;
    };
    if !e.pool_refused() {
        return first;
    }
    if RETRYING.get() == Some(at) || RETRIED.get() == Some((at, pool_refusals())) {
        RETRIED.set(Some((at, pool_refusals())));
        return first;
    }
    drop(first);
    if let Some(cache) = cache {
        cache.evict_others(keep);
    }
    let second = {
        let _retrying = Retrying::enter(at);
        f()
    };
    if matches!(&second, Err(e) if e.pool_refused()) {
        RETRIED.set(Some((at, pool_refusals())));
    }
    second
}

/// An error that may be the dependency pool's refusal, as it is or wrapped
/// ([`pool_refused`]): what [`with_room`] retries.
pub(crate) trait PoolRefusal {
    /// Whether it is the dependency pool refusing a charge.
    fn pool_refused(&self) -> bool;
}

impl PoolRefusal for Error {
    fn pool_refused(&self) -> bool {
        pool_refused(self)
    }
}

impl PoolRefusal for DerefError {
    fn pool_refused(&self) -> bool {
        deref_refused(self)
    }
}

impl PoolRefusal for ParseError {
    fn pool_refused(&self) -> bool {
        parse_refused(self)
    }
}

/// Whether `e` is the dependency pool refusing a charge
/// ([`Reservation::Dependency`]), as it is or wrapped by an error that
/// carries one: an entry's, a tree's, an object read's or a load's, the
/// wrappers [`crate::once::CellError::is_transient`] looks through (review
/// round 7: a refusal while a reopened dependency's entry was parsed came
/// back as the entry's error, and the retry, which matched only a bare
/// refusal, missed it).
pub(crate) fn pool_refused(e: &Error) -> bool {
    match e {
        Error::Budget(b) => b.what == Reservation::Dependency,
        Error::Entry { source, .. } => pool_refused(source),
        Error::Tree(t) => tree_refused(t),
        Error::AssetBundle(p) => parse_refused(p),
        Error::Deref(d) => deref_refused(d),
        _ => false,
    }
}

fn charge_refused(c: &ChargeError) -> bool {
    matches!(c, ChargeError::Budget(b) if b.what == Reservation::Dependency)
}

fn tree_refused(t: &TreeError) -> bool {
    matches!(t, TreeError::Charge(c) if charge_refused(c))
}

fn deref_refused(d: &DerefError) -> bool {
    matches!(d, DerefError::Load(e) if pool_refused(e))
}

fn parse_refused(p: &ParseError) -> bool {
    match p {
        ParseError::Read(r) => match &r.detail {
            ReadDetail::Charge(c) => charge_refused(c),
            ReadDetail::Tree(t) => tree_refused(t),
            _ => false,
        },
        ParseError::Tree(t) => tree_refused(t),
        ParseError::Deref(d) => deref_refused(d),
        _ => false,
    }
}

impl Dependency {
    /// [`with_room`] for a read or a registration of this dependency, which
    /// the eviction keeps.
    pub(crate) fn with_room<T, E: PoolRefusal>(
        self: &Arc<Self>,
        f: impl FnMut() -> Result<T, E>,
    ) -> Result<T, E> {
        with_room(self.cache.upgrade().as_deref(), Some(self), f)
    }

    /// The handle the LRU keeps, opening the dependency again from its
    /// source when it was evicted (on [`Meter::reopen`] of its meter). The
    /// source is read and parsed with no lock held; the first open to
    /// publish wins, and publishes its handle and its meter in one step.
    /// A meter it replaces is dropped after the lock.
    pub(crate) fn handle(self: &Arc<Self>) -> Result<File, Error> {
        let (alive, meter) = {
            let open = lock(&self.open);
            (open.alive(), open.meter.clone())
        };
        if let Some(f) = alive {
            if let Some(cache) = self.cache.upgrade() {
                cache.touch(self, &f)?;
            }
            return Ok(f);
        }
        let meter = meter.reopen();
        #[cfg(feature = "test-counters")]
        let load = self.load_id;
        #[cfg(not(feature = "test-counters"))]
        let load = LoadId::BARE;
        let file = open_source(&self.name, &self.source, &meter, &self.ctx, load)?;
        let (file, _replaced) = {
            let mut open = lock(&self.open);
            if let Some(theirs) = open.alive() {
                (theirs, None)
            } else {
                let mine = Open::of(&file, meter);
                (file, Some(std::mem::replace(&mut *open, mine)))
            }
        };
        if let Some(cache) = self.cache.upgrade() {
            cache.touch(self, &file)?;
        }
        Ok(file)
    }

    /// The open handle if it is alive, without opening anything.
    pub(crate) fn alive(&self) -> Option<File> {
        lock(&self.open).alive()
    }

    /// The meter of its current open.
    pub(crate) fn meter(&self) -> Arc<Meter> {
        lock(&self.open).meter.clone()
    }
}