Skip to content

Class hierarchy and cross-references

Both structures cover the whole program. Each is built the first time you ask the analysis context for it, and kept after that.

The examples come in Python, Go and Java. Pick your language in the tabs.

Class hierarchy

The class hierarchy (Python ctx.class_hierarchy, Go ctx.ClassHierarchy(), Java ctx.classHierarchy()) answers questions about inheritance. All queries take and return descriptors.

shapes: dexpp.AnalysisContext = dexpp.AnalysisContext.from_dex("tests/data/shapes.dex")
hierarchy: dexpp.ClassHierarchy = shapes.class_hierarchy

supertypes: list[str] = hierarchy.supertypes("LCircle;")
ancestors: list[str] = hierarchy.all_supertypes("LCircle;")
descendants: list[str] = hierarchy.all_descendants("LShape;")
print(supertypes)
print(ancestors)
print(sorted(descendants))
print(hierarchy.implementers("LShape;"))
print(sorted(hierarchy.subclasses("LAbstractShape;")))

is_shape: bool = hierarchy.is_subtype_of("LCircle;", "LShape;")
print(is_shape, hierarchy.is_interface("LShape;"))
print(hierarchy.is_loaded("Ljava/lang/Object;"))
['LAbstractShape;']
['LAbstractShape;', 'Ljava/lang/Object;', 'LShape;']
['LAbstractShape;', 'LCircle;', 'LRectangle;']
['LAbstractShape;']
['LCircle;', 'LRectangle;']
True True
False
shapes, err := dexpp.FromDEX("../../../tests/data/shapes.dex")
if err != nil {
    log.Fatal(err)
}
defer shapes.Close()
hierarchy, err := shapes.ClassHierarchy()
if err != nil {
    log.Fatal(err)
}

supertypes := hierarchy.Supertypes("LCircle;")
ancestors := hierarchy.AllSupertypes("LCircle;")
descendants := hierarchy.AllDescendants("LShape;")
sort.Strings(descendants)
fmt.Println(supertypes)
fmt.Println(ancestors)
fmt.Println(descendants)
fmt.Println(hierarchy.Implementers("LShape;"))
subclasses := hierarchy.Subclasses("LAbstractShape;")
sort.Strings(subclasses)
fmt.Println(subclasses)

isShape := hierarchy.IsSubtypeOf("LCircle;", "LShape;")
fmt.Println(isShape, hierarchy.IsInterface("LShape;"))
fmt.Println(hierarchy.IsLoaded("Ljava/lang/Object;"))
[LAbstractShape;]
[LAbstractShape; Ljava/lang/Object; LShape;]
[LAbstractShape; LCircle; LRectangle;]
[LAbstractShape;]
[LCircle; LRectangle;]
true true
false
Path path = Path.of("../../tests/data/shapes.dex");
try (AnalysisContext shapes = AnalysisContext.fromDex(path);
        ClassHierarchy hierarchy = shapes.classHierarchy()) {
    List<String> supertypes = hierarchy.supertypes("LCircle;");
    List<String> ancestors = hierarchy.allSupertypes("LCircle;");
    List<String> descendants =
            hierarchy.allDescendants("LShape;").stream().sorted().toList();
    System.out.println(supertypes);
    System.out.println(ancestors);
    System.out.println(descendants);
    System.out.println(hierarchy.implementers("LShape;"));
    System.out.println(hierarchy.subclasses("LAbstractShape;").stream().sorted().toList());

    boolean isShape = hierarchy.isSubtypeOf("LCircle;", "LShape;");
    System.out.println(isShape + " " + hierarchy.isInterface("LShape;"));
    System.out.println(hierarchy.isLoaded("Ljava/lang/Object;"));
}
[LAbstractShape;]
[LAbstractShape;, Ljava/lang/Object;, LShape;]
[LAbstractShape;, LCircle;, LRectangle;]
[LAbstractShape;]
[LCircle;, LRectangle;]
true true
false
Python Go Java Returns
supertypes(d) Supertypes(d) supertypes(d) the direct superclass, then the directly implemented interfaces
all_supertypes(d) AllSupertypes(d) allSupertypes(d) every ancestor class and interface; d itself is not included
subclasses(d) Subclasses(d) subclasses(d) the classes that directly extend d
implementers(d) Implementers(d) implementers(d) the classes that directly implement the interface d
all_descendants(d) AllDescendants(d) allDescendants(d) everything below d, through extends and implements; d itself is not included
is_subtype_of(sub, super) IsSubtypeOf(sub, super) isSubtypeOf(sub, super) whether sub is super or is below it
is_loaded(d) IsLoaded(d) isLoaded(d) whether the class is defined in a loaded file
is_interface(d) IsInterface(d) isInterface(d) whether the class is loaded and is an interface

