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
// Ported from UnityPy 1.25.2 (MIT): UnityPy/files/BundleFile.py. See THIRD_PARTY_LICENSES.
// Ported from UnityPy git 417d595 (MIT): UnityPy/files/BundleFile.py, UnityPy/helpers/CompressionHelper.py. See THIRD_PARTY_LICENSES.
//! [`BundleFile::open`]: the header, blocks-info and directory, read as
//! `read_fs` reads them, UnityPy's `files` dict, and where each block's
//! stored bytes are. No data block is decoded.

use std::ops::Range;
use std::sync::Arc;

use bytes::Bytes;

use super::counts::DecodeCounts;
use super::decode::{BlockContext, decode_one};
use super::index::{Ends, RunIndex};
use super::{BlockInfo, BundleFile, BundleHeader, DirEntry, FileSlot, LayoutKind};
use crate::codec::Codec;
use crate::codec::unitycn::UnityCnDecryptor;
use crate::counters::Origin;
use crate::detect::raw_by_name;
use crate::error::{Error, Unsupported};
use crate::files::Parent;
use crate::limits::{Charge, Meter, MeteredVec, heap_cost};
use crate::once::ResultCell;
use crate::options::FileContext;
use crate::raw::RawStr;
use crate::stream::{Endian, Reader, ReaderKind};
use crate::typetree::parse::string_to_null;
use crate::version::{
    FlagsClass, ResolvedVersion, flags_class, resolve_bundle, uses_block_alignment,
};

impl BundleFile {
    /// Reads the header, blocks-info and directory of bytes (the memory
    /// reader's rules). Decodes no data block. Everything it keeps is
    /// charged to `meter`, the input's.
    pub fn open(
        name: RawStr,
        data: Bytes,
        parent: Option<Parent>,
        meter: &Arc<Meter>,
        ctx: &Arc<FileContext>,
    ) -> Result<Arc<Self>, Error> {
        Self::open_with_reader(name, data, parent, meter, ctx, ReaderKind::Memory)
    }

    /// [`Self::open`] by the rules of the reader UnityPy would read `data`
    /// with ([`ReaderKind::Stream`] for a top-level file loaded from a path):
    /// the header, the blocks-info section and the blocks' stored bytes are
    /// read through it; the blocks-info table and the entries are memory
    /// (UnityPy decodes them into bytes, `files/BundleFile.py:141-142`, `:173-186`).
    pub fn open_with_reader(
        name: RawStr,
        data: Bytes,
        parent: Option<Parent>,
        meter: &Arc<Meter>,
        ctx: &Arc<FileContext>,
        reader: ReaderKind,
    ) -> Result<Arc<Self>, Error> {
        Self::open_at_depth(name, data, parent, meter, ctx, reader, 0)
    }

