Skip to content

Quick start

This page walks through the main parts of the API. Every example comes in three languages: Python, Go and Java. Pick your language in the tabs above an example. Every other example on the site then switches to the same language.

Every code block on this site is taken from a file that runs in the project's tests, and the output shown under it is the real output of that code.

To set up a language first, see Install for Python, C and Go for Go, and Java for Java.

The examples use small files from the repository's tests/data/ folder. Use the path of your own APK or DEX file instead. The tests of each language run in a different folder, so the paths differ: the Python examples open tests/data/..., the Go examples ../../../tests/data/... and the Java examples ../../tests/data/....

Open an APK

Opening an APK reads the archive. The manifest, the resources and the signing information are decoded the first time you ask for each of them.

apk: dexpp.Apk = dexpp.Apk.open("tests/data/sample.apk")
manifest: dexpp.Manifest | None = apk.manifest
assert manifest is not None

print(manifest.package)
print("version:", manifest.version_code, manifest.version_name)
print("sdk:", manifest.min_sdk, "to", manifest.target_sdk)
print("uses:", manifest.permissions)
print("declares:", manifest.declared_permissions)
print("debuggable:", manifest.debuggable, "allow backup:", manifest.allow_backup)
com.example.dexpp
version: 7 1.2.3
sdk: 21 to 34
uses: ['android.permission.INTERNET', 'android.permission.CAMERA']
declares: ['com.example.dexpp.CUSTOM']
debuggable: True allow backup: False
apk, err := dexpp.OpenAPK("../../../tests/data/sample.apk")
if err != nil {
    log.Fatal(err)
}
defer apk.Close()
manifest, ok := apk.Manifest()
if !ok {
    log.Fatal("no manifest")
}

fmt.Println(manifest.Package)
// An attribute the manifest may leave out is a pointer, nil when it is not set.
if manifest.VersionCode != nil && manifest.VersionName != nil {
    fmt.Println("version:", *manifest.VersionCode, *manifest.VersionName)
}
if manifest.MinSDK != nil && manifest.TargetSDK != nil {
    fmt.Println("sdk:", *manifest.MinSDK, "to", *manifest.TargetSDK)
}
fmt.Println("uses:", manifest.Permissions)
for _, permission := range manifest.DeclaredPermissions {
    fmt.Println("declares:", permission.Name)
}
if manifest.Debuggable != nil && manifest.AllowBackup != nil {
    fmt.Println("debuggable:", *manifest.Debuggable, "allow backup:", *manifest.AllowBackup)
}
com.example.dexpp
version: 7 1.2.3
sdk: 21 to 34
uses: [android.permission.INTERNET android.permission.CAMERA]
declares: com.example.dexpp.CUSTOM
debuggable: true allow backup: false
try (Apk apk = Apk.open(Path.of("../../tests/data/sample.apk"))) {
    Manifest manifest = apk.manifest().orElseThrow();

    System.out.println(manifest.packageName());
    // An attribute the manifest may leave out is an Optional, empty when it is not set.
    if (manifest.versionCode().isPresent() && manifest.versionName().isPresent()) {
        System.out.println("version: " + manifest.versionCode().getAsLong() + " "
                + manifest.versionName().get());
    }
    if (manifest.minSdk().isPresent() && manifest.targetSdk().isPresent()) {
        System.out.println("sdk: " + manifest.minSdk().getAsLong() + " to "
                + manifest.targetSdk().getAsLong());
    }
    System.out.println("uses: " + manifest.permissions());
    for (DeclaredPermission permission : manifest.declaredPermissions()) {
        System.out.println("declares: " + permission.name());
    }
    if (manifest.debuggable().isPresent() && manifest.allowBackup().isPresent()) {
        System.out.println("debuggable: " + manifest.debuggable().get()
                + " allow backup: " + manifest.allowBackup().get());
    }
}
com.example.dexpp
version: 7 1.2.3
sdk: 21 to 34
uses: [android.permission.INTERNET, android.permission.CAMERA]
declares: com.example.dexpp.CUSTOM
debuggable: true allow backup: false

More in APK metadata.

Go from the package to its code

The APK's analysis() method (Go: Analysis()) returns an analysis context: the object that holds the code of every classes*.dex file of the APK. If you only have a DEX file, or you do not need the manifest, load the code directly:

