Introduction
A .dex file holds the compiled code of an app for
Android. Android apps are written in Java or
Kotlin and compiled to JVM .class
files first; the D8 tool then converts all the classes into Dalvik bytecode in one
.dex file. The name comes from Dalvik, Android’s original virtual machine;
its successor, the Android Runtime (ART), reads the same files and compiles them to
machine code on the device.
DEX files travel inside .apk packages
as classes.dex, with classes2.dex and so on when an app has
more than 65,536 methods.
Structure
A DEX file starts with a 112-byte header. Its first eight bytes are the magic
dex\n and a three-digit version followed by a zero byte, such as
035 or 039. Then come an Adler-32 checksum and a SHA-1
signature of the rest of the file, the file size, the header size, and an endian tag,
0x12345678, written little-endian.
The rest of the header gives the size and offset of each table. All the classes in the file share these tables, which is what makes a DEX file smaller than the class files it came from: strings, types, method prototypes, fields and methods are each stored once and referred to by index. The class definitions and the bytecode itself are in the data area, and a map list at its end lists every section.
0x00magicdex\nand version, such as035\08 bytes0x08checksum (Adler-32) and signature (SHA-1)24 bytes0x20file_size, header_size, endian_tag12 bytes0x2Clink size and offset, map_off12 bytes0x38size and offset of string_ids, type_ids, proto_ids, field_ids, method_ids, class_defs and data56 bytes0x70ID tables, then class definitionsvaries…data: strings, code, annotations and the map listvaries
Links
Software
- Android Studio, whose APK Analyzer shows the classes in a DEX file (Windows, macOS, Linux)
- jadx, which decompiles DEX to Java (Windows, macOS, Linux)
- Apktool (Windows, macOS, Linux)
- smali and baksmali, an assembler and disassembler for Dalvik bytecode (any system with Java)
- Ghidra (Windows, macOS, Linux)
Developers
- Androguard, Python, reads DEX files and APKs
- dexlib2, Java, the library inside smali that reads and writes DEX files
Reference
- Dalvik executable format, Android Open Source Project