Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 16 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,18 +79,20 @@ pip install .
After installation, the `droidasc` CLI command is available globally:

```
usage: droidasc [-h] {getclass,disassemble,listclass,getmanifest,findrefs} ...
usage: droidasc [-h] {getclass,disassemble,listclass,batch,getmanifest,findrefs} ...

ASC tooling entry (v0.1.2.post1).

positional arguments:
{getclass,disassemble,listclass,getmanifest,findrefs}
{getclass,disassemble,listclass,batch,getmanifest,findrefs}
getclass Locate the target class in APK, extract one DEX in
memory, then decompile.
disassemble Extract a class, rebuild a small DEX, then disassemble
it with dadguard.
listclass List classes across all DEX entries; use --prefix to
filter by package/class prefix.
batch Decompile many classes in one APK pass, inflating each
DEX exactly once.
getmanifest Decode AndroidManifest.xml from APK and print it as
XML.
findrefs Find code references for string/type/method/field
Expand All @@ -110,6 +112,8 @@ examples:
droidasc listclass app.apk
droidasc listclass app.apk -o classes.txt
droidasc listclass app.apk --prefix com.poc
droidasc batch app.apk --prefix com.poc -o out/
droidasc batch app.apk --from-file classes.txt -o out/ --resume
droidasc getmanifest app.apk
droidasc getmanifest app.apk -o AndroidManifest.xml
droidasc findrefs app.apk string token -o string_refs.txt
Expand All @@ -134,6 +138,16 @@ line. With `-o`, output is written to the selected file instead of stdout.
`--prefix com.poc` filters by `Lcom/poc`; an already normalized prefix such as
`Lcom/poc` is kept unchanged.

`batch` decompiles many classes in a single APK pass. `getclass` reopens the
APK and re-inflates DEX entries for every class it is asked for, so a
classes.txt round-trip spends most of its time copying the same buffers; `batch`
inflates each DEX once, indexes the classes it defines, then decompiles straight
from those in-memory buffers. Select classes with `--prefix com.poc` or
`--from-file classes.txt` (one name per line, dotted or Dalvik, `#` comments
allowed); `-o/--out-dir` is required and files mirror the package tree
(`com/poc/Main.java`). `--resume` skips classes whose output already exists and
`--limit N` caps the run. Output is byte-identical to `getclass`.

`disassemble` accepts the same dotted or Dalvik class formats as `getclass`.
It extracts the target class from the APK, rebuilds a small DEX in memory, and
disassembles the rebuilt DEX with `dadguard`. `--debug` enables timing output
Expand Down
88 changes: 88 additions & 0 deletions droidasc/asc_client/batch.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
"""Decompile many classes with one APK pass.

``getclass`` reopens the APK and re-inflates DEX entries for every class. This
module inflates each DEX once, indexes the classes it defines, then decompiles
from those in-memory buffers.
"""
import mmap
import os

from droidasc.asc_client.apk.dex_reader import list_dex_classes
from droidasc.asc_client.apk.loader import _inflate_dex, _parse_cd_dex_entries
from droidasc.asc_client.asc_handler import AscHandler
from droidasc.asc_client.dex_container import iter_logical_dex_buffers


def _to_dalvik_class(name):
if not name:
raise ValueError("Class name cannot be empty")
name = name.strip()
if name.startswith("L") and name.endswith(";") and "/" in name:
return name
name = name.replace(".", "/")
if not name.startswith("L"):
name = "L" + name
return name if name.endswith(";") else name + ";"


def class_output_path(dalvik_class):
return dalvik_class[1:-1] + ".java"


def index_apk(apk_path, prefix=None, log=None):
if prefix is not None:
prefix = prefix.strip()
if not prefix:
raise ValueError("Class prefix cannot be empty")
if not prefix.startswith("L"):
prefix = "L" + prefix.replace(".", "/")
prefix_bytes = prefix.encode("ascii") if prefix and prefix.isascii() else None

index = {}
with open(apk_path, "rb") as fp:
mm = mmap.mmap(fp.fileno(), 0, access=mmap.ACCESS_READ)
try:
entries = _parse_cd_dex_entries(mm)
if not entries:
raise ValueError("No DEX entries found in APK")
for entry in entries:
data = _inflate_dex(mm, entry)
if data is None:
continue
for logical_name, buf in iter_logical_dex_buffers(entry[0], data):
if log is not None:
log(f"[APK] '{logical_name}' inflated={len(buf)} bytes")
try:
names = list_dex_classes(buf, prefix=prefix, prefix_bytes=prefix_bytes)
except ValueError:
# A malformed sibling DEX must not hide the classes that are fine.
continue
for name in names:
index.setdefault(name, buf)
return index
finally:
mm.close()


def read_class_list(path):
names = []
with open(path, "r", encoding="utf-8", errors="replace") as fp:
for line in fp:
name = line.strip()
if name and not name.startswith("#"):
names.append(_to_dalvik_class(name))
if not names:
raise ValueError(f"{path}: no class names found")
return names


