Skip to content

Editing DEX files

The model is an editable DEX file in memory: dexpp.Model in Python, *dexpp.Model in Go, Model in Java. You read a file into it, change it, and write a valid DEX file again.

From Python, Go and Java, the model works on whole classes: you can inspect, copy, move, remove and rename classes. Changing the instructions inside a method, or building a class from nothing, is only possible from C++.

The model is separate from the analysis API. A model is not an analysis context, and a class in a model is not a class handle of the analysis API.

The examples come in Python, Go and Java. Pick your language in the tabs.

Read and inspect

model: dexpp.Model = dexpp.Model.read_file("tests/data/shapes.dex")
print("DEX version", model.version, "with", len(model), "classes")
print(model.class_descriptors())

info: dexpp.ClassInfo | None = model.class_info("LCircle;")
assert info is not None
print(info.descriptor, "extends", info.superclass, "-", info.method_count, "methods")

abstract: dexpp.ClassInfo | None = model.class_info("LAbstractShape;")
assert abstract is not None
print(abstract.descriptor, "implements", abstract.interfaces)
DEX version 35 with 4 classes
['LShape;', 'LAbstractShape;', 'LCircle;', 'LRectangle;']
LCircle; extends LAbstractShape; - 4 methods
LAbstractShape; implements ['LShape;']
model, err := dexpp.ReadModelFile("../../../tests/data/shapes.dex", true)
if err != nil {
    log.Fatal(err)
}
defer model.Close()
fmt.Println("DEX version", model.Version(), "with", model.ClassCount(), "classes")
fmt.Println(model.ClassDescriptors())

info, ok := model.ClassInfo("LCircle;")
if !ok {
    log.Fatal("no Circle class")
}
if info.Superclass != nil {
    fmt.Println(info.Descriptor, "extends", *info.Superclass, "-", info.MethodCount, "methods")
}

abstract, ok := model.ClassInfo("LAbstractShape;")
if !ok {
    log.Fatal("no AbstractShape class")
}
fmt.Println(abstract.Descriptor, "implements", abstract.Interfaces)
DEX version 35 with 4 classes
[LShape; LAbstractShape; LCircle; LRectangle;]
LCircle; extends LAbstractShape; - 4 methods
LAbstractShape; implements [LShape;]
try (Model model = Model.readFile(Path.of("../../tests/data/shapes.dex"))) {
    System.out.println("DEX version " + model.version() + " with " + model.classCount()
            + " classes");
    System.out.println(model.classDescriptors());

    ClassInfo info = model.classInfo("LCircle;").orElseThrow();
    System.out.println(info.descriptor() + " extends " + info.superclass().orElse("nothing")
            + " - " + info.methodCount() + " methods");

    ClassInfo abstractShape = model.classInfo("LAbstractShape;").orElseThrow();
    System.out.println(abstractShape.descriptor() + " implements "
            + abstractShape.interfaces());
}
DEX version 35 with 4 classes
[LShape;, LAbstractShape;, LCircle;, LRectangle;]
LCircle; extends LAbstractShape; - 4 methods
LAbstractShape; implements [LShape;]
What Python Go Java
read a file Model.read_file(path) dexpp.ReadModelFile(path, true) Model.readFile(path)
read bytes Model.read(data) dexpp.ReadModel(data, true) Model.read(data)
make an empty model Model(version) dexpp.NewModel(version) new Model(version)
the number of classes len(model) model.ClassCount() model.classCount()
whether a class is there descriptor in model model.HasClass(d) model.hasClass(d)
every class descriptor model.class_descriptors() model.ClassDescriptors() model.classDescriptors()
a summary of one class model.class_info(d) model.ClassInfo(d) model.classInfo(d)
  • The class descriptors come in model order. Each call copies them into a new list. Because it is a copy, you can loop over it while you move or remove classes, as the merge example below does.
  • The summary of a class, a ClassInfo, has the descriptor, the access flags, the superclass, the source file, the list of interfaces, and the number of fields and methods. When the model has no such class, there is no summary: None in Python, false as the second result in Go, an empty Optional in Java.

