il2cpp-ghidrah 0.1.5__tar.gz → 0.2.0__tar.gz

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.
Files changed (35) hide show
  1. il2cpp_ghidrah-0.2.0/CHANGELOG.md +13 -0
  2. il2cpp_ghidrah-0.2.0/MANIFEST.in +1 -0
  3. il2cpp_ghidrah-0.1.5/README.md → il2cpp_ghidrah-0.2.0/PKG-INFO +14 -11
  4. il2cpp_ghidrah-0.1.5/PKG-INFO → il2cpp_ghidrah-0.2.0/README.md +3 -23
  5. {il2cpp_ghidrah-0.1.5 → il2cpp_ghidrah-0.2.0}/pyproject.toml +3 -3
  6. {il2cpp_ghidrah-0.1.5 → il2cpp_ghidrah-0.2.0}/src/il2cpp_ghidrah/__init__.py +1 -1
  7. {il2cpp_ghidrah-0.1.5 → il2cpp_ghidrah-0.2.0}/src/il2cpp_ghidrah/cli.py +5 -1
  8. il2cpp_ghidrah-0.2.0/src/il2cpp_ghidrah/export_contract.py +142 -0
  9. il2cpp_ghidrah-0.2.0/src/il2cpp_ghidrah/ghidra_scripts/ImportIl2CppCParser.java +40 -0
  10. il2cpp_ghidrah-0.2.0/src/il2cpp_ghidrah/headless_manifest.py +155 -0
  11. il2cpp_ghidrah-0.2.0/src/il2cpp_ghidrah/headless_process.py +393 -0
  12. {il2cpp_ghidrah-0.1.5 → il2cpp_ghidrah-0.2.0}/src/il2cpp_ghidrah/installation.py +96 -19
  13. {il2cpp_ghidrah-0.1.5 → il2cpp_ghidrah-0.2.0}/src/il2cpp_ghidrah/pipeline.py +79 -70
  14. {il2cpp_ghidrah-0.1.5 → il2cpp_ghidrah-0.2.0}/src/il2cpp_ghidrah/process.py +8 -0
  15. {il2cpp_ghidrah-0.1.5 → il2cpp_ghidrah-0.2.0}/src/il2cpp_ghidrah.egg-info/PKG-INFO +4 -13
  16. {il2cpp_ghidrah-0.1.5 → il2cpp_ghidrah-0.2.0}/src/il2cpp_ghidrah.egg-info/SOURCES.txt +10 -6
  17. {il2cpp_ghidrah-0.1.5 → il2cpp_ghidrah-0.2.0}/tests/test_cli.py +87 -32
  18. il2cpp_ghidrah-0.2.0/tests/test_export_contract.py +107 -0
  19. il2cpp_ghidrah-0.2.0/tests/test_headless_manifest.py +195 -0
  20. il2cpp_ghidrah-0.2.0/tests/test_headless_process.py +350 -0
  21. il2cpp_ghidrah-0.1.5/src/il2cpp_ghidrah/ghidra.py +0 -140
  22. il2cpp_ghidrah-0.1.5/src/il2cpp_ghidrah/ghidra_scripts/ghidraUnityMetadata.py +0 -96
  23. il2cpp_ghidrah-0.1.5/src/il2cpp_ghidrah/ghidra_scripts/ghidra_with_struct_headless.py +0 -610
  24. il2cpp_ghidrah-0.1.5/src/il2cpp_ghidrah/ghidra_scripts/parse_header_headless.py +0 -214
  25. il2cpp_ghidrah-0.1.5/src/il2cpp_ghidrah.egg-info/requires.txt +0 -1
  26. {il2cpp_ghidrah-0.1.5 → il2cpp_ghidrah-0.2.0}/LICENSE +0 -0
  27. {il2cpp_ghidrah-0.1.5 → il2cpp_ghidrah-0.2.0}/setup.cfg +0 -0
  28. {il2cpp_ghidrah-0.1.5 → il2cpp_ghidrah-0.2.0}/src/il2cpp_ghidrah/__main__.py +0 -0
  29. {il2cpp_ghidrah-0.1.5 → il2cpp_ghidrah-0.2.0}/src/il2cpp_ghidrah/config.py +0 -0
  30. {il2cpp_ghidrah-0.1.5 → il2cpp_ghidrah-0.2.0}/src/il2cpp_ghidrah/generators.py +0 -0
  31. {il2cpp_ghidrah-0.1.5 → il2cpp_ghidrah-0.2.0}/src/il2cpp_ghidrah/inputs.py +0 -0
  32. {il2cpp_ghidrah-0.1.5 → il2cpp_ghidrah-0.2.0}/src/il2cpp_ghidrah/selection.py +0 -0
  33. {il2cpp_ghidrah-0.1.5 → il2cpp_ghidrah-0.2.0}/src/il2cpp_ghidrah.egg-info/dependency_links.txt +0 -0
  34. {il2cpp_ghidrah-0.1.5 → il2cpp_ghidrah-0.2.0}/src/il2cpp_ghidrah.egg-info/entry_points.txt +0 -0
  35. {il2cpp_ghidrah-0.1.5 → il2cpp_ghidrah-0.2.0}/src/il2cpp_ghidrah.egg-info/top_level.txt +0 -0
