Formato eseguibile Dalvik

Questo documento descrive il layout e il contenuto dei file .dex , che vengono utilizzati per contenere una serie di definizioni di classi e i dati aggiuntivi associati.

Guida ai tipi

Nome Descrizione
byte 8 bit firmato int
ubite Int. senza segno a 8 bit
breve 16 bit firmato int, little-endian
corto 16 bit senza segno int, little-endian
int 32 bit firmato int, little-endian
uint 32 bit senza segno int, little-endian
lungo 64 bit firmato int, little-endian
lungo 64 bit senza segno int, little-endian
sleb128 firmato LEB128, lunghezza variabile (vedi sotto)
uleb128 LEB128 senza segno, a lunghezza variabile (vedi sotto)
uleb128p1 senza segno LEB128 più 1 , a lunghezza variabile (vedi sotto)

LEB128

LEB128 ("Little- Endian B ase 128 ") è una codifica a lunghezza variabile per quantità intere arbitrarie con o senza segno. Il formato è stato preso in prestito dalla specifica DWARF3 . In un file .dex , LEB128 viene utilizzato solo per codificare quantità a 32 bit.

Ciascun valore codificato LEB128 è composto da uno a cinque byte, che insieme rappresentano un singolo valore a 32 bit. Ogni byte ha il bit più significativo impostato tranne il byte finale nella sequenza, che ha il bit più significativo libero. I restanti sette bit di ogni byte sono payload, con i sette bit meno significativi della quantità nel primo byte, i successivi sette nel secondo byte e così via. Nel caso di un LEB128 con segno ( sleb128 ), il bit di payload più significativo del byte finale nella sequenza viene esteso con il segno per produrre il valore finale. Nel caso senza segno ( uleb128 ), tutti i bit non rappresentati in modo esplicito vengono interpretati come 0 .

Diagramma bit per bit di un valore LEB128 a due byte
Primo byte Secondo byte
1 bit 6 bit 5 bit 4 bit 3 bit 2 bit 1 bit 0 0 bit 13 bit 12 bit 11 bit 10 bit 9 bit 8 bit 7

La variante uleb128p1 viene utilizzata per rappresentare un valore con segno, dove la rappresentazione è del valore più uno codificato come uleb128 . Questo rende la codifica di -1 (in alternativa pensato come il valore senza segno 0xffffffff ) - ma nessun altro numero negativo - un singolo byte, ed è utile esattamente in quei casi in cui il numero rappresentato deve essere non negativo o -1 (o 0xffffffff ) e dove non sono consentiti altri valori negativi (o dove è improbabile che siano necessari valori grandi senza segno).

Ecco alcuni esempi di formati:

Sequenza codificata Come sleb128 Come uleb128 Come uleb128p1
00 0 0 -1
01 1 1 0
7f -1 127 126
80 7f -128 16256 16255

Disposizione dei file

Nome Formato Descrizione
intestazione header_item l'intestazione
string_id string_id_item[] elenco di identificatori di stringa. Questi sono identificatori per tutte le stringhe utilizzate da questo file, sia per la denominazione interna (es. descrittori di tipo) sia come oggetti costanti a cui fa riferimento il codice. Questo elenco deve essere ordinato in base al contenuto della stringa, utilizzando i valori dei punti di codice UTF-16 (non in modo sensibile alle impostazioni locali) e non deve contenere voci duplicate.
ID_tipo type_id_item[] elenco di identificatori di tipo. Questi sono identificatori per tutti i tipi (classi, array o tipi primitivi) a cui fa riferimento questo file, siano essi definiti nel file o meno. Questo elenco deve essere ordinato in base all'indice string_id e non deve contenere voci duplicate.
proto_id proto_id_item[] elenco degli identificatori del prototipo del metodo. Questi sono gli identificatori per tutti i prototipi a cui fa riferimento questo file. Questo elenco deve essere ordinato in ordine maggiore di tipo restituito (per indice type_id ) e quindi per elenco di argomenti (ordinamento lessicografico, singoli argomenti ordinati per indice type_id ). L'elenco non deve contenere voci duplicate.
ID_campo field_id_item[] elenco degli identificatori di campo. Questi sono identificatori per tutti i campi a cui fa riferimento questo file, siano essi definiti nel file o meno. Questo elenco deve essere ordinato, dove il tipo di definizione (per indice type_id ) è l'ordine principale, il nome del campo (per indice string_id ) è l'ordine intermedio e il tipo (per indice type_id ) è l'ordine minore. L'elenco non deve contenere voci duplicate.
ID_metodo elemento_id_metodo[] elenco degli identificatori di metodo. Questi sono identificatori per tutti i metodi a cui fa riferimento questo file, siano essi definiti nel file o meno. Questo elenco deve essere ordinato, dove il tipo di definizione (per type_id ) è l'ordine principale, il nome del metodo (per string_id ) è l'ordine intermedio e il prototipo del metodo (per proto_id ) è l'ordine minore. L'elenco non deve contenere voci duplicate.
class_defs class_def_item[] elenco delle definizioni di classe. Le classi devono essere ordinate in modo tale che la superclasse di una data classe e le interfacce implementate appaiano nell'elenco prima della classe di riferimento. Inoltre, non è valido che una definizione per la classe con lo stesso nome appaia più di una volta nell'elenco.
call_site_ids call_site_id_item[] elenco degli identificatori del sito di chiamata. Questi sono identificatori per tutti i siti di chiamata a cui fa riferimento questo file, siano essi definiti nel file o meno. Questo elenco deve essere ordinato in ordine crescente di call_site_off .
metodo_handles metodo_handle_item[] elenco degli handle di metodo. Un elenco di tutti gli handle di metodo a cui fa riferimento questo file, siano essi definiti nel file o meno. Questo elenco non è ordinato e può contenere duplicati che corrisponderanno logicamente a diverse istanze di handle di metodo.
dati ubyte[] area dati, contenente tutti i dati di supporto per le tabelle sopra elencate. Elementi diversi hanno requisiti di allineamento diversi e i byte di riempimento vengono inseriti prima di ogni elemento, se necessario, per ottenere un allineamento corretto.
link_data ubyte[] dati utilizzati nei file collegati staticamente. Il formato dei dati in questa sezione non è specificato da questo documento. Questa sezione è vuota nei file non collegati e le implementazioni di runtime possono utilizzarla come meglio credono.

Definizioni di bitfield, stringhe e costanti

DEX_FILE_MAGIC

incorporato in header_item

L'array/string costante DEX_FILE_MAGIC è l'elenco di byte che devono apparire all'inizio di un file .dex affinché venga riconosciuto come tale. Il valore contiene intenzionalmente una nuova riga ( "\n" o 0x0a ) e un byte null ( "\0" o 0x00 ) per facilitare il rilevamento di determinate forme di corruzione. Il valore codifica anche un numero di versione del formato come tre cifre decimali, che dovrebbe aumentare in modo monotono nel tempo man mano che il formato evolve.