Reading can leave out the debug information: line numbers and local variable names. The model is then smaller. In Python, pass debug_info=False. In Go, pass false as the second argument of ReadModelFile or ReadModel. In Java, use the forms with a second boolean debugInfo argument, such as Model.readFile(path, false).

In Go, a model is a handle, like the other handles of the package: the garbage collector frees it, and Close() frees it at once. In Java, Model is AutoCloseable, so try-with-resources frees it at the end of a block.

Why classes can move freely

A DEX file stores every string, type, method and field once, in sorted tables, and the code refers to them by index. So a class in a file is tied to that file's tables.

The model holds no indices and no file offsets. Every reference is kept as a name, and branches point at labels. When you write the model, dex++ collects all the references, builds and sorts the tables, and picks the encoding of each instruction. This is why a class can be taken out of one model and put into another with no extra work.

Split a file

out_dir: str = tempfile.mkdtemp()
for index, descriptor in enumerate(model.class_descriptors()):
    one: dexpp.Model = dexpp.Model(model.version)
    one.copy_class(model, descriptor)
    one.write_file(os.path.join(out_dir, f"class{index}.dex"))

file_names: list[str] = sorted(os.listdir(out_dir))
print(file_names)
['class0.dex', 'class1.dex', 'class2.dex', 'class3.dex']
outDir, err := os.MkdirTemp("", "dexpp")
if err != nil {
    log.Fatal(err)
}
defer os.RemoveAll(outDir)

for index, descriptor := range model.ClassDescriptors() {
    one := dexpp.NewModel(model.Version())
    if err := one.CopyClass(model, descriptor); err != nil {
        log.Fatal(err)
    }
    path := filepath.Join(outDir, fmt.Sprintf("class%d.dex", index))
    if err := one.WriteFile(path, true); err != nil {
        log.Fatal(err)
    }
    one.Close()
}

entries, err := os.ReadDir(outDir) // sorted by name
if err != nil {
    log.Fatal(err)
}
var fileNames []string
for _, entry := range entries {
    fileNames = append(fileNames, entry.Name())
}
fmt.Println(fileNames)
[class0.dex class1.dex class2.dex class3.dex]
Path outDir = Files.createTempDirectory("dexpp");
List<String> descriptors = model.classDescriptors();
for (int index = 0; index < descriptors.size(); index++) {
    try (Model one = new Model(model.version())) {
        one.copyClass(model, descriptors.get(index));
        one.writeFile(outDir.resolve("class" + index + ".dex"));
    }
}

try (Stream<Path> files = Files.list(outDir)) {
    List<String> fileNames =
            files.map((Path file) -> file.getFileName().toString()).sorted().toList();
    System.out.println(fileNames);
}
[class0.dex, class1.dex, class2.dex, class3.dex]
What Python Go Java
copy a class from another model copy_class(src, d) CopyClass(src, d) copyClass(src, d)
take a class out of another model move_class(src, d) MoveClass(src, d) moveClass(src, d)
remove a class remove_class(d) RemoveClass(d) removeClass(d)
  • Copying a class leaves the source as it was.
  • Moving takes the class out of the source. The class is not copied, so this is cheaper than a copy followed by a remove.
  • Removing returns whether a class was removed.

Copying and moving fail when the source has no such class or the destination already has one: Python raises dexpp.ModelError, Go returns an error that matches dexpp.ErrModel, and Java throws a ModelException.

Merge files

merged: dexpp.Model = dexpp.Model(model.version)
for file_name in file_names:
    part: dexpp.Model = dexpp.Model.read_file(os.path.join(out_dir, file_name))
    for descriptor in part.class_descriptors():
        merged.move_class(part, descriptor)

print(len(merged), "classes")
print("same bytes as the original model:", merged.write() == model.write())
4 classes
same bytes as the original model: True
merged := dexpp.NewModel(model.Version())
defer merged.Close()
for _, fileName := range fileNames {
    part, err := dexpp.ReadModelFile(filepath.Join(outDir, fileName), true)
    if err != nil {
        log.Fatal(err)
    }
    for _, descriptor := range part.ClassDescriptors() {
        if err := merged.MoveClass(part, descriptor); err != nil {
            log.Fatal(err)
        }
    }
    part.Close()
}

