dex++ 0.3.1
C++ and C API reference
Loading...
Searching...
No Matches
dex::model Namespace Reference

An editable, in-memory model of one DEX file. More...

Classes

struct  AnnotationItem
 An annotation attached to a class, field, method or parameter. More...
 
struct  ArrayGet
 
struct  ArrayLength
 
struct  ArrayPut
 
struct  Binary
 dest = a op b. More...
 
struct  BinaryLiteral
 dest = src op literal (for Rsub: literal - src). More...
 
struct  CallSite
 An invoke-custom call site: the bootstrap method and the arguments it is linked with. More...
 
struct  Catch
 
struct  CheckCast
 
struct  ClassDef
 
struct  Code
 A method body. More...
 
struct  Compare
 
struct  Const
 A 32-bit constant (int, float bits, or 0 as null). More...
 
struct  ConstClass
 
struct  ConstMethodHandle
 
struct  ConstMethodType
 
struct  ConstString
 
struct  ConstWide
 A 64-bit constant into a register pair. More...
 
struct  Dex
 One DEX file. More...
 
struct  EncodedAnnotation
 An annotation's type and its explicitly set elements. More...
 
struct  EpilogueBegin
 The next LineNumber marks the start of the method epilogue. More...
 
struct  FieldDef
 
struct  FillArrayData
 fill-array-data: data holds the elements' little-endian bytes, element_width bytes each (1, 2, 4 or 8). More...
 
struct  FilledNewArray
 filled-new-array: type is the array type; the result is picked up by a following MoveResult. More...
 
struct  Goto
 
struct  If
 Branch to target if a cond b. More...
 
struct  IfZero
 Branch to target if value cond 0. More...
 
struct  InstanceGet
 
struct  InstanceOf
 
struct  InstancePut
 
struct  Invoke
 invoke-virtual, -super, -direct, -static or -interface. More...
 
struct  InvokeCustom
 
struct  InvokePolymorphic
 invoke-polymorphic: a signature-polymorphic call (MethodHandle.invoke...). More...
 
struct  Label
 A position in a method's code. More...
 
struct  LineNumber
 The source line of the code that follows. More...
 
struct  LocalEnd
 The local variable in reg goes out of scope. More...
 
struct  LocalRestart
 The local variable last in reg comes back into scope. More...
 
struct  LocalStart
 A local variable comes into scope in reg. More...
 
struct  LocalVariable
 
struct  MethodDef
 
struct  MethodHandle
 A method handle (java.lang.invoke.MethodHandle constant). More...
 
struct  MonitorEnter
 
struct  MonitorExit
 
struct  Move
 
struct  MoveException
 move-exception: must be the first instruction of a catch handler. More...
 
struct  MoveResult
 move-result: must directly follow an invoke or filled-new-array. More...
 
struct  NamedValue
 One name = value element of an annotation. More...
 
struct  NewArray
 new-array: type is the array type, e.g. "[I". More...
 
struct  NewInstance
 
struct  Nop
 
struct  PoolStats
 How many entries each pool of the written file would have. More...
 
struct  PrologueEnd
 The next LineNumber marks the end of the method prologue (a breakpoint spot). More...
 
struct  ReadOptions
 
class  RegList
 A list of registers: the arguments of an invoke or filled-new-array. More...
 
struct  Return
 
struct  ReturnVoid
 
struct  SetSourceFile
 Later line numbers refer to another source file (nullopt: unknown). More...
 
class  Shared
 An immutable value held by a shared pointer. More...
 
struct  StaticGet
 
struct  StaticPut
 
struct  Switch
 packed-switch or sparse-switch, chosen by write(). More...
 
struct  Throw
 
struct  TryRange
 The instructions between start and end are protected: an exception goes to the first matching catches entry, else to catch_all. More...
 
struct  Unary
 
struct  Value
 A constant value as the DEX format encodes it (encoded_value), with its exact type: a Java char stays a Char, a byte a Byte. More...
 
struct  WriteOptions
 

Typedefs

using Reg = uint16_t
 A virtual register number.
 
using Insn = std::variant< Nop, Move, MoveResult, MoveException, ReturnVoid, Return, Const, ConstWide, ConstString, ConstClass, ConstMethodHandle, ConstMethodType, MonitorEnter, MonitorExit, CheckCast, InstanceOf, ArrayLength, NewInstance, NewArray, FilledNewArray, FillArrayData, Throw, Goto, Switch, Compare, If, IfZero, ArrayGet, ArrayPut, InstanceGet, InstancePut, StaticGet, StaticPut, Invoke, InvokePolymorphic, InvokeCustom, Unary, Binary, BinaryLiteral >
 
using Item = std::variant< Insn, Label, LineNumber, LocalStart, LocalEnd, LocalRestart, PrologueEnd, EpilogueBegin, SetSourceFile >
 One entry of Code::items: an instruction, a label position, or a debug marker.
 

Enumerations

