← DEX
DEX·Format guide
All tools

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.

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

  1. Header
  2. The id tables
  3. ULEB128 and MUTF-8
  4. map_list
  5. class_def and class_data_item
  6. code_item
  7. Try / catch handlers
  8. Encoded values and annotations
  9. Instruction formats
  10. Opcodes
  11. Smali primer
  12. Multidex
  13. The decompiler
  14. The "Called by" box
  15. What the tool shows, and its limits
  16. The DEX library (DexFile, DexProgram)
  17. The opcode table (DexOpcodes)
  18. 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.

TableEntryFields
string_ids4 bytesstring_data_off u32 → a string_data_item (below). Sorted by string value.
type_ids4 bytesdescriptor_idx u32 → string: a type descriptor such as Ljava/lang/String;.
proto_ids12 bytesshorty_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_ids8 bytesclass_idx u16 · type_idx u16 · name_idx u32.
method_ids8 bytesclass_idx u16 · proto_idx u16 · name_idx u32.
class_defs32 bytesOne 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.

TypeItemTypeItem
0x0000header_item0x1000map_list
0x0001string_id_item0x1001type_list
0x0002type_id_item0x1002annotation_set_ref_list
0x0003proto_id_item0x1003annotation_set_item
0x0004field_id_item0x2000class_data_item
0x0005method_id_item0x2001code_item
0x0006class_def_item0x2002string_data_item
0x0007call_site_id_item0x2003debug_info_item
0x0008method_handle_item0x2004annotation_item
0xf000hiddenapi_class_data_item0x2005 · 0x2006encoded_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)

OffsetFieldMeaning
+0class_idxType of this class.
+4access_flags0x1 public, 0x10 final, 0x200 interface, 0x400 abstract, 0x1000 synthetic, 0x2000 annotation, 0x4000 enum.
+8superclass_idxType, or NO_INDEX (0xffffffff) for java.lang.Object.
+12interfaces_off→ type_list of implemented interfaces, or 0.
+16source_file_idxString ("LoginActivity.kt") or NO_INDEX. Often kept even by R8, so it reveals original class names under obfuscation.
+20annotations_off→ annotations_directory_item, or 0.
+24class_data_off→ class_data_item, or 0 (a marker interface with no members).
+28static_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

OffsetFieldMeaning
+0registers_sizeu16: registers the method uses (locals + parameters).
+2ins_sizeu16: registers taken by the parameters, this included. They are the last ins_size registers.
+4outs_sizeu16: argument registers needed by the calls it makes.
+6tries_sizeu16: number of try_items.
+8debug_info_offu32: → debug_info_item (line numbers, parameter and local names), or 0 when stripped.
+12insns_sizeu32: length of the bytecode in 16-bit code units.
+16insns[]u16 × insns_size: the instructions.
…paddingu16, if tries_size ≠ 0 and insns_size is odd (4-byte alignment).
…tries[]try_item × tries_size.
…handlersencoded_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_typeTypePayload
0x00 · 0x02 · 0x03 · 0x04 · 0x06byte · short · char · int · longSign- (char: zero-) extended, 1–8 bytes
0x10 · 0x11float · doubleThe high-order bytes only (zero-extended to the right)
0x15 · 0x16method_type · method_handleproto / method-handle index
0x17 · 0x18string · typestring / type index
0x19 · 0x1a · 0x1bfield · method · enumfield / method / enum-field index
0x1carrayencoded_array: size uleb128, then values
0x1dannotationencoded_annotation, see below
0x1enullnone
0x1fbooleannone: 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.

9Instruction formats

An instruction is one or more 16-bit code units; the low byte of the first is the opcode. A format name such as 22c means: 2 code units, 2 registers, c = a constant-pool index. Other letters: x no extra data, n 4-bit literal, b 8-bit, s 16-bit, h high 16 bits, i 32-bit, l 64-bit literal, t branch target, r register range. Each letter in the layout is 4 bits; op is the opcode byte.

FormatLayoutSyntaxExample
10xØØ|opopreturn-void, nop
12xB|A|opop vA, vBmove v1, v2, add-int/2addr
11nB|A|opop vA, #+Bconst/4 v0, #1
11xAA|opop vAAreturn v0, move-result, throw
10tAA|opop +AAgoto
20tØØ|op AAAAop +AAAAgoto/16
22xAA|op BBBBop vAA, vBBBBmove/from16
21tAA|op BBBBop vAA, +BBBBif-eqz v0, :L
21s · 21hAA|op BBBBop vAA, #+BBBBconst/16, const/high16
21cAA|op BBBBop vAA, kind@BBBBconst-string, sget, new-instance, check-cast
23xAA|op CC|BBop vAA, vBB, vCCadd-int, aget, cmp-long
22bAA|op CC|BBop vAA, vBB, #+CCadd-int/lit8
22tB|A|op CCCCop vA, vB, +CCCCif-lt v0, v1, :L
22sB|A|op CCCCop vA, vB, #+CCCCadd-int/lit16
22cB|A|op CCCCop vA, vB, kind@CCCCiget, iput, instance-of, new-array
30tØØ|op AAAAlo AAAAhiop +AAAAAAAAgoto/32
32xØØ|op AAAA BBBBop vAAAA, vBBBBmove/16
31i · 31t · 31cAA|op BBBBlo BBBBhiop vAA, #+B… / +B… / kind@B…const, packed-switch, const-string/jumbo
35cA|G|op BBBB F|E|D|Cop {vC, vD, vE, vF, vG}, kind@BBBBinvoke-virtual, filled-new-array: A = argument count (0–5)
3rcAA|op BBBB CCCCop {vCCCC .. vNNNN}, kind@BBBBinvoke-*/range: AA registers from vCCCC
45cc · 4rcc35c / 3rc + HHHH…, meth@BBBB, proto@HHHHinvoke-polymorphic (MethodHandle.invoke)
51lAA|op BBBB×4op vAA, #+BBBBBBBBBBBBBBBBconst-wide

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).

OpcodeMnemonicFormatIndexMeaning

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

DescriptorTypeDescriptorType
VvoidJlong (2 registers)
ZbooleanFfloat
BbyteDdouble (2 registers)
SshortLcom/acme/Foo;class com.acme.Foo
CcharLcom/acme/Foo$Bar;nested class Foo.Bar; Foo$1 is an anonymous class
Iint[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.

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:

13The decompiler

The Decompiled tab rebuilds Java-like source for one method. It is experimental: readable pseudocode, not code that compiles. The steps:

  1. Decode the instructions and parse switch payloads into case keys and targets.
  2. 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.
  3. CFG of basic blocks, with exception edges from protected blocks to their handlers.
  4. 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.
  5. 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.
  6. 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.
  7. 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.
  8. 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.
  9. 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) { … }.
  10. 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

FlagMeaning
names from debug infoThe method has local-variable debug info; names are the original ones.
SSA unavailable → register namesSSA construction failed; output uses raw registers v3, p0.
goto/label fallbackSome control flow could not be structured and is printed with labels (L001a:) and goto.
try/catch not structuredThe method has try ranges, but they couldn't be turned into try statements.
structuring failed → linear formThe 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:

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.

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

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

MethodWhat 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.headerversion, 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

MethodWhat 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_INDEX0xffffffff, the "absent" value of superIdx / sourceIdx.

A set of DEX files: DexProgram

MethodWhat 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.filesThe list given.
program.classes[{ index, fileIndex, file, definition, descriptor, packageName, simpleName, javaName, duplicate }]; duplicate marks a class defined in more than one file.
program.packagesThe 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

MethodWhat 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.callsMap 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";
MemberWhat 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";
MethodWhat 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");