ubyte[8] DEX_FILE_MAGIC = { 0x64 0x65 0x78 0x0a 0x30 0x33 0x39 0x00 }
                        = "dex\n039\0"

Nota: il supporto per la versione 039 del formato è stato aggiunto nella versione Android 9.0, che ha introdotto due nuovi bytecode, const-method-handle e const-method-type . (Tutti questi sono descritti nella tabella Riepilogo del set di bytecode .) In Android 10, la versione 039 estende il formato del file DEX per includere informazioni API nascoste applicabili solo ai file DEX nel percorso della classe di avvio.

Nota: il supporto per la versione 038 del formato è stato aggiunto nella versione Android 8.0. La versione 038 ha aggiunto nuovi bytecode ( invoke-polymorphic e invoke-custom ) e dati per gli handle del metodo.

Nota: il supporto per la versione 037 del formato è stato aggiunto nella versione Android 7.0. Prima della versione 037 la maggior parte delle versioni di Android utilizzava la versione 035 del formato. L'unica differenza tra le versioni 035 e 037 è l'aggiunta di metodi predefiniti e la regolazione invoke .

Nota: almeno un paio di versioni precedenti del formato sono state utilizzate in versioni di software pubblico ampiamente disponibili. Ad esempio, la versione 009 è stata utilizzata per le versioni M3 della piattaforma Android (novembre-dicembre 2007) e la versione 013 è stata utilizzata per le versioni M5 della piattaforma Android (febbraio-marzo 2008). Per diversi aspetti, queste versioni precedenti del formato differiscono in modo significativo dalla versione descritta in questo documento.

ENDIAN_CONSTANT e REVERSE_ENDIAN_CONSTANT

incorporato in header_item

La costante ENDIAN_CONSTANT viene utilizzata per indicare l'endianità del file in cui si trova. Sebbene il formato .dex standard sia little-endian, le implementazioni possono scegliere di eseguire lo scambio di byte. Se un'implementazione incontra un'intestazione il cui endian_tag è REVERSE_ENDIAN_CONSTANT invece di ENDIAN_CONSTANT , saprebbe che il file è stato scambiato di byte dal modulo previsto.

uint ENDIAN_CONSTANT = 0x12345678;
uint REVERSE_ENDIAN_CONSTANT = 0x78563412;

NO_INDICE

incorporato in class_def_item e debug_info_item

La costante NO_INDEX viene utilizzata per indicare che un valore di indice è assente.

Nota: questo valore non è definito come 0 , perché in realtà è in genere un indice valido.

Il valore scelto per NO_INDEX è rappresentabile come un singolo byte nella codifica uleb128p1 .

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

definizioni di access_flags

incorporato in class_def_item, encoded_field, encoded_method e InnerClass

I campi di bit di questi flag vengono utilizzati per indicare l'accessibilità e le proprietà generali delle classi e dei membri della classe.

Nome Valore Per Classi (e annotazioni InnerClass ) Per i campi Per i metodi
ACC_PUBLIC 0x1 public : visibile ovunque public : visibile ovunque public : visibile ovunque
ACC_PRIVATO 0x2 * private : visibile solo alla classe di definizione private : visibile solo alla classe di definizione private : visibile solo alla classe di definizione
ACC_PROTETTO 0x4 * protected : visibile al pacchetto e alle sottoclassi protected : visibile al pacchetto e alle sottoclassi protected : visibile al pacchetto e alle sottoclassi
ACC_STATICO 0x8 * static : this è costruito con un riferimento esterno static : globale per definire la classe static : non accetta this argomento
ACC_FINALE 0x10 final : non sottoclassificabile final : immutabile dopo la costruzione final : non annullabile
ACC_SINCRONIZZATO 0x20 synchronized : blocco associato acquisito automaticamente attorno alla chiamata a questo metodo.

Nota: questo è valido solo per l'impostazione quando è impostato anche ACC_NATIVE .

ACC_VOLATILE 0x40 volatile : regole di accesso speciali per aiutare con la sicurezza dei thread
ACC_BRIDGE 0x40 bridge, aggiunto automaticamente dal compilatore come bridge indipendente dai tipi
ACC_TRANSIENT 0x80 transient : da non salvare per serializzazione predefinita
ACC_VARARGS 0x80 l'ultimo argomento dovrebbe essere trattato come un argomento di "riposo" dal compilatore
ACC_NATIVO 0x100 native : implementato nel codice nativo
ACC_INTERFACCIA 0x200 interface : classe astratta multi-implementabile
ACC_ABSTRACT 0x400 abstract : non direttamente istanziabile abstract : non implementato da questa classe
ACC_STRETTO 0x800 strictfp : regole rigorose per l'aritmetica in virgola mobile
ACC_SINTETICO 0x1000 non direttamente definito nel codice sorgente non direttamente definito nel codice sorgente non direttamente definito nel codice sorgente
ACC_ANNOTAZIONE 0x2000 dichiarata come classe di annotazione
ACC_ENUM 0x4000 dichiarato come tipo enumerato dichiarato come valore enumerato
(non utilizzato) 0x8000
ACC_CONSTRUCTOR 0x10000 metodo del costruttore (inizializzatore di classe o istanza)
ACC_DECLARED_
SINCRONIZZATO
0x20000 dichiarato synchronized .

Nota: questo non ha alcun effetto sull'esecuzione (a parte il riflesso di questo flag, di per sé).

* Consentito solo per le annotazioni InnerClass e non deve mai essere attivo in un class_def_item .

Codifica MUTF-8 (UTF-8 modificato).

Come concessione a un supporto legacy più semplice, il formato .dex codifica i suoi dati di stringa in un formato UTF-8 modificato standard de facto, di seguito denominato MUTF-8. Questo modulo è identico allo standard UTF-8, tranne:

  • Vengono utilizzate solo le codifiche a uno, due e tre byte.
  • I punti di codice nell'intervallo U+10000U+10ffff sono codificati come una coppia surrogata, ciascuno dei quali è rappresentato come un valore codificato a tre byte.
  • Il punto di codice U+0000 è codificato in formato a due byte.
  • Un byte null semplice (valore 0 ) indica la fine di una stringa, così come l'interpretazione del linguaggio C standard.

I primi due elementi sopra possono essere riassunti come: MUTF-8 è un formato di codifica per UTF-16, invece di essere un formato di codifica più diretto per i caratteri Unicode.

Gli ultimi due elementi sopra consentono di includere contemporaneamente il punto di codice U+0000 in una stringa e di manipolarlo ancora come una stringa con terminazione nulla in stile C.

