dexsect 4.1.0__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.
Files changed (74) hide show
  1. dexsect/__init__.py +4 -0
  2. dexsect/__main__.py +5 -0
  3. dexsect/catalog/EXTRACTION_CATALOG.json +4057 -0
  4. dexsect/catalog/__init__.py +0 -0
  5. dexsect/cli.py +1272 -0
  6. dexsect/core/__init__.py +0 -0
  7. dexsect/core/config.py +177 -0
  8. dexsect/core/context.py +181 -0
  9. dexsect/core/i18n.py +40 -0
  10. dexsect/core/pipeline.py +153 -0
  11. dexsect/core/platform_utils.py +164 -0
  12. dexsect/core/runner.py +124 -0
  13. dexsect/core/theme.py +64 -0
  14. dexsect/core/ui.py +405 -0
  15. dexsect/core/utils.py +150 -0
  16. dexsect/inspectors/__init__.py +0 -0
  17. dexsect/inspectors/assets_db_inspector.py +235 -0
  18. dexsect/inspectors/base.py +46 -0
  19. dexsect/inspectors/bundle_inspector.py +55 -0
  20. dexsect/inspectors/code_inspector.py +341 -0
  21. dexsect/inspectors/custom_rules_inspector.py +178 -0
  22. dexsect/inspectors/dex_inspector.py +144 -0
  23. dexsect/inspectors/manifest_inspector.py +503 -0
  24. dexsect/inspectors/native_fw_inspector.py +167 -0
  25. dexsect/inspectors/resources_inspector.py +195 -0
  26. dexsect/inspectors/scanner_inspector.py +153 -0
  27. dexsect/inspectors/signing_inspector.py +423 -0
  28. dexsect/inspectors/text_scanner.py +336 -0
  29. dexsect/locales/__init__.py +0 -0
  30. dexsect/locales/ar.json +130 -0
  31. dexsect/locales/de.json +51 -0
  32. dexsect/locales/en.json +110 -0
  33. dexsect/locales/es.json +51 -0
  34. dexsect/locales/fr.json +51 -0
  35. dexsect/locales/ja.json +51 -0
  36. dexsect/locales/pt.json +51 -0
  37. dexsect/locales/ru.json +51 -0
  38. dexsect/locales/tr.json +51 -0
  39. dexsect/locales/zh.json +51 -0
  40. dexsect/parsers/__init__.py +0 -0
  41. dexsect/parsers/axml.py +264 -0
  42. dexsect/parsers/bundle.py +214 -0
  43. dexsect/parsers/elf.py +396 -0
  44. dexsect/phases/__init__.py +0 -0
  45. dexsect/phases/base.py +102 -0
  46. dexsect/phases/decode.py +507 -0
  47. dexsect/phases/decompile.py +408 -0
  48. dexsect/phases/fingerprint.py +341 -0
  49. dexsect/phases/frameworks.py +377 -0
  50. dexsect/phases/mapper.py +41 -0
  51. dexsect/phases/native.py +188 -0
  52. dexsect/plugins/__init__.py +0 -0
  53. dexsect/plugins/base.py +20 -0
  54. dexsect/plugins/diff.py +162 -0
  55. dexsect/plugins/inspect.py +172 -0
  56. dexsect/plugins/report.py +80 -0
  57. dexsect/plugins/trace.py +141 -0
  58. dexsect/reporting/__init__.py +0 -0
  59. dexsect/reporting/analysis_report.py +1190 -0
  60. dexsect/reporting/diff_report.py +144 -0
  61. dexsect/reporting/sarif_report.py +109 -0
  62. dexsect/reporting/unpack_map.py +149 -0
  63. dexsect/rules/__init__.py +0 -0
  64. dexsect/rules/anti_analysis.json +45 -0
  65. dexsect/rules/crypto_audit.json +41 -0
  66. dexsect/rules/secrets_extended.json +46 -0
  67. dexsect/storage/__init__.py +0 -0
  68. dexsect/storage/findings_db.py +460 -0
  69. dexsect-4.1.0.dist-info/METADATA +532 -0
  70. dexsect-4.1.0.dist-info/RECORD +74 -0
  71. dexsect-4.1.0.dist-info/WHEEL +5 -0
  72. dexsect-4.1.0.dist-info/entry_points.txt +2 -0
  73. dexsect-4.1.0.dist-info/licenses/LICENSE +21 -0
  74. dexsect-4.1.0.dist-info/top_level.txt +1 -0
