hao-il2cpp 0.0.12

Read Unity Il2Cpp metadata and generate .net proxy assemblies with hao
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
//! Custom-attribute blob decoding (ECMA-335 II.23.3) for the generator.

use super::*;

impl<'a> Generator<'a> {
    /// `[DefaultMember(name)]`, which C# needs to see indexers.
    pub(super) fn default_member_attribute(
        &mut self,
        module: usize,
        name: &str,
    ) -> Option<CustomAttribute> {
        let index = self.default_member?;
        let signature = MethodSig::new_instance(TypeSig::VOID, vec![TypeSig::STRING]);
        let constructor = match self.type_ref(module, index) {
            TypeDefOrRef::TypeDef(def) => {
                let ctor = def
                    .get()
                    .methods
                    .iter()
                    .find(|m| m.get().is_ctor() && m.get().signature == signature)
                    .cloned()?;
                CustomAttributeCtor::Method(ctor)
            }
            TypeDefOrRef::TypeRef(r) => CustomAttributeCtor::MemberRef(Entry::new(MemberRef {
                parent: hao::dotnet::entries::MemberRefParent::TypeRef(r),
                name: ".ctor".into(),
                signature: MemberRefSig::Method(signature),
                custom_attributes: Vec::new(),
            })),
            TypeDefOrRef::TypeSpec(_) => return None,
        };
        let value = CustomAttributeValue {
            fixed: vec![name.into()],
            named: Vec::new(),
        };
        CustomAttribute::new(constructor, &value).ok()
    }

    // ---- Recovered custom attributes (v29+) --------------------------------
    //
    // il2cpp v29 reintroduced per-token attribute data into metadata (earlier
    // versions kept only the attribute *types*, with arguments baked into
    // generated C++). The `attribute_data` blob stores, for each token, the
    // applied attributes with their constructor index and full argument values,
    // and `attribute_data_range` maps each token to its slice of that blob. We
    // reconstruct the attributes faithfully from this, re-encoding into ECMA-335
    // custom attribute blobs. Fidelity caveats (we drop rather than guess):
    //  * `object`/`object[]` constructor parameters would need ECMA boxing we
    //    don't emit, so those attributes are skipped (`needs_boxing`).
    //  * named arguments are typed by their recovered *value* (correct unless the
    //    field/property is declared `object`, where the static type is lost).
    //  * generic/array `System.Type` arguments and nested-array element types
    //    aren't reconstructed, so such attributes are skipped.
    // v39 (Unity 6) uses the same blob format, but its image record doesn't yet
    // expose the per-image attribute count, so nothing is recovered there.

    /// The `attribute_data` bytes for `token` in `module`'s image, if any.
    pub(super) fn attribute_blob(&self, module: usize, token: u32) -> Option<Vec<u8>> {
        let index = *self.attribute_tokens.get(module)?.get(&token)?;
        let blob = self.metadata.attribute_data();
        let start = self.attribute_ranges[index].1 as usize;
        let end = self
            .attribute_ranges
            .get(index + 1)
            .map_or(blob.len(), |r| r.1 as usize)
            .clamp(start, blob.len());
        blob.get(start..end).map(<[u8]>::to_vec)
    }

    /// Resolves an `Il2CppType` index to the type definition it names, if it is a
    /// plain class or value type.
    pub(super) fn type_def_index_of(&self, il_type_index: i32) -> Option<TypeDefinitionIndex> {
        match &self.binary.type_at(il_type_index)?.kind {
            TypeKind::Class(d) | TypeKind::ValueType(d) => Some(*d),
            _ => None,
        }
    }

    /// The ECMA element type byte backing an enum's values.
    pub(super) fn enum_underlying(&self, def: TypeDefinitionIndex) -> Option<u8> {
        let ty = self.metadata.type_definitions.get(def as usize)?;
        // v29 points `element_type_index` at the underlying primitive; v39 drops
        // it, so fall back to the enum's instance field (`value__`).
        if ty.element_type_index >= 0 {
            if let Some(TypeKind::Primitive(e)) =
                self.binary.type_at(ty.element_type_index).map(|t| &t.kind)
            {
                return Some(*e as u8);
            }
        }
        match &self
            .binary
            .type_at(self.metadata.type_fields(ty).first()?.type_index)?
            .kind
        {
            TypeKind::Primitive(e) => Some(*e as u8),
            _ => None,
        }
    }

