rabex 0.2.0

Tools for parsing and writing unity files, bundles 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
use std::borrow::Cow;
use std::collections::{BTreeMap, HashMap};
use std::io::{Cursor, Seek, Write};

use crate::files::serializedfile::{
    self, CommonOffsetMap, FileIdentifier, LocalSerializedObjectIdentifier, ObjectInfo,
    SerializedFile, SerializedFileHeader, SerializedType, TypeTreeProvider,
};
use crate::objects::pptr::{FileId, PathId};
use crate::objects::{ClassId, ClassIdType, PPtr};
use crate::serde_typetree;
use crate::typetree::TypeTreeNode;
use crate::unity_version::UnityVersion;
use byteorder::LittleEndian;
use rustc_hash::FxHashMap;
use serde::Serialize;

use super::Endianness;

pub type Result<T, E = Error> = std::result::Result<T, E>;

/// Builder for creating a new [`SerializedFile`]
pub struct SerializedFileBuilder<'a, P> {
    unity_version: UnityVersion,
    common_offset_map: &'a CommonOffsetMap<'a>,
    pub typetree_provider: &'a P,
    pub next_path_id: i64,
    pub objects: BTreeMap<PathId, (ObjectInfo, Cow<'a, [u8]>)>,

    pub serialized: SerializedFile,

    types_cache: HashMap<ClassId, i32>,
}

impl<'a, P> std::fmt::Debug for SerializedFileBuilder<'a, P> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        #[derive(Debug)]
        struct ObjectInfo {
            m_ClassId: ClassId,
            m_TypeID: i32,
            m_ScriptTypeIndex: Option<i16>,
        }
        impl ObjectInfo {
            fn new(value: &super::ObjectInfo) -> Self {
                ObjectInfo {
                    m_ClassId: value.m_ClassID,
                    m_TypeID: value.m_TypeID,
                    m_ScriptTypeIndex: value.m_ScriptTypeIndex,
                }
            }
        }
        f.debug_struct("SerializedFileBuilder")
            .field("unity_version", &self.unity_version)
            .field("next_path_id", &self.next_path_id)
            .field(
                "objects",
                &self
                    .objects
                    .iter()
                    .map(|(path_id, (info, _))| (path_id, ObjectInfo::new(info)))
                    .collect::<FxHashMap<_, _>>(),
            )
            .field("serialized", &self.serialized)
            .finish_non_exhaustive()
    }
}

impl<'a, P: TypeTreeProvider> SerializedFileBuilder<'a, P> {
    /// Create an empty `SerializeFileBuilder`
    pub fn new(
        version: &UnityVersion,
        typetree_provider: &'a P,
        common_offset_map: &'a CommonOffsetMap<'a>,
        enable_type_tree: bool,
    ) -> Self {
        Self {
            unity_version: version.clone(),
            typetree_provider,
            common_offset_map,
            next_path_id: 1,
            objects: BTreeMap::default(),
            types_cache: HashMap::default(),

            serialized: SerializedFile {
                m_Header: SerializedFileHeader {
                    m_MetadataSize: 0,
                    m_FileSize: 0,
                    m_Version: 22,
                    m_DataOffset: 0,
                    m_Endianess: Endianness::Little,
                    m_Reserved: [0, 0, 0],
                    unknown: 0,
                },
                m_UnityVersion: Some(version.clone()),
                m_TargetPlatform: Some(24), // TODO
                m_EnableTypeTree: enable_type_tree,
                m_bigIDEnabled: None,
                m_Types: Vec::new(),
                m_ScriptTypes: Some(Vec::new()),
                m_Externals: Vec::new(),
                m_RefTypes: Some(Vec::new()),
                m_UserInformation: Some("".into()),
                m_Objects: Default::default(),        // unused
                m_Objects_lookup: Default::default(), // unused
            },
        }
    }