Classes outside the loaded files are still in the hierarchy when a loaded class names them as a superclass or an interface. Ljava/lang/Object; is the usual example. For such a class is_loaded is false, and its own ancestors are unknown: the chain stops there.

A query about a descriptor the hierarchy has never seen returns an empty list, or false.

When a class is defined in more than one loaded file, its superclass and interfaces come from the first definition only, the one a lookup by descriptor returns. Android loads that definition and never the later ones.

Cross-references

The cross-reference index (Python ctx.xrefs, Go ctx.Xrefs(), Java ctx.xrefs()) answers "who uses this". It indexes four kinds of use:

Kind Python Go Java Indexed instructions
Method method_refs(id), method_refs_by_name(name) MethodRefs(id), MethodRefsByName(name) methodRefs(id), methodRefsByName(name) invokes
Field field_refs(id), field_reads(id), field_writes(id) FieldRefs(id), FieldReads(id), FieldWrites(id) fieldRefs(id), fieldReads(id), fieldWrites(id) iget, iput, sget, sput
String string_refs(value) StringRefs(value) stringRefs(value) const-string
Type type_refs(descriptor) TypeRefs(descriptor) typeRefs(descriptor) const-class, check-cast, instance-of, new-instance, new-array, filled-new-array

Every result is a list of sites. A site has a code offset and a referrer: the method whose code contains the instruction.

Who calls a method

ctx: dexpp.AnalysisContext = dexpp.AnalysisContext.from_dex("tests/data/classes.dex")
xrefs: dexpp.Xrefs = ctx.xrefs

matches: list[tuple[dexpp.MethodId, list[dexpp.MethodXref]]] = xrefs.method_refs_by_name("println")
for target, sites in matches:
    for site in sites:
        caller: dexpp.MethodId = xrefs.referrers[site.referrer]
        called: str = f"{target.class_descriptor} {target.name}"
        print(f"{called} is called by {caller.name} at {site.code_offset}")
Ljava/io/PrintStream; println is called by main at 6
ctx, err := dexpp.FromDEX("../../../tests/data/classes.dex")
if err != nil {
    log.Fatal(err)
}
defer ctx.Close()
xrefs, err := ctx.Xrefs()
if err != nil {
    log.Fatal(err)
}

for _, group := range xrefs.MethodRefsByName("println") {
    for _, site := range group.Sites {
        caller, _ := xrefs.ReferrerID(site.Referrer)
        called := group.Target.ClassDescriptor + " " + group.Target.Name
        fmt.Println(called, "is called by", caller.Name, "at", site.CodeOffset)
    }
}
Ljava/io/PrintStream; println is called by main at 6
Path path = Path.of("../../tests/data/classes.dex");
try (AnalysisContext ctx = AnalysisContext.fromDex(path);
        Xrefs xrefs = ctx.xrefs()) {
    for (MethodRefGroup group : xrefs.methodRefsByName("println")) {
        for (MethodXref site : group.sites()) {
            MethodId caller = xrefs.referrerId(site.referrer()).orElseThrow();
            String called = group.target().classDescriptor() + " " + group.target().name();
            System.out.println(called + " is called by " + caller.name()
                    + " at " + site.codeOffset());
        }
    }
}
Ljava/io/PrintStream; println is called by main at 6

method_refs_by_name finds calls by the bare method name, in any class and with any prototype. It is the quick way to find every call to exec, loadUrl or getInstance. Each result pairs the exact MethodId that was called with its sites. The results come in no fixed order.

method_refs(id) takes an exact MethodId instead.

Method references are literal: a site is listed under the target that the bytecode names. A call to Animal.sound is not listed under Dog.sound. Use the call graph when you need virtual dispatch.

