il2cpp_dumper 0.4.0

A blazing fast and reliable il2cpp dumper cross platfrom.
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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
use std::collections::{HashMap, HashSet};
use std::fmt::Write as FmtWrite;
use super::cpp_type_dependency_graph::{
    CppCompilerLayout, CppTypeDependencyGraph, GraphField, GraphType, GraphTypeKind,
};
use super::cpp_type_model::{CppTypeGroup, CppTypeGroupRegistry};
use crate::error::{Error, Result};

static C_PRIMITIVE_TYPES: &[&str] = &[
    "void", "bool", "char", "int8_t", "uint8_t", "int16_t", "uint16_t",
    "int32_t", "uint32_t", "int64_t", "uint64_t", "float", "double",
    "intptr_t", "uintptr_t", "Il2CppChar",
];

fn needs_struct_prefix(type_name: &str) -> bool {
    let base = type_name.trim_end_matches('*');
    !C_PRIMITIVE_TYPES.contains(&base)
}

fn strip_pointer(type_name: &str) -> (&str, u32) {
    let bytes = type_name.as_bytes();
    let mut depth: u32 = 0;
    let mut end = bytes.len();
    while end > 0 && bytes[end - 1] == b'*' {
        depth += 1;
        end -= 1;
    }
    let trimmed = type_name[..end].trim_end();
    (trimmed, depth)
}

#[derive(Debug, Clone)]
pub struct CppField {
    pub type_name: String,
    pub field_name: String,
    pub is_value_type: bool,
    pub is_custom_type: bool,
}

#[derive(Debug, Clone)]
pub struct CppVTableEntry {
    pub method_name: Option<String>,
}

#[derive(Debug, Clone)]
pub struct CppRGCTXEntry {
    pub rgctx_type: i64,
    pub type_name: Option<String>,
    pub class_name: Option<String>,
    pub method_name: Option<String>,
}

#[derive(Debug, Clone)]
pub struct CppTypeDecl {
    pub name: String,
    pub is_value_type: bool,
    pub parent: Option<String>,
    pub instance_fields: Vec<CppField>,
    pub static_fields: Vec<CppField>,
    pub vtable: Vec<CppVTableEntry>,
    pub rgctxs: Vec<CppRGCTXEntry>,
}

pub struct CppHeaderEmitter {
    pub compiler_layout: CppCompilerLayout,
    pub is_32bit: bool,
    pub is_pe: bool,
    pub forward_declared: HashSet<String>,
    pub emitted: HashSet<String>,
}

impl CppHeaderEmitter {
    pub fn new(compiler_layout: CppCompilerLayout, is_32bit: bool, is_pe: bool) -> Self {
        Self {
            compiler_layout,
            is_32bit,
            is_pe,
            forward_declared: HashSet::new(),
            emitted: HashSet::new(),
        }
    }

    fn classify_field(field: &CppField, known_value_types: &HashSet<String>) -> GraphField {
        let (base_name, pointer_depth) = strip_pointer(&field.type_name);
        let is_pointer = pointer_depth > 0;
        let element_name = base_name.to_string();
        let is_custom = field.is_custom_type;
        let terminal_is_value = is_custom && known_value_types.contains(&element_name);

        let (element_kind, pointer_terminal_kind) = if is_pointer {
            if !is_custom {
                (GraphTypeKind::Primitive, Some(GraphTypeKind::Primitive))
            } else if terminal_is_value {
                (GraphTypeKind::ValueStruct, Some(GraphTypeKind::ValueStruct))
            } else {
                (GraphTypeKind::ReferenceClass, Some(GraphTypeKind::ReferenceClass))
            }
        } else if !is_custom {
            (GraphTypeKind::Primitive, None)
        } else if field.is_value_type || terminal_is_value {
            (GraphTypeKind::ValueStruct, None)
        } else {
            (GraphTypeKind::ReferenceClass, None)
        };

        GraphField {
            element_name: element_name.clone(),
            element_kind,
            is_instance: true,
            is_pointer,
            pointer_depth,
            is_array: false,
            array_element_name: None,
            array_element_kind: None,
            enum_underlying_name: None,
            pointer_terminal_kind,
            pointer_terminal_name: if is_pointer { Some(element_name) } else { None },
        }
    }