    /// Create a `SerializeFileBuilder` containing all data from the given file.
    ///
    /// To include all objects from the file, pass `file.objects().cloned()` as `objects`.
    pub fn from_serialized(
        unity_version: &UnityVersion,
        file: &SerializedFile,
        data: &'a [u8],
        typetree_provider: &'a P,
        common_offset_map: &'a HashMap<&'a str, u32>,
        objects: impl Iterator<Item = ObjectInfo>,
    ) -> Self {
        let mut builder = SerializedFileBuilder::from_serialized_meta(
            unity_version,
            file,
            typetree_provider,
            common_offset_map,
        );
        builder.serialized.m_Types = file.m_Types.clone();
        builder.serialized.m_Externals = file.m_Externals.clone();
        builder.serialized.m_ScriptTypes = file.m_ScriptTypes.clone();
        builder.serialized.m_RefTypes = file.m_RefTypes.clone();

        for obj in objects {
            let data = &data[obj.m_Offset as usize..obj.m_Offset as usize + obj.m_Size as usize];
            let res = builder.add_object_inner(obj.clone(), Cow::Borrowed(data));
            res.unwrap(); // the path id must be available
        }

        builder
    }

    /// Copies unity version, and metadata like enabling type trees or the target platform.
    /// Not copied:
    /// - object data
    /// - types
    /// - external file references
    /// - script types
    /// - ref types
    pub fn from_serialized_meta(
        unity_version: &UnityVersion,
        file: &SerializedFile,
        typetree_provider: &'a P,
        common_offset_map: &'a HashMap<&'a str, u32>,
    ) -> Self {
        Self {
            unity_version: unity_version.clone(),
            typetree_provider,
            common_offset_map,
            next_path_id: 1,
            objects: BTreeMap::default(),
            types_cache: HashMap::default(),

            serialized: SerializedFile {
                m_Header: SerializedFileHeader {
                    m_MetadataSize: 0,
                    m_FileSize: 0,
                    m_Version: file.m_Header.m_Version,
                    m_DataOffset: 0,
                    m_Endianess: file.m_Header.m_Endianess,
                    m_Reserved: [0, 0, 0],
                    unknown: 0,
                },
                m_UnityVersion: file.m_UnityVersion.clone(),
                m_TargetPlatform: file.m_TargetPlatform,
                m_EnableTypeTree: file.m_EnableTypeTree,
                m_bigIDEnabled: file.m_bigIDEnabled,
                m_Types: Vec::new(),
                m_Objects: Default::default(),        // unused
                m_Objects_lookup: Default::default(), // unused
                m_ScriptTypes: Some(Vec::new()),
                m_Externals: Vec::new(),
                m_RefTypes: Some(Vec::new()),
                m_UserInformation: file.m_UserInformation.clone(),
            },
        }
    }

    /// Copy `m_Externals` from the other file
    pub fn copy_externals(&mut self, file: &SerializedFile) {
        for external in &file.m_Externals {
            self.add_external_uncached(external.clone());
        }
    }

    /// Add an object to the serialized file.
    ///
    /// This will choose the next free path ID.
    pub fn add_object<T: Serialize + ClassIdType>(&mut self, object: &T) -> Result<PathId> {
        let path_id = self.get_next_path_id();
        self.add_object_at(path_id, object)?;
        Ok(path_id)
    }

    /// Add an object to the serialized file.
    pub fn add_object_at<T: Serialize + ClassIdType>(
        &mut self,
        path_id: PathId,
        object: &T,
    ) -> Result<()> {
        debug_assert!(
            (T::CLASS_ID != ClassId::AssetBundle) || (path_id == 1 || path_id == 2),
            "Assetbundles must be at path id 1 or 2"
        );
        let type_id = self.get_or_insert_type(T::CLASS_ID);
        self.add_object_with(object, path_id, T::CLASS_ID, type_id)
    }

    /// Replace the data of the object at the path id.
    pub fn replace_object_at<T: Serialize + ClassIdType>(
        &mut self,
        path_id: PathId,
        object: &T,
    ) -> Result<()> {
        let type_id = self.get_or_insert_type(T::CLASS_ID);
        self.add_object_with(object, path_id, T::CLASS_ID, type_id)
    }