@@ -0,0 +1,13 @@
1
+ # Changelog
2
+
3
+ ## 0.2.0
4
+
5
+ - Replaced the embedded PyGhidra launcher with fixed `analyzeHeadless` Java entry points.
6
+ - Removed the installation dependency on TurboHeader's obsolete Python exporter.
7
+ - Added private typed request manifests for Ghidra import and export operations.
8
+ - Routed the TurboHeader and CParser importers through the same metadata, relocation, and export pipeline.
9
+ - Added live command output, retained logs, phase timings, and an eight-worker decompiler default.
10
+ - Added an optional `doctor --probe` check that starts Ghidra and verifies the selected importer.
11
+ - Hardened archive handling, path validation, process environments, and export verification.
12
+
13
+ This release requires TurboHeader 1.3.9 or newer.
@@ -0,0 +1 @@
1
+ include CHANGELOG.md
@@ -1,3 +1,14 @@
1
+ Metadata-Version: 2.4
2
+ Name: il2cpp-ghidrah
3
+ Version: 0.2.0
4
+ Summary: Headless Ghidra pipeline for Unity IL2CPP applications
5
+ Author: il2cpp-ghidrah contributors
6
+ License: MIT
7
+ Requires-Python: >=3.9
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Dynamic: license-file
11
+
1
12
  # il2cpp-ghidrah
2
13
 
3
14
  `il2cpp-ghidrah` builds a typed Ghidra project from a Unity IL2CPP application and exports selected classes as C++. Everything runs headlessly; the Ghidra GUI is not opened.
@@ -5,9 +16,8 @@
5
16
  ## Requirements
6
17
 
7
18
  - Python 3.9 or newer.
8
- - PyGhidra 3.1 or newer.
9
19
  - Ghidra 12 or newer.
