Call graph¶
The call graph says which method can call which. It covers every method of
every loaded DEX file. It is built the first time you ask the analysis context
for it (Python ctx.call_graph, Go ctx.CallGraph(), Java
ctx.callGraph()), and kept after that.
The examples come in Python, Go and Java. Pick your language in the tabs. Each
example uses a small label helper that writes a node as its class and its
method name; the first example defines 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
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
}
/** 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");
}
}
Nodes and edges¶
A node is a method. Its id is its MethodId, and its kind says what the
node stands for:
DEFINED: a method defined in a loaded file.EXTERNAL: a method the app calls but does not contain, such as a framework method.CALL_SITE: aninvoke-customcall site (see What the graph does not model). Its id is opaque: it only keeps call sites apart and names no method.
In Python and Java the kinds are CallNodeKind.DEFINED and so on. In Go they
are dexpp.CallNodeDefined, dexpp.CallNodeExternal and
dexpp.CallNodeCallSite, and they print in lower case.
An edge is one call site: one invoke instruction in the caller, at the edge's code offset, pointing at a callee.
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)
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)
}
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());
}
The bindings reach nodes and edges in two ways:
- In Python, nodes and edges are objects that know their neighbours.
node.out_edgesare the calls the method makes,node.in_edgesthe calls into it, andedge.callerandedge.calleeare nodes. - In Go and Java, nodes and edges are numbered. A node or an edge is a
plain value that holds its own number (
Index, Javaindex()) and the numbers of its neighbours. The methods of the graph take numbers and return numbers, andNode(i)andEdge(i)(Java:node(i),edge(i)) give the node or the edge with a number.
| What | Python | Go | Java |
|---|---|---|---|
| the node of a method, or nothing | graph.find(id) |
graph.Find(id) |
graph.find(id) |
| the calls a method makes | node.out_edges |
graph.OutEdges(node.Index) |
graph.outEdges(node.index()) |
| the calls into a method | node.in_edges |
graph.InEdges(node.Index) |
graph.inEdges(node.index()) |
| the caller and the callee of an edge | edge.caller, edge.callee |
edge.CallerNode, edge.CalleeNode (numbers) |
edge.callerNode(), edge.calleeNode() (numbers) |
the Method behind a DEFINED node |
node.method |
graph.MethodFor(node.Index) |
graph.methodFor(node.index()) |
findgives nothing when the graph has no node for the method:Nonein Python,falseas the second result in Go, an emptyOptionalin Java.- The kind of an edge is the kind of invoke:
VIRTUAL,SUPER,DIRECT,STATIC,INTERFACE,POLYMORPHICorCUSTOM(Go:dexpp.InvokeVirtualand so on, printed in lower case). - The method behind a node is absent for the other kinds of node:
Nonein Python,nilin Go, an emptyOptionalin Java.
Virtual dispatch¶
The bytecode of Kennel.noise calls Animal.sound. Animal is an interface,
so at runtime the call lands in whatever class the object really has: Dog or
Cat. The edge above only shows the declared target, Animal.sound.
The graph also knows the possible runtime targets. It finds them with class-hierarchy analysis: it looks at every loaded class below the declared one and collects the methods a call could land in.
sound_id: dexpp.MethodId = dexpp.MethodId("LAnimal;", "sound", "()Ljava/lang/String;")
sound: dexpp.CallNode | None = graph.find(sound_id)
assert sound is not None
targets: dexpp.CallNodeView = sound.dispatch_targets
callees: dexpp.CallNodeView = noise.callees()
print(sorted(label(target) for target in targets))
print(sorted(label(callee) for callee in callees))
soundID := dexpp.MethodID{
ClassDescriptor: "LAnimal;", Name: "sound", Proto: "()Ljava/lang/String;",
}
sound, ok := graph.Find(soundID)
if !ok {
log.Fatal("no node for Animal.sound")
}
var targets, callees []string
for _, index := range graph.DispatchTargets(sound.Index) {
targets = append(targets, label(index))
}
for _, index := range graph.Callees(noise.Index) {
callees = append(callees, label(index))
}
sort.Strings(targets)
sort.Strings(callees)
fmt.Println(targets)
fmt.Println(callees)
MethodId soundId = new MethodId("LAnimal;", "sound", "()Ljava/lang/String;");
CallNode sound = graph.find(soundId).orElseThrow();
List<String> targets =
graph.dispatchTargets(sound.index()).stream()
.map((Integer index) -> label(graph, index))
.sorted()
.toList();
List<String> callees =
graph.callees(noise.index()).stream()
.map((Integer index) -> label(graph, index))
.sorted()
.toList();
System.out.println(targets);
System.out.println(callees);
| What | Python | Go | Java |
|---|---|---|---|
| the methods a call declared against a node may run | node.dispatch_targets |
graph.DispatchTargets(i) |
graph.dispatchTargets(i) |
| the declared methods through which a call can reach a node | node.dispatch_sources |
graph.DispatchSources(i) |
graph.dispatchSources(i) |
| what a method can call, dispatch included | node.callees() |
graph.Callees(i) |
graph.callees(i) |
| who can call a method, dispatch included | node.callers() |
graph.Callers(i) |
graph.callers(i) |
- The dispatch targets are the other methods that a virtual or interface call declared against the node may run.
- The dispatch sources are the reverse: the declared methods through which a call can reach the node.
- The callees are the simple answer to "what can this method call": the callee of each outgoing edge plus the dispatch targets of each virtual or interface call.
- The callers are the simple answer to "who can call this method", with dispatch included.
The graph stores the dispatch targets and sources, so reading them is cheap.
The callees and the callers are collected again on each call: the library
goes through the edges, adds the dispatch targets, removes the duplicates and
sorts the result. For a method that is called from many places, the callers
go through every one of those call sites. Keep the result when you need it
more than once. (In Python this is why dispatch_targets is a property, but
callees() and callers() are methods.)
dogSoundID := dexpp.MethodID{
ClassDescriptor: "LDog;", Name: "sound", Proto: "()Ljava/lang/String;",
}
dogSound, ok := graph.Find(dogSoundID)
if !ok {
log.Fatal("no node for Dog.sound")
}
var callers []string
for _, index := range graph.Callers(dogSound.Index) {
callers = append(callers, label(index))
}
sort.Strings(callers)
fmt.Println(callers)
Dog.sound has no direct call from Kennel.noise or Pet.describe in the
bytecode. They appear because their calls to Animal.sound can dispatch to
it.
Why dispatch targets are not edges
The dispatch targets depend only on the declared method, not on the call
site. So they are stored once per method and shared by all its call sites.
Stored as edges, a popular method such as Object.toString() would repeat
its whole list of overrides at every call. On a large app that is hundreds
of millions of edges.
Class-hierarchy analysis is an over-approximation. It lists every method the call could reach given the classes in the app, not the ones it reaches in a real run.
Calls to a method the class inherits¶
Sometimes the bytecode names a class that does not define the method itself.
Pet.describe calls sound() on itself, and the bytecode says Pet.sound.
But Pet has no sound method: it inherits the declaration from Animal.
For such a call site the graph adds a second edge, to the nearest definition a loaded ancestor provides. This is the method Android would find at runtime.
Each edge has an origin (Python and Java EdgeOrigin.DECLARED and so on, Go
dexpp.EdgeDeclared and dexpp.EdgeInheritedResolution):
DECLARED: the target exactly as the bytecode names it. Every call site has exactly one.INHERITED_RESOLUTION: the definition found by walking up the superclass chain, then the interfaces. A call site has at most one. It always points at aDEFINEDnode.
When no loaded ancestor defines the method, there is no second edge and the
declared node stays EXTERNAL. This is the normal case for a call that ends
in a framework class.
External methods¶
var external []string
var first dexpp.CallNode
for _, node := range graph.Nodes() {
if node.Kind == dexpp.CallNodeExternal {
if len(external) == 0 {
first = node
}
external = append(external, label(node.Index))
}
}
sort.Strings(external)
fmt.Println(external)
noMethod := graph.MethodFor(first.Index)
fmt.Println(noMethod)
List<CallNode> external =
graph.nodes().stream()
.filter((CallNode node) -> node.kind() == CallNodeKind.EXTERNAL)
.toList();
System.out.println(
external.stream()
.map((CallNode node) -> label(graph, node.index()))
.sorted()
.toList());
Optional<DexMethod> noMethod = graph.methodFor(external.get(0).index());
System.out.println(noMethod);
LPet;->sound is in this list for the reason above: no method with exactly
that identity exists. The others are Java library methods.
Filtering edges¶
A large app has millions of call sites. Going through all of them in your own code is slow, in Python most of all. The graph can filter them inside the library:
| Language | Filter | Result |
|---|---|---|
| Python | edges.where(origin=..., kind=...); leave out a filter to match any value |
a view of the matching edges |
| Go | graph.EdgesWhere(origin, kind); pass dexpp.AnyEdgeOrigin or dexpp.AnyInvokeKind to match any value |
the numbers of the matching edges |
| Java | graph.edgesWhere(origin, kind), edgesWhere(origin) or edgesWhere(kind); null matches any value |
the numbers of the matching edges |
Filtering on the origin DECLARED gives exactly one edge per call site. In
Python, where works on graph.edges and on a node's out_edges and
in_edges.
Views and copies¶
- In Python,
graph.nodes,graph.edges, and the node lists such asdispatch_targetsand the result ofcallers()are read-only sequences that do not copy the graph. Indexing, slicing,len()and iteration work as on a list. Nodes and edges compare equal when they are the same node or edge of the same graph, and they can be put in sets and used as dictionary keys. - In Go and Java,
Nodes()andEdges()(Java:nodes(),edges()) copy the whole table, so call them once, not inside a loop.Node(i)andEdge(i)copy one entry.NodeCount()andEdgeCount()(Java:nodeCount(),edgeCount()) give the sizes without copying. The lists of numbers that the other methods return are copies too.
What the graph does not model¶
- Reflection. A method called through
Method.invokehas no edge. invoke-custom(lambdas and string concatenation on newer compilers). Each call site becomes a node of its own, of kindCALL_SITE. The graph does not follow it to the method the call site is bound to, such as a lambda body.invoke-polymorphic. Only the declaredMethodHandletarget is recorded.- Framework callbacks. Android calls methods such as
onCreateitself. Nothing in the app calls them, so they have no callers in the graph.
When the same class is defined in more than one loaded DEX file, the first
definition wins, as on Android. "First" means the earliest DEX file in load
order: for an APK, classes.dex, then classes2.dex, and so on. An Android
class loader searches the DEX files in that order and stops at the first one
that defines the class, so a later definition is never loaded and its code
never runs. The graph does the same:
- only the first definition's methods are
DEFINEDnodes, and the method behind such a node is the method of that definition; - only the code of that definition adds edges. A method that only a later definition has gets no node from it, and calls made in a later definition's code are not in the graph.
Looking up a class by descriptor, the class hierarchy and the cross-references use the same definition. The list of every class still lists every definition.