    /// Add an object to the serialized file with the specified meta data.
    /// You need to ensure that:
    /// - all file IDs in the data match `m_Externals`
    /// - `path_id` is free
    /// - `type_id` corresponds to a `m_Types` index
    pub fn add_object_with<T: Serialize>(
        &mut self,
        object: &T,
        path_id: PathId,
        class_id: ClassId,
        type_id: i32,
    ) -> Result<()> {
        let tt = self
            .typetree_provider
            .get_typetree_node(class_id, &self.unity_version)
            .unwrap();

        let data = serde_typetree::to_vec::<_, LittleEndian>(&object, &tt)
            .map_err(serializedfile::Error::Serialize)?;

        self.add_object_untyped_with(path_id, class_id, type_id, Cow::Owned(data))
    }

    /// Add an object to the file with the specified meta data.
    /// You need to ensure that:
    /// - all file IDs in the data match `m_Externals`
    /// - `path_id` is free
    /// - `type_id` corresponds to a `m_Types` index
    ///
    /// The method does not set:
    /// - `m_IsDestroyed`
    /// - `m_ScriptTypeIndex`
    /// - `m_Stripped`
    pub fn add_object_untyped_with(
        &mut self,
        path_id: PathId,
        class_id: ClassId,
        type_id: i32,
        data: Cow<'a, [u8]>,
    ) -> Result<()> {
        let info = ObjectInfo {
            m_PathID: path_id,
            m_Offset: 0, // ignored
            m_Size: 0,   // ignored
            m_TypeID: type_id,
            m_ClassID: class_id,
            m_IsDestroyed: None,
            m_ScriptTypeIndex: None,
            m_Stripped: None,
        };
        self.add_object_inner(info, data)
    }

    /// - all file IDs in the data must match `m_Externals`
    /// - if `m_ScriptTypeIndex` is set, it must match `m_ScriptTypes`
    /// - `info.m_TypeID` must correspond to a `m_Types` index
    fn add_object_inner(&mut self, info: ObjectInfo, data: Cow<'a, [u8]>) -> Result<()> {
        let path_id = info.m_PathID;
        let previous = self.objects.insert(path_id, (info, data));
        if let Some((previous, _)) = previous {
            return Err(Error::PathIdAlreadyExists(path_id, previous.m_ClassID));
        }

        Ok(())
    }

    /// Register a MonoBehaviour type instantiating `script` (a [`PPtr`] to its `MonoScript`),
    /// returning its `m_TypeID` for
    /// [`add_monobehaviour_with_type`](Self::add_monobehaviour_with_type).
    ///
    /// `typetree` is the type tree to embed, or `None` to write without type trees.
    pub fn add_monobehaviour_type(&mut self, script: PPtr, typetree: Option<TypeTreeNode>) -> i32 {
        let script_types = self.serialized.m_ScriptTypes.get_or_insert_default();
        let script_type_index: i16 = script_types
            .len()
            .try_into()
            .expect("m_ScriptTypes exceeded i16::MAX");
        script_types.push(LocalSerializedObjectIdentifier {
            m_LocalSerializedFileIndex: script.m_FileID,
            m_LocalIdentifierInFile: script.m_PathID,
        });
        let mut ty = SerializedType::simple(ClassId::MonoBehaviour, typetree);
        ty.m_ScriptTypeIndex = script_type_index;
        self.add_type_uncached(ty)
    }

    /// Add a MonoBehaviour using a type from
    /// [`add_monobehaviour_type`](Self::add_monobehaviour_type), choosing the next free path id.
    ///
    /// Serializes `object` against that type's embedded type tree when present (else the
    /// provider's).
    pub fn add_monobehaviour_with_type<T: Serialize>(
        &mut self,
        object: &T,
        mb_type_id: i32,
    ) -> Result<PathId> {
        let path_id = self.get_next_path_id();

        let ty = &self.serialized.m_Types[mb_type_id as usize];
        let script_type_index = ty.m_ScriptTypeIndex;
        let data = match &ty.m_Type {
            Some(tt) => serde_typetree::to_vec::<_, LittleEndian>(object, tt)
                .map_err(serializedfile::Error::Serialize)?,
            None => {
                let tt = self
                    .typetree_provider
                    .get_typetree_node(ClassId::MonoBehaviour, &self.unity_version)
                    .ok_or(serializedfile::Error::NoTypetree(ClassId::MonoBehaviour))?;
                serde_typetree::to_vec::<_, LittleEndian>(object, &tt)
                    .map_err(serializedfile::Error::Serialize)?
            }
        };

        let info = ObjectInfo {
            m_PathID: path_id,
            m_Offset: 0, // ignored
            m_Size: 0,   // ignored
            m_TypeID: mb_type_id,
            m_ClassID: ClassId::MonoBehaviour,
            m_IsDestroyed: None,
            m_ScriptTypeIndex: Some(script_type_index),
            m_Stripped: None,
        };
        self.add_object_inner(info, Cow::Owned(data))?;
        Ok(path_id)
    }

