`

Android Dex文件结构

 
阅读更多

dex— Dalvik Executable Format

Copyright © 2007 The Android Open Source Project

This document describes the layout and contents of.dexfiles, which are used to hold a set of class definitions and their associated adjunct data.

Guide To Types

Name

Description

byte

8-bit signed int

ubyte

8-bit unsigned int

short

16-bit signed int, little-endian

ushort

16-bit unsigned int, little-endian

int

32-bit signed int, little-endian

uint

32-bit unsigned int, little-endian

long

64-bit signed int, little-endian

ulong

64-bit unsigned int, little-endian

sleb128

signed LEB128, variable-length (see below)

uleb128

unsigned LEB128, variable-length (see below)

uleb128p1

unsigned LEB128 plus1, variable-length (see below)

LEB128

LEB128 ("Little-EndianBase128") is a variable-length encoding for arbitrary signed or unsigned integer quantities. The format was borrowed from theDWARF3specification. In a.dexfile, LEB128 is only ever used to encode 32-bit quantities.

Each LEB128 encoded value consists of one to five bytes, which together represent a single 32-bit value. Each byte has its most significant bit set except for the final byte in the sequence, which has its most significant bit clear. The remaining seven bits of each byte are payload, with the least significant seven bits of the quantity in the first byte, the next seven in the second byte and so on. In the case of a signed LEB128 (sleb128), the most significant payload bit of the final byte in the sequence is sign-extended to produce the final value. In the unsigned case (uleb128), any bits not explicitly represented are interpreted as0.

Bitwise diagram of a two-byte LEB128 value

First byte

Second byte

1

bit6

bit5

bit4

bit3

bit2

bit1

bit0

0

bit13

bit12

bit11

bit10

bit9

bit8

bit7

The variantuleb128p1is used to represent a signed value, where the representation is of the valueplus oneencoded as auleb128. This makes the encoding of-1(alternatively thought of as the unsigned value0xffffffff) — but no other negative number — a single byte, and is useful in exactly those cases where the represented number must either be non-negative or-1(or0xffffffff), and where no other negative values are allowed (or where large unsigned values are unlikely to be needed).

Here are some examples of the formats:

Encoded Sequence

Assleb128

Asuleb128

Asuleb128p1

00

0

0

-1

01

1

1

0

7f

-1

127

126

80 7f

-128

16256

16255

Overall File Layout

Name

Format

Description

header

header_item

the header

string_ids

string_id_item[]

string identifiers list. These are identifiers for all the strings used by this file, either for internal naming (e.g., type descriptors) or as constant objects referred to by code. This list must be sorted by string contents, using UTF-16 code point values (not in a locale-sensitive manner).

type_ids

type_id_item[]

type identifiers list. These are identifiers for all types (classes, arrays, or primitive types) referred to by this file, whether defined in the file or not. This list must be sorted bystring_idindex.

proto_ids

proto_id_item[]

method prototype identifiers list. These are identifiers for all prototypes referred to by this file. This list must be sorted in return-type (bytype_idindex) major order, and then by arguments (also bytype_idindex).

field_ids

field_id_item[]

field identifiers list. These are identifiers for all fields referred to by this file, whether defined in the file or not. This list must be sorted, where the defining type (bytype_idindex) is the major order, field name (bystring_idindex) is the intermediate order, and type (bytype_idindex) is the minor order.

method_ids

method_id_item[]

method identifiers list. These are identifiers for all methods referred to by this file, whether defined in the file or not. This list must be sorted, where the defining type (bytype_idindex) is the major order, method name (bystring_idindex) is the intermediate order, and method prototype (byproto_idindex) is the minor order.

class_defs

class_def_item[]

class definitions list. The classes must be ordered such that a given class's superclass and implemented interfaces appear in the list earlier than the referring class.

data

ubyte[]

data area, containing all the support data for the tables listed above. Different items have different alignment requirements, and padding bytes are inserted before each item if necessary to achieve proper alignment.

link_data

ubyte[]

data used in statically linked files. The format of the data in this section is left unspecified by this document; this section is empty in unlinked files, and runtime implementations may use it as they see fit.

Bitfield, String, and Constant Definitions

DEX_FILE_MAGIC

embedded inheader_item

The constant array/stringDEX_FILE_MAGICis the list of bytes that must appear at the beginning of a.dexfile in order for it to be recognized as such. The value intentionally contains a newline ("/n"or0x0a) and a null byte ("/0"or0x00) in order to help in the detection of certain forms of corruption. The value also encodes a format version number as three decimal digits, which is expected to increase monotonically over time as the format evolves.

ubyte[8] DEX_FILE_MAGIC = { 0x64 0x65 0x78 0x0a 0x30 0x33 0x35 0x00 }

= "dex/n035/0"

Note:At least a couple earlier versions of the format have been used in widely-available public software releases. For example, version009was used for the M3 releases of the Android platform (November-December 2007), and version013was used for the M5 releases of the Android platform (February-March 2008). In several respects, these earlier versions of the format differ significantly from the version described in this document.

ENDIAN_CONSTANTandREVERSE_ENDIAN_CONSTANT

embedded inheader_item

The constantENDIAN_CONSTANTis used to indicate the endianness of the file in which it is found. Although the standard.dexformat is little-endian, implementations may choose to perform byte-swapping. Should an implementation come across a header whoseendian_tagisREVERSE_ENDIAN_CONSTANTinstead ofENDIAN_CONSTANT, it would know that the file has been byte-swapped from the expected form.

uint ENDIAN_CONSTANT = 0x12345678;

uint REVERSE_ENDIAN_CONSTANT = 0x78563412;

NO_INDEX

embedded inclass_def_itemanddebug_info_item

The constantNO_INDEXis used to indicate that an index value is absent.

Note:This value isn't defined to be0, because that is in fact typically a valid index.

Also Note:The chosen value forNO_INDEXis representable as a single byte in theuleb128p1encoding.

uint NO_INDEX = 0xffffffff; // == -1 if treated as a signed int

access_flagsDefinitions

embedded inclass_def_item,field_item,method_item, andInnerClass

Bitfields of these flags are used to indicate the accessibility and overall properties of classes and class members.

Name

Value

For Classes (andInnerClassannotations)

For Fields

For Methods

ACC_PUBLIC

0x1

public: visible everywhere

public: visible everywhere

public: visible everywhere

ACC_PRIVATE

0x2

*private: only visible to defining class

private: only visible to defining class

private: only visible to defining class

ACC_PROTECTED

0x4

*protected: visible to package and subclasses

protected: visible to package and subclasses

protected: visible to package and subclasses

ACC_STATIC

0x8

*static: is not constructed with an outerthisreference

static: global to defining class

static: does not take athisargument

ACC_FINAL

0x10

final: not subclassable

final: immutable after construction

final: not overridable

ACC_SYNCHRONIZED

0x20

synchronized: associated lock automatically acquired around call to this method.Note:This is only valid to set whenACC_NATIVEis also set.

ACC_VOLATILE

0x40

volatile: special access rules to help with thread safety

ACC_BRIDGE

0x40

bridge method, added automatically by compiler as a type-safe bridge

ACC_TRANSIENT

0x80

transient: not to be saved by default serialization

ACC_VARARGS

0x80

last argument should be treated as a "rest" argument by compiler

ACC_NATIVE

0x100

native: implemented in native code

ACC_INTERFACE

0x200

interface: multiply-implementable abstract class

ACC_ABSTRACT

0x400

abstract: not directly instantiable

abstract: unimplemented by this class

ACC_STRICT

0x800

strictfp: strict rules for floating-point arithmetic

ACC_SYNTHETIC

0x1000

not directly defined in source code

not directly defined in source code

not directly defined in source code

ACC_ANNOTATION

0x2000

declared as an annotation class

ACC_ENUM

0x4000

declared as an enumerated type

declared as an enumerated value

(unused)

0x8000

ACC_CONSTRUCTOR

0x10000

constructor method (class or instance initializer)

ACC_DECLARED_
SYNCHRONIZED

0x20000

declaredsynchronized.Note:This has no effect on execution (other than in reflection of this flag, per se).

*Only allowed on forInnerClassannotations, and must not ever be on in aclass_def_item.

MUTF-8 (Modified UTF-8) Encoding

As a concession to easier legacy support, the.dexformat encodes its string data in a de facto standard modified UTF-8 form, hereafter referred to as MUTF-8. This form is identical to standard UTF-8, except:

  • Only the one-, two-, and three-byte encodings are used.
  • Code points in the rangeU+10000U+10ffffare encoded as a surrogate pair, each of which is represented as a three-byte encoded value.
  • The code pointU+0000is encoded in two-byte form.
  • A plain null byte (value0) indicates the end of a string, as is the standard C language interpretation.

The first two items above can be summarized as: MUTF-8 is an encoding format for UTF-16, instead of being a more direct encoding format for Unicode characters.

The final two items above make it simultaneously possible to include the code pointU+0000in a stringandstill manipulate it as a C-style null-terminated string.

However, the special encoding ofU+0000means that, unlike normal UTF-8, the result of calling the standard C functionstrcmp()on a pair of MUTF-8 strings does not always indicate the properly signed result of comparison ofunequalstrings. When ordering (not just equality) is a concern, the most straightforward way to compare MUTF-8 strings is to decode them character by character, and compare the decoded values. (However, more clever implementations are also possible.)

Please refer toThe Unicode Standardfor further information about character encoding. MUTF-8 is actually closer to the (relatively less well-known) encodingCESU-8than to UTF-8 per se.

encoded_valueEncoding

embedded inannotation_elementandencoded_array_item

Anencoded_valueis an encoded piece of (nearly) arbitrary hierarchically structured data. The encoding is meant to be both compact and straightforward to parse.

Name

Format

Description

(value_arg << 5) | value_type

ubyte

byte indicating the type of the immediately subsequentvaluealong with an optional clarifying argument in the high-order three bits. See below for the variousvaluedefinitions. In most cases,value_argencodes the length of the immediately-subsequentvaluein bytes, as(size - 1), e.g.,0means that the value requires one byte, and7means it requires eight bytes; however, there are exceptions as noted below.

value

ubyte[]

bytes representing the value, variable in length and interpreted differently for differentvalue_typebytes, though always little-endian. See the various value definitions below for details.

Value Formats

Type Name

value_type

value_argFormat

valueFormat

Description

VALUE_BYTE

0x00

(none; must be0)

ubyte[1]

signed one-byte integer value

VALUE_SHORT

0x02

size - 1 (0…1)

ubyte[size]

signed two-byte integer value, sign-extended

VALUE_CHAR

0x03

size - 1 (0…1)

ubyte[size]

unsigned two-byte integer value, zero-extended

VALUE_INT

0x04

size - 1 (0…3)

ubyte[size]

signed four-byte integer value, sign-extended

VALUE_LONG

0x06

size - 1 (0…7)

ubyte[size]

signed eight-byte integer value, sign-extended

VALUE_FLOAT

0x10

size - 1 (0…3)

ubyte[size]

four-byte bit pattern, zero-extendedto the right, and interpreted as an IEEE754 32-bit floating point value

VALUE_DOUBLE

0x11

size - 1 (0…7)

ubyte[size]

eight-byte bit pattern, zero-extendedto the right, and interpreted as an IEEE754 64-bit floating point value

VALUE_STRING

0x17

size - 1 (0…3)

ubyte[size]

unsigned (zero-extended) four-byte integer value, interpreted as an index into thestring_idssection and representing a string value

VALUE_TYPE

0x18

size - 1 (0…3)

ubyte[size]

unsigned (zero-extended) four-byte integer value, interpreted as an index into thetype_idssection and representing a reflective type/class value

VALUE_FIELD

0x19

size - 1 (0…3)

ubyte[size]

unsigned (zero-extended) four-byte integer value, interpreted as an index into thefield_idssection and representing a reflective field value

VALUE_METHOD

0x1a

size - 1 (0…3)

ubyte[size]

unsigned (zero-extended) four-byte integer value, interpreted as an index into themethod_idssection and representing a reflective method value

VALUE_ENUM

0x1b

size - 1 (0…3)

ubyte[size]

unsigned (zero-extended) four-byte integer value, interpreted as an index into thefield_idssection and representing the value of an enumerated type constant

VALUE_ARRAY

0x1c

(none; must be0)

encoded_array

an array of values, in the format specified by "encoded_arrayFormat" below. The size of thevalueis implicit in the encoding.

VALUE_ANNOTATION

0x1d

(none; must be0)

encoded_annotation

a sub-annotation, in the format specified by "encoded_annotationFormat" below. The size of thevalueis implicit in the encoding.

VALUE_NULL

0x1e

(none; must be0)

(none)

nullreference value

VALUE_BOOLEAN

0x1f

boolean (0…1)

(none)

one-bit value;0forfalseand1fortrue. The bit is represented in thevalue_arg.

encoded_arrayFormat

Name

Format

Description

size

uleb128

number of elements in the array

values

encoded_value[size]

a series ofsizeencoded_valuebyte sequences in the format specified by this section, concatenated sequentially.

encoded_annotationFormat

Name

Format

Description

type_idx

uleb128

type of the annotation. This must be a class (not array or primitive) type.

size

uleb128

number of name-value mappings in this annotation

elements

annotation_element[size]

elements of the annotataion, represented directly in-line (not as offsets). Elements must be sorted in increasing order bystring_idindex.

annotation_elementFormat

Name

Format

Description

name_idx

uleb128

element name, represented as an index into thestring_idssection. The string must conform to the syntax forMemberName, defined above.

value

encoded_value

element value

String Syntax

There are several kinds of item in a.dexfile which ultimately refer to a string. The following BNF-style definitions indicate the acceptable syntax for these strings.

SimpleName

ASimpleNameis the basis for the syntax of the names of other things. The.dexformat allows a fair amount of latitude here (much more than most common source languages). In brief, a simple name may consist of any low-ASCII alphabetic character or digit, a few specific low-ASCII symbols, and most non-ASCII code points that are not control, space, or special characters. Note that surrogate code points (in the rangeU+d800U+dfff) are not considered valid name characters, per se, but Unicode supplemental charactersarevalid (which are represented by the final alternative of the rule forSimpleNameChar), and they should be represented in a file as pairs of surrogate code points in the MUTF-8 encoding.

SimpleName

SimpleNameChar(SimpleNameChar)*

SimpleNameChar

'A''Z'

|

'a''z'

|

'0''9'

|

'$'

|

'-'

|

'_'

|

U+00a1U+1fff

|

U+2010U+2027

|

U+2030U+d7ff

|

U+e000U+ffef

|

U+10000U+10ffff

MemberName

used byfield_id_itemandmethod_id_item

AMemberNameis the name of a member of a class, members being fields, methods, and inner classes.

MemberName

SimpleName

|

'<'SimpleName'>'

FullClassName

AFullClassNameis a fully-qualified class name, including an optional package specifier followed by a required name.

FullClassName

OptionalPackagePrefixSimpleName

OptionalPackagePrefix

(SimpleName'/')*

TypeDescriptor

used bytype_id_item

ATypeDescriptoris the representation of any type, including primitives, classes, arrays, andvoid. See below for the meaning of the various versions.

TypeDescriptor

'V'

|

FieldTypeDescriptor

FieldTypeDescriptor

NonArrayFieldTypeDescriptor

|

('['* 1…255)NonArrayFieldTypeDescriptor

NonArrayFieldTypeDescriptor

'Z'

|

'B'

|

'S'

|

'C'

|

'I'

|

'J'

|

'F'

|

'D'

|

'L'FullClassName';'

ShortyDescriptor

used byproto_id_item

AShortyDescriptoris the short form representation of a method prototype, including return and parameter types, except that there is no distinction between various reference (class or array) types. Instead, all reference types are represented by a single'L'character.

ShortyDescriptor

ShortyReturnType(ShortyFieldType)*

ShortyReturnType

'V'

|

ShortyFieldType

ShortyFieldType

'Z'

|

'B'

|

'S'

|

'C'

|

'I'

|

'J'

|

'F'

|

'D'

|

'L'

TypeDescriptorSemantics

This is the meaning of each of the variants ofTypeDescriptor.

Syntax

Meaning

V

void; only valid for return types

Z

boolean

B

byte

S

short

C

char

I

int

J

long

F

float

D

double

Lfully/qualified/Name;

the classfully.qualified.Name

[descriptor

array ofdescriptor, usable recursively for arrays-of-arrays, though it is invalid to have more than 255 dimensions.

Items and Related Structures

This section includes definitions for each of the top-level items that may appear in a.dexfile.

header_item

appears in theheadersection

alignment: 4 bytes

Name

Format

Description

magic

ubyte[8] = DEX_FILE_MAGIC

magic value. See discussion above under "DEX_FILE_MAGIC" for more details.

checksum

uint

adler32 checksum of the rest of the file (everything butmagicand this field); used to detect file corruption

signature

ubyte[20]

SHA-1 signature (hash) of the rest of the file (everything butmagic,checksum, and this field); used to uniquely identify files

file_size

uint

size of the entire file (including the header), in bytes

header_size

uint = 0x70

size of the header (this entire section), in bytes. This allows for at least a limited amount of backwards/forwards compatibility without invalidating the format.

endian_tag

uint = ENDIAN_CONSTANT

endianness tag. See discussion above under "ENDIAN_CONSTANTandREVERSE_ENDIAN_CONSTANT" for more details.

link_size

uint

size of the link section, or0if this file isn't statically linked

link_off

uint

offset from the start of the file to the link section, or0iflink_size == 0. The offset, if non-zero, should be to an offset into thelink_datasection. The format of the data pointed at is left unspecified by this document; this header field (and the previous) are left as hooks for use by runtime implementations.

map_off

uint

offset from the start of the file to the map item, or0if this file has no map. The offset, if non-zero, should be to an offset into thedatasection, and the data should be in the format specified by "map_list" below.

string_ids_size

uint

count of strings in the string identifiers list

string_ids_off

uint

offset from the start of the file to the string identifiers list, or0ifstring_ids_size == 0(admittedly a strange edge case). The offset, if non-zero, should be to the start of thestring_idssection.

type_ids_size

uint

count of elements in the type identifiers list

type_ids_off

uint

offset from the start of the file to the type identifiers list, or0iftype_ids_size == 0(admittedly a strange edge case). The offset, if non-zero, should be to the start of thetype_idssection.

proto_ids_size

uint

count of elements in the prototype identifiers list

proto_ids_off

uint

offset from the start of the file to the prototype identifiers list, or0ifproto_ids_size == 0(admittedly a strange edge case). The offset, if non-zero, should be to the start of theproto_idssection.

field_ids_size

uint

count of elements in the field identifiers list

field_ids_off

uint

offset from the start of the file to the field identifiers list, or0iffield_ids_size == 0. The offset, if non-zero, should be to the start of thefield_idssection.

method_ids_size

uint

count of elements in the method identifiers list

method_ids_off

uint

offset from the start of the file to the method identifiers list, or0ifmethod_ids_size == 0. The offset, if non-zero, should be to the start of themethod_idssection.

class_defs_size

uint

count of elements in the class definitions list

class_defs_off

uint

offset from the start of the file to the class definitions list, or0ifclass_defs_size == 0(admittedly a strange edge case). The offset, if non-zero, should be to the start of theclass_defssection.

data_size

uint

Size ofdatasection in bytes. Must be an even multiple of sizeof(uint).

data_off

uint

offset from the start of the file to the start of thedatasection.

map_list

appears in thedatasection

referenced fromheader_item

alignment: 4 bytes

This is a list of the entire contents of a file, in order. It contains some redundancy with respect to theheader_itembut is intended to be an easy form to use to iterate over an entire file. A given type may appear at most once in a map, but there is no restriction on what order types may appear in, other than the restrictions implied by the rest of the format (e.g., aheadersection must appear first, followed by astring_idssection, etc.). Additionally, the map entries must be ordered by initial offset and must not overlap.

Name

Format

Description

size

uint

size of the list, in entries

list

map_item[size]

elements of the list

map_itemFormat

Name

Format

Description

type

ushort

type of the items; see table below

unused

ushort

(unused)

size

uint

count of the number of items to be found at the indicated offset

offset

uint

offset from the start of the file to the items in question

Type Codes

Item Type

Constant

Value

Item Size In Bytes

header_item

TYPE_HEADER_ITEM

0x0000

0x70

string_id_item

TYPE_STRING_ID_ITEM

0x0001

0x04

type_id_item

TYPE_TYPE_ID_ITEM

0x0002

0x04

proto_id_item

TYPE_PROTO_ID_ITEM

0x0003

0x0c

field_id_item

TYPE_FIELD_ID_ITEM

0x0004

0x08

method_id_item

TYPE_METHOD_ID_ITEM

0x0005

0x08

class_def_item

TYPE_CLASS_DEF_ITEM

0x0006

0x20

map_list

TYPE_MAP_LIST

0x1000

4 + (item.size * 12)

type_list

TYPE_TYPE_LIST

0x1001

4 + (item.size * 2)

annotation_set_ref_list

TYPE_ANNOTATION_SET_REF_LIST

0x1002

4 + (item.size * 4)

annotation_set_item

TYPE_ANNOTATION_SET_ITEM

0x1003

4 + (item.size * 4)

class_data_item

TYPE_CLASS_DATA_ITEM

0x2000

implicit; must parse

code_item

TYPE_CODE_ITEM

0x2001

implicit; must parse

string_data_item

TYPE_STRING_DATA_ITEM

0x2002

implicit; must parse

debug_info_item

TYPE_DEBUG_INFO_ITEM

0x2003

implicit; must parse

annotation_item

TYPE_ANNOTATION_ITEM

0x2004

implicit; must parse

encoded_array_item

TYPE_ENCODED_ARRAY_ITEM

0x2005

implicit; must parse

annotations_directory_item

TYPE_ANNOTATIONS_DIRECTORY_ITEM

0x2006

implicit; must parse

string_id_item

appears in thestring_idssection

alignment: 4 bytes

Name

Format

Description

string_data_off

uint

offset from the start of the file to the string data for this item. The offset should be to a location in thedatasection, and the data should be in the format specified by "string_data_item" below. There is no alignment requirement for the offset.

string_data_item

appears in thedatasection

alignment: none (byte-aligned)

Name

Format

Description

utf16_size

uleb128

size of this string, in UTF-16 code units (which is the "string length" in many systems). That is, this is the decoded length of the string. (The encoded length is implied by the position of the0byte.)

data

ubyte[]

a series of MUTF-8 code units (a.k.a. octets, a.k.a. bytes) followed by a byte of value0. See "MUTF-8 (Modified UTF-8) Encoding" above for details and discussion about the data format.

Note:It is acceptable to have a string which includes (the encoded form of) UTF-16 surrogate code units (that is,U+d800U+dfff) either in isolation or out-of-order with respect to the usual encoding of Unicode into UTF-16. It is up to higher-level uses of strings to reject such invalid encodings, if appropriate.

type_id_item

appears in thetype_idssection

alignment: 4 bytes

Name

Format

Description

descriptor_idx

uint

index into thestring_idslist for the descriptor string of this type. The string must conform to the syntax forTypeDescriptor, defined above.

proto_id_item

appears in theproto_idssection

alignment: 4 bytes

Name

Format

Description

shorty_idx

uint

index into thestring_idslist for the short-form descriptor string of this prototype. The string must conform to the syntax forShortyDescriptor, defined above, and must correspond to the return type and parameters of this item.

return_type_idx

uint

index into thetype_idslist for the return type of this prototype

parameters_off

uint

offset from the start of the file to the list of parameter types for this prototype, or0if this prototype has no parameters. This offset, if non-zero, should be in thedatasection, and the data there should be in the format specified by"type_list"below. Additionally, there should be no reference to the typevoidin the list.

field_id_item

appears in thefield_idssection

alignment: 4 bytes

Name

Format

Description

class_idx

ushort

index into thetype_idslist for the definer of this field. This must be a class type, and not an array or primitive type.

type_idx

ushort

index into thetype_idslist for the type of this field

name_idx

uint

index into thestring_idslist for the name of this field. The string must conform to the syntax forMemberName, defined above.

method_id_item

appears in themethod_idssection

alignment: 4 bytes

Name

Format

Description

class_idx

ushort

index into thetype_idslist for the definer of this method. This must be a class or array type, and not a primitive type.

proto_idx

ushort

index into theproto_idslist for the prototype of this method

name_idx

uint

index into thestring_idslist for the name of this method. The string must conform to the syntax forMemberName, defined above.

class_def_item

appears in theclass_defssection

alignment: 4 bytes

Name

Format

Description

class_idx

uint

index into thetype_idslist for this class. This must be a class type, and not an array or primitive type.

access_flags

uint

access flags for the class (public,final, etc.). See "access_flagsDefinitions" for details.

superclass_idx

uint

index into thetype_idslist for the superclass, or the constant valueNO_INDEXif this class has no superclass (i.e., it is a root class such asObject). If present, this must be a class type, and not an array or primitive type.

interfaces_off

uint

offset from the start of the file to the list of interfaces, or0if there are none. This offset should be in thedatasection, and the data there should be in the format specified by "type_list" below. Each of the elements of the list must be a class type (not an array or primitive type), and there must not be any duplicates.

source_file_idx

uint

index into thestring_idslist for the name of the file containing the original source for (at least most of) this class, or the special valueNO_INDEXto represent a lack of this information. Thedebug_info_itemof any given method may override this source file, but the expectation is that most classes will only come from one source file.

annotations_off

uint

offset from the start of the file to the annotations structure for this class, or0if there are no annotations on this class. This offset, if non-zero, should be in thedatasection, and the data there should be in the format specified by "annotations_directory_item" below, with all items referring to this class as the definer.

class_data_off

uint

offset from the start of the file to the associated class data for this item, or0if there is no class data for this class. (This may be the case, for example, if this class is a marker interface.) The offset, if non-zero, should be in thedatasection, and the data there should be in the format specified by "class_data_item" below, with all items referring to this class as the definer.

static_values_off

uint

offset from the start of the file to the list of initial values forstaticfields, or0if there are none (and allstaticfields are to be initialized with0ornull). This offset should be in thedatasection, and the data there should be in the format specified by "encoded_array_item" below. The size of the array must be no larger than the number ofstaticfields declared by this class, and the elements correspond to thestaticfields in the same order as declared in the correspondingfield_list. The type of each array element must match the declared type of its corresponding field. If there are fewer elements in the array than there arestaticfields, then the leftover fields are initialized with a type-appropriate0ornull.

class_data_item

referenced fromclass_def_item

appears in thedatasection

alignment: none (byte-aligned)

Name

Format

Description

static_fields_size

uleb128

the number of static fields defined in this item

instance_fields_size

uleb128

the number of instance fields defined in this item

direct_methods_size

uleb128

the number of direct methods defined in this item

virtual_methods_size

uleb128

the number of virtual methods defined in this item

static_fields

encoded_field[static_fields_size]

the defined static fields, represented as a sequence of encoded elements. The fields must be sorted byfield_idxin increasing order.

instance_fields

encoded_field[instance_fields_size]

the defined instance fields, represented as a sequence of encoded elements. The fields must be sorted byfield_idxin increasing order.

direct_methods

encoded_method[direct_methods_size]

the defined direct (any ofstatic,private, or constructor) methods, represented as a sequence of encoded elements. The methods must be sorted bymethod_idxin increasing order.

virtual_methods

encoded_method[virtual_methods_size]

the defined virtual (none ofstatic,private, or constructor) methods, represented as a sequence of encoded elements. This list shouldnotinclude inherited methods unless overridden by the class that this item represents. The methods must be sorted bymethod_idxin increasing order.

Note:All elements'field_ids andmethod_ids must refer to the same defining class.

encoded_fieldFormat

Name

Format

Description

field_idx_diff

uleb128

index into thefield_idslist for the identity of this field (includes the name and descriptor), represented as a difference from the index of previous element in the list. The index of the first element in a list is represented directly.

access_flags

uleb128

access flags for the field (public,final, etc.). See "access_flagsDefinitions" for details.

encoded_methodFormat

Name

Format

Description

method_idx_diff

uleb128

index into themethod_idslist for the identity of this method (includes the name and descriptor), represented as a difference from the index of previous element in the list. The index of the first element in a list is represented directly.

access_flags

uleb128

access flags for the method (public,final, etc.). See "access_flagsDefinitions" for details.

code_off

uleb128

offset from the start of the file to the code structure for this method, or0if this method is eitherabstractornative. The offset should be to a location in thedatasection. The format of the data is specified by "code_item" below.

type_list

referenced fromclass_def_itemandproto_id_item

appears in thedatasection

alignment: 4 bytes

Name

Format

Description

size

uint

size of the list, in entries

list

type_item[size]

elements of the list

type_itemFormat

Name

Format

Description

type_idx

ushort

index into thetype_idslist

code_item

referenced frommethod_item

appears in thedatasection

alignment: 4 bytes

Name

Format

Description

registers_size

ushort

the number of registers used by this code

ins_size

ushort

the number of words of incoming arguments to the method that this code is for

outs_size

ushort

the number of words of outgoing argument space required by this code for method invocation

tries_size

ushort

the number oftry_items for this instance. If non-zero, then these appear as thetriesarray just after theinsnsin this instance.

debug_info_off

uint

offset from the start of the file to the debug info (line numbers + local variable info) sequence for this code, or0if there simply is no information. The offset, if non-zero, should be to a location in thedatasection. The format of the data is specified by "debug_info_item" below.

insns_size

uint

size of the instructions list, in 16-bit code units

insns

ushort[insns_size]

actual array of bytecode. The format of code in aninsnsarray is specified by the companion document"Bytecode for the Dalvik VM". Note that though this is defined as an array ofushort, there are some internal structures that prefer four-byte alignment. Also, if this happens to be in an endian-swapped file, then the swapping isonlydone on individualushorts and not on the larger internal structures.

padding

ushort(optional)= 0

two bytes of padding to maketriesfour-byte aligned. This element is only present iftries_sizeis non-zero andinsns_sizeis odd.

tries

try_item[tries_size](optional)

array indicating where in the code exceptions may be caught and how to handle them. Elements of the array must be non-overlapping in range and in order from low to high address. This element is only present iftries_sizeis non-zero.

handlers

encoded_catch_handler_list(optional)

bytes representing a list of lists of catch types and associated handler addresses. Eachtry_itemhas a byte-wise offset into this structure. This element is only present iftries_sizeis non-zero.

try_itemFormat

Name

Format

Description

start_addr

uint

start address of the block of code covered by this entry. The address is a count of 16-bit code units to the start of the first covered instruction.

insn_count

ushort

number of 16-bit code units covered by this entry. The last code unit covered (inclusive) isstart_addr + insn_count - 1.

handler_off

ushort

offset in bytes from the start of the associated encoded handler data to thecatch_handler_itemfor this entry

encoded_catch_handler_listFormat

Name

Format

Description

size

uleb128

size of this list, in entries

list

encoded_catch_handler[handlers_size]

actual list of handler lists, represented directly (not as offsets), and concatenated sequentially

encoded_catch_handlerFormat

Name

Format

Description

size

sleb128

number of catch types in this list. If non-positive, then this is the negative of the number of catch types, and the catches are followed by a catch-all handler. For example: Asizeof0means that there is a catch-all but no explicitly typed catches. Asizeof2means that there are two explicitly typed catches and no catch-all. And asizeof-1means that there is one typed catch along with a catch-all.

handlers

encoded_type_addr_pair[abs(size)]

stream ofabs(size)encoded items, one for each caught type, in the order that the types should be tested.

catch_all_addr

uleb128(optional)

bytecode address of the catch-all handler. This element is only present ifsizeis non-positive.

encoded_type_addr_pairFormat

Name

Format

Description

type_idx

uleb128

index into thetype_idslist for the type of the exception to catch

addr

uleb128

bytecode address of the associated exception handler

debug_info_item

referenced fromcode_item

appears in thedatasection

alignment: none (byte-aligned)

Eachdebug_info_itemdefines a DWARF3-inspired byte-coded state machine that, when interpreted, emits the positions table and (potentially) the local variable information for acode_item. The sequence begins with a variable-length header (the length of which depends on the number of method parameters), is followed by the state machine bytecodes, and ends with anDBG_END_SEQUENCEbyte.

The state machine consists of five registers. Theaddressregister represents the instruction offset in the associatedinsns_itemin 16-bit code units. Theaddressregister starts at0at the beginning of eachdebug_infosequence and may only monotonically increase. Thelineregister represents what source line number should be associated with the next positions table entry emitted by the state machine. It is initialized in the sequence header, and may change in positive or negative directions but must never be less than1. Thesource_fileregister represents the source file that the line number entries refer to. It is initialized to the value ofsource_file_idxinclass_def_item. The other two variables,prologue_endandepilogue_begin, are boolean flags (initialized tofalse) that indicate whether the next position emitted should be considered a method prologue or epilogue. The state machine must also track the name and type of the last local variable live in each register for theDBG_RESTART_LOCALcode.

The header is as follows:

Name

Format

Description

line_start

uleb128

the initial value for the state machine'slineregister. Does not represent an actual positions entry.

parameters_size

uleb128

the number of parameter names that are encoded. There should be one per method parameter, excluding an instance method'sthis, if any.

parameter_names

uleb128p1[parameters_size]

string index of the method parameter name. An encoded value ofNO_INDEXindicates that no name is available for the associated parameter. The type descriptor and signature are implied from the method descriptor and signature.

The byte code values are as follows:

Name

Value

Format

Arguments

Description

DBG_END_SEQUENCE

0x00

(none)

terminates a debug info sequence for acode_item

DBG_ADVANCE_PC

0x01

uleb128addr_diff

addr_diff: amount to add to address register

advances the address register without emitting a positions entry

DBG_ADVANCE_LINE

0x02

sleb128line_diff

line_diff: amount to change line register by

advances the line register without emitting a positions entry

DBG_START_LOCAL

0x03

uleb128register_num
uleb128p1name_idx
uleb128p1type_idx

register_num: register that will contain local
name_idx: string index of the name
type_idx: type index of the type

introduces a local variable at the current address. Eithername_idxortype_idxmay beNO_INDEXto indicate that that value is unknown.

DBG_START_LOCAL_EXTENDED

0x04

uleb128register_num
uleb128p1name_idx
uleb128p1type_idx
uleb128p1sig_idx

register_num: register that will contain local
name_idx: string index of the name
type_idx: type index of the type
sig_idx: string index of the type signature

introduces a local with a type signature at the current address. Any ofname_idx,type_idx, orsig_idxmay beNO_INDEXto indicate that that value is unknown. (Ifsig_idxis-1, though, the same data could be represented more efficiently using the opcodeDBG_START_LOCAL.)

Note:See the discussion under "dalvik.annotation.Signature" below for caveats about handling signatures.

DBG_END_LOCAL

0x05

uleb128register_num

register_num: register that contained local

marks a currently-live local variable as out of scope at the current address

DBG_RESTART_LOCAL

0x06

uleb128register_num

register_num: register to restart

re-introduces a local variable at the current address. The name and type are the same as the last local that was live in the specified register.

DBG_SET_PROLOGUE_END

0x07

(none)

sets theprologue_endstate machine register, indicating that the next position entry that is added should be considered the end of a method prologue (an appropriate place for a method breakpoint). Theprologue_endregister is cleared by any special (>= 0x0a) opcode.

DBG_SET_EPILOGUE_BEGIN

0x08

(none)

sets theepilogue_beginstate machine register, indicating that the next position entry that is added should be considered the beginning of a method epilogue (an appropriate place to suspend execution before method exit). Theepilogue_beginregister is cleared by any special (>= 0x0a) opcode.

DBG_SET_FILE

0x09

uleb128p1name_idx

name_idx: string index of source file name;NO_INDEXif unknown

indicates that all subsequent line number entries make reference to this source file name, instead of the default name specified incode_item

Special Opcodes

0x0a…0xff

(none)

advances thelineandaddressregisters, emits a position entry, and clearsprologue_endandepilogue_begin. See below for description.

Special Opcodes

Opcodes with values between0x0aand0xff(inclusive) move both thelineandaddressregisters by a small amount and then emit a new position table entry. The formula for the increments are as follows:

DBG_FIRST_SPECIAL = 0x0a // the smallest special opcode

DBG_LINE_BASE = -4 // the smallest line number increment

DBG_LINE_RANGE = 15 // the number of line increments represented

adjusted_opcode = opcode - DBG_FIRST_SPECIAL

line += DBG_LINE_BASE + (adjusted_opcode % DBG_LINE_RANGE)

address += (adjusted_opcode / DBG_LINE_RANGE)

annotations_directory_item

referenced fromclass_def_item

appears in thedatasection

alignment: 4 bytes

Name

Format

Description

class_annotations_off

uint

offset from the start of the file to the annotations made directly on the class, or0if the class has no direct annotations. The offset, if non-zero, should be to a location in thedatasection. The format of the data is specified by "annotation_set_item" below.

fields_size

uint

count of fields annotated by this item

annotated_methods_off

uint

count of methods annotated by this item

annotated_parameters_off

uint

count of method parameter lists annotated by this item

field_annotations

field_annotation[fields_size](optional)

list of associated field annotations. The elements of the list must be sorted in increasing order, byfield_idx.

method_annotations

method_annotation[methods_size](optional)

list of associated method annotations. The elements of the list must be sorted in increasing order, bymethod_idx.

parameter_annotations

parameter_annotation[parameters_size](optional)

list of associated method parameter annotations. The elements of the list must be sorted in increasing order, bymethod_idx.

Note:All elements'field_ids andmethod_ids must refer to the same defining class.

field_annotationFormat

Name

Format

Description

field_idx

uint

index into thefield_idslist for the identity of the field being annotated

annotations_off

uint

offset from the start of the file to the list of annotations for the field. The offset should be to a location in thedatasection. The format of the data is specified by "annotation_set_item" below.

method_annotationFormat

Name

Format

Description

method_idx

uint

index into themethod_idslist for the identity of the method being annotated

annotations_off

uint

offset from the start of the file to the list of annotations for the method. The offset should be to a location in thedatasection. The format of the data is specified by "annotation_set_item" below.

parameter_annotationFormat

Name

Format

Description

method_idx

uint

index into themethod_idslist for the identity of the method whose parameters are being annotated

annotations_off

uint

offset from the start of the file to the list of annotations for the method parameters. The offset should be to a location in thedatasection. The format of the data is specified by "annotation_set_ref_list" below.

annotation_set_ref_list

referenced fromparameter_annotations_item

appears in thedatasection

alignment: 4 bytes

Name

Format

Description

size

uint

size of the list, in entries

list

annotation_set_ref_item[size]

elements of the list

annotation_set_ref_itemFormat

Name

Format

Description

annotations_off

uint

offset from the start of the file to the referenced annotation set or0if there are no annotations for this element. The offset, if non-zero, should be to a location in thedatasection. The format of the data is specified by "annotation_set_item" below.

annotation_set_item

referenced fromannotations_directory_item,field_annotations_item,method_annotations_item, andannotation_set_ref_item

appears in thedatasection

alignment: 4 bytes

Name

Format

Description

size

uint

size of the set, in entries

entries

annotation_off_item[size]

elements of the set. The elements must be sorted in increasing order, bytype_idx.

annotation_off_itemFormat

Name

Format

Description

annotation_off

uint

offset from the start of the file to an annotation. The offset should be to a location in thedatasection, and the format of the data at that location is specified by "annotation_item" below.

annotation_item

referenced fromannotation_set_item

appears in thedatasection

alignment: none (byte-aligned)

Name

Format

Description

visibility

ubyte

intended visibility of this annotation (see below)

annotation

encoded_annotation

encoded annotation contents, in the format described by "encoded_annotationFormat" under "encoded_valueEncoding" above.

Visibility values

These are the options for thevisibilityfield in anannotation_item:

Name

Value

Description

VISIBILITY_BUILD

0x00

intended only to be visible at build time (e.g., during compilation of other code)

VISIBILITY_RUNTIME

0x01

intended to visible at runtime

VISIBILITY_SYSTEM

0x02

intended to visible at runtime, but only to the underlying system (and not to regular user code)

encoded_array_item

referenced fromclass_def_item

appears in thedatasection

alignment: none (byte-aligned)

Name

Format

Description

value

encoded_array

bytes representing the encoded array value, in the format specified by "encoded_arrayFormat" under "encoded_valueEncoding" above.

System Annotations

System annotations are used to represent various pieces of reflective information about classes (and methods and fields). This information is generally only accessed indirectly by client (non-system) code.

System annotations are represented in.dexfiles as annotations with visibility set toVISIBILITY_SYSTEM.

dalvik.annotation.AnnotationDefault

appears on methods in annotation interfaces

AnAnnotationDefaultannotation is attached to each annotation interface which wishes to indicate default bindings.

Name

Format

Description

value

Annotation

the default bindings for this annotation, represented as an annotation of this type. The annotation need not include all names defined by the annotation; missing names simply do not have defaults.

dalvik.annotation.EnclosingClass

appears on classes

AnEnclosingClassannotation is attached to each class which is either defined as a member of another class, per se, or is anonymous but not defined within a method body (e.g., a synthetic inner class). Every class that has this annotation must also have anInnerClassannotation. Additionally, a class may not have both anEnclosingClassand anEnclosingMethodannotation.

Name

Format

Description

value

Class

the class which most closely lexically scopes this class

dalvik.annotation.EnclosingMethod

appears on classes

AnEnclosingMethodannotation is attached to each class which is defined inside a method body. Every class that has this annotation must also have anInnerClassannotation. Additionally, a class may not have both anEnclosingClassand anEnclosingMethodannotation.

Name

Format

Description

value

Method

the method which most closely lexically scopes this class

dalvik.annotation.InnerClass

appears on classes

AnInnerClassannotation is attached to each class which is defined in the lexical scope of another class's definition. Any class which has this annotation must also haveeitheranEnclosingClassannotationoranEnclosingMethodannotation.

Name

Format

Description

name

String

the originally declared simple name of this class (not including any package prefix). If this class is anonymous, then the name isnull.

accessFlags

int

the originally declared access flags of the class (which may differ from the effective flags because of a mismatch between the execution models of the source language and target virtual machine)

dalvik.annotation.MemberClasses

appears on classes

AMemberClassesannotation is attached to each class which declares member classes. (A member class is a direct inner class that has a name.)

Name

Format

Description

value

Class[]

array of the member classes

dalvik.annotation.Signature

appears on classes, fields, and methods

ASignatureannotation is attached to each class, field, or method which is defined in terms of a more complicated type than is representable by atype_id_item. The.dexformat does not define the format for signatures; it is merely meant to be able to represent whatever signatures a source language requires for successful implementation of that language's semantics. As such, signatures are not generally parsed (or verified) by virtual machine implementations. The signatures simply get handed off to higher-level APIs and tools (such as debuggers). Any use of a signature, therefore, should be written so as not to make any assumptions about only receiving valid signatures, explicitly guarding itself against the possibility of coming across a syntactically invalid signature.

Because signature strings tend to have a lot of duplicated content, aSignatureannotation is defined as anarrayof strings, where duplicated elements naturally refer to the same underlying data, and the signature is taken to be the concatenation of all the strings in the array. There are no rules about how to pull apart a signature into separate strings; that is entirely up to the tools that generate.dexfiles.

Name

Format

Description

value

String[]

the signature of this class or member, as an array of strings that is to be concatenated together

dalvik.annotation.Throws

appears on methods

AThrowsannotation is attached to each method which is declared to throw one or more exception types.

Name

Format

Description

value

Class[]

the array of exception types thrown

分享到:
评论

相关推荐

    Dex文件结构

    详细介绍android apk Dex文件结构;

    Dex文件头结构解析器

    dex作为Android平台下的exe是一个非常重要的文件。所以分析就有了必要。 dex作为Android平台下的exe是一个非常重要的文件。所以分析就有了必要。

    安卓反编译dex文件格式实例分析

    1. dex 整个文件的布局 2. header 3. string_ids 4. type_ids 5. proto_ids 6. field_ids 7. method_ids 8. class_defs 8.1 class_def_item 8.2 class_def_item --&gt; class_data_item 8.3 class_def_item --&gt; ...

    android dalvik虚拟机结构及机制剖析 第二卷

    android dalvik虚拟机结构及机制剖析 第二版,详细介绍Android虚拟机值得阅览

    Smali语法学习与DEX文件详解

    Smali代码是Android的Dalvik虚拟机的可执行文件DEX文件反汇编后的代码。所以Smali语言就是Dalvik的反汇编语言。 使用Apktool反编译apk 文件后,会在反编译工程目录下生成一个smali 文件夹,里面存放着所有反编译出的...

    Android应用程序的补丁方法.pdf

    随着Android系统版本的增加,一些结构也有了微妙的变化,本文所描述的DEX文件格式源于Android 4.0源代码中的“dalvik\libdex\DexFile.h”文件所提供的信息。另外,由于本人知识也极有限的,所以,在理解与表述方面...

    Android运行时ART加载OAT文件的过程分析

    OAT文件是一种Android私有ELF文件格式,它不仅包含有从DEX文件翻译而来的本地机器指令,还包含有原来的DEX文件内容。这使得我们无需重新编译原有的APK就可以让它正常地在ART里面运行,也就是我们不需要改变原来的APK...

    新版Android开发教程.rar

    ----------------------------------- Android 编程基础 1 封面----------------------------------- Android 编程基础 ...• SQLite SQLite SQLite SQLite 用作结构化的数据存储 • 多媒体支持 包括常见的音频、视频和...

    android系统原理及开发要点详解

     第9章“Android的多媒体系统”,介绍Android的多媒体系统的核心部分,包括Android中多媒体系统的业务、结构、多媒体系统的核心框架、OpenCore系统结构和使用等内容。  第10章“Android的电话部分”,介绍Android...

    解包打包android内核system.img文件所需工具

    最后一步:因为system.img中的apk是优化过的,apk主目录下是没有classes.dex文件的,而是一个被优化过的odex文件,用于优化启动速度。 因此需要将修改后的apk包再用dexopt-wrapper优化apk包后生成出odex文件,...

    咋把dex文件变成java源码-redexer:Dalvik字节码的Redexer二进制检测框架

    咋把dex文件变成java源码 还原剂 Redexer 是一个重新设计的工具,用于操作 Android 应用程序二进制文件。 该工具能够将 DEX 文件解析为内存中的数据结构; 推断应用程序使用哪些参数使用某些权限(我们将此功能命名...

    Android技术内幕.系统卷(扫描版)

    8.2.3 .dex文件格式解析 /470 8.2.4 dalvik内部机制 /487 8.2.5 dalvik进程管理 /492 8.2.6 dalvik内存管理 /501 8.2.7 dalvik加载器 /509 8.2.8 dalvik解释器 /517 8.2.9 dalvik jit /519 8.3 jni的构架与实现 /523...

    Android代码-apk_auto_enforce

    &gt; DEX文件结构分析 http://shuwoom.com/?p=179 &gt; DALVIK加载和解析DEX过程 http://shuwoom.com/?p=269 &gt; DALVIK查找类和方法的过程 http://shuwoom.com/?p=282 &gt; ELF文件结构分析 http://shuwoom.com/?p=286 &gt; SO...

    android 完全中文版 开发应用详解

    13.4 android 应用层api参考文档 315 第14章 android应用程序的主要方面 317 14.1 应用的基本控制 318 14.1.1 ui元素及其控制 318 14.1.2 屏幕间的跳转 320 14.1.3 弹出对话框和菜单 324 14.1.4 样式的设置 328 ...

    零基础入门Android(安卓)逆向-rar

    21.class.dex文件格式讲解 22.Android 动态代码自修改原理 23.Android 动态代码自修改实现1 . F; Z5 @* D* r 24.Android 动态代码自修改实现2 25.Android dvm 脱壳1 26.elf结构详解1, d9 H, S" s2 }8 j' B6 v 27...

    Android逆向分析基础篇之格式篇.pdf

    目录 Dalvik 虚拟机 •Dalvik 虚拟机介绍 •Dalvik汇编语言基础 •Dalvik版本HellWorld ...•Dex文件结构解析 •ODex文件结构解析 •另类APK破解方法 Smali文件格式 •Smali文件结构解析 •IDA Pro 破解实例

    Android APK文件结构 完整打包编译的流程 APK安装过程 详解

    Android apk文件结构 打包编译的流程Android官网 配置构建 流程Configure your buildThe build processAPK文件结构assetsreslibMETA-INFAndroidManifest.xmlclasses.dexresources.arscAndroid完整打包流程详细介绍1....

    Android应用程序开发教程PDF电子书完整版、Android开发学习教程

    Dalvik 虚拟机执行(.dex)的 Dalvik 可执行文件,该格式文 件针对小内存使用做了 优化。同时虚拟机是基于寄存器的,所有的类都经由 JAVA 编译器编译,然后通过 SDK 中 的 "dx" 工具转化成.dex 格式由虚拟机执行。 ...

    Android技术内幕.系统卷 pdf

    8.2.3 .dex文件格式解析 /470 8.2.4 dalvik内部机制 /487 8.2.5 dalvik进程管理 /492 8.2.6 dalvik内存管理 /501 8.2.7 dalvik加载器 /509 8.2.8 dalvik解释器 /517 8.2.9 dalvik jit /519 8.3 jni的构架与...

    AndroidLinker与SO加壳技术之下篇

    目前Android 应用加固可以分为dex加固和Native加固,Native 加固的保护对象为 Native 层的 SO 文件,使用加壳、反调试、混淆、VM 等手段增加SO文件的反编译难度。目前最主流的 SO 文件保护方案还是加壳技术, 在SO...

Global site tag (gtag.js) - Google Analytics