il2cpp-ghidrah 0.1.5__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,610 @@
1
+ # @author
2
+ # @category Il2Cpp
3
+ # @keybinding
4
+ # @menupath
5
+ # @toolbar
6
+ # @runtime PyGhidra
7
+
8
+ import json
9
+ import re
10
+ from collections import Counter, defaultdict
11
+
12
+ from java.lang import Long
13
+ from java.util import ArrayList
14
+ from ghidra.app.util.cparser.C import CParserUtils, ParseException
15
+ from ghidra.app.cmd.function import ApplyFunctionSignatureCmd
16
+ from ghidra.program.model.symbol import SourceType
17
+ from ghidra.program.model.util import CodeUnitInsertionException
18
+ from ghidra.program.model.data import (
19
+ AbstractIntegerDataType,
20
+ CategoryPath,
21
+ DataTypeConflictHandler,
22
+ TypedefDataType,
23
+ )
24
+ from turboheader.il2cpp import Il2CppProgramFacts
25
+
26
+ processFields = [
27
+ "ScriptMethod",
28
+ "ScriptString",
29
+ "ScriptMetadata",
30
+ "ScriptMetadataMethod",
31
+ "Addresses",
32
+ ]
33
+
34
+ functionManager = currentProgram.getFunctionManager()
35
+ baseAddress = currentProgram.getImageBase()
36
+ dtm = currentProgram.getDataTypeManager()
37
+ USER_DEFINED = SourceType.USER_DEFINED
38
+
39
+ MAX_SIGNATURE_FAILURE_SAMPLES = 25
40
+ signature_stats = Counter()
41
+ signature_failure_causes = Counter()
42
+ signature_failure_samples = defaultdict(list)
43
+
44
+ METHODINFO_PARAM_RE = re.compile(
45
+ r"^(?:const\s+)?(?:struct\s+)?MethodInfo(?:_[A-Fa-f0-9]+)?\s*\*\s*method$"
46
+ )
47
+
48
+ C_KEYWORD_PARAMETER_BASES = frozenset((
49
+ "alignas",
50
+ "alignof",
51
+ "asm",
52
+ "atomic",
53
+ "auto",
54
+ "bool",
55
+ "break",
56
+ "case",
57
+ "char",
58
+ "class",
59
+ "complex",
60
+ "const",
61
+ "continue",
62
+ "default",
63
+ "do",
64
+ "double",
65
+ "else",
66
+ "enum",
67
+ "extern",
68
+ "float",
69
+ "for",
70
+ "generic",
71
+ "goto",
72
+ "if",
73
+ "imaginary",
74
+ "inline",
75
+ "int",
76
+ "long",
77
+ "noreturn",
78
+ "register",
79
+ "restrict",
80
+ "return",
81
+ "short",
82
+ "signed",
83
+ "sizeof",
84
+ "static",
85
+ "static_assert",
86
+ "struct",
87
+ "switch",
88
+ "thread_local",
89
+ "typedef",
90
+ "typeof",
91
+ "union",
92
+ "unsigned",
93
+ "void",
94
+ "volatile",
95
+ "while",
96
+ ))
97
+
98
+ FUNCTION_POINTER_PARAMETER_NAME_RE = re.compile(
99
+ r"(\(\s*[*&]\s*)([A-Za-z_][A-Za-z0-9_]*)(\s*\))"
100
+ )
101
+
102
+ TRAILING_PARAMETER_NAME_RE = re.compile(
103
+ r"([A-Za-z_][A-Za-z0-9_]*)(\s*(?:\[[^\]]*\]\s*)*)$"
104
+ )
105
+
106
+
107
+ def sanitize_symbol(symbol_name):
108
+ replacements = {
109
+ "<": "_",
110
+ ">": "",
111
+ ", ": "_",
112
+ ",": "_",
113
+ " ": "_",
114
+ }
115
+
116
+ for old_char, new_char in replacements.items():
117
+ symbol_name = symbol_name.replace(old_char, new_char)
118
+
119
+ return symbol_name
120
+
121
+
122
+ def set_name(addr, name):
123
+ try:
124
+ name = name.replace(" ", "-")
125
+ name = sanitize_symbol(name) + "___" + str(addr)
126
+ createLabel(addr, name, True, USER_DEFINED)
127
+ except Exception as e:
128
+ print("set_name() Failed at {}: {}".format(addr, e))
129
+
130
+
131
+ def get_addr(addr):
132
+ return baseAddress.add(addr)
133
+
134
+
135
+ def set_type(addr, type_str):
136
+ newType = type_str.replace("*", " *").replace(" ", " ").strip()
137
+ dataTypes = getDataTypes(newType)
138
+ addrType = None
139
+
140
+ if len(dataTypes) == 0:
141
+ if newType.endswith(" *"):
142
+ baseType = newType[:-2]
143
+ dataTypes = getDataTypes(baseType)
144
+ if len(dataTypes) == 1:
145
+ pointerType = dtm.getPointer(dataTypes[0])
146
+ addrType = dtm.addDataType(pointerType, None)
147
+ elif len(dataTypes) > 1:
148
+ print("Conflicting data types found for type {} (parsed as '{}')".format(type_str, newType))
149
+ return
150
+ else:
151
+ addrType = dataTypes[0]
152
+
153
+ if addrType is None:
154
+ print("Could not identify type {} (parsed as '{}')".format(type_str, newType))
155
+ else:
156
+ try:
157
+ createData(addr, addrType)
158
+ except CodeUnitInsertionException:
159
+ print("Warning: unable to set type at {} (CodeUnitInsertionException)".format(addr))
160
+ except Exception as e:
161
+ print("Warning: unable to set type at {}: {}".format(addr, e))
162
+
163
+
164
+ def make_function(start):
165
+ func = getFunctionAt(start)
166
+ if func is None:
167
+ try:
168
+ createFunction(start, None)
169
+ except Exception as e:
170
+ print("Warning: Unable to create function at {}: {}".format(start, e))
171
+
172
+
173
+ def _integer_type(is_signed, size):
174
+ if is_signed:
175
+ return AbstractIntegerDataType.getSignedDataType(size, dtm)
176
+ return AbstractIntegerDataType.getUnsignedDataType(size, dtm)
177
+
178
+
179
+ def _has_named_datatype(name):
180
+ try:
181
+ for data_type in getDataTypes(name):
182
+ if data_type.getName() == name:
183
+ return True
184
+ except Exception:
185
+ pass
186
+ return False
187
+
188
+
189
+ def register_c_integer_aliases():
190
+ pointer_size = currentProgram.getDefaultPointerSize()
191
+ aliases = (
192
+ ("int8_t", True, 1),
193
+ ("uint8_t", False, 1),
194
+ ("int16_t", True, 2),
195
+ ("uint16_t", False, 2),
196
+ ("int32_t", True, 4),
197
+ ("uint32_t", False, 4),
198
+ ("int64_t", True, 8),
199
+ ("uint64_t", False, 8),
200
+ ("intptr_t", True, pointer_size),
201
+ ("uintptr_t", False, pointer_size),
202
+ ("size_t", False, pointer_size),
203
+ ("ssize_t", True, pointer_size),
204
+ ("ptrdiff_t", True, pointer_size),
205
+ ("il2cpp_array_size_t", False, pointer_size),
206
+ ("il2cpp_array_lower_bound_t", True, 4),
207
+ )
208
+
209
+ added = 0
210
+ existing = 0
211
+ for name, is_signed, size in aliases:
212
+ if _has_named_datatype(name):
213
+ existing += 1
214
+ continue
215
+
216
+ base_type = _integer_type(is_signed, size)
217
+ typedef = TypedefDataType(CategoryPath("/"), name, base_type, dtm)
218
+ dtm.addDataType(typedef, DataTypeConflictHandler.KEEP_HANDLER)
219
+ added += 1
220
+
221
+ print("[*] C aliases ready: {} added, {} already present".format(added, existing))
222
+
223
+
224
+ def split_top_level_arguments(text):
225
+ if not text.strip():
226
+ return []
227
+
228
+ result = []
229
+ start = 0
230
+ parentheses = 0
231
+ brackets = 0
232
+
233
+ for index, char in enumerate(text):
234
+ if char == "(":
235
+ parentheses += 1
236
+ elif char == ")":
237
+ parentheses -= 1
238
+ elif char == "[":
239
+ brackets += 1
240
+ elif char == "]":
241
+ brackets -= 1
242
+ elif char == "," and parentheses == 0 and brackets == 0:
243
+ result.append(text[start:index].strip())
244
+ start = index + 1
245
+
246
+ result.append(text[start:].strip())
247
+ return result
248
+
249
+
250
+ def remove_hidden_methodinfo(signature):
251
+ signature = signature.strip()
252
+ if signature.endswith(";"):
253
+ signature = signature[:-1].rstrip()
254
+
255
+ close_index = signature.rfind(")")
256
+ if close_index < 0:
257
+ return signature
258
+
259
+ depth = 0
260
+ open_index = None
261
+ for index in range(close_index, -1, -1):
262
+ char = signature[index]
263
+ if char == ")":
264
+ depth += 1
265
+ elif char == "(":
266
+ depth -= 1
267
+ if depth == 0:
268
+ open_index = index
269
+ break
270
+
271
+ if open_index is None:
272
+ return signature
273
+
274
+ arguments = split_top_level_arguments(signature[open_index + 1:close_index])
275
+ if not arguments or not METHODINFO_PARAM_RE.fullmatch(arguments[-1].strip()):
276
+ return signature
277
+
278
+ arguments = arguments[:-1]
279
+ replacement = ", ".join(arguments) if arguments else "void"
280
+ return signature[:open_index + 1] + replacement + signature[close_index:]
281
+
282
+
283
+ def is_keyword_shaped_parameter_name(name):
284
+ if not name or not name.startswith("_"):
285
+ return False
286
+
287
+ base_name = name.lstrip("_").lower()
288
+ return base_name in C_KEYWORD_PARAMETER_BASES
289
+
290
+
291
+ def repaired_parameter_name(name):
292
+ return "{}_arg".format(name)
293
+
294
+
295
+ def sanitize_one_parameter_declaration(argument):
296
+ stripped = argument.strip()
297
+ if not stripped or stripped == "void" or stripped == "...":
298
+ return argument, 0
299
+
300
+ function_pointer_match = FUNCTION_POINTER_PARAMETER_NAME_RE.search(argument)
301
+ if function_pointer_match is not None:
302
+ name = function_pointer_match.group(2)
303
+ if is_keyword_shaped_parameter_name(name):
304
+ replacement = (
305
+ function_pointer_match.group(1)
306
+ + repaired_parameter_name(name)
307
+ + function_pointer_match.group(3)
308
+ )
309
+ return (
310
+ argument[:function_pointer_match.start()]
311
+ + replacement
312
+ + argument[function_pointer_match.end():],
313
+ 1,
314
+ )
315
+
316
+ trailing_match = TRAILING_PARAMETER_NAME_RE.search(argument)
317
+ if trailing_match is None:
318
+ return argument, 0
319
+
320
+ name = trailing_match.group(1)
321
+ if not is_keyword_shaped_parameter_name(name):
322
+ return argument, 0
323
+
324
+ if not argument[:trailing_match.start(1)].strip():
325
+ return argument, 0
326
+
327
+ replacement = repaired_parameter_name(name) + trailing_match.group(2)
328
+ return (
329
+ argument[:trailing_match.start(1)]
330
+ + replacement
331
+ + argument[trailing_match.end():],
332
+ 1,
333
+ )
334
+
335
+
336
+ def sanitize_signature_parameter_names(signature):
337
+ close_index = signature.rfind(")")
338
+ if close_index < 0:
339
+ return signature
340
+
341
+ depth = 0
342
+ open_index = None
343
+ for index in range(close_index, -1, -1):
344
+ char = signature[index]
345
+ if char == ")":
346
+ depth += 1
347
+ elif char == "(":
348
+ depth -= 1
349
+ if depth == 0:
350
+ open_index = index
351
+ break
352
+
353
+ if open_index is None:
354
+ return signature
355
+
356
+ arguments = split_top_level_arguments(
357
+ signature[open_index + 1:close_index]
358
+ )
359
+
360
+ if not arguments:
361
+ return signature
362
+
363
+ repaired_arguments = []
364
+ repaired_count = 0
365
+
366
+ for argument in arguments:
367
+ repaired_argument, count = sanitize_one_parameter_declaration(argument)
368
+ repaired_arguments.append(repaired_argument)
369
+ repaired_count += count
370
+
371
+ if repaired_count == 0:
372
+ return signature
373
+
374
+ signature_stats["reserved_parameter_names_repaired"] += repaired_count
375
+
376
+ return (
377
+ signature[:open_index + 1]
378
+ + ", ".join(repaired_arguments)
379
+ + signature[close_index:]
380
+ )
381
+
382
+
383
+ def make_unique_parameter_names(type_sig):
384
+ args = type_sig.getArguments()
385
+ used_names = set()
386
+ next_suffix = Counter()
387
+ modified = False
388
+
389
+ for index, arg in enumerate(args):
390
+ name = arg.getName()
391
+ if not name:
392
+ name = "param_{}".format(index + 1)
393
+
394
+ if name not in used_names:
395
+ used_names.add(name)
396
+ next_suffix[name] = 1
397
+ if arg.getName() != name:
398
+ arg.setName(name)
399
+ modified = True
400
+ continue
401
+
402
+ suffix = next_suffix[name]
403
+ candidate = "{}_{}".format(name, suffix)
404
+ while candidate in used_names:
405
+ suffix += 1
406
+ candidate = "{}_{}".format(name, suffix)
407
+
408
+ next_suffix[name] = suffix + 1
409
+ used_names.add(candidate)
410
+ arg.setName(candidate)
411
+ modified = True
412
+ signature_stats["duplicate_names_repaired"] += 1
413
+
414
+ if modified:
415
+ type_sig.setArguments(args)
416
+
417
+
418
+ def record_signature_failure(name, addr, signature, error):
419
+ message = str(error).strip() or error.__class__.__name__
420
+ first_line = message.splitlines()[0]
421
+ signature_failure_causes[first_line] += 1
422
+
423
+ if sum(len(samples) for samples in signature_failure_samples.values()) < MAX_SIGNATURE_FAILURE_SAMPLES:
424
+ signature_failure_samples[first_line].append(
425
+ (name, str(addr), signature, message)
426
+ )
427
+
428
+
429
+ def set_sig(addr, name, signature):
430
+ signature_stats["total"] += 1
431
+ signature = remove_hidden_methodinfo(signature)
432
+ signature = sanitize_signature_parameter_names(signature)
433
+
434
+ try:
435
+ type_sig = CParserUtils.parseSignature(None, currentProgram, signature, False)
436
+ except ParseException as error:
437
+ signature_stats["parse_failed"] += 1
438
+ record_signature_failure(name, addr, signature, error)
439
+ return False
440
+ except Exception as error:
441
+ signature_stats["unexpected_parse_failed"] += 1
442
+ record_signature_failure(name, addr, signature, error)
443
+ return False
444
+
445
+ try:
446
+ make_unique_parameter_names(type_sig)
447
+ type_sig.setName(sanitize_symbol(name))
448
+
449
+ default_cc = (
450
+ currentProgram
451
+ .getCompilerSpec()
452
+ .getDefaultCallingConvention()
453
+ )
454
+
455
+ if default_cc is not None:
456
+ type_sig.setCallingConvention(default_cc.getName())
457
+
458
+ command = ApplyFunctionSignatureCmd(
459
+ addr,
460
+ type_sig,
461
+ USER_DEFINED,
462
+ False,
463
+ True,
464
+ )
465
+ applied = command.applyTo(currentProgram, monitor)
466
+ if not applied:
467
+ signature_stats["apply_failed"] += 1
468
+ status = command.getStatusMsg()
469
+ record_signature_failure(
470
+ name,
471
+ addr,
472
+ signature,
473
+ RuntimeError(status or "ApplyFunctionSignatureCmd returned false"),
474
+ )
475
+ return False
476
+
477
+ signature_stats["applied"] += 1
478
+ return True
479
+ except Exception as error:
480
+ signature_stats["apply_failed"] += 1
481
+ record_signature_failure(name, addr, signature, error)
482
+ return False
483
+
484
+
485
+ def print_signature_summary():
486
+ print("\n[*] Signature import summary")
487
+ print(" total : {}".format(signature_stats["total"]))
488
+ print(" applied : {}".format(signature_stats["applied"]))
489
+ print(" duplicate names repaired: {}".format(signature_stats["duplicate_names_repaired"]))
490
+ print(" reserved names repaired : {}".format(signature_stats["reserved_parameter_names_repaired"]))
491
+ print(" parse failed : {}".format(signature_stats["parse_failed"]))
492
+ print(" unexpected parse failed : {}".format(signature_stats["unexpected_parse_failed"]))
493
+ print(" apply failed : {}".format(signature_stats["apply_failed"]))
494
+
495
+ if not signature_failure_causes:
496
+ return
497
+
498
+ print("\n[!] Top signature failure causes")
499
+ for cause, count in signature_failure_causes.most_common(10):
500
+ print(" {:>7} {}".format(count, cause))
501
+
502
+ print("\n[!] Bounded signature failure samples ({})".format(
503
+ sum(len(samples) for samples in signature_failure_samples.values())
504
+ ))
505
+ shown = 0
506
+ for cause, samples in signature_failure_samples.items():
507
+ for name, addr, signature, message in samples:
508
+ shown += 1
509
+ print("\n Sample {}".format(shown))
510
+ print(" function : {}".format(name))
511
+ print(" address : {}".format(addr))
512
+ print(" signature: {}".format(signature))
513
+ print(" parser : {}".format(message))
514
+
515
+
516
+ def register_managed_method_facts(script_methods):
517
+ method_offsets = ArrayList(len(script_methods))
518
+ runtime_metadata_probe_offsets = ArrayList()
519
+
520
+ for index, method in enumerate(script_methods):
521
+ address = method.get("Address")
522
+ name = method.get("Name")
523
+ if isinstance(address, bool) or not isinstance(address, int) or address < 0:
524
+ raise ValueError("invalid ScriptMethod address at index {}".format(index))
525
+ if not isinstance(name, str):
526
+ raise ValueError("invalid ScriptMethod name at index {}".format(index))
527
+
528
+ boxed_address = Long.valueOf(address)
529
+ method_offsets.add(boxed_address)
530
+ if name == "System.Exception$$get_Message":
531
+ runtime_metadata_probe_offsets.add(boxed_address)
532
+
533
+ stats = Il2CppProgramFacts.replaceManagedMethodOffsets(
534
+ currentProgram,
535
+ method_offsets,
536
+ runtime_metadata_probe_offsets,
537
+ )
538
+ print(
539
+ "[*] IL2CPP program facts: {} method entries, {} unique executable methods, "
540
+ "{} runtime metadata probes".format(
541
+ stats.methodEntries(),
542
+ stats.managedMethods(),
543
+ stats.runtimeMetadataProbes(),
544
+ )
545
+ )
546
+
547
+
548
+ args = getScriptArgs()
549
+
550
+ if len(args) < 1:
551
+ print("[-] Missing script.json path")
552
+ exit(-1)
553
+
554
+ path = args[0]
555
+ print("[*] Loading: {}".format(path))
556
+
557
+ with open(path, "r", encoding="utf-8") as json_file:
558
+ data = json.load(json_file)
559
+
560
+ register_c_integer_aliases()
561
+
562
+ if "ScriptMethod" in data and "ScriptMethod" in processFields:
563
+ scriptMethods = data["ScriptMethod"]
564
+ register_managed_method_facts(scriptMethods)
565
+ monitor.initialize(len(scriptMethods))
566
+ monitor.setMessage("Methods")
567
+ for scriptMethod in scriptMethods:
568
+ addr = get_addr(scriptMethod["Address"])
569
+ name = scriptMethod["Name"]
570
+ set_name(addr, name)
571
+ monitor.incrementProgress(1)
572
+
573
+ if "ScriptMetadataMethod" in data and "ScriptMetadataMethod" in processFields:
574
+ scriptMetadataMethods = data["ScriptMetadataMethod"]
575
+ monitor.initialize(len(scriptMetadataMethods))
576
+ monitor.setMessage("Metadata Methods")
577
+ for scriptMetadataMethod in scriptMetadataMethods:
578
+ addr = get_addr(scriptMetadataMethod["Address"])
579
+ name = scriptMetadataMethod["Name"]
580
+ set_name(addr, name)
581
+ setEOLComment(addr, name)
582
+ monitor.incrementProgress(1)
583
+
584
+ if "Addresses" in data and "Addresses" in processFields:
585
+ addresses = data["Addresses"]
586
+ monitor.initialize(len(addresses))
587
+ monitor.setMessage("Addresses")
588
+ for index in range(len(addresses) - 1):
589
+ start = get_addr(addresses[index])
590
+ make_function(start)
591
+ monitor.incrementProgress(1)
592
+
593
+ if "ScriptMethod" in data and "ScriptMethod" in processFields:
594
+ scriptMethods = data["ScriptMethod"]
595
+ monitor.initialize(len(scriptMethods))
596
+ monitor.setMessage("Applying IL2CPP method signatures")
597
+ for scriptMethod in scriptMethods:
598
+ addr = get_addr(scriptMethod["Address"])
599
+ signature = scriptMethod.get("Signature", "")
600
+ name = scriptMethod["Name"]
601
+ if signature:
602
+ set_sig(addr, name, signature)
603
+ else:
604
+ signature_stats["total"] += 1
605
+ signature_stats["parse_failed"] += 1
606
+ record_signature_failure(name, addr, "", ValueError("empty signature"))
607
+ monitor.incrementProgress(1)
608
+
609
+ print_signature_summary()
610
+ print("Script finished!")