Tuttavia, la codifica speciale di U+0000 significa che, a differenza del normale UTF-8, il risultato della chiamata della funzione C standard strcmp() su una coppia di stringhe MUTF-8 non indica sempre il risultato del confronto di stringhe disuguali con segno corretto . Quando l'ordine (non solo l'uguaglianza) è un problema, il modo più semplice per confrontare le stringhe MUTF-8 è decodificarle carattere per carattere e confrontare i valori decodificati. (Tuttavia, sono possibili anche implementazioni più intelligenti.)

Fare riferimento a The Unicode Standard per ulteriori informazioni sulla codifica dei caratteri. MUTF-8 è in realtà più vicino alla codifica (relativamente meno nota) CESU-8 che a UTF-8 di per sé.

codifica valore_codificato

incorporato in annotation_element e encoded_array_item

Un encoded_value è un pezzo codificato di dati strutturati gerarchicamente (quasi) arbitrari. La codifica è pensata per essere compatta e semplice da analizzare.

Nome Formato Descrizione
(valore_arg << 5) | tipo_valore ubite byte che indica il tipo del value immediatamente successivo insieme a un argomento di chiarimento opzionale nei tre bit di ordine superiore. Vedi sotto per le varie definizioni di value . Nella maggior parte dei casi, value_arg codifica la lunghezza del value immediatamente successivo in byte, come (size - 1) , ad esempio, 0 significa che il valore richiede un byte e 7 significa che richiede otto byte; tuttavia, ci sono eccezioni come indicato di seguito.
valore ubyte[] byte che rappresentano il valore, di lunghezza variabile e interpretati in modo diverso per byte value_type diversi, sebbene sempre little-endian. Per i dettagli, vedere le varie definizioni di valore di seguito.

Formati di valore

Digita Nome value_type value_arg Formato value Formato Descrizione
VALUE_BYTE 0x00 (nessuno; deve essere 0 ) ubyte[1] valore intero di un byte con segno
VALUE_SHORT 0x02 taglia - 1 (0…1) ubyte[dimensione] valore intero a due byte con segno, con estensione del segno
VALUE_CHAR 0x03 taglia - 1 (0…1) ubyte[dimensione] valore intero a due byte senza segno, con estensione zero
VALUE_INT 0x04 taglia - 1 (0…3) ubyte[dimensione] valore intero a quattro byte con segno, con estensione del segno
VALUE_LONG 0x06 taglia - 1 (0…7) ubyte[dimensione] valore intero di otto byte con segno, con estensione del segno
VALUE_FLOAT 0x10 taglia - 1 (0…3) ubyte[dimensione] modello di bit a quattro byte, con estensione zero a destra e interpretato come valore in virgola mobile IEEE754 a 32 bit
VALUE_DOUBLE 0x11 taglia - 1 (0…7) ubyte[dimensione] modello di bit a otto byte, con estensione zero a destra e interpretato come valore in virgola mobile IEEE754 a 64 bit
VALUE_METHOD_TYPE 0x15 taglia - 1 (0…3) ubyte[dimensione] valore intero a quattro byte senza segno (estensione zero), interpretato come un indice nella sezione proto_ids e che rappresenta un valore del tipo di metodo
VALUE_METHOD_HANDLE 0x16 taglia - 1 (0…3) ubyte[dimensione] valore intero a quattro byte senza segno (con estensione zero), interpretato come un indice nella sezione method_handles e che rappresenta un valore di handle del metodo
VALUE_STRING 0x17 taglia - 1 (0…3) ubyte[dimensione] valore intero a quattro byte senza segno (estensione zero), interpretato come un indice nella sezione string_ids e che rappresenta un valore stringa
VALUE_TYPE 0x18 taglia - 1 (0…3) ubyte[dimensione] valore intero a quattro byte senza segno (con estensione zero), interpretato come un indice nella sezione type_ids e che rappresenta un valore riflettente di tipo/classe
VALUE_FIELD 0x19 taglia - 1 (0…3) ubyte[dimensione] valore intero a quattro byte senza segno (estensione zero), interpretato come un indice nella sezione field_ids e che rappresenta un valore di campo riflettente
VALUE_METODO 0x1a taglia - 1 (0…3) ubyte[dimensione] valore intero a quattro byte senza segno (con estensione zero), interpretato come un indice nella sezione method_ids e che rappresenta un valore di metodo riflessivo
VALUE_ENUM 0x1b taglia - 1 (0…3) ubyte[dimensione] valore intero a quattro byte senza segno (con estensione zero), interpretato come un indice nella sezione field_ids e che rappresenta il valore di una costante di tipo enumerato
VALUE_ARRAY 0x1c (nessuno; deve essere 0 ) array_codificato un array di valori, nel formato specificato da " formato encoded_array " di seguito. La dimensione del value è implicita nella codifica.
VALUE_ANNOTATION 0x1g (nessuno; deve essere 0 ) annotazione_codificata una sottoannotazione, nel formato specificato da " encoded_annotation format" di seguito. La dimensione del value è implicita nella codifica.
VALUE_NULL 0x1e (nessuno; deve essere 0 ) (nessuno) valore di riferimento null
VALUE_BOOLEANO 0x1f booleano (0…1) (nessuno) valore di un bit; 0 per false e 1 per true . Il bit è rappresentato in value_arg .

formato array_codificato

Nome Formato Descrizione
taglia uleb128 numero di elementi nell'array
i valori valore_codificato[dimensione] una serie di sequenze di byte size encoded_value nel formato specificato da questa sezione, concatenate in sequenza.

formato annotazione_codificata

Nome Formato Descrizione
tipo_idx uleb128 tipo di annotazione. Deve essere un tipo di classe (non array o primitivo).
taglia uleb128 numero di mappature nome-valore in questa annotazione
elementi elemento_annotazione[dimensione] elementi dell'annotazione, rappresentati direttamente in linea (non come offset). Gli elementi devono essere ordinati in ordine crescente in base all'indice string_id .

formato annotation_element

Nome Formato Descrizione
nome_idx uleb128 nome dell'elemento, rappresentato come un indice nella sezione string_ids . La stringa deve essere conforme alla sintassi per MemberName , definita sopra.
valore valore_codificato valore dell'elemento

Sintassi delle stringhe

Esistono diversi tipi di elementi in un file .dex che alla fine si riferiscono a una stringa. Le seguenti definizioni in stile BNF indicano la sintassi accettabile per queste stringhe.

SimpleName