The referrer

A site's referrer is a number. There are three ways to use it:

To get Python Go Java
the referrer's MethodId xrefs.referrer_id(r) or xrefs.referrers[r] xrefs.ReferrerID(r) xrefs.referrerId(r)
the Method itself xrefs.referrer_method(r) xrefs.ReferrerMethod(r) xrefs.referrerMethod(r)
every referrer's MethodId, by number xrefs.referrers xrefs.Referrers() xrefs.referrers()

In Python, xrefs.referrers is a view that copies nothing, so xrefs.referrers[site.referrer] is cheap inside a loop. In Go and Java, Referrers() copies the whole table, so call it once, or use ReferrerID (Java: referrerId) for one number. Use the Method when you need more than the identity.

Who loads a string

loaded: list[str] = xrefs.referenced_strings()
print(loaded)

string_sites: list[dexpp.StringXref] = xrefs.string_refs("Hello Dex++!!")
for string_site in string_sites:
    method: dexpp.Method | None = xrefs.referrer_method(string_site.referrer)
    assert method is not None
    print("loaded in", method.declaring_class.descriptor, method.name)
['Hello Dex++!!']
loaded in LTestDex; helloDex
loaded := xrefs.ReferencedStrings()
fmt.Println(loaded)

for _, site := range xrefs.StringRefs("Hello Dex++!!") {
    method := xrefs.ReferrerMethod(site.Referrer)
    if method == nil {
        log.Fatal("no method for referrer ", site.Referrer)
    }
    fmt.Println("loaded in", method.DeclaringClass().Descriptor(), method.Name())
}
[Hello Dex++!!]
loaded in LTestDex; helloDex
List<String> loaded = xrefs.referencedStrings();
System.out.println(loaded);

for (StringXref site : xrefs.stringRefs("Hello Dex++!!")) {
    DexMethod method = xrefs.referrerMethod(site.referrer()).orElseThrow();
    System.out.println("loaded in " + method.declaringClass().descriptor() + " "
            + method.name());
}
[Hello Dex++!!]
loaded in LTestDex; helloDex

referenced_strings() (Go: ReferencedStrings()) lists every distinct string that the code loads, in no fixed order. string_refs matches the whole string exactly. To search by substring or pattern, go through referenced_strings() first, then look up the ones that match:

greetings_ctx: dexpp.AnalysisContext = dexpp.AnalysisContext.from_dex("tests/data/multistring.dex")
greetings: dexpp.Xrefs = greetings_ctx.xrefs

world: re.Pattern[str] = re.compile(r"World!$")
values: list[str] = sorted(greetings.referenced_strings())  # in no fixed order
for value in values:
    if world.search(value) is not None:
        for pattern_site in greetings.string_refs(value):
            loader: dexpp.MethodId = greetings.referrers[pattern_site.referrer]
            print(repr(value), "loaded by", loader.name, "at", pattern_site.code_offset)
'Goodbye, World!' loaded by <clinit> at 4
'Hello, World!' loaded by <clinit> at 0
greetingsCtx, err := dexpp.FromDEX("../../../tests/data/multistring.dex")
if err != nil {
    log.Fatal(err)
}
defer greetingsCtx.Close()
greetings, err := greetingsCtx.Xrefs()
if err != nil {
    log.Fatal(err)
}

world := regexp.MustCompile(`World!$`)
values := greetings.ReferencedStrings() // in no fixed order
sort.Strings(values)
for _, value := range values {
    if world.MatchString(value) {
        for _, site := range greetings.StringRefs(value) {
            loader, _ := greetings.ReferrerID(site.Referrer)
            fmt.Printf("%q loaded by %s at %d\n", value, loader.Name, site.CodeOffset)
        }
    }
}
"Goodbye, World!" loaded by <clinit> at 4
"Hello, World!" loaded by <clinit> at 0
Path multistring = Path.of("../../tests/data/multistring.dex");
try (AnalysisContext greetingsCtx = AnalysisContext.fromDex(multistring);
        Xrefs greetings = greetingsCtx.xrefs()) {
    Pattern world = Pattern.compile("World!$");
    // The strings come in no fixed order, so sort them.
    List<String> values = greetings.referencedStrings().stream().sorted().toList();
    for (String value : values) {
        if (world.matcher(value).find()) {
            for (StringXref site : greetings.stringRefs(value)) {
                MethodId loader = greetings.referrerId(site.referrer()).orElseThrow();
                System.out.println("\"" + value + "\" loaded by " + loader.name()
                        + " at " + site.codeOffset());
            }
        }
    }
}
"Goodbye, World!" loaded by <clinit> at 4
"Hello, World!" loaded by <clinit> at 0