    #[expect(
        clippy::too_many_lines,
        reason = "format-gated header, writable CABs and charged container construction"
    )]
    pub(crate) fn open_at_depth(
        name: RawStr,
        data: Bytes,
        parent: Option<Parent>,
        meter: &Arc<Meter>,
        ctx: &Arc<FileContext>,
        reader: ReaderKind,
        source_depth: u32,
    ) -> Result<Arc<Self>, Error> {
        if legacy_layout(&data, reader)? {
            return super::legacy::open(name, data, parent, meter, ctx, reader, source_depth);
        }
        let mut charge = meter.charge(heap_cost((size_of::<Self>() + 16) as u64))?;
        let mut r = Reader::with_kind(&data, Endian::Big, reader);
        let FsHeader {
            signature,
            format,
            version_player,
            version_engine,
            info_compressed,
            info_uncompressed,
            data_flags,
            engine,
            class,
            encrypted,
            block_alignment,
            unitycn,
        } = read_fs_header(&mut r, &data, &mut charge, ctx)?;
        let blocks_ctx = BlockContext::new(ctx, encrypted, unitycn);
        // :133-139: at the end, `Position = Length - compressedSize` (which a
        // stream refuses when negative), the read, and back to the start.
        let start = r.position();
        let info_range = if data_flags & 0x80 != 0 {
            let len = i128::try_from(data.len()).unwrap_or(i128::MAX);
            r.set_position(len - i128::from(info_compressed))?;
            let range = r.read_range(i64::from(info_compressed))?;
            r.set_position(start)?;
            range
        } else {
            r.read_range(i64::from(info_compressed))?
        };
        let info_read = u32::try_from(info_range.len()).unwrap_or(u32::MAX);
        let blocks_info = BlockInfo {
            uncompressed: info_uncompressed,
            compressed: info_compressed,
            bytes_read: info_read,
            flags: data_flags,
        };
        let info = decode_one(
            &blocks_ctx,
            meter,
            data.slice(info_range),
            info_uncompressed,
            data_flags,
            0,
        )?;
        let (mut blocks, directory, offsets) = read_blocks_info(&info, format, meter)?;
        // :170-171
        if class == FlagsClass::New && data_flags & 0x200 != 0 {
            r.align(16)?;
        }
        // :173-184: the blocks, read in order from here.
        let (stored, lengths) = stored_blocks(&mut blocks, &offsets, &mut r, meter, ctx)?;
        let files = files_dict(&directory, meter)?;
        let entries = entry_cells(directory.len(), meter)?;
        let header = BundleHeader {
            signature,
            format,
            version_player,
            version_engine,
            layout: LayoutKind::Fs,
            engine_version: Some(Ok(engine)),
            data_flags: Some(data_flags),
            flags_class: Some(class),
            block_alignment,
            encrypted,
            hash: None,
            crc: None,
            blocks_info: Some(blocks_info),
        };
        let blocks = keep(blocks, &mut charge)?;
        let directory = keep(directory, &mut charge)?;
        let files = keep(files, &mut charge)?;
        let lengths = keep(lengths, &mut charge)?;
        let entries = keep(entries, &mut charge)?;
        let twins = keep(twins(&directory, meter)?, &mut charge)?;
        let stored = keep(stored, &mut charge)?;
        let (ends, c) = Ends::new(blocks.len(), meter)?;
        charge.absorb(c);
        let runs = RunIndex::mutex(&mut charge)?;
        let constructor_position = r.position();
        Ok(Arc::new_cyclic(|this| Self {
            writable: crate::files::cab::WritableCabs::new(meter),
            changed: std::sync::atomic::AtomicBool::new(false),
            name,
            source: data,
            constructor_position,
            legacy_data: None,
            header,
            blocks,
            directory,
            files,
            parent,
            dependency_path: crate::files::DependencyPath::default(),
            source_depth,
            lengths,
            ends,
            runs,
            counts: DecodeCounts::default(),
            entries,
            twins,
            charge,
            ctx: blocks_ctx,
            stored,
            this: this.clone(),
            origin: Origin::opened(),
        }))
    }
}

/// Where each block's stored bytes are (`reader.read_bytes(compressedSize)`
/// in order from `r`, by its reader's rules: a size is never negative, so
/// the two readers read the same bytes), its `bytes_read` set; and the length cells, a stored
/// block's filled with what was read (`lambda cd, _ucs: cd`) when stored
/// blocks are their own bytes ([`crate::codec::Codecs::stores_as_is`]) and
/// what was read is within the block cap
/// ([`crate::limits::Limits::max_block_output`]). A stored block past the
/// cap is left to its codec, which refuses it with
/// [`crate::LimitKind::BlockOutput`] as it does in `load_all`, so a lazy read
/// fails it as the eager load does.
#[allow(clippy::type_complexity)]
fn stored_blocks(
    blocks: &mut MeteredVec<BlockInfo>,
    offsets: &MeteredVec<u64>,
    r: &mut Reader<'_>,
    meter: &Arc<Meter>,
    ctx: &FileContext,
) -> Result<(MeteredVec<Range<usize>>, MeteredVec<ResultCell<u64, Error>>), Error> {
    let mut stored = MeteredVec::new(meter);
    let mut lengths = MeteredVec::new(meter);
    let base = r.position();
    for (i, b) in blocks.as_mut_slice().iter_mut().enumerate() {
        // HEAD files/BundleFile.py:485-491: offsets are relative to the data
        // start, independent of block order, gaps and alignment.
        if let Some(offset) = offsets.as_slice().get(i) {
            r.set_position(base + i128::from(*offset))?;
        }
        let range = r.read_range(i64::from(b.compressed))?;
        b.bytes_read = u32::try_from(range.len()).unwrap_or(u32::MAX);
        stored.push(range)?;
        let cell = ResultCell::new();
        if known_at_open(b, ctx) {
            let _ = cell.set(Ok(u64::from(b.bytes_read)));
        }
        lengths.push(cell)?;
    }
    Ok((stored, lengths))
}

/// Whether the open takes block `b`'s length from its stored bytes
/// ([`stored_blocks`]): a stored block, while stored blocks are their own
/// bytes and what was read is within the block cap.
pub(super) fn known_at_open(b: &BlockInfo, ctx: &FileContext) -> bool {
    ctx.codecs.stores_as_is()
        && Codec::from_flags(u32::from(b.flags_u16())) == Codec::None
        && u64::from(b.bytes_read) <= ctx.limits.max_block_output
}

