Changelog¶
0.3.1¶
APK from memory¶
- An APK can be opened from its bytes in memory, not only from a file. The
bytes get the same checks as a file, and everything an opened APK offers
works the same: archive entries, the manifest, resources, signing and the
code. The APK keeps its own copy of the bytes. An optional label names the
bytes at the start of error messages, where a file gives its path.
- C++:
dex::apk::Apk::from_buffer(bytes, label). One overload takes astd::vector<uint8_t>by value, so a vector passed withstd::moveis not copied; the other takes astd::span<const uint8_t>and copies it. - Python:
dexpp.Apk.from_bytes(data, label="<apk>"), for any bytes-like object, including a non-contiguousmemoryview. - C:
dexpp_apk_open_buffer(bytes, len, label, err). - Go:
dexpp.OpenAPKBytes(data, label). - Java:
Apk.fromBytes(data)andApk.fromBytes(data, label).
- C++:
- The APK's
analysis()now takes a thread count, like loading an APK with the analysis context: 1 keeps all the work, the call graph included, on the calling thread. The analysis is kept for each thread count: a second call with the same count returns the same analysis, and a call with another count builds a separate one.- C++:
Apk::analysis(const ApkLoadOptions & = {}).ApkLoadOptionsnow hasoperator==. - Python:
Apk.analysis(threads=0). - Go:
Apk.Analysis(opts ...LoadOption), withWithThreads. - Java:
Apk.analysis(int threads), next toanalysis().
- C++:
- The errors of the APK's
analysis()now start with the APK's path (or the label), not with<apk>. - Breaking, C:
dexpp_apk_analysistakes auint32_t threadsargument before the error argument, asdexpp_context_from_apkdoes. Pass 0 for the old behaviour.
0.3.0¶
Platforms¶
- dex++ now builds and is tested on macOS (Apple Silicon and Intel, with Apple Clang) and on Windows x64 (with MSVC), next to Linux. CI runs the C++ tests and the Python tests on all three, and the Go tests on Linux and macOS.
- Releases now publish wheels for macOS 14 or newer (one for arm64, one for x86_64) and for Windows x64, next to the Linux ones.
- The Go package links libc++ on macOS. It does not support Windows.
- The Python module is now placed directly in the build folder with every
CMake generator, so
PYTHONPATH=buildworks with Visual Studio too. - With MSVC, the library is compiled with Microsoft's
_DISABLE_CONSTEXPR_MUTEX_CONSTRUCTOR. Without it, code built with Visual Studio 2022 17.10 or newer crashes the first time it takes a lock when the process has loaded an oldermsvcp140.dll. A JVM loads the one in the JDK'sbinfolder, and JDK 22 ships an older one; a Python process can have loaded an older one too.
Packaging¶
- dexpp works with Python 3.10 and newer again (0.2.0 needed 3.14). Releases publish wheels for CPython 3.10, 3.11, 3.12, 3.13 and 3.14 on every platform: Linux x86_64 (glibc and musl), macOS arm64 and x86_64, and Windows x64. CI runs the Python tests on 3.10 and 3.14, the oldest and the newest.
- The package metadata now lists the supported Python versions and macOS and Windows, next to Linux.
Documentation¶
- dex++ now has a documentation site, https://burogurama.github.io/dexpp/: guides for APK metadata, code analysis, the call graph, cross-references and DEX editing, a Python reference, and a C++ and C reference. It is published from each release tag, so it describes the latest release.
- Every class, method and property in the Python type stubs now has a docstring, so editors show a description next to each completion.
- The examples in the guides are run by the tests, with the output the guides show.
- The quick start, the guides and the home page show every example in Python,
Go and Java, in tabs; choosing a language switches every example on the
site. The Go and Java versions are run by
go testand by the Java tests.
One vocabulary in every language (breaking)¶
These renames make C++, Python, C, Go and Java use the same word for the same thing. The old names are gone; there are no aliases.
Class.nameis nowClass.descriptor. It always returned the class descriptor, such as"Lcom/example/Foo;", whileMethod.nameandField.nameare simple names, and every other place calls this string a descriptor. The new names areClass::descriptor()in C++,Class.descriptorin Python,dexpp_class_descriptorin C,Class.Descriptor()in Go andDexClass.descriptor()in Java.Class.packagenow gives the package in Java source form, with dots:"com.example", not"com/example". This is the formManifest.packageuses, so the two can be compared. Before, a test such ascls.package.startswith(manifest.package)was false for the app's own classes whenever the package name has a dot, and nothing said why. The default package is still an empty string. This applies to C++ (Class::package(), which now returns astd::stringinstead of astd::string_view), Python, C (dexpp_class_package), Go (Class.Package()) and Java (DexClass.packageName()).- Two enums are renamed, so that each name says what it is about:
EdgeKind, the kind of a control-flow-graph edge, is nowCfgEdgeKindin C++ and Python. C, Go and Java already called itDexppCfgEdgeKindandCfgEdgeKind.TypeRefKind, what an instruction does with the type it names, is nowTypeUseKind:dex::TypeUseKindin C++,dexpp.TypeUseKindin Python,DexppTypeUseKindwith the valuesDEXPP_TYPE_USE_CONST_CLASSand so on in C,TypeUseKindwith the constantsTypeUseConstClassand so on in Go, andTypeUseKindin Java. The C++ helpertype_ref_kind_from_opcodeis no longer public (see "C++ API (breaking)"). The member names and numbers do not change.
- A method's prototype, such as
"(Ljava/lang/String;I)V", is calledprotoeverywhere, as inMethodId.proto. The accessor that called it a descriptor is renamed:dexpp_method_descriptoris nowdexpp_method_protoin C,Method.Descriptor()is nowMethod.Proto()in Go, andDexMethod.descriptor()is nowDexMethod.proto()in Java. - The model's class summary now holds the list of interfaces itself, instead
of only their number, and the separate call for the list is gone. Before,
that call returned an empty list for a class the model does not have, while
every other lookup reports a missing class as not found. Now the summary is
the only lookup, and a missing class gives
Nonein Python, 0 in C,falsein Go and an emptyOptionalin Java, as before.- Python:
ClassInfo.interfaces(alist[str]) replacesClassInfo.interface_countandModel.class_interfaces(). - C:
DexppClassInfohas a new memberinterfaces(an array of strings), andinterface_countis now its length.dexpp_class_info_clearfrees it.dexpp_model_class_interfacesis removed. - Go:
ClassInfo.Interfaces(a[]string) replacesClassInfo.InterfaceCountandModel.ClassInterfaces(). - Java:
ClassInfo.interfaces()(aList<String>) replacesClassInfo.interfaceCount()andModel.classInterfaces().
- Python:
- Python's
Modelhad two ways to count its classes and two ways to test for one.Model.class_countandModel.has_class()are removed: uselen(model)anddescriptor in model. C, Go and Java keep their single way:dexpp_model_class_countanddexpp_model_has_class,Model.ClassCount()andModel.HasClass(),Model.classCount()andModel.hasClass().
No magic numbers, no raw indices, no hidden cases¶
These changes make every value say what it is. A number that only meant something together with a table nobody could read, a special value that stood for a different case, and one type that held several different cases are gone. Most of them are breaking; the old names are gone, with no aliases.
- A method's identity and prototype, and a field's identity, are now one call
in every language. Go and Java already had
Method.ID()/id(),Method.Proto()/proto()andField.ID()/id(); C++ and Python had none of them.- C++:
Method::id()returns theMethodId,Method::proto()the prototype (such as"(Ljava/lang/String;I)V"), andField::id()theFieldId. - Python: the properties
Method.id,Method.protoandField.id. - C:
dexpp_method_id()anddexpp_field_id()fill aDexppMethodIdor aDexppFieldId. The newdexpp_field_id_clear()frees aDexppFieldId. - Go and Java now get each identity with one call to C, instead of one call for each part.
- C++:
- Breaking: a method handle value (in an annotation, or as a static field's
initial value) is now resolved. Before, it was only a raw index into one
DEX file's method handle table, which no public call could resolve. Now it
has a
kind, which says what the handle does, and amember, the field or the method it works on. The kind is a new enum,MethodHandleKind, with the nine method handle types of the DEX format:STATIC_PUT,STATIC_GET,INSTANCE_PUTandINSTANCE_GETwork on a field (aFieldId), andINVOKE_STATIC,INVOKE_INSTANCE,INVOKE_CONSTRUCTOR,INVOKE_DIRECTandINVOKE_INTERFACEcall a method (aMethodId). In C++ the enum isdex::MethodHandleKind, incommon/method_handle_kind.hpp: the editable model'smodel::MethodHandlenow uses the same enum, so the analysis and the model share one vocabulary (code that named itdex::model::MethodHandleKindnow namesdex::MethodHandleKind).- C: the enum
DexppMethodHandleKindand the memberDexppValue.method_handle_kindreplacemethod_handle_index; the member is infieldormethod. - Go:
MethodHandleValue.Kind(aMethodHandleKind) andMethodHandleValue.Member(aMemberID: aMethodIDor aFieldID) replaceIndex. - Java:
MethodHandleValue.kind()andMethodHandleValue.member()(aMemberId, the new sealed interface ofMethodIdandFieldId) replaceindex().
- C: the enum
- Breaking: the annotation value classes are renamed so that they do not
look like handles or cross-references. They are plain values:
TypeRefis nowTypeValue,EnumRefisEnumValue,FieldRefisFieldValue,MethodRefisMethodValue,MethodTypeRefisMethodTypeValueandMethodHandleRefisMethodHandleValue. This applies to the nested types ofdex::AnnotationValuein C++, the Python classes, the Go types and the Java records. C keeps itsDEXPP_VALUE_*kinds. - Breaking: decoded instructions no longer hide distinct cases. There are now
28 instruction types instead of 24:
MoveInstruction.srcis optional. It is empty (std::nulloptin C++,Nonein Python,HasSrcfalse in Go, an emptyOptionalIntin Java,has_src0 in C) formove-result*andmove-exception, which name no source register. Before, it was 0, which is also the real registerv0.invoke-polymorphicandinvoke-polymorphic/rangedecode to a newInvokePolymorphicInstruction, with the method index, the index of the call site's prototype, and the argument registers. Before, they were a plainInvokeInstructionand the prototype index was lost. They stay call sites: the call graph,Method.calls()and the cross-references list them with the kindPOLYMORPHIC, as before.array-lengthdecodes to a newArrayLengthInstruction(destandarray_reg). Before, it was aUnaryOpInstruction, which nothing said.- An opcode the format does not use decodes to a new
InvalidInstruction, whose opcode is the raw byte. Before, it was aNopInstruction, so a damaged method looked fine. The control-flow graph still treats it like anop. ConstHandleInstruction, whoseindexpointed into one of two tables depending on the opcode, is split intoConstMethodHandleInstruction(method_handle_index) andConstMethodTypeInstruction(proto_index).to_stringnow writes these operands asmethod_handle@Nandproto@N, instead ofidx@N.
In C, the instruction kinds are DEXPP_INSN_CONST_METHOD_HANDLE (11, which
was DEXPP_INSN_CONST_HANDLE), DEXPP_INSN_CONST_METHOD_TYPE (24),
DEXPP_INSN_INVOKE_POLYMORPHIC (25), DEXPP_INSN_ARRAY_LENGTH (26) and
DEXPP_INSN_INVALID (27); DexppInstruction has the members
method_handle_index and proto_index instead of index, and has_src
now also applies to DEXPP_INSN_MOVE. Go and Java have the same five types
and records.
- Breaking: a control-flow-graph edge no longer has a label. The label was
one optional integer with two meanings: the case key of a switch-case edge,
or, on an exception edge, the caught type as a raw index into one DEX
file's type table, with 4294967295 for a handler that catches everything.
No public call could turn that index into a name. Now:
- case_key is the case key, set only for SWITCH_CASE edges.
- catch_type is the descriptor of the caught exception class, such as
"Ljava/io/IOException;", set only for EXCEPTION edges.
- A handler that catches everything (how Java compiles finally) gets
edges of a new kind, EXCEPTION_CATCH_ALL, with no catch type.
EXCEPTION edges now always go to a handler of one class. A switch
already worked this way: SWITCH_DEFAULT is its own kind, apart from
SWITCH_CASE.
In C++ these are CfgEdge::case_key (std::optional<int32_t>),
CfgEdge::catch_type (std::optional<std::string_view>, valid as long as
the context) and CfgEdgeKind::ExceptionCatchAll. In Python,
CfgEdge.case_key, CfgEdge.catch_type and
CfgEdgeKind.EXCEPTION_CATCH_ALL. In C, DexppCfgEdge.case_key,
DexppCfgEdge.catch_type (a string the edge owns, freed by
dexpp_basic_block_array_free) and DEXPP_CFG_EXCEPTION_CATCH_ALL replace
has_label and label. In Go, CfgEdge.CaseKey, CfgEdge.CatchType and
CfgExceptionCatchAll replace Label and HasLabel. In Java,
CfgEdge.caseKey() (an OptionalInt), CfgEdge.catchType() (an
Optional<String>) and CfgEdgeKind.EXCEPTION_CATCH_ALL replace label().
- Breaking: a call-graph node now has a kind instead of the resolved
flag. The flag mixed two different cases: an invoke-custom call site was
an unresolved node, like a framework method, with a made-up identity of the
form ("call_site", "#<dex>:<index>", "") that looked like a method. The
kind is DEFINED (a method defined in a loaded file), EXTERNAL (a method
the code calls but no loaded file defines) or CALL_SITE (an
invoke-custom call site). The identity of a CALL_SITE node is opaque: it
only keeps call sites apart, and it may change.
- C++: the enum dex::CallNodeKind and CallNode::kind replace
CallNode::resolved.
- Python: the enum dexpp.CallNodeKind and CallNode.kind.
- C: the enum DexppCallNodeKind (DEXPP_CALL_NODE_DEFINED,
DEXPP_CALL_NODE_EXTERNAL, DEXPP_CALL_NODE_CALL_SITE) and the member
DexppCallNode.kind replace DexppCallNode.resolved.
- Go: the type CallNodeKind (CallNodeDefined, CallNodeExternal,
CallNodeCallSite) and the field CallNode.Kind replace
CallNode.Resolved.
- Java: the enum CallNodeKind and CallNode.kind() replace
CallNode.resolved().
Python bindings¶
- The enums
InvokeKind,EdgeOrigin,CfgEdgeKind,TypeUseKind,OperandWidth,AnnotationVisibilityandComponentKindare now real Python enums, subclasses ofenum.Enum, as the type stubs already said.list(dexpp.InvokeKind)lists the members,isinstance(kind, enum.Enum)is true, and the members can be pickled. The member names do not change, andkind.name,kind.value,==and hashing work as before. Breaking: a member is no longer a number, soint(kind)raisesTypeError. Usekind.value, which gives the same numberint(kind)gave. Passing anything other than a member of the right enum toCallEdgeView.whereorManifest.components_ofraisesTypeError. - Every function and method now takes its arguments by keyword, under the
names the type stubs give them. Before, 25 of them took positional arguments
only, so a call such as
ctx.find_class(descriptor="LFoo;")orxrefs.string_refs(value="...")passed the type checker and then failed withTypeError. The type stubs now also say thatModel.readtakes any bytes-like object (bytes,bytearray,memoryview), which it always accepted. Class,Method,FieldandClassRefobjects now compare equal when they point at the same class, method or field of the same analysis, and they can be dictionary keys and set members. Before,ctx.find_class("LA;") == ctx.find_class("LA;")wasFalse, because each call makes a new Python object, and asetof methods did not remove duplicates. The same file loaded twice gives two analyses, and their objects are not equal.- The annotation value classes (
TypeRef,EnumRef,FieldRef,MethodRef,MethodTypeRefandMethodHandleRef, now renamed; see "No magic numbers, no raw indices, no hidden cases") andResourceNamecould be compared but not hashed, so they could not be dictionary keys or set members. They now have a hash that matches their equality. - Breaking: thirteen properties that do a lot of work on every read are now
methods, so they need
():AnalysisContext.classes()(makes a newClassobject for every class of every DEX file),AnalysisContext.strings()(copies every string of every DEX file),Xrefs.referenced_strings(),CallNode.callers()andCallNode.callees()(collect, deduplicate and sort the nodes again; for a method called from many places,callers()goes through every one of those call sites; both still return aCallNodeView),Method.calls(),Method.field_accesses(),Method.string_loads()andMethod.type_uses()(go through the method's bytecode again and build new objects; a loop such asfor i in range(len(m.calls)): m.calls[i]went through the method once per step),Apk.entries()(reads the whole ZIP central directory again),Model.class_descriptors()(copies every descriptor),Model.required_version()(runs the whole validator) andModel.pool_stats()(walks the whole model). The rule, written in the Python reference, is that a property is cheap or cached and a method computes. Code that still reads one of them without()gets the bound method instead of the result. Method.instructionsis now adexpp.InstructionView, a read-only sequence over the decoded bytecode, likeCfg.blocks. It copies nothing up front; before, every read of the property built a new list of every instruction. Indexing, slicing (which returns alist),len()and iteration work as before. Code that changed the list in place, or compared it with a list, must calllist(method.instructions)first.access_flags(onClass,Method,FieldandClassInfo) is now adexpp.AccessFlags, anenum.IntFlagwith one member per DEX flag:dexpp.AccessFlags.STATIC in method.access_flags. It is still anint, so code that compared it with numbers keeps working.- dexpp now raises its own exceptions, one per kind of error, where it raised
a plain
ValueErrorbefore:
| Exception | Raised when |
|---|---|
InvalidApkError |
a file is not a ZIP archive, or an APK has no classes.dex |
InvalidDexError |
a DEX file cannot be parsed |
UnsupportedDexError |
Model.read gets a format it does not read (DEX version 41) |
InvalidModelError |
Model.write gets a model that breaks rules of the format; its problems attribute lists them |
PoolOverflowError |
Model.write would need a table with more entries than the format allows |
VersionTooLowError |
Model.write gets a model that needs a higher DEX version |
ModelError |
Model.copy_class or Model.move_class cannot find the class, or the destination already has it; also the base class of the three above |
All of them derive from dexpp.Error, and dexpp.Error derives from
ValueError, so code that catches ValueError keeps working.
- Model.read_file and Model.write_file raised FileNotFoundError for every
file problem. read_file now raises it only when the file does not exist,
and OSError when the file exists but cannot be read. write_file raises
OSError when the file cannot be created or written (breaking for code that
caught FileNotFoundError around write_file).
- AnalysisContext.from_dex, from_dex_files, from_apk and Apk.open now
raise OSError for a path that exists but cannot be read. A directory path
made them raise MemoryError before (see "Fixes").
- dexpp.Instruction and dexpp.AnnotationValue now exist in the module. The
type stubs already declared these two unions, but the module did not have
them, so isinstance(x, dexpp.Instruction) raised AttributeError.
C and Go bindings¶
- The C API (
bindings/c/dexpp.h) now covers the whole analysis API, the same ground as the Python binding. Before, it had loading, classes, the names, descriptors and flags of methods, the string table, and the manifest's package and components. New: fields and class references, decoded instructions withdexpp_opcode_nameanddexpp_instruction_to_string, control-flow graphs, try blocks, annotations with typed values and the initial values of static fields, a method's calls, field accesses, string loads, type uses and parameter registers, the call graph, the class hierarchy, the cross-reference index, and the whole manifest, resources, archive entries and signing information of an APK. The header's first comment gives the rules for memory, arrays and threads. - Breaking for C callers: every function that can fail now takes a
DexppError **errinstead of achar **err. The error object gives a code (dexpp_error_code, one value per kind of failure, matching the Python exceptions), a message (dexpp_error_message) and, for a model that breaks rules of the DEX format, the list of problems (dexpp_error_problem_count,dexpp_error_problem_where,dexpp_error_problem_message). Free it withdexpp_error_free. - Other changes that break C callers:
dexpp_context_from_apktakes the number of threads;dexpp_class_superclassanddexpp_class_interfacesreturnDexppClassRefhandles instead of strings;dexpp_context_stringsreturnsDexppText, which keeps NUL bytes;dexpp_method_call_countis replaced bydexpp_method_calls;dexpp_apk_componentsis replaced bydexpp_apk_manifest; anddexpp_class_info_freeis renameddexpp_class_info_clear. - The Go package now reaches the whole analysis API too:
Field,ClassRef,Method.Instructions(anInstructioninterface with one struct type per opcode family),OpcodeName,ToString,Method.Cfg,Method.TryBlocks,AnnotationsandField.InitialValue,Method.Calls,FieldAccesses,StringLoads,TypeUsesandParameterRegisters,CallGraph,ClassHierarchy,Xrefs,FromDEXFiles, theWithThreadsoption ofFromAPK, the wholeManifestwith intent filters,ResourceTable,Apk.Entries,Apk.Read,Apk.SigningandVersion. - Go errors are now
*dexpp.Errorvalues with aCode, aMessageand, for an invalid model, theProblems. Each code has a sentinel, such asdexpp.ErrInvalidDex, forerrors.Is, anderrors.Is(err, fs.ErrNotExist)is true for a missing file. Before, errors were plain strings. - Changed Go signatures (breaking):
Class.Superclass()returns a*ClassRef, which is nil forjava.lang.Object, instead of a string that was empty when there was no superclass.Class.Interfaces()returns[]*ClassRefinstead of[]string.- The component kind constants are renamed:
Activity,Service,ReceiverandProviderare nowComponentActivity,ComponentService,ComponentReceiverandComponentProvider. Apk.Components()is replaced byApk.Manifest(), which returns the whole manifest. InComponent,Exportedis now the attribute as the manifest writes it (a*bool, nil when missing),IsExportedis the effective answer, andReachableis renamedIsReachable.Apk.Package()returns(string, bool), false when the APK has no manifest, instead of an empty string.Class.AccessFlags(),Method.AccessFlags()andClassInfo.AccessFlagsare adexpp.AccessFlagsinstead of auint32.Method.CallCount()is removed. Its comment said it counted resolved calls, but it counted every invoke instruction.len(m.Calls())gives the same number.
- Go: calling a method on a closed or nil handle now panics with a message
that names the handle type, instead of passing a null pointer to C.
Close()on a nil handle does nothing. - The C API can now be built as one shared library,
dexpp_c_shared(libdexpp_c_shared.so,libdexpp_c_shared.dylibordexpp_c_shared.dll), with the CMake option-DDEXPP_BUILD_C_SHARED=ON. It holds the C layer and the C++ library, and exports thedexpp_functions and nothing else. Every declaration in the C headers is marked with the newDEXPP_C_APImacro for this; it is empty in every other build. The staticdexpp_cthat Go links does not change. - The
_array_freefunctions of handle arrays (classes, class references, methods, fields) are documented to free the array alone when the count is 0, so a caller can keep the handles. Use this instead offree()with the shared library: on Windows, the DLL and the program can use different C runtimes.
Java binding (new)¶
- dex++ has a Java package,
io.github.burogurama.dexpp, inbindings/java, built with Maven. It needs Java 22 or newer: it calls the C API from the shared library through the Foreign Function & Memory API, with no JNI code. It reaches the same API as the Go package: loading DEX files and APKs, classes, methods and fields, decoded bytecode, control-flow graphs, try blocks, annotations, the call graph, the class hierarchy, cross-references, the manifest, resources and signing of an APK, and the editable model a whole class at a time. It works on Linux, macOS and Windows, from a checkout; it is not on Maven Central yet. - Handles (
AnalysisContext,Apk,DexClass,ClassRef,DexMethod,DexField,CallGraph,ClassHierarchy,Xrefs,Model) areAutoCloseable, and aCleanerfrees the ones that are never closed. Everything else is copied into Java records and immutable lists. A value that may be absent is anOptional,OptionalIntorOptionalLong. - Instructions are a sealed interface with one record per kind, and
annotation values are a sealed interface too, so a pattern-matching
switchtells them apart. Access flags are anAccessFlagsrecord with one constant per flag. - A file that cannot be opened throws
NoSuchFileExceptionorFileSystemException. Every other error throws an uncheckedDexppExceptionthat carries the C error code. Its subclasses match the Python exceptions:InvalidApkException,InvalidDexException,UnsupportedDexException,ModelException, and below itInvalidModelException(with the list of problems),PoolOverflowExceptionandVersionTooLowException. - The documentation site has a Java page, with examples that the tests run. CI builds the shared library and runs the Java tests on Linux, macOS and Windows, with Java 22 and Java 25.
Fixes¶
- A damaged APK Signing Block could make
parse_signing_info(and soApk::signing()/Apk.signing) read outside the APK's memory, or loop forever. Two size checks were written asa + b > c, and a huge size taken from the file wrapped around and passed them. The fuzzer found it; the checks now compare by subtraction. - The manifest now reads the
android:attributes by resource id, as Android does, instead of by name. Before, an app could hideandroid:exported(and so changeis_exportedandis_reachable) by renaming the attribute's name string, or add an attribute that is only namedexportedand have dexpp read it although Android ignores it. The binary-XML decoder now gives each attribute itsresource_idand each documenthas_resource_map, andXmlNode::attribute_by_id()finds an attribute by id. For a document without a resource map (not written by aapt or aapt2), the manifest falls back to the attribute name in the android namespace. - Go: the short methods of
ClassandMethod(Name,Package,Superclass,AccessFlagsand others), and the early-return paths ofClasses,Strings,Interfaces,MethodsandComponents, did not keep their handle alive during the C call. In code such asctx.FindClass(d).Name(), the garbage collector could free the handle while C was still using it. Every method now keeps its handle alive until it returns. - Python: some small value objects could read freed memory. These strings
pointed into the analysis's memory:
StringLoad.value,TypeUse.descriptor,CatchHandler.type_descriptor(inTryBlock.handlers),ParameterRegister.type, andCfgEdge.catch_type(inBasicBlock.successors). But these objects do not keep the analysis alive. So once the lastAnalysisContextand every handle from it were gone, reading one of these strings gave garbage, raisedUnicodeDecodeError, or crashed. It happened to the results ofstring_loads(),type_uses(),try_blocksandparameter_registers, and to everyBasicBlockfromCfg.blocks,Cfg.entryandCfg.block_at_offset(). These objects now hold their own copy of each string, made when the object is created, so they stay valid on their own. The Python API does not change. C, Go and Java were not affected: they always copied the strings. Model.readin Python read the wrong memory when it got a buffer whose bytes are not next to each other, such as a reversed or stridedmemoryview: it read forward from the buffer's start and could go past its end. It now reads the bytes in order, copying them first when the buffer is not contiguous.- Loading a path that is a directory no longer fails with an out-of-memory
error.
AnalysisContext::from_dex,from_dex_files,from_apk,apk::Apk::openandraw::parser::parse_fileread the size of the "file", got a meaningless value, and tried to allocate that much memory. They now return an error. The new error codeAnalysisError::Code::CannotReadmeans "the path exists but cannot be read";FileNotFoundnow means only that the path does not exist. model::read_fileno longer lets astd::ios_base::failureexception escape for a path it can open but not read, such as a directory. It returns anIoerror.- Every loader now reads its file through one function,
raw::read_whole_file, which does not trust a file size it did not read. model::write_file(andModel.write_filein Python,dexpp_model_write_filein C,Model.WriteFilein Go) could report success when the file was not written, for example on a full disk: the error showed up only when the file was closed, and that result was not checked. It is now reported asCannotWrite(anOSErrorin Python).- C API: a function that returns an empty string no longer passes a null
pointer to
memcpy, which is undefined behaviour.dexpp_class_packagedid this for every class in the default package. - A class defined in more than one loaded DEX file now gets one answer
everywhere: the first definition, in load order (for an APK,
classes.dex, thenclasses2.dex, and so on). This is what Android does: an app's class loader searches its DEX files in that order and stops at the first one that defines the class (DexPathList.findClass, andClassLinker::FindClassInBaseDexClassLoaderClassPathin ART). Before,find_classreturned the first definition, the call graph'smethod_forreturned the last one and added the edges of every definition's code, and the class hierarchy took the superclass of the last definition and the interfaces of all of them. Now the call graph, the class hierarchy and the cross-references use only the first definition, asfind_classalready did: a later definition adds no node, no edge, no supertype and no cross-reference.classes()still lists every definition. The call-graph documentation said "the last definition wins, as on Android"; that was wrong, and it now describes the rule above. - A boolean or integer manifest attribute given by a resource reference, such
as
android:exported="@bool/is_exported"orandroid:debuggable="@bool/debug", read as "not set". Forexportedthat was a security problem:is_exportedthen fell back to the intent-filter rule, sois_reachablecould call an exported component unreachable.Apk::manifest()now resolves such references through the APK's resource table, in its default configuration, forexported,debuggable,allowBackup,versionCode,minSdkVersion,targetSdkVersionandprotectionLevel. The reference id is kept next to the value:Component::exported_referenceandManifest::version_code_reference(),min_sdk_reference(),target_sdk_reference(),debuggable_reference()andallow_backup_reference()(in Pythonexported_reference,version_code_referenceand so on; in C the*_referencemembers ofDexppComponentandDexppManifest, 0 for none; in Go the...Referencefields; in Java the...Referencerecord components). When a reference cannot be resolved (no resource table, an unknown id, a value of another type, or a theme attribute?attr/...), the value stays unset and the reference id is still there, so "not written" and "written, value unknown" can be told apart.Manifesttakes the resource table as a new, optional constructor argument; built from anXmlDocumentalone, it resolves nothing and keeps the reference ids. Text attributes (android:name,android:permission,android:versionName) are still read as written. Breaking: is_exported()(andis_reachable()) now answer true whenandroid:exportedis a reference that could not be resolved, instead of guessing from the intent filters: the value is unknown, and "possibly exported" is the safe answer for triage.declared_permission_protection_level()now returns no value for a declared permission whose level is an unresolved reference, and such a permission does not make a componentguarded_by_signature_permission. Before, the level read as normal (0).- C:
DexppComponentandDexppManifesthave new members, so code built against the olddexpp.hmust be rebuilt. - Java: the
ComponentandManifestrecords have new components, so their constructors take more arguments. ResourceTablenow resolves boolean and integer resources too:resolve_bool(id)andresolve_int(id)(Pythonresolve_boolandresolve_int, Cdexpp_apk_resolve_boolanddexpp_apk_resolve_int, GoResourceTable.ResolveBoolandResolveInt, JavaResourceTable.resolveBoolandresolveInt). Like Android'sTypedArray, both accept any integer-typed value. All the resolve functions, includingresolve_string, now follow a resource whose value refers to another resource (<bool name="a">@bool/b</bool>), for up to 20 steps as Android does; before,resolve_stringreturned nothing for such a resource.
C++ API¶
Class,Method,FieldandClassRefnow haveoperator==and astd::hashspecialization, so they can be compared and used as keys ofstd::unordered_mapandstd::unordered_set. Two handles are equal when they come from the same analysis (oneAnalysisContext, or copies of it) and point at the same class, method or field. Handles from two contexts that loaded the same file are not equal.Method::annotations(),Field::annotations()andField::initial_value()(and the same calls in Python, C and Go) no longer go through every class of the DEX file to find the member's class. Each DEX file now builds a table from type index to class the first time one of them is called, so the cost of a call no longer grows with the size of the file. The results do not change.
C++ API (breaking)¶
- One error type for the whole C++ library.
dex::AnalysisError,dex::model::Error,dex::axml::AxmlErroranddex::apk::ResourceErrorare replaced bydex::Error(incommon/error.hpp), with three fields:code, adex::ErrorCode;message; andproblems, which lists the broken rules for an invalid model and is empty otherwise. It comes back from every function that can fail: the analysis and APK loaders (AnalysisContext::from_*,apk::Apk::open,apk::Apk::analysis), the binary XML and resource table parsers (axml::parse,apk::ResourceTable::parse) and the model (model::read,read_file,write,write_file). So one function can load an APK and write a model and return a singlestd::expected. The code names match the Python exceptions and the C error codes. Before, the same failure had three names, and the AXML and resource errors had no code at all.AnalysisError::CodebecomesErrorCode:FileNotFoundandInvalidApkkeep their names,InvalidDexFileis nowInvalidDex, andCannotReadis new (a path that exists but cannot be read, such as a directory).MalformedBytecode,UnresolvedReference,UnsupportedInstructionandInvalidDescriptorare gone: the library never produced them.model::Error::kindis nowcode, and the kinds are renamed:MalformedisInvalidDex,UnsupportedisUnsupportedDex,InvalidisInvalidModelandTooLargeisPoolOverflow.VersionTooLowkeeps its name.Iois split intoFileNotFound(read_file: the path does not exist),CannotRead(read_file: the path exists but cannot be read) andCannotWrite(write_file: the file cannot be created or written).axml::parsenow fails with the codeInvalidXml, andapk::ResourceTable::parsewithInvalidResources.model::Problemis nowdex::Problem, sincedex::Errorholds the list.model::validate()returnsstd::vector<dex::Problem>.- The header
analysis/analysis_error.hppis removed;dex.hppincludescommon/error.hpp.
dex::build_cfgis no longer public. It took araw::CodeItem, a type of the internal parser layer, so it was the one public function that tied users to that layer.Method::cfg()is the way to get a control-flow graph. The public headers no longer include anyraw/header.- The handles
Class,Method,FieldandClassRefcan no longer be built by hand: their constructors, which took the library's private implementation type, are private. Get them from the library as before (AnalysisContext::classes()andfind_class(),Class::methods(),fields(),superclass()andinterfaces(),declaring_class(),CallGraph::method_for(),Xrefs::referrer_method()). The public constructorClassRef(descriptor, const AnalysisContext *)is removed too; useAnalysisContext::find_class(descriptor)to look a class up. - There is no null
Classany more.ClassRef::resolve()returnsstd::optional<Class>,std::nulloptwhen the class is not loaded, the same asAnalysisContext::find_class(). Before, it returned a default-constructedClasswhoseis_valid()was false.Classhas no default constructor and nois_valid()now, so everyClasspoints at a class. The bindings do not change: Python still givesNone, CNULL, Goniland Java an emptyOptional. TypeDescriptoris removed.Method::return_type(),Field::type()andParameterRegister::typenow give astd::string_view, andMethod::parameters()astd::vector<std::string_view>, like every other descriptor in the API (Class::descriptor(),TypeUse::descriptor, the class hierarchy) and like the Python, C, Go and Java bindings, which always gave plain strings. The views stay valid as long as the context, or any handle from it, is alive.TypeDescriptorhad a public constructor that took anystd::string_view, so it was easy to build one over a temporary string that then went away, andas_class_ref()asked for the context again through a raw pointer. Code that used its helpers can test the string itself:d.front() == '['foris_array(),d.substr(1)forelement_type(), andAnalysisContext::find_class(d)instead ofas_class_ref(&ctx)->resolve().dex::build_call_graph,dex::build_xrefsanddex::build_class_hierarchyare no longer public. They took the library's private implementation type, so no user could call them.AnalysisContext::call_graph(),xrefs()andclass_hierarchy()are the way to get these, as before.dex::invoke_kind_from_opcodeanddex::type_ref_kind_from_opcodeare no longer public. They map a raw opcode byte to anInvokeKindor aTypeUseKind, and the API already gives those kinds resolved:MethodCall::kind,TypeUse::kind,CallEdge::kindand the kinds of the cross-reference sites. No binding exposed them.- In the parser layer,
raw::ParseError::Code::NullPointer, whichraw::parser::parse_fileused for a file it could not open, is replaced byFileNotFoundandCannotRead.
Build¶
- dex++'s own sources are now compiled with
-Wall -Wextra, and the warnings GCC 13 and Clang 19 reported are fixed. The new CMake optionDEXPP_WERROR=ONturns a warning into an error. It is off by default, so a newer compiler that warns about something new does not break a build from source; CI builds with it on. - The C API now has its own tests (
tests/c/), which call every function ofdexpp.handdexpp_model.h. They are part of the unit tests, so the sanitizer run reports a leak or a double free in the C layer.
0.2.0¶
Editable DEX model (new)¶
dex::model (include model/model.hpp, or dex.hpp) reads a DEX file into
plain C++ structs, lets you change them or build new ones from scratch, and
writes a valid DEX file again.
- The model holds no pool indices and no byte offsets. References are written
out in full (type descriptors, prototypes,
MethodId,FieldId) and branches point at labels.write()collects the references, sorts and numbers the pools, and picks each instruction's encoding (Constbecomesconst/4,const/16,const/high16orconst; a branch grows togoto/16,goto/32, or a reversedifaround agoto/32when it does not reach). So splitting a file, merging files, renaming classes and generating code are ordinary edits followed bywrite(). read()/read_file(),write()/write_file(),validate()(the rules of ART's DEX file verifier that apply, plus what the encoding needs),required_version(),pool_stats()andrename_types()(every type reference, including the class names inside generic signatures).- Strings keep unpaired surrogates (as WTF-8), floats keep their exact bits,
and values keep their exact type (a
charstays achar), so a file survives a read and a write unchanged in meaning. Writing is deterministic, and writing a re-read output gives the same bytes again. - Checked on 776 DEX files from 253 real apps: all but one round-trip (the
exception is a corrupt file that ART also rejects), and ART's verifier
(through the SDK's
dexdump) accepts every written file. - Speed and memory on the largest of them (42 MB, 6.9M instructions): read in 0.6 s, write in 1.6 s; the model takes about 15 times the file size.
From Python and Go, the model works a whole class at a time. Building or editing a class instruction by instruction stays in C++.
- Python:
dexpp.Modelreads a DEX file (Model.read,Model.read_file) or starts empty (Model(version)). It lists and inspects classes (class_descriptors,class_info,class_interfaces), copies, moves and removes whole classes between models (copy_class,move_class,remove_class), renames types (rename_types), and checks and writes the result (validate,pool_stats,required_version,write,write_file). Errors raiseFileNotFoundErrororValueError. - C and Go:
bindings/c/dexpp_model.hgives the same operations on an opaqueDexppModelDexhandle, and the Go package wraps them asModel(ReadModel,ReadModelFile,NewModel,CopyClass,MoveClass,RemoveClass,RenameTypes,Validate,PoolStats,Write, ...).
Packaging¶
- dexpp is now on PyPI:
pip install dexpp. The wheels are also still attached to each GitHub release. - dexpp now needs Python 3.14 or newer (breaking: 0.1.0 worked with 3.9 and newer). The wheels are built for CPython 3.14 only.
Smaller changes¶
MethodId,FieldId(and their hashes),AccessFlagsandAnnotationVisibilitymoved tosrc/common/, so the analysis layer and the model share them. Their names and namespace are unchanged, and the old headers still work.AccessFlagsgainedBridgeandVarargs.dex::rawgained what writing needs: one opcode table for all 256 opcodes with an instruction decoder and encoder (raw/opcodes.hpp; the analysis decoder now uses it too), lossless MUTF-8 decoding and encoding (raw/mutf8.hpp), name and descriptor rules (raw/descriptors.hpp), SHA-1 / SHA-256 (raw/digest.hpp, moved from APK signing), a debug-info parser (parse_debug_info), and a byte writer (raw/byte_writer.hpp).raw::parser::compute_signatureis now implemented.verify_offsets, which was declared but never implemented, is removed.compute_checksumis several times faster.- The raw parser no longer negates
INT32_MIN(undefined behavior) when a catch handler declares that size.
Call graph: virtual dispatch is stored once per method (breaking)¶
A virtual or interface call can reach every override of the called method in the app. These possible targets depend only on the called method, but the call graph used to store them again at every call site, as one edge per site and per target. On large apps that came to tens or hundreds of millions of edges, and on the largest (for example the Facebook APK, 164K classes) the call graph ran out of memory.
They are now stored once per called method, and the graph is built with integer ids instead of strings. It holds the same information, in far less time and memory (building the call graph after loading the APK; peak memory includes the loaded APK):
| App | Stored before | Stored now | Build time before → now | Peak memory before → now |
|---|---|---|---|---|
| 181M edges | 3.7M edges + 206K dispatch entries | ran out of memory → 0.54 s | over 10.9 GB → 1.05 GB | |
| GitHub | 89M edges | 0.76M edges + 74K dispatch entries | 4.4 s → 0.13 s | 5.8 GB → 0.21 GB |
| 89M edges | 2.3M edges + 168K dispatch entries | 8.0 s → 0.36 s | 5.9 GB → 0.68 GB | |
| YouTube | 31M edges | 1.4M edges + 105K dispatch entries | 3.9 s → 0.23 s | 2.8 GB → 0.46 GB |
Building the call graph also no longer decodes every instruction into the context's instruction cache, and no longer builds the class hierarchy.
For an app split over several large DEX files, part of the build runs on one
thread per DEX file. ApkLoadOptions::threads (Python: from_apk(threads=...))
now also sets these threads: 1 keeps the whole build on the calling thread.
The result never depends on the number of threads.
API changes, in C++ (dex::CallGraph) and Python (dexpp.CallGraph):
edges()holds oneDeclarededge per call site, plus theInheritedResolutionedge when there is one.EdgeOrigin::ChaOverride(EdgeOrigin.CHA_OVERRIDE) is removed.dispatch_targets(node)lists the overrides a virtual or interface call to that method may reach, anddispatch_sources(node)is the reverse.dispatch_targets(edge)gives the targets that apply at one call site (empty for super, direct and static calls). Python:CallNode.dispatch_targets,CallNode.dispatch_sources,CallEdge.dispatch_targets.callees(node)andcallers(node)list every method a method may call, or be called by, with virtual dispatch included. Python:CallNode.callees,CallNode.callers.CallNode.outgoing/incoming(andout_edges/in_edgesin Python) no longer include dispatch targets. Usecallees/callersfor those.- The deprecated Python property
CallEdge.via_overrideis removed.
0.1.0 — first release¶
The first public release. The API is still alpha: it may change in later 0.x releases.
APK metadata (dex::apk / dexpp.Apk)¶
- Archive listing and entry extraction (stored and deflate entries; no ZIP64).
- Binary
AndroidManifest.xmldecoding: package, version, SDK levels, permissions, declared permissions and their protection levels, components with their exported / intent-filter / permission attributes, launcher activity,debuggable,allowBackup. Component.is_reachable: exported and not gated behind an app-declaredsignaturepermission.resources.arscdecoding: string resolution, resource names, reverse lookup.- Signing scheme detection (v1, v2, v3/v3.1) and X.509 certificate details with SHA-1 / SHA-256 fingerprints. Signatures are identified, not verified.
Code analysis (dex / dexpp.AnalysisContext)¶
- Load a single DEX, several DEX files, or every
classes*.dexof an APK. Loading is lazy: the file is memory-mapped and only what a query touches is decoded. Multidex APKs are decompressed in parallel. - Classes, methods, fields, access flags, annotations, and static field initial values.
- Decoded bytecode with mnemonics, try/catch blocks, register frames, and a control-flow graph per method.
- Per-method forward references: calls, field accesses, string loads, type uses.
- Whole-program call graph with class-hierarchy-aware virtual dispatch, a class hierarchy, and a cross-reference index (who calls / reads / writes / loads what).
Python bindings¶
- One extension module with type stubs (
mypyandpyright). - The call graph, xrefs, and CFG tables are zero-copy views; call-graph nodes and edges can be navigated directly.
dexpp.__version__.
Packaging¶
- Prebuilt wheels for Linux x86_64 (glibc and musl), attached to the GitHub release. The C++ library and the C / Go bindings are source-only for now.
- No system dependencies: DEFLATE decoding uses libdeflate, compiled in.
Robustness¶
- The parsers are hardened against malformed and hostile input (bounds checks, allocation limits against oversized counts and zip bombs).