    /// `Namespace.Outer+Inner`, the reflection form used in serialized attributes.
    pub(super) fn serialized_type_name(&self, def: TypeDefinitionIndex) -> Option<String> {
        if def < 0 || def as usize >= self.metadata.type_definitions.len() {
            return None;
        }
        Some(self.metadata.type_full_name(def).replace('/', "+"))
    }

    /// A reflection type name for a `System.Type` argument's `Il2CppType` index.
    pub(super) fn type_argument_name(&self, il_type_index: i32) -> Option<String> {
        match &self.binary.type_at(il_type_index)?.kind {
            TypeKind::Class(d) | TypeKind::ValueType(d) => self.serialized_type_name(*d),
            TypeKind::Primitive(e) => self.serialized_type_name(*self.primitive_types.get(e)?),
            _ => None,
        }
    }

    /// Reads a self-describing type tag (`ReadEncodedTypeEnum`): the element type
    /// byte, and the enum's definition when the tag is an enum (the byte is then the
    /// enum's underlying primitive). `None` when an enum can't be resolved, as its
    /// value width is then unknown.
    pub(super) fn read_encoded_type(
        &self,
        blob: &[u8],
        pos: &mut usize,
    ) -> Option<(u8, Option<TypeDefinitionIndex>)> {
        let tag = read_u8(blob, pos)?;
        if tag == TAG_ENUM {
            let type_index = read_compressed_i32(blob, pos)?;
            let def = self.type_def_index_of(type_index)?;
            Some((self.enum_underlying(def)?, Some(def)))
        } else {
            Some((tag, None))
        }
    }

    /// Reads one attribute argument (`ReadAttributeDataValue`), always advancing
    /// past a well-formed value. `Arg::Skip` marks a value that parsed but can't be
    /// represented, so the attribute is dropped without mis-encoding it.
    pub(super) fn read_arg(&self, blob: &[u8], pos: &mut usize) -> Option<Arg> {
        let (tag, enum_def) = self.read_encoded_type(blob, pos)?;
        self.read_value(blob, pos, tag, enum_def)
    }

    pub(super) fn read_value(
        &self,
        blob: &[u8],
        pos: &mut usize,
        tag: u8,
        enum_def: Option<TypeDefinitionIndex>,
    ) -> Option<Arg> {
        if let Some(def) = enum_def {
            // Read the underlying value, then wrap it with the enum's name.
            let Arg::Value(inner) = self.read_value(blob, pos, tag, None)? else {
                return Some(Arg::Skip);
            };
            return Some(match self.serialized_type_name(def) {
                Some(type_name) => Arg::Value(CAValue::Enum {
                    type_name,
                    value: Box::new(inner),
                }),
                None => Arg::Skip,
            });
        }
        let value = match ElementType::from_repr(tag) {
            Some(ElementType::Boolean) => CAValue::Bool(read_u8(blob, pos)? != 0),
            Some(ElementType::I1) => CAValue::I1(read_u8(blob, pos)? as i8),
            Some(ElementType::U1) => CAValue::U1(read_u8(blob, pos)?),
            Some(ElementType::Char) => CAValue::Char(u16::from_le_bytes(read_fixed(blob, pos)?)),
            Some(ElementType::I2) => CAValue::I2(i16::from_le_bytes(read_fixed(blob, pos)?)),
            Some(ElementType::U2) => CAValue::U2(u16::from_le_bytes(read_fixed(blob, pos)?)),
            Some(ElementType::I4) => CAValue::I4(read_compressed_i32(blob, pos)?),
            Some(ElementType::U4) => CAValue::U4(read_compressed_u32(blob, pos)?),
            Some(ElementType::I8) => CAValue::I8(i64::from_le_bytes(read_fixed(blob, pos)?)),
            Some(ElementType::U8) => CAValue::U8(u64::from_le_bytes(read_fixed(blob, pos)?)),
            Some(ElementType::R4) => CAValue::R4(f32::from_le_bytes(read_fixed(blob, pos)?)),
            Some(ElementType::R8) => CAValue::R8(f64::from_le_bytes(read_fixed(blob, pos)?)),
            Some(ElementType::String) => CAValue::String(read_ser_string(blob, pos)?),
            Some(ElementType::SzArray) => return self.read_array(blob, pos),
            _ if tag == TAG_TYPE_INDEX => {
                let type_index = read_compressed_i32(blob, pos)?;
                if type_index < 0 {
                    CAValue::Type(None)
                } else {
                    match self.type_argument_name(type_index) {
                        Some(name) => CAValue::Type(Some(name)),
                        None => return Some(Arg::Skip),
                    }
                }
            }
            _ => return None,
        };
        Some(Arg::Value(value))
    }