Un SimpleName è la base per la sintassi dei nomi di altre cose. Il formato .dex consente qui una discreta latitudine (molto più delle lingue di origine più comuni). In breve, un nome semplice è costituito da qualsiasi carattere o cifra alfabetica con ASCII basso, alcuni simboli specifici con ASCII basso e la maggior parte dei punti di codice non ASCII che non sono caratteri di controllo, spazi o speciali. A partire dalla versione 040 il formato consente inoltre i caratteri spazio (categoria Unicode Zs ). Si noti che i punti di codice surrogati (nell'intervallo U+d800U+dfff ) non sono considerati caratteri di nome validi, di per sé, ma sono validi i caratteri supplementari Unicode (che sono rappresentati dall'alternativa finale della regola per SimpleNameChar ), e dovrebbe essere rappresentato in un file come coppie di punti di codice surrogati nella codifica MUTF-8.

NomeSemplice
SimpleNameChar ( SimpleNameChar )*
NomeSempliceCart
'A''Z'
| 'a' ... 'z'
| '0''9'
| ' ' dalla versione DEX 040
| '$'
| '-'
| '_'
| U+00a0 dalla versione DEX 040
| U+00a1U+1fff
| U+2000U+200a dalla versione DEX 040
| U+2010U+2027
| U+202f dalla versione DEX 040
| U+2030U+d7ff
| U+e000U+ffef
| U+10000U+10ffff

Nome del membro

utilizzato da field_id_item e method_id_item

Un MemberName è il nome di un membro di una classe, i membri sono campi, metodi e classi interne.

Nome membro
SimpleName
| '<' SimpleName '>'

Nomeclasse completo

Un FullClassName è un nome di classe completo, incluso un identificatore di pacchetto facoltativo seguito da un nome obbligatorio.

NomeClasse Completo
Facoltativo PackagePrefix SimpleName
Prefisso pacchetto opzionale
( SimpleName '/' )*

TypeDescriptor

utilizzato da type_id_item

Un TypeDescriptor è la rappresentazione di qualsiasi tipo, incluse primitive, classi, matrici e void . Vedi sotto per il significato delle varie versioni.

TypeDescriptor
'V'
| Descrittore del tipo di campo
FieldTypeDescriptor
Non ArrayFieldTypeDescriptor
| ( '[' * 1…255) Non ArrayFieldTypeDescriptor
Non ArrayFieldTypeDescriptor
'Z'
| 'B'
| 'S'
| 'C'
| 'I'
| 'J'
| 'F'
| 'D'
| 'L' NomeClasseCompleto ';'

ShortyDescriptor

utilizzato da proto_id_item

Uno ShortyDescriptor è la rappresentazione in forma abbreviata di un prototipo di metodo, inclusi i tipi di ritorno e di parametro, tranne per il fatto che non c'è distinzione tra vari tipi di riferimento (classe o array). Tutti i tipi di riferimento sono invece rappresentati da un singolo carattere 'L' .

ShortyDescriptor
ShortyReturnType ( ShortyFieldType )*
ShortyReturnType
'V'
| Tipo di campo corto
ShortyFieldType
'Z'
| 'B'
| 'S'
| 'C'
| 'I'
| 'J'
| 'F'
| 'D'
| 'L'

TypeDescriptor Semantica

Questo è il significato di ciascuna delle varianti di TypeDescriptor .

Sintassi Significato
V void ; valido solo per i tipi di reso
Z boolean
B byte
S short
C char
io int
J long
F float
D double
L pienamente/qualificato/Nome ; il fully.qualified.Name della classe
[ descrittore array of descriptor , utilizzabile in modo ricorsivo per array di array, sebbene non sia valido per avere più di 255 dimensioni.

Articoli e relative strutture

Questa sezione include le definizioni per ciascuno degli elementi di primo livello che possono apparire in un file .dex .

header_item

appare nella sezione dell'intestazione

allineamento: 4 byte

Nome Formato Descrizione
Magia ubyte[8] = DEX_FILE_MAGIC valore magico. Vedi la discussione sopra sotto " DEX_FILE_MAGIC " per maggiori dettagli.
somma di controllo uint adler32 checksum del resto del file (tutto tranne magic e questo campo); utilizzato per rilevare la corruzione dei file
firma ubyte[20] Firma SHA-1 (hash) del resto del file (tutto tranne magic , checksum e questo campo); utilizzato per identificare in modo univoco i file
dimensione del file uint dimensione dell'intero file (inclusa l'intestazione), in byte
header_size uint = 0x70 dimensione dell'intestazione (l'intera sezione), in byte. Ciò consente almeno una quantità limitata di compatibilità all'indietro/in avanti senza invalidare il formato.
tag_endian uint = ENDIAN_CONSTANT etichetta endianness. Vedi la discussione sopra sotto " ENDIAN_CONSTANT e REVERSE_ENDIAN_CONSTANT " per maggiori dettagli.
link_size uint dimensione della sezione del collegamento o 0 se questo file non è collegato staticamente
link_off uint offset dall'inizio del file alla sezione del collegamento o 0 se link_size == 0 . L'offset, se diverso da zero, dovrebbe essere un offset nella sezione link_data . Il formato dei dati indicati non è specificato nel presente documento; questo campo di intestazione (e il precedente) vengono lasciati come hook per l'uso da parte delle implementazioni di runtime.
map_off uint offset dall'inizio del file all'elemento della mappa. L'offset, che deve essere diverso da zero, dovrebbe essere un offset nella sezione dei data ei dati dovrebbero essere nel formato specificato da " map_list " di seguito.
string_ids_size uint conteggio delle stringhe nell'elenco degli identificatori di stringa
string_ids_off uint offset dall'inizio del file all'elenco degli identificatori di stringa o 0 se string_ids_size == 0 (certamente uno strano caso limite). L'offset, se diverso da zero, dovrebbe essere all'inizio della sezione string_ids .
type_ids_size uint conteggio di elementi nell'elenco degli identificatori di tipo, al massimo 65535
type_ids_off uint offset dall'inizio del file all'elenco degli identificatori di tipo o 0 se type_ids_size == 0 (certamente uno strano caso limite). L'offset, se diverso da zero, dovrebbe essere all'inizio della sezione type_ids .
proto_ids_size uint conteggio degli elementi nell'elenco degli identificatori del prototipo, al massimo 65535
proto_ids_off uint offset dall'inizio del file all'elenco degli identificatori del prototipo, o 0 se proto_ids_size == 0 (certamente uno strano caso limite). L'offset, se diverso da zero, dovrebbe essere all'inizio della sezione proto_ids .
field_ids_size uint conteggio degli elementi nell'elenco degli identificatori di campo
field_ids_off uint offset dall'inizio del file all'elenco degli identificatori di campo o 0 se field_ids_size == 0 . L'offset, se diverso da zero, dovrebbe essere all'inizio della sezione field_ids .
dimensione_id_metodo uint conteggio degli elementi nell'elenco degli identificatori di metodo
ID_metodo_off uint offset dall'inizio del file all'elenco degli identificatori del metodo o 0 se method_ids_size == 0 . L'offset, se diverso da zero, dovrebbe essere all'inizio della sezione method_ids .
class_defs_size uint conteggio degli elementi nell'elenco delle definizioni di classe
class_defs_off uint offset dall'inizio del file all'elenco delle definizioni di classe, o 0 se class_defs_size == 0 (certamente uno strano caso limite). L'offset, se diverso da zero, dovrebbe essere all'inizio della sezione class_defs .
dimensione_dati uint Dimensione della sezione data in byte. Deve essere un multiplo pari di sizeof(uint).
data_off uint offset dall'inizio del file all'inizio della sezione data .