fmt.Println(merged.ClassCount(), "classes")
mergedBytes, err := merged.Write(true)
if err != nil {
    log.Fatal(err)
}
originalBytes, err := model.Write(true)
if err != nil {
    log.Fatal(err)
}
fmt.Println("same bytes as the original model:", bytes.Equal(mergedBytes, originalBytes))
4 classes
same bytes as the original model: true
try (Model merged = new Model(model.version())) {
    for (String fileName : fileNames) {
        try (Model part = Model.readFile(outDir.resolve(fileName))) {
            for (String descriptor : part.classDescriptors()) {
                merged.moveClass(part, descriptor);
            }
        }
    }

    System.out.println(merged.classCount() + " classes");
    boolean same = Arrays.equals(merged.write(), model.write());
    System.out.println("same bytes as the original model: " + same);
}
4 classes
same bytes as the original model: true

The output does not depend on the order in which the classes were added. The writer always puts classes, members and tables in the same fixed order.

Rename classes

renames: dict[str, str] = {"LCircle;": "Lcom/example/Round;"}
model.rename_types(renames)
print(model.class_descriptors())
['LShape;', 'LAbstractShape;', 'Lcom/example/Round;', 'LRectangle;']
renames := map[string]string{"LCircle;": "Lcom/example/Round;"}
model.RenameTypes(renames)
fmt.Println(model.ClassDescriptors())
[LShape; LAbstractShape; Lcom/example/Round; LRectangle;]
Map<String, String> renames = Map.of("LCircle;", "Lcom/example/Round;");
model.renameTypes(renames);
System.out.println(model.classDescriptors());
[LShape;, LAbstractShape;, Lcom/example/Round;, LRectangle;]

rename_types (Go: RenameTypes, Java: renameTypes) takes a mapping from old descriptor to new descriptor. It changes every reference to each class: the class itself, superclasses and interfaces, method and field identities, array types, instructions, catch types, annotations, and the class names inside generic signatures.

It does not change:

  • string constants, so a name passed to Class.forName("...") stays as it is;
  • Kotlin metadata;
  • the simple name stored in an inner class's InnerClass annotation.

Rename an inner class together with its outer class.

Check before writing

problems: list[dexpp.Problem] = model.validate()
print("problems:", problems)

stats: dexpp.PoolStats = model.pool_stats()
print(stats.strings, "strings,", stats.types, "types,", stats.methods, "methods")
needed: int = model.required_version()
print("needs DEX version", needed)
problems: []
22 strings, 8 types, 12 methods
needs DEX version 35
problems := model.Validate()
fmt.Println("problems:", problems)

stats := model.PoolStats()
fmt.Println(stats.Strings, "strings,", stats.Types, "types,", stats.Methods, "methods")
needed := model.RequiredVersion()
fmt.Println("needs DEX version", needed)
problems: []
22 strings, 8 types, 12 methods
needs DEX version 35
List<Problem> problems = model.validate();
System.out.println("problems: " + problems);

PoolStats stats = model.poolStats();
System.out.println(stats.strings() + " strings, " + stats.types() + " types, "
        + stats.methods() + " methods");
int needed = model.requiredVersion();
System.out.println("needs DEX version " + needed);
problems: []
22 strings, 8 types, 12 methods
needs DEX version 35
  • validate() (Go: Validate()) lists every rule of the format the model breaks. Each Problem has a where and a message (Go: Where and Message). An empty list means the model can be written.
  • pool_stats() (Go: PoolStats(), Java: poolStats()) says how many entries each table of the written file would have. A DEX file can hold at most 65,535 types and prototypes, and 65,536 fields and methods. Use this to decide when a file is full and classes must go to another one.
  • required_version() (Go: RequiredVersion(), Java: requiredVersion()) is the lowest DEX version that has every feature the model uses. Writing never raises the version by itself. Set the model's version when a higher one is needed: model.version = 37 in Python, model.SetVersion(37) in Go, model.setVersion(37) in Java.

Write