enum class  ValueKind : uint8_t {
  Normal , Wide , Object , Boolean ,
  Byte , Char , Short
}
 Which variant of a move, return, array, field or result instruction: the kind of value it moves. More...
 
enum class  Condition : uint8_t {
  Eq , Ne , Lt , Ge ,
  Gt , Le
}
 Comparison of an If (two registers) or IfZero (a register and zero). More...
 
enum class  CompareOp : uint8_t {
  CmplFloat , CmpgFloat , CmplDouble , CmpgDouble ,
  CmpLong
}
 
enum class  UnaryOp : uint8_t {
  NegInt , NotInt , NegLong , NotLong ,
  NegFloat , NegDouble , IntToLong , IntToFloat ,
  IntToDouble , LongToInt , LongToFloat , LongToDouble ,
  FloatToInt , FloatToLong , FloatToDouble , DoubleToInt ,
  DoubleToLong , DoubleToFloat , IntToByte , IntToChar ,
  IntToShort
}
 
enum class  BinaryOp : uint8_t {
  AddInt , SubInt , MulInt , DivInt ,
  RemInt , AndInt , OrInt , XorInt ,
  ShlInt , ShrInt , UshrInt , AddLong ,
  SubLong , MulLong , DivLong , RemLong ,
  AndLong , OrLong , XorLong , ShlLong ,
  ShrLong , UshrLong , AddFloat , SubFloat ,
  MulFloat , DivFloat , RemFloat , AddDouble ,
  SubDouble , MulDouble , DivDouble , RemDouble
}
 
enum class  LiteralOp : uint8_t {
  Add , Rsub , Mul , Div ,
  Rem , And , Or , Xor ,
  Shl , Shr , Ushr
}
 Operation of a BinaryLiteral (an int operation with a constant). More...
 

Functions

std::expected< Dex, Error > read (std::span< const uint8_t > bytes, const ReadOptions &options={})
 Read a whole DEX file into a model.
 
std::expected< Dex, Error > read_file (const std::string &path, const ReadOptions &options={})
 
std::expected< std::vector< uint8_t >, Error > write (const Dex &dex, const WriteOptions &options={})
 Write a model as a DEX file.
 
std::expected< void, Error > write_file (const Dex &dex, const std::string &path, const WriteOptions &options={})
 
std::vector< Problem > validate (const Dex &dex)
 Every rule of the format the model breaks.
 
uint32_t required_version (const Dex &dex)
 The lowest DEX version that has every feature dex uses: 37 for default and private interface methods, 38 for invoke-polymorphic, invoke-custom and method handle / method type values, 39 for const-method-handle and const-method-type.
 
PoolStats pool_stats (const Dex &dex)
 
void rename_types (Dex &dex, const std::function< std::optional< std::string >(std::string_view)> &rename)
 Rename classes everywhere they are referenced.
 

Detailed Description

An editable, in-memory model of one DEX file.

The model holds no pool indices and no byte offsets. Every reference is written out in full — type descriptors, prototype descriptors, MethodId, FieldId — and branches point at labels. write() collects the references, builds and sorts the pools, assigns indices, and picks each instruction's encoding. So editing never involves index bookkeeping: splitting, merging, renaming and generating code are ordinary edits followed by write().

Everything is plain data with value semantics: copying a Dex copies it, and two models compare equal when they hold the same content.

Strings are WTF-8 (see raw/mutf8.hpp): UTF-8, except that an unpaired surrogate, which DEX string constants may contain, is kept as its 3-byte sequence. Every DEX string survives a read and a write unchanged.

Typedef Documentation

◆ Reg

using dex::model::Reg = typedef uint16_t

A virtual register number.

◆ Insn

◆ Item

One entry of Code::items: an instruction, a label position, or a debug marker.

Labels and markers take no space: they belong to the position of the next instruction (or the end of the code).

Enumeration Type Documentation

◆ ValueKind

enum class dex::model::ValueKind : uint8_t
strong

Which variant of a move, return, array, field or result instruction: the kind of value it moves.

Normal is a 32-bit non-object value (int or float); Wide a register pair (long or double). Move, MoveResult and Return take only Normal, Wide and Object.

Enumerator
Normal 
Wide 
Object 
Boolean 
Byte 
Char 
Short 

◆ Condition

enum class dex::model::Condition : uint8_t
strong

Comparison of an If (two registers) or IfZero (a register and zero).

Enumerator
Eq 
Ne 
Lt 
Ge 
Gt 
Le 

◆ CompareOp

enum class dex::model::CompareOp : uint8_t
strong
Enumerator
CmplFloat 
CmpgFloat 
CmplDouble 
CmpgDouble 
CmpLong 

◆ UnaryOp

enum class dex::model::UnaryOp : uint8_t
strong
Enumerator
NegInt 
NotInt 
NegLong 
NotLong 
NegFloat 
NegDouble 
IntToLong 
IntToFloat 
IntToDouble 
LongToInt 
LongToFloat 
LongToDouble 
FloatToInt 
FloatToLong 
FloatToDouble 
DoubleToInt 
DoubleToLong 
DoubleToFloat 
IntToByte 
IntToChar 
IntToShort 

