How an Android app's code is stored
Java and Kotlin code for Android is compiled to JVM bytecode and then converted by d8 / R8 into Dalvik Executable (DEX) bytecode: one file per up to 65,536 methods, holding every class, its methods and their register-based bytecode. This page describes the format as the DEX tool reads it, and how its decompiler and "Called by" box work.
- In the APK:
classes.dex, classes2.dex, classes3.dex… at the root of the archive.
- On the device, ART compiles DEX ahead of time into
.oat / .odex / .vdex files; when those still hold the DEX files, the tool opens the DEX files inside them.
The format is specified in the AOSP documentation (Dalvik Executable format, Dalvik bytecode, Dalvik instruction formats) and implemented in libdexfile. All values are little-endian.
Contents
- Header
- The id tables
- ULEB128 and MUTF-8
- map_list
- class_def and class_data_item
- code_item
- Try / catch handlers
- Encoded values and annotations
- Instruction formats
- Opcodes
- Smali primer
- Multidex
- The decompiler
- The "Called by" box
- What the tool shows, and its limits
- The DEX library (DexFile, DexProgram)
- The opcode table (DexOpcodes)
- The decompiler library (DexDecompiler)
2The id tables
Six fixed-size tables, each sorted, give every string, type, prototype, field, method and class an index. Instructions refer to them by index (string@0012, method@01a3). They describe everything the file references, including framework classes it doesn't define.
| Table | Entry | Fields |
| string_ids | 4 bytes | string_data_off u32 → a string_data_item (below). Sorted by string value. |
| type_ids | 4 bytes | descriptor_idx u32 → string: a type descriptor such as Ljava/lang/String;. |
| proto_ids | 12 bytes | shorty_idx u32 (e.g. ZLI: returns boolean, takes an object and an int) · return_type_idx u32 (type) · parameters_off u32 → type_list (u32 size, then u16 type indices; 0 = no parameters). |
| field_ids | 8 bytes | class_idx u16 · type_idx u16 · name_idx u32. |
| method_ids | 8 bytes | class_idx u16 · proto_idx u16 · name_idx u32. |
| class_defs | 32 bytes | One per class defined in this file (below). |
The 16-bit method index in invoke instructions is why one DEX file can reference at most 65,536 methods (and fields): the origin of multidex.
3ULEB128 and MUTF-8
LEB128
Variable-length integers, 7 bits per byte, least significant group first; the high bit is set on every byte except the last. At most 5 bytes for 32 bits.
uleb128 80 7f → 0x00 + 0x7f × 128 = 16256
e5 8e 26 → 0x65 + 0x0e × 128 + 0x26 × 16384 = 624485
sleb128 7f → −1 (bit 6 of the last byte is the sign)
uleb128p1 00 → −1 (the value + 1, so −1 = "none" fits in one byte)
string_data_item
A utf16_size (uleb128: the length in UTF-16 code units, not bytes), then the characters in MUTF-8, then a NUL byte. MUTF-8 is UTF-8 with two differences: the character U+0000 is written as the two bytes c0 80 (so the only zero byte is the terminator), and characters above U+FFFF are written as a surrogate pair, each half encoded as 3 bytes (CESU-8 style), instead of one 4-byte sequence.
4map_list
At map_off: a u32 size, then map_items of 12 bytes — type u16, unused u16, size u32 (number of items), offset u32. It lists every section of the file in order, and is what tools use to walk the data section.
| Type | Item | Type | Item |
| 0x0000 | header_item | 0x1000 | map_list |
| 0x0001 | string_id_item | 0x1001 | type_list |
| 0x0002 | type_id_item | 0x1002 | annotation_set_ref_list |
| 0x0003 | proto_id_item | 0x1003 | annotation_set_item |
| 0x0004 | field_id_item | 0x2000 | class_data_item |
| 0x0005 | method_id_item | 0x2001 | code_item |
| 0x0006 | class_def_item | 0x2002 | string_data_item |
| 0x0007 | call_site_id_item | 0x2003 | debug_info_item |
| 0x0008 | method_handle_item | 0x2004 | annotation_item |
| 0xf000 | hiddenapi_class_data_item | 0x2005 · 0x2006 | encoded_array_item · annotations_directory_item |
The tool reads the header's fixed tables directly and shows map_off in the overview; it doesn't decode the map itself.
5class_def and class_data_item
class_def_item (32 bytes)
| Offset | Field | Meaning |
| +0 | class_idx | Type of this class. |
| +4 | access_flags | 0x1 public, 0x10 final, 0x200 interface, 0x400 abstract, 0x1000 synthetic, 0x2000 annotation, 0x4000 enum. |
| +8 | superclass_idx | Type, or NO_INDEX (0xffffffff) for java.lang.Object. |
| +12 | interfaces_off | → type_list of implemented interfaces, or 0. |
| +16 | source_file_idx | String ("LoginActivity.kt") or NO_INDEX. Often kept even by R8, so it reveals original class names under obfuscation. |
| +20 | annotations_off | → annotations_directory_item, or 0. |
| +24 | class_data_off | → class_data_item, or 0 (a marker interface with no members). |
| +28 | static_values_off | → encoded_array_item: initial values of static final fields, in declaration order. |
class_data_item
static_fields_size uleb128
instance_fields_size uleb128
direct_methods_size uleb128 static, private and constructors
virtual_methods_size uleb128 everything that can be overridden
static_fields[] encoded_field: field_idx_diff uleb128, access_flags uleb128
instance_fields[]
direct_methods[] encoded_method: method_idx_diff uleb128, access_flags uleb128, code_off uleb128
virtual_methods[]
Indices are delta-encoded: the first entry of each list holds the index itself, the next ones the difference from the previous. code_off is 0 for abstract and native methods. Method access flags add 0x20 synchronized, 0x40 bridge, 0x80 varargs, 0x100 native, 0x10000 constructor, 0x20000 declared-synchronized.
6code_item
| Offset | Field | Meaning |
| +0 | registers_size | u16: registers the method uses (locals + parameters). |
| +2 | ins_size | u16: registers taken by the parameters, this included. They are the last ins_size registers. |
| +4 | outs_size | u16: argument registers needed by the calls it makes. |
| +6 | tries_size | u16: number of try_items. |
| +8 | debug_info_off | u32: → debug_info_item (line numbers, parameter and local names), or 0 when stripped. |
| +12 | insns_size | u32: length of the bytecode in 16-bit code units. |
| +16 | insns[] | u16 × insns_size: the instructions. |
| … | padding | u16, if tries_size ≠ 0 and insns_size is odd (4-byte alignment). |
| … | tries[] | try_item × tries_size. |
| … | handlers | encoded_catch_handler_list. |
Instruction offsets and branch targets are counted in code units from the start of insns. packed-switch, sparse-switch and fill-array-data point at payloads stored inside insns, usually at the end, recognisable by a first code unit of 0x0100, 0x0200 or 0x0300.
packed-switch-payload 0x0100, size u16, first_key i32, targets i32[size]
sparse-switch-payload 0x0200, size u16, keys i32[size], targets i32[size]
fill-array-data-payload 0x0300, element_width u16, size u32, data (padded to 16 bits)
Switch targets are relative to the switch instruction, not to the payload.
debug_info_item
line_start (uleb128), parameters_size (uleb128), one parameter name per parameter (uleb128p1 string index), then a small state machine of opcodes: DBG_START_LOCAL (register, name, type), DBG_END_LOCAL, DBG_ADVANCE_PC, DBG_ADVANCE_LINE, and special opcodes ≥ 0x0a that advance address and line together. The decompiler uses it to name parameters and locals.
7Try / catch handlers
try_item (8 bytes)
start_addr u32 first code unit covered
insn_count u16 number of code units covered
handler_off u16 byte offset of its handler from the start of encoded_catch_handler_list
encoded_catch_handler_list
size uleb128
list[size] encoded_catch_handler:
size sleb128 number of typed catches; ≤ 0 means a catch-all follows
handlers[|size|] type_idx uleb128, addr uleb128
catch_all_addr uleb128 (only if size ≤ 0)
The handler starts with move-exception vA, which puts the exception in a register. Java finally becomes a catch-all handler that runs the finally code and rethrows, plus a copy of that code on the normal path. synchronized blocks become monitor-enter, the body, monitor-exit, and a catch-all that exits the monitor and rethrows.
d8 doesn't keep the source try as one range: it splits it around instructions that cannot throw, and flattens nesting, so an inner try's ranges list the inner handlers followed by the outer ones. The decompiler rebuilds the nested Java try statements from that.
8Encoded values and annotations
Constant values (static field initialisers, annotation elements, call-site arguments) are encoded_values: one header byte (value_arg << 5) | value_type, then value_arg + 1 bytes of little-endian data for the numeric types.
| value_type | Type | Payload |
| 0x00 · 0x02 · 0x03 · 0x04 · 0x06 | byte · short · char · int · long | Sign- (char: zero-) extended, 1–8 bytes |
| 0x10 · 0x11 | float · double | The high-order bytes only (zero-extended to the right) |
| 0x15 · 0x16 | method_type · method_handle | proto / method-handle index |
| 0x17 · 0x18 | string · type | string / type index |
| 0x19 · 0x1a · 0x1b | field · method · enum | field / method / enum-field index |
| 0x1c | array | encoded_array: size uleb128, then values |
| 0x1d | annotation | encoded_annotation, see below |
| 0x1e | null | none |
| 0x1f | boolean | none: value_arg is the value (0 / 1) |
Annotations
annotations_directory_item: class_annotations_off, then counts and lists of field, method and parameter annotations, each pointing at an annotation_set_item (a list of offsets to annotation_items). An annotation_item is a visibility byte (0 build, 1 runtime, 2 system) and an encoded_annotation: type_idx uleb128, size uleb128, and size × (name_idx uleb128, encoded_value).
System annotations carry what the bytecode lost: dalvik.annotation.Signature (generic signatures, as string arrays), InnerClass / EnclosingClass / EnclosingMethod / MemberClasses (nesting), Throws, MethodParameters. Kotlin adds kotlin.Metadata, whose strings contain the original Kotlin declarations even after obfuscation.
The tool doesn't decode encoded values or annotations; their strings are still listed under Strings → All strings.
10Opcodes
All the opcodes the tool knows, generated from its own table (lib/dex-opcodes.js), with what each one does. In the meanings, vA, vB, vC are the registers of the instruction's format, in order. The ones you will read most are const-string (string literals: the way to find URLs, keys and messages), the invoke-* calls, and the field reads and writes (iget / iput, sget / sput).
| Opcode | Mnemonic | Format | Index | Meaning |
11Smali primer
Smali is the usual text form of DEX bytecode (from the smali / baksmali tools and apktool). The tool's Smali tab uses dexdump's notation, which is the same instructions written slightly differently.
Registers
A method has registers_size registers v0 … vN−1; the parameters occupy the last ins_size of them. Smali names those p0, p1…: in an instance method p0 is this. long and double take two consecutive registers. The tool's listing always shows v numbers; the decompiler names parameters this, p0, p1… (or their names from debug info).
.method public check(Ljava/lang/String;I)Z registers_size = 5, ins_size = 3
v0, v1 locals
v2 = p0 this
v3 = p1 the String
v4 = p2 the int
Type descriptors
| Descriptor | Type | Descriptor | Type |
| V | void | J | long (2 registers) |
| Z | boolean | F | float |
| B | byte | D | double (2 registers) |
| S | short | Lcom/acme/Foo; | class com.acme.Foo |
| C | char | Lcom/acme/Foo$Bar; | nested class Foo.Bar; Foo$1 is an anonymous class |
| I | int | [I · [[Ljava/lang/String; | int[] · String[][] |
Member references
smali Lcom/acme/Auth;->check(Ljava/lang/String;I)Z method: class -> name(params)return
Lcom/acme/Auth;->token:Ljava/lang/String; field: class -> name:type
dexdump Lcom/acme/Auth;.check:(Ljava/lang/String;I)Z the tool's Smali tab
Lcom/acme/Auth;.token:Ljava/lang/String;
A short example
0000: iget-object v0, v2, Lcom/acme/Auth;.token:Ljava/lang/String;
0002: if-eqz v0, 0009
0004: invoke-virtual {v0, v3}, Ljava/lang/String;.equals:(Ljava/lang/Object;)Z
0007: move-result v1
0008: return v1
0009: const/4 v1, #0
000a: return v1
The Decompiled tab turns this into roughly the following (without debug info, parameters are p0, p1; a boolean constant stays 0 / 1):
v0 = this.token;
if (v0 != null) {
return v0.equals(p0);
}
return 0;
12Multidex
Because a DEX file can reference at most 65,536 methods, larger apps are split into classes.dex, classes2.dex, classes3.dex… Android 5+ (ART) loads all of them natively. A class is defined in exactly one file, but each file has its own id tables, so the same method reference (Ljava/lang/String;->equals…) can appear in several files with different indices.
- Open all the files at once by handing an APK's dex files over from the APK tool. The tool merges their classes into one package tree and one string list; each class is decompiled with its own file.
- A class defined in more than one file (it happens with broken builds or packers) is tagged with its file name.
- The overview's method count sums the
method_ids of every file, so it counts references to the same method once per file.
- Packers and some protections ship an encrypted DEX in
assets/ and load it at run time; only the small loader is in classes.dex.
VDEX, ODEX and OAT
On a device, ART keeps compiled and verified copies of an app's code under oat/<arch>/ next to the APK (or in /data/dalvik-cache, and under /system/framework for the platform). Open one of these files and the tool opens the DEX files inside it:
- VDEX (Android 8+): verification data, and often the DEX files themselves. From Android 12 (version
027) a section table says where the DEX section is; when the APK stores its DEX uncompressed the section is empty and the DEX stays in the APK. In Android 8–11 the DEX files may be quickened: some field and method instructions are rewritten into ART's -quick forms, which have no reference to resolve and show as unknown opcodes.
- ODEX / OAT: an ELF file with ahead-of-time compiled native code (open it in the ELF tool for that). Before Android 8 it embeds the DEX files; from Android 8 they are in the matching
.vdex.
- DEX files in ART's compact format (
cdex, used for some system images) are counted but not read.
13The decompiler
The Decompiled tab rebuilds Java-like source for one method. It is experimental: readable pseudocode, not code that compiles. The steps:
- Decode the instructions and parse switch payloads into case keys and targets.
- Statements: each instruction becomes an assignment, store, call, branch or return.
invoke + move-result become one assignment; new-instance + invoke-direct <init> become new Foo(args) at the constructor call; an <init> on this becomes super(…), and invoke-super becomes super.m(…) (it calls the superclass's version, not this class's override). Static calls and fields use the class's simple name (TextUtils.isEmpty(…)). Anything not handled is kept as a /* … */ comment. Kotlin's Intrinsics.checkNotNullParameter-style null checks are dropped; the parameter names they carry name the parameters when there is no debug info.
- CFG of basic blocks, with exception edges from protected blocks to their handlers.
- SSA (Cytron et al.: dominance frontiers, φ insertion, renaming), dead φ elimination, and propagation of single-use values into their use when that cannot reorder side effects. Constants, copies and casts that can't fail whose value is never read are removed. D8 loads a constant once and reuses its register where the source repeated it, so a constant (a number, a class literal or a string of up to 40 characters) is written out at every read instead of becoming a variable; only the lock of a
synchronized block, and a constant that also reaches a φ, stay variables.
- Types of constants: the bytecode has no
null, true or false, only 0 and 1. A 0 passed for an object parameter, stored in an object field or returned as an object prints as null; a 0 or 1 where a boolean is expected prints as false / true.
- Casts that can't fail are left out: a
check-cast of a value whose type is already that type or a subtype (this, a parameter, a field, a call's result, a new object), checked against the app's class hierarchy and the common java.lang / java.util types. kotlinc and D8 emit many of these, such as (ComponentActivity) this in an activity.
- Recovery: short-circuit
&& / || from chains of conditional blocks; ternaries from if/else diamonds that assign one variable; cross-block inlining of pure single-use temporaries.
- Structuring with dominators and post-dominators:
if / else, while, for (an induction variable updated at the end of the body), do … while, switch from the payload, break / continue.
- try / catch from the flat try table: one region per distinct handler list, ranges joined across gaps of non-throwing code, nested by handler-list suffix;
catch (Type e) per handler, Throwable for a catch-all. A catch-all whose handler is just monitor-exit x; throw becomes synchronized (x) { … }.
- Naming out of SSA (values joined by φs share a name): parameters as
this and p0, p1… or their debug-info names; locals from debug info; loop counters i, j, k…; a value created by new Foo(…) as foo; others v0, v1….
Lambdas. D8 compiles a Java or Kotlin lambda to a small class (Foo$$ExternalSyntheticLambda0, older -$$Lambda$…, or a Kotlin kotlin.jvm.internal.Lambda subclass) whose constructor stores the captured values in fields f$0, f$1… and whose one method implements the interface. Where the class is created (new …(captures), or its INSTANCE for a lambda that captures nothing), the tool decompiles that method with the captured values put back, and shows (a, b) -> this.onItem(key, a, b). It does this when the body is a single statement and doesn't use the lambda object itself; otherwise the new stays. The body is often a call to a synthetic method of the enclosing class that holds the real code ($r8$lambda$…, javac's lambda$foo$0, Kotlin's foo$lambda$0). When that method is one statement or one returned expression and the arguments are plain values, its body is shown in place of the call, so a -> Foo.$r8$lambda$Xy…(this, a) becomes a -> this.onItem(a); hover it to see which method it came from. Longer ones stay as a call you can click to open, and a $r8$lambda$ forwarder is replaced by the method it forwards to, so the name you see is the real one.
Kotlin calls. For a function with default arguments, fun f(a: A, b: B = …, c: C = …), kotlinc also emits a static f$default(a, b, c, mask, marker) (with the object first for a member function); each bit of mask says that a parameter was left out and gets its default. A call to it is shown as a call of f with only the arguments that were given, so FloatSet.joinToString$default(this, separator, 0, 0, 0, 0, 30, null) becomes this.joinToString(separator). An argument that comes after a left-out one is written with its name (f(a, c = x)); that needs f's parameter names from its debug info, otherwise the $default call stays as it is. An extension function, fun A.g(…), compiles to a static method whose first parameter, the receiver, is named $this$g in debug info; a call to it is shown on its receiver: this.setContent(…) instead of ComponentActivityKt.setContent(this, …). Both need the called method's debug info, which release builds often strip; the tool looks for it in all the DEX files of the app. The final return; of a void method is not printed.
Comparisons with zero print as == null, != null or a plain boolean test when the operand's type is known to be an object or a boolean (from the method's parameter types, field types and call return types).
Status flags
| Flag | Meaning |
| names from debug info | The method has local-variable debug info; names are the original ones. |
| SSA unavailable → register names | SSA construction failed; output uses raw registers v3, p0. |
| goto/label fallback | Some control flow could not be structured and is printed with labels (L001a:) and goto. |
| try/catch not structured | The method has try ranges, but they couldn't be turned into try statements. |
| structuring failed → linear form | The method is printed block by block. |
Longer lambdas and anonymous classes. A lambda whose body is more than one statement (its own, or that of the …$lambda$0 / $r8$lambda$… method it calls) is shown as a block, (a, b) -> { … }, up to 80 lines, with its locals numbered after the enclosing method's. An anonymous class (Foo$1) created with new Foo$1(this, x) is shown where it is created, as new Runnable() { public void run() { … } } with all its methods; the fields it captured (this$0, val$x) are replaced by the values passed in, and the enclosing object is written Outer.this. This is done only when its constructor just stores those values and calls super() without arguments, and no method changes them; otherwise the new Foo$1(…) stays and you can open the class.
String concatenation. javac and kotlinc compile "Error: " + code + '.' to a StringBuilder: new StringBuilder("Error: "), one append per piece (D8 drops their results, so each is its own statement), then toString(). The tool puts the + expression back where toString() was used, when the builder is used for nothing else and moving the pieces there can't change their values. append(char) pieces show as character literals, and a leading "" is added when neither of the first two pieces is a String, so the expression still means concatenation. Builders filled in a loop, in different branches, or passed to other methods stay as they are.
Kotlin coroutines. A suspend function compiles to a state machine: it gets the caller's Continuation as an extra last parameter (shown as $completion), keeps its resume point in label and the locals it needs after a suspension in L$0, I$0, J$0… of a continuation object ($cont, a class such as Foo$bar$1), and returns COROUTINE_SUSPENDED when a call it makes suspends; it is called again with label set once that call completes. Suspend lambdas run the same machine in invokeSuspend($result) with the state in this. The tool marks these methods (suspend fun / suspend lambda), folds the prologue that reuses the continuation on resume or creates it on the first call into one line ($cont = $completion instanceof Foo$bar$1 resumed && resumed.label < 0 ? resumed : new Foo$bar$1($completion); on resume the real code also clears the flag bit in label), shows getCOROUTINE_SUSPENDED() as the constant, and turns each suspension check into an early if (x == COROUTINE_SUSPENDED) return COROUTINE_SUSPENDED; so the code after it reads in order. The switch (label) stays: each case is where the method continues after suspension point N, restoring its locals and jumping back into the code.
Jetpack Compose. The Compose compiler rewrites every @Composable function and lambda: it adds parameters ($composer, $changed, $default), wraps the body in bookkeeping the runtime needs, and expands inline composables such as Column, Row, Box and remember into the caller. The tool takes that back out, so the code reads like the source:
- the skip test (
if (!$composer.shouldExecute(…)) skipToGroupEnd() else …), trace events, restart and replace groups, source-information strings and the $dirty change tracking are dropped;
- calls to composables lose their
$composer, $changed and $default arguments, and $default is folded like Kotlin's default arguments (Surface(modifier, content = …)); a composable lambda parameter called as content.invoke($composer, …) becomes content.invoke();
- the lambdas a
ComposableSingletons$FileKt class creates once are shown where they are used, with their body: setContent(content = () -> { MaterialTheme(content = () -> …) });
remember { … }, which compiles to rememberedValue(), a test against Composer.Empty (and changed(key) for its keys) and updateRememberedValue(…), is shown as remember(key, () -> value) when its block computes one expression;
Column, Row and Box, recognized by their measure policy, are shown as the call with the arguments that aren't at their default and their content indented inside: ColumnKt.Column(modifier = …, verticalArrangement = …) { … };
$composer.consume(LocalContext) is shown as LocalContext.current.
Other inline layouts (Layout, custom ones), remember blocks of several statements, and composable lambdas that capture values stay as the compiler expanded them.
Not recovered: generic types, local variable types (no declarations are printed), anonymous classes whose constructor does more than store what they capture, strings built with a StringBuilder in a loop or across branches, fill-array-data contents, and invoke-custom targets. Coroutines are shown as their state machine (see above), not as the original sequential code.
14The "Called by" box
When a method is selected, the box under the code lists the methods whose bytecode calls it.
- After loading, the tool scans the code of every method once, in the background (the same pass collects the strings each method loads). Every instruction with a method operand (
invoke-*, including /range and invoke-polymorphic) is recorded under the textual key Lclass;->name(params)return, so references from different dex files meet. Until the scan finishes, the box says indexing calls….
- Exact references are calls naming this class and method.
- For an overridable method (a virtual method that is not a constructor), calls that name the same method on one of its supertypes — superclasses and interfaces, transitively — are listed separately as via supertypes:
Runnable.run() called on a variable may reach this override or another one at run time.
- Up to 300 callers are shown; each opens that method.
An empty list does not mean dead code: the framework calls lifecycle methods (onCreate, onClick…), and reflection, JNI, invoke-custom call sites and method references in annotations or resources are not seen.
15What the tool shows, and its limits
- Overview: version, checksum, signature, header and file size, endianness, map offset and the table counts; with several files, a table with one row per file.
- Classes: a package tree with filters by class name and by method name. A class shows its declaration (modifiers,
extends, implements), its source file, an overview of fields and methods, and each method decompiled or as a Smali listing, with register, in, out and try counts and the "Called by" box.
- Strings: by default the strings loaded by code (
const-string), each with the methods that use it; All strings shows the whole table, tagging the ones that are type, field or method names or shorties.
From VDEX and OAT/ODEX files only the plain DEX files inside are read: compact DEX (cdex) is not supported, and the opcodes 0xe3–0xf9 of quickened or odex code show as unused-xx. Annotations, encoded static values and the map list are not decoded.
16The DEX library
The reader is lib/dex.js, a JavaScript module with no user interface (it imports lib/dex-opcodes.js). It exports two classes: DexFile, whose instances are opened DEX files and whose static methods read containers, decode instructions, name types and build the string / call index, and DexProgram, a set of DEX files (one application) with the lookups a class browser needs. It does not know where it runs: the tool builds its string and call index in dex/dex-worker.js, and the tests run it in jsc.
import { DexFile, DexProgram } from "../lib/dex.js";
One DEX file: DexFile
| Method | What it does |
DexFile.open(arrayBuffer) new DexFile(arrayBuffer) | Opens a DEX file; throws an Error when it is too small, has no dex\n magic or its id tables run past the end. Everything below is read lazily from the buffer. |
| dexFile.header | version, checksum, signature (SHA-1, hex), fileSize, headerSize, endianTag, mapOff, and the size and offset of every id table (stringIdsSize, stringIdsOff, typeIds…, protoIds…, fieldIds…, methodIds…, classDefs…, data…). |
| dexFile.stringAt(index) | A string of the string table, MUTF-8 decoded (cached). |
| dexFile.typeDescriptor(index) | A type as a descriptor: Lcom/acme/Foo;, I, [B. |
| dexFile.protoDescriptor(index), protoParameterTypes(index), protoReturnType(index) | A method prototype as (ILjava/lang/String;)V, its parameter descriptors, its return descriptor. |
| dexFile.fieldReference(index) | { cls, name, type } (descriptors). |
| dexFile.methodReference(index) | { cls, name, proto, protoIdx }. |
| dexFile.classDefinition(index) | A class_def: { classIdx, access, superIdx, interfacesOff, sourceIdx, annotationsOff, classDataOff, staticValuesOff }; superIdx / sourceIdx are DexFile.NO_INDEX (0xffffffff) when absent. |
| dexFile.interfaceTypes(definition, limit) | The descriptors of the interfaces a class implements (at most limit). |
| dexFile.classData(offset) | A class_data_item: { staticFields, instanceFields: [{ fieldIdx, access }], directMethods, virtualMethods: [{ methodIdx, access, codeOff }] }. |
| dexFile.codeItem(offset) | A code_item: { off, registers, ins, outs, tries, debugOff, insnsSize, insns }, insns a Uint16Array over the buffer. |
| dexFile.debugInfo(offset) | A debug_info_item: { lineStart, paramNames, locals: Map(register → [{ start, end, name }]) }, or null. |
| dexFile.tryBlocks(code) | The try ranges and their handlers: [{ startAddr, endAddr, handlers: [{ typeIdx, type, addr }], catchAll }], addresses in code units. |
| dexFile.readUleb128(offset), readSleb128(offset) | A LEB128 value: [value, offset after it]. |
Containers, instructions, names: DexFile's static methods
| Method | What it does |
| DexFile.extractFromContainer(arrayBuffer) | The DEX files in a buffer: { kind, version, note, dexes: [{ name, off, buffer }], cdex }. kind is "dex" (the buffer is one), "vdex", "oat" (an ELF OAT/ODEX) or "data"; note explains an empty result; cdex counts compact-DEX files, which are skipped. |
| DexFile.decodeInstructions(dexFile, code) | { insns, payloads }. Each instruction is { off, size, op, mnemonic, format, indexKind, regs, lit, litWide, target, idx, idx2, range } (offsets in code units, lit a BigInt when litWide). A switch or array payload is one entry with payload: true, payloadKind, entryCount and elementWidth. payloads maps a switch payload's offset to { kind, keys, targets }. |
| DexFile.methodKey(reference), DexFile.fieldKey(reference) | Lcls;->name(proto) and Lcls;->name:type, the keys the index and the resolvers use. |
| DexFile.descriptorToJava(descriptor), DexFile.simpleTypeName(descriptor) | [Ljava/lang/String; → java.lang.String[], and the same without the package (String[]). |
| DexFile.classNameParts(descriptor) | { packageName, simpleName, javaName }. |
| DexFile.accessFlagNames(flags, kind) | The names of the access flags set, for "class", "method" or "field": ["public", "static", "final"]. |
| DexFile.NO_INDEX | 0xffffffff, the "absent" value of superIdx / sourceIdx. |
A set of DEX files: DexProgram
| Method | What it does |
| new DexProgram([{ name, size, off, file }]) | A program over opened DEX files (file a DexFile): classes are numbered across the files, in order. |
| program.files | The list given. |
| program.classes | [{ index, fileIndex, file, definition, descriptor, packageName, simpleName, javaName, duplicate }]; duplicate marks a class defined in more than one file. |
| program.packages | The package tree: { segment, fullName, packages: Map, classes, classCount }, classCount counting every class below. |
| program.classByDescriptor(descriptor) | The first class with that descriptor, or null. |
| program.members(classEntry) | { data, methods: [{ method, direct, reference, file }] }: the class data and its methods, direct ones first. Throws when the class data can't be read. |
| program.methodSignatures(classEntry), fieldSignatures(classEntry) | The methods it declares (Map name + proto → methodIdx) and its fields (Set of name:type). |
| program.methodNames(), filterClasses(nameQuery, methodQuery, cap) | The method names of every class; the classes whose name contains nameQuery and that have a method containing methodQuery (case-insensitive): [{ classEntry, matched }], at most cap + 1. |
| program.interfaces(classEntry), supertypes(classEntry) | Its interfaces; every superclass and interface, transitively, as descriptors. |
| program.resolveMethod(methodKey) | The method a call reaches statically, declared in that class or inherited: { classEntry, methodIdx, inherited }, or { missing: true, cls, start } when it is in the framework or a library. |
| program.resolveField(fieldKey) | The class declaring the field (that class or a superclass), or null. |
| program.nameStrings() | { tags, all }: the strings that are type descriptors, field or method names or shorties (Map string → tag), and every distinct string, sorted. |
The string and call index: DexFile's static methods
| Method | What it does |
| DexFile.createCodeIndex(dexFiles) | An index over every method's code; classes are numbered like program.classes. |
| index.scan(shouldPause) | Scans class by class until shouldPause() returns true; returns true when finished. index.progress goes from 0 to 1. |
| index.uses, index.calls | Map string value → [[class index, methodIdx], …] for const-string, and Map method key → callers for every invoke-*. |
| DexFile.packCodeIndex(index), DexFile.unpackCodeIndex(packed.uses) | A compact form (keys plus one Int32Array, with a _transfer list) to move the index out of a worker, and a read-only Map-like view of it (get, has, keys, values, size). |
import { DexFile, DexProgram } from "../lib/dex.js";
const container = DexFile.extractFromContainer(buffer); // a .dex, .vdex or .odex
const files = container.dexes.map(dex => ({ name: dex.name, size: dex.buffer.byteLength, off: dex.off, file: DexFile.open(dex.buffer) }));
const program = new DexProgram(files);
const activity = program.classByDescriptor("Lcom/acme/MainActivity;");
for (const entry of program.members(activity).methods) {
console.log(entry.reference.name + entry.reference.proto, DexFile.accessFlagNames(entry.method.access, "method").join(" "));
}
const index = DexFile.createCodeIndex(files.map(entry => entry.file));
index.scan(() => false);
console.log(index.uses.get("https://api.acme.com/")); // [[class index, methodIdx], …]
17The opcode table: DexOpcodes
lib/dex-opcodes.js is the Dalvik instruction set as data (the table in Opcodes is generated from it): a module with no dependencies whose class DexOpcodes has static members only.
import { DexOpcodes } from "../lib/dex-opcodes.js";
| Member | What it does |
| DexOpcodes.table[opcode] | { mnemonic, format, indexKind }, or null for an unused opcode. indexKind is "s" string, "t" type, "f" field, "m" method, "p" proto, "c" call site, "h" method handle, or null. |
| DexOpcodes.lookup(opcode) | The same entry. |
| DexOpcodes.codeUnits(format) | The size of an instruction of that format, in 16-bit code units (its first digit). |
DexOpcodes.table[0x6e]; // { mnemonic: "invoke-virtual", format: "35c", indexKind: "m" }
DexOpcodes.codeUnits("35c"); // 3
18The decompiler library: DexDecompiler
lib/dex-decompiler.js is the decompiler described in The decompiler: a module (it imports lib/dex.js) whose class DexDecompiler has one public static method; its passes are private.
import { DexDecompiler } from "../lib/dex-decompiler.js";
| Method | What it does |
| DexDecompiler.decompile(dexFile, code, method, options) | Decompiles one method: code is dexFile.codeItem(method.codeOff) and method the encoded method from classData. options is optional: { program }, the DexProgram of the whole app, gives the class hierarchy and the parameter names of methods in the other DEX files (for casts that can't fail, Kotlin extension calls and default arguments); without it only dexFile is used. Returns { lines: [{ indent, html }], hasDebug, ssa, usedGoto, hasTry, structuredTry, failed, coroutine }. The lines are HTML with highlighting spans; a call is a <span data-m="Lcls;->name(proto)"> and a field a <span data-f="Lcls;->name:type">, for navigation. The flags say whether names came from debug info, whether SSA worked, whether goto/labels or the linear fallback were needed, and coroutine describes a Kotlin suspend function's state machine. |
import { DexFile } from "../lib/dex.js";
import { DexDecompiler } from "../lib/dex-decompiler.js";
const dexFile = DexFile.open(buffer);
const definition = dexFile.classDefinition(0);
const method = dexFile.classData(definition.classDataOff).virtualMethods[0];
const result = DexDecompiler.decompile(dexFile, dexFile.codeItem(method.codeOff), method);
const text = result.lines.map(line => " ".repeat(line.indent) + line.html.replace(/<[^>]+>/g, "")).join("\n");