Who reads or writes a field

out: dexpp.FieldId = dexpp.FieldId("Ljava/lang/System;", "out", "Ljava/io/PrintStream;")
reads: list[dexpp.FieldXref] = xrefs.field_reads(out)
writes: list[dexpp.FieldXref] = xrefs.field_writes(out)
print(len(reads), "reads,", len(writes), "writes")
1 reads, 0 writes
out := dexpp.FieldID{
    ClassDescriptor: "Ljava/lang/System;", Name: "out", Type: "Ljava/io/PrintStream;",
}
reads := xrefs.FieldReads(out)
writes := xrefs.FieldWrites(out)
fmt.Println(len(reads), "reads,", len(writes), "writes")
1 reads, 0 writes
FieldId out = new FieldId("Ljava/lang/System;", "out", "Ljava/io/PrintStream;");
List<FieldXref> reads = xrefs.fieldReads(out);
List<FieldXref> writes = xrefs.fieldWrites(out);
System.out.println(reads.size() + " reads, " + writes.size() + " writes");
1 reads, 0 writes

field_refs returns reads and writes together. Each site says whether it is a write and whether the field is static (Python is_write and is_static, Go IsWrite and IsStatic, Java isWrite() and isStatic()).

Who uses a type

pets_ctx: dexpp.AnalysisContext = dexpp.AnalysisContext.from_dex("tests/data/polymorphic.dex")
pets: dexpp.Xrefs = pets_ctx.xrefs

type_sites: list[dexpp.TypeXref] = pets.type_refs("Ljava/lang/StringBuilder;")
for type_site in type_sites:
    user: dexpp.MethodId = pets.referrers[type_site.referrer]
    print(type_site.kind.name, "in", user.class_descriptor, user.name, "at", type_site.code_offset)
NEW_INSTANCE in LPet; describe at 0
NEW_INSTANCE in LDog; describe at 0
petsCtx, err := dexpp.FromDEX("../../../tests/data/polymorphic.dex")
if err != nil {
    log.Fatal(err)
}
defer petsCtx.Close()
pets, err := petsCtx.Xrefs()
if err != nil {
    log.Fatal(err)
}

for _, site := range pets.TypeRefs("Ljava/lang/StringBuilder;") {
    user, _ := pets.ReferrerID(site.Referrer)
    fmt.Println(site.Kind, "in", user.ClassDescriptor, user.Name, "at", site.CodeOffset)
}
new-instance in LPet; describe at 0
new-instance in LDog; describe at 0
Path polymorphic = Path.of("../../tests/data/polymorphic.dex");
try (AnalysisContext petsCtx = AnalysisContext.fromDex(polymorphic);
        Xrefs pets = petsCtx.xrefs()) {
    for (TypeXref site : pets.typeRefs("Ljava/lang/StringBuilder;")) {
        MethodId user = pets.referrerId(site.referrer()).orElseThrow();
        System.out.println(site.kind() + " in " + user.classDescriptor() + " "
                + user.name() + " at " + site.codeOffset());
    }
}
NEW_INSTANCE in LPet; describe at 0
NEW_INSTANCE in LDog; describe at 0

The kind of a site says what the instruction does with the type, such as NEW_INSTANCE (Go: dexpp.TypeUseNewInstance, printed as new-instance). For NEW_ARRAY the descriptor is the array type, such as [I.

What is not indexed

  • invoke-custom call sites.
  • The operands of const-method-handle and const-method-type.
  • Types that appear only in a signature, a field type or an annotation. Only instructions are indexed.
  • The code of a later definition of a class that is defined in more than one loaded file. Only the first definition, the one a lookup by descriptor returns, is indexed, because Android never loads the others.