apk_ctx: dexpp.AnalysisContext = dexpp.AnalysisContext.from_apk("tests/data/app.apk")
dex_ctx: dexpp.AnalysisContext = dexpp.AnalysisContext.from_dex("tests/data/classes.dex")
split_ctx: dexpp.AnalysisContext = dexpp.AnalysisContext.from_dex_files(
    ["tests/data/inherit_a.dex", "tests/data/inherit_b.dex"]
)
print(len(apk_ctx.classes()), len(dex_ctx.classes()), len(split_ctx.classes()))
2 1 4
apkCtx, err := dexpp.FromAPK("../../../tests/data/app.apk")
if err != nil {
    log.Fatal(err)
}
defer apkCtx.Close()

dexCtx, err := dexpp.FromDEX("../../../tests/data/classes.dex")
if err != nil {
    log.Fatal(err)
}
defer dexCtx.Close()

splitCtx, err := dexpp.FromDEXFiles([]string{
    "../../../tests/data/inherit_a.dex",
    "../../../tests/data/inherit_b.dex",
})
if err != nil {
    log.Fatal(err)
}
defer splitCtx.Close()

fmt.Println(len(apkCtx.Classes()), len(dexCtx.Classes()), len(splitCtx.Classes()))
2 1 4
try (AnalysisContext apkCtx = AnalysisContext.fromApk(Path.of("../../tests/data/app.apk"));
        AnalysisContext dexCtx =
                AnalysisContext.fromDex(Path.of("../../tests/data/classes.dex"));
        AnalysisContext splitCtx =
                AnalysisContext.fromDexFiles(
                        List.of(
                                Path.of("../../tests/data/inherit_a.dex"),
                                Path.of("../../tests/data/inherit_b.dex")))) {
    System.out.println(apkCtx.classes().size() + " " + dexCtx.classes().size() + " "
            + splitCtx.classes().size());
}
2 1 4
Load Python Go Java
every classes*.dex of an APK AnalysisContext.from_apk FromAPK AnalysisContext.fromApk
one DEX file AnalysisContext.from_dex FromDEX AnalysisContext.fromDex
several DEX files together AnalysisContext.from_dex_files FromDEXFiles AnalysisContext.fromDexFiles

List classes and methods

ctx: dexpp.AnalysisContext = dexpp.AnalysisContext.from_dex("tests/data/shapes.dex")

classes: list[dexpp.Class] = ctx.classes()
for cls in classes:
    kind: str = "interface" if cls.is_interface is True else "class"
    superclass: dexpp.ClassRef | None = cls.superclass
    parent: str | None = superclass.descriptor if superclass is not None else None
    interfaces: list[str] = [interface.descriptor for interface in cls.interfaces]
    print(kind, cls.descriptor, "extends", parent, "implements", interfaces)

circle: dexpp.Class | None = ctx.find_class("LCircle;")
assert circle is not None
print([field.name + ":" + field.type for field in circle.fields])

missing: dexpp.Class | None = ctx.find_class("Lno/such/Class;")
print(missing)
interface LShape; extends Ljava/lang/Object; implements []
class LAbstractShape; extends Ljava/lang/Object; implements ['LShape;']
class LCircle; extends LAbstractShape; implements []
class LRectangle; extends LAbstractShape; implements []
['radius:D']
None
ctx, err := dexpp.FromDEX("../../../tests/data/shapes.dex")
if err != nil {
    log.Fatal(err)
}
defer ctx.Close()

for _, cls := range ctx.Classes() {
    kind := "class"
    if cls.IsInterface() {
        kind = "interface"
    }
    parent := "none"
    if superclass := cls.Superclass(); superclass != nil {
        parent = superclass.Descriptor()
    }
    interfaces := []string{}
    for _, ref := range cls.Interfaces() {
        interfaces = append(interfaces, ref.Descriptor())
    }
    fmt.Println(kind, cls.Descriptor(), "extends", parent, "implements", interfaces)
}

circle := ctx.FindClass("LCircle;")
if circle == nil {
    log.Fatal("no Circle class")
}
var fields []string
for _, field := range circle.Fields() {
    fields = append(fields, field.Name()+":"+field.Type())
}
fmt.Println(fields)