data: bytes = model.write()
again: dexpp.Model = dexpp.Model.read(data)
print(len(data), "bytes;", "writing is repeatable:", again.write() == data)
1364 bytes; writing is repeatable: True
data, err := model.Write(true)
if err != nil {
    log.Fatal(err)
}
again, err := dexpp.ReadModel(data, true)
if err != nil {
    log.Fatal(err)
}
defer again.Close()
againData, err := again.Write(true)
if err != nil {
    log.Fatal(err)
}
fmt.Println(len(data), "bytes; writing is repeatable:", bytes.Equal(againData, data))
1364 bytes; writing is repeatable: true
byte[] data = model.write();
try (Model again = Model.read(data)) {
    boolean repeatable = Arrays.equals(again.write(), data);
    System.out.println(data.length + " bytes; writing is repeatable: " + repeatable);
}
1364 bytes; writing is repeatable: true

write() (Go: Write) returns the bytes of a DEX file, and write_file(path) (Go: WriteFile, Java: writeFile) writes a file. Both check the model first and write nothing if it is not valid.

Writing is deterministic: the same model always gives the same bytes. Reading the output and writing it again gives the same bytes too.

Writing can strip line numbers and local variable names. In Python, pass debug_info=False. In Go, pass false to Write or as the second argument of WriteFile. In Java, use write(false) or writeFile(path, false).

What changes in a round trip

Reading a file and writing it back gives a file with the same program, but not always the same bytes as the input. The writer chooses its own layout and encodings.

A few things are not kept:

  • hidden-API flags, which only exist in boot class path files;
  • the link section;
  • debug positions that point past the end of a method's code;
  • data that no instruction refers to.

Errors

The model has its own errors. Each one says what to do next.

Call Failure Python raises Go error matches Java throws
read the input is not a valid DEX file dexpp.InvalidDexError dexpp.ErrInvalidDex InvalidDexException
read the input uses a format the model does not read, such as the DEX version 41 container dexpp.UnsupportedDexError dexpp.ErrUnsupportedDex UnsupportedDexException
read a file the file does not exist FileNotFoundError dexpp.ErrFileNotFound NoSuchFileException
read a file the file exists but cannot be read OSError dexpp.ErrCannotRead FileSystemException
write the model breaks rules of the format dexpp.InvalidModelError dexpp.ErrInvalidModel InvalidModelException
write a table would have more entries than the format allows dexpp.PoolOverflowError dexpp.ErrPoolOverflow PoolOverflowException
write a feature needs a higher DEX version than the model's version dexpp.VersionTooLowError dexpp.ErrVersionTooLow VersionTooLowException
write a file the file cannot be created or written OSError dexpp.ErrCannotWrite FileSystemException
copy or move a class the class is missing in the source or present in the destination dexpp.ModelError dexpp.ErrModel ModelException

In Python and Java, the errors of a failed write (an invalid model, a table overflow, a version that is too low) are subclasses of the model error: dexpp.ModelError in Python, ModelException in Java. So one except or catch handles every failed write. In Go, compare with the values in the table through errors.Is, or read the Code of the *dexpp.Error with errors.As.

See Concepts for errors in general, Errors in Go, and Errors on the Java page.

Input that is not a DEX file

try:
    dexpp.Model.read(b"not a dex file")
except dexpp.InvalidDexError as error:
    print("InvalidDexError:", error)
InvalidDexError: not a DEX file (bad magic)
_, err := dexpp.ReadModel([]byte("not a dex file"), true)
if errors.Is(err, dexpp.ErrInvalidDex) {
    fmt.Println("invalid DEX:", err)
}
invalid DEX: not a DEX file (bad magic)
try (Model model = Model.read("not a dex file".getBytes(StandardCharsets.UTF_8))) {
    System.out.println(model.classCount());
} catch (InvalidDexException e) {
    System.out.println("InvalidDexException: " + e.getMessage());
}
InvalidDexException: not a DEX file (bad magic)

Reading is strict. A file with something the model could not write back faithfully, such as an unused opcode or a branch into the middle of an instruction, is refused as an invalid DEX file.

A model that is not valid

The error for an invalid model carries the list of broken rules: problems in Python, Problems of the *dexpp.Error in Go, problems() in Java. It is the list validate() returns.

