Classes, methods and bytecode¶
An analysis context holds the code: one or more DEX files, loaded together.
Python and Java call it AnalysisContext; in Go it is a *dexpp.Context. You
load it from an APK, from one DEX file or from several, or you get it from an
opened APK with its analysis() method (Go: Analysis()).
The examples come in Python, Go and Java. Pick your language in the tabs.
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()))
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()))
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());
}
Loading an APK takes every top-level classes*.dex entry in multidex order:
classes.dex, classes2.dex, classes3.dex, and so on.
How the names differ¶
The three bindings have the same parts, named in the style of each language. In this guide, a name in the text is the Python one, and the tables give all three. The rules are simple:
- A Python property, such as
cls.methods, is a method in Go and Java:cls.Methods()andcls.methods(). - Python uses
snake_case, Go usesCamelCase, Java usescamelCase:find_class,FindClass,findClass. - A lookup that may find nothing returns
Nonein Python. In Go it returnsnilwhen the result is a handle, such as a class, and otherwise a secondboolresult that isfalse. In Java it returns an emptyOptional.
Classes¶
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)
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)
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);
}
| What | Python | Go | Java |
|---|---|---|---|
| every class | ctx.classes() |
ctx.Classes() |
ctx.classes() |
| one class by descriptor | ctx.find_class(d) |
ctx.FindClass(d) |
ctx.findClass(d) |
| the class's descriptor | cls.descriptor |
cls.Descriptor() |
cls.descriptor() |
| its package | cls.package |
cls.Package() |
cls.packageName() |
| its superclass | cls.superclass |
cls.Superclass() |
cls.superclass() |
| its interfaces | cls.interfaces |
cls.Interfaces() |
cls.interfaces() |
| its fields | cls.fields |
cls.Fields() |
cls.fields() |
classes()returns every class of every loaded file, in file order. Each call makes a new list with a new class object for every class. On a large app that is a lot of objects, so keep the list when you need it more than once.find_class(descriptor)returns one class, or nothing. So the example checks the result before it uses it.- The descriptor of a class is the name the DEX format gives it, such as
Lcom/example/Foo;. The package is in Java source form,com.example, the same form as the manifest's package name, so the two can be compared directly: a class is in the app's package, or below it, when the two are equal or the class's package starts with the app's package and a dot. The package is an empty string for a class in the default package. - A class can be defined in more than one loaded file. Then
classes()lists every definition, andfind_classreturns the first one: the definition in the earliest file, in load order. Android does the same. An app's class loader searches its DEX files in multidex order and stops at the first one that defines the class, so a later definition is never loaded. The call graph, the class hierarchy and the cross-references also use only the first definition. - The superclass and the interfaces are class references (
ClassRef), not classes. The superclass is often a framework class that is not in the file, so a reference only carries the descriptor. Callresolve()on a reference (Go:Resolve()) to get the class when it is loaded. When it is not loaded, there is no class:Nonein Python,nilin Go, an emptyOptionalin Java.
Methods and fields¶
for method in circle.methods:
visibility: str = "public" if method.is_public is True else "non-public"
print(visibility, method.name, method.parameters, "->", method.return_type)
constructor: dexpp.Method = circle.methods[0]
flags: dexpp.AccessFlags = constructor.access_flags
print(constructor.name, int(flags), dexpp.AccessFlags.CONSTRUCTOR in flags)
for _, method := range circle.Methods() {
visibility := "non-public"
if method.IsPublic() {
visibility = "public"
}
fmt.Println(visibility, method.Name(), method.Parameters(), "->", method.ReturnType())
}
constructor := circle.Methods()[0]
flags := constructor.AccessFlags()
fmt.Println(constructor.Name(), uint32(flags), flags.Has(dexpp.AccessConstructor))
for (DexMethod method : circle.methods()) {
String visibility = method.isPublic() ? "public" : "non-public";
System.out.println(visibility + " " + method.name() + " " + method.parameters()
+ " -> " + method.returnType());
}
DexMethod constructor = circle.methods().get(0);
AccessFlags flags = constructor.accessFlags();
System.out.println(constructor.name() + " " + flags.value() + " "
+ flags.has(AccessFlags.CONSTRUCTOR));
A class's methods list the direct methods first (constructors, static and
private methods), then the virtual ones. Constructors are named <init>, and
the static initializer is named <clinit>.
has_code (Go: HasCode(), Java: hasCode()) is false for abstract and
native methods. For those, the instruction list is empty and the control-flow
graph has no blocks.
The access flags hold one bit per DEX flag, such as public or
constructor. Each language tests a flag in its own way:
| Language | Type | Test a flag |
|---|---|---|
| Python | dexpp.AccessFlags, an enum.IntFlag |
dexpp.AccessFlags.CONSTRUCTOR in flags |
| Go | dexpp.AccessFlags, a uint32 |
flags.Has(dexpp.AccessConstructor) |
| Java | AccessFlags, a record around an int |
flags.has(AccessFlags.CONSTRUCTOR) |
In all three, the flags are also a plain number: int(flags) in Python,
uint32(flags) in Go, flags.value() in Java. Methods such as is_public,
is_static and is_final (Go: IsPublic(), Java: isPublic(), and so on)
are shortcuts for single flags.
Bytecode¶
A method's instructions are its decoded bytecode. to_string (Go:
dexpp.ToString, Java: Dexpp.toString) renders one instruction as text.
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));
}
The library decodes a method's bytecode once, the first time you ask, and keeps it. How you read it depends on the language:
- In Python,
method.instructionsis adexpp.InstructionView: a read-only sequence that copies nothing up front and builds each instruction when you read it. It supportslen(), indexing, slicing and iteration, like a list. - In Go,
method.Instructions()returns a slice, and in Java,method.instructions()returns a list. Each call copies every instruction into new values, so keep the result when you need it more than once. The same is true for the control-flow graph below.
The text shows constant-pool operands as raw indices, such as field@1 or
string@12. An instruction alone has no context to turn them into names. To
get names, use the resolved lists below.
Each instruction has one of 28 types, one per family of opcodes:
InvokeInstruction, FieldInstruction, ConstStringInstruction,
IfInstruction and so on. The names are the same in the three languages. An
opcode the format does not use, as in a damaged method, becomes an
InvalidInstruction. To tell the types apart, Python uses isinstance, Go a
type switch or a type assertion, and Java pattern matching (instanceof or a
switch). Every instruction has the fields they all share:
| Field | Python | Go | Java |
|---|---|---|---|
| the position in the method, in code units | base.offset |
Base().Offset |
offset() |
| the raw opcode byte | base.opcode |
Base().Opcode |
opcode() |
| the length of the instruction, in code units | base.size |
Base().Size |
size() |
opcode_name (Go: dexpp.OpcodeName, Java: Dexpp.opcodeName) gives the
name of an opcode byte.
What a method refers to¶
Most analyses do not need raw instructions. They need to know what a method calls, which fields it touches, which strings it loads and which types it uses. A method answers these directly, with names already resolved:
for instruction in instructions:
if isinstance(instruction, dexpp.FieldInstruction):
action: str = "write" if instruction.is_write is True else "read"
print("field access at", instruction.base.offset, action)
calls: list[dexpp.MethodCall] = area.calls()
accesses: list[dexpp.FieldAccess] = area.field_accesses()
print([(call.target.class_descriptor, call.target.name) for call in calls])
print([(access.field.name, access.is_write) for access in accesses])
for _, instruction := range instructions {
if field, ok := instruction.(dexpp.FieldInstruction); ok {
action := "read"
if field.IsWrite {
action = "write"
}
fmt.Println("field access at", field.Offset, action)
}
}
called := []string{}
for _, call := range area.Calls() {
called = append(called, call.Target.ClassDescriptor+" "+call.Target.Name)
}
accessed := []string{}
for _, access := range area.FieldAccesses() {
accessed = append(accessed, fmt.Sprintf("%s write=%v", access.Field.Name, access.IsWrite))
}
fmt.Println(called)
fmt.Println(accessed)
for (Instruction instruction : instructions) {
if (instruction instanceof FieldInstruction field) {
String action = field.isWrite() ? "write" : "read";
System.out.println("field access at " + field.offset() + " " + action);
}
}
List<String> called =
area.calls().stream()
.map((MethodCall call) ->
call.target().classDescriptor() + " " + call.target().name())
.toList();
List<String> accessed =
area.fieldAccesses().stream()
.map((FieldAccess access) ->
access.field().name() + " write=" + access.isWrite())
.toList();
System.out.println(called);
System.out.println(accessed);
| Python | Go | Java | One entry per | Fields |
|---|---|---|---|---|
calls() |
Calls() |
calls() |
invoke instruction | the target (a MethodId), the kind, the code offset |
field_accesses() |
FieldAccesses() |
fieldAccesses() |
field read or write | the field (a FieldId), whether it is a write, whether it is static, the code offset |
string_loads() |
StringLoads() |
stringLoads() |
const-string |
the value, the code offset |
type_uses() |
TypeUses() |
typeUses() |
const-class, check-cast, instance-of, new-instance, new-array, filled-new-array |
the descriptor, the kind, the code offset |
Each call goes through the method's bytecode again, resolves the names again
and makes a new list. So keep the list when you need it more than once. For
example, do not call calls() again for each entry inside a loop.
calls() gives the target exactly as the bytecode names it. It does not
follow inheritance or virtual dispatch. The call graph does
that.
These are the forward direction: from a method to what it uses. For the other direction, from a method, field, string or type to its users, see cross-references.
Registers¶
Dalvik is a register machine. Each method has a fixed number of registers, and its arguments arrive in the last ones.
register_count (Go: RegisterCount(), Java: registerCount()) is the
number of registers. parameter_registers (Go: ParameterRegisters(), Java:
parameterRegisters()) lists the incoming arguments in order. For an instance
method the first entry is this. A long or double argument takes two
registers: reg and reg + 1, and its is_wide is true. Both are 0 or empty
for a method without code.
Control-flow graph¶
A method's control-flow graph (Python method.cfg, Go method.Cfg(), Java
method.cfg()) splits the bytecode into basic blocks. A basic block is a run
of instructions that is always executed from its first instruction to its
last.
fibonacci_ctx: dexpp.AnalysisContext = dexpp.AnalysisContext.from_dex("tests/data/fibonacci.dex")
fibonacci: dexpp.Class | None = fibonacci_ctx.find_class("LFibonacci;")
assert fibonacci is not None
compute: dexpp.Method = next(m for m in fibonacci.methods if m.name == "compute")
cfg: dexpp.Cfg = compute.cfg
for block in cfg.blocks:
edges: list[tuple[str, int]] = [(e.kind.name, e.target_block) for e in block.successors]
print(f"block {block.index} [{block.start_offset:#x}, {block.end_offset:#x})", edges)
block 0 [0x0, 0x2) [('BRANCH_TAKEN', 2), ('BRANCH_NOT_TAKEN', 1)]
block 1 [0x2, 0x5) []
block 2 [0x5, 0x9) [('BRANCH_TAKEN', 4), ('BRANCH_NOT_TAKEN', 3)]
block 3 [0x9, 0xa) []
block 4 [0xa, 0x14) [('FALLTHROUGH', 5)]
block 5 [0x14, 0x16) [('BRANCH_TAKEN', 7), ('BRANCH_NOT_TAKEN', 6)]
block 6 [0x16, 0x20) [('GOTO', 5)]
block 7 [0x20, 0x23) []
fibonacciCtx, err := dexpp.FromDEX("../../../tests/data/fibonacci.dex")
if err != nil {
log.Fatal(err)
}
defer fibonacciCtx.Close()
fibonacci := fibonacciCtx.FindClass("LFibonacci;")
if fibonacci == nil {
log.Fatal("no Fibonacci class")
}
var compute *dexpp.Method
for _, method := range fibonacci.Methods() {
if method.Name() == "compute" {
compute = method
}
}
for _, block := range compute.Cfg().Blocks {
edges := []string{}
for _, edge := range block.Successors {
edges = append(edges, fmt.Sprintf("%v->%d", edge.Kind, edge.TargetBlock))
}
fmt.Printf("block %d [%#x, %#x) %v\n", block.Index, block.StartOffset, block.EndOffset, edges)
}
block 0 [0x0, 0x2) [branch-taken->2 branch-not-taken->1]
block 1 [0x2, 0x5) []
block 2 [0x5, 0x9) [branch-taken->4 branch-not-taken->3]
block 3 [0x9, 0xa) []
block 4 [0xa, 0x14) [fallthrough->5]
block 5 [0x14, 0x16) [branch-taken->7 branch-not-taken->6]
block 6 [0x16, 0x20) [goto->5]
block 7 [0x20, 0x23) []
Path fibonacciPath = Path.of("../../tests/data/fibonacci.dex");
try (AnalysisContext fibonacciCtx = AnalysisContext.fromDex(fibonacciPath)) {
DexClass fibonacci = fibonacciCtx.findClass("LFibonacci;").orElseThrow();
DexMethod compute =
fibonacci.methods().stream()
.filter((DexMethod method) -> method.name().equals("compute"))
.findFirst()
.orElseThrow();
for (BasicBlock block : compute.cfg().blocks()) {
List<String> edges =
block.successors().stream()
.map((CfgEdge edge) -> edge.kind() + "->" + edge.targetBlock())
.toList();
System.out.printf("block %d [%#x, %#x) %s%n",
block.index(), block.startOffset(), block.endOffset(), edges);
}
}
block 0 [0x0, 0x2) [BRANCH_TAKEN->2, BRANCH_NOT_TAKEN->1]
block 1 [0x2, 0x5) []
block 2 [0x5, 0x9) [BRANCH_TAKEN->4, BRANCH_NOT_TAKEN->3]
block 3 [0x9, 0xa) []
block 4 [0xa, 0x14) [FALLTHROUGH->5]
block 5 [0x14, 0x16) [BRANCH_TAKEN->7, BRANCH_NOT_TAKEN->6]
block 6 [0x16, 0x20) [GOTO->5]
block 7 [0x20, 0x23) []
- Blocks are ordered by offset, and block 0 is the entry.
first_insnandinsn_count(Go:FirstInsn,InsnCount; Java:firstInsn(),insnCount()) say which entries of the method's instruction list belong to the block.successorsare the outgoing edges. An edge has atarget_blockindex and akind:FALLTHROUGH,GOTO,BRANCH_TAKEN,BRANCH_NOT_TAKEN,SWITCH_CASE,SWITCH_DEFAULT,EXCEPTIONorEXCEPTION_CATCH_ALL. In Go the kinds are constants such asdexpp.CfgBranchTaken, and they print in lower case, asbranch-taken.predecessorsare the indices of the blocks that lead here.is_handler_entryis true for the first block of a catch handler.
A block with no successors ends the method: it returns or throws.
Two kinds of edge carry one more value. A SWITCH_CASE edge has a case_key:
the value that case of the switch matches. An EXCEPTION edge goes to the
handler of one exception class, and its catch_type is the descriptor of that
class. An EXCEPTION_CATCH_ALL edge goes to a handler that catches every
exception, which is how Java compiles finally, so it has no catch_type.
On every other edge both values are absent: None in Python, an empty
Optional in Java. In Go, CaseKey and CatchType are plain fields that
hold 0 and "" on the other edges, so check the kind first.
parse_ctx: dexpp.AnalysisContext = dexpp.AnalysisContext.from_dex("tests/data/trycatch.dex")
parse_class: dexpp.Class | None = parse_ctx.find_class("LTryCatch;")
assert parse_class is not None
safe_parse: dexpp.Method = next(m for m in parse_class.methods if m.name == "safeParse")
for block in safe_parse.cfg.blocks:
for edge in block.successors:
if edge.kind is dexpp.CfgEdgeKind.EXCEPTION:
print(f"block {block.index} -> {edge.target_block}: catches {edge.catch_type}")
elif edge.kind is dexpp.CfgEdgeKind.EXCEPTION_CATCH_ALL:
print(f"block {block.index} -> {edge.target_block}: catches everything")
parseCtx, err := dexpp.FromDEX("../../../tests/data/trycatch.dex")
if err != nil {
log.Fatal(err)
}
defer parseCtx.Close()
parseClass := parseCtx.FindClass("LTryCatch;")
if parseClass == nil {
log.Fatal("no TryCatch class")
}
var safeParse *dexpp.Method
for _, method := range parseClass.Methods() {
if method.Name() == "safeParse" {
safeParse = method
}
}
for _, block := range safeParse.Cfg().Blocks {
for _, edge := range block.Successors {
switch edge.Kind {
case dexpp.CfgException:
fmt.Printf("block %d -> %d: catches %s\n", block.Index, edge.TargetBlock, edge.CatchType)
case dexpp.CfgExceptionCatchAll:
fmt.Printf("block %d -> %d: catches everything\n", block.Index, edge.TargetBlock)
}
}
}
Path tryCatchPath = Path.of("../../tests/data/trycatch.dex");
try (AnalysisContext parseCtx = AnalysisContext.fromDex(tryCatchPath)) {
DexClass parseClass = parseCtx.findClass("LTryCatch;").orElseThrow();
DexMethod safeParse =
parseClass.methods().stream()
.filter((DexMethod method) -> method.name().equals("safeParse"))
.findFirst()
.orElseThrow();
for (BasicBlock block : safeParse.cfg().blocks()) {
for (CfgEdge edge : block.successors()) {
switch (edge.kind()) {
case EXCEPTION -> System.out.printf("block %d -> %d: catches %s%n",
block.index(), edge.targetBlock(), edge.catchType().orElseThrow());
case EXCEPTION_CATCH_ALL -> System.out.printf(
"block %d -> %d: catches everything%n",
block.index(), edge.targetBlock());
default -> {}
}
}
}
}
Try blocks¶
try_catch_ctx: dexpp.AnalysisContext = dexpp.AnalysisContext.from_dex("tests/data/trycatch.dex")
try_catch: dexpp.Class | None = try_catch_ctx.find_class("LTryCatch;")
assert try_catch is not None
divide: dexpp.Method = next(m for m in try_catch.methods if m.name == "divide")
try_blocks: list[dexpp.TryBlock] = divide.try_blocks
for try_block in try_blocks:
print(f"try [{try_block.start_offset:#x}, {try_block.end_offset:#x})")
for handler in try_block.handlers:
print(" catch", handler.type_descriptor, "at", hex(handler.handler_offset))
print(" catch-all at", try_block.catch_all_offset)
tryCatchCtx, err := dexpp.FromDEX("../../../tests/data/trycatch.dex")
if err != nil {
log.Fatal(err)
}
defer tryCatchCtx.Close()
tryCatch := tryCatchCtx.FindClass("LTryCatch;")
if tryCatch == nil {
log.Fatal("no TryCatch class")
}
var divide *dexpp.Method
for _, method := range tryCatch.Methods() {
if method.Name() == "divide" {
divide = method
}
}
for _, tryBlock := range divide.TryBlocks() {
fmt.Printf("try [%#x, %#x)\n", tryBlock.StartOffset, tryBlock.EndOffset)
for _, handler := range tryBlock.Handlers {
fmt.Printf(" catch %s at %#x\n", handler.TypeDescriptor, handler.HandlerOffset)
}
if tryBlock.HasCatchAll {
fmt.Printf(" catch-all at %#x\n", tryBlock.CatchAllOffset)
} else {
fmt.Println(" no catch-all")
}
}
Path tryCatchPath = Path.of("../../tests/data/trycatch.dex");
try (AnalysisContext tryCatchCtx = AnalysisContext.fromDex(tryCatchPath)) {
DexClass tryCatch = tryCatchCtx.findClass("LTryCatch;").orElseThrow();
DexMethod divide =
tryCatch.methods().stream()
.filter((DexMethod method) -> method.name().equals("divide"))
.findFirst()
.orElseThrow();
for (TryBlock tryBlock : divide.tryBlocks()) {
System.out.printf("try [%#x, %#x)%n", tryBlock.startOffset(), tryBlock.endOffset());
for (CatchHandler handler : tryBlock.handlers()) {
System.out.printf(" catch %s at %#x%n",
handler.typeDescriptor(), handler.handlerOffset());
}
System.out.println(" catch-all at " + tryBlock.catchAllOffset());
}
}
A try block covers the offsets from start_offset up to, but not including,
end_offset. handlers are its typed catch clauses in order.
catch_all_offset is the handler that catches everything, which is how
finally is compiled. When there is none, it is None in Python and an empty
OptionalInt in Java; in Go, HasCatchAll is false.
Annotations and initial values¶
annotated_ctx: dexpp.AnalysisContext = dexpp.AnalysisContext.from_dex("tests/data/annotated.dex")
annotated: dexpp.Class | None = annotated_ctx.find_class("LAnnotated;")
assert annotated is not None
annotations: list[dexpp.Annotation] = annotated.annotations
for annotation in annotations:
print(annotation.type_descriptor, annotation.visibility.name, annotation.elements)
fields: dict[str, dexpp.Field] = {field.name: field for field in annotated.fields}
magic: dexpp.AnnotationValue = fields["MAGIC"].initial_value
greeting: dexpp.AnnotationValue = fields["GREETING"].initial_value
print(magic, repr(greeting))
annotatedCtx, err := dexpp.FromDEX("../../../tests/data/annotated.dex")
if err != nil {
log.Fatal(err)
}
defer annotatedCtx.Close()
annotated := annotatedCtx.FindClass("LAnnotated;")
if annotated == nil {
log.Fatal("no Annotated class")
}
for _, annotation := range annotated.Annotations() {
fmt.Println(annotation.TypeDescriptor, annotation.Visibility)
for _, element := range annotation.Elements {
fmt.Printf(" %s = %v (%T)\n", element.Name, element.Value, element.Value)
}
}
for _, field := range annotated.Fields() {
if field.Name() == "MAGIC" || field.Name() == "GREETING" {
value, _ := field.InitialValue()
fmt.Printf("%s = %v (%T)\n", field.Name(), value, value)
}
}
Path annotatedPath = Path.of("../../tests/data/annotated.dex");
try (AnalysisContext annotatedCtx = AnalysisContext.fromDex(annotatedPath)) {
DexClass annotated = annotatedCtx.findClass("LAnnotated;").orElseThrow();
for (Annotation annotation : annotated.annotations()) {
System.out.println(annotation.typeDescriptor() + " " + annotation.visibility());
for (AnnotationElement element : annotation.elements()) {
String text =
switch (element.value()) {
case AnnotationValue.IntValue(long number) ->
"the number " + number;
case AnnotationValue.StringValue(String string) ->
"the string \"" + string + "\"";
case AnnotationValue.ArrayValue(List<AnnotationValue> items) ->
"an array of " + items.size() + " values";
default -> element.value().toString();
};
System.out.println(" " + element.name() + " = " + text);
}
}
for (DexField field : annotated.fields()) {
if (field.name().equals("MAGIC") || field.name().equals("GREETING")) {
System.out.println(field.name() + " = " + field.initialValue().orElseThrow());
}
}
}
Classes, methods and fields each have a list of annotations. An annotation has
a type descriptor, a visibility and its elements. Python gives the elements
as a dictionary from name to value; Go and Java give a list of name and value
pairs, and Element(name) (Java: element(name)) finds one.
Element values are converted to the plain values of each language:
| Value | Python | Go | Java |
|---|---|---|---|
| null | None |
nil |
NullValue |
| boolean | bool |
bool |
BooleanValue |
| any integer type | int |
int64 |
IntValue |
float or double |
float |
float64 |
FloatValue |
| string | str |
string |
StringValue |
| array | list |
[]AnnotationValue |
ArrayValue |
| nested annotation | Annotation |
Annotation |
Annotation |
In Java, AnnotationValue is a sealed interface and each kind of value is a
record, so record patterns take a value apart, as the example does. In Go,
AnnotationValue is any, so a type switch tells the kinds apart.
Values that refer to something have their own small types, with the same names
in the three languages: TypeValue for a class literal, EnumValue for an
enum constant, FieldValue for a field, MethodValue for a method,
MethodTypeValue for a method prototype, and MethodHandleValue for a method
handle. A method handle reads or writes a field or calls a method: its kind
is a MethodHandleKind such as STATIC_GET or INVOKE_STATIC, and its
member is the FieldId or MethodId it works on.
An element that the source left at its default value is not in the elements. The DEX format stores defaults on the annotation's own class, not at each use.
The initial value of a field (Python field.initial_value, Go
field.InitialValue(), Java field.initialValue()) is the constant a static
field starts with. It is absent when the field has no recorded value, which
means the field starts at its type's default: zero or null.
All strings¶
strings() (Go: Strings()) returns the whole string table of every loaded
file. It includes names of classes, methods and fields, not only the strings
the code loads. The first call decodes the whole table, and every call copies
all of it into a new list, so it is one of the more expensive calls: keep the
result when you need it more than once. For only the strings that the code
loads, use the referenced_strings() of the
cross-references.