missing := ctx.FindClass("Lno/such/Class;")
fmt.Println(missing)
interface LShape; extends Ljava/lang/Object; implements []
class LAbstractShape; extends Ljava/lang/Object; implements [LShape;]
class LCircle; extends LAbstractShape; implements []
class LRectangle; extends LAbstractShape; implements []
[radius:D]
<nil>
Path path = Path.of("../../tests/data/shapes.dex");
try (AnalysisContext ctx = AnalysisContext.fromDex(path)) {
    for (DexClass cls : ctx.classes()) {
        String kind = cls.isInterface() ? "interface" : "class";
        String parent = cls.superclass().map(ClassRef::descriptor).orElse("none");
        List<String> interfaces =
                cls.interfaces().stream().map(ClassRef::descriptor).toList();
        System.out.println(kind + " " + cls.descriptor() + " extends " + parent
                + " implements " + interfaces);
    }

    DexClass circle = ctx.findClass("LCircle;").orElseThrow();
    List<String> fields =
            circle.fields().stream()
                    .map((DexField field) -> field.name() + ":" + field.type())
                    .toList();
    System.out.println(fields);

    Optional<DexClass> missing = ctx.findClass("Lno/such/Class;");
    System.out.println(missing);
}
interface LShape; extends Ljava/lang/Object; implements []
class LAbstractShape; extends Ljava/lang/Object; implements [LShape;]
class LCircle; extends LAbstractShape; implements []
class LRectangle; extends LAbstractShape; implements []
[radius:D]
Optional.empty