lista_mappa

appare nella sezione dati

referenziato da header_item

allineamento: 4 byte

Questo è un elenco dell'intero contenuto di un file, in ordine. Contiene una certa ridondanza rispetto a header_item ma è inteso come un modulo facile da usare per scorrere un intero file. Un determinato tipo deve apparire al massimo una volta in una mappa, ma non ci sono restrizioni su quali tipi di ordine possono apparire, a parte le restrizioni implicite nel resto del formato (ad esempio, una sezione di header deve apparire prima, seguita da string_ids sezione, ecc.). Inoltre, le voci della mappa devono essere ordinate per offset iniziale e non devono sovrapporsi.

Nome Formato Descrizione
taglia uint dimensione dell'elenco, nelle voci
elenco map_item[dimensione] elementi della lista

formato map_item

Nome Formato Descrizione
genere corto tipo degli articoli; vedi tabella sotto
inutilizzato corto (non utilizzato)
taglia uint conteggio del numero di articoli che si trovano allo scostamento indicato
compensare uint offset dall'inizio del file agli elementi in questione

Codici di tipo

Tipo di elemento Costante Valore Dimensione articolo in byte
header_item TYPE_HEADER_ITEM 0x0000 0x70
elemento_id_stringa TYPE_STRING_ID_ITEM 0x0001 0x04
type_id_item TYPE_TYPE_ID_ITEM 0x0002 0x04
proto_id_item TYPE_PROTO_ID_ITEM 0x0003 0x0c
elemento_id_campo TYPE_FIELD_ID_ITEM 0x0004 0x08
elemento_id_metodo TYPE_METHOD_ID_ITEM 0x0005 0x08
class_def_item TYPE_CLASS_DEF_ITEM 0x0006 0x20
call_site_id_item TYPE_CALL_SITE_ID_ITEM 0x0007 0x04
metodo_handle_item TYPE_METHOD_HANDLE_ITEM 0x0008 0x08
lista_mappa TYPE_MAP_LIST 0x1000 4 + (dimensione articolo * 12)
tipo_lista TYPE_TYPE_LIST 0x1001 4 + (dimensione articolo * 2)
annotation_set_ref_list TYPE_ANNOTATION_SET_REF_LIST 0x1002 4 + (dimensione articolo * 4)
annotation_set_item TYPE_ANNOTATION_SET_ITEM 0x1003 4 + (dimensione articolo * 4)
class_data_item TYPE_CLASS_DATA_ITEM 0x2000 implicito; deve analizzare
codice_elemento TYPE_CODE_ITEM 0x2001 implicito; deve analizzare
elemento_dati_stringa TYPE_STRING_DATA_ITEM 0x2002 implicito; deve analizzare
debug_info_item TYPE_DEBUG_INFO_ITEM 0x2003 implicito; deve analizzare
annotation_item TYPE_ANNOTATION_ITEM 0x2004 implicito; deve analizzare
elemento_array_codificato TYPE_ENCODED_ARRAY_ITEM 0x2005 implicito; deve analizzare
voce_directory_annotazioni TYPE_ANNOTATIONS_DIRECTORY_ITEM 0x2006 implicito; deve analizzare
hiddenapi_class_data_item TYPE_HIDDENAPI_CLASS_DATA_ITEM 0xF000 implicito; deve analizzare

elemento_id_stringa

appare nella sezione string_ids

allineamento: 4 byte

Nome Formato Descrizione
stringa_dati_off uint offset dall'inizio del file ai dati della stringa per questo elemento. L'offset dovrebbe trovarsi in una posizione nella sezione data e i dati dovrebbero essere nel formato specificato da " string_data_item " di seguito. Non è richiesto alcun allineamento per l'offset.

elemento_dati_stringa

appare nella sezione dati

allineamento: nessuno (allineato ai byte)

Nome Formato Descrizione
utf16_dimensione uleb128 dimensione di questa stringa, in unità di codice UTF-16 (che è la "lunghezza della stringa" in molti sistemi). Cioè, questa è la lunghezza decodificata della stringa. (La lunghezza codificata è implicita nella posizione del byte 0 )
dati ubyte[] una serie di unità di codice MUTF-8 (aka ottetti, alias byte) seguite da un byte di valore 0 . Vedere "Codifica MUTF-8 (UTF-8 modificata)" sopra per dettagli e discussioni sul formato dei dati.

Nota: è accettabile avere una stringa che includa (la forma codificata di) unità di codice surrogato UTF-16 (ovvero, U+d800U+dfff ) isolatamente o fuori ordine rispetto alla normale codifica di Unicode in UTF-16. Spetta agli usi di livello superiore delle stringhe rifiutare tali codifiche non valide, se appropriato.

type_id_item

appare nella sezione type_ids

allineamento: 4 byte

Nome Formato Descrizione
descrittore_idx uint index nell'elenco string_ids per la stringa del descrittore di questo tipo. La stringa deve essere conforme alla sintassi per TypeDescriptor , definita sopra.

proto_id_item

appare nella sezione proto_ids

allineamento: 4 byte

Nome Formato Descrizione
shorty_idx uint index nell'elenco string_ids per la stringa del descrittore in forma abbreviata di questo prototipo. La stringa deve essere conforme alla sintassi per ShortyDescriptor , definita sopra, e deve corrispondere al tipo restituito e ai parametri di questo elemento.
return_type_idx uint index nell'elenco type_ids per il tipo restituito di questo prototipo
parametri_off uint offset dall'inizio del file all'elenco dei tipi di parametri per questo prototipo o 0 se questo prototipo non ha parametri. Questo offset, se diverso da zero, dovrebbe trovarsi nella sezione dei data e i dati dovrebbero essere nel formato specificato da "type_list" di seguito. Inoltre, non dovrebbe esserci alcun riferimento al tipo void nell'elenco.

elemento_id_campo

appare nella sezione field_ids

allineamento: 4 byte

