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.
- il2cpp_ghidrah/__init__.py +3 -0
- il2cpp_ghidrah/__main__.py +3 -0
- il2cpp_ghidrah/cli.py +146 -0
- il2cpp_ghidrah/config.py +46 -0
- il2cpp_ghidrah/generators.py +167 -0
- il2cpp_ghidrah/ghidra.py +140 -0
- il2cpp_ghidrah/ghidra_scripts/ghidraUnityMetadata.py +96 -0
- il2cpp_ghidrah/ghidra_scripts/ghidra_with_struct_headless.py +610 -0
- il2cpp_ghidrah/ghidra_scripts/parse_header_headless.py +214 -0
- il2cpp_ghidrah/inputs.py +393 -0
- il2cpp_ghidrah/installation.py +160 -0
- il2cpp_ghidrah/pipeline.py +221 -0
- il2cpp_ghidrah/process.py +75 -0
- il2cpp_ghidrah/selection.py +56 -0
- il2cpp_ghidrah-0.1.5.dist-info/METADATA +187 -0
- il2cpp_ghidrah-0.1.5.dist-info/RECORD +20 -0
- il2cpp_ghidrah-0.1.5.dist-info/WHEEL +5 -0
- il2cpp_ghidrah-0.1.5.dist-info/entry_points.txt +2 -0
- il2cpp_ghidrah-0.1.5.dist-info/licenses/LICENSE +21 -0
- il2cpp_ghidrah-0.1.5.dist-info/top_level.txt +1 -0
il2cpp_ghidrah/cli.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import json
|
|
5
|
+
import sys
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from . import __version__
|
|
9
|
+
from .config import RunConfig
|
|
10
|
+
from .installation import doctor
|
|
11
|
+
from .pipeline import run
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _class_list(value: str) -> list[str]:
|
|
15
|
+
try:
|
|
16
|
+
parsed = json.loads(value)
|
|
17
|
+
except json.JSONDecodeError as error:
|
|
18
|
+
raise argparse.ArgumentTypeError(f"invalid JSON class list: {error}") from error
|
|
19
|
+
if not isinstance(parsed, list) or not all(isinstance(item, str) and item.strip() for item in parsed):
|
|
20
|
+
raise argparse.ArgumentTypeError("--classes must be a JSON array of non-empty strings")
|
|
21
|
+
return [item.strip() for item in parsed]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _classes_file(path: Path) -> list[str]:
|
|
25
|
+
text = path.read_text(encoding="utf-8")
|
|
26
|
+
if path.suffix.lower() == ".json":
|
|
27
|
+
return _class_list(text)
|
|
28
|
+
return [line.split("#", 1)[0].strip() for line in text.splitlines() if line.split("#", 1)[0].strip()]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _common_tools(parser: argparse.ArgumentParser) -> None:
|
|
32
|
+
parser.add_argument("--ghidra", type=Path, help="Ghidra installation root (or GHIDRA_INSTALL_DIR)")
|
|
33
|
+
parser.add_argument("--il2cpp-command", default="il2cpp")
|
|
34
|
+
parser.add_argument("--dumper-command", default="Il2CppDumper")
|
|
35
|
+
parser.add_argument("--cpp2il-command", default="Cpp2IL")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def parser() -> argparse.ArgumentParser:
|
|
39
|
+
root = argparse.ArgumentParser(prog="il2cpp-ghidrah", description="Headless Ghidra pipeline for Unity IL2CPP")
|
|
40
|
+
root.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
|
|
41
|
+
commands = root.add_subparsers(dest="command", required=True)
|
|
42
|
+
|
|
43
|
+
run_parser = commands.add_parser("run", help="generate artifacts and run targeted Ghidra headlessly")
|
|
44
|
+
run_parser.add_argument("input", type=Path, help="APK/XAPK/APKS/ZIP, extracted directory, or native binary")
|
|
45
|
+
run_parser.add_argument("-o", "--output", type=Path, required=True)
|
|
46
|
+
run_parser.add_argument("-g", "--generator", choices=("auto", "aotopsy", "dumper"), default="auto")
|
|
47
|
+
run_parser.add_argument("--importer", choices=("turbo", "cparser"), default="turbo")
|
|
48
|
+
run_parser.add_argument("-l", "--layout", choices=("inferred", "external", "authoritative"), default="external")
|
|
49
|
+
run_parser.add_argument("-s", "--scope", choices=("whitelist", "blacklist", "all"), default="blacklist")
|
|
50
|
+
run_parser.add_argument("-M", "--metadata", type=Path)
|
|
51
|
+
run_parser.add_argument("-A", "--assets", type=Path)
|
|
52
|
+
run_parser.add_argument("-U", "--unity-data", type=Path)
|
|
53
|
+
run_parser.add_argument("-u", "--unity", "--force-unity-version", dest="unity")
|
|
54
|
+
run_parser.add_argument("--abi", default="arm64-v8a")
|
|
55
|
+
run_parser.add_argument("-a", "--assembly", action="append", default=[])
|
|
56
|
+
run_parser.add_argument("-c", "--class", dest="selected_classes", action="append", default=[])
|
|
57
|
+
run_parser.add_argument("--classes", type=_class_list, default=[])
|
|
58
|
+
run_parser.add_argument("--classes-file", type=Path)
|
|
59
|
+
run_parser.add_argument("--ignore-frameworks", type=Path)
|
|
60
|
+
run_parser.add_argument("--project-name")
|
|
61
|
+
run_parser.add_argument(
|
|
62
|
+
"--decompile-jobs",
|
|
63
|
+
type=int,
|
|
64
|
+
choices=range(13),
|
|
65
|
+
default=8,
|
|
66
|
+
metavar="N",
|
|
67
|
+
help="Ghidra decompiler workers from 0 through 12 (default: 8; 0 uses the legacy sequential path)",
|
|
68
|
+
)
|
|
69
|
+
run_parser.add_argument("--dry-run", action="store_true")
|
|
70
|
+
run_parser.add_argument("--show-commands", action="store_true")
|
|
71
|
+
run_parser.add_argument("--keep-temporary", action="store_true")
|
|
72
|
+
_common_tools(run_parser)
|
|
73
|
+
|
|
74
|
+
doctor_parser = commands.add_parser("doctor", help="verify the headless toolchain installation")
|
|
75
|
+
doctor_parser.add_argument("-g", "--generator", choices=("auto", "aotopsy", "dumper"), default="auto")
|
|
76
|
+
doctor_parser.add_argument("--importer", choices=("turbo", "cparser"), default="turbo")
|
|
77
|
+
doctor_parser.add_argument("--probe", action="store_true", help="initialize Ghidra through PyGhidra")
|
|
78
|
+
doctor_parser.add_argument("--json", action="store_true", dest="json_output")
|
|
79
|
+
_common_tools(doctor_parser)
|
|
80
|
+
return root
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _run(args: argparse.Namespace) -> None:
|
|
84
|
+
classes = [*args.selected_classes, *args.classes]
|
|
85
|
+
if args.classes_file:
|
|
86
|
+
classes.extend(_classes_file(args.classes_file))
|
|
87
|
+
config = RunConfig(
|
|
88
|
+
input_path=args.input,
|
|
89
|
+
output=args.output,
|
|
90
|
+
generator=args.generator,
|
|
91
|
+
layout=args.layout,
|
|
92
|
+
scope=args.scope,
|
|
93
|
+
metadata=args.metadata,
|
|
94
|
+
assets=args.assets,
|
|
95
|
+
unity_data=args.unity_data,
|
|
96
|
+
unity=args.unity,
|
|
97
|
+
abi=args.abi,
|
|
98
|
+
assemblies=tuple(dict.fromkeys(args.assembly)),
|
|
99
|
+
classes=tuple(dict.fromkeys(classes)),
|
|
100
|
+
ignore_frameworks=args.ignore_frameworks,
|
|
101
|
+
ghidra_dir=args.ghidra,
|
|
102
|
+
importer=args.importer,
|
|
103
|
+
project_name=args.project_name,
|
|
104
|
+
il2cpp_command=args.il2cpp_command,
|
|
105
|
+
dumper_command=args.dumper_command,
|
|
106
|
+
cpp2il_command=args.cpp2il_command,
|
|
107
|
+
decompile_jobs=args.decompile_jobs,
|
|
108
|
+
dry_run=args.dry_run,
|
|
109
|
+
show_commands=args.show_commands,
|
|
110
|
+
keep_temporary=args.keep_temporary,
|
|
111
|
+
)
|
|
112
|
+
run(config)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _doctor(args: argparse.Namespace) -> int:
|
|
116
|
+
checks = doctor(
|
|
117
|
+
args.ghidra,
|
|
118
|
+
importer=args.importer,
|
|
119
|
+
generator=args.generator,
|
|
120
|
+
il2cpp_command=args.il2cpp_command,
|
|
121
|
+
dumper_command=args.dumper_command,
|
|
122
|
+
cpp2il_command=args.cpp2il_command,
|
|
123
|
+
probe=args.probe,
|
|
124
|
+
)
|
|
125
|
+
if args.json_output:
|
|
126
|
+
print(json.dumps([{"name": name, "ok": ok, "detail": detail} for name, ok, detail in checks], indent=2))
|
|
127
|
+
else:
|
|
128
|
+
for name, ok, detail in checks:
|
|
129
|
+
print(f"{'OK' if ok else 'FAIL':4} {name}: {detail}")
|
|
130
|
+
return 0 if all(ok for _, ok, _ in checks) else 1
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def main(argv: list[str] | None = None) -> int:
|
|
134
|
+
args = parser().parse_args(argv)
|
|
135
|
+
try:
|
|
136
|
+
if args.command == "run":
|
|
137
|
+
_run(args)
|
|
138
|
+
return 0
|
|
139
|
+
return _doctor(args)
|
|
140
|
+
except (FileNotFoundError, FileExistsError, ValueError, RuntimeError) as error:
|
|
141
|
+
print(f"il2cpp-ghidrah: error: {error}", file=sys.stderr)
|
|
142
|
+
return 2
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
if __name__ == "__main__":
|
|
146
|
+
raise SystemExit(main())
|
il2cpp_ghidrah/config.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
LAYOUT_POLICIES = {
|
|
8
|
+
"inferred": "allow-inferred",
|
|
9
|
+
"external": "require-external-offsets",
|
|
10
|
+
"authoritative": "require-authoritative",
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass(frozen=True)
|
|
15
|
+
class RunConfig:
|
|
16
|
+
input_path: Path
|
|
17
|
+
output: Path
|
|
18
|
+
generator: str = "auto"
|
|
19
|
+
layout: str = "external"
|
|
20
|
+
scope: str = "blacklist"
|
|
21
|
+
metadata: Path | None = None
|
|
22
|
+
assets: Path | None = None
|
|
23
|
+
unity_data: Path | None = None
|
|
24
|
+
unity: str | None = None
|
|
25
|
+
abi: str = "arm64-v8a"
|
|
26
|
+
assemblies: tuple[str, ...] = ()
|
|
27
|
+
classes: tuple[str, ...] = ()
|
|
28
|
+
ignore_frameworks: Path | None = None
|
|
29
|
+
ghidra_dir: Path | None = None
|
|
30
|
+
importer: str = "turbo"
|
|
31
|
+
project_name: str | None = None
|
|
32
|
+
il2cpp_command: str = "il2cpp"
|
|
33
|
+
dumper_command: str = "Il2CppDumper"
|
|
34
|
+
cpp2il_command: str = "Cpp2IL"
|
|
35
|
+
decompile_jobs: int = 8
|
|
36
|
+
dry_run: bool = False
|
|
37
|
+
show_commands: bool = False
|
|
38
|
+
keep_temporary: bool = False
|
|
39
|
+
|
|
40
|
+
def __post_init__(self) -> None:
|
|
41
|
+
if type(self.decompile_jobs) is not int or not 0 <= self.decompile_jobs <= 12:
|
|
42
|
+
raise ValueError("decompile_jobs must be an integer from 0 through 12")
|
|
43
|
+
|
|
44
|
+
@property
|
|
45
|
+
def turbo_policy(self) -> str:
|
|
46
|
+
return LAYOUT_POLICIES[self.layout]
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
import shutil
|
|
6
|
+
|
|
7
|
+
from .config import RunConfig
|
|
8
|
+
from .inputs import ResolvedInput
|
|
9
|
+
from .process import run_command
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass(frozen=True)
|
|
13
|
+
class Artifacts:
|
|
14
|
+
directory: Path
|
|
15
|
+
header: Path
|
|
16
|
+
script: Path
|
|
17
|
+
offsets: Path
|
|
18
|
+
diffable: Path
|
|
19
|
+
generator: str
|
|
20
|
+
noreturn_seeds: Path | None
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def resolve_tool(command: str) -> str | None:
|
|
24
|
+
return shutil.which(command)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def select_generator(config: RunConfig) -> tuple[str, str, str | None]:
|
|
28
|
+
aotopsy = resolve_tool(config.il2cpp_command)
|
|
29
|
+
dumper = resolve_tool(config.dumper_command)
|
|
30
|
+
cpp2il = resolve_tool(config.cpp2il_command)
|
|
31
|
+
if config.generator == "aotopsy":
|
|
32
|
+
if not aotopsy:
|
|
33
|
+
raise FileNotFoundError(f"AOTopsy command not found: {config.il2cpp_command}")
|
|
34
|
+
return "aotopsy", aotopsy, None
|
|
35
|
+
if config.generator == "dumper":
|
|
36
|
+
if not dumper:
|
|
37
|
+
raise FileNotFoundError(f"Il2CppDumper command not found: {config.dumper_command}")
|
|
38
|
+
if not cpp2il:
|
|
39
|
+
raise FileNotFoundError(f"Cpp2IL command not found: {config.cpp2il_command}")
|
|
40
|
+
return "dumper", dumper, cpp2il
|
|
41
|
+
if aotopsy:
|
|
42
|
+
return "aotopsy", aotopsy, None
|
|
43
|
+
if dumper and cpp2il:
|
|
44
|
+
return "dumper", dumper, cpp2il
|
|
45
|
+
raise FileNotFoundError(
|
|
46
|
+
"no artifact generator is usable: install AOTopsy, or both Il2CppDumper and Cpp2IL"
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _input_options(config: RunConfig, resolved: ResolvedInput) -> list[str]:
|
|
51
|
+
options: list[str] = []
|
|
52
|
+
if resolved.original == resolved.binary:
|
|
53
|
+
options += ["--metadata", str(resolved.metadata)]
|
|
54
|
+
if config.unity:
|
|
55
|
+
options += ["--unity", config.unity]
|
|
56
|
+
elif config.unity_data:
|
|
57
|
+
options += ["--unity-data", str(config.unity_data.resolve())]
|
|
58
|
+
elif resolved.assets:
|
|
59
|
+
options += ["--assets", str(resolved.assets)]
|
|
60
|
+
return options
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _cpp2il_unity_version(config: RunConfig) -> str:
|
|
64
|
+
if config.unity:
|
|
65
|
+
return config.unity
|
|
66
|
+
raise ValueError(
|
|
67
|
+
"Cpp2IL requires the exact Unity version; pass --unity <version>. "
|
|
68
|
+
"No default version is guessed."
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def generate(
|
|
73
|
+
config: RunConfig,
|
|
74
|
+
resolved: ResolvedInput,
|
|
75
|
+
artifacts_dir: Path,
|
|
76
|
+
cpp2il_dir: Path,
|
|
77
|
+
logs_dir: Path,
|
|
78
|
+
) -> Artifacts:
|
|
79
|
+
artifacts_dir.mkdir(parents=True, exist_ok=True)
|
|
80
|
+
cpp2il_dir.mkdir(parents=True, exist_ok=True)
|
|
81
|
+
input_options = _input_options(config, resolved)
|
|
82
|
+
generator, generator_command, cpp2il_command = select_generator(config)
|
|
83
|
+
cpp2il_unity_version = None
|
|
84
|
+
if generator == "dumper":
|
|
85
|
+
cpp2il_unity_version = _cpp2il_unity_version(config)
|
|
86
|
+
print(f"Artifact generator selected: {generator}")
|
|
87
|
+
if generator == "aotopsy":
|
|
88
|
+
command = [
|
|
89
|
+
generator_command,
|
|
90
|
+
"gen",
|
|
91
|
+
str(resolved.original),
|
|
92
|
+
str(artifacts_dir),
|
|
93
|
+
*input_options,
|
|
94
|
+
]
|
|
95
|
+
else:
|
|
96
|
+
command = [
|
|
97
|
+
generator_command,
|
|
98
|
+
str(resolved.binary),
|
|
99
|
+
str(resolved.metadata),
|
|
100
|
+
str(artifacts_dir),
|
|
101
|
+
]
|
|
102
|
+
run_command(
|
|
103
|
+
command,
|
|
104
|
+
log=logs_dir / "generation.log",
|
|
105
|
+
dry_run=config.dry_run,
|
|
106
|
+
show=config.show_commands,
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
if generator == "aotopsy":
|
|
110
|
+
diffable_command = [
|
|
111
|
+
generator_command,
|
|
112
|
+
"diffable",
|
|
113
|
+
str(resolved.original),
|
|
114
|
+
str(cpp2il_dir),
|
|
115
|
+
*input_options,
|
|
116
|
+
]
|
|
117
|
+
else:
|
|
118
|
+
if cpp2il_unity_version is None:
|
|
119
|
+
raise RuntimeError("Cpp2IL Unity version was not resolved")
|
|
120
|
+
diffable_command = [
|
|
121
|
+
str(cpp2il_command),
|
|
122
|
+
"--force-binary-path",
|
|
123
|
+
str(resolved.binary),
|
|
124
|
+
"--force-metadata-path",
|
|
125
|
+
str(resolved.metadata),
|
|
126
|
+
"--output-as",
|
|
127
|
+
"diffable-cs",
|
|
128
|
+
"--output-to",
|
|
129
|
+
str(cpp2il_dir),
|
|
130
|
+
"--force-unity-version",
|
|
131
|
+
cpp2il_unity_version,
|
|
132
|
+
]
|
|
133
|
+
run_command(
|
|
134
|
+
diffable_command,
|
|
135
|
+
log=logs_dir / "diffable.log",
|
|
136
|
+
dry_run=config.dry_run,
|
|
137
|
+
show=config.show_commands,
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
header = artifacts_dir / "il2cpp.h"
|
|
141
|
+
script = artifacts_dir / "script.json"
|
|
142
|
+
if config.layout == "inferred":
|
|
143
|
+
offsets = Path("-")
|
|
144
|
+
elif generator == "aotopsy":
|
|
145
|
+
offsets = artifacts_dir / "type_offsets.json"
|
|
146
|
+
else:
|
|
147
|
+
offsets = artifacts_dir / "dump.cs"
|
|
148
|
+
if not config.dry_run:
|
|
149
|
+
required = [header, script, cpp2il_dir / "DiffableCs"]
|
|
150
|
+
if offsets != Path("-"):
|
|
151
|
+
required.append(offsets)
|
|
152
|
+
missing = [str(path) for path in required if not path.exists()]
|
|
153
|
+
if missing:
|
|
154
|
+
raise FileNotFoundError("generator did not produce: " + ", ".join(missing))
|
|
155
|
+
noreturn_seeds = artifacts_dir / "noreturn-seeds.txt" if generator == "aotopsy" else None
|
|
156
|
+
if noreturn_seeds is not None and not config.dry_run:
|
|
157
|
+
if not noreturn_seeds.is_file() or noreturn_seeds.stat().st_size == 0:
|
|
158
|
+
noreturn_seeds = None
|
|
159
|
+
return Artifacts(
|
|
160
|
+
artifacts_dir,
|
|
161
|
+
header,
|
|
162
|
+
script,
|
|
163
|
+
offsets,
|
|
164
|
+
cpp2il_dir / "DiffableCs",
|
|
165
|
+
generator,
|
|
166
|
+
noreturn_seeds,
|
|
167
|
+
)
|
il2cpp_ghidrah/ghidra.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import contextlib
|
|
4
|
+
import multiprocessing
|
|
5
|
+
import os
|
|
6
|
+
import queue
|
|
7
|
+
import shutil
|
|
8
|
+
import sys
|
|
9
|
+
import tempfile
|
|
10
|
+
import time
|
|
11
|
+
import traceback
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Sequence
|
|
15
|
+
|
|
16
|
+
from .process import MirroredTextWriter, display_command
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass(frozen=True)
|
|
20
|
+
class HeadlessLogs:
|
|
21
|
+
application: Path
|
|
22
|
+
script: Path
|
|
23
|
+
launcher: Path
|
|
24
|
+
elapsed_seconds: float
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def format_elapsed(seconds: float) -> str:
|
|
28
|
+
milliseconds = round(max(0.0, seconds) * 1000)
|
|
29
|
+
hours, remainder = divmod(milliseconds, 3_600_000)
|
|
30
|
+
minutes, remainder = divmod(remainder, 60_000)
|
|
31
|
+
whole_seconds, milliseconds = divmod(remainder, 1000)
|
|
32
|
+
return f"{hours:02d}:{minutes:02d}:{whole_seconds:02d}.{milliseconds:03d}"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _copy_isolated_log(root: Path, name: str, destination: Path) -> None:
|
|
36
|
+
matches = list(root.rglob(name))
|
|
37
|
+
if len(matches) == 1:
|
|
38
|
+
shutil.copyfile(matches[0], destination)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def start_headless_pyghidra(install_dir: Path | str):
|
|
42
|
+
from pyghidra.launcher import HeadlessPyGhidraLauncher
|
|
43
|
+
|
|
44
|
+
launcher = HeadlessPyGhidraLauncher(install_dir=Path(install_dir))
|
|
45
|
+
launcher.add_vmargs("-Djava.awt.headless=true")
|
|
46
|
+
launcher.start()
|
|
47
|
+
return launcher
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _headless_worker(
|
|
51
|
+
install_dir: str,
|
|
52
|
+
arguments: tuple[str, ...],
|
|
53
|
+
log_path: str,
|
|
54
|
+
config_home: str,
|
|
55
|
+
cache_home: str,
|
|
56
|
+
errors: multiprocessing.Queue,
|
|
57
|
+
) -> None:
|
|
58
|
+
log = Path(log_path)
|
|
59
|
+
try:
|
|
60
|
+
os.environ["XDG_CONFIG_HOME"] = config_home
|
|
61
|
+
os.environ["XDG_CACHE_HOME"] = cache_home
|
|
62
|
+
with log.open("a", encoding="utf-8") as stream:
|
|
63
|
+
mirror = MirroredTextWriter(stream, sys.stdout)
|
|
64
|
+
mirror.write(f"PyGhidra process: {os.getpid()}\n")
|
|
65
|
+
with contextlib.redirect_stdout(mirror), contextlib.redirect_stderr(mirror):
|
|
66
|
+
launcher = start_headless_pyghidra(install_dir)
|
|
67
|
+
|
|
68
|
+
from ghidra.app.util.headless import AnalyzeHeadless
|
|
69
|
+
|
|
70
|
+
AnalyzeHeadless().launch(launcher._layout, list(arguments))
|
|
71
|
+
except BaseException:
|
|
72
|
+
errors.put(traceback.format_exc())
|
|
73
|
+
raise
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def run_headless(
|
|
77
|
+
install_dir: Path,
|
|
78
|
+
arguments: Sequence[str],
|
|
79
|
+
*,
|
|
80
|
+
log: Path,
|
|
81
|
+
dry_run: bool = False,
|
|
82
|
+
show: bool = False,
|
|
83
|
+
) -> HeadlessLogs:
|
|
84
|
+
if len(arguments) < 2:
|
|
85
|
+
raise ValueError("AnalyzeHeadless requires a project directory and project name")
|
|
86
|
+
script_log = log.with_name(f"{log.stem}-script{log.suffix}")
|
|
87
|
+
launcher_log = log.with_name(f"{log.stem}-launcher{log.suffix}")
|
|
88
|
+
complete_arguments = list(arguments)
|
|
89
|
+
rendered = "pyghidra AnalyzeHeadless " + display_command(complete_arguments)
|
|
90
|
+
if show or dry_run:
|
|
91
|
+
print(f"$ {rendered}")
|
|
92
|
+
if dry_run:
|
|
93
|
+
return HeadlessLogs(log, script_log, launcher_log, 0.0)
|
|
94
|
+
|
|
95
|
+
try:
|
|
96
|
+
import pyghidra # noqa: F401
|
|
97
|
+
except ImportError as error:
|
|
98
|
+
raise RuntimeError(
|
|
99
|
+
"PyGhidra is required; install this package with its dependencies"
|
|
100
|
+
) from error
|
|
101
|
+
|
|
102
|
+
launcher_log.parent.mkdir(parents=True, exist_ok=True)
|
|
103
|
+
launcher_log.write_text(f"$ {rendered}\n", encoding="utf-8")
|
|
104
|
+
|
|
105
|
+
with tempfile.TemporaryDirectory(prefix="il2cpp-ghidrah-ghidra-") as directory:
|
|
106
|
+
isolated = Path(directory)
|
|
107
|
+
config_home = isolated / "config"
|
|
108
|
+
cache_home = isolated / "cache"
|
|
109
|
+
config_home.mkdir()
|
|
110
|
+
cache_home.mkdir()
|
|
111
|
+
context = multiprocessing.get_context("spawn")
|
|
112
|
+
errors = context.Queue()
|
|
113
|
+
process = context.Process(
|
|
114
|
+
target=_headless_worker,
|
|
115
|
+
args=(
|
|
116
|
+
str(install_dir),
|
|
117
|
+
tuple(complete_arguments),
|
|
118
|
+
str(launcher_log),
|
|
119
|
+
str(config_home),
|
|
120
|
+
str(cache_home),
|
|
121
|
+
errors,
|
|
122
|
+
),
|
|
123
|
+
name="il2cpp-ghidrah-headless",
|
|
124
|
+
)
|
|
125
|
+
started = time.perf_counter()
|
|
126
|
+
process.start()
|
|
127
|
+
process.join()
|
|
128
|
+
elapsed_seconds = time.perf_counter() - started
|
|
129
|
+
_copy_isolated_log(config_home, "application.log", log)
|
|
130
|
+
_copy_isolated_log(config_home, "script.log", script_log)
|
|
131
|
+
if process.exitcode:
|
|
132
|
+
try:
|
|
133
|
+
detail = errors.get_nowait()
|
|
134
|
+
except queue.Empty:
|
|
135
|
+
detail = "no Python traceback was reported"
|
|
136
|
+
raise RuntimeError(
|
|
137
|
+
f"PyGhidra headless process failed with exit code {process.exitcode}; "
|
|
138
|
+
f"see {launcher_log}\n{detail}"
|
|
139
|
+
)
|
|
140
|
+
return HeadlessLogs(log, script_log, launcher_log, elapsed_seconds)
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import string
|
|
3
|
+
|
|
4
|
+
import ghidra
|
|
5
|
+
from ghidra.program.model.symbol import SourceType
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
PROCESS_FIELDS = {
|
|
9
|
+
"ScriptString",
|
|
10
|
+
"ScriptMetadata",
|
|
11
|
+
"ScriptMetadataMethod",
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
base_address = currentProgram.getImageBase()
|
|
15
|
+
user_defined = SourceType.USER_DEFINED
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def get_address(offset):
|
|
19
|
+
return base_address.add(offset)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def set_name(address, name):
|
|
23
|
+
createLabel(address, name.replace(" ", "-"), True, user_defined)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def escape_label_text(value):
|
|
27
|
+
escaped = []
|
|
28
|
+
for character in value:
|
|
29
|
+
if character == "\n":
|
|
30
|
+
escaped.append("\\n")
|
|
31
|
+
elif character == "\t":
|
|
32
|
+
escaped.append("\\t")
|
|
33
|
+
elif character == "\r":
|
|
34
|
+
escaped.append("\\r")
|
|
35
|
+
elif character in string.printable and character not in string.whitespace:
|
|
36
|
+
escaped.append(character)
|
|
37
|
+
else:
|
|
38
|
+
escaped.append("\\x{:02x}".format(ord(character)))
|
|
39
|
+
return "".join(escaped).replace(" ", "\\x20")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def rename_string_pointer(address, value):
|
|
43
|
+
name = "s_{}_{}".format(value[:1950] + "..." if len(value) >= 2000 else value, address)
|
|
44
|
+
symbol_table = currentProgram.getSymbolTable()
|
|
45
|
+
symbol = symbol_table.getPrimarySymbol(address)
|
|
46
|
+
try:
|
|
47
|
+
if symbol is None:
|
|
48
|
+
symbol_table.createLabel(address, name, user_defined)
|
|
49
|
+
else:
|
|
50
|
+
symbol.setName(name, user_defined)
|
|
51
|
+
except ghidra.util.exception.DuplicateNameException:
|
|
52
|
+
print("Duplicate string label at {}: {}".format(address, name))
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
script_args = getScriptArgs()
|
|
56
|
+
if not script_args:
|
|
57
|
+
raise ValueError("Missing script.json path")
|
|
58
|
+
|
|
59
|
+
with open(script_args[0], "r", encoding="utf-8") as input_file:
|
|
60
|
+
data = json.load(input_file)
|
|
61
|
+
|
|
62
|
+
if "ScriptString" in data and "ScriptString" in PROCESS_FIELDS:
|
|
63
|
+
script_strings = data["ScriptString"]
|
|
64
|
+
monitor.initialize(len(script_strings))
|
|
65
|
+
monitor.setMessage("Strings")
|
|
66
|
+
for index, script_string in enumerate(script_strings, 1):
|
|
67
|
+
address = get_address(script_string["Address"])
|
|
68
|
+
value = script_string["Value"]
|
|
69
|
+
createLabel(address, "StringLiteral_{}".format(index), True, user_defined)
|
|
70
|
+
setEOLComment(address, value)
|
|
71
|
+
rename_string_pointer(address, escape_label_text(value))
|
|
72
|
+
monitor.incrementProgress(1)
|
|
73
|
+
|
|
74
|
+
if "ScriptMetadata" in data and "ScriptMetadata" in PROCESS_FIELDS:
|
|
75
|
+
script_metadata = data["ScriptMetadata"]
|
|
76
|
+
monitor.initialize(len(script_metadata))
|
|
77
|
+
monitor.setMessage("Metadata")
|
|
78
|
+
for item in script_metadata:
|
|
79
|
+
address = get_address(item["Address"])
|
|
80
|
+
name = item["Name"]
|
|
81
|
+
set_name(address, name)
|
|
82
|
+
setEOLComment(address, name)
|
|
83
|
+
monitor.incrementProgress(1)
|
|
84
|
+
|
|
85
|
+
if "ScriptMetadataMethod" in data and "ScriptMetadataMethod" in PROCESS_FIELDS:
|
|
86
|
+
metadata_methods = data["ScriptMetadataMethod"]
|
|
87
|
+
monitor.initialize(len(metadata_methods))
|
|
88
|
+
monitor.setMessage("Metadata Methods")
|
|
89
|
+
for method in metadata_methods:
|
|
90
|
+
address = get_address(method["Address"])
|
|
91
|
+
name = method["Name"]
|
|
92
|
+
set_name(address, name)
|
|
93
|
+
setEOLComment(address, name)
|
|
94
|
+
monitor.incrementProgress(1)
|
|
95
|
+
|
|
96
|
+
print("Script finished!")
|