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
// Ported from UnityPy 1.25.2 (MIT): UnityPy/files/ObjectReader.py. See THIRD_PARTY_LICENSES.
//! `ObjectReader` (`files/ObjectReader.py:44-311`): one object of a
//! `SerializedFile`, read on demand.
//!
//! An [`ObjectRef`] is a cheap handle: an `Arc` on the file and the row's
//! index in the file's object table, which it reads on demand. It owns no
//! copy of the row and nothing else, so a batch can hold millions and clone
//! them freely: every handle of a file shares the one table the file's
//! parse charged to the input's meter (plan section 3.12). Reading goes
//! through [`crate::walk::read_typetree_with_reader`], by the rules of the
//! file's reader ([`SerializedFile::reader_kind`]), with the tree that
//! [`ObjectRef::tree`] resolves (plan section 3.12: explicit, embedded, then
//! the provider chain with the class and packed version as its key).
//!
//! Owner: package D. The constructor and getters are implemented by the
//! scaffold.
use std::sync::Arc;
use bytes::Bytes;
use crate::budget::DecodeBuf;
use crate::error::{Error, LimitKind};
use crate::files::{ObjectInfo, SerializedFile, SerializedType};
use crate::provider::{NoTree, TreeRef, TreeRequest, TreeSource};
use crate::typetree::Tree;
use crate::value::Parsed;
use crate::walk::{ParseError, ReadCtx, WriteCtx, WriteError, WriteRules};
/// One object of a `SerializedFile`: the file and the index of its row
/// (module docs).
#[derive(Clone, Debug)]
pub struct ObjectRef {
file: Arc<SerializedFile>,
index: u32,
}
/// What [`ObjectRef::info`] would answer for an index [`ObjectRef::new`] did
/// not check. Never returned: `new` checks the index, and a file's object
/// table never changes after its parse.
static NO_ROW: ObjectInfo = ObjectInfo {
path_id: 0,
byte_start: 0,
byte_size: 0,
type_id: 0,
class_id: 0,
type_index: None,
is_destroyed: None,
is_stripped: None,
script_type_index: None,
};
impl ObjectRef {
/// Read only the MonoBehaviour head, ignoring trailing script fields
/// (`files/ObjectReader.py:325-330`). With no override, request class 114
/// from the providers, even when the object stores an embedded tree.
pub fn parse_monobehaviour_head(
&self,
nodes: Option<&Arc<Tree>>,
) -> Result<Parsed, ParseError> {
if let Some(nodes) = nodes {
return self.read_typetree_object(Some(nodes), false);
}
let tree = self
.file
.version()
.map(|version| {
self.file.context().providers.lookup(&TreeRequest {
class_id: 114,
version: &version.version,
script: None,
})
})
.transpose()?
.flatten()
.ok_or(ParseError::NoTypeTree {
class_id: 114,
why: self
.file
.context()
.providers
.why_none(114, self.file.version().map(|v| &v.version)),
})?;
self.read_typetree_object(Some(&tree.tree), false)
}
/// The object at `index` in [`SerializedFile::object_infos`], or `None`
/// past the table's end.
#[must_use]
pub fn new(file: Arc<SerializedFile>, index: u32) -> Option<Self> {
file.object_infos().get(usize::try_from(index).ok()?)?;
Some(Self { file, index })
}
/// The file it belongs to.
#[must_use]
pub fn file(&self) -> &Arc<SerializedFile> {
&self.file
}
/// Its index in [`SerializedFile::object_infos`].
#[must_use]
pub fn index(&self) -> u32 {
self.index
}
/// Its table row, read from the file's table (no copy).
#[must_use]
pub fn info(&self) -> &ObjectInfo {
usize::try_from(self.index)
.ok()
.and_then(|i| self.file.object_infos().get(i))
.unwrap_or(&NO_ROW)
}
/// `path_id`.
#[must_use]
pub fn path_id(&self) -> i64 {
self.info().path_id
}
/// `class_id`.
#[must_use]
pub fn class_id(&self) -> i32 {
self.info().class_id
}
/// The type record it resolves to, if any.
#[must_use]
pub fn serialized_type(&self) -> Option<&SerializedType> {
self.file.types().get(self.info().type_index?)
}
/// `get_raw_data`: `byte_size` bytes from `byte_start`, cut short at the
/// end of the file (a slice of the file's buffer, no copy, so it keeps
/// that whole buffer alive while it lives: a bundle entry's run, unlike
/// [`Self::read_typetree`]'s value, which [`crate::pin`] copies out of a
/// much larger run), by the file's reader's rules
/// ([`SerializedFile::reader_kind`]): the stream
/// reader (a file loaded from a path) refuses a negative `byte_start`, or
/// one at or above 2^63, as UnityPy's does on every machine, where the
/// memory reader slices from the end or reads nothing. A `byte_start`
/// past the largest file the file system takes is UnityPy's `OSError`
/// on that machine; the stream reader takes it and reads nothing
/// ([`crate::stream::ReaderKind`], `PARITY.md` section 19.3).
pub fn raw_data(&self) -> Result<Bytes, Error> {
// UnityPy files/ObjectReader.py:278-283: `reset()`, then
// `read_bytes(byte_size)`.
let info = self.info();
let data = self.file.data();
let kind = self.file.reader_kind();
let start = kind.seek(info.byte_start)?;
let (range, _) = kind.read(data.len(), start, i64::from(info.byte_size))?;
Ok(data.slice(range))
}
/// The tree a read would use: `nodes` when given, else the type record's,
/// else the provider chain's class tree (`ObjectReader.py:285-307`), with
/// no script (`TreeRequest::script` is `None`). `Ok(None)` where UnityPy
/// raises: [`Self::why_no_tree`] says which exception. The
/// `MonoBehaviour` script hook needs the Environment to dereference
/// `m_Script`: [`crate::env::Environment::object_tree`].
pub fn tree(&self, nodes: Option<&Arc<Tree>>) -> Result<Option<TreeRef>, ParseError> {
// UnityPy files/ObjectReader.py:285-307
if let Some(tree) = nodes {
return Ok(Some(TreeRef {
tree: tree.clone(),
source: TreeSource::Explicit,
}));
}
// :296-297: the type record's own tree, when it has one.
if let Some(st) = self.serialized_type()
&& let Some(tree) = st.tree(&self.file.context().limits)
{
return Ok(Some(TreeRef {
tree: tree?,
source: TreeSource::Embedded,
}));
}
// :298-299: `get_typetree_node(class_id, version)`. A file below
// format 7 has no version: UnityPy's `assets_file.version` is unset,
// so the `ObjectReader.version` property's `AttributeError` falls to
// `ObjectReader.__getattr__` (:223-225), which returns `None`, and
// `get_typetree_node` raises with that `None` (`why_no_tree` names
// which exception: `NoTree::NoVersion` for the comparison). No tree.
let Some(version) = self.file.version() else {
return Ok(None);
};
let req = TreeRequest {
class_id: self.class_id(),
version: &version.version,
script: None,
};
Ok(self.file.context().providers.lookup(&req)?)
}
/// Why [`Self::tree`] finds none for this object without `nodes` (its
/// type record holds none, and no provider has its class's): the
/// exception UnityPy raises there ([`NoTree`],
/// [`ProviderChain::why_none`] for the file's version, or for none below
/// format 7). `None` where no provider says. What
/// [`ParseError::NoTypeTree`] and [`WriteError::NoTypeTree`] carry.
///
/// [`ProviderChain::why_none`]: crate::provider::ProviderChain::why_none
#[must_use]
pub fn why_no_tree(&self) -> Option<NoTree> {
let version = self.file.version().map(|v| &v.version);
self.file
.context()
.providers
.why_none(self.class_id(), version)
}
/// `read_typetree(nodes, wrap=False, check_read)`.
pub fn read_typetree(
&self,
nodes: Option<&Arc<Tree>>,
check_read: bool,
) -> Result<Parsed, ParseError> {
self.read_typetree_mode(nodes, check_read, false)
}
/// Read the dictionary on the supplied meter with exact serialized
/// float bits, including signalling NaNs used by some animation slots.
/// Tree resolution stays scoped to the owning file.
pub fn read_typetree_lossless(
&self,
nodes: Option<&Arc<Tree>>,
check_read: bool,
meter: &Arc<crate::limits::Meter>,
) -> Result<Parsed, ParseError> {
self.read_fields_mode(nodes, check_read, false, None, Some(meter))
}
/// Read object-mode values into the dict model, retaining the Python
/// reader's pointer and referenced-type validation. The binding constructs
/// Python classes from these values; the core fallback also uses this mode.
pub fn read_typetree_object(
&self,
nodes: Option<&Arc<Tree>>,
check_read: bool,
) -> Result<Parsed, ParseError> {
self.read_typetree_mode(nodes, check_read, true)
}
/// Read each child's node and value without collapsing duplicate names.
/// A later reader error is returned with the completed construction prefix.
pub fn read_object_fields(&self) -> Result<(Parsed, crate::walk::FieldProgress), ParseError> {
self.read_object_fields_with_nodes(None)
}
/// Read object fields using an explicit tree before the file's own tree.
pub fn read_object_fields_with_nodes(
&self,
nodes: Option<&Arc<Tree>>,
) -> Result<(Parsed, crate::walk::FieldProgress), ParseError> {
let mut progress = crate::walk::FieldProgress::default();
let parsed = self.read_fields_mode(nodes, false, true, Some(&mut progress), None)?;
Ok((parsed, progress))
}
fn read_typetree_mode(
&self,
nodes: Option<&Arc<Tree>>,
check_read: bool,
object_mode: bool,
) -> Result<Parsed, ParseError> {
self.read_fields_mode(nodes, check_read, object_mode, None, None)
}
fn read_fields_mode(
&self,
nodes: Option<&Arc<Tree>>,
check_read: bool,
object_mode: bool,
progress: Option<&mut crate::walk::FieldProgress>,
lossless_meter: Option<&Arc<crate::limits::Meter>>,
) -> Result<Parsed, ParseError> {
// UnityPy files/ObjectReader.py:244-262
let Some(tree) = self.tree(nodes)? else {
return Err(ParseError::NoTypeTree {
class_id: self.class_id(),
why: self.why_no_tree(),
});
};
let file = &self.file;
let mut options = file.context().read_options();
if lossless_meter.is_some() {
options.floats = crate::walk::FloatMode::Lossless;
}
let ctx = ReadCtx {
endian: file.header().endian,
ref_types: file.ref_types_view(),
options: &options,
meter: lossless_meter.unwrap_or_else(|| file.meter()),
};
let info = self.info();
let mut read = crate::walk::read_with_fields(
file.data(),
info.byte_start,
info.byte_size,
&tree.tree,
&ctx,
check_read,
(file.reader_kind(), file.header().version >= 23, object_mode),
progress,
);
// A value kept past the file's handles keeps alive the buffer its
// slices are of: copied out of a run much larger than they are
// (`crate::pin`; plan section 8, R3), `check_read`'s value too.
let value = match &mut read {
Ok(value) => Some(value),
Err(ParseError::CheckRead { parsed, .. }) => Arc::get_mut(parsed),
Err(_) => None,
};
if let Some(value) = value {
file.unpin(value, lossless_meter).map_err(|error| {
crate::walk::charge_error(u64::try_from(value.bytes_read).unwrap_or(0), error)
})?;
}
read
}
/// The type record's own tree once it is compiled (the tree
/// [`Self::tree`] resolves with no `nodes` for an object whose record
/// stores one), without compiling or waiting: `None` until a read has
/// compiled it, or when the record has none.
#[must_use]
pub fn compiled_tree(&self) -> Option<&Arc<Tree>> {
self.serialized_type()?.compiled_tree()
}
/// [`Self::read_typetree`] with `tree` as `nodes`, its values handed to
/// `sink` as they are read ([`crate::walk::emit`]), and the bytes read;
/// or `None` where the direct read gives up, and the full read is to be
/// made instead. Only an object of `byte_size > 0` (UnityPyBoost's
/// reader) is read; a `check_read` mismatch gives up too. The read's
/// work, and `extra_work` of the caller's, are counted on the file's
/// meter in one check-and-add once the values are made; work the
/// allowance cannot hold gives up, counting nothing, and the read stops
/// as soon as its own work passes what the allowance holds. Copies none
/// of the file's bytes out ([`crate::pin`]): the sink's values are its
/// own.
pub fn emit_typetree<S: crate::walk::emit::Sink>(
&self,
tree: &Tree,
check_read: bool,
sink: &mut S,
extra_work: impl FnOnce(&S) -> u64,
) -> Option<(S::Obj, i64)> {
let meter = self.file.meter();
let (value, bytes_read, work) = self
.emit_typetree_uncounted(tree, check_read, sink, meter.work_left())
.ok()?;
let work = work.checked_add(extra_work(sink))?;
meter.try_count_work(work).then_some((value, bytes_read))
}
/// [`Self::emit_typetree`]'s read, its work (at most `max_work`, or it
/// gives up) returned, not counted: the caller counts it. A read that
/// gives up returns the work it did (`Err`), for the caller to count.
pub fn emit_typetree_uncounted<S: crate::walk::emit::Sink>(
&self,
tree: &Tree,
check_read: bool,
sink: &mut S,
max_work: u64,
) -> Result<(S::Obj, i64, u64), u64> {
let info = self.info();
let file = &self.file;
if info.byte_size == 0 || file.meter().work_used_up().is_some() {
return Err(0);
}
let options = file.context().read_options();
// UnityPy TypeTreeHelper.py:146-153: the memory reader's slice of
// `byte_size` bytes from `byte_start`, as `read_with_fields` takes it.
let kind = file.reader_kind();
let start = kind.seek(info.byte_start).map_err(|_| 0_u64)?;
let (range, _) = kind
.read(file.data().len(), start, i64::from(info.byte_size))
.map_err(|_| 0_u64)?;
let data = file.data().get(range).ok_or(0_u64)?;
let read = crate::walk::emit::emit(
data,
tree,
file.header().endian == crate::stream::Endian::Big,
options.floats,
options.limits.max_value_depth,
max_work,
sink,
)?;
let bytes_read = i64::try_from(read.bytes_read).map_err(|_| read.work)?;
if check_read && bytes_read != i64::from(info.byte_size) {
return Err(read.work);
}
Ok((read.value, bytes_read, read.work))
}
/// `parse_as_dict(check_read=check_read)`: [`Self::read_typetree`] with
/// the resolved tree.
pub fn parse_as_dict(&self, check_read: bool) -> Result<Parsed, ParseError> {
self.read_typetree(None, check_read)
}
/// Replace the bytes file save will write, and mark every parent changed.
/// Reads continue using the original reader, as UnityPy does.
pub fn set_raw_data(&self, data: impl AsRef<[u8]>) -> Result<(), crate::files::SaveError> {
self.file.set_raw_data(self.index, data.as_ref())
}
/// Restore the original save payload, marking this file and its parents.
/// Reads continue using the original reader throughout.
pub fn clear_raw_data(&self) {
self.file.clear_raw_data(self.index);
}
/// Write and install a typetree, as `files/ObjectReader.py:264-276` does.
/// A failed write or replacement leaves the file's previous edit intact.
pub fn save_typetree(
&self,
value: &Parsed,
nodes: Option<&Arc<Tree>>,
rules: WriteRules,
) -> Result<Bytes, crate::files::SaveError> {
let bytes = self.write_typetree(value, nodes, rules)?;
self.set_raw_data(&bytes)?;
Ok(bytes)
}
/// `save_typetree`'s bytes: UnityPy's writer (or `rules`) over `value`,
/// written into a buffer charged to the file's input meter, whose charge
/// rides in the returned `Bytes`.
pub fn write_typetree(
&self,
value: &Parsed,
nodes: Option<&Arc<Tree>>,
rules: WriteRules,
) -> Result<Bytes, WriteError> {
// UnityPy files/ObjectReader.py:264-276
// `_get_typetree_node` raised: the writer never ran.
let tree = match self.tree(nodes) {
Ok(Some(t)) => t.tree,
Ok(None) => {
return Err(WriteError::NoTypeTree {
class_id: self.class_id(),
why: self.why_no_tree(),
});
}
Err(e) => return Err(WriteError::Tree(Box::new(e))),
};
let file = &self.file;
let limits = file.context().limits;
let ctx = WriteCtx {
endian: file.header().endian,
ref_types: file.ref_types_view(),
rules,
limits: &limits,
};
let mut out = DecodeBuf::new(file.meter(), 0, u64::MAX, LimitKind::InputMemory)
.map_err(WriteError::Charge)?;
crate::walk::write::write(value, &tree, &ctx, &mut out)?;
out.into_bytes().map_err(WriteError::Charge)
}
}
#[cfg(test)]
mod tests {
use std::mem::size_of;
use std::sync::Arc;
use super::ObjectRef;
use crate::files::{ObjectInfo, SerializedFile};
#[test]
fn a_handle_holds_the_file_and_an_index_and_reads_its_row_from_the_table() {
// Round 4 (Codex): every handle held its own copy of the row, so
// handles kept or cloned by a caller duplicated the object table
// outside the meter that paid for it.
assert_eq!(
size_of::<ObjectRef>(),
size_of::<Arc<SerializedFile>>() + size_of::<u64>()
);
let row = |path_id| ObjectInfo {
path_id,
byte_start: 0,
byte_size: 4,
type_id: 0,
class_id: 114,
type_index: None,
is_destroyed: None,
is_stripped: None,
script_type_index: None,
};
let file = SerializedFile::for_tests(vec![row(7), row(-3)]);
let o = ObjectRef::new(file.clone(), 1).unwrap();
assert!(
std::ptr::eq(o.info(), &raw const file.object_infos()[1]),
"the file's own row"
);
assert_eq!((o.path_id(), o.class_id()), (-3, 114));
assert!(ObjectRef::new(file.clone(), 2).is_none());
let ids: Vec<i64> = file.objects().map(|o| o.path_id()).collect();
assert_eq!(ids, [7, -3]);
}
}