Nome Formato Descrizione
classe_idx corto index nell'elenco type_ids per il definitore di questo campo. Deve essere un tipo di classe e non un tipo array o primitivo.
tipo_idx corto index nell'elenco type_ids per il tipo di questo campo
nome_idx uint index nell'elenco string_ids per il nome di questo campo. La stringa deve essere conforme alla sintassi per MemberName , definita sopra.

elemento_id_metodo

appare nella sezione method_ids

allineamento: 4 byte

Nome Formato Descrizione
classe_idx corto index nell'elenco type_ids per il definitore di questo metodo. Deve essere una classe o un tipo di array e non un tipo primitivo.
proto_idx corto index nell'elenco proto_ids per il prototipo di questo metodo
nome_idx uint index nell'elenco string_ids per il nome di questo metodo. La stringa deve essere conforme alla sintassi per MemberName , definita sopra.

class_def_item

appare nella sezione class_defs

allineamento: 4 byte

Nome Formato Descrizione
classe_idx uint index nell'elenco type_ids per questa classe. Deve essere un tipo di classe e non un tipo array o primitivo.
access_flags uint flag di accesso per la classe ( public , final , ecc.). Vedi " access_flags Definitions" per i dettagli.
superclass_idx uint index nell'elenco type_ids per la superclasse, o il valore costante NO_INDEX se questa classe non ha superclasse (cioè, è una classe radice come Object ). Se presente, deve essere un tipo di classe e non un tipo array o primitivo.
interfacce_off uint offset dall'inizio del file all'elenco delle interfacce o 0 se non ce ne sono. Questo offset dovrebbe essere nella sezione dei data e i dati dovrebbero essere nel formato specificato da " type_list " di seguito. Ciascuno degli elementi dell'elenco deve essere un tipo di classe (non un tipo array o primitivo) e non devono esserci duplicati.
sorgente_file_idx uint index nell'elenco string_ids per il nome del file contenente l'origine originale per (almeno la maggior parte di) questa classe, o il valore speciale NO_INDEX per rappresentare una mancanza di queste informazioni. Il debug_info_item di un dato metodo può sovrascrivere questo file di origine, ma ci si aspetta che la maggior parte delle classi provenga da un solo file di origine.
annotazioni_off uint offset dall'inizio del file alla struttura delle annotazioni per questa classe o 0 se non ci sono annotazioni su questa classe. Questo offset, se diverso da zero, dovrebbe essere nella sezione dei data e i dati dovrebbero essere nel formato specificato da " annotations_directory_item " di seguito, con tutti gli elementi che si riferiscono a questa classe come definer.
class_data_off uint offset dall'inizio del file ai dati di classe associati per questo elemento o 0 se non ci sono dati di classe per questa classe. (Questo può essere il caso, ad esempio, se questa classe è un'interfaccia marker.) L'offset, se diverso da zero, dovrebbe essere nella sezione data e i dati dovrebbero essere nel formato specificato da " class_data_item " di seguito, con tutti gli elementi che si riferiscono a questa classe come definer.
static_values_off uint offset dall'inizio del file all'elenco dei valori iniziali per i campi static o 0 se non ce ne sono (e tutti i campi static devono essere inizializzati con 0 o null ). Questo offset dovrebbe trovarsi nella sezione dei data e i dati dovrebbero essere nel formato specificato da " encoded_array_item " di seguito. La dimensione dell'array non deve essere maggiore del numero di campi static dichiarati da questa classe e gli elementi corrispondono ai campi static nello stesso ordine dichiarato nel corrispondente field_list . Il tipo di ogni elemento dell'array deve corrispondere al tipo dichiarato del campo corrispondente. Se nella matrice sono presenti meno elementi rispetto ai campi static , i campi rimanenti vengono inizializzati con uno 0 o null appropriato al tipo.

call_site_id_item

appare nella sezione call_site_ids

allineamento: 4 byte

Nome Formato Descrizione
call_site_off uint offset dall'inizio del file per chiamare la definizione del sito. L'offset dovrebbe essere nella sezione dei dati e i dati dovrebbero essere nel formato specificato da "call_site_item" di seguito.

call_site_item

appare nella sezione dati

allineamento: nessuno (byte allineato)

Il call_site_item è un encoded_array_item i cui elementi corrispondono agli argomenti forniti a un metodo del linker bootstrap. I primi tre argomenti sono:

  1. Un handle di metodo che rappresenta il metodo del linker bootstrap (VALUE_METHOD_HANDLE).
  2. Un nome di metodo che il linker bootstrap dovrebbe risolvere (VALUE_STRING).
  3. A method type corresponding to the type of the method name to be resolved (VALUE_METHOD_TYPE).

Any additional arguments are constant values passed to the bootstrap linker method. These arguments are passed in order and without any type conversions.

The method handle representing the bootstrap linker method must have return type java.lang.invoke.CallSite . The first three parameter types are:

  1. java.lang.invoke.Lookup
  2. java.lang.String
  3. java.lang.invoke.MethodType

The parameter types of any additional arguments are determined from their constant values.

method_handle_item

appears in the method_handles section

alignment: 4 bytes

Name Format Descrizione
method_handle_type ushort type of the method handle; see table below
unused ushort (unused)
field_or_method_id ushort Field or method id depending on whether the method handle type is an accessor or a method invoker
unused ushort (unused)

Method Handle Type Codes

Constant Value Descrizione
METHOD_HANDLE_TYPE_STATIC_PUT 0x00 Method handle is a static field setter (accessor)
METHOD_HANDLE_TYPE_STATIC_GET 0x01 Method handle is a static field getter (accessor)
METHOD_HANDLE_TYPE_INSTANCE_PUT 0x02 Method handle is an instance field setter (accessor)
METHOD_HANDLE_TYPE_INSTANCE_GET 0x03 Method handle is an instance field getter (accessor)
METHOD_HANDLE_TYPE_INVOKE_STATIC 0x04 Method handle is a static method invoker
METHOD_HANDLE_TYPE_INVOKE_INSTANCE 0x05 Method handle is an instance method invoker
METHOD_HANDLE_TYPE_INVOKE_CONSTRUCTOR 0x06 Method handle is a constructor method invoker
METHOD_HANDLE_TYPE_INVOKE_DIRECT 0x07 Method handle is a direct method invoker
METHOD_HANDLE_TYPE_INVOKE_INTERFACE 0x08 Method handle is an interface method invoker

class_data_item

referenced from class_def_item

appears in the data section

alignment: none (byte-aligned)

