unityrs_core/files/bundle/mod.rs
1// Ported from UnityPy 1.25.2 (MIT): UnityPy/files/BundleFile.py, UnityPy/files/File.py. See THIRD_PARTY_LICENSES.
2//! `BundleFile` (`files/BundleFile.py`), read lazily.
3//!
4//! [`BundleFile::open`] reads the header, blocks-info and directory and
5//! decodes no data block, so a registry over thousands of bundles is cheap
6//! and [`BundleFile::uncompressed_size`] (the declared total) is known before
7//! any decode (for a caller that plans with it, plan section 4.1).
8//!
9//! **One layout** (plan section 3.6). UnityPy always reads entries from the
10//! `b"".join` of every block's *actual* output (`files/BundleFile.py:173-186`), so
11//! an entry's offset depends on the actual length of every block before it.
12//! Before a lazy read returns bytes ending at joined offset `X`, every block
13//! starting below `X` has a known length (`lengths`): a stored block's is
14//! known at open when slot 0 holds the built-in stored codec
15//! ([`crate::codec::Codecs::stores_as_is`]) and its bytes are within the
16//! block cap ([`crate::limits::Limits::max_block_output`], which a stored
17//! block meets on every path, as it does in `load_all`); an unmeasured
18//! block wholly before the read is decoded with
19//! its output discarded (a measuring decode: charged while it runs, returned
20//! after). An entry is the Python slice `data[offset : offset + size]` of the
21//! joined data (`File.py:78-81`; [`crate::stream::py_read`]). A lazy read
22//! that succeeds returns exactly the slice of [`BundleFile::load_all`]'s
23//! joined data, and a block that fails before or inside the read fails it
24//! as it fails `load_all`; a block that fails only *after* the read fails
25//! `load_all` and not the read (plan section 3.13, difference (c)).
26//!
27//! **Block outcomes.** A block's measurement is kept once known, failures
28//! included: `lengths` holds each block's length or the error its decode
29//! gave, so a block that fails is decoded once and every later read that
30//! needs it fails at once, as UnityPy fails once. A refusal that depends on
31//! what else is held (the meter, the budget) is not kept
32//! ([`crate::once::get_or_publish_result`]).
33//!
34//! **Runs.** The blocks one read overlaps are decoded into one buffer, a run,
35//! cached by its block span (a span of stored blocks that are their own
36//! bytes is one slice of the input, cached as a run too). A read whose span
37//! a cached run covers is a zero-copy slice of it; any other read decodes
38//! its own whole span into a new run, so a block that two spans share is
39//! decoded once per span. `load_all` decodes every block into one run.
40//! [`BundleFile::entry_range`] is a read like any other: it measures, slices
41//! a covering cached run when there is one, and otherwise decodes its span
42//! into a run it caches, so N ranges in one block decode it once.
43//!
44//! **What a read costs** (`index`). The bundle keeps where each block of the
45//! known prefix ends (the prefix sums of the known lengths, in a table
46//! charged at open), and its cached runs in an index by first block (a
47//! B-tree charged a share per run), in which no run contains another. A read
48//! finds its first block and its span's end by binary search of the prefix
49//! and a covering run by one search of the index, extends the prefix only
50//! past its end (so each block is learned once per open), and decodes only
51//! the blocks of a span no run covers: O(log B + log R) steps besides the
52//! blocks it learns or decodes, for B blocks and R runs. Every step counts
53//! as the open's work, 8 bytes a step (a row a search reads, a block a read
54//! learns, decodes again or checks for a stored slice, a run a publish
55//! drops), so K reads over B blocks count O(K log B) steps, where each read
56//! walked the blocks from block 0 and scanned every run, uncounted
57//! (`tests/bundles/runs.rs`).
58//!
59//! **Memory and work.** Every decode (first, measuring, repeated) writes
60//! into a [`crate::budget::DecodeBuf`] on the input's meter, one segment per
61//! block (each capped at `max_block_output`), so whatever the runs hold is
62//! charged, and a hostile directory whose spans overlap fails with
63//! `LimitKind::InputMemory` instead of growing; every byte a decode writes
64//! also counts as its open's work (`LimitKind::DecodeWork`, on the meter,
65//! which is this open of the input: a reopen after eviction is a new meter
66//! on the same memory, [`crate::limits::Meter::reopen`]), which is not
67//! returned while the open lives (a refused growth counts nothing, and
68//! writes on several threads never pass the bound together). The header,
69//! blocks, directory, `files` and the per-row
70//! cells are charged at open; each parsed entry charges its own file, and
71//! a kept error charges its heap. An entry's cell keeps its parse's
72//! failure, so the row is not parsed again, but every directory row is its
73//! own cell, and rows over one span repeat one parse: what the meter granted
74//! a parse that ends in an error the cell keeps, on its own thread, counts
75//! as the open's work too, so K such rows stop at the open's `DecodeWork`
76//! limit instead of costing K parses no limit sees (round 4;
77//! `tests/bundles/work.rs`). A parse that succeeds keeps its tables (each
78//! row pays for them), and what its AssetBundle read builds and drops is
79//! counted by the read (`files::serialized`, "Work"; round 5). A failure the
80//! cell does not keep (the meter's or the budget's refusal) is
81//! [`crate::once`]'s to count. A block's stored bytes count too, before a
82//! codec reads them, as credit for what it writes (`decode`, "The input is
83//! work"; round 6: LZ4 scans a whole block before it writes, so a nested
84//! bundle whose blocks-info or block fails at its end cost each row over it
85//! a scan no count saw).
86//!
87//! **Twins.** Rows with the same offset and size read the same bytes, and
88//! when their names agree on the one rule that changes what a parse builds
89//! from given bytes (a raw suffix, [`crate::detect::parsed_as`]) they parse
90//! alike, but for the name each file and each wrapped error carries. Such
91//! rows are twins, and they answer a failure as one cell does: the first
92//! failure the input decides kept for any of them (the first twin's cell
93//! holds it) is every twin's answer, under each one's own name, so K rows
94//! over one failing span parse it once (round 6). A twin that parses
95//! successfully parses for itself, as its file carries its name. The table
96//! of first twins is a sort of the directory's keys at open, charged with
97//! the other per-row tables.
98//!
99//! Decodes and user codecs run with no
100//! lock held: a run is decoded first and then published into `runs`, and an
101//! entry is parsed first and then published into its cell
102//! ([`crate::once::get_or_publish_result`]). Publishing a run may grow the
103//! run index under its mutex, which charges the meter and so calls the
104//! budget; the budget's contract forbids it to block or call the core
105//! ([`crate::budget::MemoryBudget`]), and a run replaced or dropped under
106//! the lock is released after it. The known prefix takes no lock: a reader
107//! loads how many blocks it holds and searches them while another thread
108//! extends it.
109//!
110//! UnityPy rules ported exactly (plan section 3.6):
111//! - the extra byte after the data flags only for non-UnityFS signatures
112//! (`files/BundleFile.py:104-106`; rabex reads it for UnityFS, `files/bundlefile/mod.rs:616-618`);
113//! - the flag set by engine version (`files/BundleFile.py:113-121`); the decryptor read *before*
114//! the 16-byte alignment (`:123-124`, then `:129-131`; rabex reads it after,
115//! `files/bundlefile/mod.rs:638-645`); the alignment at format 7 and up or a
116//! 2019 engine at 2019.4.15 or later;
117//! - blocks-info at the end read at `len - compressed` (`files/BundleFile.py:134-137`); padding at
118//! the start only under `ArchiveFlags` with 0x200 (`:170-171`);
119//! - short reads: a truncated block is read short and decoded as it is; its
120//! `bytes_read` is what the dump writes as `compressed`;
121//! - LZMA's output can outgrow its declared size: the block cap
122//! ([`crate::limits::Limits::max_block_output`]) and the input's meter
123//! follow the actual bytes, never the declared ones.
124//!
125//! UnityWeb/UnityRaw: format 6 takes the UnityFS layout. Other formats take
126//! `read_web_raw`, with the legacy payload decoded once at open. `UnityArchive` is
127//! [`crate::Unsupported::UnityArchive`], as UnityPy raises (`files/BundleFile.py:41-42`).
128//!
129//! Owner: package C.
130
131use std::ops::Range;
132use std::sync::{Arc, Mutex, PoisonError, Weak};
133
134use bytes::Bytes;
135
136use crate::counters::{Origin, SpanRow};
137use crate::detect::{DetectError, check_entry_type};
138use crate::error::Error;
139use crate::files::{File, Parent, ParentKind, parse_file};
140use crate::limits::{Charge, GrantScope, Meter};
141use crate::once::{CellError, ResultCell, get_or_publish_result};
142use crate::options::FileContext;
143use crate::raw::RawStr;
144use crate::stream::py_read;
145use crate::version::{FlagsClass, ResolvedVersion, VersionError};
146use index::{Ends, RunIndex};
147
148mod ahead;
149mod counts;
150mod decode;
151mod index;
152mod legacy;
153pub(super) mod open;
154mod runs;
155mod write;
156mod write_legacy;
157
158pub use write::{BundlePacker, BundleSaveOptions};
159
160pub use counts::BundleCounts;
161use counts::DecodeCounts;
162use decode::BlockContext;
163
164/// Which of UnityPy's two readers a bundle takes.
165#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
166pub enum LayoutKind {
167 /// `read_fs`: UnityFS, and UnityWeb/UnityRaw at format 6.
168 Fs,
169 /// `read_web_raw`: UnityWeb/UnityRaw at other formats.
170 WebRaw,
171}
172
173/// The header, as read.
174#[derive(Clone, Debug, PartialEq, Eq)]
175#[non_exhaustive]
176pub struct BundleHeader {
177 /// `signature`.
178 pub signature: RawStr,
179 /// UnityPy's `version`: the format number.
180 pub format: u32,
181 /// `version_player`.
182 pub version_player: RawStr,
183 /// `version_engine`.
184 pub version_engine: RawStr,
185 /// The reader taken.
186 pub layout: LayoutKind,
187 /// `parse_version()`'s result, where loading calls it (the `Fs` layout).
188 /// The dump's `engine_version_packed` comes from it whether or not
189 /// loading called it (`CANONICAL_DUMP.md` 4.2).
190 pub engine_version: Option<Result<ResolvedVersion, VersionError>>,
191 /// The data flags (`Fs` layout).
192 pub data_flags: Option<u32>,
193 /// `ArchiveFlags` or `ArchiveFlagsOld` (`Fs` layout).
194 pub flags_class: Option<FlagsClass>,
195 /// Whether the 16-byte alignment after the header applied.
196 pub block_alignment: bool,
197 /// Whether the encryption flag made UnityPy build a decryptor.
198 pub encrypted: bool,
199 /// The web/raw hash (format 4 and up, not 6).
200 pub hash: Option<[u8; 16]>,
201 /// The web/raw CRC (format 4 and up, not 6).
202 pub crc: Option<u32>,
203 /// The blocks-info section's row (`Fs` layout).
204 pub blocks_info: Option<BlockInfo>,
205}
206
207/// One block (or the blocks-info section).
208#[derive(Clone, Copy, Debug, PartialEq, Eq)]
209#[non_exhaustive]
210pub struct BlockInfo {
211 /// Declared decoded size.
212 pub uncompressed: u32,
213 /// Declared stored size.
214 pub compressed: u32,
215 /// The bytes actually available and read: below `compressed` when the
216 /// file is truncated. The dump writes this as `compressed`.
217 pub bytes_read: u32,
218 /// Flags: `u16` for a block, the data flags for blocks-info.
219 pub flags: u32,
220}
221
222/// One directory row.
223#[derive(Clone, Debug, PartialEq, Eq)]
224#[non_exhaustive]
225pub struct DirEntry {
226 /// Offset in the decoded data.
227 pub offset: i64,
228 /// Size in the decoded data.
229 pub size: i64,
230 /// Flags (`Fs` layout).
231 pub flags: Option<u32>,
232 /// The path, as read.
233 pub path: RawStr,
234}
235
236/// One key of UnityPy's `files` dict: a path at its first position, holding
237/// the last directory entry of that path.
238#[derive(Clone, Debug, PartialEq, Eq)]
239pub struct FileSlot {
240 /// The path.
241 pub name: RawStr,
242 /// The directory index of the entry the dict holds.
243 pub dir_index: usize,
244}
245
246/// A bundle: header and directory parsed, data decoded on demand.
247pub struct BundleFile {
248 pub(crate) writable: super::cab::WritableCabs,
249 pub(super) changed: std::sync::atomic::AtomicBool,
250 name: RawStr,
251 source: Bytes,
252 constructor_position: i128,
253 legacy_data: Option<Bytes>,
254 header: BundleHeader,
255 blocks: Box<[BlockInfo]>,
256 directory: Box<[DirEntry]>,
257 files: Box<[FileSlot]>,
258 parent: Option<Parent>,
259 pub(super) dependency_path: super::DependencyPath,
260 /// Enclosing ZIP levels when this is an Environment file.
261 source_depth: u32,
262 /// Each block's outcome, once known: its actual decoded length (a stored
263 /// block's at open while stored blocks are their own bytes,
264 /// `Codecs::stores_as_is`; any other's when it is first decoded or
265 /// measured), or the error its decode gave, kept so it is not decoded
266 /// again.
267 lengths: Box<[ResultCell<u64, Error>]>,
268 /// Where each block of the known prefix ends in the joined data, found
269 /// by binary search; charged at open, extended with no lock.
270 ends: Ends,
271 /// The cached runs by first block, each run's charge inside its `Bytes`
272 /// and the index's own in it. Locked only to look up or publish.
273 runs: Mutex<RunIndex>,
274 /// What the block decodes wrote, dropped and wrote again
275 /// ([`Self::counts`]).
276 counts: DecodeCounts,
277 /// Parsed entries, by directory index, published once; a kept error
278 /// carries the charge for its heap, and a refused charge is not kept.
279 pub(super) entries: Box<[super::teardown::FileCell]>,
280 /// Each row's first twin (module docs, "Twins"): the first row, in
281 /// directory order, with its offset, size and name rule; a row with no
282 /// earlier twin names itself.
283 twins: Box<[u32]>,
284 /// The caller's context, and whether the header built a decryptor
285 /// (UnityPy's `self.decryptor`): what the blocks decode with.
286 ctx: BlockContext,
287 /// Each block's stored bytes in `source`: the Python slice UnityPy read.
288 stored: Box<[Range<usize>]>,
289 /// This bundle, for its entries' [`ParentKind::Bundle`].
290 this: Weak<BundleFile>,
291 /// Under the test feature, the key its span reads are counted by: its
292 /// load's id and, for a nested bundle, a node naming its row, given by
293 /// the core's open that made it (`crate::testing`, "The key";
294 /// `docs/plans/batch.md` section 6, CR8). Without it a unit struct,
295 /// which takes no room.
296 origin: Origin,
297 /// The handle and its tables (header, blocks, directory, `files`, the
298 /// parse cells), charged to the input at open, with the engine version's
299 /// heap ([`crate::version::UnityVersion::heap_bytes`], charged by the chain
300 /// before it was allocated; its string is the
301 /// header's own slice, never a copy).
302 /// Last so all the storage it covers is freed before its refund.
303 pub(super) charge: Charge,
304}
305
306impl Drop for BundleFile {
307 fn drop(&mut self) {
308 super::teardown::drain(&mut self.entries, &self.charge);
309 }
310}
311
312impl std::fmt::Debug for BundleFile {
313 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
314 f.debug_struct("BundleFile")
315 .field("name", &self.name)
316 .field("header", &self.header)
317 .field("blocks", &self.blocks.len())
318 .field("directory", &self.directory.len())
319 .finish_non_exhaustive()
320 }
321}
322
323impl BundleFile {
324 /// Final cursor of the constructor's outer input reader.
325 #[must_use]
326 pub fn constructor_position(&self) -> i128 {
327 self.constructor_position
328 }
329
330 /// The meter of the input it belongs to (of this open of it); its
331 /// entries, nested bundles included, charge it too.
332 #[must_use]
333 pub fn meter(&self) -> &Arc<Meter> {
334 self.charge.meter()
335 }
336
337 /// The input bytes it was opened on (for telling two handles on one
338 /// input apart from two inputs: a resource read through `from`'s own
339 /// handle, plan section 3.13).
340 #[must_use]
341 pub fn source(&self) -> &Bytes {
342 &self.source
343 }
344
345 /// The name it was opened under.
346 #[must_use]
347 pub fn name(&self) -> &RawStr {
348 &self.name
349 }
350
351 /// The header.
352 #[must_use]
353 pub fn header(&self) -> &BundleHeader {
354 &self.header
355 }
356
357 /// The blocks, in file order (`Fs` layout).
358 #[must_use]
359 pub fn blocks(&self) -> &[BlockInfo] {
360 &self.blocks
361 }
362
363 /// The directory, in file order, repeated paths kept.
364 #[must_use]
365 pub fn directory(&self) -> &[DirEntry] {
366 &self.directory
367 }
368
369 /// Loaded `files` dict, in order. Newly created resource writers are in
370 /// [`Self::writeable_cabs`] and follow these entries when saved.
371 #[must_use]
372 pub fn files(&self) -> &[FileSlot] {
373 &self.files
374 }
375
376 /// The container this bundle is an entry of.
377 #[must_use]
378 pub fn parent(&self) -> Option<&Parent> {
379 self.parent.as_ref()
380 }
381
382 /// The context it was opened with.
383 #[must_use]
384 pub fn context(&self) -> &Arc<FileContext> {
385 self.ctx.file()
386 }
387
388 /// The sum of the blocks' *declared* decoded sizes: what a full decode is
389 /// expected to cost. The actual total can differ (module docs).
390 #[must_use]
391 pub fn uncompressed_size(&self) -> u64 {
392 self.blocks.iter().map(|b| u64::from(b.uncompressed)).sum()
393 }
394
395 /// What this bundle's block reads have decoded, dropped, decoded again
396 /// and cached so far ([`BundleCounts`]; a nested bundle counts its own):
397 /// what plan section 8's R2 and R3 measure. Takes the run index's lock
398 /// for the runs' share.
399 #[must_use]
400 pub fn counts(&self) -> BundleCounts {
401 let runs = self.runs.lock().unwrap_or_else(PoisonError::into_inner);
402 let n = u64::try_from(runs.len()).unwrap_or(u64::MAX);
403 self.counts.snapshot(n, runs.bytes())
404 }
405
406 /// Directory entry `dir_index`'s bytes: the Python slice
407 /// `data[offset : offset + size]` of the joined data (size -1 to the end,
408 /// negative indexes from the end, short at the end). Measures every block
409 /// before the slice first (module docs).
410 pub fn entry_bytes(&self, dir_index: usize) -> Result<Bytes, Error> {
411 let span = self.entry_span(dir_index)?;
412 self.read_span(span.start, span.end, SpanRow::row(dir_index))
413 }
414
415 /// The length of the buffer this bundle's own bytes are a slice of,
416 /// which a slice of a stored block keeps alive (`Parent::pinned`; its
417 /// own length for a top-level bundle).
418 #[must_use]
419 pub fn pinned(&self) -> u64 {
420 let own = u64::try_from(self.source.len()).unwrap_or(u64::MAX);
421 self.parent.as_ref().map_or(own, |p| p.pinned.max(own))
422 }
423
424 /// A byte range of an entry (a `.resS` read), short at the end of the
425 /// entry as a Python slice. It measures every block before the range as
426 /// any read does, slices a cached run that covers the range's blocks, and
427 /// otherwise decodes those blocks into a run it caches, so later ranges
428 /// in the same blocks are slices of it.
429 pub fn entry_range(&self, dir_index: usize, range: Range<u64>) -> Result<Bytes, Error> {
430 let span = self.entry_span(dir_index)?;
431 let lo = span.start.saturating_add(range.start).min(span.end);
432 let hi = span.start.saturating_add(range.end).clamp(lo, span.end);
433 self.read_span(lo, hi, SpanRow::row(dir_index))
434 }
435
436 /// Directory entry `dir_index`, detected and parsed (`parse_file`) and
437 /// published once ([`crate::once::get_or_publish_result`]); under
438 /// contention two callers may both parse it, and the loser's result (and
439 /// its charge) is dropped. A parse the meter or the budget refuses is
440 /// returned and not kept.
441 pub fn entry(&self, dir_index: usize) -> Result<File, Error> {
442 let cell = self
443 .entries
444 .get(dir_index)
445 .ok_or_else(|| no_entry(dir_index))?;
446 get_or_publish_result(cell, self.meter(), || self.parse_entry(dir_index)).cloned()
447 }
448
449 /// UnityPy's eager load (`File.read_files`, `File.py:76-90`): every block
450 /// decoded, every directory entry parsed in order (a path repeated in the
451 /// directory included: its earlier entry can fail the bundle though the
452 /// `files` dict keeps the later one); the first failure fails the bundle.
453 pub fn load_all(&self) -> Result<(), Error> {
454 // UnityPy files/BundleFile.py:173-184: `b"".join` of every block.
455 self.read_span(0, u64::MAX, SpanRow::WHOLE)?;
456 // UnityPy files/File.py:76-90
457 for i in 0..self.directory.len() {
458 match self.entry(i)? {
459 File::Bundle(b) => b.load_all().map_err(|e| self.entry_error(i, e))?,
460 File::Web(w) => w.load_all().map_err(|e| self.entry_error(i, e))?,
461 _ => {}
462 }
463 }
464 Ok(())
465 }
466
467 /// The entry's slice of the joined data, as joined offsets: `offset` and
468 /// `size` as UnityPy's `reader.Position = offset; reader.read(size)`. A
469 /// non-negative offset with a positive size needs no total (the end is
470 /// clamped as the read goes); anything else measures every block.
471 fn entry_span(&self, dir_index: usize) -> Result<Range<u64>, Error> {
472 let e = self
473 .directory
474 .get(dir_index)
475 .ok_or_else(|| no_entry(dir_index))?;
476 let u = |v: i64| u64::try_from(v).unwrap_or(0);
477 if e.size == 0 {
478 return Ok(0..0);
479 }
480 if e.offset >= 0 && e.size > 0 {
481 return Ok(u(e.offset)..u(e.offset).saturating_add(u(e.size)));
482 }
483 let total = self.measure_all()?;
484 let len = usize::try_from(total).unwrap_or(usize::MAX);
485 let (range, _) = py_read(len, i128::from(e.offset), e.size);
486 Ok(u64::try_from(range.start).unwrap_or(u64::MAX)
487 ..u64::try_from(range.end).unwrap_or(u64::MAX))
488 }
489
490 /// The key its span reads are counted by (`crate::testing`).
491 #[cfg(feature = "test-counters")]
492 pub(crate) fn span_origin(&self) -> &Origin {
493 &self.origin
494 }
495
496 fn entry_error(&self, dir_index: usize, e: Error) -> Error {
497 match e {
498 Error::Entry { .. } | Error::Limit(_) | Error::Budget(_) | Error::Allocator(_) => e,
499 e => Error::Entry {
500 name: self
501 .directory
502 .get(dir_index)
503 .map(|d| d.path.clone())
504 .unwrap_or_default(),
505 source: Arc::new(e),
506 },
507 }
508 }
509
510 /// The entry's parse (module docs, "Twins"): its first twin's kept
511 /// failure, when there is one; else its own parse, whose failure the
512 /// input decides is kept for its first twin too.
513 fn parse_entry(&self, dir_index: usize) -> Result<File, Error> {
514 let twin = self
515 .twins
516 .get(dir_index)
517 .and_then(|t| usize::try_from(*t).ok())
518 .filter(|t| *t != dir_index);
519 let twin_cell = twin.and_then(|t| Some((t, self.entries.get(t)?)));
520 if let Some((t, cell)) = twin_cell
521 && let Some(Err(kept)) = cell.get()
522 {
523 return Err(self.as_row(kept.error(), t, dir_index));
524 }
525 let got = self.parse_own(dir_index);
526 if let (Some((t, cell)), Err(e)) = (twin_cell, &got)
527 && !e.is_transient()
528 {
529 let _ = get_or_publish_result(cell, self.meter(), || Err(self.as_row(e, dir_index, t)));
530 }
531 got
532 }
533
534 /// `e`, the failure of row `from`, as row `to`'s: the same failure, under
535 /// `to`'s name where [`Self::entry_error`] gave it `from`'s. Only that
536 /// wrapping builds an [`Error::Entry`]: no parse returns one.
537 fn as_row(&self, e: &Error, from: usize, to: usize) -> Error {
538 let path = |i: usize| self.directory.get(i).map(|d| &d.path);
539 match e {
540 Error::Entry { name, source } if path(from) == Some(name) => Error::Entry {
541 name: path(to).cloned().unwrap_or_default(),
542 source: source.clone(),
543 },
544 e => e.clone(),
545 }
546 }
547
548 /// `parse_file` on the entry's bytes, its detection included, as
549 /// `File.read_files` calls it.
550 fn parse_own(&self, dir_index: usize) -> Result<File, Error> {
551 let e = self
552 .directory
553 .get(dir_index)
554 .ok_or_else(|| no_entry(dir_index))?;
555 let span = self.entry_span(dir_index)?;
556 let (bytes, pinned) =
557 self.read_span_pinned(span.start, span.end, SpanRow::row(dir_index))?;
558 let wrap = |e| self.entry_error(dir_index, e);
559 // The inflation of a gzip entry is the open's work (`detect`'s
560 // "Work"); its refusal is the open's limit, as a block decode's is.
561 let ty = check_entry_type(&bytes, &self.ctx.limits, self.meter()).map_err(|d| {
562 wrap(match d {
563 DetectError::Work(l) => Error::Limit(l),
564 d => Error::Detect(d),
565 })
566 })?;
567 let parent = Parent {
568 name: self.name.clone(),
569 kind: ParentKind::Bundle {
570 version_engine: self.header.version_engine.clone(),
571 bundle: self.this.clone(),
572 dir_index,
573 },
574 depth: self
575 .parent
576 .as_ref()
577 .map_or(self.source_depth, |p| p.depth)
578 .saturating_add(1),
579 pinned: pinned.max(u64::try_from(bytes.len()).unwrap_or(u64::MAX)),
580 };
581 // A failure the cell keeps: its grants are the open's work (module
582 // docs, "Memory and work").
583 let meter = self.meter();
584 let scope = GrantScope::enter(meter);
585 let got = self.dependency_path.parse_child(meter, dir_index, || {
586 parse_file(
587 e.path.clone(),
588 bytes,
589 ty,
590 Some(parent),
591 meter,
592 self.ctx.file(),
593 )
594 });
595 // A nested bundle is keyed by this one's load and its row: a
596 // statement only the feature builds.
597 #[cfg(feature = "test-counters")]
598 crate::testing::adopt(&got, || self.origin.child(dir_index));
599 let granted = scope.finish(meter);
600 if got.as_ref().is_err_and(|e| !e.is_transient()) {
601 meter.add_work(granted);
602 }
603 got.map_err(wrap)
604 }
605}
606
607fn no_entry(i: usize) -> Error {
608 Error::Malformed {
609 what: "bundle index",
610 detail: format!("no row {i}").into(),
611 }
612}
613
614impl BlockInfo {
615 /// A block's `u16` flags.
616 fn flags_u16(&self) -> u16 {
617 u16::try_from(self.flags & 0xFFFF).unwrap_or(0)
618 }
619}