/// The header fields `read_fs` reads before the blocks-info section.
struct FsHeader {
    signature: RawStr,
    format: u32,
    version_player: RawStr,
    version_engine: RawStr,
    info_compressed: u32,
    info_uncompressed: u32,
    data_flags: u32,
    engine: ResolvedVersion,
    class: FlagsClass,
    encrypted: bool,
    block_alignment: bool,
    unitycn: Option<UnityCnDecryptor>,
}

/// `BundleFile.__init__` up to the signature dispatch, then `read_fs` up to
/// the blocks-info section (`files/BundleFile.py:36-51`, `:96-131`); leaves `r` where
/// blocks-info would start. Its strings' searches and its engine version's
/// parse are the work of `charge`'s meter, the input's, and the version's
/// heap is charged to `charge`, the bundle's handle.
fn read_fs_header(
    r: &mut Reader<'_>,
    data: &Bytes,
    charge: &mut Charge,
    ctx: &FileContext,
) -> Result<FsHeader, Error> {
    let meter = charge.meter().clone();
    let meter = &meter;
    // UnityPy files/BundleFile.py:36-39
    let signature = string_to_null(r, data, meter)?;
    let format = r.read_u32()?;
    let version_player = string_to_null(r, data, meter)?;
    let version_engine = string_to_null(r, data, meter)?;
    // :41-51
    match signature.as_bytes() {
        b"UnityArchive" => return Err(Error::Unsupported(Unsupported::UnityArchive)),
        b"UnityWeb" | b"UnityRaw" if format != 6 => {
            return Err(Error::Unsupported(Unsupported::WebRawLayout));
        }
        b"UnityWeb" | b"UnityRaw" | b"UnityFS" => {}
        _ => {
            return Err(Error::BundleSignature(RawStr::charged(
                signature.as_bytes(),
                meter,
            )?));
        }
    }
    // :97-106
    let _size = r.read_i64()?;
    let info_compressed = r.read_u32()?;
    let info_uncompressed = r.read_u32()?;
    let data_flags = r.read_u32()?;
    if signature.as_bytes() != b"UnityFS" {
        r.read_i8()?;
    }
    // :108-121
    let engine = resolve_bundle(&version_engine, &ctx.version_policy(), charge)?;
    let class = flags_class(&engine.version)?;
    // :123-124: the encryption flag, before the alignment.
    let mask = match class {
        FlagsClass::Old => 0x200,
        FlagsClass::New => 0x1400,
    };
    let encrypted = data_flags & mask != 0;
    let unitycn = if encrypted {
        if ctx.decryptor.is_some() {
            // A custom decryptor owns its header semantics; retain the existing
            // hook's consumption of the 70-byte UnityCN envelope.
            r.read_u32()?;
            for _ in 0..2 {
                r.read_bytes_short(32);
                r.set_position(r.position() + 1)?;
            }
            None
        } else {
            Some(UnityCnDecryptor::read_with_key(r, || {
                ctx.runtime_config
                    .as_ref()
                    .map_or(Ok(ctx.assetbundle_decrypt_key), |config| {
                        config
                            .resolve_decrypt_key(charge.meter())
                            .map(|key| key.or(ctx.assetbundle_decrypt_key))
                            .map_err(Error::from)
                    })
            })?)
        }
    } else {
        None
    };
    // :129-131
    let block_alignment = uses_block_alignment(format, &engine.version)?;
    if block_alignment {
        r.align(16)?;
    }
    Ok(FsHeader {
        signature,
        format,
        version_player,
        version_engine,
        info_compressed,
        info_uncompressed,
        data_flags,
        engine,
        class,
        encrypted,
        block_alignment,
        unitycn,
    })
}

/// The blocks-info and directory tables (`files/BundleFile.py:141-165`), read
/// big-endian from the decoded section; paths are slices of it.
#[allow(clippy::type_complexity)]
fn read_blocks_info(
    info: &Bytes,
    format: u32,
    meter: &Arc<Meter>,
) -> Result<(MeteredVec<BlockInfo>, MeteredVec<DirEntry>, MeteredVec<u64>), Error> {
    let mut r = Reader::new(info, Endian::Big);
    // The uncompressed-data hash, read and discarded (short at the end).
    r.read_bytes_short(16);
    let mut blocks = MeteredVec::new(meter);
    let mut offsets = MeteredVec::new(meter);
    for _ in 0..r.read_i32()?.max(0) {
        let uncompressed = r.read_u32()?;
        let compressed = r.read_u32()?;
        let flags = u32::from(r.read_u16()?);
        // HEAD helpers/CompressionHelper.py:158-172.
        if format >= 9 {
            offsets.push(r.read_u64()?)?;
        }
        blocks.push(BlockInfo {
            uncompressed,
            compressed,
            bytes_read: 0,
            flags,
        })?;
    }
    let mut directory = MeteredVec::new(meter);
    for _ in 0..r.read_i32()?.max(0) {
        let offset = r.read_i64()?;
        let size = r.read_i64()?;
        let flags = r.read_u32()?;
        let path = string_to_null(&mut r, info, meter)?;
        directory.push(DirEntry {
            offset,
            size,
            flags: Some(flags),
            path,
        })?;
    }
    Ok((blocks, directory, offsets))
}