Name Format Descrizione
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 by field_idx in 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 by field_idx in increasing order.
direct_methods encoded_method[direct_methods_size] the defined direct (any of static , private , or constructor) methods, represented as a sequence of encoded elements. The methods must be sorted by method_idx in increasing order.
virtual_methods encoded_method[virtual_methods_size] the defined virtual (none of static , private , or constructor) methods, represented as a sequence of encoded elements. This list should not include inherited methods unless overridden by the class that this item represents. The methods must be sorted by method_idx in increasing order. The method_idx of a virtual method must not be the same as any direct method.

Note: All elements' field_id s and method_id s must refer to the same defining class.

encoded_field format

Name Format Descrizione
field_idx_diff uleb128 index into the field_ids list 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_flags Definitions" for details.

encoded_method format

Name Format Descrizione
method_idx_diff uleb128 index into the method_ids list 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_flags Definitions" for details.
code_off uleb128 offset from the start of the file to the code structure for this method, or 0 if this method is either abstract or native . The offset should be to a location in the data section. The format of the data is specified by " code_item " below.

type_list

referenced from class_def_item and proto_id_item

appears in the data section

alignment: 4 bytes

Name Format Descrizione
size uint size of the list, in entries
list type_item[size] elements of the list

type_item format

Name Format Descrizione
type_idx ushort index into the type_ids list

code_item

referenced from encoded_method

appears in the data section

alignment: 4 bytes

Name Format Descrizione
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 of try_item s for this instance. If non-zero, then these appear as the tries array just after the insns in 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, or 0 if there simply is no information. The offset, if non-zero, should be to a location in the data section. 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 an insns array is specified by the companion document Dalvik bytecode . Note that though this is defined as an array of ushort , there are some internal structures that prefer four-byte alignment. Also, if this happens to be in an endian-swapped file, then the swapping is only done on individual ushort s and not on the larger internal structures.
padding ushort (optional) = 0 two bytes of padding to make tries four-byte aligned. This element is only present if tries_size is non-zero and insns_size is odd.
tries try_item[tries_size] (optional) array indicating where in the code exceptions are 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 if tries_size is non-zero.
handlers encoded_catch_handler_list (optional) bytes representing a list of lists of catch types and associated handler addresses. Each try_item has a byte-wise offset into this structure. This element is only present if tries_size is non-zero.

try_item format

Name Format Descrizione
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) is start_addr + insn_count - 1 .
handler_off ushort offset in bytes from the start of the associated encoded_catch_hander_list to the encoded_catch_handler for this entry. This must be an offset to the start of an encoded_catch_handler .

encoded_catch_handler_list format

Name Format Descrizione
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_handler format

Name Format Descrizione
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: A size of 0 means that there is a catch-all but no explicitly typed catches. A size of 2 means that there are two explicitly typed catches and no catch-all. And a size of -1 means that there is one typed catch along with a catch-all.
handlers encoded_type_addr_pair[abs(size)] stream of abs(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 if size is non-positive.

encoded_type_addr_pair format

Name Format Descrizione
type_idx uleb128 index into the type_ids list for the type of the exception to catch
addr uleb128 bytecode address of the associated exception handler

debug_info_item

referenced from code_item

appears in the data section

alignment: none (byte-aligned)

Each debug_info_item defines a DWARF3-inspired byte-coded state machine that, when interpreted, emits the positions table and (potentially) the local variable information for a code_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 an DBG_END_SEQUENCE byte.

The state machine consists of five registers. The address register represents the instruction offset in the associated insns_item in 16-bit code units. The address register starts at 0 at the beginning of each debug_info sequence and must only monotonically increase. The line register 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 than 1 . The source_file register represents the source file that the line number entries refer to. It is initialized to the value of source_file_idx in class_def_item . The other two variables, prologue_end and epilogue_begin , are boolean flags (initialized to false ) 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 the DBG_RESTART_LOCAL code.

The header is as follows:

Name Format Descrizione
line_start uleb128 the initial value for the state machine's line register. 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's this , if any.
parameter_names uleb128p1[parameters_size] string index of the method parameter name. An encoded value of NO_INDEX indicates 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 Descrizione
DBG_END_SEQUENCE 0x00 (none) terminates a debug info sequence for a code_item
DBG_ADVANCE_PC 0x01 uleb128 addr_diff addr_diff : amount to add to address register advances the address register without emitting a positions entry
DBG_ADVANCE_LINE 0x02 sleb128 line_diff line_diff : amount to change line register by advances the line register without emitting a positions entry
DBG_START_LOCAL 0x03 uleb128 register_num
uleb128p1 name_idx
uleb128p1 type_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. Either name_idx or type_idx may be NO_INDEX to indicate that that value is unknown.
DBG_START_LOCAL_EXTENDED 0x04 uleb128 register_num
uleb128p1 name_idx
uleb128p1 type_idx
uleb128p1 sig_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 of name_idx , type_idx , or sig_idx may be NO_INDEX to indicate that that value is unknown. (If sig_idx is -1 , though, the same data could be represented more efficiently using the opcode DBG_START_LOCAL .)

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

DBG_END_LOCAL 0x05 uleb128 register_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 uleb128 register_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 the prologue_end state 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). The prologue_end register is cleared by any special ( >= 0x0a ) opcode.
DBG_SET_EPILOGUE_BEGIN 0x08 (none) sets the epilogue_begin state 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). The epilogue_begin register is cleared by any special ( >= 0x0a ) opcode.
DBG_SET_FILE 0x09 uleb128p1 name_idx name_idx : string index of source file name; NO_INDEX if unknown indicates that all subsequent line number entries make reference to this source file name, instead of the default name specified in code_item
Special Opcodes 0x0a…0xff (none) advances the line and address registers, emits a position entry, and clears prologue_end and epilogue_begin . See below for description.

Special opcodes

Opcodes with values between 0x0a and 0xff (inclusive) move both the line and address registers 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 from class_def_item

appears in the data section

alignment: 4 bytes

Name Format Descrizione
class_annotations_off uint offset from the start of the file to the annotations made directly on the class, or 0 if the class has no direct annotations. The offset, if non-zero, should be to a location in the data section. The format of the data is specified by " annotation_set_item " below.
fields_size uint count of fields annotated by this item
annotated_methods_size uint count of methods annotated by this item
annotated_parameters_size 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, by field_idx .
method_annotations method_annotation[methods_size] (optional) list of associated method annotations. The elements of the list must be sorted in increasing order, by method_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, by method_idx .

Note: All elements' field_id s and method_id s must refer to the same defining class.

field_annotation format

Name Format Descrizione
field_idx uint index into the field_ids list 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 the data section. The format of the data is specified by " annotation_set_item " below.

method_annotation format

Name Format Descrizione
method_idx uint index into the method_ids list 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 the data section. The format of the data is specified by " annotation_set_item " below.

parameter_annotation format

Name Format Descrizione
method_idx uint index into the method_ids list 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 the data section. The format of the data is specified by " annotation_set_ref_list " below.