10
- - [TurboHeader](https://github.com/TeamRocketIst/turboHeader) installed under Ghidra's `Ghidra/Extensions` directory.
20
+ - [TurboHeader](https://github.com/TeamRocketIst/turboHeader) 1.3.9 or newer, installed under Ghidra's `Ghidra/Extensions` directory.
11
21
  - `Il2CppDumper` and `Cpp2IL`.
12
22
 
13
23
  Generator commands must be available through `PATH`, unless an explicit executable is supplied with the corresponding command option.
@@ -40,13 +50,6 @@ python -m pip install .
40
50
  il2cpp-ghidrah doctor --probe
41
51
  ```
42
52
 
43
- For an offline installation, activate `.venv` and use the PyGhidra wheels included with Ghidra:
44
-
45
- ```sh
46
- python -m pip install --no-index \
47
- -f "$GHIDRA_INSTALL_DIR/Ghidra/Features/PyGhidra/pypkg/dist" .
48
- ```
49
-
50
53
  For development:
51
54
 
52
55
  ```sh
@@ -87,13 +90,13 @@ Il2CppDumper creates the header and metadata artifacts, while Cpp2IL creates the
87
90
  il2cpp-ghidrah run game.apk -o out -g dumper --importer turbo -u "$UNITY_VERSION"
88
91
  ```
89
92
 
90
- The compatibility importer uses the bundled CParserUtils scripts:
93
+ The compatibility importer uses Ghidra's CParser through a fixed Java script:
91
94
 
92
95
  ```sh
93
96
  il2cpp-ghidrah run game.apk -o out -g dumper --importer cparser -u "$UNITY_VERSION"
94
97
  ```
95
98
 
96
- That flow runs `parse_header_headless.py`, `ghidra_with_struct_headless.py`, and `ghidraUnityMetadata.py`. It imports the header, method signatures, and basic metadata labels, but it does not currently provide TurboHeader's authoritative layouts or complete GOT typing. TurboHeader is still required for the exporter.
99
+ It shares TurboHeader's method, string, metadata, relocation and export stages. CParser infers layouts from `il2cpp.h` and does not consume external field offsets, so the native importer remains recommended.
97
100
 
98
101
  TurboHeader layout policies are:
99
102
 
@@ -1,15 +1,3 @@
1
- Metadata-Version: 2.4
2
- Name: il2cpp-ghidrah
3
- Version: 0.1.5
4
- Summary: Headless Ghidra pipeline for Unity IL2CPP applications
5
- Author: il2cpp-ghidrah contributors
6
- License: MIT
7
- Requires-Python: >=3.9
8
- Description-Content-Type: text/markdown
9
- License-File: LICENSE
10
- Requires-Dist: pyghidra<4,>=3.1
11
- Dynamic: license-file
12
-
13
1
  # il2cpp-ghidrah
14
2
 
15
3
  `il2cpp-ghidrah` builds a typed Ghidra project from a Unity IL2CPP application and exports selected classes as C++. Everything runs headlessly; the Ghidra GUI is not opened.
@@ -17,9 +5,8 @@ Dynamic: license-file
17
5
  ## Requirements
18
6
 
19
7
  - Python 3.9 or newer.
20
- - PyGhidra 3.1 or newer.
21
8
  - Ghidra 12 or newer.
22
- - [TurboHeader](https://github.com/TeamRocketIst/turboHeader) installed under Ghidra's `Ghidra/Extensions` directory.
9
+ - [TurboHeader](https://github.com/TeamRocketIst/turboHeader) 1.3.9 or newer, installed under Ghidra's `Ghidra/Extensions` directory.
23
10
  - `Il2CppDumper` and `Cpp2IL`.
24
11
 
25
12
  Generator commands must be available through `PATH`, unless an explicit executable is supplied with the corresponding command option.
@@ -52,13 +39,6 @@ python -m pip install .
52
39
  il2cpp-ghidrah doctor --probe
53
40
  ```
54
41
 
55
- For an offline installation, activate `.venv` and use the PyGhidra wheels included with Ghidra:
56
-
57
- ```sh
58
- python -m pip install --no-index \
59
- -f "$GHIDRA_INSTALL_DIR/Ghidra/Features/PyGhidra/pypkg/dist" .
60
- ```
61
-
62
42
  For development:
63
43
 
64
44
  ```sh
@@ -99,13 +79,13 @@ Il2CppDumper creates the header and metadata artifacts, while Cpp2IL creates the
99
79
  il2cpp-ghidrah run game.apk -o out -g dumper --importer turbo -u "$UNITY_VERSION"
100
80
  ```
101
81
 
102
- The compatibility importer uses the bundled CParserUtils scripts:
82
+ The compatibility importer uses Ghidra's CParser through a fixed Java script:
103
83
 
104
84
  ```sh
105
85
  il2cpp-ghidrah run game.apk -o out -g dumper --importer cparser -u "$UNITY_VERSION"
106
86
  ```
107
87
 
108
- That flow runs `parse_header_headless.py`, `ghidra_with_struct_headless.py`, and `ghidraUnityMetadata.py`. It imports the header, method signatures, and basic metadata labels, but it does not currently provide TurboHeader's authoritative layouts or complete GOT typing. TurboHeader is still required for the exporter.
88
+ It shares TurboHeader's method, string, metadata, relocation and export stages. CParser infers layouts from `il2cpp.h` and does not consume external field offsets, so the native importer remains recommended.
109
89
 
110
90
  TurboHeader layout policies are:
111
91
 
@@ -4,13 +4,13 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "il2cpp-ghidrah"
7
- version = "0.1.5"
7
+ version = "0.2.0"
8
8
  description = "Headless Ghidra pipeline for Unity IL2CPP applications"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.9"
11
11
  license = { text = "MIT" }
12
12
  authors = [{ name = "il2cpp-ghidrah contributors" }]
13
- dependencies = ["pyghidra>=3.1,<4"]
13
+ dependencies = []
14
14
 
15
15
  [project.scripts]
16
16
  il2cpp-ghidrah = "il2cpp_ghidrah.cli:main"
@@ -19,7 +19,7 @@ il2cpp-ghidrah = "il2cpp_ghidrah.cli:main"
19
19
  where = ["src"]
20
20
 
21
21
  [tool.setuptools.package-data]
22
- il2cpp_ghidrah = ["ghidra_scripts/*.py"]
22
+ il2cpp_ghidrah = ["ghidra_scripts/*.java"]
23
23
 
24
24
  [tool.pytest.ini_options]
25
25
  testpaths = ["tests"]
@@ -1,3 +1,3 @@
1
1
  """Headless Unity IL2CPP to Ghidra pipeline."""
2
2
 
3
- __version__ = "0.1.5"
3
+ __version__ = "0.2.0"
@@ -74,7 +74,11 @@ def parser() -> argparse.ArgumentParser:
74
74
  doctor_parser = commands.add_parser("doctor", help="verify the headless toolchain installation")
75
75
  doctor_parser.add_argument("-g", "--generator", choices=("auto", "aotopsy", "dumper"), default="auto")
76
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")
77
+ doctor_parser.add_argument(
78
+ "--probe",
79
+ action="store_true",
80
+ help="run a temporary analyzeHeadless importer check",
81
+ )
78
82
  doctor_parser.add_argument("--json", action="store_true", dest="json_output")
79
83
  _common_tools(doctor_parser)
80
84
  return root
@@ -0,0 +1,142 @@
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import os
5
+ import re
6
+ from dataclasses import dataclass
7
+ from pathlib import Path
8
+ from typing import Dict, Iterable, Tuple
9
+
10
+
11
+ SUMMARY_FIELDS = (
12
+ "Assemblies included",
13
+ "Assemblies skipped",
14
+ "Classes selected",
15
+ "Class files written",
16
+ "Functions scanned",
17
+ "Functions matched/exported",
18
+ "Functions failed to decompile",
19
+ "Functions recovered after restart",
20
+ "Ambiguous functions skipped",
21
+ "Assembly ambiguities resolved",
22
+ "Assembly mismatches skipped",
23
+ "Classes with no matches",
24
+ )
25
+
26
+ DIAGNOSTIC_FILES = (
27
+ "_ambiguous_matches.txt",
28
+ "_assembly_filter.txt",
29
+ "_classes_with_no_matches.txt",
30
+ )
31
+
32
+ _SUMMARY_LINE = re.compile(r"^([^:\n]+):\s*(\d+)\s*$", re.MULTILINE)
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class ExportFile:
37
+ path: str
38
+ size: int
39
+ sha256: str
40
+
41
+
42
+ @dataclass(frozen=True)
43
+ class ExportSnapshot:
44
+ summary: Tuple[Tuple[str, int], ...]
45
+ files: Tuple[ExportFile, ...]
46
+
47
+
48
+ @dataclass(frozen=True)
49
+ class ExportComparison:
50
+ differences: Tuple[str, ...]
51
+
52
+ @property
53
+ def equal(self) -> bool:
54
+ return not self.differences
55
+
56
+
57
+ def _regular_files(root: Path) -> Iterable[Path]:
58
+ for directory, names, filenames in os.walk(root, followlinks=False):
59
+ directory_path = Path(directory)
60
+ for name in names:
61
+ path = directory_path / name
62
+ if path.is_symlink():
63
+ raise ValueError(f"export contains a directory symlink: {path}")
64
+ for name in filenames:
65
+ path = directory_path / name
66
+ if path.is_symlink():
67
+ raise ValueError(f"export contains a file symlink: {path}")
68
+ if not path.is_file():
69
+ raise ValueError(f"export contains a non-regular file: {path}")
70
+ yield path
71
+
72
+
73
+ def _sha256(path: Path) -> str:
74
+ digest = hashlib.sha256()
75
+ with path.open("rb") as stream:
76
+ while True:
77
+ block = stream.read(1024 * 1024)
78
+ if not block:
79
+ return digest.hexdigest()
80
+ digest.update(block)
81
+
82
+
83
+ def _parse_summary(path: Path) -> Tuple[Tuple[str, int], ...]:
84
+ if not path.is_file() or path.is_symlink():
85
+ raise ValueError(f"export summary is missing or unsafe: {path}")
86
+ values = {
87
+ name.strip(): int(value)
88
+ for name, value in _SUMMARY_LINE.findall(
89
+ path.read_text(encoding="utf-8", errors="strict")
90
+ )
91
+ }
92
+ missing = [name for name in SUMMARY_FIELDS if name not in values]
93
+ if missing:
94
+ raise ValueError("export summary is missing: " + ", ".join(missing))
95
+ return tuple((name, values[name]) for name in SUMMARY_FIELDS)
96
+
97
+
98
+ def capture_export(directory: Path) -> ExportSnapshot:
99
+ root = directory.expanduser().resolve(strict=True)
100
+ if not root.is_dir():
101
+ raise ValueError(f"export root is not a directory: {root}")
102
+
103
+ summary = _parse_summary(root / "_export_summary.txt")
104
+ included = set(DIAGNOSTIC_FILES)
105
+ files = []
106
+ for path in _regular_files(root):
107
+ relative = path.relative_to(root).as_posix()
108
+ if path.suffix == ".cpp" or relative in included:
109
+ files.append(ExportFile(relative, path.stat().st_size, _sha256(path)))
110
+ files.sort(key=lambda item: item.path)
111
+ return ExportSnapshot(summary, tuple(files))
112
+
113
+
114
+ def compare_exports(reference: Path, candidate: Path) -> ExportComparison:
115
+ expected = capture_export(reference)
116
+ actual = capture_export(candidate)
117
+ differences = []
118
+
119
+ expected_summary = dict(expected.summary)
120
+ actual_summary = dict(actual.summary)
121
+ for name in SUMMARY_FIELDS:
122
+ if expected_summary[name] != actual_summary[name]:
123
+ differences.append(
124
+ f"summary {name}: expected {expected_summary[name]}, "
125
+ f"found {actual_summary[name]}"
126
+ )
127
+
128
+ expected_files: Dict[str, ExportFile] = {item.path: item for item in expected.files}
129
+ actual_files: Dict[str, ExportFile] = {item.path: item for item in actual.files}
130
+ for path in sorted(expected_files.keys() - actual_files.keys()):
131
+ differences.append(f"missing file: {path}")
132
+ for path in sorted(actual_files.keys() - expected_files.keys()):
133
+ differences.append(f"unexpected file: {path}")
134
+ for path in sorted(expected_files.keys() & actual_files.keys()):
135
+ expected_file = expected_files[path]
136
+ actual_file = actual_files[path]
137
+ if expected_file.sha256 != actual_file.sha256:
138
+ differences.append(
139
+ f"changed file: {path} "
140
+ f"({expected_file.size} bytes -> {actual_file.size} bytes)"
141
+ )
142
+ return ExportComparison(tuple(differences))
@@ -0,0 +1,40 @@
1
+ // Imports IL2CPP C types with Ghidra's CParser and applies managed metadata.
2
+ // @category Data Types
3
+
4
+ import java.nio.file.Path;
5
+
6
+ import ghidra.app.script.GhidraScript;
7
+ import turboheader.il2cpp.GhidraCParserTypeImportStrategy;
8
+ import turboheader.il2cpp.HeadlessRequestReader;
9
+ import turboheader.il2cpp.Il2CppLayoutPolicy;
10
+ import turboheader.il2cpp.Il2CppMetadataImportService;
11
+
12
+ public class ImportIl2CppCParser extends GhidraScript {
13
+ @Override
14
+ protected void run() throws Exception {
15
+ if (currentProgram == null) {
16
+ throw new IllegalStateException("Open a program before importing IL2CPP types");
17
+ }
18
+
19
+ String[] args = getScriptArgs();
20
+ if (args.length != 2 || !args[0].equals("--request")) {
21
+ throw new IllegalArgumentException(
22
+ "Expected: --request <import-request.json>");
23
+ }
24
+
25
+ var request = HeadlessRequestReader.readImport(Path.of(args[1]));
26
+ if (request.offsets() != null ||
27
+ request.layoutPolicy() != HeadlessRequestReader.LayoutPolicy.ALLOW_INFERRED) {
28
+ throw new IllegalArgumentException(
29
+ "Ghidra CParser requires allow-inferred layout without external offsets");
30
+ }
31
+
32
+ new GhidraCParserTypeImportStrategy(currentProgram, monitor, this::println)
33
+ .importTypes(request.header(), null, currentProgram.getDefaultPointerSize(),
34
+ Il2CppLayoutPolicy.ALLOW_INFERRED);
35
+ if (request.methods() != null) {
36
+ new Il2CppMetadataImportService(currentProgram, monitor, this::println, this::printerr)
37
+ .importScript(request.methods());
38
+ }
39
+ }
40
+ }
@@ -0,0 +1,155 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import os
5
+ import tempfile
6
+ from dataclasses import dataclass
7
+ from pathlib import Path
8
+ from typing import Optional
9
+
10
+
11
+ MAX_MANIFEST_BYTES = 1024 * 1024
12
+ LAYOUT_POLICIES = frozenset((
13
+ "allow-inferred",
14
+ "require-external-offsets",
15
+ "require-authoritative",
16
+ ))
17
+ EXPORT_SCOPES = frozenset(("whitelist", "blacklist", "all"))
18
+ MAX_DECOMPILE_JOBS = 12
19
+
20
+
21
+ def _input_file(path: Path, description: str) -> str:
22
+ expanded = path.expanduser()
23
+ if expanded.is_symlink():
24
+ raise ValueError(f"{description} must not be a symlink: {expanded}")
25
+ resolved = expanded.resolve(strict=True)
26
+ if not resolved.is_file():
27
+ raise ValueError(f"{description} is not a regular file: {resolved}")
28
+ return str(resolved)
29
+
30
+
31
+ def _input_directory(path: Path, description: str) -> str:
32
+ expanded = path.expanduser()
33
+ if expanded.is_symlink():
34
+ raise ValueError(f"{description} must not be a symlink: {expanded}")
35
+ resolved = expanded.resolve(strict=True)
36
+ if not resolved.is_dir():
37
+ raise ValueError(f"{description} is not a directory: {resolved}")
38
+ return str(resolved)
39
+
40
+
41
+ def _output_directory(path: Path) -> str:
42
+ expanded = path.expanduser()
43
+ if expanded.is_symlink():
44
+ raise ValueError(f"export directory must not be a symlink: {expanded}")
45
+ if expanded.exists():
46
+ resolved = expanded.resolve(strict=True)
47
+ if not resolved.is_dir():
48
+ raise ValueError(f"export path is not a directory: {resolved}")
49
+ return str(resolved)
50
+
51
+ parent = expanded.parent.resolve(strict=True)
52
+ if not parent.is_dir():
53
+ raise ValueError(f"export parent is not a directory: {parent}")
54
+ return str(parent / expanded.name)
55
+
56
+
57
+ @dataclass(frozen=True)
58
+ class ImportManifest:
59
+ header: Path
60
+ offsets: Optional[Path]
61
+ methods: Optional[Path]
62
+ layout_policy: str
63
+
64
+ def document(self) -> dict:
65
+ if self.layout_policy not in LAYOUT_POLICIES:
66
+ raise ValueError(f"unsupported layout policy: {self.layout_policy}")
67
+ return {
68
+ "schema": 1,
69
+ "operation": "import",
70
+ "header": _input_file(self.header, "IL2CPP header"),
71
+ "offsets": (
72
+ _input_file(self.offsets, "IL2CPP offset data")
73
+ if self.offsets is not None
74
+ else None
75
+ ),
76
+ "methods": (
77
+ _input_file(self.methods, "IL2CPP method data")
78
+ if self.methods is not None
79
+ else None
80
+ ),
81
+ "layoutPolicy": self.layout_policy,
82
+ }
83
+
84
+
85
+ @dataclass(frozen=True)
86
+ class ExportManifest:
87
+ class_source: Path
88
+ output: Path
89
+ scope: str
90
+ framework_rules: Optional[Path]
91
+ noreturn_seeds: Optional[Path]
92
+ decompile_jobs: int
93
+
94
+ def document(self) -> dict:
95
+ if self.scope not in EXPORT_SCOPES:
96
+ raise ValueError(f"unsupported export scope: {self.scope}")
97
+ if not 0 <= self.decompile_jobs <= MAX_DECOMPILE_JOBS:
98
+ raise ValueError("decompile jobs must be between 0 and 12")
99
+ return {
100
+ "schema": 1,
101
+ "operation": "export",
102
+ "classSource": _input_directory(self.class_source, "class source"),
103
+ "output": _output_directory(self.output),
104
+ "scope": self.scope,
105
+ "frameworkRules": (
106
+ _input_file(self.framework_rules, "framework rules")
107
+ if self.framework_rules is not None
108
+ else None
109
+ ),
110
+ "noreturnSeeds": (
111
+ _input_file(self.noreturn_seeds, "non-return seeds")
112
+ if self.noreturn_seeds is not None
113
+ else None
114
+ ),
115
+ "decompileJobs": self.decompile_jobs,
116
+ }
117
+
118
+
119
+ def _write_manifest(directory: Path, prefix: str, document: dict) -> Path:
120
+ root = directory.expanduser()
121
+ if root.is_symlink():
122
+ raise ValueError(f"manifest directory must not be a symlink: {root}")
123
+ root = root.resolve(strict=True)
124
+ if not root.is_dir():
125
+ raise ValueError(f"manifest directory is not a directory: {root}")
126
+ if os.name == "posix" and root.stat().st_mode & 0o077:
127
+ raise ValueError(f"manifest directory must be private: {root}")
128
+
129
+ contents = json.dumps(
130
+ document, ensure_ascii=False, separators=(",", ":")
131
+ ).encode("utf-8")
132
+ if len(contents) > MAX_MANIFEST_BYTES:
133
+ raise ValueError("headless request manifest exceeds 1 MiB")
134
+
135
+ descriptor, name = tempfile.mkstemp(prefix=prefix, suffix=".json", dir=root)
136
+ path = Path(name)
137
+ try:
138
+ with os.fdopen(descriptor, "wb") as stream:
139
+ stream.write(contents)
140
+ except BaseException:
141
+ try:
142
+ os.close(descriptor)
143
+ except OSError:
144
+ pass
145
+ path.unlink(missing_ok=True)
146
+ raise
147
+ return path
148
+
149
+
150
+ def write_import_manifest(directory: Path, request: ImportManifest) -> Path:
151
+ return _write_manifest(directory, "import-", request.document())
152
+
153
+
154
+ def write_export_manifest(directory: Path, request: ExportManifest) -> Path:
155
+ return _write_manifest(directory, "export-", request.document())