/// UnityPy's `files` dict over the directory: each path at its first
/// position, holding its last entry. Computed by sorting.
pub(crate) fn files_dict(
    dir: &MeteredVec<DirEntry>,
    meter: &Arc<Meter>,
) -> Result<MeteredVec<FileSlot>, Error> {
    let rows = dir.as_slice();
    let mut perm: MeteredVec<usize> = MeteredVec::with_capacity(meter, rows.len())?;
    for i in 0..rows.len() {
        perm.push(i)?;
    }
    let path = |i: &usize| rows.get(*i).map(|d| d.path.as_bytes()).unwrap_or_default();
    // Stable by the index tiebreak, and in place: a stable sort's scratch
    // (half the rows or more) would be heap no meter charged (plan 3.15).
    perm.as_mut_slice()
        .sort_unstable_by(|a, b| path(a).cmp(path(b)).then(a.cmp(b)));
    let mut groups: MeteredVec<(usize, usize)> = MeteredVec::new(meter);
    let all = perm.as_slice();
    let mut at = 0;
    while let Some(first) = all.get(at) {
        let mut last = *first;
        let mut end = at + 1;
        while let Some(next) = all.get(end).filter(|n| path(n) == path(first)) {
            last = *next;
            end += 1;
        }
        groups.push((*first, last))?;
        at = end;
    }
    groups.as_mut_slice().sort_unstable_by_key(|g| g.0);
    let mut files = MeteredVec::with_capacity(meter, groups.len())?;
    for (first, last) in groups.as_slice() {
        files.push(FileSlot {
            name: rows.get(*first).map(|d| d.path.clone()).unwrap_or_default(),
            dir_index: *last,
        })?;
    }
    Ok(files)
}

/// Each row's first twin (the `bundle` module docs, "Twins"): the first row,
/// in directory order, whose offset, size and name rule
/// ([`crate::detect::raw_by_name`]) are the row's own, or the row itself.
/// Computed by sorting the rows' keys, the scratch charged.
pub(super) fn twins(rows: &[DirEntry], meter: &Arc<Meter>) -> Result<MeteredVec<u32>, Error> {
    let mut keys: MeteredVec<(i64, i64, bool, u32)> = MeteredVec::with_capacity(meter, rows.len())?;
    let mut twins: MeteredVec<u32> = MeteredVec::with_capacity(meter, rows.len())?;
    for (i, d) in rows.iter().enumerate() {
        // A directory holds at most `i32::MAX` rows (its count is an `i32`).
        let i = u32::try_from(i).unwrap_or(u32::MAX);
        keys.push((d.offset, d.size, raw_by_name(d.path.as_bytes()), i))?;
        twins.push(i)?;
    }
    keys.as_mut_slice().sort_unstable();
    let mut first = None;
    for &(offset, size, raw, i) in keys.as_slice() {
        match first {
            Some((key, f)) if key == (offset, size, raw) => {
                if let Some(t) = usize::try_from(i)
                    .ok()
                    .and_then(|i| twins.as_mut_slice().get_mut(i))
                {
                    *t = f;
                }
            }
            _ => first = Some(((offset, size, raw), i)),
        }
    }
    Ok(twins)
}

/// A table as the bundle keeps it, its charge moved into the bundle's.
pub(crate) fn keep<T>(table: MeteredVec<T>, charge: &mut Charge) -> Result<Box<[T]>, Error> {
    let (b, c) = table.into_boxed_slice()?;
    charge.absorb(c);
    Ok(b)
}

fn legacy_layout(data: &Bytes, kind: ReaderKind) -> Result<bool, Error> {
    if !(data.starts_with(b"UnityWeb\0") || data.starts_with(b"UnityRaw\0")) {
        return Ok(false);
    }
    let mut r = Reader::with_kind(data, Endian::Big, kind);
    r.set_position(9)?;
    Ok(r.read_u32()? != 6)
}

fn entry_cells(
    n: usize,
    meter: &Arc<Meter>,
) -> Result<MeteredVec<super::super::teardown::FileCell>, Error> {
    let mut cells = MeteredVec::new(meter);
    for _ in 0..n {
        cells.push(super::super::teardown::FileCell::new())?;
    }
    Ok(cells)
}