    // TODO: reuse existing types if possible
    fn get_or_insert_type(&mut self, class_id: ClassId) -> i32 {
        *self.types_cache.entry(class_id).or_insert_with(|| {
            if class_id == ClassId::MonoBehaviour {
                panic!(
                    "MonoBehaviour objects need a script-bound type; \
                     use add_monobehaviour_type + add_monobehaviour_with_type instead of add_object_at"
                );
            }

            // PERF: don't construct if not required
            let ty = self
                .typetree_provider
                .get_typetree_node(class_id, &self.unity_version)
                .ok_or(serializedfile::Error::NoTypetree(class_id))
                .unwrap();
            let serialized_type =
                SerializedType::new(class_id, ty, self.serialized.m_EnableTypeTree);

            let type_index = self.serialized.m_Types.len();
            self.serialized.m_Types.push(serialized_type);
            type_index as i32
        })
    }

    /// Add an entry to the `m_Types` of the serialized file
    pub fn add_type_uncached(&mut self, ty: SerializedType) -> i32 {
        self.serialized.add_type(ty)
    }

    /// Add an entry to the `m_Externals` of the serialized file
    pub fn add_external_uncached(&mut self, external: FileIdentifier) -> FileId {
        self.serialized.add_external(external)
    }

    pub fn get_or_insert_external(&mut self, external: &str) -> FileId {
        // PERF: O(n)
        let file_id = self
            .serialized
            .m_Externals
            .iter()
            .enumerate()
            .find_map(|(i, e)| (e.pathName == external).then_some(FileId::from_externals_index(i)));
        file_id
            .unwrap_or_else(|| self.add_external_uncached(FileIdentifier::new(external.to_owned())))
    }

    /// The Unity version this file is being built for.
    pub fn unity_version(&self) -> &UnityVersion {
        &self.unity_version
    }

    pub fn get_next_path_id(&mut self) -> PathId {
        loop {
            let id = self.next_path_id;
            self.next_path_id = self.next_path_id.checked_add(1).unwrap();
            if !self.objects.contains_key(&id) {
                return id;
            }
        }
    }

    /// Serialize the file into the given writer.
    pub fn write<W: Write + Seek>(self, writer: W) -> Result<()> {
        serializedfile::write_serialized_with_objects(
            writer,
            &self.serialized,
            self.common_offset_map,
            self.objects.into_values(),
        )?;

        Ok(())
    }

    /// Serialize the file.
    pub fn write_vec(self) -> Result<Vec<u8>, Error> {
        let mut out = Vec::new();
        self.write(Cursor::new(&mut out))?;
        Ok(out)
    }
}

#[derive(Debug)]
#[non_exhaustive]
pub enum Error {
    SerializedFile(serializedfile::Error),
    PathIdAlreadyExists(PathId, ClassId),
    IO(std::io::Error),
}

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Error::SerializedFile(error) => error.fmt(f),
            Error::IO(error) => write!(f, "IO error: {error}"),
            Error::PathIdAlreadyExists(path_id, class_id) => write!(
                f,
                "Can't add object {path_id} to SerializeFileBuilder: a {class_id:?} already exists",
            ),
        }
    }
}
impl std::error::Error for Error {}

impl From<std::io::Error> for Error {
    fn from(error: std::io::Error) -> Self {
        Error::IO(error)
    }
}

impl From<serializedfile::Error> for Error {
    fn from(error: serializedfile::Error) -> Self {
        Error::SerializedFile(error)
    }
}