В этом документе описывается структура и содержимое файлов .dex
, которые используются для хранения набора определений классов и связанных с ними дополнительных данных.
Руководство по типам
Имя | Описание |
---|---|
байт | 8-битное целое число со знаком |
убайт | 8-битное беззнаковое целое число |
короткий | 16-битное целое число со знаком, прямой порядок байтов |
сокращать | 16-битное беззнаковое целое число с прямым порядком байтов |
интервал | 32-битное целое число со знаком, прямой порядок байтов |
uint | 32-битное целое число без знака, с прямым порядком байтов |
длинный | 64-битное целое число со знаком, прямой порядок байтов |
улонг | 64-битное целое число без знака, с прямым порядком байтов |
слеб128 | подписан LEB128, переменной длины (см. ниже) |
улеб128 | беззнаковый LEB128, переменная длина (см. ниже) |
улеб128п1 | беззнаковый LEB128 плюс 1 переменной длины (см. ниже) |
ЛЕБ128
LEB128 (« Little -Endian Base 128 ») — это кодировка переменной длины для произвольных целых чисел со знаком или без знака. Формат был заимствован из спецификации DWARF3 . В файле .dex
LEB128 используется только для кодирования 32-битных величин.
Каждое значение, закодированное LEB128, состоит из одного-пяти байтов, которые вместе представляют одно 32-битное значение. Для каждого байта установлен самый старший бит, за исключением последнего байта последовательности, у которого самый старший бит очищен. Остальные семь бит каждого байта представляют собой полезную нагрузку, при этом младшие семь битов количества находятся в первом байте, следующие семь — во втором байте и так далее. В случае LEB128 со знаком ( sleb128
) старший бит полезной нагрузки последнего байта последовательности расширяется по знаку для получения конечного значения. В беззнаковом случае ( uleb128
) любые биты, не представленные явно, интерпретируются как 0
.
Побитовая диаграмма двухбайтового значения LEB128 | |||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Первый байт | Второй байт | ||||||||||||||
1 | бит 6 | бит 5 | бит 4 | бит 3 | бит 2 | бит 1 | бит 0 | 0 | бит 13 | бит 12 | бит 11 | бит 10 | бит 9 | бит 8 | бит 7 |
Вариант uleb128p1
используется для представления значения со знаком, где представление представляет собой значение плюс одно, закодированное как uleb128
. Это делает кодирование -1
(альтернативно называемого беззнаковым значением 0xffffffff
) - но не другого отрицательного числа - одним байтом и полезно именно в тех случаях, когда представленное число должно быть либо неотрицательным, либо -1
(или 0xffffffff
), и когда никакие другие отрицательные значения не допускаются (или когда большие беззнаковые значения вряд ли потребуются).
Вот несколько примеров форматов:
Закодированная последовательность | Как sleb128 | Как uleb128 | Как uleb128p1 |
---|---|---|---|
00 | 0 | 0 | -1 |
01 | 1 | 1 | 0 |
7ф | -1 | 127 | 126 |
80 7ф | -128 | 16256 | 16255 |
Макет файла
Имя | Формат | Описание |
---|---|---|
заголовок | заголовок_элемент | заголовок |
string_ids | string_id_item[] | список строковых идентификаторов. Это идентификаторы всех строк, используемых в этом файле, либо для внутреннего именования (например, дескрипторы типов), либо как постоянные объекты, на которые ссылается код. Этот список должен быть отсортирован по содержимому строки с использованием значений кодовых точек UTF-16 (не с учетом локали) и не должен содержать повторяющихся записей. |
type_ids | type_id_item[] | список идентификаторов типов. Это идентификаторы всех типов (классов, массивов или примитивных типов), на которые ссылается этот файл, независимо от того, определены они в файле или нет. Этот список должен быть отсортирован по индексу string_id и не должен содержать повторяющихся записей. |
proto_ids | proto_id_item[] | список идентификаторов прототипов методов. Это идентификаторы всех прототипов, на которые ссылается этот файл. Этот список должен быть отсортирован в основном порядке возвращаемого типа (по индексу type_id ), а затем по списку аргументов (лексикографический порядок, отдельные аргументы упорядочены по индексу type_id ). Список не должен содержать повторяющихся записей. |
field_ids | field_id_item[] | список идентификаторов полей. Это идентификаторы всех полей, на которые ссылается этот файл, независимо от того, определены они в файле или нет. Этот список должен быть отсортирован, где определяющий тип (по индексу type_id ) — это основной порядок, имя поля (по индексу string_id ) — это промежуточный порядок, а тип (по индексу type_id ) — это второстепенный порядок. Список не должен содержать повторяющихся записей. |
идентификаторы метода | метод_id_item[] | список идентификаторов методов. Это идентификаторы всех методов, на которые ссылается этот файл, независимо от того, определены они в файле или нет. Этот список должен быть отсортирован, где определяющий тип (по индексу type_id ) — это основной порядок, имя метода (по индексу string_id ) — это промежуточный порядок, а прототип метода (по индексу proto_id ) — это второстепенный порядок. Список не должен содержать повторяющихся записей. |
class_defs | class_def_item[] | список определений классов. Классы должны быть упорядочены таким образом, чтобы суперкласс данного класса и реализованные интерфейсы появлялись в списке раньше, чем ссылающийся класс. Более того, определение одного и того же класса недопустимо появляться в списке более одного раза. |
call_site_ids | call_site_id_item[] | список идентификаторов сайтов вызовов. Это идентификаторы всех сайтов вызова, на которые ссылается этот файл, независимо от того, определены они в файле или нет. Этот список должен быть отсортирован в порядке возрастания call_site_off . |
метод_handles | метод_handle_item[] | метод обрабатывает список. Список всех дескрипторов методов, на которые ссылается этот файл, независимо от того, определены они в файле или нет. Этот список не отсортирован и может содержать дубликаты, которые логически соответствуют различным экземплярам дескриптора метода. |
данные | убайт[] | область данных, содержащая все вспомогательные данные для таблиц, перечисленных выше. Разные элементы имеют разные требования к выравниванию, и байты заполнения вставляются перед каждым элементом, если это необходимо для достижения правильного выравнивания. |
ссылка_данные | убайт[] | данные, используемые в статически связанных файлах. Формат данных в этом разделе в этом документе не указан. Этот раздел пуст в несвязанных файлах, и реализации среды выполнения могут использовать его по своему усмотрению. |
Формат контейнера
Версия 41 представляет новый формат контейнера для данных DEX с целью экономии места. Этот формат контейнера позволяет объединить несколько логических файлов DEX в один физический файл. Новый формат по большей части представляет собой простое объединение файлов предыдущего формата с некоторыми отличиями:
-
file_size
— это размер логического файла, а не физического файла. Его можно использовать для перебора всех логических файлов в контейнере. - Логические файлы dex могут ссылаться на любые более поздние данные в контейнере (но не более ранние). Это позволяет файлам dex обмениваться данными, например строками, между собой.
- Все смещения указаны относительно физического файла. Никакого смещения относительно заголовка нет. Это гарантирует, что разделы со смещениями могут быть разделены между логическими файлами.
- В заголовок добавляются два новых поля для описания границ контейнера. Это дополнительная проверка согласованности, которая упрощает перенос кода в новый формат.
-
data_size
иdata_off
теперь не используются. Данные могут быть распределены по нескольким логическим файлам и не обязательно должны быть смежными.
Определения битовых полей, строк и констант
DEX_FILE_MAGIC
Встроено в header_item
Константный массив/строка DEX_FILE_MAGIC
представляет собой список байтов, которые должны появиться в начале файла .dex
, чтобы он был распознан как таковой. Значение намеренно содержит новую строку ( "\n"
или 0x0a
) и нулевой байт ( "\0"
или 0x00
), чтобы помочь в обнаружении определенных форм повреждения. Это значение также кодирует номер версии формата в виде трех десятичных цифр, который, как ожидается, будет монотонно увеличиваться с течением времени по мере развития формата.
ubyte[8] DEX_FILE_MAGIC = { 0x64 0x65 0x78 0x0a 0x30 0x33 0x39 0x00 } = "dex\n039\0"
Примечание. Поддержка версии 040
формата была добавлена в выпуске Android 10.0, что расширило набор разрешенных символов в SimpleNames .
Примечание. Поддержка версии 039
формата была добавлена в выпуске Android 9.0, в котором были представлены два новых байт-кода: const-method-handle
и const-method-type
. (Каждый из них описан в сводной таблице набора байт-кодов .) В Android 10 версия 039
расширяет формат файла DEX, включив в него скрытую информацию API, которая применима только к файлам DEX в пути к классу загрузки.
Примечание. Поддержка версии 038
формата была добавлена в версии Android 8.0. В версии 038
добавлены новые байт-коды ( invoke-polymorphic
и invoke-custom
) и данные для дескрипторов методов.
Примечание. Поддержка версии 037
формата была добавлена в версии Android 7.0. До версии 037
в большинстве версий Android использовалась версия формата 035
. Единственная разница между версиями 035
и 037
— это добавление методов по умолчанию и настройка метода invoke
.
Примечание. По крайней мере, несколько более ранних версий этого формата использовались в широко доступных общедоступных выпусках программного обеспечения. Например, версия 009
использовалась для выпусков M3 платформы Android (ноябрь – декабрь 2007 г.), а версия 013
использовалась для выпусков M5 платформы Android (февраль – март 2008 г.). В некоторых отношениях эти более ранние версии формата существенно отличаются от версии, описанной в этом документе.
ENDIAN_CONSTANT и REVERSE_ENDIAN_CONSTANT
Встроено в header_item
Константа ENDIAN_CONSTANT
используется для указания порядка байтов файла, в котором она находится. Хотя стандартный формат .dex
имеет прямой порядок байтов, реализации могут выполнять замену байтов. Если реализация встретит заголовок, у которого endian_tag
имеет значение REVERSE_ENDIAN_CONSTANT
вместо ENDIAN_CONSTANT
, она будет знать, что файл был заменен байтами из ожидаемой формы.
uint ENDIAN_CONSTANT = 0x12345678; uint REVERSE_ENDIAN_CONSTANT = 0x78563412;
NO_INDEX
Встроен в class_def_item и debug_info_item.
Константа NO_INDEX
используется для указания отсутствия значения индекса.
Примечание. Это значение не равно 0
, поскольку обычно это действительный индекс.
Выбранное значение NO_INDEX
можно представить в виде одного байта в кодировке uleb128p1
.
uint NO_INDEX = 0xffffffff; // == -1 if treated as a signed int
определения access_flags
Встроен в class_def_item, encoded_field, encoded_method и InnerClass.
Битовые поля этих флагов используются для указания доступности и общих свойств классов и членов классов.
Имя | Ценить | Для классов (и аннотаций InnerClass ) | Для полей | Для методов |
---|---|---|---|---|
ACC_PUBLIC | 0x1 | public : виден везде | public : виден везде | public : виден везде |
ACC_PRIVATE | 0x2 | private : виден только определяющему классу | private : виден только определяющему классу | private : виден только определяющему классу |
ACC_PROTECTED | 0x4 | protected : виден пакету и подклассам | protected : виден пакету и подклассам | protected : виден пакету и подклассам |
АКК_СТАТИК | 0x8 | static : не создается с использованием внешней ссылки this | static : глобально для определения класса | static : не принимает this аргумент |
ACC_FINAL | 0x10 | final : не подклассифицируется | final : неизменяемый после создания | final : не переопределяемый |
АКК_СИНХРОНИЗИРОВАННЫЙ | 0x20 | synchronized : связанная блокировка автоматически устанавливается при вызове этого метода. Примечание. Эту настройку можно устанавливать только в том случае, если также установлен | ||
ACC_VOLATILE | 0x40 | volatile : специальные правила доступа, помогающие обеспечить потокобезопасность. | ||
АКК_БРИДЖЕ | 0x40 | метод моста, автоматически добавляемый компилятором как типобезопасный мост | ||
ACC_TRANSIENT | 0x80 | transient : не сохраняться при сериализации по умолчанию | ||
ACC_VARARGS | 0x80 | последний аргумент должен рассматриваться компилятором как «остальный» аргумент | ||
ACC_NATIVE | 0x100 | native : реализован в собственном коде | ||
АКК_ИНТЕРФЕЙС | 0x200 | interface : многократно реализуемый абстрактный класс | ||
ACC_ABSTRACT | 0x400 | abstract : невозможно создать экземпляр напрямую | abstract : не реализовано в этом классе | |
ACC_STRICT | 0x800 | strictfp : строгие правила для арифметики с плавающей запятой. | ||
АКК_СИНТЕТИЧЕСКИЙ | 0x1000 | не определено напрямую в исходном коде | не определено напрямую в исходном коде | не определено напрямую в исходном коде |
АКК_АННОТАЦИЯ | 0x2000 | объявлен как класс аннотации | ||
АКК_ЕНУМ | 0x4000 | объявлен как перечислимый тип | объявлен как перечислимое значение | |
(не используется) | 0x8000 | |||
АКК_КОНСТРУКТОР | 0x10000 | метод конструктора (инициализатор класса или экземпляра) | ||
ACC_DECLARED_ СИНХРОНИЗИРОВАНО | 0x20000 | объявлен synchronized .Примечание. Это не влияет на выполнение (кроме отражения этого флага как такового). |
InnerClass
и никогда не должно быть включено в class_def_item
.
Модифицированная кодировка UTF-8.
В качестве уступки для упрощения устаревшей поддержки формат .dex
кодирует строковые данные в стандартную модифицированную форму UTF-8, именуемую в дальнейшем MUTF-8. Эта форма идентична стандартной UTF-8, за исключением:
- Используются только одно-, двух- и трехбайтовые кодировки.
- Кодовые точки в диапазоне
U+10000
…U+10ffff
кодируются как суррогатная пара, каждая из которых представлена как трехбайтовое закодированное значение. - Кодовая точка
U+0000
кодируется в двухбайтовой форме. - Простой нулевой байт (значение
0
) указывает на конец строки, как это принято в стандартной интерпретации языка C.
Первые два пункта выше можно резюмировать следующим образом: MUTF-8 — это формат кодировки UTF-16, а не более прямой формат кодирования символов Unicode.
Последние два пункта выше позволяют одновременно включать кодовую точку U+0000
в строку и при этом манипулировать ею как строкой с нулевым завершением в стиле C.
Однако специальная кодировка U+0000
означает, что, в отличие от обычной UTF-8, результат вызова стандартной функции C strcmp()
для пары строк MUTF-8 не всегда указывает на правильно подписанный результат сравнения неравных строк. Когда порядок (а не только равенство) является проблемой, самый простой способ сравнить строки MUTF-8 — это декодировать их посимвольно и сравнить декодированные значения. (Однако возможны и более умные реализации.)
Дополнительную информацию о кодировке символов см. в стандарте Unicode . MUTF-8 на самом деле ближе к (относительно менее известной) кодировке CESU-8, чем к UTF-8 как таковой.
кодировка encoded_value
Встроен в annotation_element и encoded_array_item.
encoded_value
— это закодированный фрагмент (почти) произвольных иерархически структурированных данных. Кодировка должна быть компактной и простой для анализа.
Имя | Формат | Описание |
---|---|---|
(значение_аргумент << 5) | тип_значения | убайт | байт, указывающий тип следующего за ним value вместе с необязательным уточняющим аргументом в трех старших битах. Ниже приведены различные определения value . В большинстве случаев value_arg кодирует длину следующего value в байтах, как (size - 1) , например, 0 означает, что для значения требуется один байт, а 7 означает, что требуется восемь байтов; однако есть исключения, как указано ниже. |
ценить | убайт[] | байты, представляющие значение, переменные по длине и интерпретируемые по-разному для разных байтов value_type , хотя всегда с прямым порядком байтов. Подробности см. в различных определениях значений ниже. |
Форматы значений
Тип Имя | value_type | Формат value_arg | Формат value | Описание |
---|---|---|---|---|
VALUE_BYTE | 0x00 | (нет; должно быть 0 ) | убайт[1] | однобайтовое целое число со знаком |
VALUE_SHORT | 0x02 | размер - 1 (0…1) | убайт [размер] | двухбайтовое целочисленное значение со знаком, расширенное знаком |
VALUE_CHAR | 0x03 | размер - 1 (0…1) | убайт [размер] | беззнаковое двухбайтовое целое число, расширяемое нулем |
VALUE_INT | 0x04 | размер - 1 (0…3) | убайт [размер] | четырехбайтовое целое число со знаком, расширенное знаком |
VALUE_LONG | 0x06 | размер - 1 (0…7) | убайт [размер] | восьмибайтовое целое число со знаком, расширенное знаком |
VALUE_FLOAT | 0x10 | размер - 1 (0…3) | убайт [размер] | четырехбайтовый битовый шаблон, расширенный до нуля вправо и интерпретируемый как 32-битное значение с плавающей запятой IEEE754. |
VALUE_DOUBLE | 0x11 | размер - 1 (0…7) | убайт [размер] | восьмибайтовый битовый шаблон, расширенный до нуля вправо и интерпретируемый как 64-битное значение с плавающей запятой IEEE754. |
VALUE_METHOD_TYPE | 0x15 | размер - 1 (0…3) | убайт [размер] | беззнаковое (расширенное нулем) четырехбайтовое целочисленное значение, интерпретируемое как индекс в разделе proto_ids и представляющее значение типа метода. |
VALUE_METHOD_HANDLE | 0x16 | размер - 1 (0…3) | убайт [размер] | беззнаковое (расширенное нулем) четырехбайтовое целочисленное значение, интерпретируемое как индекс в разделе method_handles и представляющее значение дескриптора метода |
VALUE_STRING | 0x17 | размер - 1 (0…3) | убайт [размер] | беззнаковое (расширенное нулем) четырехбайтовое целочисленное значение, интерпретируемое как индекс в разделе string_ids и представляющее строковое значение. |
VALUE_TYPE | 0x18 | размер - 1 (0…3) | убайт [размер] | беззнаковое (расширенное нулем) четырехбайтовое целочисленное значение, интерпретируемое как индекс в разделе type_ids и представляющее отражающее значение типа/класса. |
VALUE_FIELD | 0x19 | размер - 1 (0…3) | убайт [размер] | беззнаковое (расширенное нулем) четырехбайтовое целое значение, интерпретируемое как индекс в разделе field_ids и представляющее отражающее значение поля. |
VALUE_METHOD | 0x1а | размер - 1 (0…3) | убайт [размер] | беззнаковое (расширенное нулем) четырехбайтовое целочисленное значение, интерпретируемое как индекс в разделе method_ids и представляющее отражающее значение метода. |
VALUE_ENUM | 0x1b | размер - 1 (0…3) | убайт [размер] | беззнаковое (расширенное нулем) четырехбайтовое целое значение, интерпретируемое как индекс в разделе field_ids и представляющее значение константы перечисляемого типа. |
VALUE_ARRAY | 0x1c | (нет; должно быть 0 ) | закодированный_массив | массив значений в формате, указанном в «формате encoded_array » ниже. Размер value неявно заложен в кодировке. |
VALUE_ANNOTATION | 0x1d | (нет; должно быть 0 ) | закодированная_аннотация | дополнительная аннотация в формате, указанном в «формате encoded_annotation » ниже. Размер value неявно заложен в кодировке. |
VALUE_NULL | 0x1е | (нет; должно быть 0 ) | (никто) | null опорное значение |
VALUE_BOOLEAN | 0x1f | логическое значение (0…1) | (никто) | однобитовое значение; 0 для false и 1 для true . Бит представлен в value_arg . |
формат закодированного_массива
Имя | Формат | Описание |
---|---|---|
размер | улеб128 | количество элементов в массиве |
ценности | закодированное_значение[размер] | серия последовательностей байтов size encoded_value в формате, указанном в этом разделе, объединенных последовательно. |
формат закодированной_аннотации
Имя | Формат | Описание |
---|---|---|
type_idx | улеб128 | тип аннотации. Это должен быть тип класса (а не массива или примитива). |
размер | улеб128 | количество сопоставлений имени и значения в этой аннотации |
элементы | annotation_element[размер] | элементы аннотации, представленные непосредственно в строке (а не в виде смещений). Элементы должны быть отсортированы в порядке возрастания индекса string_id . |
формат annotation_element
Имя | Формат | Описание |
---|---|---|
name_idx | улеб128 | имя элемента, представленное как индекс в разделе string_ids . Строка должна соответствовать синтаксису MemberName , определенному выше. |
ценить | закодированное_значение | значение элемента |
Строковый синтаксис
В файле .dex
есть несколько типов элементов, которые в конечном итоге относятся к строке. Следующие определения в стиле BNF указывают приемлемый синтаксис для этих строк.
Простое имя
SimpleName является основой синтаксиса имен других вещей. Формат .dex
предоставляет здесь достаточную свободу действий (намного большую, чем большинство распространенных исходных языков). Короче говоря, простое имя состоит из любого буквенного символа или цифры младшего ASCII, нескольких конкретных символов младшего ASCII и большинства кодовых точек, отличных от ASCII, которые не являются управляющими, пробелами или специальными символами. Начиная с версии 040
формат дополнительно допускает пробелы (категория Unicode Zs
). Обратите внимание, что суррогатные кодовые точки (в диапазоне U+d800
… U+dfff
) сами по себе не считаются допустимыми символами имени, но допустимы дополнительные символы Юникода (которые представлены последней альтернативой правила для SimpleNameChar ), и они должны быть представлены в файле как пары суррогатных кодовых точек в кодировке MUTF-8.
ПростоеИмя → | ||
SimpleNameChar ( SimpleNameChar )* | ||
ПростоеИмяСимвол → | ||
'A' … 'Z' | ||
| | 'a' … 'z' | |
| | '0' … '9' | |
| | ' ' | начиная с версии DEX 040 |
| | '$' | |
| | '-' | |
| | '_' | |
| | U+00a0 | начиная с версии DEX 040 |
| | U+00a1 … U+1fff | |
| | U+2000 … U+200a | начиная с версии DEX 040 |
| | U+2010 … U+2027 | |
| | U+202f | начиная с версии DEX 040 |
| | U+2030 … U+d7ff | |
| | U+e000 … U+ffef | |
| | U+10000 … U+10ffff |
Имя участника
используется field_id_item и Method_id_item
MemberName — это имя члена класса, членами которого являются поля, методы и внутренние классы.
Имя участника → | |
Простое имя | |
| | '<' ПростоеИмя '>' |
ПолноеИмяКласса
FullClassName — это полное имя класса, включающее необязательный спецификатор пакета, за которым следует обязательное имя.
ПолноеИмяКласса → | |
Необязательный префикс пакета SimpleName | |
Необязательный префикс пакета → | |
( ПростоеИмя '/' )* |
Типдескриптор
Используется type_id_item
TypeDescriptor — это представление любого типа, включая примитивы, классы, массивы и void
. Ниже описано значение различных версий.
Дескриптор типа → | |
'V' | |
| | Полетипдескриптор |
ПолеТипДескриптор → | |
NonArrayFieldTypeDescriptor | |
| | ( '[' * 1…255) NonArrayFieldTypeDescriptor |
Дескриптор NonArrayFieldTypeDescriptor → | |
'Z' | |
| | 'B' |
| | 'S' |
| | 'C' |
| | 'I' |
| | 'J' |
| | 'F' |
| | 'D' |
| | 'L' Имя полного класса ';' |
КоротышкаДескриптор
Используется proto_id_item
ShortyDescriptor — это краткое представление прототипа метода, включая типы возвращаемых значений и параметров, за исключением того, что нет различия между различными типами ссылок (класс или массив). Вместо этого все ссылочные типы представлены одним символом 'L'
.
КороткийДескриптор → | |
ShortyReturnType ( ShortyFieldType )* | |
Тип возврата → | |
'V' | |
| | Коротыфилдтипе |
КороткийФилдТип → | |
'Z' | |
| | 'B' |
| | 'S' |
| | 'C' |
| | 'I' |
| | 'J' |
| | 'F' |
| | 'D' |
| | 'L' |
Семантика дескриптора типа
В этом смысл каждого из вариантов TypeDescriptor .
Синтаксис | Значение |
---|---|
В | void ; действительно только для возвращаемых типов |
З | boolean |
Б | byte |
С | short |
С | char |
я | int |
Дж | long |
Ф | float |
Д | double |
L полностью/квалифицированный/имя ; | класс fully.qualified.Name |
[ дескриптор | массив descriptor , который можно использовать рекурсивно для массивов массивов, хотя недопустимо иметь более 255 измерений. |
Предметы и связанные структуры
В этом разделе приведены определения для каждого элемента верхнего уровня, который может присутствовать в файле .dex
.
заголовок_элемент
Появляется в разделе заголовка
Выравнивание: 4 байта
Имя | Формат | Описание |
---|---|---|
магия | убайт[8] = DEX_FILE_MAGIC | магическое значение. Более подробную информацию смотрите в обсуждении выше в разделе « DEX_FILE_MAGIC ». |
контрольная сумма | uint | adler32 контрольная сумма остальной части файла (все, кроме magic и этого поля); используется для обнаружения повреждения файлов |
подпись | убайт [20] | Подпись SHA-1 (хеш) остальной части файла (все, кроме magic , checksum и этого поля); используется для уникальной идентификации файлов |
размер_файла | uint | размер всего файла (включая заголовок) в байтах (v40 или более ранняя версия) расстояние в байтах от начала этого заголовка до следующего заголовка или до конца всего файла (контейнера). (v41 или новее) |
размер_заголовка | uint | размер заголовка (весь этот раздел) в байтах. Это обеспечивает, по крайней мере, ограниченную обратную/прямую совместимость, не делая формат недействительным. должен быть 0x70 (112) байт (v40 или более ранняя версия) должен быть 0x78 (120) байт (v41 или новее) |
endian_tag | uint = ENDIAN_CONSTANT | тег порядка байтов. Дополнительные сведения см. выше в разделе « ENDIAN_CONSTANT и REVERSE_ENDIAN_CONSTANT ». |
link_size | uint | размер раздела ссылки или 0 , если этот файл не связан статически |
ссылка_off | uint | смещение от начала файла до раздела ссылки или 0 , если link_size == 0 . Смещение, если оно не равно нулю, должно соответствовать смещению в разделе link_data . Формат указанных данных в этом документе не указан; это поле заголовка (и предыдущее) остается в качестве перехватчиков для использования реализациями во время выполнения. |
map_off | uint | смещение от начала файла до элемента карты. Смещение, которое должно быть ненулевым, должно соответствовать смещению в разделе data , а данные должны быть в формате, указанном в « map_list » ниже. |
string_ids_size | uint | количество строк в списке идентификаторов строк |
string_ids_off | uint | смещение от начала файла до списка идентификаторов строк или 0 , если string_ids_size == 0 (правда, странный крайний случай). Смещение, если оно не равно нулю, должно быть в начале раздела string_ids . |
type_ids_size | uint | количество элементов в списке идентификаторов типов, не более 65535 |
type_ids_off | uint | смещение от начала файла до списка идентификаторов типов или 0 , если type_ids_size == 0 (правда, странный крайний случай). Смещение, если оно не равно нулю, должно быть в начале раздела type_ids . |
proto_ids_size | uint | количество элементов в списке идентификаторов прототипа, не более 65535 |
proto_ids_off | uint | смещение от начала файла до списка идентификаторов прототипа или 0 , если proto_ids_size == 0 (правда, странный крайний случай). Смещение, если оно не равно нулю, должно быть в начале раздела proto_ids . |
field_ids_size | uint | количество элементов в списке идентификаторов полей |
field_ids_off | uint | смещение от начала файла до списка идентификаторов полей или 0 , если field_ids_size == 0 . Смещение, если оно не равно нулю, должно быть в начале раздела field_ids . |
метод_ids_size | uint | количество элементов в списке идентификаторов метода |
метод_ids_off | uint | смещение от начала файла до списка идентификаторов методов или 0 , если method_ids_size == 0 . Смещение, если оно не равно нулю, должно быть в начале раздела method_ids . |
class_defs_size | uint | количество элементов в списке определений классов |
class_defs_off | uint | смещение от начала файла до списка определений классов или 0 , если class_defs_size == 0 (правда, странный крайний случай). Смещение, если оно не равно нулю, должно быть в начале раздела class_defs . |
размер_данных | uint | Размер раздела Не используется (v41 или новее) |
data_off | uint | смещение от начала файла до начала раздела Не используется (v41 или новее) |
размер_контейнера | uint | этого поля не существует. Можно предположить, что он равен размер всего файла (включая другие заголовки dex и их данные). (v41 или новее) |
header_offset | uint | этого поля не существует. Его можно принять равным смещение от начала файла до начала этого заголовка. (v41 или новее) |
список_карт
Появляется в разделе данных
Ссылка из header_item
Выравнивание: 4 байта
Это список всего содержимого файла по порядку. Он содержит некоторую избыточность по отношению к header_item
, но задуман как простая форма для перебора всего файла. Данный тип должен появляться на карте не более одного раза, но нет никаких ограничений на то, в каком порядке могут появляться типы, кроме ограничений, подразумеваемых остальной частью формата (например, сначала должен появиться раздел header
, затем раздел string_ids
и т. д.). Кроме того, записи карты должны быть упорядочены по начальному смещению и не должны перекрываться.
Имя | Формат | Описание |
---|---|---|
размер | uint | размер списка, в записях |
список | карта_элемент[размер] | элементы списка |
формат карты_элемента
Имя | Формат | Описание |
---|---|---|
тип | сокращать | тип предметов; см. таблицу ниже |
неиспользованный | сокращать | (не используется) |
размер | uint | количество элементов, которые можно найти по указанному смещению |
компенсировать | uint | смещение от начала файла до рассматриваемых элементов |
Типовые коды
Тип элемента | Постоянный | Ценить | Размер элемента в байтах |
---|---|---|---|
заголовок_элемент | 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 |
метод_id_item | 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 |
метод_handle_item | TYPE_METHOD_HANDLE_ITEM | 0x0008 | 0x08 |
список_карт | TYPE_MAP_LIST | 0x1000 | 4 + (размер элемента * 12) |
список_типов | TYPE_TYPE_LIST | 0x1001 | 4 + (размер элемента * 2) |
annotation_set_ref_list | TYPE_ANNOTATION_SET_REF_LIST | 0x1002 | 4 + (размер элемента * 4) |
annotation_set_item | TYPE_ANNOTATION_SET_ITEM | 0x1003 | 4 + (размер элемента * 4) |
class_data_item | TYPE_CLASS_DATA_ITEM | 0x2000 | скрытый; должен разобрать |
code_item | TYPE_CODE_ITEM | 0x2001 | скрытый; должен разобрать |
string_data_item | TYPE_STRING_DATA_ITEM | 0x2002 | скрытый; должен разобрать |
debug_info_item | TYPE_DEBUG_INFO_ITEM | 0x2003 | скрытый; должен разобрать |
аннотация_элемент | TYPE_ANNOTATION_ITEM | 0x2004 | скрытый; должен разобрать |
encoded_array_item | TYPE_ENCODED_ARRAY_ITEM | 0x2005 | скрытый; должен разобрать |
annotations_directory_item | TYPE_ANNOTATIONS_DIRECTORY_ITEM | 0x2006 | скрытый; должен разобрать |
скрытыйapi_class_data_item | TYPE_HIDDENAPI_CLASS_DATA_ITEM | 0xF000 | скрытый; должен разобрать |
string_id_item
Появляется в разделе string_ids.
Выравнивание: 4 байта
Имя | Формат | Описание |
---|---|---|
string_data_off | uint | смещение от начала файла до строковых данных для этого элемента. Смещение должно быть в разделе data , а данные должны быть в формате, указанном в параметре « string_data_item » ниже. Для смещения не существует требований по выравниванию. |
string_data_item
Появляется в разделе данных
Выравнивание: нет (выровнено по байтам)
Имя | Формат | Описание |
---|---|---|
utf16_size | улеб128 | размер этой строки в кодовых единицах UTF-16 (во многих системах это «длина строки»). То есть это декодированная длина строки. (Закодированная длина определяется позицией 0 байта.) |
данные | убайт[] | серия кодовых единиц MUTF-8 (также известных как октеты или байты), за которыми следует байт со значением 0 . Подробную информацию и обсуждение формата данных см. выше в разделе «Кодировка MUTF-8 (модифицированная UTF-8)». Примечание. Допустимо иметь строку, которая включает (в закодированной форме) суррогатные кодовые единицы UTF-16 (то есть |
type_id_item
Появляется в разделе type_ids
Выравнивание: 4 байта
Имя | Формат | Описание |
---|---|---|
дескриптор_idx | uint | индекс в списке string_ids для строки дескриптора этого типа. Строка должна соответствовать синтаксису TypeDescriptor , определенному выше. |
proto_id_item
Появляется в разделе proto_ids
Выравнивание: 4 байта
Имя | Формат | Описание |
---|---|---|
коротышка_idx | uint | индекс в списке string_ids для строки краткого дескриптора этого прототипа. Строка должна соответствовать синтаксису ShortyDescriptor , определенному выше, и должна соответствовать возвращаемому типу и параметрам этого элемента. |
return_type_idx | uint | индекс в списке type_ids для возвращаемого типа этого прототипа |
параметры_выкл. | uint | смещение от начала файла до списка типов параметров для этого прототипа или 0 , если этот прототип не имеет параметров. Это смещение, если оно не равно нулю, должно находиться в разделе data , а данные там должны быть в формате, указанном в "type_list" ниже. Кроме того, в списке не должно быть ссылок на тип void . |
field_id_item
Появляется в разделе field_ids.
Выравнивание: 4 байта
Имя | Формат | Описание |
---|---|---|
class_idx | сокращать | индекс в списке type_ids для определителя этого поля. Это должен быть тип класса, а не массив или примитивный тип. |
type_idx | сокращать | индекс в списке type_ids для типа этого поля |
name_idx | uint | индекс в списке string_ids для имени этого поля. Строка должна соответствовать синтаксису MemberName , определенному выше. |
метод_id_item
Появляется в разделе Method_ids.
Выравнивание: 4 байта
Имя | Формат | Описание |
---|---|---|
class_idx | сокращать | индекс в списке type_ids для определяющего этого метода. Это должен быть тип класса или массива, а не примитивный тип. |
proto_idx | сокращать | индекс в списке proto_ids для прототипа этого метода |
name_idx | uint | индекс в списке string_ids для имени этого метода. Строка должна соответствовать синтаксису MemberName , определенному выше. |
class_def_item
Появляется в разделе class_defs.
Выравнивание: 4 байта
Имя | Формат | Описание |
---|---|---|
class_idx | uint | индекс в список type_ids для этого класса. Это должен быть тип класса, а не массив или примитивный тип. |
access_flags | uint | флаги доступа для класса ( public , final и т. д.). Подробности см. в разделе «Определения access_flags ». |
суперкласс_idx | uint | индекс в списке type_ids для суперкласса или постоянное значение NO_INDEX , если у этого класса нет суперкласса (т. е. это корневой класс, такой как Object ). Если он присутствует, это должен быть тип класса, а не массив или примитивный тип. |
интерфейсы_off | uint | смещение от начала файла до списка интерфейсов или 0 , если их нет. Это смещение должно находиться в разделе data , а данные там должны быть в формате, указанном в « type_list » ниже. Каждый из элементов списка должен быть типом класса (а не массивом или примитивным типом), и не должно быть дубликатов. |
source_file_idx | uint | индекс в списке string_ids для имени файла, содержащего исходный источник (по крайней мере, большей части) этого класса, или специальное значение NO_INDEX , обозначающее отсутствие этой информации. debug_info_item любого данного метода может переопределить этот исходный файл, но ожидается, что большинство классов будут получены только из одного исходного файла. |
аннотации_off | uint | смещение от начала файла до структуры аннотаций для этого класса или 0 , если для этого класса нет аннотаций. Это смещение, если оно не равно нулю, должно находиться в разделе data , а данные там должны быть в формате, указанном в « annotations_directory_item » ниже, причем все элементы ссылаются на этот класс как на определяющий. |
class_data_off | uint | смещение от начала файла до связанных данных класса для этого элемента или 0 , если для этого класса нет данных класса. (Это может иметь место, например, если этот класс является интерфейсом маркера.) Смещение, если оно не равно нулю, должно находиться в разделе data , а данные там должны быть в формате, указанном в « class_data_item » ниже, причем все элементы ссылаются на этот класс как на определяющий элемент. |
static_values_off | uint | Смещение от начала файла в список начальных значений для static полей или 0 , если нет (и все static поля должны быть инициализированы с помощью 0 или null ). Это смещение должно быть в разделе data , а данные должны быть в формате, указанном в « encoded_array_item » ниже. Размер массива должен быть не больше, чем количество static полей, объявленных этим классом, и элементы соответствуют static полям в том же порядке, что и в соответствующем field_list . Тип каждого элемента массива должен соответствовать заявленному типу соответствующего поля. Если в массиве меньше элементов, чем static поля, то оставшиеся поля инициализируются с подходящим типом 0 или null . |
call_site_id_item
Появляется в разделе Call_site_ids
Выравнивание: 4 байта
Имя | Формат | Описание |
---|---|---|
call_site_off | uint | смещено с начала файла, чтобы позвонить по определению сайта. Смещение должно быть в разделе данных, а данные должны быть в формате, указанном «call_site_item» ниже. |
call_site_item
Появляется в разделе данных
Выравнивание: нет (байт выровнен)
Call_Site_Item - это кодированный_арайский_итм, элементы которых соответствуют аргументам, предоставленным методу сантиметра Bootstrap. Первые три аргумента:
- Руководство метода, представляющее метод линкера Bootstrap (value_method_handle).
- Имя метода, которое должен разрешить линкер начальной загрузки (value_string).
- Тип метода, соответствующий типу имени метода, который должен быть разрешен (value_method_type).
Любые дополнительные аргументы - это постоянные значения, передаваемые методу линкеров Bootstrap. Эти аргументы передаются по порядку и без каких -либо преобразований типа.
Руководство метода, представляющее метод линкера Bootstrap, должен иметь return Type java.lang.invoke.CallSite
. Первые три типа параметров:
-
java.lang.invoke.Lookup
-
java.lang.String
-
java.lang.invoke.MethodType
Типы параметров любых дополнительных аргументов определяются по их постоянным значениям.
method_handle_item
Появляется в разделе Method_handles
Выравнивание: 4 байта
Имя | Формат | Описание |
---|---|---|
method_handle_type | Ushort | тип рукоятки метода; См. Таблицу ниже |
неиспользованный | Ushort | (неиспользованный) |
Field_or_method_id | Ushort | Идентификатор поля или метода в зависимости от того, является ли тип дескриптора метода аксессуаром или методом Invoker |
неиспользованный | Ushort | (неиспользованный) |
Коды типа метода
Постоянный | Ценить | Описание |
---|---|---|
Method_handle_type_static_put | 0x00 | Грандизатор метода является статическим сеттером поля (аксессуар) |
Method_handle_type_static_get | 0x01 | Грандизатор метода является статическим полем Getter (аксессуар) |
Method_handle_type_instance_put | 0x02 | Грандизатор метода - это установщик поля экземпляра (аксессуар) |
Method_handle_type_instance_get | 0x03 | Грандизатор метода является получением поля экземпляра (аксессуар) |
Method_handle_type_invoke_static | 0x04 | Грандизатор метода является статическим методом Invoker |
Method_handle_type_invoke_instance | 0x05 | Грандизатор метода - это метод экземпляра Invoker |
Method_handle_type_invoke_constructor | 0x06 | Грандизатор метода - это метод конструктора Invoker |
Method_handle_type_invoke_direct | 0x07 | Грандизатор метода - это прямой метод Invoker |
Method_handle_type_invoke_interface | 0x08 | Грандизатор метода - это метод интерфейса Invoker |
class_data_item
Ссылка на class_def_item
Появляется в разделе данных
Выравнивание: нет (выровненная байтовая)
Имя | Формат | Описание |
---|---|---|
static_fields_size | Uleb128 | количество статических полей, определенных в этом элементе |
exance_fields_size | Uleb128 | Количество полей экземпляра, определенных в этом элементе |
direct_methods_size | Uleb128 | количество прямых методов, определенных в этом элементе |
virtual_methods_size | Uleb128 | количество виртуальных методов, определенных в этом элементе |
static_fields | incoded_field [static_fields_size] | Определенные статические поля, представленные как последовательность закодированных элементов. Поля должны быть отсортированы по field_idx в порядке увеличения. |
exance_fields | encoded_field [exance_fields_size] | Определенные поля экземпляра, представленные как последовательность закодированных элементов. Поля должны быть отсортированы по field_idx в порядке увеличения. |
Direct_methods | incoded_method [direct_methods_size] | Определенные прямые (любой из static , private или конструкторов) методов, представленные как последовательность кодируемых элементов. Методы должны быть отсортированы с помощью method_idx в увеличении порядка. |
virtual_methods | incoded_method [virtual_methods_size] | Определенные виртуальные (ни один из static , private или конструкторов) методов, представленных как последовательность кодируемых элементов. Этот список не должен включать в себя унаследованные методы, если это не переоценка классом, который представляет этот элемент. Методы должны быть отсортированы с помощью method_idx в увеличении порядка. method_idx виртуального метода не должен быть таким же, как и любой прямой метод. |
Примечание. Все экземпляры Elements ' field_id
и method_id
должны относиться к одному и тому же определяющему классу.
Формат кодировки
Имя | Формат | Описание |
---|---|---|
Field_idx_diff | Uleb128 | Индекс в список field_ids для идентификации этого поля (включает имя и дескриптор), представленного как отличие от индекса предыдущего элемента в списке. Индекс первого элемента в списке представлен напрямую. |
access_flags | Uleb128 | Флаги доступа для поля ( public , final и т. Д.). См. «Определения access_flags » для получения подробной информации. |
Кодированный формат
Имя | Формат | Описание |
---|---|---|
method_idx_diff | Uleb128 | ИНДЕКС В СПИСОК method_ids для идентификации этого метода (включает имя и дескриптор), представленного как отличие от индекса предыдущего элемента в списке. Индекс первого элемента в списке представлен напрямую. |
access_flags | Uleb128 | Флаги доступа к методу ( public , final и т. Д.). См. «Определения access_flags » для получения подробной информации. |
code_off | Uleb128 | Смещение от начала файла в структуру кода для этого метода, или 0 если этот метод либо abstract , либо native . Смещение должно быть в месте в разделе data . Формат данных указан « code_item » ниже. |
type_list
Ссылка на Class_def_item и Proto_id_item
Появляется в разделе данных
Выравнивание: 4 байта
Имя | Формат | Описание |
---|---|---|
размер | uint | размер списка, в записях |
список | type_item [размер] | элементы списка |
формат type_item
Имя | Формат | Описание |
---|---|---|
type_idx | Ushort | Индекс в список type_ids |
code_item
Ссылка на кодировку
Появляется в разделе данных
Выравнивание: 4 байта
Имя | Формат | Описание |
---|---|---|
registers_size | Ushort | количество регистров, используемых этим кодом |
ins_size | Ushort | количество слов входящих аргументов по методу, для которого предназначен этот код |
outs_size | Ushort | количество слов исходящего пространства аргументов, необходимых для этого кода для вызова метода |
tries_size | Ushort | Количество try_item S для этого экземпляра. Если ненулевые, то они появляются в качестве массива tries сразу после insns в этом случае. |
DEBUG_INFO_OFF | uint | Смещение от начала файла в последовательность «Информация отладки» (номера строк + локальная информация переменной) для этого кода, или 0 если просто нет информации. Смещение, если он не нулевой, должно быть в месте в разделе data . Формат данных указан « debug_info_item » ниже. |
insns_size | uint | размер списка инструкций, в 16-битных кодовых единицах |
Insns | Ushort [insns_size] | Фактический массив байт -кода. Формат кода в массиве insns указывается компаньоном Dalvik Bytecode . Обратите внимание, что, хотя это определяется как массив ushort , есть некоторые внутренние структуры, которые предпочитают четырех байтов. Кроме того, если это оказывается в файле с эндсианом, то обмен выполняется только на отдельных экземплярах ushort , а не на более крупных внутренних структурах. |
прокладка | Ushort (необязательно) = 0 | Два байта прокладки, чтобы сделать tries четырех байтовых. Этот элемент присутствует только в том случае, если tries_size не нулевой, а insns_size нечетный. |
пытается | try_item [tries_size] (необязательно) | массив, указывающий, где в коде исключения пойманы и как их обрабатывать. Элементы массива должны быть непересекающимися в диапазоне и по порядку от низкого до высокого адреса. Этот элемент присутствует только в том случае, если tries_size является ненулевым. |
обработчики | incoded_catch_handler_list (необязательно) | Байты, представляющие список списков типов улова и связанных адресов обработчика. Каждый try_item имеет байтовое смещение в эту структуру. Этот элемент присутствует только в том случае, если tries_size является ненулевым. |
Format try_item
Имя | Формат | Описание |
---|---|---|
start_addr | uint | Начальный адрес блока кода, охваченного этой записью. Адрес представляет собой подсчет 16-битных кодовых единиц для начала первой охватываемой инструкции. |
insn_count | Ushort | Количество 16-битных кодовых единиц, охватываемых этой записью. Последний код, покрытый (включительно), start_addr + insn_count - 1 . |
handler_off | Ushort | смещено в байтах с начала связанного encoded_catch_hander_list в encoded_catch_handler для этой записи. Это должно быть смещением к началу encoded_catch_handler . |
Encoded_catch_handler_list Format
Имя | Формат | Описание |
---|---|---|
размер | Uleb128 | размер этого списка, в записях |
список | incoded_catch_handler [handlers_size] | Фактический список списков обработчиков, представленных непосредственно (не как смещения) и последовательно |
Encoded_catch_handler Format
Имя | Формат | Описание |
---|---|---|
размер | SLEB128 | Количество типов уловов в этом списке. Если не положительный, то это отрицательно от количества типов улова, а за уловками следует обработчик с уловами. Например: size 0 означает, что есть все, но нет явно напечатанных уловов. size 2 означает, что есть два явных напечатанных улова и нет всех. А size -1 означает, что есть один типичный улов вместе с всеобъемлющим. |
обработчики | incoded_type_addr_pair [abs (size)] | Поток предметов abs(size) , кодируемых, по одному для каждого пойманного типа, в порядке, чтобы типы должны быть проверены. |
catch_all_addr | Uleb128 (необязательно) | БАЙДЕКОДНЫЙ АДРЕС УДОВАЯ ОБРАЗОВАНИЯ. Этот элемент присутствует только в том случае, если size не является положительным. |
incoded_type_addr_pair формат
Имя | Формат | Описание |
---|---|---|
type_idx | Uleb128 | индекс в список type_ids для типа исключения, чтобы поймать |
Адр | Uleb128 | Адрес по байт -коде соответствующего обработчика исключений |
DEBUG_INFO_ITEM
Ссылка на CODE_ITEM
Появляется в разделе данных
Выравнивание: нет (выровненная байтовая)
Каждый debug_info_item
определяет машину с байто-кодированным DWARF3, которая, при интерпретации, излучает таблицу позиций и (потенциально) информацию локальной переменной для code_item
. Последовательность начинается с заголовка переменной длины (длина которого зависит от количества параметров метода), сопровождается байткодами машины состояния и заканчивается байтом DBG_END_SEQUENCE
.
Государственная машина состоит из пяти регистров. Регистр address
представляет собой смещение инструкции в связанных с этим insns_item
в 16-битных кодовых единицах. Регистр address
начинается с 0
в начале каждой последовательности debug_info
и должен только монотонно увеличиваться. Реестр line
представляет, какой номер исходной строки должен быть связан с записью таблицы следующих позиций, излучаемой государственной машиной. Он инициализируется в заголовке последовательности и может измениться в положительных или отрицательных направлениях, но никогда не должно быть меньше 1
. Регистр source_file
представляет исходный файл, на который ссылаются записи строки. Он инициализируется значению source_file_idx
в class_def_item
. Две другие переменные, prologue_end
и epilogue_begin
, являются логическими флагами (инициализированными в false
), которые указывают, следует ли считать следующую излученную позицию прологом или эпилогом. Государственный аппарат также должен отслеживать имя и тип последней локальной переменной в прямом эфире в каждом регистре для кода DBG_RESTART_LOCAL
.
Заголовок заключается в следующем:
Имя | Формат | Описание |
---|---|---|
line_start | Uleb128 | Начальное значение для регистра line штата. Не представляет фактическую запись позиций. |
параметры_size | Uleb128 | Количество имен параметров, которые закодированы. Должен быть один параметр для метода, исключая метод this , если таковые имеются. |
Parameter_names | uleb128p1 [parameters_size] | Строковой индекс имени параметра метода. Кодированное значение NO_INDEX указывает, что имя не доступно для соответствующего параметра. Дескриптор и подпись типа подразумеваются из дескриптора метода и подписи. |
Значения кода байта следующие:
Имя | Ценить | Формат | Аргументы | Описание |
---|---|---|---|---|
Dbg_end_sequence | 0x00 | (никто) | Заканчивает информационную последовательность отладки для code_item | |
Dbg_advance_pc | 0x01 | uleb128 addr_diff | addr_diff : сумма для добавления в адрес адреса | продвигает регистр адреса без выпуска входа в позиции |
Dbg_advance_line | 0x02 | SLEB128 LINE_DIFF | line_diff : сумма для изменения линии | продвигает регистр строки без выпуска входа в позиции |
Dbg_start_local | 0x03 | uleb128 Register_num uleb128p1 name_idx uleb128p1 type_idx | register_num : регистр, который будет содержать локальныйname_idx : индекс строки имениtype_idx : индекс типа типа | Представляет локальную переменную по текущему адресу. Либо name_idx или type_idx может быть NO_INDEX чтобы указать, что это значение неизвестно. |
Dbg_start_local_extended | 0x04 | uleb128 Register_num uleb128p1 name_idx uleb128p1 type_idx uleb128p1 sig_idx | register_num : регистр, который будет содержать локальныйname_idx : индекс строки имениtype_idx : индекс типа типаsig_idx : индекс строки типа подписи | Представляет локальный с типом подписи по текущему адресу. Любое из name_idx , type_idx или sig_idx может быть NO_INDEX чтобы указать, что это значение неизвестно. (Если sig_idx равен -1 , однако, те же данные могут быть представлены более эффективно, используя OPCODE DBG_START_LOCAL .) ПРИМЕЧАНИЕ. См. Обсуждение в разделе « |
Dbg_end_local | 0x05 | uleb128 Register_num | register_num : регистр, который содержал локальный | Оценка локальной переменной в настоящее время в настоящее время не в текущем адресе |
Dbg_restart_local | 0x06 | uleb128 Register_num | register_num : зарегистрироваться для перезапуска | Повторно вводит локальную переменную по текущему адресу. Название и тип такие же, как последний локальный, который жил в указанном реестре. |
Dbg_set_prologue_end | 0x07 | (никто) | Устанавливает регистр машины prologue_end State, указывая, что добавленная запись следующей позиции следует рассматривать конец пролога метода (подходящее место для точки останова метода). Регистр prologue_end очищается любым специальным ( >= 0x0a ) Opcode. | |
DBG_SET_EPILOGE_BEGIN | 0x08 | (никто) | Устанавливает регистр машины epilogue_begin State Machine, указывая, что добавленная запись следующей позиции должна рассматриваться как начало эпилога метода (подходящее место для приостановки выполнения перед выходом метода). Регистр epilogue_begin очищается любым специальным ( >= 0x0a ) OPCODE. | |
Dbg_set_file | 0x09 | uleb128p1 name_idx | name_idx : индекс String исходного файла; NO_INDEX если неизвестно | Указывает, что все последующие записи номера строки ссылаются на это имя исходного файла, а не имя по умолчанию, указанное в code_item |
Специальные опкоды | 0x0a… 0xff | (никто) | Достижение регистров line и address , излучает запись позиции и очищает prologue_end и epilogue_begin . Смотрите ниже для описания. |
Специальные опкоды
Опыты со значениями между 0x0a
и 0xff
(включительно) перемещают как регистры line
, так и address
на небольшое количество, а затем излучают новую запись таблицы позиций. Формула для приращений заключается в следующем:
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
Ссылка на class_def_item
Появляется в разделе данных
Выравнивание: 4 байта
Имя | Формат | Описание |
---|---|---|
class_annotations_off | uint | Смещение от начала файла в аннотации, сделанные непосредственно в классе, или 0 если у класса нет прямых аннотаций. Смещение, если он не нулевой, должно быть в месте в разделе data . Формат данных указан « annotation_set_item » ниже. |
fields_size | uint | Подсчет полей, аннотированных этим предметом |
Annotated_methods_size | uint | Подсчет методов, аннотированных этим предметом |
Annotated_Parameters_size | uint | Подсчет параметров метода перечисляет аннотированный этим элементом |
Field_annotations | Field_annotation [fields_size] (необязательно) | Список связанных полевых аннотаций. Элементы списка должны быть отсортированы в порядке увеличения, по field_idx . |
method_annotations | method_annotation [methods_size] (необязательно) | Список связанных методов аннотаций. Элементы списка должны быть отсортированы в порядке увеличения, по method_idx . |
Parameter_annotations | parameter_annotation [parameters_size] (необязательно) | СПИСОК АННОТАЦИИ ПАРАМЕТАЦИИ МЕТОДА. Элементы списка должны быть отсортированы в порядке увеличения, по method_idx . |
Примечание. Все экземпляры Elements ' field_id
и method_id
должны относиться к одному и тому же определяющему классу.
Field_annotation Format
Имя | Формат | Описание |
---|---|---|
Field_idx | uint | индекс в список field_ids для аннотированного идентификации поля |
Annotations_off | uint | смещено с начала файла в список аннотаций для поля. Смещение должно быть в месте в разделе data . Формат данных указан « annotation_set_item » ниже. |
method_annotation format
Имя | Формат | Описание |
---|---|---|
method_idx | uint | индекс в список method_ids для идентификации аннотированного метода |
Annotations_off | uint | смещено с начала файла в список аннотаций для метода. Смещение должно быть в месте в разделе data . Формат данных указан « annotation_set_item » ниже. |
FARATER_ANNOTATION FORMAT
Имя | Формат | Описание |
---|---|---|
method_idx | uint | Индекс в список method_ids для идентификации метода, параметры которых аннотируются |
Annotations_off | uint | смещено с начала файла в список аннотаций для параметров метода. Смещение должно быть в месте в разделе data . Формат данных указывается « annotation_set_ref_list » ниже. |
Annotation_set_ref_list
Ссылка на Parameter_annotations_item
Появляется в разделе данных
Выравнивание: 4 байта
Имя | Формат | Описание |
---|---|---|
размер | uint | размер списка, в записях |
список | annotation_set_ref_item [size] | элементы списка |
Annotation_set_ref_item Format
Имя | Формат | Описание |
---|---|---|
Annotations_off | uint | Смещение от начала файла в набор аннотаций с указанием или 0 , если для этого элемента нет аннотаций. Смещение, если он не нулевой, должно быть в месте в разделе data . Формат данных указан « annotation_set_item » ниже. |
Annotation_set_item
Ссылка на Annotations_directory_item, Field_annotations_item, method_annotations_item и Annotation_set_ref_item
Появляется в разделе данных
Выравнивание: 4 байта
Имя | Формат | Описание |
---|---|---|
размер | uint | размер набора, в записях |
записи | Annotation_off_item [размер] | элементы набора. Элементы должны быть отсортированы в увеличении порядка, по type_idx . |
Annotation_off_item Format
Имя | Формат | Описание |
---|---|---|
Annotation_off | uint | смещено от начала файла в аннотацию. Смещение должно быть в месте в разделе data , а формат данных в этом месте указывается « annotation_item » ниже. |
Annotation_Item
Ссылка на Annotation_set_item
Появляется в разделе данных
Выравнивание: нет (выровненная байтовая)
Имя | Формат | Описание |
---|---|---|
видимость | Ubyte | Предполагаемая видимость этой аннотации (см. Ниже) |
аннотация | кодировка_аннотации | Кодированное содержимое аннотации, в формате, описанном в « encoded_annotation формате» в «Кодировании encoded_value », кодировании »выше. |
Значения видимости
Это варианты поля visibility
в annotation_item
:
Имя | Ценить | Описание |
---|---|---|
Visibility_build | 0x00 | предназначен для того, чтобы быть видимым во время сборки (например, во время компиляции другого кода) |
Visibility_runtime | 0x01 | предназначен для видимости во время выполнения |
Visibility_system | 0x02 | предназначен для видимых во время выполнения, но только для базовой системы (а не для регулярного кода пользователя) |
Encoded_array_item
Ссылка на class_def_item
Появляется в разделе данных
Выравнивание: нет (выровненная байтовая)
Имя | Формат | Описание |
---|---|---|
ценить | кодированный_райр | Байты, представляющие кодируемое значение массива, в формате, указанном в « encoded_array формате» в разделе «Кодирование encoded_value » выше. |
hiddenapi_class_data_item
Этот раздел содержит данные о ограниченных интерфейсах, используемых каждым классом.
ПРИМЕЧАНИЕ. Функция скрытой API была введена в Android 10.0 и применима только к файлам DEX классов в пути класса загрузки. Список флагов, описанных ниже, может быть расширен в будущих выпусках Android. Для получения дополнительной информации см. Ограничения на не-SDK-интерфейсы .
Имя | Формат | Описание |
---|---|---|
размер | uint | Общий размер секции |
смещения | uint [] | Массив смещений, индексируемый class_idx . Запись с нулевым массивом в индексе class_idx означает, что либо нет данных для этого class_idx , либо все скрытые флаги API равны нулю. В противном случае запись в массиве ненулевой и содержит смещение от начала раздела до массива скрытых флагов API для этого class_idx . |
флаги | Uleb128 [] | Согласованные массивы скрытых флагов API для каждого класса. Возможные значения флага описаны в таблице ниже. Флаги кодируются в том же порядке, что и поля, а методы кодируются в данных класса. |
Ограничение типы флага:
Имя | Ценить | Описание |
---|---|---|
белый список | 0 | Интерфейсы, которые могут быть свободно использованы и поддерживаются как часть официально документированного индекса пакета Android Framework. |
СЕРИЙСКИЙ СЛИБ | 1 | Не-SDK интерфейсы, которые можно использовать независимо от целевого уровня API приложения. |
черный список | 2 | Не-SDK интерфейсы, которые не могут быть использованы независимо от целевого уровня API приложения. Доступ к одному из этих интерфейсов вызывает ошибку времени выполнения . |
Greylist -Max -O | 3 | Не-SDK интерфейсы, которые можно использовать для Android 8.x и ниже, если они не ограничены. |
Greylist -Max -P | 4 | Не-SDK интерфейсы, которые можно использовать для Android 9.x, если они не ограничены. |
Greylist -Max -Q | 5 | Не-SDK интерфейсы, которые можно использовать для Android 10.x, если они не ограничены. |
Greylist -Max -R | 6 | Не-SDK интерфейсы, которые можно использовать для Android 11.x, если они не ограничены. |
Системные аннотации
Системные аннотации используются для представления различных фрагментов рефлексивной информации о классах (и методах и полях). Эта информация, как правило, доступна только косвенно по клиентскому (несистемному) коду.
Системные аннотации представлены в файлах .dex
в виде аннотаций с видимостью, установленными на VISIBILITY_SYSTEM
.
dalvik.annotation.annotationdefault
Появляется на методах в интерфейсах аннотации
Аннотация AnnotationDefault
прикреплена к каждому интерфейсу аннотации, который хочет указать привязки по умолчанию.
Имя | Формат | Описание |
---|---|---|
ценить | Аннотация | Привязки по умолчанию для этой аннотации представлены как аннотация этого типа. Аннотация не должна включать все имена, определенные аннотацией; Пропущенные имена просто не имеют по умолчанию. |
dalvik.annotation.inclosingclass
Появляется на классах
Аннотация EnclosingClass
прилагается к каждому классу, который либо определяется как член другого класса, как таковой, либо анонимна, но не определяется в теле метода (например, синтетический внутренний класс). Каждый класс, у которого есть эта аннотация, также должен иметь аннотацию InnerClass
. Кроме того, класс не должен иметь как EnclosingClass
класс, так и аннотацию EnclosingMethod
.
Имя | Формат | Описание |
---|---|---|
ценить | Сорт | Класс, который наиболее близко квалифицирует этот класс |
dalvik.annotation.inclosingmethod
Появляется на классах
Аннотация EnclosingMethod
прикреплена к каждому классу, который определяется внутри тела метода. Каждый класс, у которого есть эта аннотация, также должен иметь аннотацию InnerClass
. Кроме того, класс не должен иметь как EnclosingClass
класс, так и аннотацию EnclosingMethod
.
Имя | Формат | Описание |
---|---|---|
ценить | Метод | метод, который наиболее близко квалифицирует этот класс |
dalvik.annotation.innerclass
Появляется на классах
Аннотация InnerClass
прикреплена к каждому классу, который определяется в лексическом объеме определения другого класса. Любой класс, который имеет эту аннотацию, также должен иметь либо аннотацию EnclosingClass
, либо аннотация EnclosingMethod
.
Имя | Формат | Описание |
---|---|---|
имя | Нить | Первоначально объявлено простое название этого класса (не считая любого префикса пакета). Если этот класс является анонимным, то имя null . |
Accessflags | интервал | Первоначально объявленные флаги доступа класса (которые могут отличаться от эффективных флагов из -за несоответствия между моделями выполнения исходного языка и целевой виртуальной машиной) |
dalvik.annotation.memberclasses
Появляется на классах
Аннотация MemberClasses
прилагается к каждому классу, который объявляет классы участников. (Класс участников - это прямой внутренний класс, который имеет имя.)
Имя | Формат | Описание |
---|---|---|
ценить | Сорт[] | массив классов участников |
dalvik.annotation.methodparameters
Появляется на методах
Примечание. Эта аннотация была добавлена после Android 7.1. Его присутствие в более ранних выпусках Android будет проигнорировано.
Аннотация MethodParameters
является необязательным и может использоваться для предоставления параметров метаданных, таких как имена параметров и модификаторы.
Аннотация может быть безопасно пропущена из метода или конструктора, когда метаданные параметра не требуются во время выполнения. java.lang.reflect.Parameter.isNamePresent()
может использоваться для проверки того, присутствуют ли метаданные для параметра, и связанные методы отражения, такие как java.lang.reflect.Parameter.getName()
вернутся к поведению по умолчанию во время выполнения, если информация нет.
При включении метаданных параметров компиляторы должны включать информацию для сгенерированных классов, таких как перечисление, поскольку метаданные параметры включают, является ли параметр синтетическим или обязательным.
Аннотация MethodParameters
описывает только отдельные параметры метода. Следовательно, компиляторы могут полностью пропустить аннотацию для конструкторов и методов, которые не имеют параметров, ради эффективности размера кода и времени выполнения.
Массивы, зарегистрированные ниже, должны быть тем же размером, что и для структуры Dex method_id_item
, связанной с методом, в противном случае java.lang.reflect.MalformedParametersException
будет брошен во время выполнения.
То есть: method_id_item.proto_idx
-> proto_id_item.parameters_off
-> type_list.size
должен быть таким же, как и names().length
и accessFlags().length
.
Поскольку MethodParameters
описывают все формальные параметры метода, даже те, которые не явно или неявно объявляются в исходном коде, размер массивов может отличаться от подписи или другой информации метаданных, основанной только на явных параметрах, объявленных в исходном коде. MethodParameters
также не будет включать какую -либо информацию о параметрах приемника типа, которые не существуют в фактической подписи метода.
Имя | Формат | Описание |
---|---|---|
имена | Нить[] | Названия формальных параметров для связанного метода. Массив не должен быть нулевым, но должен быть пустым, если нет формальных параметров. Значение в массиве должно быть нулевым, если формальный параметр с этим индексом не имеет имени. Если строки имени параметра пусты или содержат '.', ';', '[' Или '/', то java.lang.reflect.MalformedParametersException будет брошен во время выполнения. |
Accessflags | int [] | Флаги доступа формальных параметров для связанного метода. Массив не должен быть нулевым, но должен быть пустым, если нет формальных параметров. Значение немного маски со следующими значениями:
java.lang.reflect.MalformedParametersException будет брошен во время выполнения. |
Dalvik.annotation.Signature
Появляется на классах, полях и методах
Аннотация Signature
прикреплена к каждому классу, полю или методу, который определяется в терминах более сложного типа, чем представляется type_id_item
. Формат .dex
не определяет формат для подписей; Он просто предназначен для того, чтобы иметь возможность представлять любые подписи, которые требуют исходного языка для успешной реализации семантики этого языка. Таким образом, подписи, как правило, не проанализируются (или проверяются) с помощью реализаций виртуальных машин. Подписи просто передаются API и инструментам более высокого уровня (например, отладчики). Следовательно, любое использование подписи должно быть написано, чтобы не делать никаких предположений о получении только действительных подписей, явных охраняющихся от возможности столкновения с синтаксически недействительной.
Поскольку строки подписи имеют тенденцию иметь много дублированного контента, аннотация Signature
определяется как массив строк, где дублированные элементы, естественно, относятся к одинаковым основным данным, а подпись считается объединением всех строк в массиве. Нет никаких правил о том, как разместить подпись в отдельные строки; Это полностью зависит от инструментов, которые генерируют файлы .dex
.
Имя | Формат | Описание |
---|---|---|
ценить | Нить[] | Подпись этого класса или члена, как множество струн, которые должны быть объединены вместе |
dalvik.annotation.throws
Появляется на методах
Аннотация Throws
прикреплена к каждому методу, который объявляется, чтобы бросить один или несколько типов исключений.
Имя | Формат | Описание |
---|---|---|
ценить | Сорт[] | массив типов исключений |
Этот документ описывает макет и содержание файлов .dex
, которые используются для сохранения набора определений класса и связанных с ними дополнительных данных.
Руководство по типам
Имя | Описание |
---|---|
байт | 8-битный подписанный инт |
Ubyte | 8-битный без подписи инт |
короткий | 16-битный подписанный int, маленький |
Ushort | 16-битный unsigned int, маленький |
интервал | 32-битный подписанный int, маленький |
uint | 32-разрядный без знака Int, Маленький Эндиан |
длинный | 64-битный подписанный int, маленький |
улонг | 64-разрядный без знака Int, Маленький Эндиан |
SLEB128 | Подписанный LEB128, переменная длина (см. Ниже) |
Uleb128 | Unsigned LEB128, переменная длина (см. Ниже) |
Uleb128p1 | Unsigned LEB128 плюс 1 , переменная длина (см. Ниже) |
LEB128
LEB128 (" L Ittle- e ndian B ASE 128 ") является кодированием переменной длины для произвольных подписанных или неподписанных целочисленных величин. Формат был заимствован из спецификации Dwarf3 . В файле .dex
LEB128 используется только для кодирования 32-разрядных величин.
Каждое кодированное значение LOB128 состоит из одного до пяти байтов, которые вместе представляют одно 32-разрядное значение. Каждый байт имеет свой наиболее значимый набор битов, за исключением последнего байта в последовательности, который имеет наиболее значительный бит. Оставшиеся семь бит каждого байта являются полезной нагрузкой, с наименее значительными семь бит количества в первом байте, следующие семь во втором байте и так далее. В случае подписанного LEB128 ( sleb128
) наиболее значимый бит полезной нагрузки из окончательного байта в последовательности подписан для получения конечного значения. В случае без знака ( uleb128
) любые биты, не представленные явно, интерпретируются как 0
.
Более бить диаграмма двух байтовой значения LEB128 | |||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Первый байт | Второй байт | ||||||||||||||
1 | бит 6 | бит 5 | бит 4 | бит 3 | бит 2 | бит 1 | бит 0 | 0 | бит 13 | бит 12 | бит 11 | бит 10 | бит 9 | бит 8 | бит 7 |
Вариант uleb128p1
используется для представления подписанного значения, где представление имеет значение, плюс одно кодируемое как uleb128
. Это делает кодирование -1
(альтернативно считается незнанным значением 0xffffffff
), но никакого другого отрицательного числа -единого байта, и это полезно в тех случаях, когда представленное число должно быть либо неотрицательным, либо -1
(или 0xffffffff
), и где не допускаются другие негативные значения (или где большие значения без подписи вряд ли не требуются).
Вот несколько примеров форматов:
Кодированная последовательность | Как sleb128 | Как uleb128 | Как uleb128p1 |
---|---|---|---|
00 | 0 | 0 | -1 |
01 | 1 | 1 | 0 |
7f | -1 | 127 | 126 |
80 7f | -128 | 16256 | 16255 |
Макет файла
Имя | Формат | Описание |
---|---|---|
заголовок | header_item | Заголовок |
string_ids | string_id_item [] | Список идентификаторов строк. Это идентификаторы для всех строк, используемых этим файлом, либо для внутреннего именования (например, дескрипторов типа), либо как постоянные объекты, упомянутые кодом. Этот список должен быть отсортирован с помощью строкового содержимого, используя значения точек кода UTF-16 (не чувствительно локализации), и он не должен содержать каких-либо дублирующих записей. |
type_ids | type_id_item [] | Список идентификаторов типа. Это идентификаторы для всех типов (классы, массивы или примитивные типы), упомянутые этим файлом, определены в файле или нет. Этот список должен быть отсортирован по индексу string_id , и он не должен содержать каких -либо дублирующих записей. |
proto_ids | proto_id_item [] | Список идентификаторов прототипа метода. Это идентификаторы для всех прототипов, упомянутых этим файлом. Этот список должен быть отсортирован в основном порядке типа (по type_id ), а затем по списку аргументов (лексикографический порядок, отдельные аргументы, упорядоченные с помощью индекса type_id ). Список не должен содержать каких -либо дубликатов записей. |
Field_ids | field_id_item [] | Список идентификаторов поля. Это идентификаторы для всех полей, упомянутых этим файлом, определены в файле или нет. Этот список должен быть отсортирован, где определяющий тип (по индексу type_id ) является основным порядком, имя поля (по string_id ) является промежуточным порядком, а тип (по индексу type_id ) - это незначительный порядок. Список не должен содержать каких -либо дубликатов записей. |
method_ids | method_id_item [] | Список идентификаторов метода. Это идентификаторы для всех методов, упомянутых этим файлом, определены в файле или нет. This list must be sorted, where the defining type (by type_id index) is the major order, method name (by string_id index) is the intermediate order, and method prototype (by proto_id index) is the minor order. The list must not contain any duplicate entries. |
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. Furthermore, it is invalid for a definition for the same-named class to appear more than once in the list. |
call_site_ids | call_site_id_item[] | call site identifiers list. These are identifiers for all call sites referred to by this file, whether defined in the file or not. This list must be sorted in ascending order of call_site_off . |
method_handles | method_handle_item[] | method handles list. A list of all method handles referred to by this file, whether defined in the file or not. This list is not sorted and may contain duplicates which will logically correspond to different method handle instances. |
данные | 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. |
Container format
Version 41 introduces a new container format for DEX data with the goal to save space. This container format allows several logical DEX files to be combined into a single physical file. The new format is mostly just naive concatenation of files in the previous format, with some differences:
- The
file_size
is the size of the logical file, not the physical file. It can be used to iterate over all the logical files in the container. - Logical dex files may reference any later data in the container (but not earlier). This allows dex files to share data, such as strings, between them.
- All offsets are relative to the physical file. No offset is relative to the header. This is ensures that sections with offsets can be shared between logical files.
- The header adds two new fields to describe the bounds of the container. This is an additional consistency check and makes porting code to the new format easier.
- The
data_size
anddata_off
are now unused. Data can be spread across multiple logical files and does not have to be contiguous.
Bitfield, string, and constant definitions
DEX_FILE_MAGIC
Embedded in header_item
The constant array/string DEX_FILE_MAGIC
is the list of bytes that must appear at the beginning of a .dex
file in order for it to be recognized as such. The value intentionally contains a newline ( "\n"
or 0x0a
) and a null byte ( "\0"
or 0x00
) 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 0x39 0x00 } = "dex\n039\0"
Note: Support for version 040
of the format was added in the Android 10.0 release, which extended the set of allowed characters in SimpleNames .
Note: Support for version 039
of the format was added in the Android 9.0 release, which introduced two new bytecodes, const-method-handle
and const-method-type
. (These are each described in the Summary of bytecode set table.) In Android 10, version 039
extends the DEX file format to include hidden API information that's only applicable to DEX files on the boot class path.
Note: Support for version 038
of the format was added in the Android 8.0 release. Version 038
added new bytecodes ( invoke-polymorphic
and invoke-custom
) and data for method handles.
Note: Support for version 037
of the format was added in the Android 7.0 release. Prior to version 037
most versions of Android have used version 035
of the format. The only difference between versions 035
and 037
is the addition of default methods and the adjustment of the invoke
.
Note: At least a couple earlier versions of the format have been used in widely available public software releases. For example, version 009
was used for the M3 releases of the Android platform (November–December 2007), and version 013
was 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_CONSTANT and REVERSE_ENDIAN_CONSTANT
Embedded in header_item
The constant ENDIAN_CONSTANT
is used to indicate the endianness of the file in which it is found. Although the standard .dex
format is little-endian, implementations may choose to perform byte-swapping. Should an implementation come across a header whose endian_tag
is REVERSE_ENDIAN_CONSTANT
instead of ENDIAN_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 in class_def_item and debug_info_item
The constant NO_INDEX
is used to indicate that an index value is absent.
Note: This value isn't defined to be 0
, because that is in fact typically a valid index.
The chosen value for NO_INDEX
is representable as a single byte in the uleb128p1
encoding.
uint NO_INDEX = 0xffffffff; // == -1 if treated as a signed int
access_flags definitions
Embedded in class_def_item, encoded_field, encoded_method, and InnerClass
Bitfields of these flags are used to indicate the accessibility and overall properties of classes and class members.
Имя | Ценить | For Classes (and InnerClass annotations) | 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 outer this reference | static : global to defining class | static : does not take a this argument |
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 when | ||
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 | declared synchronized .Note: This has no effect on execution (other than in reflection of this flag, per se). |
InnerClass
annotations, and must not ever be on in a class_def_item
.
Modified UTF-8 encoding
As a concession to easier legacy support, the .dex
format 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 range
U+10000
…U+10ffff
are encoded as a surrogate pair, each of which is represented as a three-byte encoded value. - The code point
U+0000
is encoded in two-byte form. - A plain null byte (value
0
) 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 point U+0000
in a string and still manipulate it as a C-style null-terminated string.
However, the special encoding of U+0000
means that, unlike normal UTF-8, the result of calling the standard C function strcmp()
on a pair of MUTF-8 strings does not always indicate the properly signed result of comparison of unequal strings. 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 to The Unicode Standard for further information about character encoding. MUTF-8 is actually closer to the (relatively less well-known) encoding CESU-8 than to UTF-8 per se.
encoded_value encoding
Embedded in annotation_element and encoded_array_item
An encoded_value
is an encoded piece of (nearly) arbitrary hierarchically structured data. The encoding is meant to be both compact and straightforward to parse.
Имя | Формат | Описание |
---|---|---|
(value_arg << 5) | value_type | ubyte | byte indicating the type of the immediately subsequent value along with an optional clarifying argument in the high-order three bits. See below for the various value definitions. In most cases, value_arg encodes the length of the immediately-subsequent value in bytes, as (size - 1) , eg, 0 means that the value requires one byte, and 7 means it requires eight bytes; however, there are exceptions as noted below. |
ценить | ubyte[] | bytes representing the value, variable in length and interpreted differently for different value_type bytes, though always little-endian. See the various value definitions below for details. |
Value formats
Type Name | value_type | value_arg Format | value Format | Описание |
---|---|---|---|---|
VALUE_BYTE | 0x00 | (none; must be 0 ) | 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-extended to 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-extended to the right , and interpreted as an IEEE754 64-bit floating point value |
VALUE_METHOD_TYPE | 0x15 | size - 1 (0…3) | ubyte[size] | unsigned (zero-extended) four-byte integer value, interpreted as an index into the proto_ids section and representing a method type value |
VALUE_METHOD_HANDLE | 0x16 | size - 1 (0…3) | ubyte[size] | unsigned (zero-extended) four-byte integer value, interpreted as an index into the method_handles section and representing a method handle value |
VALUE_STRING | 0x17 | size - 1 (0…3) | ubyte[size] | unsigned (zero-extended) four-byte integer value, interpreted as an index into the string_ids section 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 the type_ids section 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 the field_ids section 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 the method_ids section 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 the field_ids section and representing the value of an enumerated type constant |
VALUE_ARRAY | 0x1c | (none; must be 0 ) | encoded_array | an array of values, in the format specified by " encoded_array format" below. The size of the value is implicit in the encoding. |
VALUE_ANNOTATION | 0x1d | (none; must be 0 ) | encoded_annotation | a sub-annotation, in the format specified by " encoded_annotation format" below. The size of the value is implicit in the encoding. |
VALUE_NULL | 0x1e | (none; must be 0 ) | (никто) | null reference value |
VALUE_BOOLEAN | 0x1f | boolean (0…1) | (никто) | one-bit value; 0 for false and 1 for true . The bit is represented in the value_arg . |
encoded_array format
Имя | Формат | Описание |
---|---|---|
размер | uleb128 | number of elements in the array |
ценности | encoded_value[size] | a series of size encoded_value byte sequences in the format specified by this section, concatenated sequentially. |
encoded_annotation format
Имя | Формат | Описание |
---|---|---|
type_idx | uleb128 | type of the annotation. This must be a class (not array or primitive) type. |
размер | uleb128 | number of name-value mappings in this annotation |
элементы | annotation_element[size] | elements of the annotation, represented directly in-line (not as offsets). Elements must be sorted in increasing order by string_id index. |
annotation_element format
Имя | Формат | Описание |
---|---|---|
name_idx | uleb128 | element name, represented as an index into the string_ids section. The string must conform to the syntax for MemberName , defined above. |
ценить | encoded_value | element value |
String syntax
There are several kinds of item in a .dex
file which ultimately refer to a string. The following BNF-style definitions indicate the acceptable syntax for these strings.
SimpleName
A SimpleName is the basis for the syntax of the names of other things. The .dex
format allows a fair amount of latitude here (much more than most common source languages). In brief, a simple name consists 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. Starting from version 040
the format additionally allows space characters (Unicode Zs
category). Note that surrogate code points (in the range U+d800
… U+dfff
) are not considered valid name characters, per se, but Unicode supplemental characters are valid (which are represented by the final alternative of the rule for SimpleNameChar ), 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' | |
| | ' ' | since DEX version 040 |
| | '$' | |
| | '-' | |
| | '_' | |
| | U+00a0 | since DEX version 040 |
| | U+00a1 … U+1fff | |
| | U+2000 … U+200a | since DEX version 040 |
| | U+2010 … U+2027 | |
| | U+202f | since DEX version 040 |
| | U+2030 … U+d7ff | |
| | U+e000 … U+ffef | |
| | U+10000 … U+10ffff |
MemberName
used by field_id_item and method_id_item
A MemberName is the name of a member of a class, members being fields, methods, and inner classes.
MemberName → | |
SimpleName | |
| | '<' SimpleName '>' |
FullClassName
A FullClassName is a fully qualified class name, including an optional package specifier followed by a required name.
FullClassName → | |
OptionalPackagePrefix SimpleName | |
OptionalPackagePrefix → | |
( SimpleName '/' )* |
TypeDescriptor
Used by type_id_item
A TypeDescriptor is the representation of any type, including primitives, classes, arrays, and void
. 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 by proto_id_item
A ShortyDescriptor is 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' |
TypeDescriptor semantics
This is the meaning of each of the variants of TypeDescriptor .
Синтаксис | Значение |
---|---|
В | void ; only valid for return types |
З | boolean |
Б | byte |
С | short |
С | char |
я | int |
Дж | long |
Ф | float |
Д | double |
L fully/qualified/Name ; | the class fully.qualified.Name |
[ descriptor | array of descriptor , 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 .dex
file.
header_item
Appears in the header section
Alignment: 4 bytes
Имя | Формат | Описание |
---|---|---|
магия | 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 but magic and this field); used to detect file corruption |
подпись | ubyte[20] | SHA-1 signature (hash) of the rest of the file (everything but magic , checksum , and this field); used to uniquely identify files |
file_size | uint | size of the entire file (including the header), in bytes (v40 or earlier) distance in bytes from the start of this header to the next header or to the end of the whole file (the container). (v41 или позже) |
header_size | uint | 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. must be 0x70 (112) bytes (v40 or earlier) must be 0x78 (120) bytes (v41 or later) |
endian_tag | uint = ENDIAN_CONSTANT | endianness tag. See discussion above under " ENDIAN_CONSTANT and REVERSE_ENDIAN_CONSTANT " for more details. |
link_size | uint | size of the link section, or 0 if this file isn't statically linked |
link_off | uint | offset from the start of the file to the link section, or 0 if link_size == 0 . The offset, if non-zero, should be to an offset into the link_data section. 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. The offset, which must be non-zero, should be to an offset into the data section, 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, or 0 if string_ids_size == 0 (admittedly a strange edge case). The offset, if non-zero, should be to the start of the string_ids section. |
type_ids_size | uint | count of elements in the type identifiers list, at most 65535 |
type_ids_off | uint | offset from the start of the file to the type identifiers list, or 0 if type_ids_size == 0 (admittedly a strange edge case). The offset, if non-zero, should be to the start of the type_ids section. |
proto_ids_size | uint | count of elements in the prototype identifiers list, at most 65535 |
proto_ids_off | uint | offset from the start of the file to the prototype identifiers list, or 0 if proto_ids_size == 0 (admittedly a strange edge case). The offset, if non-zero, should be to the start of the proto_ids section. |
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, or 0 if field_ids_size == 0 . The offset, if non-zero, should be to the start of the field_ids section. |
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, or 0 if method_ids_size == 0 . The offset, if non-zero, should be to the start of the method_ids section. |
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, or 0 if class_defs_size == 0 (admittedly a strange edge case). The offset, if non-zero, should be to the start of the class_defs section. |
data_size | uint | Size of Unused (v41 or later) |
data_off | uint | offset from the start of the file to the start of the Unused (v41 or later) |
container_size | uint | this field does not exist. It can be assumed to be equal to size of the entire file (including other dex headers and their data). (v41 или позже) |
header_offset | uint | this field does not exist. It can be assumed to be equal to offset from the start of the file to the start of this header. (v41 или позже) |
map_list
Appears in the data section
Referenced from header_item
Alignment: 4 bytes
This is a list of the entire contents of a file, in order. It contains some redundancy with respect to the header_item
but is intended to be an easy form to use to iterate over an entire file. A given type must 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 (eg, a header
section must appear first, followed by a string_ids
section, etc.). Additionally, the map entries must be ordered by initial offset and must not overlap.
Имя | Формат | Описание |
---|---|---|
размер | uint | size of the list, in entries |
список | map_item[size] | elements of the list |
map_item format
Имя | Формат | Описание |
---|---|---|
тип | ushort | type of the items; see table below |
неиспользованный | ushort | (unused) |
размер | uint | count of the number of items to be found at the indicated offset |
компенсировать | uint | offset from the start of the file to the items in question |
Type codes
Item Type | Постоянный | Ценить | 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 |
call_site_id_item | TYPE_CALL_SITE_ID_ITEM | 0x0007 | 0x04 |
method_handle_item | TYPE_METHOD_HANDLE_ITEM | 0x0008 | 0x08 |
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 | скрытый; must parse |
code_item | TYPE_CODE_ITEM | 0x2001 | скрытый; must parse |
string_data_item | TYPE_STRING_DATA_ITEM | 0x2002 | скрытый; must parse |
debug_info_item | TYPE_DEBUG_INFO_ITEM | 0x2003 | скрытый; must parse |
annotation_item | TYPE_ANNOTATION_ITEM | 0x2004 | скрытый; must parse |
encoded_array_item | TYPE_ENCODED_ARRAY_ITEM | 0x2005 | скрытый; must parse |
annotations_directory_item | TYPE_ANNOTATIONS_DIRECTORY_ITEM | 0x2006 | скрытый; must parse |
hiddenapi_class_data_item | TYPE_HIDDENAPI_CLASS_DATA_ITEM | 0xF000 | скрытый; must parse |
string_id_item
Appears in the string_ids section
Alignment: 4 bytes
Имя | Формат | Описание |
---|---|---|
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 the data section, 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 the data section
Alignment: none (byte-aligned)
Имя | Формат | Описание |
---|---|---|
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 the 0 byte.) |
данные | ubyte[] | a series of MUTF-8 code units (aka octets, aka bytes) followed by a byte of value 0 . 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, |
type_id_item
Appears in the type_ids section
Alignment: 4 bytes
Имя | Формат | Описание |
---|---|---|
descriptor_idx | uint | index into the string_ids list for the descriptor string of this type. The string must conform to the syntax for TypeDescriptor , defined above. |
proto_id_item
Appears in the proto_ids section
Alignment: 4 bytes
Имя | Формат | Описание |
---|---|---|
shorty_idx | uint | index into the string_ids list for the short-form descriptor string of this prototype. The string must conform to the syntax for ShortyDescriptor , defined above, and must correspond to the return type and parameters of this item. |
return_type_idx | uint | index into the type_ids list 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, or 0 if this prototype has no parameters. This offset, if non-zero, should be in the data section, and the data there should be in the format specified by "type_list" below. Additionally, there should be no reference to the type void in the list. |
field_id_item
Appears in the field_ids section
Alignment: 4 bytes
Имя | Формат | Описание |
---|---|---|
class_idx | ushort | index into the type_ids list for the definer of this field. This must be a class type, and not an array or primitive type. |
type_idx | ushort | index into the type_ids list for the type of this field |
name_idx | uint | index into the string_ids list for the name of this field. The string must conform to the syntax for MemberName , defined above. |
method_id_item
Appears in the method_ids section
Alignment: 4 bytes
Имя | Формат | Описание |
---|---|---|
class_idx | ushort | index into the type_ids list for the definer of this method. This must be a class or array type, and not a primitive type. |
proto_idx | ushort | index into the proto_ids list for the prototype of this method |
name_idx | uint | index into the string_ids list for the name of this method. The string must conform to the syntax for MemberName , defined above. |
class_def_item
Appears in the class_defs section
Alignment: 4 bytes
Имя | Формат | Описание |
---|---|---|
class_idx | uint | index into the type_ids list 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_flags Definitions" for details. |
superclass_idx | uint | index into the type_ids list for the superclass, or the constant value NO_INDEX if this class has no superclass (ie, it is a root class such as Object ). 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, or 0 if there are none. This offset should be in the data section, 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 the string_ids list for the name of the file containing the original source for (at least most of) this class, or the special value NO_INDEX to represent a lack of this information. The debug_info_item of 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, or 0 if there are no annotations on this class. This offset, if non-zero, should be in the data section, 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, or 0 if 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 the data section, 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 for static fields, or 0 if there are none (and all static fields are to be initialized with 0 or null ). This offset should be in the data section, 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 of static fields declared by this class, and the elements correspond to the static fields in the same order as declared in the corresponding field_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 are static fields, then the leftover fields are initialized with a type-appropriate 0 or null . |
call_site_id_item
Appears in the call_site_ids section
Alignment: 4 bytes
Имя | Формат | Описание |
---|---|---|
call_site_off | uint | offset from the start of the file to call site definition. The offset should be in the data section, and the data there should be in the format specified by "call_site_item" below. |
call_site_item
Appears in the data section
Alignment: none (byte aligned)
The call_site_item is an encoded_array_item whose elements correspond to the arguments provided to a bootstrap linker method. The first three arguments are:
- A method handle representing the bootstrap linker method (VALUE_METHOD_HANDLE).
- A method name that the bootstrap linker should resolve (VALUE_STRING).
- 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:
-
java.lang.invoke.Lookup
-
java.lang.String
-
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
Имя | Формат | Описание |
---|---|---|
method_handle_type | ushort | type of the method handle; see table below |
неиспользованный | 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 |
неиспользованный | ushort | (unused) |
Method handle type codes
Постоянный | Ценить | Описание |
---|---|---|
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)
Имя | Формат | Описание |
---|---|---|
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
and method_id
instances must refer to the same defining class.
encoded_field format
Имя | Формат | Описание |
---|---|---|
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
Имя | Формат | Описание |
---|---|---|
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
Имя | Формат | Описание |
---|---|---|
размер | uint | size of the list, in entries |
список | type_item[size] | elements of the list |
type_item format
Имя | Формат | Описание |
---|---|---|
type_idx | ushort | index into the type_ids list |
code_item
Referenced from encoded_method
Appears in the data section
Alignment: 4 bytes
Имя | Формат | Описание |
---|---|---|
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 instances and not on the larger internal structures. |
прокладка | 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. |
пытается | 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. |
обработчики | 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
Имя | Формат | Описание |
---|---|---|
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
Имя | Формат | Описание |
---|---|---|
размер | uleb128 | size of this list, in entries |
список | encoded_catch_handler[handlers_size] | actual list of handler lists, represented directly (not as offsets), and concatenated sequentially |
encoded_catch_handler format
Имя | Формат | Описание |
---|---|---|
размер | 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. |
обработчики | 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
Имя | Формат | Описание |
---|---|---|
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:
Имя | Формат | Описание |
---|---|---|
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:
Имя | Ценить | Формат | Arguments | Описание |
---|---|---|---|---|
DBG_END_SEQUENCE | 0x00 | (никто) | 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 localname_idx : string index of the nametype_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 localname_idx : string index of the nametype_idx : type index of the typesig_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 " |
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 | (никто) | 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 | (никто) | 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 | (никто) | 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
Имя | Формат | Описание |
---|---|---|
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
and method_id
instances must refer to the same defining class.
field_annotation format
Имя | Формат | Описание |
---|---|---|
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
Имя | Формат | Описание |
---|---|---|
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
Имя | Формат | Описание |
---|---|---|
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
Имя | Формат | Описание |
---|---|---|
размер | uint | size of the list, in entries |
список | annotation_set_ref_item[size] | elements of the list |
annotation_set_ref_item format
Имя | Формат | Описание |
---|---|---|
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
Имя | Формат | Описание |
---|---|---|
размер | 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
Имя | Формат | Описание |
---|---|---|
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)
Имя | Формат | Описание |
---|---|---|
видимость | 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
:
Имя | Ценить | Описание |
---|---|---|
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)
Имя | Формат | Описание |
---|---|---|
ценить | 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 .
Имя | Формат | Описание |
---|---|---|
размер | uint | total size of the section |
смещения | 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 . |
флаги | 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:
Имя | Ценить | Описание |
---|---|---|
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 . |
черный список | 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.
Имя | Формат | Описание |
---|---|---|
ценить | 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.
Имя | Формат | Описание |
---|---|---|
ценить | Сорт | 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.
Имя | Формат | Описание |
---|---|---|
ценить | Метод | 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.
Имя | Формат | Описание |
---|---|---|
имя | Нить | the originally declared simple name of this class (not including any package prefix). If this class is anonymous, then the name is null . |
accessFlags | интервал | 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.)
Имя | Формат | Описание |
---|---|---|
ценить | Сорт[] | 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.
Имя | Формат | Описание |
---|---|---|
имена | Нить[] | 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:
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.
Имя | Формат | Описание |
---|---|---|
ценить | Нить[] | 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.
Имя | Формат | Описание |
---|---|---|
ценить | Сорт[] | the array of exception types thrown |
This document describes the layout and contents of .dex
files, which are used to hold a set of class definitions and their associated adjunct data.
Guide to types
Имя | Описание |
---|---|
байт | 8-bit signed int |
ubyte | 8-bit unsigned int |
короткий | 16-bit signed int, little-endian |
ushort | 16-bit unsigned int, little-endian |
интервал | 32-bit signed int, little-endian |
uint | 32-bit unsigned int, little-endian |
длинный | 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 plus 1 , variable-length (see below) |
LEB128
LEB128 (" L ittle- E ndian B ase 128 ") is a variable-length encoding for arbitrary signed or unsigned integer quantities. The format was borrowed from the DWARF3 specification. In a .dex
file, 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 as 0
.
Bitwise diagram of a two-byte LEB128 value | |||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
First byte | Second byte | ||||||||||||||
1 | bit 6 | bit 5 | bit 4 | bit 3 | bit 2 | бит 1 | bit 0 | 0 | bit 13 | bit 12 | bit 11 | bit 10 | bit 9 | бит 8 | bit 7 |
The variant uleb128p1
is used to represent a signed value, where the representation is of the value plus one encoded as a uleb128
. This makes the encoding of -1
(alternatively thought of as the unsigned value 0xffffffff
) — 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
(or 0xffffffff
), 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 | As sleb128 | As uleb128 | As uleb128p1 |
---|---|---|---|
00 | 0 | 0 | -1 |
01 | 1 | 1 | 0 |
7f | -1 | 127 | 126 |
80 7f | -128 | 16256 | 16255 |
File layout
Имя | Формат | Описание |
---|---|---|
заголовок | 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 (eg, 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), and it must not contain any duplicate entries. |
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 by string_id index, and it must not contain any duplicate entries. |
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 (by type_id index) major order, and then by argument list (lexicographic ordering, individual arguments ordered by type_id index). The list must not contain any duplicate entries. |
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 (by type_id index) is the major order, field name (by string_id index) is the intermediate order, and type (by type_id index) is the minor order. The list must not contain any duplicate entries. |
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 (by type_id index) is the major order, method name (by string_id index) is the intermediate order, and method prototype (by proto_id index) is the minor order. The list must not contain any duplicate entries. |
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. Furthermore, it is invalid for a definition for the same-named class to appear more than once in the list. |
call_site_ids | call_site_id_item[] | call site identifiers list. These are identifiers for all call sites referred to by this file, whether defined in the file or not. This list must be sorted in ascending order of call_site_off . |
method_handles | method_handle_item[] | method handles list. A list of all method handles referred to by this file, whether defined in the file or not. This list is not sorted and may contain duplicates which will logically correspond to different method handle instances. |
данные | 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. |
Container format
Version 41 introduces a new container format for DEX data with the goal to save space. This container format allows several logical DEX files to be combined into a single physical file. The new format is mostly just naive concatenation of files in the previous format, with some differences:
- The
file_size
is the size of the logical file, not the physical file. It can be used to iterate over all the logical files in the container. - Logical dex files may reference any later data in the container (but not earlier). This allows dex files to share data, such as strings, between them.
- All offsets are relative to the physical file. No offset is relative to the header. This is ensures that sections with offsets can be shared between logical files.
- The header adds two new fields to describe the bounds of the container. This is an additional consistency check and makes porting code to the new format easier.
- The
data_size
anddata_off
are now unused. Data can be spread across multiple logical files and does not have to be contiguous.
Bitfield, string, and constant definitions
DEX_FILE_MAGIC
Embedded in header_item
The constant array/string DEX_FILE_MAGIC
is the list of bytes that must appear at the beginning of a .dex
file in order for it to be recognized as such. The value intentionally contains a newline ( "\n"
or 0x0a
) and a null byte ( "\0"
or 0x00
) 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 0x39 0x00 } = "dex\n039\0"
Note: Support for version 040
of the format was added in the Android 10.0 release, which extended the set of allowed characters in SimpleNames .
Note: Support for version 039
of the format was added in the Android 9.0 release, which introduced two new bytecodes, const-method-handle
and const-method-type
. (These are each described in the Summary of bytecode set table.) In Android 10, version 039
extends the DEX file format to include hidden API information that's only applicable to DEX files on the boot class path.
Note: Support for version 038
of the format was added in the Android 8.0 release. Version 038
added new bytecodes ( invoke-polymorphic
and invoke-custom
) and data for method handles.
Note: Support for version 037
of the format was added in the Android 7.0 release. Prior to version 037
most versions of Android have used version 035
of the format. The only difference between versions 035
and 037
is the addition of default methods and the adjustment of the invoke
.
Note: At least a couple earlier versions of the format have been used in widely available public software releases. For example, version 009
was used for the M3 releases of the Android platform (November–December 2007), and version 013
was 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_CONSTANT and REVERSE_ENDIAN_CONSTANT
Embedded in header_item
The constant ENDIAN_CONSTANT
is used to indicate the endianness of the file in which it is found. Although the standard .dex
format is little-endian, implementations may choose to perform byte-swapping. Should an implementation come across a header whose endian_tag
is REVERSE_ENDIAN_CONSTANT
instead of ENDIAN_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 in class_def_item and debug_info_item
The constant NO_INDEX
is used to indicate that an index value is absent.
Note: This value isn't defined to be 0
, because that is in fact typically a valid index.
The chosen value for NO_INDEX
is representable as a single byte in the uleb128p1
encoding.
uint NO_INDEX = 0xffffffff; // == -1 if treated as a signed int
access_flags definitions
Embedded in class_def_item, encoded_field, encoded_method, and InnerClass
Bitfields of these flags are used to indicate the accessibility and overall properties of classes and class members.
Имя | Ценить | For Classes (and InnerClass annotations) | 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 outer this reference | static : global to defining class | static : does not take a this argument |
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 when | ||
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 | declared synchronized .Note: This has no effect on execution (other than in reflection of this flag, per se). |
InnerClass
annotations, and must not ever be on in a class_def_item
.
Modified UTF-8 encoding
As a concession to easier legacy support, the .dex
format 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 range
U+10000
…U+10ffff
are encoded as a surrogate pair, each of which is represented as a three-byte encoded value. - The code point
U+0000
is encoded in two-byte form. - A plain null byte (value
0
) 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 point U+0000
in a string and still manipulate it as a C-style null-terminated string.
However, the special encoding of U+0000
means that, unlike normal UTF-8, the result of calling the standard C function strcmp()
on a pair of MUTF-8 strings does not always indicate the properly signed result of comparison of unequal strings. 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 to The Unicode Standard for further information about character encoding. MUTF-8 is actually closer to the (relatively less well-known) encoding CESU-8 than to UTF-8 per se.
encoded_value encoding
Embedded in annotation_element and encoded_array_item
An encoded_value
is an encoded piece of (nearly) arbitrary hierarchically structured data. The encoding is meant to be both compact and straightforward to parse.
Имя | Формат | Описание |
---|---|---|
(value_arg << 5) | value_type | ubyte | byte indicating the type of the immediately subsequent value along with an optional clarifying argument in the high-order three bits. See below for the various value definitions. In most cases, value_arg encodes the length of the immediately-subsequent value in bytes, as (size - 1) , eg, 0 means that the value requires one byte, and 7 means it requires eight bytes; however, there are exceptions as noted below. |
ценить | ubyte[] | bytes representing the value, variable in length and interpreted differently for different value_type bytes, though always little-endian. See the various value definitions below for details. |
Value formats
Type Name | value_type | value_arg Format | value Format | Описание |
---|---|---|---|---|
VALUE_BYTE | 0x00 | (none; must be 0 ) | 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-extended to 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-extended to the right , and interpreted as an IEEE754 64-bit floating point value |
VALUE_METHOD_TYPE | 0x15 | size - 1 (0…3) | ubyte[size] | unsigned (zero-extended) four-byte integer value, interpreted as an index into the proto_ids section and representing a method type value |
VALUE_METHOD_HANDLE | 0x16 | size - 1 (0…3) | ubyte[size] | unsigned (zero-extended) four-byte integer value, interpreted as an index into the method_handles section and representing a method handle value |
VALUE_STRING | 0x17 | size - 1 (0…3) | ubyte[size] | unsigned (zero-extended) four-byte integer value, interpreted as an index into the string_ids section 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 the type_ids section 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 the field_ids section 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 the method_ids section 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 the field_ids section and representing the value of an enumerated type constant |
VALUE_ARRAY | 0x1c | (none; must be 0 ) | encoded_array | an array of values, in the format specified by " encoded_array format" below. The size of the value is implicit in the encoding. |
VALUE_ANNOTATION | 0x1d | (none; must be 0 ) | encoded_annotation | a sub-annotation, in the format specified by " encoded_annotation format" below. The size of the value is implicit in the encoding. |
VALUE_NULL | 0x1e | (none; must be 0 ) | (никто) | null reference value |
VALUE_BOOLEAN | 0x1f | boolean (0…1) | (никто) | one-bit value; 0 for false and 1 for true . The bit is represented in the value_arg . |
encoded_array format
Имя | Формат | Описание |
---|---|---|
размер | uleb128 | number of elements in the array |
ценности | encoded_value[size] | a series of size encoded_value byte sequences in the format specified by this section, concatenated sequentially. |
encoded_annotation format
Имя | Формат | Описание |
---|---|---|
type_idx | uleb128 | type of the annotation. This must be a class (not array or primitive) type. |
размер | uleb128 | number of name-value mappings in this annotation |
элементы | annotation_element[size] | elements of the annotation, represented directly in-line (not as offsets). Elements must be sorted in increasing order by string_id index. |
annotation_element format
Имя | Формат | Описание |
---|---|---|
name_idx | uleb128 | element name, represented as an index into the string_ids section. The string must conform to the syntax for MemberName , defined above. |
ценить | encoded_value | element value |
String syntax
There are several kinds of item in a .dex
file which ultimately refer to a string. The following BNF-style definitions indicate the acceptable syntax for these strings.
SimpleName
A SimpleName is the basis for the syntax of the names of other things. The .dex
format allows a fair amount of latitude here (much more than most common source languages). In brief, a simple name consists 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. Starting from version 040
the format additionally allows space characters (Unicode Zs
category). Note that surrogate code points (in the range U+d800
… U+dfff
) are not considered valid name characters, per se, but Unicode supplemental characters are valid (which are represented by the final alternative of the rule for SimpleNameChar ), 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' | |
| | ' ' | since DEX version 040 |
| | '$' | |
| | '-' | |
| | '_' | |
| | U+00a0 | since DEX version 040 |
| | U+00a1 … U+1fff | |
| | U+2000 … U+200a | since DEX version 040 |
| | U+2010 … U+2027 | |
| | U+202f | since DEX version 040 |
| | U+2030 … U+d7ff | |
| | U+e000 … U+ffef | |
| | U+10000 … U+10ffff |
MemberName
used by field_id_item and method_id_item
A MemberName is the name of a member of a class, members being fields, methods, and inner classes.
MemberName → | |
SimpleName | |
| | '<' SimpleName '>' |
FullClassName
A FullClassName is a fully qualified class name, including an optional package specifier followed by a required name.
FullClassName → | |
OptionalPackagePrefix SimpleName | |
OptionalPackagePrefix → | |
( SimpleName '/' )* |
TypeDescriptor
Used by type_id_item
A TypeDescriptor is the representation of any type, including primitives, classes, arrays, and void
. 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 by proto_id_item
A ShortyDescriptor is 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' |
TypeDescriptor semantics
This is the meaning of each of the variants of TypeDescriptor .
Синтаксис | Значение |
---|---|
В | void ; only valid for return types |
З | boolean |
Б | byte |
С | short |
С | char |
я | int |
Дж | long |
Ф | float |
Д | double |
L fully/qualified/Name ; | the class fully.qualified.Name |
[ descriptor | array of descriptor , 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 .dex
file.
header_item
Appears in the header section
Alignment: 4 bytes
Имя | Формат | Описание |
---|---|---|
магия | 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 but magic and this field); used to detect file corruption |
подпись | ubyte[20] | SHA-1 signature (hash) of the rest of the file (everything but magic , checksum , and this field); used to uniquely identify files |
file_size | uint | size of the entire file (including the header), in bytes (v40 or earlier) distance in bytes from the start of this header to the next header or to the end of the whole file (the container). (v41 или позже) |
header_size | uint | 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. must be 0x70 (112) bytes (v40 or earlier) must be 0x78 (120) bytes (v41 or later) |
endian_tag | uint = ENDIAN_CONSTANT | endianness tag. See discussion above under " ENDIAN_CONSTANT and REVERSE_ENDIAN_CONSTANT " for more details. |
link_size | uint | size of the link section, or 0 if this file isn't statically linked |
link_off | uint | offset from the start of the file to the link section, or 0 if link_size == 0 . The offset, if non-zero, should be to an offset into the link_data section. 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. The offset, which must be non-zero, should be to an offset into the data section, 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, or 0 if string_ids_size == 0 (admittedly a strange edge case). The offset, if non-zero, should be to the start of the string_ids section. |
type_ids_size | uint | count of elements in the type identifiers list, at most 65535 |
type_ids_off | uint | offset from the start of the file to the type identifiers list, or 0 if type_ids_size == 0 (admittedly a strange edge case). The offset, if non-zero, should be to the start of the type_ids section. |
proto_ids_size | uint | count of elements in the prototype identifiers list, at most 65535 |
proto_ids_off | uint | offset from the start of the file to the prototype identifiers list, or 0 if proto_ids_size == 0 (admittedly a strange edge case). The offset, if non-zero, should be to the start of the proto_ids section. |
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, or 0 if field_ids_size == 0 . The offset, if non-zero, should be to the start of the field_ids section. |
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, or 0 if method_ids_size == 0 . The offset, if non-zero, should be to the start of the method_ids section. |
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, or 0 if class_defs_size == 0 (admittedly a strange edge case). The offset, if non-zero, should be to the start of the class_defs section. |
data_size | uint | Size of Unused (v41 or later) |
data_off | uint | offset from the start of the file to the start of the Unused (v41 or later) |
container_size | uint | this field does not exist. It can be assumed to be equal to size of the entire file (including other dex headers and their data). (v41 или позже) |
header_offset | uint | this field does not exist. It can be assumed to be equal to offset from the start of the file to the start of this header. (v41 или позже) |
map_list
Appears in the data section
Referenced from header_item
Alignment: 4 bytes
This is a list of the entire contents of a file, in order. It contains some redundancy with respect to the header_item
but is intended to be an easy form to use to iterate over an entire file. A given type must 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 (eg, a header
section must appear first, followed by a string_ids
section, etc.). Additionally, the map entries must be ordered by initial offset and must not overlap.
Имя | Формат | Описание |
---|---|---|
размер | uint | size of the list, in entries |
список | map_item[size] | elements of the list |
map_item format
Имя | Формат | Описание |
---|---|---|
тип | ushort | type of the items; see table below |
неиспользованный | ushort | (unused) |
размер | uint | count of the number of items to be found at the indicated offset |
компенсировать | uint | offset from the start of the file to the items in question |
Type codes
Item Type | Постоянный | Ценить | 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 |
call_site_id_item | TYPE_CALL_SITE_ID_ITEM | 0x0007 | 0x04 |
method_handle_item | TYPE_METHOD_HANDLE_ITEM | 0x0008 | 0x08 |
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 | скрытый; must parse |
code_item | TYPE_CODE_ITEM | 0x2001 | скрытый; must parse |
string_data_item | TYPE_STRING_DATA_ITEM | 0x2002 | скрытый; must parse |
debug_info_item | TYPE_DEBUG_INFO_ITEM | 0x2003 | скрытый; must parse |
annotation_item | TYPE_ANNOTATION_ITEM | 0x2004 | скрытый; must parse |
encoded_array_item | TYPE_ENCODED_ARRAY_ITEM | 0x2005 | скрытый; must parse |
annotations_directory_item | TYPE_ANNOTATIONS_DIRECTORY_ITEM | 0x2006 | скрытый; must parse |
hiddenapi_class_data_item | TYPE_HIDDENAPI_CLASS_DATA_ITEM | 0xF000 | скрытый; must parse |
string_id_item
Appears in the string_ids section
Alignment: 4 bytes
Имя | Формат | Описание |
---|---|---|
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 the data section, 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 the data section
Alignment: none (byte-aligned)
Имя | Формат | Описание |
---|---|---|
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 the 0 byte.) |
данные | ubyte[] | a series of MUTF-8 code units (aka octets, aka bytes) followed by a byte of value 0 . 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, |
type_id_item
Appears in the type_ids section
Alignment: 4 bytes
Имя | Формат | Описание |
---|---|---|
descriptor_idx | uint | index into the string_ids list for the descriptor string of this type. The string must conform to the syntax for TypeDescriptor , defined above. |
proto_id_item
Appears in the proto_ids section
Alignment: 4 bytes
Имя | Формат | Описание |
---|---|---|
shorty_idx | uint | index into the string_ids list for the short-form descriptor string of this prototype. The string must conform to the syntax for ShortyDescriptor , defined above, and must correspond to the return type and parameters of this item. |
return_type_idx | uint | index into the type_ids list 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, or 0 if this prototype has no parameters. This offset, if non-zero, should be in the data section, and the data there should be in the format specified by "type_list" below. Additionally, there should be no reference to the type void in the list. |
field_id_item
Appears in the field_ids section
Alignment: 4 bytes
Имя | Формат | Описание |
---|---|---|
class_idx | ushort | index into the type_ids list for the definer of this field. This must be a class type, and not an array or primitive type. |
type_idx | ushort | index into the type_ids list for the type of this field |
name_idx | uint | index into the string_ids list for the name of this field. The string must conform to the syntax for MemberName , defined above. |
method_id_item
Appears in the method_ids section
Alignment: 4 bytes
Имя | Формат | Описание |
---|---|---|
class_idx | ushort | index into the type_ids list for the definer of this method. This must be a class or array type, and not a primitive type. |
proto_idx | ushort | index into the proto_ids list for the prototype of this method |
name_idx | uint | index into the string_ids list for the name of this method. The string must conform to the syntax for MemberName , defined above. |
class_def_item
Appears in the class_defs section
Alignment: 4 bytes
Имя | Формат | Описание |
---|---|---|
class_idx | uint | index into the type_ids list 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_flags Definitions" for details. |
superclass_idx | uint | index into the type_ids list for the superclass, or the constant value NO_INDEX if this class has no superclass (ie, it is a root class such as Object ). 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, or 0 if there are none. This offset should be in the data section, 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 the string_ids list for the name of the file containing the original source for (at least most of) this class, or the special value NO_INDEX to represent a lack of this information. The debug_info_item of 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, or 0 if there are no annotations on this class. This offset, if non-zero, should be in the data section, 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, or 0 if 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 the data section, 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 for static fields, or 0 if there are none (and all static fields are to be initialized with 0 or null ). This offset should be in the data section, 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 of static fields declared by this class, and the elements correspond to the static fields in the same order as declared in the corresponding field_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 are static fields, then the leftover fields are initialized with a type-appropriate 0 or null . |
call_site_id_item
Appears in the call_site_ids section
Alignment: 4 bytes
Имя | Формат | Описание |
---|---|---|
call_site_off | uint | offset from the start of the file to call site definition. The offset should be in the data section, and the data there should be in the format specified by "call_site_item" below. |
call_site_item
Appears in the data section
Alignment: none (byte aligned)
The call_site_item is an encoded_array_item whose elements correspond to the arguments provided to a bootstrap linker method. The first three arguments are:
- A method handle representing the bootstrap linker method (VALUE_METHOD_HANDLE).
- A method name that the bootstrap linker should resolve (VALUE_STRING).
- 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:
-
java.lang.invoke.Lookup
-
java.lang.String
-
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
Имя | Формат | Описание |
---|---|---|
method_handle_type | ushort | type of the method handle; see table below |
неиспользованный | 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 |
неиспользованный | ushort | (unused) |
Method handle type codes
Постоянный | Ценить | Описание |
---|---|---|
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)
Имя | Формат | Описание |
---|---|---|
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
and method_id
instances must refer to the same defining class.
encoded_field format
Имя | Формат | Описание |
---|---|---|
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
Имя | Формат | Описание |
---|---|---|
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
Имя | Формат | Описание |
---|---|---|
размер | uint | size of the list, in entries |
список | type_item[size] | elements of the list |
type_item format
Имя | Формат | Описание |
---|---|---|
type_idx | ushort | index into the type_ids list |
code_item
Referenced from encoded_method
Appears in the data section
Alignment: 4 bytes
Имя | Формат | Описание |
---|---|---|
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 instances and not on the larger internal structures. |
прокладка | 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. |
пытается | 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. |
обработчики | 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
Имя | Формат | Описание |
---|---|---|
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
Имя | Формат | Описание |
---|---|---|
размер | uleb128 | size of this list, in entries |
список | encoded_catch_handler[handlers_size] | actual list of handler lists, represented directly (not as offsets), and concatenated sequentially |
encoded_catch_handler format
Имя | Формат | Описание |
---|---|---|
размер | 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. |
обработчики | 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
Имя | Формат | Описание |
---|---|---|
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:
Имя | Формат | Описание |
---|---|---|
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:
Имя | Ценить | Формат | Arguments | Описание |
---|---|---|---|---|
DBG_END_SEQUENCE | 0x00 | (никто) | 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 localname_idx : string index of the nametype_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 localname_idx : string index of the nametype_idx : type index of the typesig_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 " |
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 | (никто) | 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 | (никто) | 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 | (никто) | 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
Имя | Формат | Описание |
---|---|---|
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
and method_id
instances must refer to the same defining class.
field_annotation format
Имя | Формат | Описание |
---|---|---|
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
Имя | Формат | Описание |
---|---|---|
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
Имя | Формат | Описание |
---|---|---|
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
Имя | Формат | Описание |
---|---|---|
размер | uint | size of the list, in entries |
список | annotation_set_ref_item[size] | elements of the list |
annotation_set_ref_item format
Имя | Формат | Описание |
---|---|---|
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
Имя | Формат | Описание |
---|---|---|
размер | 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
Имя | Формат | Описание |
---|---|---|
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)
Имя | Формат | Описание |
---|---|---|
видимость | 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
:
Имя | Ценить | Описание |
---|---|---|
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)
Имя | Формат | Описание |
---|---|---|
ценить | 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 .
Имя | Формат | Описание |
---|---|---|
размер | uint | total size of the section |
смещения | 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 . |
флаги | 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:
Имя | Ценить | Описание |
---|---|---|
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 . |
черный список | 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.
Имя | Формат | Описание |
---|---|---|
ценить | 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.
Имя | Формат | Описание |
---|---|---|
ценить | Сорт | 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.
Имя | Формат | Описание |
---|---|---|
ценить | Метод | 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.
Имя | Формат | Описание |
---|---|---|
имя | Нить | the originally declared simple name of this class (not including any package prefix). If this class is anonymous, then the name is null . |
accessFlags | интервал | 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.)
Имя | Формат | Описание |
---|---|---|
ценить | Сорт[] | 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.
Имя | Формат | Описание |
---|---|---|
имена | Нить[] | 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:
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.
Имя | Формат | Описание |
---|---|---|
ценить | Нить[] | 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.
Имя | Формат | Описание |
---|---|---|
ценить | Сорт[] | the array of exception types thrown |
This document describes the layout and contents of .dex
files, which are used to hold a set of class definitions and their associated adjunct data.
Guide to types
Имя | Описание |
---|---|
байт | 8-bit signed int |
ubyte | 8-bit unsigned int |
короткий | 16-bit signed int, little-endian |
ushort | 16-bit unsigned int, little-endian |
интервал | 32-bit signed int, little-endian |
uint | 32-bit unsigned int, little-endian |
длинный | 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 plus 1 , variable-length (see below) |
LEB128
LEB128 (" L ittle- E ndian B ase 128 ") is a variable-length encoding for arbitrary signed or unsigned integer quantities. The format was borrowed from the DWARF3 specification. In a .dex
file, 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 as 0
.
Bitwise diagram of a two-byte LEB128 value | |||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
First byte | Second byte | ||||||||||||||
1 | bit 6 | bit 5 | bit 4 | bit 3 | bit 2 | бит 1 | bit 0 | 0 | bit 13 | bit 12 | bit 11 | bit 10 | bit 9 | бит 8 | bit 7 |
The variant uleb128p1
is used to represent a signed value, where the representation is of the value plus one encoded as a uleb128
. This makes the encoding of -1
(alternatively thought of as the unsigned value 0xffffffff
) — 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
(or 0xffffffff
), 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 | As sleb128 | As uleb128 | As uleb128p1 |
---|---|---|---|
00 | 0 | 0 | -1 |
01 | 1 | 1 | 0 |
7f | -1 | 127 | 126 |
80 7f | -128 | 16256 | 16255 |
File layout
Имя | Формат | Описание |
---|---|---|
заголовок | 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 (eg, 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), and it must not contain any duplicate entries. |
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 by string_id index, and it must not contain any duplicate entries. |
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 (by type_id index) major order, and then by argument list (lexicographic ordering, individual arguments ordered by type_id index). The list must not contain any duplicate entries. |
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 (by type_id index) is the major order, field name (by string_id index) is the intermediate order, and type (by type_id index) is the minor order. The list must not contain any duplicate entries. |
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 (by type_id index) is the major order, method name (by string_id index) is the intermediate order, and method prototype (by proto_id index) is the minor order. The list must not contain any duplicate entries. |
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. Furthermore, it is invalid for a definition for the same-named class to appear more than once in the list. |
call_site_ids | call_site_id_item[] | call site identifiers list. These are identifiers for all call sites referred to by this file, whether defined in the file or not. This list must be sorted in ascending order of call_site_off . |
method_handles | method_handle_item[] | method handles list. A list of all method handles referred to by this file, whether defined in the file or not. This list is not sorted and may contain duplicates which will logically correspond to different method handle instances. |
данные | 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. |
Container format
Version 41 introduces a new container format for DEX data with the goal to save space. This container format allows several logical DEX files to be combined into a single physical file. The new format is mostly just naive concatenation of files in the previous format, with some differences:
- The
file_size
is the size of the logical file, not the physical file. It can be used to iterate over all the logical files in the container. - Logical dex files may reference any later data in the container (but not earlier). This allows dex files to share data, such as strings, between them.
- All offsets are relative to the physical file. No offset is relative to the header. This is ensures that sections with offsets can be shared between logical files.
- The header adds two new fields to describe the bounds of the container. This is an additional consistency check and makes porting code to the new format easier.
- The
data_size
anddata_off
are now unused. Data can be spread across multiple logical files and does not have to be contiguous.
Bitfield, string, and constant definitions
DEX_FILE_MAGIC
Embedded in header_item
The constant array/string DEX_FILE_MAGIC
is the list of bytes that must appear at the beginning of a .dex
file in order for it to be recognized as such. The value intentionally contains a newline ( "\n"
or 0x0a
) and a null byte ( "\0"
or 0x00
) 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 0x39 0x00 } = "dex\n039\0"
Note: Support for version 040
of the format was added in the Android 10.0 release, which extended the set of allowed characters in SimpleNames .
Note: Support for version 039
of the format was added in the Android 9.0 release, which introduced two new bytecodes, const-method-handle
and const-method-type
. (These are each described in the Summary of bytecode set table.) In Android 10, version 039
extends the DEX file format to include hidden API information that's only applicable to DEX files on the boot class path.
Note: Support for version 038
of the format was added in the Android 8.0 release. Version 038
added new bytecodes ( invoke-polymorphic
and invoke-custom
) and data for method handles.
Note: Support for version 037
of the format was added in the Android 7.0 release. Prior to version 037
most versions of Android have used version 035
of the format. The only difference between versions 035
and 037
is the addition of default methods and the adjustment of the invoke
.
Note: At least a couple earlier versions of the format have been used in widely available public software releases. For example, version 009
was used for the M3 releases of the Android platform (November–December 2007), and version 013
was 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_CONSTANT and REVERSE_ENDIAN_CONSTANT
Embedded in header_item
The constant ENDIAN_CONSTANT
is used to indicate the endianness of the file in which it is found. Although the standard .dex
format is little-endian, implementations may choose to perform byte-swapping. Should an implementation come across a header whose endian_tag
is REVERSE_ENDIAN_CONSTANT
instead of ENDIAN_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 in class_def_item and debug_info_item
The constant NO_INDEX
is used to indicate that an index value is absent.
Note: This value isn't defined to be 0
, because that is in fact typically a valid index.
The chosen value for NO_INDEX
is representable as a single byte in the uleb128p1
encoding.
uint NO_INDEX = 0xffffffff; // == -1 if treated as a signed int
access_flags definitions
Embedded in class_def_item, encoded_field, encoded_method, and InnerClass
Bitfields of these flags are used to indicate the accessibility and overall properties of classes and class members.
Имя | Ценить | For Classes (and InnerClass annotations) | 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 outer this reference | static : global to defining class | static : does not take a this argument |
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 when | ||
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 | declared synchronized .Note: This has no effect on execution (other than in reflection of this flag, per se). |
InnerClass
annotations, and must not ever be on in a class_def_item
.
Modified UTF-8 encoding
As a concession to easier legacy support, the .dex
format 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 range
U+10000
…U+10ffff
are encoded as a surrogate pair, each of which is represented as a three-byte encoded value. - The code point
U+0000
is encoded in two-byte form. - A plain null byte (value
0
) 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 point U+0000
in a string and still manipulate it as a C-style null-terminated string.
However, the special encoding of U+0000
means that, unlike normal UTF-8, the result of calling the standard C function strcmp()
on a pair of MUTF-8 strings does not always indicate the properly signed result of comparison of unequal strings. 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 to The Unicode Standard for further information about character encoding. MUTF-8 is actually closer to the (relatively less well-known) encoding CESU-8 than to UTF-8 per se.
encoded_value encoding
Embedded in annotation_element and encoded_array_item
An encoded_value
is an encoded piece of (nearly) arbitrary hierarchically structured data. The encoding is meant to be both compact and straightforward to parse.
Имя | Формат | Описание |
---|---|---|
(value_arg << 5) | value_type | ubyte | byte indicating the type of the immediately subsequent value along with an optional clarifying argument in the high-order three bits. See below for the various value definitions. In most cases, value_arg encodes the length of the immediately-subsequent value in bytes, as (size - 1) , eg, 0 means that the value requires one byte, and 7 means it requires eight bytes; however, there are exceptions as noted below. |
ценить | ubyte[] | bytes representing the value, variable in length and interpreted differently for different value_type bytes, though always little-endian. See the various value definitions below for details. |
Value formats
Type Name | value_type | value_arg Format | value Format | Описание |
---|---|---|---|---|
VALUE_BYTE | 0x00 | (none; must be 0 ) | 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-extended to 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-extended to the right , and interpreted as an IEEE754 64-bit floating point value |
VALUE_METHOD_TYPE | 0x15 | size - 1 (0…3) | ubyte[size] | unsigned (zero-extended) four-byte integer value, interpreted as an index into the proto_ids section and representing a method type value |
VALUE_METHOD_HANDLE | 0x16 | size - 1 (0…3) | ubyte[size] | unsigned (zero-extended) four-byte integer value, interpreted as an index into the method_handles section and representing a method handle value |
VALUE_STRING | 0x17 | size - 1 (0…3) | ubyte[size] | unsigned (zero-extended) four-byte integer value, interpreted as an index into the string_ids section 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 the type_ids section 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 the field_ids section 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 the method_ids section 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 the field_ids section and representing the value of an enumerated type constant |
VALUE_ARRAY | 0x1c | (none; must be 0 ) | encoded_array | an array of values, in the format specified by " encoded_array format" below. The size of the value is implicit in the encoding. |
VALUE_ANNOTATION | 0x1d | (none; must be 0 ) | encoded_annotation | a sub-annotation, in the format specified by " encoded_annotation format" below. The size of the value is implicit in the encoding. |
VALUE_NULL | 0x1e | (none; must be 0 ) | (никто) | null reference value |
VALUE_BOOLEAN | 0x1f | boolean (0…1) | (никто) | one-bit value; 0 for false and 1 for true . The bit is represented in the value_arg . |
encoded_array format
Имя | Формат | Описание |
---|---|---|
размер | uleb128 | number of elements in the array |
ценности | encoded_value[size] | a series of size encoded_value byte sequences in the format specified by this section, concatenated sequentially. |
encoded_annotation format
Имя | Формат | Описание |
---|---|---|
type_idx | uleb128 | type of the annotation. This must be a class (not array or primitive) type. |
размер | uleb128 | number of name-value mappings in this annotation |
элементы | annotation_element[size] | elements of the annotation, represented directly in-line (not as offsets). Elements must be sorted in increasing order by string_id index. |
annotation_element format
Имя | Формат | Описание |
---|---|---|
name_idx | uleb128 | element name, represented as an index into the string_ids section. The string must conform to the syntax for MemberName , defined above. |
ценить | encoded_value | element value |
String syntax
There are several kinds of item in a .dex
file which ultimately refer to a string. The following BNF-style definitions indicate the acceptable syntax for these strings.
SimpleName
A SimpleName is the basis for the syntax of the names of other things. The .dex
format allows a fair amount of latitude here (much more than most common source languages). In brief, a simple name consists 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. Starting from version 040
the format additionally allows space characters (Unicode Zs
category). Note that surrogate code points (in the range U+d800
… U+dfff
) are not considered valid name characters, per se, but Unicode supplemental characters are valid (which are represented by the final alternative of the rule for SimpleNameChar ), 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' | |
| | ' ' | since DEX version 040 |
| | '$' | |
| | '-' | |
| | '_' | |
| | U+00a0 | since DEX version 040 |
| | U+00a1 … U+1fff | |
| | U+2000 … U+200a | since DEX version 040 |
| | U+2010 … U+2027 | |
| | U+202f | since DEX version 040 |
| | U+2030 … U+d7ff | |
| | U+e000 … U+ffef | |
| | U+10000 … U+10ffff |
MemberName
used by field_id_item and method_id_item
A MemberName is the name of a member of a class, members being fields, methods, and inner classes.
MemberName → | |
SimpleName | |
| | '<' SimpleName '>' |
FullClassName
A FullClassName is a fully qualified class name, including an optional package specifier followed by a required name.
FullClassName → | |
OptionalPackagePrefix SimpleName | |
OptionalPackagePrefix → | |
( SimpleName '/' )* |
TypeDescriptor
Used by type_id_item
A TypeDescriptor is the representation of any type, including primitives, classes, arrays, and void
. 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 by proto_id_item
A ShortyDescriptor is 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' |
TypeDescriptor semantics
This is the meaning of each of the variants of TypeDescriptor .
Синтаксис | Значение |
---|---|
В | void ; only valid for return types |
З | boolean |
Б | byte |
С | short |
С | char |
я | int |
Дж | long |
Ф | float |
Д | double |
L fully/qualified/Name ; | the class fully.qualified.Name |
[ descriptor | array of descriptor , 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 .dex
file.
header_item
Appears in the header section
Alignment: 4 bytes
Имя | Формат | Описание |
---|---|---|
магия | 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 but magic and this field); used to detect file corruption |
подпись | ubyte[20] | SHA-1 signature (hash) of the rest of the file (everything but magic , checksum , and this field); used to uniquely identify files |
file_size | uint | size of the entire file (including the header), in bytes (v40 or earlier) distance in bytes from the start of this header to the next header or to the end of the whole file (the container). (v41 или позже) |
header_size | uint | 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. must be 0x70 (112) bytes (v40 or earlier) must be 0x78 (120) bytes (v41 or later) |
endian_tag | uint = ENDIAN_CONSTANT | endianness tag. See discussion above under " ENDIAN_CONSTANT and REVERSE_ENDIAN_CONSTANT " for more details. |
link_size | uint | size of the link section, or 0 if this file isn't statically linked |
link_off | uint | offset from the start of the file to the link section, or 0 if link_size == 0 . The offset, if non-zero, should be to an offset into the link_data section. 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. The offset, which must be non-zero, should be to an offset into the data section, 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, or 0 if string_ids_size == 0 (admittedly a strange edge case). The offset, if non-zero, should be to the start of the string_ids section. |
type_ids_size | uint | count of elements in the type identifiers list, at most 65535 |
type_ids_off | uint | offset from the start of the file to the type identifiers list, or 0 if type_ids_size == 0 (admittedly a strange edge case). The offset, if non-zero, should be to the start of the type_ids section. |
proto_ids_size | uint | count of elements in the prototype identifiers list, at most 65535 |
proto_ids_off | uint | offset from the start of the file to the prototype identifiers list, or 0 if proto_ids_size == 0 (admittedly a strange edge case). The offset, if non-zero, should be to the start of the proto_ids section. |
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, or 0 if field_ids_size == 0 . The offset, if non-zero, should be to the start of the field_ids section. |
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, or 0 if method_ids_size == 0 . The offset, if non-zero, should be to the start of the method_ids section. |
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, or 0 if class_defs_size == 0 (admittedly a strange edge case). The offset, if non-zero, should be to the start of the class_defs section. |
data_size | uint | Size of Unused (v41 or later) |
data_off | uint | offset from the start of the file to the start of the Unused (v41 or later) |
container_size | uint | this field does not exist. It can be assumed to be equal to size of the entire file (including other dex headers and their data). (v41 или позже) |
header_offset | uint | this field does not exist. It can be assumed to be equal to offset from the start of the file to the start of this header. (v41 или позже) |
map_list
Appears in the data section
Referenced from header_item
Alignment: 4 bytes
This is a list of the entire contents of a file, in order. It contains some redundancy with respect to the header_item
but is intended to be an easy form to use to iterate over an entire file. A given type must 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 (eg, a header
section must appear first, followed by a string_ids
section, etc.). Additionally, the map entries must be ordered by initial offset and must not overlap.
Имя | Формат | Описание |
---|---|---|
размер | uint | size of the list, in entries |
список | map_item[size] | elements of the list |
map_item format
Имя | Формат | Описание |
---|---|---|
тип | ushort | type of the items; see table below |
неиспользованный | ushort | (unused) |
размер | uint | count of the number of items to be found at the indicated offset |
компенсировать | uint | offset from the start of the file to the items in question |
Type codes
Item Type | Постоянный | Ценить | 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 |
call_site_id_item | TYPE_CALL_SITE_ID_ITEM | 0x0007 | 0x04 |
method_handle_item | TYPE_METHOD_HANDLE_ITEM | 0x0008 | 0x08 |
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 | скрытый; must parse |
code_item | TYPE_CODE_ITEM | 0x2001 | скрытый; must parse |
string_data_item | TYPE_STRING_DATA_ITEM | 0x2002 | скрытый; must parse |
debug_info_item | TYPE_DEBUG_INFO_ITEM | 0x2003 | скрытый; must parse |
annotation_item | TYPE_ANNOTATION_ITEM | 0x2004 | скрытый; must parse |
encoded_array_item | TYPE_ENCODED_ARRAY_ITEM | 0x2005 | скрытый; must parse |
annotations_directory_item | TYPE_ANNOTATIONS_DIRECTORY_ITEM | 0x2006 | скрытый; must parse |
hiddenapi_class_data_item | TYPE_HIDDENAPI_CLASS_DATA_ITEM | 0xF000 | скрытый; must parse |
string_id_item
Appears in the string_ids section
Alignment: 4 bytes
Имя | Формат | Описание |
---|---|---|
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 the data section, 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 the data section
Alignment: none (byte-aligned)
Имя | Формат | Описание |
---|---|---|
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 the 0 byte.) |
данные | ubyte[] | a series of MUTF-8 code units (aka octets, aka bytes) followed by a byte of value 0 . 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, |
type_id_item
Appears in the type_ids section
Alignment: 4 bytes
Имя | Формат | Описание |
---|---|---|
descriptor_idx | uint | index into the string_ids list for the descriptor string of this type. The string must conform to the syntax for TypeDescriptor , defined above. |
proto_id_item
Appears in the proto_ids section
Alignment: 4 bytes
Имя | Формат | Описание |
---|---|---|
shorty_idx | uint | index into the string_ids list for the short-form descriptor string of this prototype. The string must conform to the syntax for ShortyDescriptor , defined above, and must correspond to the return type and parameters of this item. |
return_type_idx | uint | index into the type_ids list 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, or 0 if this prototype has no parameters. This offset, if non-zero, should be in the data section, and the data there should be in the format specified by "type_list" below. Additionally, there should be no reference to the type void in the list. |
field_id_item
Appears in the field_ids section
Alignment: 4 bytes
Имя | Формат | Описание |
---|---|---|
class_idx | ushort | index into the type_ids list for the definer of this field. This must be a class type, and not an array or primitive type. |
type_idx | ushort | index into the type_ids list for the type of this field |
name_idx | uint | index into the string_ids list for the name of this field. The string must conform to the syntax for MemberName , defined above. |
method_id_item
Appears in the method_ids section
Alignment: 4 bytes
Имя | Формат | Описание |
---|---|---|
class_idx | ushort | index into the type_ids list for the definer of this method. This must be a class or array type, and not a primitive type. |
proto_idx | ushort | index into the proto_ids list for the prototype of this method |
name_idx | uint | index into the string_ids list for the name of this method. The string must conform to the syntax for MemberName , defined above. |
class_def_item
Appears in the class_defs section
Alignment: 4 bytes
Имя | Формат | Описание |
---|---|---|
class_idx | uint | index into the type_ids list 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_flags Definitions" for details. |
superclass_idx | uint | index into the type_ids list for the superclass, or the constant value NO_INDEX if this class has no superclass (ie, it is a root class such as Object ). 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, or 0 if there are none. This offset should be in the data section, 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 the string_ids list for the name of the file containing the original source for (at least most of) this class, or the special value NO_INDEX to represent a lack of this information. The debug_info_item of 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, or 0 if there are no annotations on this class. This offset, if non-zero, should be in the data section, 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, or 0 if 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 the data section, 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 for static fields, or 0 if there are none (and all static fields are to be initialized with 0 or null ). This offset should be in the data section, 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 of static fields declared by this class, and the elements correspond to the static fields in the same order as declared in the corresponding field_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 are static fields, then the leftover fields are initialized with a type-appropriate 0 or null . |
call_site_id_item
Appears in the call_site_ids section
Alignment: 4 bytes
Имя | Формат | Описание |
---|---|---|
call_site_off | uint | offset from the start of the file to call site definition. The offset should be in the data section, and the data there should be in the format specified by "call_site_item" below. |
call_site_item
Appears in the data section
Alignment: none (byte aligned)
The call_site_item is an encoded_array_item whose elements correspond to the arguments provided to a bootstrap linker method. The first three arguments are:
- A method handle representing the bootstrap linker method (VALUE_METHOD_HANDLE).
- A method name that the bootstrap linker should resolve (VALUE_STRING).
- 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:
-
java.lang.invoke.Lookup
-
java.lang.String
-
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
Имя | Формат | Описание |
---|---|---|
method_handle_type | ushort | type of the method handle; see table below |
неиспользованный | 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 |
неиспользованный | ushort | (unused) |
Method handle type codes
Постоянный | Ценить | Описание |
---|---|---|
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)
Имя | Формат | Описание |
---|---|---|
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
and method_id
instances must refer to the same defining class.
encoded_field format
Имя | Формат | Описание |
---|---|---|
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
Имя | Формат | Описание |
---|---|---|
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
Имя | Формат | Описание |
---|---|---|
размер | uint | size of the list, in entries |
список | type_item[size] | elements of the list |
type_item format
Имя | Формат | Описание |
---|---|---|
type_idx | ushort | index into the type_ids list |
code_item
Referenced from encoded_method
Appears in the data section
Alignment: 4 bytes
Имя | Формат | Описание |
---|---|---|
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 instances and not on the larger internal structures. |
прокладка | 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. |
пытается | 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. |
обработчики | 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
Имя | Формат | Описание |
---|---|---|
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
Имя | Формат | Описание |
---|---|---|
размер | uleb128 | size of this list, in entries |
список | encoded_catch_handler[handlers_size] | actual list of handler lists, represented directly (not as offsets), and concatenated sequentially |
encoded_catch_handler format
Имя | Формат | Описание |
---|---|---|
размер | 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. |
обработчики | 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
Имя | Формат | Описание |
---|---|---|
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:
Имя | Формат | Описание |
---|---|---|
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:
Имя | Ценить | Формат | Arguments | Описание |
---|---|---|---|---|
DBG_END_SEQUENCE | 0x00 | (никто) | 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 localname_idx : string index of the nametype_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 localname_idx : string index of the nametype_idx : type index of the typesig_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 " |
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 | (никто) | 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 | (никто) | 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 | (никто) | 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
Имя | Формат | Описание |
---|---|---|
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
and method_id
instances must refer to the same defining class.
field_annotation format
Имя | Формат | Описание |
---|---|---|
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
Имя | Формат | Описание |
---|---|---|
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
Имя | Формат | Описание |
---|---|---|
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
Имя | Формат | Описание |
---|---|---|
размер | uint | size of the list, in entries |
список | annotation_set_ref_item[size] | elements of the list |
annotation_set_ref_item format
Имя | Формат | Описание |
---|---|---|
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
Имя | Формат | Описание |
---|---|---|
размер | 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
Имя | Формат | Описание |
---|---|---|
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)
Имя | Формат | Описание |
---|---|---|
видимость | 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
:
Имя | Ценить | Описание |
---|---|---|
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)
Имя | Формат | Описание |
---|---|---|
ценить | 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 .
Имя | Формат | Описание |
---|---|---|
размер | uint | total size of the section |
смещения | 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 . |
флаги | 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:
Имя | Ценить | Описание |
---|---|---|
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 . |
черный список | 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.
Имя | Формат | Описание |
---|---|---|
ценить | 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.
Имя | Формат | Описание |
---|---|---|
ценить | Сорт | 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.
Имя | Формат | Описание |
---|---|---|
ценить | Метод | 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.
Имя | Формат | Описание |
---|---|---|
имя | Нить | the originally declared simple name of this class (not including any package prefix). If this class is anonymous, then the name is null . |
accessFlags | интервал | 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.)
Имя | Формат | Описание |
---|---|---|
ценить | Сорт[] | 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.
Имя | Формат | Описание |
---|---|---|
имена | Нить[] | 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:
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.
Имя | Формат | Описание |
---|---|---|
ценить | Нить[] | 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.
Имя | Формат | Описание |
---|---|---|
ценить | Сорт[] | the array of exception types thrown |