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
dexsect/cli.py ADDED
@@ -0,0 +1,1272 @@
1
+ import argparse
2
+ import json
3
+ import os
4
+ import re
5
+ import shlex
6
+ import shutil
7
+ import sys
8
+ import tarfile
9
+ import time
10
+ import zipfile
11
+ from pathlib import Path
12
+ from typing import Any, Dict, List, Optional
13
+
14
+ from . import __version__
15
+ from .core.config import USER_CONFIG_PATH, RunConfig, discover_tools, load_user_config
16
+ from .core.context import PipelineContext, WorkspaceState
17
+ from .core.i18n import available_locales
18
+ from .core.pipeline import UNPACK_PHASE_ORDER, PipelineEngine, build_default_registry, resolve_phases
19
+ from .core.platform_utils import RunsRegistry, detect_os_family, get_config_dir
20
+ from .core.ui import Colors, TerminalDashboard
21
+ from .core.utils import format_duration, safe_slug
22
+ from .inspectors.custom_rules_inspector import resolve_rule_tokens
23
+ from .parsers.axml import decode_axml_file, is_binary_axml
24
+ from .parsers.bundle import peek_package_identity
25
+ from .phases.base import bootstrap_external_target
26
+ from .plugins.diff import DiffPlugin, format_diff_output
27
+ from .plugins.inspect import InspectPlugin
28
+ from .plugins.report import ReportPlugin
29
+ from .plugins.trace import TracePlugin, format_trace_output
30
+ from .storage.findings_db import FindingsDB, format_findings_output
31
+
32
+
33
+ SUBCOMMANDS = {
34
+ "unpack", "run", "decode", "decompile",
35
+ "fingerprint", "framework", "native", "map", "doctor",
36
+ "inspect", "query", "search", "report", "catalog",
37
+ "help", "runs", "diff", "trace", "explain", "pack",
38
+ }
39
+
40
+ VALUE_FLAGS = {
41
+ "-o", "--output", "--only", "--skip", "-j", "--jobs",
42
+ "--jadx-jobs", "-d", "--max-depth", "--java-xmx",
43
+ "--profile", "--unit", "--id", "--domain", "--layer",
44
+ "--match", "--regex", "--format", "--limit", "--lang",
45
+ "--timeout", "--scope", "--rules", "--jadx-args", "--confidence",
46
+ }
47
+
48
+ SEQ_DIR_RE = re.compile(r"^(\d+)_")
49
+
50
+
51
+ def _find_first_positional(argv: List[str]) -> Optional[str]:
52
+ i = 0
53
+ while i < len(argv):
54
+ tok = argv[i]
55
+ if tok == "--":
56
+ return argv[i + 1] if i + 1 < len(argv) else None
57
+ if tok in VALUE_FLAGS:
58
+ i += 2
59
+ continue
60
+ if any(tok.startswith(f + "=") for f in VALUE_FLAGS if f.startswith("--")):
61
+ i += 1
62
+ continue
63
+ if tok.startswith("-"):
64
+ i += 1
65
+ continue
66
+ return tok
67
+ return None
68
+
69
+
70
+ def _get_runs_root(prefs: Dict[str, Any]) -> Path:
71
+ custom = prefs.get("runs_dir")
72
+ if custom:
73
+ return Path(str(custom)).expanduser().resolve()
74
+ cwd = Path.cwd()
75
+ if cwd.name == "dexsect_runs":
76
+ return cwd
77
+ return cwd / "dexsect_runs"
78
+
79
+
80
+ def _build_numbered_run_dir(target: Path, runs_root: Path) -> Path:
81
+ max_seq = 0
82
+ if runs_root.is_dir():
83
+ for entry in runs_root.iterdir():
84
+ if entry.is_dir():
85
+ m = SEQ_DIR_RE.match(entry.name)
86
+ if m:
87
+ max_seq = max(max_seq, int(m.group(1)))
88
+ seq = max_seq + 1
89
+ date_str = time.strftime("%Y%m%d")
90
+
91
+ pkg, ver = peek_package_identity(target)
92
+ pkg_slug = safe_slug(pkg, max_len=64, fallback=safe_slug(target.stem))
93
+ ver_slug = safe_slug(ver, max_len=24, fallback="") if ver else ""
94
+ folder_name = f"{seq:02d}_{pkg_slug}_{ver_slug}-{date_str}" if ver_slug else f"{seq:02d}_{pkg_slug}-{date_str}"
95
+ return runs_root / folder_name
96
+
97
+
98
+ def _resolve_target_shortcut(raw_target: str, runs_root: Path) -> Path:
99
+ p = Path(raw_target).expanduser()
100
+ if p.exists():
101
+ return p.resolve()
102
+ found = RunsRegistry().resolve_shortcut(raw_target, runs_root)
103
+ if found:
104
+ return found
105
+ return p.resolve()
106
+
107
+
108
+ def _short_path(path: Path, base: Optional[Path] = None) -> str:
109
+ try:
110
+ return str(path.relative_to(base or Path.cwd()))
111
+ except ValueError:
112
+ return str(path)
113
+
114
+
115
+ def _add_common_flags(p: argparse.ArgumentParser) -> None:
116
+ p.add_argument("-o", "--output", default=None, help="Custom output workspace directory (bypasses auto-numbering)")
117
+ p.add_argument("-j", "--jobs", type=int, default=None, choices=range(1, 9), metavar="1-8", help="Apktool parallel jobs [default: 2]")
118
+ p.add_argument("--jadx-jobs", type=int, default=None, choices=range(1, 9), metavar="1-8", help="JADX decompiler threads [default: 2]")
119
+ p.add_argument("-d", "--max-depth", type=int, default=None, help="Max embedded APK recursion depth [default: 10]")
120
+ p.add_argument("--java-xmx", default=None, help="JVM max heap size for Apktool/JADX (e.g. 1536m, 2g)")
121
+ p.add_argument("--timeout", type=int, default=None, help="Per-tool timeout in seconds [default: 1800]")
122
+ p.add_argument("--resume", action="store_true", help="Resume an existing interrupted workspace")
123
+ p.add_argument("--deobf", action="store_true", help="Enable JADX deobfuscation (--deobf)")
124
+ p.add_argument("--jadx-with-res", action="store_true", help="Also decode resources inside JADX")
125
+ p.add_argument("--jadx-args", default="", help="Extra arguments passed directly to JADX (quoted string)")
126
+ p.add_argument("--all-so", action="store_true", help="Inspect framework .so libs in addition to custom .so libs")
127
+ p.add_argument("--low-mem", action="store_true", help="Low-memory preset (jobs=1, java-xmx=1024m, skip lang-splits/so-strings)")
128
+ p.add_argument("--quiet", "-q", action="store_true", help="Suppress interactive terminal dashboard")
129
+ p.add_argument("--no-color", action="store_true", help="Disable ANSI colors")
130
+
131
+
132
+ def build_parser() -> argparse.ArgumentParser:
133
+ locs = ", ".join(available_locales())
134
+ top_epilog = f"""
135
+ ========================================================================
136
+ HOW DEXSECT WORKS (DEFAULT BEHAVIOR & WORKSPACES)
137
+ ========================================================================
138
+ 1. Default Unpack:
139
+ dexsect app.apk
140
+ Auto-detects input (.apk/.xapk/.apks/.apkm/.dex/.so/.xml/dir) and
141
+ unpacks into a sequentially numbered workspace:
142
+ ./dexsect_runs/01_<package>_<version>-<YYYYMMDD>/
143
+
144
+ 2. Full Pipeline (Unpack + 153-Item Inspect + HTML/MD/JSON/SARIF):
145
+ dexsect app.apk --inspect --report
146
+ dexsect app.apk --inspect --report --lang ar --rules builtin
147
+
148
+ 3. Smart Shortcuts (Work From Any Directory via Global Registry):
149
+ dexsect runs List all workspaces with their IDs (01, 02...)
150
+ dexsect query 01 ... Refer to run #01 simply as '01' or 'latest'
151
+
152
+ ========================================================================
153
+ FLEXIBLE CUSTOMIZATION (--only / --skip / --profile / --scope / --rules)
154
+ ========================================================================
155
+ * Select exact unpack phases (--only):
156
+ decode, decompile, fingerprint, frameworks, native, map
157
+ * Skip phases or granular sub-tasks (--skip):
158
+ smali, res, debug-info, lang-splits, embedded, inventory, disasm, so-strings
159
+ * Low-Memory Device / Mobile Preset (--low-mem):
160
+ dexsect big_app.apk --low-mem --inspect --report
161
+ * Inspection Depth (--profile): fast | standard | deep
162
+ * Scope & Confidence Filters:
163
+ dexsect query 01 --id SEC-005 --scope app --confidence high,medium
164
+ * Built-in & Custom Rule Packs (--rules):
165
+ dexsect inspect 01 --rules builtin,./my_rules.json --deterministic
166
+
167
+ ========================================================================
168
+ ESSENTIAL COMMAND RECIPES
169
+ ========================================================================
170
+ [Query, Explain & Export]
171
+ dexsect explain ACT-005
172
+ dexsect query 01 --summary
173
+ dexsect query 01 --id ACT-005 --scope app --format json -o exported.json
174
+ dexsect query 01 --id NET-001 --scope app --unique --format values -o domains.txt
175
+
176
+ [Search, Trace, Diff & Share]
177
+ dexsect search 01 firebase --scope app --format table
178
+ dexsect trace 01 MainActivity
179
+ dexsect diff 01 02 --format html -o diff_report.html
180
+ dexsect pack 01 --minimal -o case_01.zip
181
+
182
+ [Reports (Languages: {locs})]
183
+ dexsect report 01 --lang ar
184
+ dexsect report 01 --format sarif -o dexsect.sarif
185
+
186
+ [Standalone Single-Artifact Tools]
187
+ dexsect decode AndroidManifest.xml (Binary AXML -> XML)
188
+ dexsect decompile classes2.dex (Standalone DEX -> Java)
189
+ dexsect framework index.android.bundle (Hermes / JS unpack)
190
+ dexsect native libfoo.so (ELF32/64 & JNI)
191
+ dexsect fingerprint app.apk (Fast ZIP stack check)
192
+
193
+ ========================================================================
194
+ MORE DETAILED GUIDES
195
+ ========================================================================
196
+ dexsect help query Full query, filtering & export manual
197
+ dexsect help phases Complete phase & sub-task customization guide
198
+ dexsect help standalone Single-file tools & external folder guide
199
+ dexsect help diff Version diff & cross-layer tracing guide
200
+ dexsect help rules Built-in & custom JSON rule packs + config guide
201
+ dexsect help examples End-to-end real-world command cheat sheet
202
+ dexsect <command> --help Full flags & examples for any command
203
+ dexsect catalog Browse all 153 official extraction IDs
204
+ """
205
+
206
+ parser = argparse.ArgumentParser(
207
+ prog="dexsect",
208
+ description=f"DexSect v{__version__} - Cross-Platform Android Unpacking, Inspection & Reporting Toolkit",
209
+ epilog=top_epilog,
210
+ formatter_class=argparse.RawDescriptionHelpFormatter,
211
+ )
212
+ parser.add_argument("-v", "--version", action="version", version=f"%(prog)s {__version__}")
213
+
214
+ sub = parser.add_subparsers(dest="command", metavar="<command>")
215
+
216
+ for cname in ("unpack", "run"):
217
+ sp = sub.add_parser(
218
+ cname,
219
+ help="Unpack APK/Bundle/Dir (default when passing a file directly)",
220
+ epilog=(
221
+ "Examples:\n"
222
+ " dexsect app.apk Unpack only\n"
223
+ " dexsect app.apk --inspect --report Full pipeline + HTML/MD/JSON/SARIF\n"
224
+ " dexsect app.apk --inspect --report --lang ar Full pipeline + Arabic RTL report\n"
225
+ " dexsect app.xapk --low-mem --inspect Mobile/low-RAM preset\n"
226
+ " dexsect app.apk --only decode,fingerprint,native,map Run selected phases only\n"
227
+ " dexsect app.apk --resume Resume interrupted run automatically\n"
228
+ ),
229
+ formatter_class=argparse.RawDescriptionHelpFormatter,
230
+ )
231
+ sp.add_argument("target", help="APK, XAPK/APKS/APKM, DEX, SO, Bundle, XML, decoded dir, run ID (01/latest), or workspace")
232
+ sp.add_argument("--only", default="", help=f"Comma-separated phases: {','.join(UNPACK_PHASE_ORDER)}")
233
+ sp.add_argument("--skip", default="", help="Skip phases or sub-tasks (smali,res,lang-splits,embedded,debug-info,inventory,disasm,so-strings)")
234
+ sp.add_argument("--inspect", action="store_true", help="Run 153-item static Catalog Inspection after unpacking")
235
+ sp.add_argument("--report", action="store_true", help="Generate HTML/MD/JSON/SARIF reports after inspection")
236
+ sp.add_argument("--profile", choices=["fast", "standard", "deep"], default="standard", help="Inspection depth profile [default: standard]")
237
+ sp.add_argument("--deterministic", action="store_true", help="Record forensic reproducibility hash in inspection summary")
238
+ sp.add_argument("--rules", default="", help="Comma-separated rule packs (or 'builtin', 'builtin:crypto_audit')")
239
+ sp.add_argument("--lang", default="en", help=f"Report language ({locs}) [default: en]")
240
+ _add_common_flags(sp)
241
+
242
+ sp_dec = sub.add_parser(
243
+ "decode",
244
+ help="Decode APK/Bundle via Apktool OR decode binary AndroidManifest.xml",
245
+ epilog=(
246
+ "Examples:\n"
247
+ " dexsect decode app.apk\n"
248
+ " dexsect decode AndroidManifest.xml\n"
249
+ " dexsect decode AndroidManifest.xml -o readable_manifest.xml\n"
250
+ " dexsect decode app.xapk --skip lang-splits,smali\n"
251
+ ),
252
+ formatter_class=argparse.RawDescriptionHelpFormatter,
253
+ )
254
+ sp_dec.add_argument("target", help=".apk, .xapk/.apks/.apkm, or binary XML file")
255
+ sp_dec.add_argument("--skip", default="", help="Skip sub-tasks (smali,res,lang-splits,embedded,debug-info,inventory)")
256
+ _add_common_flags(sp_dec)
257
+
258
+ sp_jadx = sub.add_parser(
259
+ "decompile",
260
+ help="Decompile APK or standalone .dex file to Java/Kotlin via JADX",
261
+ epilog=(
262
+ "Examples:\n"
263
+ " dexsect decompile classes.dex\n"
264
+ " dexsect decompile 01 --jadx-jobs 1 --java-xmx 1536m --deobf\n"
265
+ ),
266
+ formatter_class=argparse.RawDescriptionHelpFormatter,
267
+ )
268
+ sp_jadx.add_argument("target", help=".apk, .dex, run ID (01/latest), or workspace directory")
269
+ _add_common_flags(sp_jadx)
270
+
271
+ sp_fp = sub.add_parser(
272
+ "fingerprint",
273
+ help="Detect frameworks (Flutter/RN/Unity/Web), Hermes version, and packers",
274
+ epilog="Examples:\n dexsect fingerprint app.apk\n dexsect fingerprint ./old_decoded_dir\n",
275
+ formatter_class=argparse.RawDescriptionHelpFormatter,
276
+ )
277
+ sp_fp.add_argument("target", help=".apk, .xapk, run ID, or unpacked directory")
278
+ _add_common_flags(sp_fp)
279
+
280
+ sp_fw = sub.add_parser(
281
+ "framework",
282
+ help="Unpack standalone Flutter/RN/Unity/Web/Xamarin artifacts",
283
+ epilog="Examples:\n dexsect framework index.android.bundle\n dexsect framework libapp.so\n dexsect framework global-metadata.dat\n dexsect framework ./assets/www\n",
284
+ formatter_class=argparse.RawDescriptionHelpFormatter,
285
+ )
286
+ sp_fw.add_argument("target", help="index.android.bundle, libapp.so, global-metadata.dat, .dll, www/, or workspace")
287
+ sp_fw.add_argument("--skip", default="", help="Skip sub-tasks (e.g. disasm)")
288
+ _add_common_flags(sp_fw)
289
+
290
+ sp_nat = sub.add_parser(
291
+ "native",
292
+ help="Unpack ELF32/64 metadata, DT_NEEDED, exports/imports, JNI & strings from .so",
293
+ epilog="Examples:\n dexsect native libnative.so\n dexsect native 01 --all-so\n dexsect native ./assets/motion/libstripped.so\n",
294
+ formatter_class=argparse.RawDescriptionHelpFormatter,
295
+ )
296
+ sp_nat.add_argument("target", help=".so file, lib/ directory, run ID, or unpacked workspace")
297
+ sp_nat.add_argument("--skip", default="", help="Skip sub-tasks (e.g. so-strings)")
298
+ _add_common_flags(sp_nat)
299
+
300
+ sp_map = sub.add_parser(
301
+ "map",
302
+ help="Regenerate UNPACK_MAP.txt and UNPACK_MAP.md from a workspace",
303
+ epilog="Examples:\n dexsect map 01\n dexsect map latest\n",
304
+ formatter_class=argparse.RawDescriptionHelpFormatter,
305
+ )
306
+ sp_map.add_argument("target", help="Workspace directory, run ID (01), or 'latest'")
307
+ sp_map.add_argument("-q", "--quiet", action="store_true")
308
+ sp_map.add_argument("--no-color", action="store_true")
309
+
310
+ sp_ins = sub.add_parser(
311
+ "inspect",
312
+ help="Run 153-item catalog inspection into 10_Analysis/findings.db",
313
+ epilog=(
314
+ "Examples:\n"
315
+ " dexsect inspect 01 --report --lang ar\n"
316
+ " dexsect inspect app.apk --profile deep --deterministic --report\n"
317
+ " dexsect inspect 01 --only manifest,signing,ACT-005\n"
318
+ " dexsect inspect 01 --rules builtin --report\n"
319
+ ),
320
+ formatter_class=argparse.RawDescriptionHelpFormatter,
321
+ )
322
+ sp_ins.add_argument("target", help="Workspace, run ID (01/latest), unpacked dir, or raw .apk/.xapk")
323
+ sp_ins.add_argument("--profile", choices=["fast", "standard", "deep"], default="standard", help="Depth profile [default: standard]")
324
+ sp_ins.add_argument("--only", default="", help="Run only specific inspectors, domains, or catalog IDs")
325
+ sp_ins.add_argument("--skip", default="", help="Skip specific inspectors, domains, or catalog IDs")
326
+ sp_ins.add_argument("--unit", default=None, help="Restrict inspection to a single unit ID (e.g. 0001)")
327
+ sp_ins.add_argument("--report", action="store_true", help="Generate HTML/MD/JSON/SARIF reports afterward")
328
+ sp_ins.add_argument("--deterministic", action="store_true", help="Record forensic reproducibility hash in inspection summary")
329
+ sp_ins.add_argument("--rules", default="", help="Comma-separated rule packs (or 'builtin', 'builtin:crypto_audit')")
330
+ sp_ins.add_argument("--lang", default="en", help=f"Report language ({locs}) [default: en]")
331
+ _add_common_flags(sp_ins)
332
+
333
+ sp_qry = sub.add_parser(
334
+ "query",
335
+ help="Filter, summarize, extract, and export findings from findings.db",
336
+ epilog=(
337
+ "Examples:\n"
338
+ " dexsect query 01 --summary List all available Catalog IDs & counts\n"
339
+ " dexsect query 01 --id ACT-005 --scope app Unprotected exported activities (app only)\n"
340
+ " dexsect query 01 --confidence high --format table Show high-confidence findings only\n"
341
+ " dexsect query 01 --id URL-001 --layer java --unique Unique URLs from Java\n"
342
+ " dexsect query 01 --id NET-001 --format values -o d.txt Export domains to plain text\n"
343
+ " dexsect query 01 --domain Permissions --format csv -o p.csv\n"
344
+ ),
345
+ formatter_class=argparse.RawDescriptionHelpFormatter,
346
+ )
347
+ sp_qry.add_argument("target", help="Workspace, run ID (01/latest), or findings.db path")
348
+ sp_qry.add_argument("--summary", action="store_true", help="List all Catalog IDs and counts present in this workspace")
349
+ sp_qry.add_argument("--id", default="", help="Catalog ID(s) or prefixes (e.g. ACT-005,PER-001,URL-*,CUSTOM-*)")
350
+ sp_qry.add_argument("--domain", default="", help="Filter by domain(s) (e.g. Permissions,Components)")
351
+ sp_qry.add_argument("--unit", default="", help="Filter by unit ID(s) (e.g. 0001,0002)")
352
+ sp_qry.add_argument("--layer", default="", help="Filter by layer(s) (manifest,java,smali,dex,native,resources,assets,framework)")
353
+ sp_qry.add_argument("--scope", default="", help="Filter by code scope (app, third_party, boilerplate)")
354
+ sp_qry.add_argument("--confidence", default="", help="Filter by confidence (high, medium, low)")
355
+ sp_qry.add_argument("--match", default=None, help="Substring / FTS5 filter")
356
+ sp_qry.add_argument("--regex", default=None, help="Regex filter on value/title/file")
357
+ sp_qry.add_argument("--unique", action="store_true", help="Deduplicate identical values across any output format")
358
+ sp_qry.add_argument("--format", choices=["table", "values", "json", "jsonl", "csv", "tsv", "md"], default="table", help="Output format [default: table]")
359
+ sp_qry.add_argument("--limit", type=int, default=200, help="Max rows (0 = unlimited) [default: 200]")
360
+ sp_qry.add_argument("-o", "--output", default=None, help="Save extracted output directly to file")
361
+
362
+ sp_src = sub.add_parser(
363
+ "search",
364
+ help="Fast FTS5 or regex search across all extracted findings or deep strings",
365
+ epilog=(
366
+ "Examples:\n"
367
+ " dexsect search 01 firebase --scope app\n"
368
+ " dexsect search latest \"https://.*api\" --regex --format values\n"
369
+ " dexsect search 01 secret_key --strings --layer java\n"
370
+ ),
371
+ formatter_class=argparse.RawDescriptionHelpFormatter,
372
+ )
373
+ sp_src.add_argument("target", help="Workspace, run ID (01/latest), or findings.db path")
374
+ sp_src.add_argument("query_text", help="Text or regex pattern to search")
375
+ sp_src.add_argument("--strings", action="store_true", help="Search raw strings_index table (from --profile deep)")
376
+ sp_src.add_argument("--regex", action="store_true", help="Interpret query_text as regular expression")
377
+ sp_src.add_argument("--unit", default="", help="Filter by unit ID(s)")
378
+ sp_src.add_argument("--layer", default="", help="Filter by layer(s)")
379
+ sp_src.add_argument("--scope", default="", help="Filter by code scope (app, third_party, boilerplate)")
380
+ sp_src.add_argument("--confidence", default="", help="Filter by confidence (high, medium, low)")
381
+ sp_src.add_argument("--unique", action="store_true", help="Deduplicate matching values")
382
+ sp_src.add_argument("--format", choices=["table", "values", "json", "jsonl", "csv", "tsv", "md"], default="table")
383
+ sp_src.add_argument("--limit", type=int, default=100, help="Max rows (0 = unlimited) [default: 100]")
384
+ sp_src.add_argument("-o", "--output", default=None, help="Save search results to file")
385
+
386
+ sp_rpt = sub.add_parser(
387
+ "report",
388
+ help="Generate interactive HTML, Markdown, JSON, and SARIF 2.1.0 reports",
389
+ epilog=(
390
+ "Examples:\n"
391
+ " dexsect report 01\n"
392
+ " dexsect report 01 --lang ar\n"
393
+ " dexsect report latest --format sarif -o results.sarif\n"
394
+ " dexsect report 01 --include-noise --full-json\n"
395
+ ),
396
+ formatter_class=argparse.RawDescriptionHelpFormatter,
397
+ )
398
+ sp_rpt.add_argument("target", help="Workspace, run ID (01/latest) (auto-runs inspect if findings.db missing)")
399
+ sp_rpt.add_argument("--format", choices=["all", "html", "md", "json", "sarif"], default="all", help="Report format [default: all]")
400
+ sp_rpt.add_argument("--include-noise", action="store_true", help="Include XML schema/boilerplate noise in reports")
401
+ sp_rpt.add_argument("--full-json", action="store_true", help="Do not cap sections in ANALYSIS_REPORT.json")
402
+ sp_rpt.add_argument("--lang", default="en", help=f"HTML report language ({locs}) [default: en]")
403
+ sp_rpt.add_argument("--profile", choices=["fast", "standard", "deep"], default="standard", help="Profile if auto-inspect runs")
404
+ sp_rpt.add_argument("-o", "--output", default=None, help="Custom output folder for reports")
405
+ sp_rpt.add_argument("-q", "--quiet", action="store_true")
406
+ sp_rpt.add_argument("--no-color", action="store_true")
407
+
408
+ sp_diff = sub.add_parser(
409
+ "diff",
410
+ help="Compare two DexSect workspaces (added/removed permissions, components, URLs, native JNI)",
411
+ epilog=(
412
+ "Examples:\n"
413
+ " dexsect diff 01 02\n"
414
+ " dexsect diff 01 02 --scope app --format md -o diff.md\n"
415
+ " dexsect diff 01 02 --format html -o diff_report.html\n"
416
+ ),
417
+ formatter_class=argparse.RawDescriptionHelpFormatter,
418
+ )
419
+ sp_diff.add_argument("baseline", help="Baseline workspace path, run ID (01), or 'latest'")
420
+ sp_diff.add_argument("target", help="Target/newer workspace path, run ID (02), or 'latest'")
421
+ sp_diff.add_argument("--scope", default="", help="Filter diff by scope (app, third_party, boilerplate)")
422
+ sp_diff.add_argument("--format", choices=["table", "md", "json", "html"], default="table")
423
+ sp_diff.add_argument("-o", "--output", default=None, help="Save diff report to file")
424
+
425
+ sp_trc = sub.add_parser(
426
+ "trace",
427
+ help="Correlate a class, URL, library, permission, or JNI method across all layers",
428
+ epilog=(
429
+ "Examples:\n"
430
+ " dexsect trace 01 MainActivity\n"
431
+ " dexsect trace 01 libvidmatecodec --format json -o trace.json\n"
432
+ " dexsect trace latest firebase\n"
433
+ ),
434
+ formatter_class=argparse.RawDescriptionHelpFormatter,
435
+ )
436
+ sp_trc.add_argument("target", help="Workspace path, run ID (01), or 'latest'")
437
+ sp_trc.add_argument("query_text", help="Symbol, class, URL, domain, library, or permission to trace")
438
+ sp_trc.add_argument("--format", choices=["tree", "json"], default="tree")
439
+ sp_trc.add_argument("--limit", type=int, default=150)
440
+ sp_trc.add_argument("-o", "--output", default=None, help="Save trace output to file")
441
+
442
+ sp_exp = sub.add_parser("explain", help="Explain any Catalog ID (source, reliability, query example)")
443
+ sp_exp.add_argument("catalog_id", help="Catalog ID (e.g. ACT-005, SIG-004, NAT-005, COD-GAP-002)")
444
+
445
+ sp_pck = sub.add_parser("pack", help="Export a workspace as a portable .zip or .tar.gz archive")
446
+ sp_pck.add_argument("target", help="Workspace path, run ID (01), or 'latest'")
447
+ sp_pck.add_argument("-o", "--output", default=None, help="Output archive path")
448
+ sp_pck.add_argument("--format", choices=["zip", "tar.gz"], default="zip")
449
+ sp_pck.add_argument("--minimal", action="store_true", help="Include only workspace.json, reports, analysis DB & logs")
450
+
451
+ sp_runs = sub.add_parser(
452
+ "runs",
453
+ help="List all recorded DexSect workspaces across runs",
454
+ epilog="Examples:\n dexsect runs\n dexsect runs --format json\n",
455
+ formatter_class=argparse.RawDescriptionHelpFormatter,
456
+ )
457
+ sp_runs.add_argument("--format", choices=["table", "json"], default="table")
458
+
459
+ sp_cat = sub.add_parser(
460
+ "catalog",
461
+ help="Browse the official Extraction Catalog",
462
+ epilog="Examples:\n dexsect catalog\n dexsect catalog --domain Security\n dexsect catalog --id SIG --format json\n",
463
+ formatter_class=argparse.RawDescriptionHelpFormatter,
464
+ )
465
+ sp_cat.add_argument("--domain", default="", help="Filter by domain name")
466
+ sp_cat.add_argument("--profile", choices=["fast", "standard", "deep", "future"], default=None)
467
+ sp_cat.add_argument("--id", default="", help="Filter by ID prefix (e.g. ACT, SIG, NAT)")
468
+ sp_cat.add_argument("--format", choices=["table", "json"], default="table")
469
+
470
+ sp_hlp = sub.add_parser("help", help="Detailed guides (topics: query, phases, standalone, diff, rules, examples)")
471
+ sp_hlp.add_argument("topic", nargs="?", default="overview", help="Topic: overview, query, phases, standalone, diff, rules, examples")
472
+
473
+ sub.add_parser("doctor", help="Audit installed tools, optional unpackers, locales & environment")
474
+
475
+ return parser
476
+
477
+
478
+ def _cmd_help_topic(topic: str) -> int:
479
+ t = (topic or "overview").lower()
480
+ if t == "query":
481
+ print("""
482
+ DexSect :: Query, Search & Export Guide
483
+ ====================================================================
484
+ 1. Check runs, explain IDs & discover extracted Catalog IDs:
485
+ dexsect runs
486
+ dexsect explain ACT-005
487
+ dexsect query 01 --summary
488
+
489
+ 2. Filter by Catalog ID, Domain, Layer, Scope, or Confidence:
490
+ dexsect query 01 --id ACT-005 --scope app
491
+ dexsect query 01 --confidence high,medium --format table
492
+ dexsect query 01 --id URL-001 --layer java --unique
493
+ dexsect query 01 --id NAT-005
494
+
495
+ 3. Output Formats (--format) & File Export (-o):
496
+ table | values | json | jsonl | csv | tsv | md
497
+
498
+ 4. Fast Full-Text (FTS5) & Regex Search:
499
+ dexsect search 01 firebase --scope app
500
+ dexsect search 01 "AIza|AKIA" --regex --format json -o keys.json
501
+ dexsect search 01 token --strings --unique
502
+ ====================================================================
503
+ """)
504
+ return 0
505
+
506
+ if t == "phases":
507
+ print("""
508
+ DexSect :: Pipeline Phases & Granular Customization
509
+ ====================================================================
510
+ Default Unpack Order:
511
+ decode -> decompile -> fingerprint -> frameworks -> native -> map
512
+
513
+ 1. Run ONLY selected phases (--only):
514
+ dexsect app.apk --only decode,fingerprint,map
515
+
516
+ 2. Skip phases or sub-tasks (--skip):
517
+ Sub-tasks: smali, res, debug-info, lang-splits, embedded,
518
+ inventory, disasm, so-strings
519
+
520
+ 3. Low-Memory, Memory & JADX Tuning:
521
+ dexsect big_app.apk --low-mem --inspect --report
522
+ dexsect big_app.apk -j 4 --jadx-jobs 1 --java-xmx 1536m --jadx-args "--escape-unicode"
523
+ dexsect app.apk --resume
524
+ ====================================================================
525
+ """)
526
+ return 0
527
+
528
+ if t == "standalone":
529
+ print("""
530
+ DexSect :: Standalone Single-Artifact Commands
531
+ ====================================================================
532
+ * Binary AndroidManifest.xml -> Plain UTF-8 XML:
533
+ dexsect decode AndroidManifest.xml -o readable_manifest.xml
534
+ * Standalone .dex -> Java/Kotlin (JADX):
535
+ dexsect decompile classes2.dex
536
+ * Standalone .so library -> ELF headers, DT_NEEDED, JNI, strings:
537
+ dexsect native libvidmatecodec.so
538
+ * Standalone Framework file -> Flutter/RN/Hermes/Unity/Web:
539
+ dexsect framework index.android.bundle
540
+ dexsect framework libapp.so
541
+ * Fast ZIP Fingerprinting:
542
+ dexsect fingerprint app.apk
543
+ ====================================================================
544
+ """)
545
+ return 0
546
+
547
+ if t == "diff":
548
+ print("""
549
+ DexSect :: Version Diff, Trace & Sharing Guide
550
+ ====================================================================
551
+ 1. Compare two versions:
552
+ dexsect diff 01 02 --scope app --format html -o diff_report.html
553
+
554
+ 2. Cross-layer correlation trace:
555
+ dexsect trace 01 MainActivity
556
+
557
+ 3. Pack a workspace for sharing with colleagues:
558
+ dexsect pack 01 --minimal -o share_case01.zip
559
+ ====================================================================
560
+ """)
561
+ return 0
562
+
563
+ if t == "rules":
564
+ rules_dir = get_config_dir() / "rules"
565
+ locs_dir = get_config_dir() / "locales"
566
+ print(f"""
567
+ DexSect :: Bundled & Custom Rule Packs, Config & Locales
568
+ ====================================================================
569
+ 1. Built-in Rule Packs:
570
+ dexsect inspect 01 --rules builtin --report
571
+ dexsect inspect 01 --rules builtin:crypto_audit,builtin:anti_analysis
572
+
573
+ 2. Custom JSON Rules (anywhere or inside {rules_dir}):
574
+ dexsect inspect 01 --rules ./my_rules.json --report
575
+ dexsect query 01 --id CUSTOM-*
576
+
577
+ 3. User Config ({USER_CONFIG_PATH}) & Custom Locales ({locs_dir}):
578
+ dexsect report 01 --lang ar
579
+ dexsect report 01 --format sarif -o dexsect.sarif
580
+ ====================================================================
581
+ """)
582
+ return 0
583
+
584
+ if t == "examples":
585
+ print("""
586
+ DexSect :: Complete End-to-End Cheat Sheet
587
+ ====================================================================
588
+ dexsect app.apk --inspect --report
589
+ dexsect app.apk --low-mem --inspect --report --lang ar
590
+ dexsect inspect 01 --rules builtin --deterministic --report
591
+ dexsect report 01 --format sarif -o dexsect.sarif
592
+ dexsect query 01 --summary
593
+ dexsect query 01 --id SEC-005 --scope app --confidence high,medium
594
+ dexsect diff 01 02 --format html -o v1_vs_v2.html
595
+ dexsect trace 01 MainActivity
596
+ dexsect pack 01 --minimal -o case01_minimal.zip
597
+ ====================================================================
598
+ """)
599
+ return 0
600
+
601
+ build_parser().print_help()
602
+ return 0
603
+
604
+
605
+ def _cmd_explain(args: argparse.Namespace) -> int:
606
+ cat_path = Path(__file__).resolve().parent / "catalog" / "EXTRACTION_CATALOG.json"
607
+ if not cat_path.is_file():
608
+ print("[ERROR] Catalog not found.", file=sys.stderr)
609
+ return 1
610
+ items = json.loads(cat_path.read_text(encoding="utf-8")).get("items", [])
611
+ want = args.catalog_id.strip().upper()
612
+ match = next((x for x in items if x["id"].upper() == want), None)
613
+ if not match:
614
+ partial = [x for x in items if want in x["id"].upper() or want.lower() in x["name"].lower()]
615
+ if not partial:
616
+ print(f"[ERROR] Unknown Catalog ID: {args.catalog_id}. Run 'dexsect catalog' to list all IDs.", file=sys.stderr)
617
+ return 1
618
+ print(f"Did you mean one of ({len(partial)}):")
619
+ for x in partial[:15]:
620
+ print(f" {x['id']:<12} {x['name']} ({x['domain']})")
621
+ return 0
622
+
623
+ print("=" * 68)
624
+ print(f"Catalog ID : {match['id']} — {match['name']}")
625
+ print("=" * 68)
626
+ print(f"Domain : {match['domain']} / {match['subdomain']}")
627
+ print(f"Reliability : {match.get('reliability', 'high')}")
628
+ print(f"Profile : {match['profile']} | Storage: {match['storage']}")
629
+ print(f"Method : {match['extraction_type']} ({match['method']})")
630
+ print(f"Sources : {', '.join(match['source_files'])}")
631
+ print(f"Provenance : {', '.join(match['provenance_fields'])}")
632
+ print(f"Description : {match['description']}")
633
+ print("-" * 68)
634
+ print(f"Query Usage : dexsect query 01 --id {match['id']} --format table")
635
+ print("=" * 68)
636
+ return 0
637
+
638
+
639
+ def _cmd_pack(args: argparse.Namespace, runs_root: Path) -> int:
640
+ ws = _resolve_target_shortcut(args.target, runs_root)
641
+ if not (ws.is_dir() and (ws / "workspace.json").is_file()):
642
+ print(f"[ERROR] Valid DexSect workspace not found: {args.target}", file=sys.stderr)
643
+ return 1
644
+ ext = "tar.gz" if args.format == "tar.gz" else "zip"
645
+ suffix = "_minimal" if args.minimal else ""
646
+ out_file = Path(args.output).expanduser().resolve() if args.output else (ws.parent / f"{ws.name}{suffix}.{ext}")
647
+ out_file.parent.mkdir(parents=True, exist_ok=True)
648
+
649
+ keep_roots = {"workspace.json", "07_Logs", "08_Inventory", "09_Reports", "10_Analysis"}
650
+ files_to_pack = []
651
+ for p in sorted(ws.rglob("*")):
652
+ if not p.is_file():
653
+ continue
654
+ rel = p.relative_to(ws)
655
+ if args.minimal and rel.parts[0] not in keep_roots:
656
+ continue
657
+ files_to_pack.append((p, rel))
658
+
659
+ if args.format == "tar.gz":
660
+ with tarfile.open(out_file, "w:gz") as tf:
661
+ for p, rel in files_to_pack:
662
+ tf.add(p, arcname=f"{ws.name}/{rel.as_posix()}")
663
+ else:
664
+ with zipfile.ZipFile(out_file, "w", compression=zipfile.ZIP_DEFLATED) as zf:
665
+ for p, rel in files_to_pack:
666
+ zf.write(p, arcname=f"{ws.name}/{rel.as_posix()}")
667
+
668
+ sz = out_file.stat().st_size
669
+ print(f"[OK] Packed {len(files_to_pack)} files -> {out_file} ({sz / (1024 * 1024):.2f} MB)")
670
+ return 0
671
+
672
+
673
+ def _cmd_runs(args: argparse.Namespace, runs_root: Path) -> int:
674
+ runs = RunsRegistry().list_runs(runs_root)
675
+ if args.format == "json":
676
+ print(json.dumps(runs, indent=2, ensure_ascii=False))
677
+ return 0
678
+ if not runs:
679
+ print("No DexSect workspaces recorded yet.")
680
+ return 0
681
+ print(f"DexSect Workspaces ({len(runs)})")
682
+ print("=" * 96)
683
+ print(f"{'ID':<5} {'Workspace Name':<44} {'Updated':<20} {'Path'}")
684
+ print("-" * 96)
685
+ for r in runs:
686
+ seq = f"{r['seq']:02d}" if r.get("seq") is not None else "-"
687
+ print(f"{seq:<5} {str(r.get('name', '-'))[:43]:<44} {str(r.get('updated_at', '-')):<20} {r.get('path')}")
688
+ print("=" * 96)
689
+ print("Tip: Pass ID (e.g. '01') or 'latest' to query/search/trace/diff/pack/inspect/report from anywhere!")
690
+ return 0
691
+
692
+
693
+ def _cmd_doctor() -> int:
694
+ prefs = load_user_config()
695
+ tools = discover_tools(prefs)
696
+ print(f"DexSect v{__version__} :: System & Tools Diagnostic")
697
+ print("=" * 68)
698
+ print(f"Python : {sys.version.split()[0]} ({sys.executable})")
699
+ print(f"OS Family : {detect_os_family()} ({os.uname().sysname} {os.uname().machine})" if hasattr(os, "uname") else f"OS Family : {detect_os_family()}")
700
+ print(f"User Config : {USER_CONFIG_PATH} ({'found' if USER_CONFIG_PATH.is_file() else 'not set'})")
701
+ print(f"Locales : {', '.join(available_locales())}")
702
+ print("-" * 68)
703
+ print(f"{'Tool':<18} {'Status':<10} {'Required For':<24} {'Version / Hint'}")
704
+ print("-" * 68)
705
+ for name, info in tools.items():
706
+ status = "OK" if info.found else "MISSING"
707
+ detail = info.version if info.found else info.install_hint
708
+ print(f"{name:<18} {status:<10} {info.required_for:<24} {detail}")
709
+ print("=" * 68)
710
+ core_ok = all(tools[k].found for k in ("java", "apktool", "jadx"))
711
+ print("Core tools ready! All unpack & inspection features are operational." if core_ok else "Warning: Core tools missing.")
712
+ return 0 if core_ok else 1
713
+
714
+
715
+ def _cmd_catalog(args: argparse.Namespace) -> int:
716
+ cat_path = Path(__file__).resolve().parent / "catalog" / "EXTRACTION_CATALOG.json"
717
+ if not cat_path.is_file():
718
+ print(f"[ERROR] Catalog file not found: {cat_path}", file=sys.stderr)
719
+ return 1
720
+ data = json.loads(cat_path.read_text(encoding="utf-8"))
721
+ items = data.get("items", [])
722
+
723
+ if args.domain:
724
+ items = [x for x in items if args.domain.lower() in x["domain"].lower()]
725
+ if args.profile:
726
+ items = [x for x in items if x["profile"] == args.profile]
727
+ if args.id:
728
+ items = [x for x in items if x["id"].lower().startswith(args.id.lower())]
729
+
730
+ if args.format == "json":
731
+ print(json.dumps({"total": len(items), "items": items}, indent=2, ensure_ascii=False))
732
+ return 0
733
+
734
+ print(f"DexSect Extraction Catalog v{data.get('catalog_version')} ({len(items)} items)")
735
+ print("-" * 108)
736
+ print(f"{'ID':<12} {'Rel':<7} {'Profile':<9} {'Storage':<11} {'Domain':<22} {'Name'}")
737
+ print("-" * 108)
738
+ for x in items:
739
+ print(f"{x['id']:<12} {x.get('reliability', 'high'):<7} {x['profile']:<9} {x['storage']:<11} {x['domain'][:21]:<22} {x['name']}")
740
+ return 0
741
+
742
+
743
+ def _resolve_db_path(target: Path) -> Optional[Path]:
744
+ if target.is_file() and target.suffix == ".db":
745
+ return target
746
+ cand = target / "10_Analysis" / "findings.db"
747
+ if cand.is_file():
748
+ return cand
749
+ return None
750
+
751
+
752
+ def _cmd_query(args: argparse.Namespace, runs_root: Path) -> int:
753
+ target = _resolve_target_shortcut(args.target, runs_root)
754
+ db_path = _resolve_db_path(target)
755
+ if not db_path:
756
+ print(f"[ERROR] findings.db not found for '{args.target}'. Run 'dexsect inspect {args.target}' first.", file=sys.stderr)
757
+ return 1
758
+
759
+ db = FindingsDB(db_path)
760
+ try:
761
+ if args.summary:
762
+ sum_rows = db.summary_by_catalog()
763
+ if args.format == "json":
764
+ print(json.dumps(sum_rows, indent=2, ensure_ascii=False))
765
+ return 0
766
+ print(f"Available Findings in: {_short_path(target)}")
767
+ print("=" * 64)
768
+ print(f"{'Catalog ID':<12} {'Count':<8} {'Domain'}")
769
+ print("-" * 64)
770
+ total = 0
771
+ for r in sum_rows:
772
+ total += r["cnt"]
773
+ print(f"{r['catalog_id']:<12} {r['cnt']:<8} {r['domain']}")
774
+ print("-" * 64)
775
+ print(f"Total: {total} findings across {len(sum_rows)} Catalog IDs")
776
+ m = SEQ_DIR_RE.match(target.name)
777
+ ws_ref = m.group(1) if m else _short_path(target)
778
+ print(f"Tip : dexsect query {ws_ref} --id <CATALOG_ID>")
779
+ return 0
780
+
781
+ cids = [x.strip().upper() for x in args.id.split(",") if x.strip()]
782
+ doms = [x.strip() for x in args.domain.split(",") if x.strip()]
783
+ uids = [x.strip() for x in args.unit.split(",") if x.strip()]
784
+ lyrs = [x.strip() for x in args.layer.split(",") if x.strip()]
785
+ scps = [x.strip() for x in args.scope.split(",") if x.strip()]
786
+ confs = [x.strip() for x in args.confidence.split(",") if x.strip()]
787
+ lim = None if args.limit == 0 else args.limit
788
+
789
+ rows = db.query_findings(
790
+ catalog_ids=cids or None,
791
+ domains=doms or None,
792
+ unit_ids=uids or None,
793
+ layers=lyrs or None,
794
+ scopes=scps or None,
795
+ confidences=confs or None,
796
+ text_query=args.match,
797
+ regex_pattern=args.regex,
798
+ limit=lim,
799
+ unique_only=args.unique,
800
+ )
801
+ finally:
802
+ db.close()
803
+
804
+ rendered = format_findings_output(rows, args.format)
805
+ if args.output:
806
+ out_p = Path(args.output).expanduser().resolve()
807
+ out_p.parent.mkdir(parents=True, exist_ok=True)
808
+ out_p.write_text((rendered + "\n") if rendered else "", encoding="utf-8")
809
+ print(f"[OK] Exported {len(rows)} rows ({args.format}) -> {out_p}")
810
+ else:
811
+ if rows or args.format not in ("values", "jsonl"):
812
+ print(rendered)
813
+ return 0
814
+
815
+
816
+ def _cmd_search(args: argparse.Namespace, runs_root: Path) -> int:
817
+ target = _resolve_target_shortcut(args.target, runs_root)
818
+ db_path = _resolve_db_path(target)
819
+ if not db_path:
820
+ print(f"[ERROR] findings.db not found for '{args.target}'. Run 'dexsect inspect {args.target}' first.", file=sys.stderr)
821
+ return 1
822
+
823
+ uids = [x.strip() for x in args.unit.split(",") if x.strip()]
824
+ lyrs = [x.strip() for x in args.layer.split(",") if x.strip()]
825
+ scps = [x.strip() for x in args.scope.split(",") if x.strip()]
826
+ confs = [x.strip() for x in args.confidence.split(",") if x.strip()]
827
+ lim = None if args.limit == 0 else args.limit
828
+
829
+ db = FindingsDB(db_path)
830
+ try:
831
+ if args.strings:
832
+ rows = db.search_strings(
833
+ text_query=None if args.regex else args.query_text,
834
+ regex_pattern=args.query_text if args.regex else None,
835
+ unit_ids=uids or None,
836
+ layers=lyrs or None,
837
+ limit=lim,
838
+ unique_only=args.unique,
839
+ )
840
+ for r in rows:
841
+ r.setdefault("catalog_id", "STR-001")
842
+ r.setdefault("domain", "Strings & Constants")
843
+ r.setdefault("title", "String")
844
+ r.setdefault("scope", "app")
845
+ r.setdefault("confidence", "low")
846
+ else:
847
+ rows = db.query_findings(
848
+ unit_ids=uids or None,
849
+ layers=lyrs or None,
850
+ scopes=scps or None,
851
+ confidences=confs or None,
852
+ text_query=None if args.regex else args.query_text,
853
+ regex_pattern=args.query_text if args.regex else None,
854
+ limit=lim,
855
+ unique_only=args.unique,
856
+ )
857
+ finally:
858
+ db.close()
859
+
860
+ rendered = format_findings_output(rows, args.format)
861
+ if args.output:
862
+ out_p = Path(args.output).expanduser().resolve()
863
+ out_p.parent.mkdir(parents=True, exist_ok=True)
864
+ out_p.write_text((rendered + "\n") if rendered else "", encoding="utf-8")
865
+ print(f"[OK] Saved {len(rows)} search results ({args.format}) -> {out_p}")
866
+ else:
867
+ if rows or args.format not in ("values", "jsonl"):
868
+ print(rendered)
869
+ return 0
870
+
871
+
872
+ def _cmd_diff(args: argparse.Namespace, runs_root: Path) -> int:
873
+ ws1 = _resolve_target_shortcut(args.baseline, runs_root)
874
+ ws2 = _resolve_target_shortcut(args.target, runs_root)
875
+ for w in (ws1, ws2):
876
+ if not (w.is_dir() and (w / "10_Analysis" / "findings.db").is_file()):
877
+ print(f"[ERROR] Inspected workspace (with findings.db) not found: {w}", file=sys.stderr)
878
+ return 1
879
+ scps = [s.strip() for s in args.scope.split(",") if s.strip()] or None
880
+ diff_data = DiffPlugin().compare(ws1, ws2, scope_filter=scps)
881
+ rendered = format_diff_output(diff_data, args.format)
882
+ if args.output:
883
+ op = Path(args.output).expanduser().resolve()
884
+ op.parent.mkdir(parents=True, exist_ok=True)
885
+ op.write_text(rendered + "\n", encoding="utf-8")
886
+ print(f"[OK] Saved diff ({args.format}) -> {op}")
887
+ else:
888
+ print(rendered)
889
+ return 0
890
+
891
+
892
+ def _cmd_trace(args: argparse.Namespace, runs_root: Path) -> int:
893
+ ws = _resolve_target_shortcut(args.target, runs_root)
894
+ if not (ws.is_dir() and (ws / "10_Analysis" / "findings.db").is_file()):
895
+ print(f"[ERROR] Inspected workspace (with findings.db) not found: {ws}", file=sys.stderr)
896
+ return 1
897
+ tdata = TracePlugin().trace_target(ws, args.query_text, limit=args.limit)
898
+ rendered = format_trace_output(tdata, args.format)
899
+ if args.output:
900
+ op = Path(args.output).expanduser().resolve()
901
+ op.parent.mkdir(parents=True, exist_ok=True)
902
+ op.write_text(rendered + "\n", encoding="utf-8")
903
+ print(f"[OK] Saved trace ({args.format}) -> {op}")
904
+ else:
905
+ print(rendered)
906
+ return 0
907
+
908
+
909
+ def _handle_binary_xml(target: Path, output: Optional[str]) -> int:
910
+ try:
911
+ raw = target.read_bytes()
912
+ decoded_xml = decode_axml_file(target)
913
+ except Exception as exc:
914
+ print(f"[ERROR] Failed to decode XML {target}: {exc}", file=sys.stderr)
915
+ return 1
916
+ kind = "Binary AXML" if is_binary_axml(raw) else "Plain XML"
917
+ if output:
918
+ out_p = Path(output).expanduser().resolve()
919
+ out_p.parent.mkdir(parents=True, exist_ok=True)
920
+ out_p.write_text(decoded_xml, encoding="utf-8")
921
+ print(f"[OK] Decoded {kind} -> {out_p}")
922
+ else:
923
+ sys.stdout.write(decoded_xml)
924
+ return 0
925
+
926
+
927
+ def _resolve_output_dir(target: Path, explicit_out: Optional[str], runs_root: Path, resume: bool = False) -> Path:
928
+ if explicit_out:
929
+ return Path(explicit_out).expanduser().resolve()
930
+ if target.is_dir() and (target / "workspace.json").is_file():
931
+ return target
932
+ if resume:
933
+ pkg, _ = peek_package_identity(target)
934
+ pkg_slug = safe_slug(pkg, max_len=64, fallback=safe_slug(target.stem))
935
+ for r in RunsRegistry().list_runs(runs_root):
936
+ rp = Path(r["path"])
937
+ if rp.is_dir() and (f"_{pkg_slug}" in rp.name or r.get("target") == str(target)):
938
+ return rp
939
+ return _build_numbered_run_dir(target, runs_root)
940
+
941
+
942
+ def _print_clean_summary(
943
+ state: WorkspaceState,
944
+ results: Dict[str, Any],
945
+ ins_res: Optional[Dict[str, Any]],
946
+ rpt_res: Optional[Dict[str, Any]],
947
+ elapsed: float,
948
+ no_color: bool,
949
+ ) -> None:
950
+ c = Colors(enabled=sys.stdout.isatty() and not os.environ.get("NO_COLOR") and not no_color)
951
+ ws_short = _short_path(state.root)
952
+ m = SEQ_DIR_RE.match(state.root.name)
953
+ pkg_hint = ""
954
+ units = state.get_units()
955
+ if units:
956
+ pkg_hint = units[0].name
957
+ RunsRegistry().register(
958
+ state.root,
959
+ target_input=str(state.data.get("target_input", "")),
960
+ package=pkg_hint,
961
+ version="",
962
+ status="COMPLETED" if not state.data.get("errors") else "WITH_WARNINGS",
963
+ )
964
+ ws_ref = m.group(1) if m else str(state.root)
965
+
966
+ print("")
967
+ print(f"{c.CRIMSON}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━{c.RESET}")
968
+ print(f"{c.CRIMSON}◆ {c.ORANGE}{c.BOLD}Dex{c.CREAM}{c.BOLD}Sect{c.RESET} {c.MUTED}v{__version__}{c.RESET} {c.CRIMSON}│{c.RESET} {c.OK}Completed in {format_duration(elapsed)}{c.RESET}")
969
+ print(f"{c.CRIMSON}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━{c.RESET}")
970
+ print(f"{c.MUTED}Workspace :{c.RESET} {c.CREAM}{ws_short}{c.RESET}")
971
+
972
+ if results:
973
+ print(f"\n{c.ORANGE}{c.BOLD}Pipeline Summary:{c.RESET}")
974
+ for pname, pres in results.items():
975
+ col = c.OK if pres.status == "COMPLETED" else (c.ERR if pres.status == "FAILED" else c.WARN)
976
+ extra = ""
977
+ if pname == "decode" and pres.details:
978
+ extra = f"({pres.details.get('files_indexed', 0)} files)"
979
+ elif pname == "decompile" and pres.details:
980
+ extra = f"({pres.details.get('java_files', 0)} java files)"
981
+ elif pname == "native" and pres.details:
982
+ extra = f"({pres.details.get('libs_processed', 0)} libs, {pres.details.get('total_jni_symbols', 0)} JNI)"
983
+ print(f" - {pname:<12} {col}{pres.status:<11}{c.RESET} {format_duration(pres.duration_sec)} {c.MUTED}{extra}{c.RESET}")
984
+
985
+ if ins_res:
986
+ tot_f = sum(ins_res["counts_by_domain"].values())
987
+ dom_n = len(ins_res["counts_by_domain"])
988
+ ah = str(ins_res.get("analysis_hash", ""))[:12]
989
+ print(f" - {'inspect':<12} {c.OK}{'COMPLETED':<11}{c.RESET} {ins_res['duration_sec']}s {c.MUTED}({tot_f} findings, {dom_n} domains, hash={ah}){c.RESET}")
990
+
991
+ print(f"\n{c.ORANGE}{c.BOLD}Key Outputs:{c.RESET}")
992
+ if (state.report_dir / "UNPACK_MAP.txt").is_file():
993
+ print(f" * Unpack Map : {_short_path(state.report_dir / 'UNPACK_MAP.txt', state.root)}")
994
+ if (state.root / "10_Analysis" / "findings.db").is_file():
995
+ print(" * Findings DB : 10_Analysis/findings.db")
996
+ if rpt_res:
997
+ for k, p in rpt_res["files"].items():
998
+ print(f" * Report {k.upper():<5}: {_short_path(Path(p), state.root)}")
999
+
1000
+ err_cnt = len(state.data.get("errors", []))
1001
+ if err_cnt:
1002
+ print(f" * {c.WARN}Warnings/Errs: {err_cnt} logged -> 07_Logs/errors.log{c.RESET}")
1003
+
1004
+ print(f"\n{c.ORANGE}{c.BOLD}Next Steps:{c.RESET}")
1005
+ if ins_res or (state.root / "10_Analysis" / "findings.db").is_file():
1006
+ print(f" dexsect query {ws_ref} --summary")
1007
+ print(f" dexsect query {ws_ref} --id ACT-005,NET-001 --scope app --format table")
1008
+ print(f" dexsect search {ws_ref} <keyword>")
1009
+ print(f" dexsect trace {ws_ref} <class_or_lib>")
1010
+ if not rpt_res:
1011
+ print(f" dexsect report {ws_ref} --lang ar")
1012
+ else:
1013
+ print(f" dexsect inspect {ws_ref} --report")
1014
+ print(f" cat {ws_short}/09_Reports/UNPACK_MAP.txt")
1015
+ print(f"{c.CRIMSON}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━{c.RESET}")
1016
+
1017
+
1018
+ def _main_impl(argv: Optional[List[str]] = None) -> int:
1019
+ raw_argv = list(sys.argv[1:] if argv is None else argv)
1020
+ raw_argv = ["--help" if tok == "-help" else tok for tok in raw_argv]
1021
+
1022
+ if not raw_argv:
1023
+ build_parser().print_help()
1024
+ return 0
1025
+
1026
+ first_pos = _find_first_positional(raw_argv)
1027
+ if first_pos is not None and first_pos not in SUBCOMMANDS:
1028
+ raw_argv = ["unpack"] + raw_argv
1029
+
1030
+ parser = build_parser()
1031
+ args = parser.parse_args(raw_argv)
1032
+
1033
+ if args.command == "help":
1034
+ return _cmd_help_topic(args.topic)
1035
+ if args.command == "doctor":
1036
+ return _cmd_doctor()
1037
+ if args.command == "catalog":
1038
+ return _cmd_catalog(args)
1039
+ if args.command == "explain":
1040
+ return _cmd_explain(args)
1041
+
1042
+ prefs = load_user_config()
1043
+ runs_root = _get_runs_root(prefs)
1044
+
1045
+ if args.command == "runs":
1046
+ return _cmd_runs(args, runs_root)
1047
+ if args.command == "pack":
1048
+ return _cmd_pack(args, runs_root)
1049
+ if args.command == "query":
1050
+ return _cmd_query(args, runs_root)
1051
+ if args.command == "search":
1052
+ return _cmd_search(args, runs_root)
1053
+ if args.command == "diff":
1054
+ return _cmd_diff(args, runs_root)
1055
+ if args.command == "trace":
1056
+ return _cmd_trace(args, runs_root)
1057
+
1058
+ target = _resolve_target_shortcut(args.target, runs_root)
1059
+ if not target.exists():
1060
+ print(f"[ERROR] Target not found: {args.target}", file=sys.stderr)
1061
+ return 1
1062
+
1063
+ if args.command in ("decode", "unpack", "run") and target.is_file() and target.suffix.lower() == ".xml":
1064
+ return _handle_binary_xml(target, getattr(args, "output", None))
1065
+
1066
+ tools = discover_tools(prefs)
1067
+
1068
+ if args.command == "map":
1069
+ if not target.is_dir() or not (target / "workspace.json").is_file():
1070
+ print(f"[ERROR] Valid DexSect workspace not found at: {target}", file=sys.stderr)
1071
+ return 1
1072
+ cfg = RunConfig(target_path=target, output_dir=target, only_phases=["map"], quiet=args.quiet, no_color=args.no_color, tools=tools, user_prefs=prefs)
1073
+ rc, state, results = PipelineEngine(build_default_registry()).execute(cfg, ["map"])
1074
+ if not args.quiet:
1075
+ _print_clean_summary(state, results, None, None, 0.0, args.no_color)
1076
+ return rc
1077
+
1078
+ if args.command == "report":
1079
+ if not target.is_dir() or not (target / "workspace.json").is_file():
1080
+ print(f"[ERROR] Valid DexSect workspace not found at: {target}", file=sys.stderr)
1081
+ return 1
1082
+ state = WorkspaceState(root=target)
1083
+ state.load()
1084
+ cfg = RunConfig(target_path=target, output_dir=target, quiet=args.quiet, no_color=args.no_color, tools=tools, user_prefs=prefs)
1085
+ ui = TerminalDashboard(version=__version__, quiet=args.quiet, no_color=args.no_color)
1086
+ ctx = PipelineContext(cfg=cfg, state=state, ui=ui)
1087
+ ins_res = None
1088
+ if not (target / "10_Analysis" / "findings.db").is_file():
1089
+ ins_res = InspectPlugin().execute(ctx, profile=args.profile)
1090
+ custom_out = Path(args.output).expanduser().resolve() if args.output else None
1091
+ rpt_res = ReportPlugin().execute(
1092
+ ctx, formats=[args.format], out_dir=custom_out, lang=args.lang,
1093
+ include_noise=args.include_noise, full_json=args.full_json,
1094
+ )
1095
+ if not args.quiet:
1096
+ _print_clean_summary(state, {}, ins_res, rpt_res, rpt_res["duration_sec"], args.no_color)
1097
+ return 0
1098
+
1099
+ if args.command == "inspect":
1100
+ output_dir = _resolve_output_dir(target, args.output, runs_root, getattr(args, "resume", False))
1101
+ is_ws = target.is_dir() and (target / "workspace.json").is_file()
1102
+ state = WorkspaceState(root=output_dir, target_input=str(target))
1103
+ unpack_results: Dict[str, Any] = {}
1104
+ t0 = time.time()
1105
+ low_mem = getattr(args, "low_mem", False)
1106
+ if is_ws:
1107
+ state.load()
1108
+ else:
1109
+ if target.is_file() and target.suffix.lower() in (".apk", ".xapk", ".apks", ".apkm", ".zip"):
1110
+ cfg_u = RunConfig(
1111
+ target_path=target, output_dir=output_dir,
1112
+ jobs=args.jobs or (1 if low_mem else prefs.get("jobs", 2)),
1113
+ jadx_jobs=args.jadx_jobs or (1 if low_mem else prefs.get("jadx_jobs", 2)),
1114
+ max_depth=args.max_depth or prefs.get("max_depth", 10),
1115
+ timeout_sec=args.timeout or prefs.get("timeout_sec", 1800),
1116
+ java_xmx=args.java_xmx or ("1024m" if low_mem else prefs.get("java_xmx")),
1117
+ resume=args.resume, deobf=args.deobf, jadx_with_res=args.jadx_with_res,
1118
+ jadx_args=shlex.split(getattr(args, "jadx_args", "") or ""),
1119
+ all_so=args.all_so, quiet=args.quiet, no_color=args.no_color,
1120
+ tools=tools, user_prefs=prefs,
1121
+ )
1122
+ if low_mem:
1123
+ cfg_u.skip_items.update(["lang-splits", "so-strings"])
1124
+ phases = resolve_phases(cfg_u, target, state)
1125
+ rc, state, unpack_results = PipelineEngine(build_default_registry()).execute(cfg_u, phases)
1126
+ if rc != 0:
1127
+ return rc
1128
+ else:
1129
+ state.init_dirs()
1130
+ bootstrap_external_target(state, target)
1131
+
1132
+ cfg = RunConfig(target_path=target, output_dir=output_dir, quiet=args.quiet, no_color=args.no_color, tools=tools, user_prefs=prefs)
1133
+ ui = TerminalDashboard(version=__version__, quiet=args.quiet, no_color=args.no_color)
1134
+ ui.set_pipeline_stages(["inspect", "report"] if args.report else ["inspect"])
1135
+ ui.start()
1136
+ rpt_res = None
1137
+ try:
1138
+ ctx = PipelineContext(cfg=cfg, state=state, ui=ui)
1139
+ only_set = {x.strip().lower() for x in args.only.split(",") if x.strip()}
1140
+ skip_set = {x.strip().lower() for x in args.skip.split(",") if x.strip()}
1141
+ r_paths = resolve_rule_tokens([x for x in getattr(args, "rules", "").split(",") if x.strip()])
1142
+ ins_res = InspectPlugin().execute(
1143
+ ctx, profile=args.profile, only_filters=only_set, skip_filters=skip_set,
1144
+ unit_filter=args.unit, rule_paths=r_paths, deterministic=getattr(args, "deterministic", False),
1145
+ )
1146
+ if args.report:
1147
+ rpt_res = ReportPlugin().execute(ctx, formats=["all"], lang=args.lang)
1148
+ finally:
1149
+ ui.stop()
1150
+
1151
+ if not args.quiet:
1152
+ _print_clean_summary(state, unpack_results, ins_res, rpt_res, time.time() - t0, args.no_color)
1153
+ return 0
1154
+
1155
+ resume = getattr(args, "resume", False)
1156
+ explicit_out = getattr(args, "output", None)
1157
+ output_dir = _resolve_output_dir(target, explicit_out, runs_root, resume)
1158
+
1159
+ is_existing_ws = output_dir.is_dir() and (output_dir / "workspace.json").is_file()
1160
+ if args.command in ("unpack", "run") and output_dir.exists() and not resume and not is_existing_ws:
1161
+ print(f"[ERROR] Output directory already exists: {output_dir}\n Use --resume or -o.", file=sys.stderr)
1162
+ return 1
1163
+ if resume and not output_dir.exists():
1164
+ print(f"[ERROR] Cannot resume; directory does not exist: {output_dir}", file=sys.stderr)
1165
+ return 1
1166
+
1167
+ only_raw = getattr(args, "only", "")
1168
+ skip_raw = getattr(args, "skip", "")
1169
+ only_phases = [p.strip().lower() for p in only_raw.split(",") if p.strip()]
1170
+ skip_items = {s.strip().lower() for s in skip_raw.split(",") if s.strip()}
1171
+ low_mem = getattr(args, "low_mem", False)
1172
+ if low_mem:
1173
+ skip_items.update(["lang-splits", "so-strings"])
1174
+
1175
+ if args.command == "decode":
1176
+ only_phases = ["decode"] if "map" in skip_items else ["decode", "map"]
1177
+ elif args.command == "decompile":
1178
+ only_phases = ["decompile"] if "map" in skip_items else ["decompile", "map"]
1179
+ elif args.command == "fingerprint":
1180
+ only_phases = ["fingerprint"] if "map" in skip_items else ["fingerprint", "map"]
1181
+ elif args.command == "framework":
1182
+ only_phases = ["frameworks"] if "map" in skip_items else ["frameworks", "map"]
1183
+ elif args.command == "native":
1184
+ only_phases = ["native"] if "map" in skip_items else ["native", "map"]
1185
+
1186
+ invalid_only = [p for p in only_phases if p not in UNPACK_PHASE_ORDER]
1187
+ if invalid_only:
1188
+ print(f"[ERROR] Unknown phase(s): {', '.join(invalid_only)}", file=sys.stderr)
1189
+ return 1
1190
+
1191
+ cfg = RunConfig(
1192
+ target_path=target,
1193
+ output_dir=output_dir,
1194
+ only_phases=only_phases,
1195
+ skip_items=skip_items,
1196
+ jobs=getattr(args, "jobs", None) or (1 if low_mem else prefs.get("jobs", 2)),
1197
+ jadx_jobs=getattr(args, "jadx_jobs", None) or (1 if low_mem else prefs.get("jadx_jobs", 2)),
1198
+ max_depth=getattr(args, "max_depth", None) or prefs.get("max_depth", 10),
1199
+ timeout_sec=getattr(args, "timeout", None) or prefs.get("timeout_sec", 1800),
1200
+ java_xmx=getattr(args, "java_xmx", None) or ("1024m" if low_mem else prefs.get("java_xmx")),
1201
+ resume=resume,
1202
+ deobf=getattr(args, "deobf", False),
1203
+ jadx_with_res=getattr(args, "jadx_with_res", False),
1204
+ jadx_args=shlex.split(getattr(args, "jadx_args", "") or ""),
1205
+ all_so=getattr(args, "all_so", False),
1206
+ quiet=getattr(args, "quiet", False),
1207
+ no_color=getattr(args, "no_color", False),
1208
+ tools=tools,
1209
+ user_prefs=prefs,
1210
+ )
1211
+
1212
+ probe_state = WorkspaceState(root=output_dir, target_input=str(target))
1213
+ phases_to_run = resolve_phases(cfg, target, probe_state)
1214
+ if not phases_to_run:
1215
+ print("[ERROR] No phases left to run.", file=sys.stderr)
1216
+ return 1
1217
+
1218
+ if "decode" in phases_to_run and (not tools["apktool"].found or not tools["java"].found):
1219
+ print("[ERROR] 'decode' phase requires java and apktool. Run 'dexsect doctor'.", file=sys.stderr)
1220
+ return 1
1221
+ if "decompile" in phases_to_run and (not tools["jadx"].found or not tools["java"].found):
1222
+ print("[ERROR] 'decompile' phase requires java and jadx. Run 'dexsect doctor'.", file=sys.stderr)
1223
+ return 1
1224
+
1225
+ t0 = time.time()
1226
+ run_inspect = getattr(args, "inspect", False) or getattr(args, "report", False)
1227
+ run_report = getattr(args, "report", False)
1228
+ extra_stages = []
1229
+ if run_inspect:
1230
+ extra_stages.append("inspect")
1231
+ if run_report:
1232
+ extra_stages.append("report")
1233
+
1234
+ shared_ui = TerminalDashboard(version=__version__, quiet=cfg.quiet, no_color=cfg.no_color)
1235
+ shared_ui.start()
1236
+ ins_res = None
1237
+ rpt_res = None
1238
+ try:
1239
+ rc, state, results = PipelineEngine(build_default_registry()).execute(
1240
+ cfg, phases_to_run, extra_stages=extra_stages, shared_ui=shared_ui
1241
+ )
1242
+ if rc == 0 and run_inspect:
1243
+ ctx = PipelineContext(cfg=cfg, state=state, ui=shared_ui)
1244
+ r_paths = resolve_rule_tokens([x for x in getattr(args, "rules", "").split(",") if x.strip()])
1245
+ ins_res = InspectPlugin().execute(
1246
+ ctx, profile=getattr(args, "profile", "standard"),
1247
+ rule_paths=r_paths, deterministic=getattr(args, "deterministic", False),
1248
+ )
1249
+ if run_report:
1250
+ rpt_res = ReportPlugin().execute(ctx, formats=["all"], lang=getattr(args, "lang", "en"))
1251
+ finally:
1252
+ shared_ui.stop()
1253
+
1254
+ if not cfg.quiet:
1255
+ _print_clean_summary(state, results, ins_res, rpt_res, time.time() - t0, cfg.no_color)
1256
+ return rc
1257
+
1258
+
1259
+ def main(argv: Optional[List[str]] = None) -> int:
1260
+ try:
1261
+ return _main_impl(argv)
1262
+ except BrokenPipeError:
1263
+ try:
1264
+ devnull = os.open(os.devnull, os.O_WRONLY)
1265
+ os.dup2(devnull, sys.stdout.fileno())
1266
+ except Exception:
1267
+ pass
1268
+ return 0
1269
+
1270
+
1271
+ if __name__ == "__main__":
1272
+ sys.exit(main())