Class names and types are written as descriptors, the form the DEX format uses: Lcom/example/Foo; for a class, I for int, [I for int[]. Concepts explains them.

Read bytecode

area: dexpp.Method = next(method for method in circle.methods if method.name == "area")
instructions: dexpp.InstructionView = area.instructions

for instruction in instructions:
    print(f"{instruction.base.offset:04x}  {dexpp.to_string(instruction)}")
0000  iget-wide v0, v4.field@1
0002  const-wide v2, #4614256656552045848
0007  mul-double v2, v2, v0
0009  mul-double v2, v2, v0
000b  return-wide v2
var area *dexpp.Method
for _, method := range circle.Methods() {
    if method.Name() == "area" {
        area = method
    }
}
instructions := area.Instructions()

for _, instruction := range instructions {
    fmt.Printf("%04x  %s\n", instruction.Base().Offset, dexpp.ToString(instruction))
}
0000  iget-wide v0, v4.field@1
0002  const-wide v2, #4614256656552045848
0007  mul-double v2, v2, v0
0009  mul-double v2, v2, v0
000b  return-wide v2
DexMethod area =
        circle.methods().stream()
                .filter((DexMethod method) -> method.name().equals("area"))
                .findFirst()
                .orElseThrow();
List<Instruction> instructions = area.instructions();

for (Instruction instruction : instructions) {
    System.out.printf("%04x  %s%n", instruction.offset(), Dexpp.toString(instruction));
}
0000  iget-wide v0, v4.field@1
0002  const-wide v2, #4614256656552045848
0007  mul-double v2, v2, v0
0009  mul-double v2, v2, v0
000b  return-wide v2

More in Classes, methods and bytecode.

Ask who calls what

The call graph covers the whole program. It is built the first time you ask the analysis context for it.

ctx: dexpp.AnalysisContext = dexpp.AnalysisContext.from_dex("tests/data/polymorphic.dex")
graph: dexpp.CallGraph = ctx.call_graph
print(len(graph.nodes), "methods,", len(graph.edges), "edges")


def label(node: dexpp.CallNode) -> str:
    """A short name for a node: its class and its method name."""
    return node.id.class_descriptor + "->" + node.id.name

noise_id: dexpp.MethodId = dexpp.MethodId("LKennel;", "noise", "(LAnimal;)Ljava/lang/String;")
noise: dexpp.CallNode | None = graph.find(noise_id)
assert noise is not None
print(label(noise), "kind:", noise.kind.name)

for edge in noise.out_edges:
    print("  calls", label(edge.callee), edge.kind.name, "at offset", edge.code_offset)
16 methods, 18 edges

LKennel;->noise kind: DEFINED
  calls LAnimal;->sound INTERFACE at offset 0
ctx, err := dexpp.FromDEX("../../../tests/data/polymorphic.dex")
if err != nil {
    log.Fatal(err)
}
defer ctx.Close()
graph, err := ctx.CallGraph()
if err != nil {
    log.Fatal(err)
}
fmt.Println(graph.NodeCount(), "methods,", graph.EdgeCount(), "edges")

// label is a short name for a node: its class and its method name.
label := func(index uint32) string {
    node, _ := graph.Node(index)
    return node.ID.ClassDescriptor + "->" + node.ID.Name
}

noiseID := dexpp.MethodID{
    ClassDescriptor: "LKennel;", Name: "noise", Proto: "(LAnimal;)Ljava/lang/String;",
}
noise, ok := graph.Find(noiseID)
if !ok {
    log.Fatal("no node for Kennel.noise")
}
fmt.Println(label(noise.Index), "kind:", noise.Kind)

for _, index := range graph.OutEdges(noise.Index) {
    edge, _ := graph.Edge(index)
    fmt.Println("  calls", label(edge.CalleeNode), edge.Kind, "at offset", edge.CodeOffset)
}
16 methods, 18 edges

LKennel;->noise kind: defined
  calls LAnimal;->sound interface at offset 0
/** A short name for a node: its class and its method name. */
static String label(CallGraph graph, int index) {
    MethodId id = graph.node(index).orElseThrow().id();
    return id.classDescriptor() + "->" + id.name();
}

static void graph() throws IOException {
    Path path = Path.of("../../tests/data/polymorphic.dex");
    try (AnalysisContext ctx = AnalysisContext.fromDex(path);
            CallGraph graph = ctx.callGraph()) {
        System.out.println(graph.nodeCount() + " methods, " + graph.edgeCount() + " edges");
    }
}

MethodId noiseId = new MethodId("LKennel;", "noise", "(LAnimal;)Ljava/lang/String;");
CallNode noise = graph.find(noiseId).orElseThrow();
System.out.println(label(graph, noise.index()) + " kind: " + noise.kind());

for (int index : graph.outEdges(noise.index())) {
    CallEdge edge = graph.edge(index).orElseThrow();
    System.out.println("  calls " + label(graph, edge.calleeNode()) + " " + edge.kind()
            + " at offset " + edge.codeOffset());
}
16 methods, 18 edges

LKennel;->noise kind: DEFINED
  calls LAnimal;->sound INTERFACE at offset 0

More in Call graph and Class hierarchy and cross-references.

Edit a DEX file

The model reads a DEX file into memory, lets you move, copy, remove and rename whole classes, and writes a valid DEX file again.

model: dexpp.Model = dexpp.Model.read_file("tests/data/shapes.dex")
print("DEX version", model.version, "with", len(model), "classes")
print(model.class_descriptors())

info: dexpp.ClassInfo | None = model.class_info("LCircle;")
assert info is not None
print(info.descriptor, "extends", info.superclass, "-", info.method_count, "methods")

abstract: dexpp.ClassInfo | None = model.class_info("LAbstractShape;")
assert abstract is not None
print(abstract.descriptor, "implements", abstract.interfaces)
DEX version 35 with 4 classes
['LShape;', 'LAbstractShape;', 'LCircle;', 'LRectangle;']
LCircle; extends LAbstractShape; - 4 methods
LAbstractShape; implements ['LShape;']
model, err := dexpp.ReadModelFile("../../../tests/data/shapes.dex", true)
if err != nil {
    log.Fatal(err)
}
defer model.Close()
fmt.Println("DEX version", model.Version(), "with", model.ClassCount(), "classes")
fmt.Println(model.ClassDescriptors())

info, ok := model.ClassInfo("LCircle;")
if !ok {
    log.Fatal("no Circle class")
}
if info.Superclass != nil {
    fmt.Println(info.Descriptor, "extends", *info.Superclass, "-", info.MethodCount, "methods")
}

abstract, ok := model.ClassInfo("LAbstractShape;")
if !ok {
    log.Fatal("no AbstractShape class")
}
fmt.Println(abstract.Descriptor, "implements", abstract.Interfaces)
DEX version 35 with 4 classes
[LShape; LAbstractShape; LCircle; LRectangle;]
LCircle; extends LAbstractShape; - 4 methods
LAbstractShape; implements [LShape;]
try (Model model = Model.readFile(Path.of("../../tests/data/shapes.dex"))) {
    System.out.println("DEX version " + model.version() + " with " + model.classCount()
            + " classes");
    System.out.println(model.classDescriptors());

    ClassInfo info = model.classInfo("LCircle;").orElseThrow();
    System.out.println(info.descriptor() + " extends " + info.superclass().orElse("nothing")
            + " - " + info.methodCount() + " methods");

    ClassInfo abstractShape = model.classInfo("LAbstractShape;").orElseThrow();
    System.out.println(abstractShape.descriptor() + " implements "
            + abstractShape.interfaces());
}
DEX version 35 with 4 classes
[LShape;, LAbstractShape;, LCircle;, LRectangle;]
LCircle; extends LAbstractShape; - 4 methods
LAbstractShape; implements [LShape;]

More in Editing DEX files.

Errors

A file that cannot be used is an error. A lookup that finds nothing is not an error: it gives an empty result instead.

def package_of(path: str) -> str | None:
    """The package name of an APK, or None when the file cannot be used."""
    try:
        apk: dexpp.Apk = dexpp.Apk.open(path)
    except FileNotFoundError:
        print(path, "does not exist")
        return None
    except dexpp.InvalidApkError as error:
        print("not an APK:", error)
        return None

    manifest: dexpp.Manifest | None = apk.manifest
    if manifest is None:
        return None
    return manifest.package


print(package_of("tests/data/sample.apk"))
print(package_of("tests/data/missing.apk"))
print(package_of("tests/data/classes.dex"))
com.example.dexpp
tests/data/missing.apk does not exist
None
not an APK: tests/data/classes.dex: no end-of-central-directory record (not a ZIP archive)
None
paths := []string{
    "../../../tests/data/sample.apk",
    "../../../tests/data/missing.apk",
    "../../../tests/data/classes.dex",
}
for _, path := range paths {
    apk, err := dexpp.OpenAPK(path)
    switch {
    case errors.Is(err, fs.ErrNotExist):
        fmt.Println(path, "does not exist")
    case errors.Is(err, dexpp.ErrInvalidAPK):
        fmt.Println("not an APK:", err)
    case err != nil:
        log.Fatal(err)
    default:
        name, _ := apk.Package()
        fmt.Println(name)
        apk.Close()
    }
}
com.example.dexpp
../../../tests/data/missing.apk does not exist
not an APK: ../../../tests/data/classes.dex: no end-of-central-directory record (not a ZIP archive)
for (String name : List.of("sample.apk", "missing.apk", "classes.dex")) {
    try (Apk apk = Apk.open(Path.of("../../tests/data", name))) {
        Optional<String> packageName = apk.manifest().map(Manifest::packageName);
        System.out.println(packageName.orElse("no manifest"));
    } catch (NoSuchFileException e) {
        System.out.println(name + " does not exist");
    } catch (InvalidApkException e) {
        System.out.println("not an APK: " + name + " (" + e.code() + ")");
    }
}
com.example.dexpp
missing.apk does not exist
not an APK: classes.dex (INVALID_APK)

Each language reports errors in its own way:

  • Python raises exceptions. A path that does not exist raises the built-in FileNotFoundError, and a path that exists but cannot be read, such as a directory, raises OSError. A file that dexpp cannot use raises one of dexpp's own exceptions: dexpp.InvalidApkError for a file that is not an APK, and dexpp.InvalidDexError for a DEX file that cannot be parsed. All of dexpp's exceptions have one base class, dexpp.Error. A lookup that finds nothing returns None.
  • Go returns an error. Every failed call returns a *dexpp.Error, and errors.Is tells the kinds apart: fs.ErrNotExist or dexpp.ErrFileNotFound for a missing file, dexpp.ErrInvalidAPK, dexpp.ErrInvalidDex and so on. A lookup that finds nothing returns nil, or false as its second result. See Errors in Go.
  • Java throws exceptions. A file that cannot be opened throws an IOException, such as NoSuchFileException. Every other error is an unchecked DexppException, with subclasses such as InvalidApkException and InvalidDexException. A lookup that finds nothing returns an empty Optional. See Errors on the Java page.

Concepts has more about errors.