File without changes
dexsect/core/config.py ADDED
@@ -0,0 +1,177 @@
1
+ import json
2
+ import os
3
+ import shutil
4
+ import subprocess
5
+ from dataclasses import dataclass, field
6
+ from pathlib import Path
7
+ from typing import Any, Dict, List, Optional, Set
8
+
9
+ from .platform_utils import detect_os_family, get_config_dir
10
+
11
+
12
+ USER_CONFIG_PATH = get_config_dir() / "config.json"
13
+
14
+
15
+ @dataclass
16
+ class ToolInfo:
17
+ name: str
18
+ found: bool
19
+ path: str = ""
20
+ version: str = ""
21
+ required_for: str = ""
22
+ install_hint: str = ""
23
+
24
+
25
+ @dataclass
26
+ class RunConfig:
27
+ target_path: Path
28
+ output_dir: Path
29
+ only_phases: List[str] = field(default_factory=list)
30
+ skip_items: Set[str] = field(default_factory=set)
31
+ jobs: int = 2
32
+ jadx_jobs: int = 2
33
+ max_depth: int = 10
34
+ timeout_sec: int = 1800
35
+ java_xmx: Optional[str] = None
36
+ resume: bool = False
37
+ deobf: bool = False
38
+ jadx_with_res: bool = False
39
+ jadx_args: List[str] = field(default_factory=list)
40
+ all_so: bool = False
41
+ quiet: bool = False
42
+ no_color: bool = False
43
+ tools: Dict[str, ToolInfo] = field(default_factory=dict)
44
+ user_prefs: Dict[str, Any] = field(default_factory=dict)
45
+
46
+ def is_skipped(self, item: str) -> bool:
47
+ return item.lower() in self.skip_items
48
+
49
+
50
+ def load_user_config() -> Dict[str, Any]:
51
+ if not USER_CONFIG_PATH.is_file():
52
+ return {}
53
+ try:
54
+ data = json.loads(USER_CONFIG_PATH.read_text(encoding="utf-8", errors="replace"))
55
+ return data if isinstance(data, dict) else {}
56
+ except Exception:
57
+ return {}
58
+
59
+
60
+ def _probe_version(cmd: List[str]) -> str:
61
+ try:
62
+ proc = subprocess.run(
63
+ cmd,
64
+ stdout=subprocess.PIPE,
65
+ stderr=subprocess.STDOUT,
66
+ text=True,
67
+ errors="replace",
68
+ timeout=10,
69
+ )
70
+ lines = [ln.strip() for ln in proc.stdout.splitlines() if ln.strip()]
71
+ return lines[0] if lines else "Installed"
72
+ except Exception:
73
+ return "Installed"
74
+
75
+
76
+ def _os_hint(hints_by_os: Dict[str, str], os_fam: str) -> str:
77
+ return hints_by_os.get(os_fam) or hints_by_os.get("linux", "")
78
+
79
+
80
+ def discover_tools(user_prefs: Optional[Dict[str, Any]] = None) -> Dict[str, ToolInfo]:
81
+ prefs = user_prefs or {}
82
+ custom_paths = prefs.get("tool_paths", {}) if isinstance(prefs.get("tool_paths"), dict) else {}
83
+ os_fam = detect_os_family()
84
+
85
+ specs = [
86
+ ("java", ["java", "-version"], "decode, decompile", {
87
+ "termux": "pkg install openjdk-17",
88
+ "linux": "sudo apt install openjdk-17-jre",
89
+ "macos": "brew install openjdk@17",
90
+ "windows": "winget install EclipseAdoptium.Temurin.17.JDK",
91
+ }),
92
+ ("apktool", ["apktool", "--version"], "decode", {
93
+ "termux": "pkg install apktool",
94
+ "linux": "sudo apt install apktool (or official jar wrapper)",
95
+ "macos": "brew install apktool",
96
+ "windows": "scoop install apktool (or choco install apktool)",
97
+ }),
98
+ ("jadx", ["jadx", "--version"], "decompile", {
99
+ "termux": "pkg install jadx",
100
+ "linux": "Install jadx release from GitHub / apt",
101
+ "macos": "brew install jadx",
102
+ "windows": "scoop install jadx",
103
+ }),
104
+ ("hbc-decompiler", ["hbc-decompiler", "--help"], "frameworks (Hermes)", {
105
+ "linux": "pip install git+https://github.com/P1sec/hermes-dec.git",
106
+ }),
107
+ ("hbc-disassembler", ["hbc-disassembler", "--help"], "frameworks (Hermes)", {
108
+ "linux": "pip install git+https://github.com/P1sec/hermes-dec.git",
109
+ }),
110
+ ("hbctool", ["hbctool", "--help"], "frameworks (Hermes)", {
111
+ "linux": "pip install hbctool",
112
+ }),
113
+ ("js-beautify", ["js-beautify", "--version"], "frameworks (JS)", {
114
+ "linux": "pip install jsbeautifier",
115
+ }),
116
+ ("readelf", ["readelf", "--version"], "native (optional)", {
117
+ "termux": "pkg install binutils",
118
+ "linux": "sudo apt install binutils",
119
+ "macos": "brew install binutils",
120
+ "windows": "Optional (built-in ELF parser handles .so)",
121
+ }),
122
+ ("ilspycmd", ["ilspycmd", "--version"], "frameworks (.NET)", {
123
+ "linux": "dotnet tool install -g ilspycmd",
124
+ }),
125
+ ]
126
+
127
+ found_map: Dict[str, ToolInfo] = {}
128
+ for name, ver_cmd, req, hint_map in specs:
129
+ bin_path = custom_paths.get(name) or shutil.which(name)
130
+ if not bin_path and name == "hbc-decompiler":
131
+ bin_path = shutil.which("hermes-dec.hbc-decompiler")
132
+ hint = _os_hint(hint_map, os_fam)
133
+ if bin_path:
134
+ ver = (
135
+ _probe_version([bin_path] + ver_cmd[1:])
136
+ if name in ("java", "apktool", "jadx", "js-beautify", "readelf")
137
+ else "Installed"
138
+ )
139
+ found_map[name] = ToolInfo(name=name, found=True, path=bin_path, version=ver, required_for=req, install_hint=hint)
140
+ else:
141
+ found_map[name] = ToolInfo(name=name, found=False, required_for=req, install_hint=hint)
142
+
143
+ blutter_env = custom_paths.get("blutter") or os.environ.get("BLUTTER_PATH")
144
+ blutter_path = shutil.which("blutter")
145
+ if not blutter_path:
146
+ for cand in (
147
+ Path(blutter_env) if blutter_env else None,
148
+ Path.home() / "blutter" / "blutter.py",
149
+ Path.home() / "tools" / "blutter" / "blutter.py",
150
+ ):
151
+ if cand and cand.is_file():
152
+ blutter_path = str(cand)
153
+ break
154
+ found_map["blutter"] = ToolInfo(
155
+ name="blutter",
156
+ found=bool(blutter_path),
157
+ path=blutter_path or "",
158
+ version="Installed" if blutter_path else "",
159
+ required_for="frameworks (Flutter)",
160
+ install_hint="Clone blutter & set BLUTTER_PATH",
161
+ )
162
+
163
+ il2cpp_path = (
164
+ custom_paths.get("Il2CppDumper")
165
+ or os.environ.get("IL2CPPDUMPER_BIN")
166
+ or shutil.which("Il2CppDumper")
167
+ or shutil.which("il2cppdumper")
168
+ )
169
+ found_map["Il2CppDumper"] = ToolInfo(
170
+ name="Il2CppDumper",
171
+ found=bool(il2cpp_path),
172
+ path=il2cpp_path or "",
173
+ version="Installed" if il2cpp_path else "",
174
+ required_for="frameworks (Unity IL2CPP)",
175
+ install_hint="Set IL2CPPDUMPER_BIN or add to PATH",
176
+ )
177
+ return found_map
@@ -0,0 +1,181 @@
1
+ import json
2
+ import time
3
+ from dataclasses import asdict, dataclass, field
4
+ from pathlib import Path
5
+ from typing import Any, Callable, Dict, List, Optional
6
+
7
+ from .. import __version__
8
+ from .config import RunConfig
9
+ from .ui import TerminalDashboard
10
+
11
+
12
+ @dataclass
13
+ class ErrorRecord:
14
+ phase: str
15
+ target: str
16
+ message: str
17
+ exit_code: Optional[int] = None
18
+ log_file: str = ""
19
+ timestamp: str = field(default_factory=lambda: time.strftime("%Y-%m-%d %H:%M:%S"))
20
+
21
+
22
+ @dataclass
23
+ class ArtifactUnit:
24
+ unit_id: str
25
+ role: str # MAIN, SPLIT, EMBEDDED, STANDALONE
26
+ name: str
27
+ depth: int
28
+ sha256: str
29
+ source_path: str
30
+ decode_dir: str = ""
31
+ manifest_xml: str = ""
32
+ apktool_yml: str = ""
33
+ java_dir: str = ""
34
+ frameworks_dir: str = ""
35
+ native_dir: str = ""
36
+ abis: List[str] = field(default_factory=list)
37
+ frameworks: List[str] = field(default_factory=list)
38
+ primary_stack: str = ""
39
+ packer_hints: List[str] = field(default_factory=list)
40
+ custom_so_paths: List[str] = field(default_factory=list)
41
+ framework_so_paths: List[str] = field(default_factory=list)
42
+ framework_plan: List[Dict[str, Any]] = field(default_factory=list)
43
+ phase_status: Dict[str, str] = field(default_factory=dict)
44
+ metrics: Dict[str, Any] = field(default_factory=dict)
45
+
46
+
47
+ class WorkspaceState:
48
+ SCHEMA_VERSION = "3.0"
49
+
50
+ def __init__(self, root: Path, target_input: str = "", input_kind: str = "") -> None:
51
+ self.root = root
52
+ self.state_file = root / "workspace.json"
53
+ self.log_dir = root / "07_Logs"
54
+ self.task_log_dir = self.log_dir / "tasks"
55
+ self.inv_dir = root / "08_Inventory"
56
+ self.report_dir = root / "09_Reports"
57
+
58
+ self.session_log = self.log_dir / "session.log"
59
+ self.error_log = self.log_dir / "errors.log"
60
+ self.errors_json = self.log_dir / "errors.json"
61
+
62
+ self.data: Dict[str, Any] = {
63
+ "schema_version": self.SCHEMA_VERSION,
64
+ "dexsect_version": __version__,
65
+ "created_at": time.strftime("%Y-%m-%d %H:%M:%S"),
66
+ "updated_at": time.strftime("%Y-%m-%d %H:%M:%S"),
67
+ "workspace_root": str(root),
68
+ "target_input": target_input,
69
+ "input_kind": input_kind,
70
+ "phases": {},
71
+ "units": {}, # keyed by unit_id
72
+ "hash_index": {}, # sha256 -> unit_id
73
+ "errors": [],
74
+ "extensions": {}, # Reserved namespace for future inspect/report plugins
75
+ }
76
+
77
+ def init_dirs(self) -> None:
78
+ for d in (self.root, self.log_dir, self.task_log_dir, self.inv_dir, self.report_dir):
79
+ d.mkdir(parents=True, exist_ok=True)
80
+ self.session_log.touch(exist_ok=True)
81
+ self.error_log.touch(exist_ok=True)
82
+
83
+ def load(self) -> bool:
84
+ if not self.state_file.is_file():
85
+ return False
86
+ try:
87
+ loaded = json.loads(self.state_file.read_text(encoding="utf-8", errors="replace"))
88
+ if isinstance(loaded, dict):
89
+ self.data.update(loaded)
90
+ return True
91
+ except Exception:
92
+ return False
93
+ return False
94
+
95
+ def save(self) -> None:
96
+ self.data["updated_at"] = time.strftime("%Y-%m-%d %H:%M:%S")
97
+ tmp = self.state_file.with_suffix(".tmp")
98
+ tmp.write_text(json.dumps(self.data, indent=2, ensure_ascii=False), encoding="utf-8")
99
+ tmp.replace(self.state_file)
100
+ self.errors_json.write_text(
101
+ json.dumps(self.data.get("errors", []), indent=2, ensure_ascii=False),
102
+ encoding="utf-8",
103
+ )
104
+
105
+ def log(self, phase: str, msg: str) -> None:
106
+ ts = time.strftime("%Y-%m-%d %H:%M:%S")
107
+ with self.session_log.open("a", encoding="utf-8") as f:
108
+ f.write(f"[{ts}] [{phase}] {msg}\n")
109
+
110
+ def record_error(
111
+ self, phase: str, target: str, message: str, exit_code: Optional[int] = None, log_file: str = ""
112
+ ) -> None:
113
+ rec = ErrorRecord(
114
+ phase=phase,
115
+ target=target,
116
+ message=message,
117
+ exit_code=exit_code,
118
+ log_file=log_file,
119
+ )
120
+ self.data["errors"].append(asdict(rec))
121
+ with self.error_log.open("a", encoding="utf-8") as f:
122
+ f.write(f"[{rec.timestamp}] [{phase}] target={target} rc={exit_code} | {message} | log={log_file}\n")
123
+ self.log(phase, f"ERROR: {target} -> {message}")
124
+
125
+ def set_phase_summary(self, phase_name: str, summary: Dict[str, Any]) -> None:
126
+ self.data["phases"][phase_name] = summary
127
+ self.save()
128
+
129
+ def upsert_unit(self, unit: ArtifactUnit) -> None:
130
+ self.data["units"][unit.unit_id] = asdict(unit)
131
+ if unit.sha256:
132
+ self.data["hash_index"][unit.sha256] = unit.unit_id
133
+
134
+ def get_units(self) -> List[ArtifactUnit]:
135
+ out: List[ArtifactUnit] = []
136
+ for uid in sorted(self.data.get("units", {}).keys()):
137
+ out.append(ArtifactUnit(**self.data["units"][uid]))
138
+ return out
139
+
140
+ def next_unit_id(self) -> str:
141
+ existing = self.data.get("units", {})
142
+ if not existing:
143
+ return "0001"
144
+ nums = [int(k) for k in existing.keys() if k.isdigit()]
145
+ return f"{(max(nums) + 1) if nums else 1:04d}"
146
+
147
+
148
+ class PluginRegistry:
149
+ """Extensible registry for unpack phases and future inspect/report plugins."""
150
+
151
+ def __init__(self) -> None:
152
+ self._unpack_phases: Dict[str, Callable[..., Any]] = {}
153
+ self._extension_plugins: Dict[str, Callable[..., Any]] = {}
154
+
155
+ def register_phase(self, name: str, factory: Callable[..., Any]) -> None:
156
+ self._unpack_phases[name] = factory
157
+
158
+ def register_extension(self, name: str, factory: Callable[..., Any]) -> None:
159
+ self._extension_plugins[name] = factory
160
+
161
+ def get_phase(self, name: str) -> Optional[Callable[..., Any]]:
162
+ return self._unpack_phases.get(name)
163
+
164
+ def get_extension(self, name: str) -> Optional[Callable[..., Any]]:
165
+ return self._extension_plugins.get(name)
166
+
167
+ def list_phases(self) -> List[str]:
168
+ return list(self._unpack_phases.keys())
169
+
170
+ def list_extensions(self) -> List[str]:
171
+ return list(self._extension_plugins.keys())
172
+
173
+
174
+ class PipelineContext:
175
+ def __init__(self, cfg: RunConfig, state: WorkspaceState, ui: TerminalDashboard) -> None:
176
+ self.cfg = cfg
177
+ self.state = state
178
+ self.ui = ui
179
+ self.interrupted = False
180
+ self.overall_start = time.time()
181
+ self.runtime_cache: Dict[str, Any] = {}
dexsect/core/i18n.py ADDED
@@ -0,0 +1,40 @@
1
+ import json
2
+ from pathlib import Path
3
+ from typing import Any, Dict, List
4
+
5
+
6
+ BUILTIN_LOCALES_DIR = Path(__file__).resolve().parent.parent / "locales"
7
+ USER_LOCALES_DIR = Path.home() / ".config" / "dexsect" / "locales"
8
+
9
+
10
+ def available_locales() -> List[str]:
11
+ found = set()
12
+ for d in (BUILTIN_LOCALES_DIR, USER_LOCALES_DIR):
13
+ if d.is_dir():
14
+ for p in d.glob("*.json"):
15
+ found.add(p.stem.lower())
16
+ return sorted(found) or ["en"]
17
+
18
+
19
+ def load_locale(lang: str = "en") -> Dict[str, Any]:
20
+ lang_clean = (lang or "en").strip().lower()
21
+ en_data = json.loads((BUILTIN_LOCALES_DIR / "en.json").read_text(encoding="utf-8"))
22
+ if lang_clean == "en":
23
+ return en_data
24
+
25
+ for d in (USER_LOCALES_DIR, BUILTIN_LOCALES_DIR):
26
+ cand = d / f"{lang_clean}.json"
27
+ if cand.is_file():
28
+ try:
29
+ custom = json.loads(cand.read_text(encoding="utf-8"))
30
+ # Merge with English defaults so partial community translations never crash
31
+ merged = dict(en_data)
32
+ merged["lang"] = custom.get("lang", lang_clean)
33
+ merged["dir"] = custom.get("dir", en_data["dir"])
34
+ merged["name"] = custom.get("name", lang_clean)
35
+ for sec in ("ui", "kpis", "sections", "md"):
36
+ merged[sec] = {**en_data[sec], **custom.get(sec, {})}
37
+ return merged
38
+ except Exception:
39
+ pass
40
+ return en_data
@@ -0,0 +1,153 @@
1
+ import time
2
+ import zipfile
3
+ from pathlib import Path
4
+ from typing import Dict, List, Optional, Tuple
5
+
6
+ from .. import __version__
7
+ from ..phases.base import BasePhase, PhaseResult, bootstrap_external_target
8
+ from ..phases.decode import DecodePhase
9
+ from ..phases.decompile import DecompilePhase
10
+ from ..phases.fingerprint import FingerprintPhase
11
+ from ..phases.frameworks import FrameworksPhase
12
+ from ..phases.mapper import MapPhase
13
+ from ..phases.native import NativePhase
14
+ from .config import RunConfig
15
+ from .context import PipelineContext, PluginRegistry, WorkspaceState
16
+ from .runner import CommandRunner
17
+ from .ui import TerminalDashboard
18
+ from .utils import format_duration
19
+
20
+
21
+ UNPACK_PHASE_ORDER = ["decode", "decompile", "fingerprint", "frameworks", "native", "map"]
22
+
23
+
24
+ def build_default_registry() -> PluginRegistry:
25
+ reg = PluginRegistry()
26
+ reg.register_phase("decode", DecodePhase)
27
+ reg.register_phase("decompile", DecompilePhase)
28
+ reg.register_phase("fingerprint", FingerprintPhase)
29
+ reg.register_phase("frameworks", FrameworksPhase)
30
+ reg.register_phase("native", NativePhase)
31
+ reg.register_phase("map", MapPhase)
32
+ return reg
33
+
34
+
35
+ def detect_default_phases(target: Path, state: WorkspaceState) -> List[str]:
36
+ if (target / "workspace.json").is_file() and state.load():
37
+ # Existing workspace: run remaining or requested phases (default: fingerprint..map if already decoded)
38
+ if state.data.get("phases", {}).get("decode", {}).get("status") == "COMPLETED":
39
+ return ["decompile", "fingerprint", "frameworks", "native", "map"]
40
+ return list(UNPACK_PHASE_ORDER)
41
+
42
+ if target.is_dir():
43
+ is_apk_root = any(
44
+ (target / m).exists() for m in ("AndroidManifest.xml", "apktool.yml", "smali", "lib", "assets")
45
+ )
46
+ if is_apk_root:
47
+ return ["fingerprint", "frameworks", "native", "map"]
48
+ if any(target.rglob("*.apk")):
49
+ return ["decode", "decompile", "fingerprint", "frameworks", "native", "map"]
50
+ if any(target.rglob("*.dex")):
51
+ return ["decompile", "map"]
52
+ if any(target.rglob("*.so")):
53
+ return ["native", "map"]
54
+ return ["frameworks", "map"]
55
+
56
+ ext = target.suffix.lower()
57
+ name_low = target.name.lower()
58
+ if ext in (".apk", ".xapk", ".apks", ".apkm") or (ext == ".zip" and zipfile.is_zipfile(target)):
59
+ return list(UNPACK_PHASE_ORDER)
60
+ if ext == ".dex":
61
+ return ["decompile", "map"]
62
+ if name_low == "libapp.so":
63
+ return ["frameworks", "native", "map"]
64
+ if ext == ".so":
65
+ return ["native", "map"]
66
+ if name_low in ("index.android.bundle", "global-metadata.dat") or ext in (".bundle", ".hbc", ".dll"):
67
+ return ["frameworks", "map"]
68
+ return list(UNPACK_PHASE_ORDER)
69
+
70
+
71
+ def resolve_phases(cfg: RunConfig, target: Path, state: WorkspaceState) -> List[str]:
72
+ if cfg.only_phases:
73
+ selected = [p for p in cfg.only_phases if p in UNPACK_PHASE_ORDER]
74
+ else:
75
+ selected = detect_default_phases(target, state)
76
+
77
+ final_list = [p for p in selected if not cfg.is_skipped(p)]
78
+ # Ensure map runs at the end unless explicitly skipped or only single non-map requested with --no-map
79
+ if final_list and "map" not in final_list and not cfg.is_skipped("map") and not cfg.only_phases:
80
+ final_list.append("map")
81
+ return final_list
82
+
83
+
84
+ class PipelineEngine:
85
+ def __init__(self, registry: PluginRegistry) -> None:
86
+ self.registry = registry
87
+
88
+ def execute(
89
+ self,
90
+ cfg: RunConfig,
91
+ phase_names: List[str],
92
+ extra_stages: Optional[List[str]] = None,
93
+ shared_ui: Optional[TerminalDashboard] = None,
94
+ ) -> Tuple[int, WorkspaceState, Dict[str, PhaseResult]]:
95
+ state = WorkspaceState(root=cfg.output_dir, target_input=str(cfg.target_path))
96
+ state.init_dirs()
97
+ state.load()
98
+ if not state.data.get("target_input"):
99
+ state.data["target_input"] = str(cfg.target_path)
100
+
101
+ # Bootstrap external directory or standalone file if decode phase is not running first
102
+ if "decode" not in phase_names:
103
+ bootstrap_external_target(state, cfg.target_path)
104
+
105
+ ui = shared_ui or TerminalDashboard(version=__version__, quiet=cfg.quiet, no_color=cfg.no_color)
106
+ ui.set_pipeline_stages(list(phase_names) + list(extra_stages or []))
107
+ ui.set_meta(
108
+ input=cfg.target_path.name,
109
+ type=state.data.get("input_kind") or "AUTO",
110
+ output=str(cfg.output_dir),
111
+ jobs=str(cfg.jobs),
112
+ )
113
+
114
+ runner = CommandRunner(java_xmx=cfg.java_xmx, timeout_sec=cfg.timeout_sec)
115
+ ctx = PipelineContext(cfg=cfg, state=state, ui=ui)
116
+
117
+ def on_sig(signum: int) -> None:
118
+ ctx.interrupted = True
119
+ ui.push_event("ERR", f"Signal {signum} received, shutting down safely...")
120
+ state.log("pipeline", f"Interrupted by signal {signum}")
121
+
122
+ runner.install_signal_handlers(on_interrupt=on_sig)
123
+
124
+ results: Dict[str, PhaseResult] = {}
125
+ total_phases = len(phase_names)
126
+ exit_code = 0
127
+
128
+ owns_ui = not ui.started
129
+ if owns_ui:
130
+ ui.start()
131
+ try:
132
+ for idx, pname in enumerate(phase_names, start=1):
133
+ if runner.interrupted:
134
+ break
135
+ factory = self.registry.get_phase(pname)
136
+ if not factory:
137
+ continue
138
+ phase: BasePhase = factory()
139
+ res = phase.run(ctx, runner, f"{idx}/{total_phases}")
140
+ results[pname] = res
141
+ ui.finish_stage(pname, res.status, res.duration_sec)
142
+ if res.status == "INTERRUPTED":
143
+ exit_code = 130
144
+ break
145
+ if res.status == "FAILED" and pname == "decode":
146
+ exit_code = 1
147
+ break
148
+ finally:
149
+ state.save()
150
+ if owns_ui:
151
+ ui.stop()
152
+
153
+ return exit_code, state, results