    fn to_graph_type(decl: &CppTypeDecl, known_value_types: &HashSet<String>) -> GraphType {
        let kind = if decl.is_value_type {
            GraphTypeKind::ValueStruct
        } else {
            GraphTypeKind::ReferenceClass
        };

        let mut fields: Vec<GraphField> = decl
            .instance_fields
            .iter()
            .map(|f| Self::classify_field(f, known_value_types))
            .collect();
        for f in fields.iter_mut() {
            f.is_instance = true;
        }

        let mut static_fields: Vec<GraphField> = decl
            .static_fields
            .iter()
            .map(|f| Self::classify_field(f, known_value_types))
            .collect();
        for f in static_fields.iter_mut() {
            f.is_instance = false;
        }

        GraphType {
            name: decl.name.clone(),
            kind,
            parent: decl.parent.clone(),
            enum_underlying_name: None,
            fields,
            static_fields,
        }
    }

    pub fn emit_all_with_groups(
        &mut self,
        types: &[CppTypeDecl],
        groups: Option<&CppTypeGroupRegistry>,
    ) -> Result<String> {
        let known_type_names: HashSet<String> = types.iter().map(|t| t.name.clone()).collect();
        let known_value_types: HashSet<String> = types
            .iter()
            .filter(|t| t.is_value_type)
            .map(|t| t.name.clone())
            .collect();
        let type_map: HashMap<String, &CppTypeDecl> =
            types.iter().map(|t| (t.name.clone(), t)).collect();

        let mut graph = CppTypeDependencyGraph::new();
        let graph_types: Vec<GraphType> = types
            .iter()
            .map(|d| Self::to_graph_type(d, &known_value_types))
            .collect();
        graph.add_types_bulk(&graph_types);

        let ordered_names = graph
            .derive_dependency_order()
            .map_err(|cycle| Error::CyclicDependency(cycle.to_string()))?;
        let fwd_candidates = graph.get_forward_declaration_candidates();

        let total_estimate = types.len() * 512;
        let mut buf = String::with_capacity(total_estimate);

        let mut sorted_fwd: Vec<&String> = fwd_candidates.iter().collect();
        sorted_fwd.sort();
        if !sorted_fwd.is_empty() {
            Self::write_section_banner(&mut buf, CppTypeGroup::RequiredForwardDefinitions.section_header());
            for fwd_name in sorted_fwd {
                if !known_type_names.contains(fwd_name)
                    && self.forward_declared.insert(fwd_name.clone())
                {
                    writeln!(buf, "struct {};", fwd_name).ok();
                }
            }
            writeln!(buf).ok();
        }

        let group_order = [
            CppTypeGroup::TypesFromMethods,
            CppTypeGroup::TypesFromGenericMethods,
            CppTypeGroup::TypesFromUsages,
            CppTypeGroup::UnusedConcreteTypes,
        ];

        if let Some(reg) = groups {
            let assigned: HashMap<String, CppTypeGroup> = ordered_names
                .iter()
                .filter_map(|n| reg.group_of(n).map(|g| (n.clone(), g)))
                .collect();

            for &group in &group_order {
                let mut wrote_banner = false;
                for name in &ordered_names {
                    if assigned.get(name).copied() != Some(group) {
                        continue;
                    }
                    if let Some(decl) = type_map.get(name) {
                        if !self.emitted.insert(decl.name.clone()) {
                            continue;
                        }
                        if !wrote_banner {
                            Self::write_section_banner(&mut buf, group.section_header());
                            wrote_banner = true;
                        }
                        self.emit_type_decl(&mut buf, decl, &type_map);
                        writeln!(buf).ok();
                    }
                }
            }

            let mut wrote_unassigned = false;
            for name in &ordered_names {
                if assigned.contains_key(name) {
                    continue;
                }
                if let Some(decl) = type_map.get(name) {
                    if !self.emitted.insert(decl.name.clone()) {
                        continue;
                    }
                    if !wrote_unassigned {
                        Self::write_section_banner(&mut buf, "Unclassified application types");
                        wrote_unassigned = true;
                    }
                    self.emit_type_decl(&mut buf, decl, &type_map);
                    writeln!(buf).ok();
                }
            }
        } else {
            for name in &ordered_names {
                if let Some(decl) = type_map.get(name) {
                    if self.emitted.insert(decl.name.clone()) {
                        self.emit_type_decl(&mut buf, decl, &type_map);
                        writeln!(buf).ok();
                    }
                }
            }
        }

        Ok(buf)
    }

    fn write_section_banner(buf: &mut String, name: &str) {
        writeln!(buf, "// ******************************************************************************").ok();
        writeln!(buf, "// * {name}").ok();
        writeln!(buf, "// ******************************************************************************").ok();
        writeln!(buf).ok();
    }