◆ BinaryOp

enum class dex::model::BinaryOp : uint8_t
strong
Enumerator
AddInt 
SubInt 
MulInt 
DivInt 
RemInt 
AndInt 
OrInt 
XorInt 
ShlInt 
ShrInt 
UshrInt 
AddLong 
SubLong 
MulLong 
DivLong 
RemLong 
AndLong 
OrLong 
XorLong 
ShlLong 
ShrLong 
UshrLong 
AddFloat 
SubFloat 
MulFloat 
DivFloat 
RemFloat 
AddDouble 
SubDouble 
MulDouble 
DivDouble 
RemDouble 

◆ LiteralOp

enum class dex::model::LiteralOp : uint8_t
strong

Operation of a BinaryLiteral (an int operation with a constant).

Rsub is literal - src. Shl, Shr and Ushr only exist with an 8-bit literal.

Enumerator
Add 
Rsub 
Mul 
Div 
Rem 
And 
Or 
Xor 
Shl 
Shr 
Ushr 

Function Documentation

◆ read()

std::expected< Dex, Error > dex::model::read ( std::span< const uint8_t >  bytes,
const ReadOptions &  options = {} 
)

Read a whole DEX file into a model.

Reading is strict: a structure the model could not write back faithfully — an unused opcode, a branch into the middle of an instruction, a malformed string — is an error. Rules the model can represent (names, access flags, ...) are not checked here; validate() and write() check those.

Errors: ErrorCode::InvalidDex for input that is not a valid DEX file, UnsupportedDex for a DEX 041 container or a big-endian file. read_file() also gives FileNotFound when the path does not exist and CannotRead when it cannot be read (a directory, no permission).

What is not kept: hidden-API flags (boot class path DEX files only) and the link section are dropped; debug positions past the end of the code are dropped; payloads no instruction refers to are dropped.

◆ read_file()

std::expected< Dex, Error > dex::model::read_file ( const std::string &  path,
const ReadOptions &  options = {} 
)

◆ write()

std::expected< std::vector< uint8_t >, Error > dex::model::write ( const Dex &  dex,
const WriteOptions &  options = {} 
)

Write a model as a DEX file.

The model is checked first (validate(), then required_version()); nothing is written if it fails. The output is deterministic: the same model always gives the same bytes. Reading the output gives the same model up to normalization: classes ordered so supertypes come first, members and annotation elements sorted, labels renumbered in code order, switch cases that only fall through removed, overlapping try ranges flattened and neighbouring ones with the same handlers joined. Writing that model again gives the same bytes.

Errors: ErrorCode::InvalidModel when the model breaks rules of the format (Error::problems lists every one), PoolOverflow when part of the file would be bigger than the format can encode, VersionTooLow when the model uses a feature its version does not have. write_file() also gives CannotWrite when the file cannot be created or written.

◆ write_file()

std::expected< void, Error > dex::model::write_file ( const Dex &  dex,
const std::string &  path,
const WriteOptions &  options = {} 
)

◆ validate()

std::vector< Problem > dex::model::validate ( const Dex &  dex)

Every rule of the format the model breaks.

Empty means write() can encode it. The rules are those of ART's DEX file verifier that apply to the model — names and descriptors, access flags, member uniqueness, static values — plus what the encoding needs: registers that fit the instruction and the frame, labels placed exactly once, branch targets followed by an instruction. It does not follow the control flow: rules that only apply to code that can run (a move-result after an invoke, a move-exception first in a handler, types flowing correctly) are ART's method verifier's, which checks them at runtime — apps ship dead code that breaks them.

◆ required_version()

uint32_t dex::model::required_version ( const Dex &  dex)

The lowest DEX version that has every feature dex uses: 37 for default and private interface methods, 38 for invoke-polymorphic, invoke-custom and method handle / method type values, 39 for const-method-handle and const-method-type.

Set dex.version to it to opt in; write() never raises the version by itself, because a higher version also makes ART stricter.

Names may contain space characters at any version, as ART accepts them (the format reserves them for 040, and Android 10 and older reject them).

◆ pool_stats()

PoolStats dex::model::pool_stats ( const Dex &  dex)

◆ rename_types()

void dex::model::rename_types ( Dex &  dex,
const std::function< std::optional< std::string >(std::string_view)> &  rename 
)

Rename classes everywhere they are referenced.

rename gets each class descriptor ("Lcom/a/B;") and returns its new descriptor, or nullopt to keep it. It is applied to every type reference: classes, supertypes, member ids, prototypes, array types, instructions, catch types, annotations and values, call sites, debug local types — and the class names inside generic signatures (dalvik.annotation.Signature, local variable signatures).

Not changed: class names inside string constants (e.g. for Class.forName), Kotlin metadata, and the simple name in an InnerClass annotation. In a generic signature the inner-class suffix of LOuter<...>.Inner; is kept, so rename an inner class together with its outer class.