annotation_set_ref_list

referenced from parameter_annotations_item

appears in the data section

alignment: 4 bytes

Name Format Descrizione
size uint size of the list, in entries
list annotation_set_ref_item[size] elements of the list

annotation_set_ref_item format

Name Format Descrizione
annotations_off uint offset from the start of the file to the referenced annotation set or 0 if there are no annotations for this element. The offset, if non-zero, should be to a location in the data section. The format of the data is specified by " annotation_set_item " below.

annotation_set_item

referenced from annotations_directory_item, field_annotations_item, method_annotations_item, and annotation_set_ref_item

appears in the data section

alignment: 4 bytes

Name Format Descrizione
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, by type_idx .

annotation_off_item format

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

annotation_item

referenced from annotation_set_item

appears in the data section

alignment: none (byte-aligned)

Name Format Descrizione
visibility ubyte intended visibility of this annotation (see below)
annotation encoded_annotation encoded annotation contents, in the format described by " encoded_annotation format" under " encoded_value encoding" above.

Visibility values

These are the options for the visibility field in an annotation_item :

Name Value Descrizione
VISIBILITY_BUILD 0x00 intended only to be visible at build time (eg, 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 from class_def_item

appears in the data section

alignment: none (byte-aligned)

Name Format Descrizione
value encoded_array bytes representing the encoded array value, in the format specified by " encoded_array Format" under " encoded_value Encoding" above.

hiddenapi_class_data_item

This section contains data on restricted interfaces used by each class.

Note: The hidden API feature was introduced in Android 10.0 and is only applicable to the DEX files of classes in the boot class path. The list of flags described below may be extended in the future releases of Android. For more information, see restrictions on non-SDK interfaces .

Name Format Descrizione
size uint total size of the section
offsets uint[] array of offsets indexed by class_idx . A zero array entry at index class_idx means that either there is no data for this class_idx , or all hidden API flags are zero. Otherwise the array entry is non-zero and contains an offset from the beginning of the section to an array of hidden API flags for this class_idx .
flags uleb128[] concatenated arrays of hidden API flags for each class. Possible flag values are described in the table below. Flags are encoded in the same order as fields and methods are encoded in class data.

Restriction flag types:

Name Value Descrizione
whitelist 0 Interfaces that can be freely used and are supported as part of the officially documented Android framework Package Index .
greylist 1 Non-SDK interfaces that can be used regardless of the application's target API level .
blacklist 2 Non-SDK interfaces that cannot be used regardless of the application's target API level . Accessing one of these interfaces causes a runtime error .
greylist‑max‑o 3 Non-SDK interfaces that can be used for Android 8.x and below unless they are restricted.
greylist‑max‑p 4 Non-SDK interfaces that can be used for Android 9.x unless they are restricted.
greylist‑max‑q 5 Non-SDK interfaces that can be used for Android 10.x unless they are restricted.
greylist‑max‑r 6 Non-SDK interfaces that can be used for Android 11.x unless they are restricted.

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 .dex files as annotations with visibility set to VISIBILITY_SYSTEM .

dalvik.annotation.AnnotationDefault

appears on methods in annotation interfaces

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

Name Format Descrizione
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

An EnclosingClass annotation 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 (eg, a synthetic inner class). Every class that has this annotation must also have an InnerClass annotation. Additionally, a class must not have both an EnclosingClass and an EnclosingMethod annotation.

Name Format Descrizione
value Class the class which most closely lexically scopes this class

dalvik.annotation.EnclosingMethod

appears on classes

An EnclosingMethod annotation is attached to each class which is defined inside a method body. Every class that has this annotation must also have an InnerClass annotation. Additionally, a class must not have both an EnclosingClass and an EnclosingMethod annotation.

Name Format Descrizione
value Method the method which most closely lexically scopes this class

dalvik.annotation.InnerClass

appears on classes

An InnerClass annotation 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 have either an EnclosingClass annotation or an EnclosingMethod annotation.

Name Format Descrizione
name String the originally declared simple name of this class (not including any package prefix). If this class is anonymous, then the name is null .
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

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

Name Format Descrizione
value Class[] array of the member classes

dalvik.annotation.MethodParameters

appears on methods

Note: This annotation was added after Android 7.1. Its presence on earlier Android releases will be ignored.

A MethodParameters annotation is optional and can be used to provide parameter metadata such as parameter names and modifiers.

The annotation can be omitted from a method or constructor safely when the parameter metadata is not required at runtime. java.lang.reflect.Parameter.isNamePresent() can be used to check whether metadata is present for a parameter, and the associated reflection methods such as java.lang.reflect.Parameter.getName() will fall back to default behavior at runtime if the information is not present.

When including parameter metadata, compilers must include information for generated classes such as enums, since the parameter metadata includes whether or not a parameter is synthetic or mandated.

A MethodParameters annotation describes only individual method parameters. Therefore, compilers may omit the annotation entirely for constructors and methods that have no parameters, for the sake of code-size and runtime efficiency.

The arrays documented below must be the same size as for the method_id_item dex structure associated with the method, otherwise a java.lang.reflect.MalformedParametersException will be thrown at runtime.

That is: method_id_item.proto_idx -> proto_id_item.parameters_off -> type_list.size must be the same as names().length and accessFlags().length .

Because MethodParameters describes all formal method parameters, even those not explicitly or implicitly declared in source code, the size of the arrays may differ from the Signature or other metadata information that is based only on explicit parameters declared in source code. MethodParameters will also not include any information about type annotation receiver parameters that do not exist in the actual method signature.

Name Format Descrizione
names String[] The names of formal parameters for the associated method. The array must not be null but must be empty if there are no formal parameters. A value in the array must be null if the formal parameter with that index has no name.
If parameter name strings are empty or contain '.', ';', '[' or '/' then a java.lang.reflect.MalformedParametersException will be thrown at runtime.
accessFlags int[] The access flags of the formal parameters for the associated method. The array must not be null but must be empty if there are no formal parameters.
The value is a bit mask with the following values:
  • 0x0010 : final, the parameter was declared final
  • 0x1000 : synthetic, the parameter was introduced by the compiler
  • 0x8000 : mandated, the parameter is synthetic but also implied by the language specification
If any bits are set outside of this set then a java.lang.reflect.MalformedParametersException will be thrown at runtime.

dalvik.annotation.Signature

appears on classes, fields, and methods

A Signature annotation is attached to each class, field, or method which is defined in terms of a more complicated type than is representable by a type_id_item . The .dex format 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, a Signature annotation is defined as an array of 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 .dex files.

Name Format Descrizione
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

A Throws annotation is attached to each method which is declared to throw one or more exception types.

Name Format Descrizione
value Class[] the array of exception types thrown