    pub fn emit_all(&mut self, types: &[CppTypeDecl]) -> Result<String> {
        let known_type_names: HashSet<String> = types.iter().map(|t| t.name.clone()).collect();
        let known_value_types: HashSet<String> = types
            .iter()
            .filter(|t| t.is_value_type)
            .map(|t| t.name.clone())
            .collect();
        let type_map: HashMap<String, &CppTypeDecl> =
            types.iter().map(|t| (t.name.clone(), t)).collect();

        let mut graph = CppTypeDependencyGraph::new();
        let graph_types: Vec<GraphType> = types
            .iter()
            .map(|d| Self::to_graph_type(d, &known_value_types))
            .collect();
        graph.add_types_bulk(&graph_types);

        let ordered_names = graph
            .derive_dependency_order()
            .map_err(|cycle| Error::CyclicDependency(cycle.to_string()))?;
        let fwd_candidates = graph.get_forward_declaration_candidates();

        let total_estimate = types.len() * 512;
        let mut buf = String::with_capacity(total_estimate);

        let mut sorted_fwd: Vec<&String> = fwd_candidates.iter().collect();
        sorted_fwd.sort();
        for fwd_name in sorted_fwd {
            if !known_type_names.contains(fwd_name)
                && self.forward_declared.insert(fwd_name.clone())
            {
                writeln!(buf, "struct {};", fwd_name).ok();
            }
        }
        if !fwd_candidates.is_empty() {
            writeln!(buf).ok();
        }

        for name in &ordered_names {
            if let Some(decl) = type_map.get(name) {
                if self.emitted.insert(decl.name.clone()) {
                    self.emit_type_decl(&mut buf, decl, &type_map);
                    writeln!(buf).ok();
                }
            }
        }

        Ok(buf)
    }

    fn emit_type_decl(
        &mut self,
        buf: &mut String,
        decl: &CppTypeDecl,
        type_map: &HashMap<String, &CppTypeDecl>,
    ) {
        self.emit_fields_struct(buf, decl, type_map);
        self.emit_rgctx_struct(buf, decl);
        self.emit_vtable_struct(buf, decl);
        self.emit_class_struct(buf, decl);
        self.emit_object_struct(buf, decl);
        self.emit_static_fields_struct(buf, decl);
    }

    fn emit_fields_struct(
        &mut self,
        buf: &mut String,
        decl: &CppTypeDecl,
        type_map: &HashMap<String, &CppTypeDecl>,
    ) {
        match self.compiler_layout {
            CppCompilerLayout::GCC => {
                self.emit_fields_struct_gcc(buf, decl, type_map);
            }
            CppCompilerLayout::MSVC => {
                self.emit_fields_struct_msvc(buf, decl);
            }
        }
    }

    fn emit_fields_struct_gcc(
        &mut self,
        buf: &mut String,
        decl: &CppTypeDecl,
        type_map: &HashMap<String, &CppTypeDecl>,
    ) {
        if !decl.is_value_type && decl.parent.is_none() {
            let align = if self.is_32bit { 4 } else { 8 };
            writeln!(
                buf,
                "struct __attribute__((aligned({}))) {}_Fields {{",
                align, decl.name
            )
            .ok();
        } else {
            writeln!(buf, "struct {}_Fields {{", decl.name).ok();
        }

        self.write_flattened_parent_fields(buf, decl, type_map);

        for field in &decl.instance_fields {
            Self::write_field_line(buf, field);
        }

        if decl.instance_fields.is_empty() && decl.parent.is_none() {
            writeln!(buf, "\tuint8_t __padding_empty;").ok();
        }

        writeln!(buf, "}};").ok();
    }

    fn write_flattened_parent_fields(
        &self,
        buf: &mut String,
        decl: &CppTypeDecl,
        type_map: &HashMap<String, &CppTypeDecl>,
    ) {
        if let Some(parent_name) = &decl.parent {
            if let Some(parent_decl) = type_map.get(parent_name) {
                self.write_flattened_parent_fields(buf, parent_decl, type_map);
                for field in &parent_decl.instance_fields {
                    Self::write_field_line(buf, field);
                }
            }
        }
    }