def decompile(index, dalvik_class):
return AscHandler().getclass(index[dalvik_class], dalvik_class)


def write_source(dest, source):
os.makedirs(os.path.dirname(dest), exist_ok=True)
with open(dest, "w", encoding="utf-8", errors="replace", newline="\n") as fp:
fp.write(source)
if not source.endswith("\n"):
fp.write("\n")
107 changes: 107 additions & 0 deletions droidasc/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,68 @@ def _handle_listclass(args):
print(f"[DEBUG] Total Execution Time: {(t_end - t_start) * 1000000:.2f} us")


def _handle_batch(args):
from droidasc.asc_client import batch

log = print if args.debug else None
index = batch.index_apk(args.apk_path, args.prefix, log)
if not index:
raise ValueError("No classes matched the requested selection.")

if args.from_file:
requested = batch.read_class_list(args.from_file)
missing = [name for name in requested if name not in index]
if missing:
print(
f"Warning: {len(missing)} class(es) not in APK, first: {missing[0]}",
file=sys.stderr,
)
selected = [name for name in requested if name in index]
if not selected:
raise ValueError("None of the listed classes are present in the APK.")
else:
selected = sorted(index)

if args.limit:
selected = selected[: args.limit]

t_batch = time.perf_counter()
written = skipped = failed = 0
for position, name in enumerate(selected, 1):
dest = os.path.join(args.out_dir, batch.class_output_path(name))
if args.resume and os.path.exists(dest):
skipped += 1
else:
try:
source = batch.decompile(index, name)
except Exception as exc: # one bad class must not abort the pass
failed += 1
print(f"[BATCH] failed: {name}: {exc}", file=sys.stderr)
else:
batch.write_source(dest, source)
written += 1
if position % 500 == 0 or position == len(selected):
elapsed = time.perf_counter() - t_batch
print(
f"[BATCH] {position}/{len(selected)} written={written} "
f"skipped={skipped} failed={failed} {position / elapsed:.1f} class/s",
file=sys.stderr,
)

print(
f"[BATCH] done written={written} skipped={skipped} failed={failed} "
f"in {time.perf_counter() - t_batch:.2f}s",
file=sys.stderr,
)

if args.debug:
t_end = time.perf_counter()
print(f"[DEBUG] Total Execution Time: {(t_end - t_start) * 1000000:.0f} us")

if failed == len(selected):
raise ValueError("Every selected class failed to decompile.")


def _handle_getmanifest(args):
from droidasc.asc_client.manifest_handler import get_manifest_xml

Expand Down Expand Up @@ -290,6 +352,8 @@ def main():
_handle_disassemble(args)
elif args.command == "listclass":
_handle_listclass(args)
elif args.command == "batch":
_handle_batch(args)
elif args.command == "getmanifest":
_handle_getmanifest(args)
elif args.command == "findrefs":
Expand Down Expand Up @@ -327,6 +391,8 @@ def _build_main_parser(show_version=False):
droidasc listclass app.apk
droidasc listclass app.apk -o classes.txt
droidasc listclass app.apk --prefix com.poc
droidasc batch app.apk --prefix com.poc -o out/
droidasc batch app.apk --from-file classes.txt -o out/ --resume
droidasc getmanifest app.apk
droidasc getmanifest app.apk -o AndroidManifest.xml
droidasc findrefs app.apk string token -o string_refs.txt
Expand Down Expand Up @@ -415,6 +481,47 @@ def _build_main_parser(show_version=False):
listclass_parser.add_argument("-o", "--output", help="Write class names to this file instead of stdout.")
listclass_parser.add_argument("apk_path", help="Path to the input APK file.")

batch_parser = subparsers.add_parser(
"batch",
help="Decompile many classes in one APK pass, inflating each DEX exactly once.",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""examples:
droidasc batch app.apk --prefix com.poc -o out/
droidasc batch app.apk --from-file classes.txt -o out/
droidasc batch app.apk --from-file classes.txt -o out/ --resume
""",
)
batch_parser.add_argument("--debug", action="store_true", help="Enable debug profiling output.")
selection = batch_parser.add_mutually_exclusive_group(required=True)
selection.add_argument(
"--from-file",
metavar="FILE",
help="Class list file: one name per line, dotted or Dalvik, # comments allowed.",
)
selection.add_argument(
"--prefix",
help="Decompile every class whose name starts with this prefix.",
)
batch_parser.add_argument(
"-o",
"--out-dir",
required=True,
help="Output directory; files mirror the package tree (com/poc/Main.java).",
)
batch_parser.add_argument(
"--resume",
action="store_true",
help="Skip classes whose output file already exists.",
)
batch_parser.add_argument(
"--limit",
type=int,
default=0,
metavar="N",
help="Decompile at most N classes (0 means no limit).",
)
batch_parser.add_argument("apk_path", help="Path to the input APK file.")

getmanifest_parser = subparsers.add_parser(
"getmanifest",
help="Decode AndroidManifest.xml from APK and print it as XML.",
Expand Down
Loading