    pub(super) fn read_array(&self, blob: &[u8], pos: &mut usize) -> Option<Arg> {
        let len = read_compressed_i32(blob, pos)?;
        if len < 0 {
            return Some(Arg::Value(CAValue::Array {
                element: CAType::Object,
                values: None,
            }));
        }
        let (base_tag, base_enum) = self.read_encoded_type(blob, pos)?;
        let different = read_u8(blob, pos)? == 1;
        let mut values = Vec::new();
        let mut skip = false;
        for _ in 0..len as usize {
            let (tag, enum_def) = if different {
                self.read_encoded_type(blob, pos)?
            } else {
                (base_tag, base_enum)
            };
            match self.read_value(blob, pos, tag, enum_def)? {
                Arg::Value(v) => values.push(v),
                Arg::Skip => skip = true,
            }
        }
        if skip {
            return Some(Arg::Skip);
        }
        Some(match self.array_element_type(base_tag, base_enum) {
            Some(element) => Arg::Value(CAValue::Array {
                element,
                values: Some(values),
            }),
            None => Arg::Skip,
        })
    }

    pub(super) fn array_element_type(
        &self,
        tag: u8,
        enum_def: Option<TypeDefinitionIndex>,
    ) -> Option<CAType> {
        if let Some(def) = enum_def {
            return Some(CAType::Enum {
                type_name: self.serialized_type_name(def)?,
                underlying: PrimitiveType::from_repr(tag)?,
            });
        }
        if tag == TAG_TYPE_INDEX {
            return Some(CAType::Type);
        }
        match ElementType::from_repr(tag)? {
            ElementType::Boolean
            | ElementType::Char
            | ElementType::I1
            | ElementType::U1
            | ElementType::I2
            | ElementType::U2
            | ElementType::I4
            | ElementType::U4
            | ElementType::I8
            | ElementType::U8
            | ElementType::R4
            | ElementType::R8
            | ElementType::String => Some(CAType::Primitive(PrimitiveType::from_repr(tag)?)),
            _ => None,
        }
    }

    /// The name of a named-argument field or property, from its declaring type and
    /// member index (`ReadCustomAttributeNamedArgumentClassAndIndex`). Always
    /// advances; the inner `None` means the member couldn't be resolved.
    pub(super) fn read_named_member(
        &self,
        blob: &[u8],
        pos: &mut usize,
        ctor_type: Option<TypeDefinitionIndex>,
        is_field: bool,
    ) -> Option<Option<String>> {
        let member = read_compressed_i32(blob, pos)?;
        let (decl, index) = if member >= 0 {
            (ctor_type, member as usize)
        } else {
            let type_index = read_compressed_u32(blob, pos)? as TypeDefinitionIndex;
            (Some(type_index), (-(member + 1)) as usize)
        };
        Some(decl.and_then(|d| self.member_name(d, index, is_field)))
    }

    pub(super) fn member_name(
        &self,
        decl: TypeDefinitionIndex,
        index: usize,
        is_field: bool,
    ) -> Option<String> {
        let ty = self
            .metadata
            .type_definitions
            .get(usize::try_from(decl).ok()?)?;
        let name_index = if is_field {
            let start = ty.field_start.max(0) as usize;
            self.metadata.fields.get(start + index)?.name_index
        } else {
            let start = ty.property_start.max(0) as usize;
            self.metadata.properties.get(start + index)?.name_index
        };
        Some(self.metadata.string(name_index).to_owned())
    }

    /// Parses one attribute's argument block: the fixed arguments, then the named
    /// fields and properties. Must stay byte-aligned, so returns `None` (stopping
    /// the token) on malformed data.
    #[allow(clippy::type_complexity)]
    pub(super) fn parse_arguments(
        &self,
        blob: &[u8],
        pos: &mut usize,
        ctor_type: Option<TypeDefinitionIndex>,
    ) -> Option<(Vec<Arg>, Vec<(bool, String, Arg)>)> {
        let arg_count = read_compressed_u32(blob, pos)?;
        let field_count = read_compressed_u32(blob, pos)?;
        let property_count = read_compressed_u32(blob, pos)?;
        let mut fixed = Vec::new();
        for _ in 0..arg_count {
            fixed.push(self.read_arg(blob, pos)?);
        }
        let mut named = Vec::new();
        for (is_field, count) in [(true, field_count), (false, property_count)] {
            for _ in 0..count {
                let value = self.read_arg(blob, pos)?;
                match self.read_named_member(blob, pos, ctor_type, is_field)? {
                    Some(name) => named.push((is_field, name, value)),
                    None => named.push((is_field, String::new(), Arg::Skip)),
                }
            }
        }
        Some((fixed, named))
    }