    fn emit_fields_struct_msvc(&mut self, buf: &mut String, decl: &CppTypeDecl) {
        if let Some(parent_name) = &decl.parent {
            writeln!(
                buf,
                "struct {}_Fields : {}_Fields {{",
                decl.name, parent_name
            )
            .ok();
        } else if !decl.is_value_type && self.is_pe {
            let align = if self.is_32bit { 4 } else { 8 };
            writeln!(
                buf,
                "struct __declspec(align({})) {}_Fields {{",
                align, decl.name
            )
            .ok();
        } else {
            writeln!(buf, "struct {}_Fields {{", decl.name).ok();
        }

        for field in &decl.instance_fields {
            Self::write_field_line(buf, field);
        }

        if decl.instance_fields.is_empty() && decl.parent.is_none() {
            writeln!(buf, "\tuint8_t __padding_empty;").ok();
        }

        writeln!(buf, "}};").ok();
    }

    fn write_field_line(buf: &mut String, field: &CppField) {
        if field.is_custom_type && needs_struct_prefix(&field.type_name) {
            writeln!(buf, "\tstruct {} {};", field.type_name, field.field_name).ok();
        } else {
            writeln!(buf, "\t{} {};", field.type_name, field.field_name).ok();
        }
    }

    fn emit_rgctx_struct(&self, buf: &mut String, decl: &CppTypeDecl) {
        if decl.rgctxs.is_empty() {
            return;
        }
        writeln!(buf, "struct {}_RGCTXs {{", decl.name).ok();
        for (i, rgctx) in decl.rgctxs.iter().enumerate() {
            match rgctx.rgctx_type as i32 {
                1 => {
                    let tn = rgctx.type_name.as_deref().unwrap_or("unknown");
                    writeln!(buf, "\tIl2CppType* _{i}_{tn};").ok();
                }
                2 => {
                    let cn = rgctx.class_name.as_deref().unwrap_or("unknown");
                    writeln!(buf, "\tIl2CppClass* _{i}_{cn};").ok();
                }
                3 => {
                    let mn = rgctx.method_name.as_deref().unwrap_or("unknown");
                    writeln!(buf, "\tMethodInfo* _{i}_{mn};").ok();
                }
                _ => {}
            }
        }
        writeln!(buf, "}};").ok();
    }

    fn emit_vtable_struct(&self, buf: &mut String, decl: &CppTypeDecl) {
        if decl.vtable.is_empty() {
            return;
        }
        writeln!(buf, "struct {}_VTable {{", decl.name).ok();
        for (i, entry) in decl.vtable.iter().enumerate() {
            let method_name = entry.method_name.as_deref().unwrap_or("unknown");
            writeln!(buf, "\tVirtualInvokeData _{i}_{method_name};").ok();
        }
        writeln!(buf, "}};").ok();
    }

    fn emit_class_struct(&self, buf: &mut String, decl: &CppTypeDecl) {
        writeln!(buf, "struct {}_c {{", decl.name).ok();
        writeln!(buf, "\tIl2CppClass_1 _1;").ok();

        if !decl.static_fields.is_empty() {
            writeln!(buf, "\tstruct {}_StaticFields* static_fields;", decl.name).ok();
        } else {
            writeln!(buf, "\tvoid* static_fields;").ok();
        }

        if !decl.rgctxs.is_empty() {
            writeln!(buf, "\t{}_RGCTXs* rgctx_data;", decl.name).ok();
        } else {
            writeln!(buf, "\tIl2CppRGCTXData* rgctx_data;").ok();
        }

        writeln!(buf, "\tIl2CppClass_2 _2;").ok();

        if !decl.vtable.is_empty() {
            writeln!(buf, "\t{}_VTable vtable;", decl.name).ok();
        } else {
            writeln!(buf, "\tVirtualInvokeData vtable[32];").ok();
        }

        writeln!(buf, "}};").ok();
    }

    fn emit_object_struct(&self, buf: &mut String, decl: &CppTypeDecl) {
        writeln!(buf, "struct {}_o {{", decl.name).ok();
        if !decl.is_value_type {
            writeln!(buf, "\t{}_c *klass;", decl.name).ok();
            writeln!(buf, "\tvoid *monitor;").ok();
        }
        writeln!(buf, "\t{}_Fields fields;", decl.name).ok();
        writeln!(buf, "}};").ok();
    }

    fn emit_static_fields_struct(&self, buf: &mut String, decl: &CppTypeDecl) {
        if decl.static_fields.is_empty() {
            return;
        }
        writeln!(buf, "struct {}_StaticFields {{", decl.name).ok();
        for field in &decl.static_fields {
            Self::write_field_line(buf, field);
        }
        writeln!(buf, "}};").ok();
    }
}