broken: dexpp.Model = dexpp.Model.read_file("tests/data/shapes.dex")
broken.rename_types({"LCircle;": "not a descriptor"})
try:
    broken.write()
except dexpp.InvalidModelError as error:
    print(len(error.problems), "problems")
    for problem in error.problems:
        print(" ", problem.where, "-", problem.message)
2 problems
  not a descriptor - invalid class descriptor "not a descriptor"
  not a descriptor-><init>(Ljava/lang/String;D)V, item 3 - invalid class descriptor "not a descriptor"
broken, err := dexpp.ReadModelFile("../../../tests/data/shapes.dex", true)
if err != nil {
    log.Fatal(err)
}
defer broken.Close()
broken.RenameTypes(map[string]string{"LCircle;": "not a descriptor"})

_, err = broken.Write(true)
var modelErr *dexpp.Error
if errors.As(err, &modelErr) && modelErr.Code == dexpp.CodeInvalidModel {
    fmt.Println(len(modelErr.Problems), "problems")
    for _, problem := range modelErr.Problems {
        fmt.Println(" ", problem.Where, "-", problem.Message)
    }
}
2 problems
  not a descriptor - invalid class descriptor "not a descriptor"
  not a descriptor-><init>(Ljava/lang/String;D)V, item 3 - invalid class descriptor "not a descriptor"
try (Model broken = Model.readFile(Path.of("../../tests/data/shapes.dex"))) {
    broken.renameTypes(Map.of("LCircle;", "not a descriptor"));
    try {
        broken.write();
    } catch (InvalidModelException e) {
        System.out.println(e.problems().size() + " problems");
        for (Problem problem : e.problems()) {
            System.out.println("  " + problem.where() + " - " + problem.message());
        }
    }
}
2 problems
  not a descriptor - invalid class descriptor "not a descriptor"
  not a descriptor-><init>(Ljava/lang/String;D)V, item 3 - invalid class descriptor "not a descriptor"

A table that is too large

A table overflow means the classes do not fit in one DEX file. A file holds at most 65,536 methods and 65,536 fields. Move some classes to another model and write two files. To avoid the error, check the pool statistics while you fill a model, before you write it.

A version that is too low

defaults: dexpp.Model = dexpp.Model.read_file("tests/data/inherit.dex")
defaults.version = 35
try:
    defaults.write()
except dexpp.VersionTooLowError as error:
    print("VersionTooLowError:", error)

defaults.version = defaults.required_version()
print("written with version", defaults.version, "-", len(defaults.write()), "bytes")
VersionTooLowError: the model needs DEX 037 (LGreeter;->greet()V: a private or default interface method), but its version is 035
written with version 37 - 4024 bytes
defaults, err := dexpp.ReadModelFile("../../../tests/data/inherit.dex", true)
if err != nil {
    log.Fatal(err)
}
defer defaults.Close()
defaults.SetVersion(35)
if _, err := defaults.Write(true); errors.Is(err, dexpp.ErrVersionTooLow) {
    fmt.Println("version too low:", err)
}

defaults.SetVersion(defaults.RequiredVersion())
data, err := defaults.Write(true)
if err != nil {
    log.Fatal(err)
}
fmt.Println("written with version", defaults.Version(), "-", len(data), "bytes")
version too low: the model needs DEX 037 (LGreeter;->greet()V: a private or default interface method), but its version is 035
written with version 37 - 4024 bytes
try (Model defaults = Model.readFile(Path.of("../../tests/data/inherit.dex"))) {
    defaults.setVersion(35);
    try {
        defaults.write();
    } catch (VersionTooLowException e) {
        System.out.println("VersionTooLowException: " + e.getMessage());
    }

    defaults.setVersion(defaults.requiredVersion());
    System.out.println("written with version " + defaults.version() + " - "
            + defaults.write().length + " bytes");
}
VersionTooLowException: the model needs DEX 037 (LGreeter;->greet()V: a private or default interface method), but its version is 035
written with version 37 - 4024 bytes

Memory

A model takes about 15 to 25 times the size of its DEX file, because every reference is held as a name. Reading a 40 MB DEX file needs several hundred megabytes.