    /// The custom attributes applied to `token` in `module`, reconstructed from the
    /// v29+ `attribute_data` blob.
    pub(super) fn custom_attributes(&mut self, module: usize, token: u32) -> Vec<CustomAttribute> {
        let Some(blob) = self.attribute_blob(module, token) else {
            return Vec::new();
        };
        let mut pos = 0;
        let Some(count) = read_compressed_u32(&blob, &mut pos) else {
            return Vec::new();
        };
        let ctor_base = pos;
        let mut data_pos = ctor_base + count as usize * 4;
        let mut out = Vec::new();
        for i in 0..count as usize {
            let Some(ctor_bytes) = blob.get(ctor_base + i * 4..ctor_base + i * 4 + 4) else {
                break;
            };
            let ctor_index = i32::from_le_bytes(ctor_bytes.try_into().unwrap());
            let ctor_type = self
                .metadata
                .methods
                .get(usize::try_from(ctor_index).unwrap_or(usize::MAX))
                .map(|m| m.declaring_type);
            let Some((fixed, named)) = self.parse_arguments(&blob, &mut data_pos, ctor_type) else {
                break;
            };
            if let Some(attribute) = self.build_attribute(module, ctor_index, fixed, named) {
                out.push(attribute);
            }
        }
        out
    }

    pub(super) fn build_attribute(
        &mut self,
        module: usize,
        ctor_index: i32,
        fixed: Vec<Arg>,
        named: Vec<(bool, String, Arg)>,
    ) -> Option<CustomAttribute> {
        let method = self
            .metadata
            .methods
            .get(usize::try_from(ctor_index).ok()?)?
            .clone();
        let decl = method.declaring_type;
        let params: Vec<TypeSig> = self
            .metadata
            .method_parameters(&method)
            .to_vec()
            .iter()
            .map(|p| self.sig_at(module, p.type_index))
            .collect();
        if params.len() != fixed.len() || params.iter().any(needs_boxing) {
            return None;
        }
        let fixed = fixed
            .into_iter()
            .map(|a| match a {
                Arg::Value(v) => Some(v),
                Arg::Skip => None,
            })
            .collect::<Option<Vec<_>>>()?;
        let named = named
            .into_iter()
            .map(|(is_field, name, a)| match a {
                Arg::Value(v) if is_field => Some(CANamedArgument::field(name, v)),
                Arg::Value(v) => Some(CANamedArgument::property(name, v)),
                Arg::Skip => None,
            })
            .collect::<Option<Vec<_>>>()?;
        let constructor = self.attribute_ctor(module, decl, ctor_index, params)?;
        CustomAttribute::new(constructor, &CustomAttributeValue { fixed, named }).ok()
    }

    pub(super) fn attribute_ctor(
        &mut self,
        module: usize,
        decl: TypeDefinitionIndex,
        ctor_index: i32,
        params: Vec<TypeSig>,
    ) -> Option<CustomAttributeCtor> {
        match self.type_ref(module, decl) {
            TypeDefOrRef::TypeDef(def) => {
                let method_start = self
                    .metadata
                    .type_definitions
                    .get(decl as usize)?
                    .method_start;
                let local = usize::try_from(ctor_index - method_start).ok()?;
                Some(CustomAttributeCtor::Method(
                    def.get().methods.get(local)?.clone(),
                ))
            }
            TypeDefOrRef::TypeRef(r) => {
                Some(CustomAttributeCtor::MemberRef(Entry::new(MemberRef {
                    parent: MemberRefParent::TypeRef(r),
                    name: ".ctor".into(),
                    signature: MemberRefSig::Method(MethodSig::new_instance(TypeSig::VOID, params)),
                    custom_attributes: Vec::new(),
                })))
            }
            TypeDefOrRef::TypeSpec(_) => None,
        }
    }
}