blob: f376c4dc7b0f2a00cbaf60c32df24a8869b52133 [file] [log] [blame]
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "dex_file_verifier.h"
#include <inttypes.h>
#include <memory>
#include "android-base/stringprintf.h"
#include "base/leb128.h"
#include "class_accessor-inl.h"
#include "code_item_accessors-inl.h"
#include "descriptors_names.h"
#include "dex_file-inl.h"
#include "modifiers.h"
#include "utf-inl.h"
namespace art {
using android::base::StringAppendV;
using android::base::StringPrintf;
static constexpr uint32_t kTypeIdLimit = std::numeric_limits<uint16_t>::max();
static bool IsValidOrNoTypeId(uint16_t low, uint16_t high) {
return (high == 0) || ((high == 0xffffU) && (low == 0xffffU));
}
static bool IsValidTypeId(uint16_t low ATTRIBUTE_UNUSED, uint16_t high) {
return (high == 0);
}
static uint32_t MapTypeToBitMask(DexFile::MapItemType map_item_type) {
switch (map_item_type) {
case DexFile::kDexTypeHeaderItem: return 1 << 0;
case DexFile::kDexTypeStringIdItem: return 1 << 1;
case DexFile::kDexTypeTypeIdItem: return 1 << 2;
case DexFile::kDexTypeProtoIdItem: return 1 << 3;
case DexFile::kDexTypeFieldIdItem: return 1 << 4;
case DexFile::kDexTypeMethodIdItem: return 1 << 5;
case DexFile::kDexTypeClassDefItem: return 1 << 6;
case DexFile::kDexTypeCallSiteIdItem: return 1 << 7;
case DexFile::kDexTypeMethodHandleItem: return 1 << 8;
case DexFile::kDexTypeMapList: return 1 << 9;
case DexFile::kDexTypeTypeList: return 1 << 10;
case DexFile::kDexTypeAnnotationSetRefList: return 1 << 11;
case DexFile::kDexTypeAnnotationSetItem: return 1 << 12;
case DexFile::kDexTypeClassDataItem: return 1 << 13;
case DexFile::kDexTypeCodeItem: return 1 << 14;
case DexFile::kDexTypeStringDataItem: return 1 << 15;
case DexFile::kDexTypeDebugInfoItem: return 1 << 16;
case DexFile::kDexTypeAnnotationItem: return 1 << 17;
case DexFile::kDexTypeEncodedArrayItem: return 1 << 18;
case DexFile::kDexTypeAnnotationsDirectoryItem: return 1 << 19;
case DexFile::kDexTypeHiddenapiClassData: return 1 << 20;
}
return 0;
}
static bool IsDataSectionType(DexFile::MapItemType map_item_type) {
switch (map_item_type) {
case DexFile::kDexTypeHeaderItem:
case DexFile::kDexTypeStringIdItem:
case DexFile::kDexTypeTypeIdItem:
case DexFile::kDexTypeProtoIdItem:
case DexFile::kDexTypeFieldIdItem:
case DexFile::kDexTypeMethodIdItem:
case DexFile::kDexTypeClassDefItem:
return false;
case DexFile::kDexTypeCallSiteIdItem:
case DexFile::kDexTypeMethodHandleItem:
case DexFile::kDexTypeMapList:
case DexFile::kDexTypeTypeList:
case DexFile::kDexTypeAnnotationSetRefList:
case DexFile::kDexTypeAnnotationSetItem:
case DexFile::kDexTypeClassDataItem:
case DexFile::kDexTypeCodeItem:
case DexFile::kDexTypeStringDataItem:
case DexFile::kDexTypeDebugInfoItem:
case DexFile::kDexTypeAnnotationItem:
case DexFile::kDexTypeEncodedArrayItem:
case DexFile::kDexTypeAnnotationsDirectoryItem:
case DexFile::kDexTypeHiddenapiClassData:
return true;
}
return true;
}
const char* DexFileVerifier::CheckLoadStringByIdx(dex::StringIndex idx, const char* error_string) {
if (UNLIKELY(!CheckIndex(idx.index_, dex_file_->NumStringIds(), error_string))) {
return nullptr;
}
return dex_file_->StringDataByIdx(idx);
}
const char* DexFileVerifier::CheckLoadStringByTypeIdx(dex::TypeIndex type_idx,
const char* error_string) {
if (UNLIKELY(!CheckIndex(type_idx.index_, dex_file_->NumTypeIds(), error_string))) {
return nullptr;
}
return CheckLoadStringByIdx(dex_file_->GetTypeId(type_idx).descriptor_idx_, error_string);
}
const dex::FieldId* DexFileVerifier::CheckLoadFieldId(uint32_t idx, const char* error_string) {
if (UNLIKELY(!CheckIndex(idx, dex_file_->NumFieldIds(), error_string))) {
return nullptr;
}
return &dex_file_->GetFieldId(idx);
}
const dex::MethodId* DexFileVerifier::CheckLoadMethodId(uint32_t idx, const char* err_string) {
if (UNLIKELY(!CheckIndex(idx, dex_file_->NumMethodIds(), err_string))) {
return nullptr;
}
return &dex_file_->GetMethodId(idx);
}
const dex::ProtoId* DexFileVerifier::CheckLoadProtoId(dex::ProtoIndex idx,
const char* err_string) {
if (UNLIKELY(!CheckIndex(idx.index_, dex_file_->NumProtoIds(), err_string))) {
return nullptr;
}
return &dex_file_->GetProtoId(idx);
}
// Helper macro to load string and return false on error.
#define LOAD_STRING(var, idx, error) \
const char* (var) = CheckLoadStringByIdx(idx, error); \
if (UNLIKELY((var) == nullptr)) { \
return false; \
}
// Helper macro to load string by type idx and return false on error.
#define LOAD_STRING_BY_TYPE(var, type_idx, error) \
const char* (var) = CheckLoadStringByTypeIdx(type_idx, error); \
if (UNLIKELY((var) == nullptr)) { \
return false; \
}
// Helper macro to load method id. Return last parameter on error.
#define LOAD_METHOD(var, idx, error_string, error_stmt) \
const dex::MethodId* (var) = CheckLoadMethodId(idx, error_string); \
if (UNLIKELY((var) == nullptr)) { \
error_stmt; \
}
// Helper macro to load method id. Return last parameter on error.
#define LOAD_FIELD(var, idx, fmt, error_stmt) \
const dex::FieldId* (var) = CheckLoadFieldId(idx, fmt); \
if (UNLIKELY((var) == nullptr)) { \
error_stmt; \
}
bool DexFileVerifier::Verify(const DexFile* dex_file,
const uint8_t* begin,
size_t size,
const char* location,
bool verify_checksum,
std::string* error_msg) {
std::unique_ptr<DexFileVerifier> verifier(
new DexFileVerifier(dex_file, begin, size, location, verify_checksum));
if (!verifier->Verify()) {
*error_msg = verifier->FailureReason();
return false;
}
return true;
}
bool DexFileVerifier::CheckShortyDescriptorMatch(char shorty_char, const char* descriptor,
bool is_return_type) {
switch (shorty_char) {
case 'V':
if (UNLIKELY(!is_return_type)) {
ErrorStringPrintf("Invalid use of void");
return false;
}
FALLTHROUGH_INTENDED;
case 'B':
case 'C':
case 'D':
case 'F':
case 'I':
case 'J':
case 'S':
case 'Z':
if (UNLIKELY((descriptor[0] != shorty_char) || (descriptor[1] != '\0'))) {
ErrorStringPrintf("Shorty vs. primitive type mismatch: '%c', '%s'",
shorty_char, descriptor);
return false;
}
break;
case 'L':
if (UNLIKELY((descriptor[0] != 'L') && (descriptor[0] != '['))) {
ErrorStringPrintf("Shorty vs. type mismatch: '%c', '%s'", shorty_char, descriptor);
return false;
}
break;
default:
ErrorStringPrintf("Bad shorty character: '%c'", shorty_char);
return false;
}
return true;
}
bool DexFileVerifier::CheckListSize(const void* start, size_t count, size_t elem_size,
const char* label) {
// Check that size is not 0.
CHECK_NE(elem_size, 0U);
const uint8_t* range_start = reinterpret_cast<const uint8_t*>(start);
const uint8_t* file_start = reinterpret_cast<const uint8_t*>(begin_);
// Check for overflow.
uintptr_t max = 0 - 1;
size_t available_bytes_till_end_of_mem = max - reinterpret_cast<uintptr_t>(start);
size_t max_count = available_bytes_till_end_of_mem / elem_size;
if (max_count < count) {
ErrorStringPrintf("Overflow in range for %s: %zx for %zu@%zu", label,
static_cast<size_t>(range_start - file_start),
count, elem_size);
return false;
}
const uint8_t* range_end = range_start + count * elem_size;
const uint8_t* file_end = file_start + size_;
if (UNLIKELY((range_start < file_start) || (range_end > file_end))) {
// Note: these two tests are enough as we make sure above that there's no overflow.
ErrorStringPrintf("Bad range for %s: %zx to %zx", label,
static_cast<size_t>(range_start - file_start),
static_cast<size_t>(range_end - file_start));
return false;
}
return true;
}
bool DexFileVerifier::CheckList(size_t element_size, const char* label, const uint8_t* *ptr) {
// Check that the list is available. The first 4B are the count.
if (!CheckListSize(*ptr, 1, 4U, label)) {
return false;
}
uint32_t count = *reinterpret_cast<const uint32_t*>(*ptr);
if (count > 0) {
if (!CheckListSize(*ptr + 4, count, element_size, label)) {
return false;
}
}
*ptr += 4 + count * element_size;
return true;
}
bool DexFileVerifier::CheckIndex(uint32_t field, uint32_t limit, const char* label) {
if (UNLIKELY(field >= limit)) {
ErrorStringPrintf("Bad index for %s: %x >= %x", label, field, limit);
return false;
}
return true;
}
bool DexFileVerifier::CheckValidOffsetAndSize(uint32_t offset,
uint32_t size,
size_t alignment,
const char* label) {
if (size == 0) {
if (offset != 0) {
ErrorStringPrintf("Offset(%d) should be zero when size is zero for %s.", offset, label);
return false;
}
}
if (size_ <= offset) {
ErrorStringPrintf("Offset(%d) should be within file size(%zu) for %s.", offset, size_, label);
return false;
}
if (alignment != 0 && !IsAlignedParam(offset, alignment)) {
ErrorStringPrintf("Offset(%d) should be aligned by %zu for %s.", offset, alignment, label);
return false;
}
return true;
}
bool DexFileVerifier::CheckSizeLimit(uint32_t size, uint32_t limit, const char* label) {
if (size > limit) {
ErrorStringPrintf("Size(%u) should not exceed limit(%u) for %s.", size, limit, label);
return false;
}
return true;
}
bool DexFileVerifier::CheckHeader() {
// Check file size from the header.
uint32_t expected_size = header_->file_size_;
if (size_ != expected_size) {
ErrorStringPrintf("Bad file size (%zd, expected %u)", size_, expected_size);
return false;
}
uint32_t adler_checksum = dex_file_->CalculateChecksum();
// Compute and verify the checksum in the header.
if (adler_checksum != header_->checksum_) {
if (verify_checksum_) {
ErrorStringPrintf("Bad checksum (%08x, expected %08x)", adler_checksum, header_->checksum_);
return false;
} else {
LOG(WARNING) << StringPrintf(
"Ignoring bad checksum (%08x, expected %08x)", adler_checksum, header_->checksum_);
}
}
// Check the contents of the header.
if (header_->endian_tag_ != DexFile::kDexEndianConstant) {
ErrorStringPrintf("Unexpected endian_tag: %x", header_->endian_tag_);
return false;
}
const uint32_t expected_header_size = dex_file_->IsCompactDexFile()
? sizeof(CompactDexFile::Header)
: sizeof(StandardDexFile::Header);
if (header_->header_size_ != expected_header_size) {
ErrorStringPrintf("Bad header size: %ud expected %ud",
header_->header_size_,
expected_header_size);
return false;
}
// Check that all offsets are inside the file.
bool result =
CheckValidOffsetAndSize(header_->link_off_,
header_->link_size_,
/* alignment= */ 0,
"link") &&
CheckValidOffsetAndSize(header_->map_off_,
header_->map_off_,
/* alignment= */ 4,
"map") &&
CheckValidOffsetAndSize(header_->string_ids_off_,
header_->string_ids_size_,
/* alignment= */ 4,
"string-ids") &&
CheckValidOffsetAndSize(header_->type_ids_off_,
header_->type_ids_size_,
/* alignment= */ 4,
"type-ids") &&
CheckSizeLimit(header_->type_ids_size_, DexFile::kDexNoIndex16, "type-ids") &&
CheckValidOffsetAndSize(header_->proto_ids_off_,
header_->proto_ids_size_,
/* alignment= */ 4,
"proto-ids") &&
CheckSizeLimit(header_->proto_ids_size_, DexFile::kDexNoIndex16, "proto-ids") &&
CheckValidOffsetAndSize(header_->field_ids_off_,
header_->field_ids_size_,
/* alignment= */ 4,
"field-ids") &&
CheckValidOffsetAndSize(header_->method_ids_off_,
header_->method_ids_size_,
/* alignment= */ 4,
"method-ids") &&
CheckValidOffsetAndSize(header_->class_defs_off_,
header_->class_defs_size_,
/* alignment= */ 4,
"class-defs") &&
CheckValidOffsetAndSize(header_->data_off_,
header_->data_size_,
// Unaligned, spec doesn't talk about it, even though size
// is supposed to be a multiple of 4.
/* alignment= */ 0,
"data");
return result;
}
bool DexFileVerifier::CheckMap() {
const dex::MapList* map = reinterpret_cast<const dex::MapList*>(begin_ + header_->map_off_);
// Check that map list content is available.
if (!CheckListSize(map, 1, sizeof(dex::MapList), "maplist content")) {
return false;
}
const dex::MapItem* item = map->list_;
uint32_t count = map->size_;
uint32_t last_offset = 0;
uint32_t last_type = 0;
uint32_t data_item_count = 0;
uint32_t data_items_left = header_->data_size_;
uint32_t used_bits = 0;
// Sanity check the size of the map list.
if (!CheckListSize(item, count, sizeof(dex::MapItem), "map size")) {
return false;
}
// Check the items listed in the map.
for (uint32_t i = 0; i < count; i++) {
if (UNLIKELY(last_offset >= item->offset_ && i != 0)) {
ErrorStringPrintf("Out of order map item: %x then %x for type %x last type was %x",
last_offset,
item->offset_,
static_cast<uint32_t>(item->type_),
last_type);
return false;
}
if (UNLIKELY(item->offset_ >= header_->file_size_)) {
ErrorStringPrintf("Map item after end of file: %x, size %x",
item->offset_, header_->file_size_);
return false;
}
DexFile::MapItemType item_type = static_cast<DexFile::MapItemType>(item->type_);
if (IsDataSectionType(item_type)) {
uint32_t icount = item->size_;
if (UNLIKELY(icount > data_items_left)) {
ErrorStringPrintf("Too many items in data section: %ud item_type %zx",
data_item_count + icount,
static_cast<size_t>(item_type));
return false;
}
data_items_left -= icount;
data_item_count += icount;
}
uint32_t bit = MapTypeToBitMask(item_type);
if (UNLIKELY(bit == 0)) {
ErrorStringPrintf("Unknown map section type %x", item->type_);
return false;
}
if (UNLIKELY((used_bits & bit) != 0)) {
ErrorStringPrintf("Duplicate map section of type %x", item->type_);
return false;
}
used_bits |= bit;
last_offset = item->offset_;
last_type = item->type_;
item++;
}
// Check for missing sections in the map.
if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeHeaderItem)) == 0)) {
ErrorStringPrintf("Map is missing header entry");
return false;
}
if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeMapList)) == 0)) {
ErrorStringPrintf("Map is missing map_list entry");
return false;
}
if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeStringIdItem)) == 0 &&
((header_->string_ids_off_ != 0) || (header_->string_ids_size_ != 0)))) {
ErrorStringPrintf("Map is missing string_ids entry");
return false;
}
if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeTypeIdItem)) == 0 &&
((header_->type_ids_off_ != 0) || (header_->type_ids_size_ != 0)))) {
ErrorStringPrintf("Map is missing type_ids entry");
return false;
}
if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeProtoIdItem)) == 0 &&
((header_->proto_ids_off_ != 0) || (header_->proto_ids_size_ != 0)))) {
ErrorStringPrintf("Map is missing proto_ids entry");
return false;
}
if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeFieldIdItem)) == 0 &&
((header_->field_ids_off_ != 0) || (header_->field_ids_size_ != 0)))) {
ErrorStringPrintf("Map is missing field_ids entry");
return false;
}
if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeMethodIdItem)) == 0 &&
((header_->method_ids_off_ != 0) || (header_->method_ids_size_ != 0)))) {
ErrorStringPrintf("Map is missing method_ids entry");
return false;
}
if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeClassDefItem)) == 0 &&
((header_->class_defs_off_ != 0) || (header_->class_defs_size_ != 0)))) {
ErrorStringPrintf("Map is missing class_defs entry");
return false;
}
return true;
}
uint32_t DexFileVerifier::ReadUnsignedLittleEndian(uint32_t size) {
uint32_t result = 0;
if (LIKELY(CheckListSize(ptr_, size, sizeof(uint8_t), "encoded_value"))) {
for (uint32_t i = 0; i < size; i++) {
result |= ((uint32_t) *(ptr_++)) << (i * 8);
}
}
return result;
}
#define DECODE_UNSIGNED_CHECKED_FROM_WITH_ERROR_VALUE(ptr, var, error_value) \
uint32_t var; \
if (!DecodeUnsignedLeb128Checked(&(ptr), begin_ + size_, &(var))) { \
return error_value; \
}
#define DECODE_UNSIGNED_CHECKED_FROM(ptr, var) \
uint32_t var; \
if (!DecodeUnsignedLeb128Checked(&(ptr), begin_ + size_, &(var))) { \
ErrorStringPrintf("Read out of bounds"); \
return false; \
}
#define DECODE_SIGNED_CHECKED_FROM(ptr, var) \
int32_t var; \
if (!DecodeSignedLeb128Checked(&(ptr), begin_ + size_, &(var))) { \
ErrorStringPrintf("Read out of bounds"); \
return false; \
}
bool DexFileVerifier::CheckAndGetHandlerOffsets(const dex::CodeItem* code_item,
uint32_t* handler_offsets,
uint32_t handlers_size) {
CodeItemDataAccessor accessor(*dex_file_, code_item);
const uint8_t* handlers_base = accessor.GetCatchHandlerData();
for (uint32_t i = 0; i < handlers_size; i++) {
bool catch_all;
size_t offset = ptr_ - handlers_base;
DECODE_SIGNED_CHECKED_FROM(ptr_, size);
if (UNLIKELY((size < -65536) || (size > 65536))) {
ErrorStringPrintf("Invalid exception handler size: %d", size);
return false;
}
if (size <= 0) {
catch_all = true;
size = -size;
} else {
catch_all = false;
}
handler_offsets[i] = static_cast<uint32_t>(offset);
while (size-- > 0) {
DECODE_UNSIGNED_CHECKED_FROM(ptr_, type_idx);
if (!CheckIndex(type_idx, header_->type_ids_size_, "handler type_idx")) {
return false;
}
DECODE_UNSIGNED_CHECKED_FROM(ptr_, addr);
if (UNLIKELY(addr >= accessor.InsnsSizeInCodeUnits())) {
ErrorStringPrintf("Invalid handler addr: %x", addr);
return false;
}
}
if (catch_all) {
DECODE_UNSIGNED_CHECKED_FROM(ptr_, addr);
if (UNLIKELY(addr >= accessor.InsnsSizeInCodeUnits())) {
ErrorStringPrintf("Invalid handler catch_all_addr: %x", addr);
return false;
}
}
}
return true;
}
bool DexFileVerifier::CheckClassDataItemField(uint32_t idx,
uint32_t access_flags,
uint32_t class_access_flags,
dex::TypeIndex class_type_index,
bool expect_static) {
// Check for overflow.
if (!CheckIndex(idx, header_->field_ids_size_, "class_data_item field_idx")) {
return false;
}
// Check that it's the right class.
dex::TypeIndex my_class_index =
(reinterpret_cast<const dex::FieldId*>(begin_ + header_->field_ids_off_) + idx)->class_idx_;
if (class_type_index != my_class_index) {
ErrorStringPrintf("Field's class index unexpected, %" PRIu16 "vs %" PRIu16,
my_class_index.index_,
class_type_index.index_);
return false;
}
// Check that it falls into the right class-data list.
bool is_static = (access_flags & kAccStatic) != 0;
if (UNLIKELY(is_static != expect_static)) {
ErrorStringPrintf("Static/instance field not in expected list");
return false;
}
// Check field access flags.
std::string error_msg;
if (!CheckFieldAccessFlags(idx, access_flags, class_access_flags, &error_msg)) {
ErrorStringPrintf("%s", error_msg.c_str());
return false;
}
return true;
}
bool DexFileVerifier::CheckClassDataItemMethod(uint32_t idx,
uint32_t access_flags,
uint32_t class_access_flags,
dex::TypeIndex class_type_index,
uint32_t code_offset,
ClassAccessor::Method* direct_method,
size_t* remaining_directs) {
// Check for overflow.
if (!CheckIndex(idx, header_->method_ids_size_, "class_data_item method_idx")) {
return false;
}
const dex::MethodId& method_id =
*(reinterpret_cast<const dex::MethodId*>(begin_ + header_->method_ids_off_) + idx);
// Check that it's the right class.
dex::TypeIndex my_class_index = method_id.class_idx_;
if (class_type_index != my_class_index) {
ErrorStringPrintf("Method's class index unexpected, %" PRIu16 " vs %" PRIu16,
my_class_index.index_,
class_type_index.index_);
return false;
}
// For virtual methods, we cross reference the method index to make sure it doesn't match any
// direct methods.
const bool expect_direct = direct_method == nullptr;
if (!expect_direct && *remaining_directs > 0) {
// The direct methods are already known to be in ascending index order. So just keep up
// with the current index.
while (true) {
const uint32_t direct_idx = direct_method->GetIndex();
if (direct_idx > idx) {
break;
}
if (direct_idx == idx) {
ErrorStringPrintf("Found virtual method with same index as direct method: %d", idx);
return false;
}
--*remaining_directs;
if (*remaining_directs == 0u) {
break;
}
direct_method->Read();
}
}
std::string error_msg;
uint32_t constructor_flags_by_name = 0;
{
uint32_t string_idx = method_id.name_idx_.index_;
if (!CheckIndex(string_idx, header_->string_ids_size_, "method flags verification")) {
return false;
}
if (UNLIKELY(string_idx < angle_bracket_end_index_) &&
string_idx >= angle_bracket_start_index_) {
if (string_idx == angle_clinit_angle_index_) {
constructor_flags_by_name = kAccStatic | kAccConstructor;
} else if (string_idx == angle_init_angle_index_) {
constructor_flags_by_name = kAccConstructor;
} else {
ErrorStringPrintf("Bad method name for method index %u", idx);
return false;
}
}
}
bool has_code = (code_offset != 0);
if (!CheckMethodAccessFlags(idx,
access_flags,
class_access_flags,
constructor_flags_by_name,
has_code,
expect_direct,
&error_msg)) {
ErrorStringPrintf("%s", error_msg.c_str());
return false;
}
if (constructor_flags_by_name != 0) {
if (!CheckConstructorProperties(idx, constructor_flags_by_name)) {
DCHECK(FailureReasonIsSet());
return false;
}
}
return true;
}
bool DexFileVerifier::CheckPadding(size_t offset,
uint32_t aligned_offset,
DexFile::MapItemType type) {
if (offset < aligned_offset) {
if (!CheckListSize(begin_ + offset, aligned_offset - offset, sizeof(uint8_t), "section")) {
return false;
}
while (offset < aligned_offset) {
if (UNLIKELY(*ptr_ != '\0')) {
ErrorStringPrintf("Non-zero padding %x before section of type %zu at offset 0x%zx",
*ptr_,
static_cast<size_t>(type),
offset);
return false;
}
ptr_++;
offset++;
}
}
return true;
}
bool DexFileVerifier::CheckEncodedValue() {
if (!CheckListSize(ptr_, 1, sizeof(uint8_t), "encoded_value header")) {
return false;
}
uint8_t header_byte = *(ptr_++);
uint32_t value_type = header_byte & DexFile::kDexAnnotationValueTypeMask;
uint32_t value_arg = header_byte >> DexFile::kDexAnnotationValueArgShift;
switch (value_type) {
case DexFile::kDexAnnotationByte:
if (UNLIKELY(value_arg != 0)) {
ErrorStringPrintf("Bad encoded_value byte size %x", value_arg);
return false;
}
ptr_++;
break;
case DexFile::kDexAnnotationShort:
case DexFile::kDexAnnotationChar:
if (UNLIKELY(value_arg > 1)) {
ErrorStringPrintf("Bad encoded_value char/short size %x", value_arg);
return false;
}
ptr_ += value_arg + 1;
break;
case DexFile::kDexAnnotationInt:
case DexFile::kDexAnnotationFloat:
if (UNLIKELY(value_arg > 3)) {
ErrorStringPrintf("Bad encoded_value int/float size %x", value_arg);
return false;
}
ptr_ += value_arg + 1;
break;
case DexFile::kDexAnnotationLong:
case DexFile::kDexAnnotationDouble:
ptr_ += value_arg + 1;
break;
case DexFile::kDexAnnotationString: {
if (UNLIKELY(value_arg > 3)) {
ErrorStringPrintf("Bad encoded_value string size %x", value_arg);
return false;
}
uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
if (!CheckIndex(idx, header_->string_ids_size_, "encoded_value string")) {
return false;
}
break;
}
case DexFile::kDexAnnotationType: {
if (UNLIKELY(value_arg > 3)) {
ErrorStringPrintf("Bad encoded_value type size %x", value_arg);
return false;
}
uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
if (!CheckIndex(idx, header_->type_ids_size_, "encoded_value type")) {
return false;
}
break;
}
case DexFile::kDexAnnotationField:
case DexFile::kDexAnnotationEnum: {
if (UNLIKELY(value_arg > 3)) {
ErrorStringPrintf("Bad encoded_value field/enum size %x", value_arg);
return false;
}
uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
if (!CheckIndex(idx, header_->field_ids_size_, "encoded_value field")) {
return false;
}
break;
}
case DexFile::kDexAnnotationMethod: {
if (UNLIKELY(value_arg > 3)) {
ErrorStringPrintf("Bad encoded_value method size %x", value_arg);
return false;
}
uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
if (!CheckIndex(idx, header_->method_ids_size_, "encoded_value method")) {
return false;
}
break;
}
case DexFile::kDexAnnotationArray:
if (UNLIKELY(value_arg != 0)) {
ErrorStringPrintf("Bad encoded_value array value_arg %x", value_arg);
return false;
}
if (!CheckEncodedArray()) {
return false;
}
break;
case DexFile::kDexAnnotationAnnotation:
if (UNLIKELY(value_arg != 0)) {
ErrorStringPrintf("Bad encoded_value annotation value_arg %x", value_arg);
return false;
}
if (!CheckEncodedAnnotation()) {
return false;
}
break;
case DexFile::kDexAnnotationNull:
if (UNLIKELY(value_arg != 0)) {
ErrorStringPrintf("Bad encoded_value null value_arg %x", value_arg);
return false;
}
break;
case DexFile::kDexAnnotationBoolean:
if (UNLIKELY(value_arg > 1)) {
ErrorStringPrintf("Bad encoded_value boolean size %x", value_arg);
return false;
}
break;
case DexFile::kDexAnnotationMethodType: {
if (UNLIKELY(value_arg > 3)) {
ErrorStringPrintf("Bad encoded_value method type size %x", value_arg);
return false;
}
uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
if (!CheckIndex(idx, header_->proto_ids_size_, "method_type value")) {
return false;
}
break;
}
case DexFile::kDexAnnotationMethodHandle: {
if (UNLIKELY(value_arg > 3)) {
ErrorStringPrintf("Bad encoded_value method handle size %x", value_arg);
return false;
}
uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
if (!CheckIndex(idx, dex_file_->NumMethodHandles(), "method_handle value")) {
return false;
}
break;
}
default:
ErrorStringPrintf("Bogus encoded_value value_type %x", value_type);
return false;
}
return true;
}
bool DexFileVerifier::CheckEncodedArray() {
DECODE_UNSIGNED_CHECKED_FROM(ptr_, size);
for (; size != 0u; --size) {
if (!CheckEncodedValue()) {
failure_reason_ = StringPrintf("Bad encoded_array value: %s", failure_reason_.c_str());
return false;
}
}
return true;
}
bool DexFileVerifier::CheckEncodedAnnotation() {
DECODE_UNSIGNED_CHECKED_FROM(ptr_, anno_idx);
if (!CheckIndex(anno_idx, header_->type_ids_size_, "encoded_annotation type_idx")) {
return false;
}
DECODE_UNSIGNED_CHECKED_FROM(ptr_, size);
uint32_t last_idx = 0;
for (uint32_t i = 0; i < size; i++) {
DECODE_UNSIGNED_CHECKED_FROM(ptr_, idx);
if (!CheckIndex(idx, header_->string_ids_size_, "annotation_element name_idx")) {
return false;
}
if (UNLIKELY(last_idx >= idx && i != 0)) {
ErrorStringPrintf("Out-of-order annotation_element name_idx: %x then %x",
last_idx, idx);
return false;
}
if (!CheckEncodedValue()) {
return false;
}
last_idx = idx;
}
return true;
}
bool DexFileVerifier::FindClassIndexAndDef(uint32_t index,
bool is_field,
dex::TypeIndex* class_type_index,
const dex::ClassDef** output_class_def) {
DCHECK(class_type_index != nullptr);
DCHECK(output_class_def != nullptr);
// First check if the index is valid.
if (index >= (is_field ? header_->field_ids_size_ : header_->method_ids_size_)) {
return false;
}
// Next get the type index.
if (is_field) {
*class_type_index =
(reinterpret_cast<const dex::FieldId*>(begin_ + header_->field_ids_off_) + index)->
class_idx_;
} else {
*class_type_index =
(reinterpret_cast<const dex::MethodId*>(begin_ + header_->method_ids_off_) + index)->
class_idx_;
}
// Check if that is valid.
if (class_type_index->index_ >= header_->type_ids_size_) {
return false;
}
// Now search for the class def. This is basically a specialized version of the DexFile code, as
// we should not trust that this is a valid DexFile just yet.
const dex::ClassDef* class_def_begin =
reinterpret_cast<const dex::ClassDef*>(begin_ + header_->class_defs_off_);
for (size_t i = 0; i < header_->class_defs_size_; ++i) {
const dex::ClassDef* class_def = class_def_begin + i;
if (class_def->class_idx_ == *class_type_index) {
*output_class_def = class_def;
return true;
}
}
// Didn't find the class-def, not defined here...
return false;
}
bool DexFileVerifier::CheckOrder(const char* type_descr,
uint32_t curr_index,
uint32_t prev_index) {
if (UNLIKELY(curr_index < prev_index)) {
ErrorStringPrintf("out-of-order %s indexes %" PRIu32 " and %" PRIu32,
type_descr,
prev_index,
curr_index);
return false;
}
return true;
}
bool DexFileVerifier::CheckStaticFieldTypes(const dex::ClassDef* class_def) {
if (class_def == nullptr) {
return true;
}
ClassAccessor accessor(*dex_file_, ptr_);
EncodedStaticFieldValueIterator array_it(*dex_file_, *class_def);
for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
if (!array_it.HasNext()) {
break;
}
uint32_t index = field.GetIndex();
const dex::TypeId& type_id = dex_file_->GetTypeId(dex_file_->GetFieldId(index).type_idx_);
const char* field_type_name =
dex_file_->GetStringData(dex_file_->GetStringId(type_id.descriptor_idx_));
Primitive::Type field_type = Primitive::GetType(field_type_name[0]);
EncodedArrayValueIterator::ValueType array_type = array_it.GetValueType();
// Ensure this matches RuntimeEncodedStaticFieldValueIterator.
switch (array_type) {
case EncodedArrayValueIterator::ValueType::kBoolean:
if (field_type != Primitive::kPrimBoolean) {
ErrorStringPrintf("unexpected static field initial value type: 'Z' vs '%c'",
field_type_name[0]);
return false;
}
break;
case EncodedArrayValueIterator::ValueType::kByte:
if (field_type != Primitive::kPrimByte) {
ErrorStringPrintf("unexpected static field initial value type: 'B' vs '%c'",
field_type_name[0]);
return false;
}
break;
case EncodedArrayValueIterator::ValueType::kShort:
if (field_type != Primitive::kPrimShort) {
ErrorStringPrintf("unexpected static field initial value type: 'S' vs '%c'",
field_type_name[0]);
return false;
}
break;
case EncodedArrayValueIterator::ValueType::kChar:
if (field_type != Primitive::kPrimChar) {
ErrorStringPrintf("unexpected static field initial value type: 'C' vs '%c'",
field_type_name[0]);
return false;
}
break;
case EncodedArrayValueIterator::ValueType::kInt:
if (field_type != Primitive::kPrimInt) {
ErrorStringPrintf("unexpected static field initial value type: 'I' vs '%c'",
field_type_name[0]);
return false;
}
break;
case EncodedArrayValueIterator::ValueType::kLong:
if (field_type != Primitive::kPrimLong) {
ErrorStringPrintf("unexpected static field initial value type: 'J' vs '%c'",
field_type_name[0]);
return false;
}
break;
case EncodedArrayValueIterator::ValueType::kFloat:
if (field_type != Primitive::kPrimFloat) {
ErrorStringPrintf("unexpected static field initial value type: 'F' vs '%c'",
field_type_name[0]);
return false;
}
break;
case EncodedArrayValueIterator::ValueType::kDouble:
if (field_type != Primitive::kPrimDouble) {
ErrorStringPrintf("unexpected static field initial value type: 'D' vs '%c'",
field_type_name[0]);
return false;
}
break;
case EncodedArrayValueIterator::ValueType::kNull:
case EncodedArrayValueIterator::ValueType::kString:
case EncodedArrayValueIterator::ValueType::kType:
if (field_type != Primitive::kPrimNot) {
ErrorStringPrintf("unexpected static field initial value type: 'L' vs '%c'",
field_type_name[0]);
return false;
}
break;
default:
ErrorStringPrintf("unexpected static field initial value type: %x", array_type);
return false;
}
array_it.Next();
}
if (array_it.HasNext()) {
ErrorStringPrintf("too many static field initial values");
return false;
}
return true;
}
template <bool kStatic>
bool DexFileVerifier::CheckIntraClassDataItemFields(size_t count,
ClassAccessor::Field* field,
bool* have_class,
dex::TypeIndex* class_type_index,
const dex::ClassDef** class_def) {
DCHECK(field != nullptr);
constexpr const char* kTypeDescr = kStatic ? "static field" : "instance field";
if (count == 0u) {
return true;
}
field->Read();
if (!*have_class) {
*have_class = FindClassIndexAndDef(field->GetIndex(), true, class_type_index, class_def);
if (!*have_class) {
// Should have really found one.
ErrorStringPrintf("could not find declaring class for %s index %" PRIu32,
kTypeDescr,
field->GetIndex());
return false;
}
}
DCHECK(*class_def != nullptr);
uint32_t prev_index = 0;
for (size_t i = 0; ;) {
uint32_t curr_index = field->GetIndex();
// These calls use the raw access flags to check whether the whole dex field is valid.
if (!CheckOrder(kTypeDescr, curr_index, prev_index)) {
return false;
}
if (!CheckClassDataItemField(curr_index,
field->GetAccessFlags(),
(*class_def)->access_flags_,
*class_type_index,
kStatic)) {
return false;
}
++i;
if (i >= count) {
break;
}
field->Read();
prev_index = curr_index;
}
return true;
}
bool DexFileVerifier::CheckIntraClassDataItemMethods(ClassAccessor::Method* method,
size_t num_methods,
ClassAccessor::Method* direct_method,
size_t num_directs,
bool* have_class,
dex::TypeIndex* class_type_index,
const dex::ClassDef** class_def) {
DCHECK(method != nullptr);
const char* kTypeDescr = method->IsStaticOrDirect() ? "direct method" : "virtual method";
if (num_methods == 0u) {
return true;
}
method->Read();
if (!*have_class) {
*have_class = FindClassIndexAndDef(method->GetIndex(), false, class_type_index, class_def);
if (!*have_class) {
// Should have really found one.
ErrorStringPrintf("could not find declaring class for %s index %" PRIu32,
kTypeDescr,
method->GetIndex());
return false;
}
}
DCHECK(*class_def != nullptr);
uint32_t prev_index = 0;
for (size_t i = 0; ;) {
uint32_t curr_index = method->GetIndex();
if (!CheckOrder(kTypeDescr, curr_index, prev_index)) {
return false;
}
if (!CheckClassDataItemMethod(curr_index,
method->GetAccessFlags(),
(*class_def)->access_flags_,
*class_type_index,
method->GetCodeItemOffset(),
direct_method,
&num_directs)) {
return false;
}
++i;
if (i >= num_methods) {
break;
}
method->Read();
prev_index = curr_index;
}
return true;
}
bool DexFileVerifier::CheckIntraClassDataItem() {
ClassAccessor accessor(*dex_file_, ptr_);
// This code is complicated by the fact that we don't directly know which class this belongs to.
// So we need to explicitly search with the first item we find (either field or method), and then,
// as the lookup is expensive, cache the result.
bool have_class = false;
dex::TypeIndex class_type_index;
const dex::ClassDef* class_def = nullptr;
ClassAccessor::Field field(*dex_file_, accessor.ptr_pos_);
// Check fields.
if (!CheckIntraClassDataItemFields<true>(accessor.NumStaticFields(),
&field,
&have_class,
&class_type_index,
&class_def)) {
return false;
}
field.NextSection();
if (!CheckIntraClassDataItemFields<false>(accessor.NumInstanceFields(),
&field,
&have_class,
&class_type_index,
&class_def)) {
return false;
}
// Check methods.
ClassAccessor::Method method(*dex_file_, field.ptr_pos_);
if (!CheckIntraClassDataItemMethods(&method,
accessor.NumDirectMethods(),
/* direct_method= */ nullptr,
0u,
&have_class,
&class_type_index,
&class_def)) {
return false;
}
ClassAccessor::Method direct_methods(*dex_file_, field.ptr_pos_);
method.NextSection();
if (accessor.NumDirectMethods() != 0u) {
direct_methods.Read();
}
if (!CheckIntraClassDataItemMethods(&method,
accessor.NumVirtualMethods(),
&direct_methods,
accessor.NumDirectMethods(),
&have_class,
&class_type_index,
&class_def)) {
return false;
}
// Check static field types against initial static values in encoded array.
if (!CheckStaticFieldTypes(class_def)) {
return false;
}
ptr_ = method.ptr_pos_;
return true;
}
bool DexFileVerifier::CheckIntraCodeItem() {
const dex::CodeItem* code_item = reinterpret_cast<const dex::CodeItem*>(ptr_);
if (!CheckListSize(code_item, 1, sizeof(dex::CodeItem), "code")) {
return false;
}
CodeItemDataAccessor accessor(*dex_file_, code_item);
if (UNLIKELY(accessor.InsSize() > accessor.RegistersSize())) {
ErrorStringPrintf("ins_size (%ud) > registers_size (%ud)",
accessor.InsSize(), accessor.RegistersSize());
return false;
}
if (UNLIKELY(accessor.OutsSize() > 5 && accessor.OutsSize() > accessor.RegistersSize())) {
/*
* outs_size can be up to 5, even if registers_size is smaller, since the
* short forms of method invocation allow repetitions of a register multiple
* times within a single parameter list. However, longer parameter lists
* need to be represented in-order in the register file.
*/
ErrorStringPrintf("outs_size (%ud) > registers_size (%ud)",
accessor.OutsSize(), accessor.RegistersSize());
return false;
}
const uint16_t* insns = accessor.Insns();
uint32_t insns_size = accessor.InsnsSizeInCodeUnits();
if (!CheckListSize(insns, insns_size, sizeof(uint16_t), "insns size")) {
return false;
}
// Grab the end of the insns if there are no try_items.
uint32_t try_items_size = accessor.TriesSize();
if (try_items_size == 0) {
ptr_ = reinterpret_cast<const uint8_t*>(&insns[insns_size]);
return true;
}
// try_items are 4-byte aligned. Verify the spacer is 0.
if (((reinterpret_cast<uintptr_t>(&insns[insns_size]) & 3) != 0) && (insns[insns_size] != 0)) {
ErrorStringPrintf("Non-zero padding: %x", insns[insns_size]);
return false;
}
const dex::TryItem* try_items = accessor.TryItems().begin();
if (!CheckListSize(try_items, try_items_size, sizeof(dex::TryItem), "try_items size")) {
return false;
}
ptr_ = accessor.GetCatchHandlerData();
DECODE_UNSIGNED_CHECKED_FROM(ptr_, handlers_size);
if (UNLIKELY((handlers_size == 0) || (handlers_size >= 65536))) {
ErrorStringPrintf("Invalid handlers_size: %ud", handlers_size);
return false;
}
// Avoid an expensive allocation, if possible.
std::unique_ptr<uint32_t[]> handler_offsets_uptr;
uint32_t* handler_offsets;
constexpr size_t kAllocaMaxSize = 1024;
if (handlers_size < kAllocaMaxSize/sizeof(uint32_t)) {
// Note: Clang does not specify alignment guarantees for alloca. So align by hand.
handler_offsets =
AlignUp(reinterpret_cast<uint32_t*>(alloca((handlers_size + 1) * sizeof(uint32_t))),
alignof(uint32_t[]));
} else {
handler_offsets_uptr.reset(new uint32_t[handlers_size]);
handler_offsets = handler_offsets_uptr.get();
}
if (!CheckAndGetHandlerOffsets(code_item, &handler_offsets[0], handlers_size)) {
return false;
}
uint32_t last_addr = 0;
for (; try_items_size != 0u; --try_items_size) {
if (UNLIKELY(try_items->start_addr_ < last_addr)) {
ErrorStringPrintf("Out-of_order try_item with start_addr: %x", try_items->start_addr_);
return false;
}
if (UNLIKELY(try_items->start_addr_ >= insns_size)) {
ErrorStringPrintf("Invalid try_item start_addr: %x", try_items->start_addr_);
return false;
}
uint32_t i;
for (i = 0; i < handlers_size; i++) {
if (try_items->handler_off_ == handler_offsets[i]) {
break;
}
}
if (UNLIKELY(i == handlers_size)) {
ErrorStringPrintf("Bogus handler offset: %x", try_items->handler_off_);
return false;
}
last_addr = try_items->start_addr_ + try_items->insn_count_;
if (UNLIKELY(last_addr > insns_size)) {
ErrorStringPrintf("Invalid try_item insn_count: %x", try_items->insn_count_);
return false;
}
try_items++;
}
return true;
}
bool DexFileVerifier::CheckIntraStringDataItem() {
DECODE_UNSIGNED_CHECKED_FROM(ptr_, size);
const uint8_t* file_end = begin_ + size_;
for (uint32_t i = 0; i < size; i++) {
CHECK_LT(i, size); // b/15014252 Prevents hitting the impossible case below
if (UNLIKELY(ptr_ >= file_end)) {
ErrorStringPrintf("String data would go beyond end-of-file");
return false;
}
uint8_t byte = *(ptr_++);
// Switch on the high 4 bits.
switch (byte >> 4) {
case 0x00:
// Special case of bit pattern 0xxx.
if (UNLIKELY(byte == 0)) {
CHECK_LT(i, size); // b/15014252 Actually hit this impossible case with clang
ErrorStringPrintf("String data shorter than indicated utf16_size %x", size);
return false;
}
break;
case 0x01:
case 0x02:
case 0x03:
case 0x04:
case 0x05:
case 0x06:
case 0x07:
// No extra checks necessary for bit pattern 0xxx.
break;
case 0x08:
case 0x09:
case 0x0a:
case 0x0b:
case 0x0f:
// Illegal bit patterns 10xx or 1111.
// Note: 1111 is valid for normal UTF-8, but not here.
ErrorStringPrintf("Illegal start byte %x in string data", byte);
return false;
case 0x0c:
case 0x0d: {
// Bit pattern 110x has an additional byte.
uint8_t byte2 = *(ptr_++);
if (UNLIKELY((byte2 & 0xc0) != 0x80)) {
ErrorStringPrintf("Illegal continuation byte %x in string data", byte2);
return false;
}
uint16_t value = ((byte & 0x1f) << 6) | (byte2 & 0x3f);
if (UNLIKELY((value != 0) && (value < 0x80))) {
ErrorStringPrintf("Illegal representation for value %x in string data", value);
return false;
}
break;
}
case 0x0e: {
// Bit pattern 1110 has 2 additional bytes.
uint8_t byte2 = *(ptr_++);
if (UNLIKELY((byte2 & 0xc0) != 0x80)) {
ErrorStringPrintf("Illegal continuation byte %x in string data", byte2);
return false;
}
uint8_t byte3 = *(ptr_++);
if (UNLIKELY((byte3 & 0xc0) != 0x80)) {
ErrorStringPrintf("Illegal continuation byte %x in string data", byte3);
return false;
}
uint16_t value = ((byte & 0x0f) << 12) | ((byte2 & 0x3f) << 6) | (byte3 & 0x3f);
if (UNLIKELY(value < 0x800)) {
ErrorStringPrintf("Illegal representation for value %x in string data", value);
return false;
}
break;
}
}
}
if (UNLIKELY(*(ptr_++) != '\0')) {
ErrorStringPrintf("String longer than indicated size %x", size);
return false;
}
return true;
}
bool DexFileVerifier::CheckIntraDebugInfoItem() {
DECODE_UNSIGNED_CHECKED_FROM(ptr_, dummy);
DECODE_UNSIGNED_CHECKED_FROM(ptr_, parameters_size);
if (UNLIKELY(parameters_size > 65536)) {
ErrorStringPrintf("Invalid parameters_size: %x", parameters_size);
return false;
}
for (uint32_t j = 0; j < parameters_size; j++) {
DECODE_UNSIGNED_CHECKED_FROM(ptr_, parameter_name);
if (parameter_name != 0) {
parameter_name--;
if (!CheckIndex(parameter_name, header_->string_ids_size_, "debug_info_item parameter_name")) {
return false;
}
}
}
while (true) {
uint8_t opcode = *(ptr_++);
switch (opcode) {
case DexFile::DBG_END_SEQUENCE: {
return true;
}
case DexFile::DBG_ADVANCE_PC: {
DECODE_UNSIGNED_CHECKED_FROM(ptr_, advance_pc_dummy);
break;
}
case DexFile::DBG_ADVANCE_LINE: {
DECODE_SIGNED_CHECKED_FROM(ptr_, advance_line_dummy);
break;
}
case DexFile::DBG_START_LOCAL: {
DECODE_UNSIGNED_CHECKED_FROM(ptr_, reg_num);
if (UNLIKELY(reg_num >= 65536)) {
ErrorStringPrintf("Bad reg_num for opcode %x", opcode);
return false;
}
DECODE_UNSIGNED_CHECKED_FROM(ptr_, name_idx);
if (name_idx != 0) {
name_idx--;
if (!CheckIndex(name_idx, header_->string_ids_size_, "DBG_START_LOCAL name_idx")) {
return false;
}
}
DECODE_UNSIGNED_CHECKED_FROM(ptr_, type_idx);
if (type_idx != 0) {
type_idx--;
if (!CheckIndex(type_idx, header_->type_ids_size_, "DBG_START_LOCAL type_idx")) {
return false;
}
}
break;
}
case DexFile::DBG_END_LOCAL:
case DexFile::DBG_RESTART_LOCAL: {
DECODE_UNSIGNED_CHECKED_FROM(ptr_, reg_num);
if (UNLIKELY(reg_num >= 65536)) {
ErrorStringPrintf("Bad reg_num for opcode %x", opcode);
return false;
}
break;
}
case DexFile::DBG_START_LOCAL_EXTENDED: {
DECODE_UNSIGNED_CHECKED_FROM(ptr_, reg_num);
if (UNLIKELY(reg_num >= 65536)) {
ErrorStringPrintf("Bad reg_num for opcode %x", opcode);
return false;
}
DECODE_UNSIGNED_CHECKED_FROM(ptr_, name_idx);
if (name_idx != 0) {
name_idx--;
if (!CheckIndex(name_idx, header_->string_ids_size_, "DBG_START_LOCAL_EXTENDED name_idx")) {
return false;
}
}
DECODE_UNSIGNED_CHECKED_FROM(ptr_, type_idx);
if (type_idx != 0) {
type_idx--;
if (!CheckIndex(type_idx, header_->type_ids_size_, "DBG_START_LOCAL_EXTENDED type_idx")) {
return false;
}
}
DECODE_UNSIGNED_CHECKED_FROM(ptr_, sig_idx);
if (sig_idx != 0) {
sig_idx--;
if (!CheckIndex(sig_idx, header_->string_ids_size_, "DBG_START_LOCAL_EXTENDED sig_idx")) {
return false;
}
}
break;
}
case DexFile::DBG_SET_FILE: {
DECODE_UNSIGNED_CHECKED_FROM(ptr_, name_idx);
if (name_idx != 0) {
name_idx--;
if (!CheckIndex(name_idx, header_->string_ids_size_, "DBG_SET_FILE name_idx")) {
return false;
}
}
break;
}
}
}
}
bool DexFileVerifier::CheckIntraAnnotationItem() {
if (!CheckListSize(ptr_, 1, sizeof(uint8_t), "annotation visibility")) {
return false;
}
// Check visibility
switch (*(ptr_++)) {
case DexFile::kDexVisibilityBuild:
case DexFile::kDexVisibilityRuntime:
case DexFile::kDexVisibilitySystem:
break;
default:
ErrorStringPrintf("Bad annotation visibility: %x", *ptr_);
return false;
}
if (!CheckEncodedAnnotation()) {
return false;
}
return true;
}
bool DexFileVerifier::CheckIntraHiddenapiClassData() {
const dex::HiddenapiClassData* item = reinterpret_cast<const dex::HiddenapiClassData*>(ptr_);
// Check expected header size.
uint32_t num_header_elems = dex_file_->NumClassDefs() + 1;
uint32_t elem_size = sizeof(uint32_t);
uint32_t header_size = num_header_elems * elem_size;
if (!CheckListSize(item, num_header_elems, elem_size, "hiddenapi class data section header")) {
return false;
}
// Check total size.
if (!CheckListSize(item, item->size_, 1u, "hiddenapi class data section")) {
return false;
}
// Check that total size can fit header.
if (item->size_ < header_size) {
ErrorStringPrintf(
"Hiddenapi class data too short to store header (%u < %u)", item->size_, header_size);
return false;
}
const uint8_t* data_end = ptr_ + item->size_;
ptr_ += header_size;
// Check offsets for each class def.
for (uint32_t i = 0; i < dex_file_->NumClassDefs(); ++i) {
const dex::ClassDef& class_def = dex_file_->GetClassDef(i);
const uint8_t* class_data = dex_file_->GetClassData(class_def);
uint32_t offset = item->flags_offset_[i];
if (offset == 0) {
continue;
}
// Check that class defs with no class data do not have any hiddenapi class data.
if (class_data == nullptr) {
ErrorStringPrintf(
"Hiddenapi class data offset not zero for class def %u with no class data", i);
return false;
}
// Check that the offset is within the section.
if (offset > item->size_) {
ErrorStringPrintf(
"Hiddenapi class data offset out of section bounds (%u > %u) for class def %u",
offset, item->size_, i);
return false;
}
// Check that the offset matches current pointer position. We do not allow
// offsets into already parsed data, or gaps between class def data.
uint32_t ptr_offset = ptr_ - reinterpret_cast<const uint8_t*>(item);
if (offset != ptr_offset) {
ErrorStringPrintf(
"Hiddenapi class data unexpected offset (%u != %u) for class def %u",
offset, ptr_offset, i);
return false;
}
// Parse a uleb128 value for each field and method of this class.
bool failure = false;
auto fn_member = [&](const ClassAccessor::BaseItem& member, const char* member_type) {
if (failure) {
return;
}
uint32_t decoded_flags;
if (!DecodeUnsignedLeb128Checked(&ptr_, data_end, &decoded_flags)) {
ErrorStringPrintf("Hiddenapi class data value out of bounds (%p > %p) for %s %i",
ptr_, data_end, member_type, member.GetIndex());
failure = true;
return;
}
if (!hiddenapi::AreValidDexFlags(decoded_flags)) {
ErrorStringPrintf("Hiddenapi class data flags invalid (%u) for %s %i",
decoded_flags, member_type, member.GetIndex());
failure = true;
return;
}
};
auto fn_field = [&](const ClassAccessor::Field& field) { fn_member(field, "field"); };
auto fn_method = [&](const ClassAccessor::Method& method) { fn_member(method, "method"); };
ClassAccessor accessor(*dex_file_, class_data);
accessor.VisitFieldsAndMethods(fn_field, fn_field, fn_method, fn_method);
if (failure) {
return false;
}
}
if (ptr_ != data_end) {
ErrorStringPrintf("Hiddenapi class data wrong reported size (%u != %u)",
static_cast<uint32_t>(ptr_ - reinterpret_cast<const uint8_t*>(item)),
item->size_);
return false;
}
return true;
}
bool DexFileVerifier::CheckIntraAnnotationsDirectoryItem() {
const dex::AnnotationsDirectoryItem* item =
reinterpret_cast<const dex::AnnotationsDirectoryItem*>(ptr_);
if (!CheckListSize(item, 1, sizeof(dex::AnnotationsDirectoryItem), "annotations_directory")) {
return false;
}
// Field annotations follow immediately after the annotations directory.
const dex::FieldAnnotationsItem* field_item =
reinterpret_cast<const dex::FieldAnnotationsItem*>(item + 1);
uint32_t field_count = item->fields_size_;
if (!CheckListSize(field_item,
field_count,
sizeof(dex::FieldAnnotationsItem),
"field_annotations list")) {
return false;
}
uint32_t last_idx = 0;
for (uint32_t i = 0; i < field_count; i++) {
if (UNLIKELY(last_idx >= field_item->field_idx_ && i != 0)) {
ErrorStringPrintf("Out-of-order field_idx for annotation: %x then %x",
last_idx, field_item->field_idx_);
return false;
}
last_idx = field_item->field_idx_;
field_item++;
}
// Method annotations follow immediately after field annotations.
const dex::MethodAnnotationsItem* method_item =
reinterpret_cast<const dex::MethodAnnotationsItem*>(field_item);
uint32_t method_count = item->methods_size_;
if (!CheckListSize(method_item,
method_count,
sizeof(dex::MethodAnnotationsItem),
"method_annotations list")) {
return false;
}
last_idx = 0;
for (uint32_t i = 0; i < method_count; i++) {
if (UNLIKELY(last_idx >= method_item->method_idx_ && i != 0)) {
ErrorStringPrintf("Out-of-order method_idx for annotation: %x then %x",
last_idx, method_item->method_idx_);
return false;
}
last_idx = method_item->method_idx_;
method_item++;
}
// Parameter annotations follow immediately after method annotations.
const dex::ParameterAnnotationsItem* parameter_item =
reinterpret_cast<const dex::ParameterAnnotationsItem*>(method_item);
uint32_t parameter_count = item->parameters_size_;
if (!CheckListSize(parameter_item, parameter_count, sizeof(dex::ParameterAnnotationsItem),
"parameter_annotations list")) {
return false;
}
last_idx = 0;
for (uint32_t i = 0; i < parameter_count; i++) {
if (UNLIKELY(last_idx >= parameter_item->method_idx_ && i != 0)) {
ErrorStringPrintf("Out-of-order method_idx for annotation: %x then %x",
last_idx, parameter_item->method_idx_);
return false;
}
last_idx = parameter_item->method_idx_;
parameter_item++;
}
// Return a pointer to the end of the annotations.
ptr_ = reinterpret_cast<const uint8_t*>(parameter_item);
return true;
}
template <DexFile::MapItemType kType>
bool DexFileVerifier::CheckIntraSectionIterate(size_t offset, uint32_t section_count) {
// Get the right alignment mask for the type of section.
size_t alignment_mask;
switch (kType) {
case DexFile::kDexTypeClassDataItem:
case DexFile::kDexTypeStringDataItem:
case DexFile::kDexTypeDebugInfoItem:
case DexFile::kDexTypeAnnotationItem:
case DexFile::kDexTypeEncodedArrayItem:
alignment_mask = sizeof(uint8_t) - 1;
break;
default:
alignment_mask = sizeof(uint32_t) - 1;
break;
}
// Iterate through the items in the section.
for (uint32_t i = 0; i < section_count; i++) {
size_t aligned_offset = (offset + alignment_mask) & ~alignment_mask;
// Check the padding between items.
if (!CheckPadding(offset, aligned_offset, kType)) {
return false;
}
// Check depending on the section type.
const uint8_t* start_ptr = ptr_;
switch (kType) {
case DexFile::kDexTypeStringIdItem: {
if (!CheckListSize(ptr_, 1, sizeof(dex::StringId), "string_ids")) {
return false;
}
ptr_ += sizeof(dex::StringId);
break;
}
case DexFile::kDexTypeTypeIdItem: {
if (!CheckListSize(ptr_, 1, sizeof(dex::TypeId), "type_ids")) {
return false;
}
ptr_ += sizeof(dex::TypeId);
break;
}
case DexFile::kDexTypeProtoIdItem: {
if (!CheckListSize(ptr_, 1, sizeof(dex::ProtoId), "proto_ids")) {
return false;
}
ptr_ += sizeof(dex::ProtoId);
break;
}
case DexFile::kDexTypeFieldIdItem: {
if (!CheckListSize(ptr_, 1, sizeof(dex::FieldId), "field_ids")) {
return false;
}
ptr_ += sizeof(dex::FieldId);
break;
}
case DexFile::kDexTypeMethodIdItem: {
if (!CheckListSize(ptr_, 1, sizeof(dex::MethodId), "method_ids")) {
return false;
}
ptr_ += sizeof(dex::MethodId);
break;
}
case DexFile::kDexTypeClassDefItem: {
if (!CheckListSize(ptr_, 1, sizeof(dex::ClassDef), "class_defs")) {
return false;
}
ptr_ += sizeof(dex::ClassDef);
break;
}
case DexFile::kDexTypeCallSiteIdItem: {
if (!CheckListSize(ptr_, 1, sizeof(dex::CallSiteIdItem), "call_site_ids")) {
return false;
}
ptr_ += sizeof(dex::CallSiteIdItem);
break;
}
case DexFile::kDexTypeMethodHandleItem: {
if (!CheckListSize(ptr_, 1, sizeof(dex::MethodHandleItem), "method_handles")) {
return false;
}
ptr_ += sizeof(dex::MethodHandleItem);
break;
}
case DexFile::kDexTypeTypeList: {
if (!CheckList(sizeof(dex::TypeItem), "type_list", &ptr_)) {
return false;
}
break;
}
case DexFile::kDexTypeAnnotationSetRefList: {
if (!CheckList(sizeof(dex::AnnotationSetRefItem), "annotation_set_ref_list", &ptr_)) {
return false;
}
break;
}
case DexFile::kDexTypeAnnotationSetItem: {
if (!CheckList(sizeof(uint32_t), "annotation_set_item", &ptr_)) {
return false;
}
break;
}
case DexFile::kDexTypeClassDataItem: {
if (!CheckIntraClassDataItem()) {
return false;
}
break;
}
case DexFile::kDexTypeCodeItem: {
if (!CheckIntraCodeItem()) {
return false;
}
break;
}
case DexFile::kDexTypeStringDataItem: {
if (!CheckIntraStringDataItem()) {
return false;
}
break;
}
case DexFile::kDexTypeDebugInfoItem: {
if (!CheckIntraDebugInfoItem()) {
return false;
}
break;
}
case DexFile::kDexTypeAnnotationItem: {
if (!CheckIntraAnnotationItem()) {
return false;
}
break;
}
case DexFile::kDexTypeEncodedArrayItem: {
if (!CheckEncodedArray()) {
return false;
}
break;
}
case DexFile::kDexTypeAnnotationsDirectoryItem: {
if (!CheckIntraAnnotationsDirectoryItem()) {
return false;
}
break;
}
case DexFile::kDexTypeHiddenapiClassData: {
if (!CheckIntraHiddenapiClassData()) {
return false;
}
break;
}
case DexFile::kDexTypeHeaderItem:
case DexFile::kDexTypeMapList:
break;
}
if (start_ptr == ptr_) {
ErrorStringPrintf("Unknown map item type %x", kType);
return false;
}
if (IsDataSectionType(kType)) {
if (aligned_offset == 0u) {
ErrorStringPrintf("Item %d offset is 0", i);
return false;
}
DCHECK(offset_to_type_map_.find(aligned_offset) == offset_to_type_map_.end());
offset_to_type_map_.insert(std::pair<uint32_t, uint16_t>(aligned_offset, kType));
}
aligned_offset = ptr_ - begin_;
if (UNLIKELY(aligned_offset > size_)) {
ErrorStringPrintf("Item %d at ends out of bounds", i);
return false;
}
offset = aligned_offset;
}
return true;
}
template <DexFile::MapItemType kType>
bool DexFileVerifier::CheckIntraIdSection(size_t offset, uint32_t count) {
uint32_t expected_offset;
uint32_t expected_size;
// Get the expected offset and size from the header.
switch (kType) {
case DexFile::kDexTypeStringIdItem:
expected_offset = header_->string_ids_off_;
expected_size = header_->string_ids_size_;
break;
case DexFile::kDexTypeTypeIdItem:
expected_offset = header_->type_ids_off_;
expected_size = header_->type_ids_size_;
break;
case DexFile::kDexTypeProtoIdItem:
expected_offset = header_->proto_ids_off_;
expected_size = header_->proto_ids_size_;
break;
case DexFile::kDexTypeFieldIdItem:
expected_offset = header_->field_ids_off_;
expected_size = header_->field_ids_size_;
break;
case DexFile::kDexTypeMethodIdItem:
expected_offset = header_->method_ids_off_;
expected_size = header_->method_ids_size_;
break;
case DexFile::kDexTypeClassDefItem:
expected_offset = header_->class_defs_off_;
expected_size = header_->class_defs_size_;
break;
default:
ErrorStringPrintf("Bad type for id section: %x", kType);
return false;
}
// Check that the offset and size are what were expected from the header.
if (UNLIKELY(offset != expected_offset)) {
ErrorStringPrintf("Bad offset for section: got %zx, expected %x", offset, expected_offset);
return false;
}
if (UNLIKELY(count != expected_size)) {
ErrorStringPrintf("Bad size for section: got %x, expected %x", count, expected_size);
return false;
}
return CheckIntraSectionIterate<kType>(offset, count);
}
template <DexFile::MapItemType kType>
bool DexFileVerifier::CheckIntraDataSection(size_t offset, uint32_t count) {
size_t data_start = header_->data_off_;
size_t data_end = data_start + header_->data_size_;
// Sanity check the offset of the section.
if (UNLIKELY((offset < data_start) || (offset > data_end))) {
ErrorStringPrintf("Bad offset for data subsection: %zx", offset);
return false;
}
if (!CheckIntraSectionIterate<kType>(offset, count)) {
return false;
}
size_t next_offset = ptr_ - begin_;
if (next_offset > data_end) {
ErrorStringPrintf("Out-of-bounds end of data subsection: %zu data_off=%u data_size=%u",
next_offset,
header_->data_off_,
header_->data_size_);
return false;
}
return true;
}
bool DexFileVerifier::CheckIntraSection() {
const dex::MapList* map = reinterpret_cast<const dex::MapList*>(begin_ + header_->map_off_);
const dex::MapItem* item = map->list_;
size_t offset = 0;
uint32_t count = map->size_;
ptr_ = begin_;
// Check the items listed in the map.
for (; count != 0u; --count) {
const size_t current_offset = offset;
uint32_t section_offset = item->offset_;
uint32_t section_count = item->size_;
DexFile::MapItemType type = static_cast<DexFile::MapItemType>(item->type_);
// Check for padding and overlap between items.
if (!CheckPadding(offset, section_offset, type)) {
return false;
} else if (UNLIKELY(offset > section_offset)) {
ErrorStringPrintf("Section overlap or out-of-order map: %zx, %x", offset, section_offset);
return false;
}
if (type == DexFile::kDexTypeClassDataItem) {
FindStringRangesForMethodNames();
}
// Check each item based on its type.
switch (type) {
case DexFile::kDexTypeHeaderItem:
if (UNLIKELY(section_count != 1)) {
ErrorStringPrintf("Multiple header items");
return false;
}
if (UNLIKELY(section_offset != 0)) {
ErrorStringPrintf("Header at %x, not at start of file", section_offset);
return false;
}
ptr_ = begin_ + header_->header_size_;
offset = header_->header_size_;
break;
#define CHECK_INTRA_ID_SECTION_CASE(type) \
case type: \
if (!CheckIntraIdSection<type>(section_offset, section_count)) { \
return false; \
} \
offset = ptr_ - begin_; \
break;
CHECK_INTRA_ID_SECTION_CASE(DexFile::kDexTypeStringIdItem)
CHECK_INTRA_ID_SECTION_CASE(DexFile::kDexTypeTypeIdItem)
CHECK_INTRA_ID_SECTION_CASE(DexFile::kDexTypeProtoIdItem)
CHECK_INTRA_ID_SECTION_CASE(DexFile::kDexTypeFieldIdItem)
CHECK_INTRA_ID_SECTION_CASE(DexFile::kDexTypeMethodIdItem)
CHECK_INTRA_ID_SECTION_CASE(DexFile::kDexTypeClassDefItem)
#undef CHECK_INTRA_ID_SECTION_CASE
case DexFile::kDexTypeMapList:
if (UNLIKELY(section_count != 1)) {
ErrorStringPrintf("Multiple map list items");
return false;
}
if (UNLIKELY(section_offset != header_->map_off_)) {
ErrorStringPrintf("Map not at header-defined offset: %x, expected %x",
section_offset, header_->map_off_);
return false;
}
ptr_ += sizeof(uint32_t) + (map->size_ * sizeof(dex::MapItem));
offset = section_offset + sizeof(uint32_t) + (map->size_ * sizeof(dex::MapItem));
break;
#define CHECK_INTRA_SECTION_ITERATE_CASE(type) \
case type: \
CheckIntraSectionIterate<type>(section_offset, section_count); \
offset = ptr_ - begin_; \
break;
CHECK_INTRA_SECTION_ITERATE_CASE(DexFile::kDexTypeMethodHandleItem)
CHECK_INTRA_SECTION_ITERATE_CASE(DexFile::kDexTypeCallSiteIdItem)
#undef CHECK_INTRA_SECTION_ITERATE_CASE
#define CHECK_INTRA_DATA_SECTION_CASE(type) \
case type: \
if (!CheckIntraDataSection<type>(section_offset, section_count)) { \
return false; \
} \
offset = ptr_ - begin_; \
break;
CHECK_INTRA_DATA_SECTION_CASE(DexFile::kDexTypeTypeList)
CHECK_INTRA_DATA_SECTION_CASE(DexFile::kDexTypeAnnotationSetRefList)
CHECK_INTRA_DATA_SECTION_CASE(DexFile::kDexTypeAnnotationSetItem)
CHECK_INTRA_DATA_SECTION_CASE(DexFile::kDexTypeClassDataItem)
CHECK_INTRA_DATA_SECTION_CASE(DexFile::kDexTypeCodeItem)
CHECK_INTRA_DATA_SECTION_CASE(DexFile::kDexTypeStringDataItem)
CHECK_INTRA_DATA_SECTION_CASE(DexFile::kDexTypeDebugInfoItem)
CHECK_INTRA_DATA_SECTION_CASE(DexFile::kDexTypeAnnotationItem)
CHECK_INTRA_DATA_SECTION_CASE(DexFile::kDexTypeEncodedArrayItem)
CHECK_INTRA_DATA_SECTION_CASE(DexFile::kDexTypeAnnotationsDirectoryItem)
CHECK_INTRA_DATA_SECTION_CASE(DexFile::kDexTypeHiddenapiClassData)
#undef CHECK_INTRA_DATA_SECTION_CASE
}
if (offset == current_offset) {
ErrorStringPrintf("Unknown map item type %x", type);
return false;
}
item++;
}
return true;
}
bool DexFileVerifier::CheckOffsetToTypeMap(size_t offset, uint16_t type) {
DCHECK_NE(offset, 0u);
auto it = offset_to_type_map_.find(offset);
if (UNLIKELY(it == offset_to_type_map_.end())) {
ErrorStringPrintf("No data map entry found @ %zx; expected %x", offset, type);
return false;
}
if (UNLIKELY(it->second != type)) {
ErrorStringPrintf("Unexpected data map entry @ %zx; expected %x, found %x",
offset, type, it->second);
return false;
}
return true;
}
dex::TypeIndex DexFileVerifier::FindFirstClassDataDefiner(const uint8_t* ptr, bool* success) {
ClassAccessor accessor(*dex_file_, ptr);
*success = true;
if (accessor.NumFields() != 0) {
ClassAccessor::Field read_field(*dex_file_, accessor.ptr_pos_);
read_field.Read();
LOAD_FIELD(field, read_field.GetIndex(), "first_class_data_definer field_id",
*success = false; return dex::TypeIndex(DexFile::kDexNoIndex16))
return field->class_idx_;
}
if (accessor.NumMethods() != 0) {
ClassAccessor::Method read_method(*dex_file_, accessor.ptr_pos_);
read_method.Read();
LOAD_METHOD(method, read_method.GetIndex(), "first_class_data_definer method_id",
*success = false; return dex::TypeIndex(DexFile::kDexNoIndex16))
return method->class_idx_;
}
return dex::TypeIndex(DexFile::kDexNoIndex16);
}
dex::TypeIndex DexFileVerifier::FindFirstAnnotationsDirectoryDefiner(const uint8_t* ptr,
bool* success) {
const dex::AnnotationsDirectoryItem* item =
reinterpret_cast<const dex::AnnotationsDirectoryItem*>(ptr);
*success = true;
if (item->fields_size_ != 0) {
dex::FieldAnnotationsItem* field_items = (dex::FieldAnnotationsItem*) (item + 1);
LOAD_FIELD(field, field_items[0].field_idx_, "first_annotations_dir_definer field_id",
*success = false; return dex::TypeIndex(DexFile::kDexNoIndex16))
return field->class_idx_;
}
if (item->methods_size_ != 0) {
dex::MethodAnnotationsItem* method_items = (dex::MethodAnnotationsItem*) (item + 1);
LOAD_METHOD(method, method_items[0].method_idx_, "first_annotations_dir_definer method id",
*success = false; return dex::TypeIndex(DexFile::kDexNoIndex16))
return method->class_idx_;
}
if (item->parameters_size_ != 0) {
dex::ParameterAnnotationsItem* parameter_items = (dex::ParameterAnnotationsItem*) (item + 1);
LOAD_METHOD(method, parameter_items[0].method_idx_, "first_annotations_dir_definer method id",
*success = false; return dex::TypeIndex(DexFile::kDexNoIndex16))
return method->class_idx_;
}
return dex::TypeIndex(DexFile::kDexNoIndex16);
}
bool DexFileVerifier::CheckInterStringIdItem() {
const dex::StringId* item = reinterpret_cast<const dex::StringId*>(ptr_);
// Check the map to make sure it has the right offset->type.
if (!CheckOffsetToTypeMap(item->string_data_off_, DexFile::kDexTypeStringDataItem)) {
return false;
}
// Check ordering between items.
if (previous_item_ != nullptr) {
const dex::StringId* prev_item = reinterpret_cast<const dex::StringId*>(previous_item_);
const char* prev_str = dex_file_->GetStringData(*prev_item);
const char* str = dex_file_->GetStringData(*item);
if (UNLIKELY(CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(prev_str, str) >= 0)) {
ErrorStringPrintf("Out-of-order string_ids: '%s' then '%s'", prev_str, str);
return false;
}
}
ptr_ += sizeof(dex::StringId);
return true;
}
bool DexFileVerifier::CheckInterTypeIdItem() {
const dex::TypeId* item = reinterpret_cast<const dex::TypeId*>(ptr_);
LOAD_STRING(descriptor, item->descriptor_idx_, "inter_type_id_item descriptor_idx")
// Check that the descriptor is a valid type.
if (UNLIKELY(!IsValidDescriptor(descriptor))) {
ErrorStringPrintf("Invalid type descriptor: '%s'", descriptor);
return false;
}
// Check ordering between items.
if (previous_item_ != nullptr) {
const dex::TypeId* prev_item = reinterpret_cast<const dex::TypeId*>(previous_item_);
if (UNLIKELY(prev_item->descriptor_idx_ >= item->descriptor_idx_)) {
ErrorStringPrintf("Out-of-order type_ids: %x then %x",
prev_item->descriptor_idx_.index_,
item->descriptor_idx_.index_);
return false;
}
}
ptr_ += sizeof(dex::TypeId);
return true;
}
bool DexFileVerifier::CheckInterProtoIdItem() {
const dex::ProtoId* item = reinterpret_cast<const dex::ProtoId*>(ptr_);
LOAD_STRING(shorty, item->shorty_idx_, "inter_proto_id_item shorty_idx")
if (item->parameters_off_ != 0 &&
!CheckOffsetToTypeMap(item->parameters_off_, DexFile::kDexTypeTypeList)) {
return false;
}
// Check that return type is representable as a uint16_t;
if (UNLIKELY(!IsValidOrNoTypeId(item->return_type_idx_.index_, item->pad_))) {
ErrorStringPrintf("proto with return type idx outside uint16_t range '%x:%x'",
item->pad_, item->return_type_idx_.index_);
return false;
}
// Check the return type and advance the shorty.
LOAD_STRING_BY_TYPE(return_type, item->return_type_idx_, "inter_proto_id_item return_type_idx")
if (!CheckShortyDescriptorMatch(*shorty, return_type, true)) {
return false;
}
shorty++;
DexFileParameterIterator it(*dex_file_, *item);
while (it.HasNext() && *shorty != '\0') {
if (!CheckIndex(it.GetTypeIdx().index_,
dex_file_->NumTypeIds(),
"inter_proto_id_item shorty type_idx")) {
return false;
}
const char* descriptor = it.GetDescriptor();
if (!CheckShortyDescriptorMatch(*shorty, descriptor, false)) {
return false;
}
it.Next();
shorty++;
}
if (UNLIKELY(it.HasNext() || *shorty != '\0')) {
ErrorStringPrintf("Mismatched length for parameters and shorty");
return false;
}
// Check ordering between items. This relies on type_ids being in order.
if (previous_item_ != nullptr) {
const dex::ProtoId* prev = reinterpret_cast<const dex::ProtoId*>(previous_item_);
if (UNLIKELY(prev->return_type_idx_ > item->return_type_idx_)) {
ErrorStringPrintf("Out-of-order proto_id return types");
return false;
} else if (prev->return_type_idx_ == item->return_type_idx_) {
DexFileParameterIterator curr_it(*dex_file_, *item);
DexFileParameterIterator prev_it(*dex_file_, *prev);
while (curr_it.HasNext() && prev_it.HasNext()) {
dex::TypeIndex prev_idx = prev_it.GetTypeIdx();
dex::TypeIndex curr_idx = curr_it.GetTypeIdx();
DCHECK_NE(prev_idx, dex::TypeIndex(DexFile::kDexNoIndex16));
DCHECK_NE(curr_idx, dex::TypeIndex(DexFile::kDexNoIndex16));
if (prev_idx < curr_idx) {
break;
} else if (UNLIKELY(prev_idx > curr_idx)) {
ErrorStringPrintf("Out-of-order proto_id arguments");
return false;
}
prev_it.Next();
curr_it.Next();
}
if (!curr_it.HasNext()) {
// Either a duplicate ProtoId or a ProtoId with a shorter argument list follows
// a ProtoId with a longer one. Both cases are forbidden by the specification.
ErrorStringPrintf("Out-of-order proto_id arguments");
return false;
}
}
}
ptr_ += sizeof(dex::ProtoId);
return true;
}
bool DexFileVerifier::CheckInterFieldIdItem() {
const dex::FieldId* item = reinterpret_cast<const dex::FieldId*>(ptr_);
// Check that the class descriptor is valid.
LOAD_STRING_BY_TYPE(class_descriptor, item->class_idx_, "inter_field_id_item class_idx")
if (UNLIKELY(!IsValidDescriptor(class_descriptor) || class_descriptor[0] != 'L')) {
ErrorStringPrintf("Invalid descriptor for class_idx: '%s'", class_descriptor);
return false;
}
// Check that the type descriptor is a valid field name.
LOAD_STRING_BY_TYPE(type_descriptor, item->type_idx_, "inter_field_id_item type_idx")
if (UNLIKELY(!IsValidDescriptor(type_descriptor) || type_descriptor[0] == 'V')) {
ErrorStringPrintf("Invalid descriptor for type_idx: '%s'", type_descriptor);
return false;
}
// Check that the name is valid.
LOAD_STRING(descriptor, item->name_idx_, "inter_field_id_item name_idx")
if (UNLIKELY(!IsValidMemberName(descriptor))) {
ErrorStringPrintf("Invalid field name: '%s'", descriptor);
return false;
}
// Check ordering between items. This relies on the other sections being in order.
if (previous_item_ != nullptr) {
const dex::FieldId* prev_item = reinterpret_cast<const dex::FieldId*>(previous_item_);
if (UNLIKELY(prev_item->class_idx_ > item->class_idx_)) {
ErrorStringPrintf("Out-of-order field_ids");
return false;
} else if (prev_item->class_idx_ == item->class_idx_) {
if (UNLIKELY(prev_item->name_idx_ > item->name_idx_)) {
ErrorStringPrintf("Out-of-order field_ids");
return false;
} else if (prev_item->name_idx_ == item->name_idx_) {
if (UNLIKELY(prev_item->type_idx_ >= item->type_idx_)) {
ErrorStringPrintf("Out-of-order field_ids");
return false;
}
}
}
}
ptr_ += sizeof(dex::FieldId);
return true;
}
bool DexFileVerifier::CheckInterMethodIdItem() {
const dex::MethodId* item = reinterpret_cast<const dex::MethodId*>(ptr_);
// Check that the class descriptor is a valid reference name.
LOAD_STRING_BY_TYPE(class_descriptor, item->class_idx_, "inter_method_id_item class_idx")
if (UNLIKELY(!IsValidDescriptor(class_descriptor) || (class_descriptor[0] != 'L' &&
class_descriptor[0] != '['))) {
ErrorStringPrintf("Invalid descriptor for class_idx: '%s'", class_descriptor);
return false;
}
// Check that the name is valid.
LOAD_STRING(descriptor, item->name_idx_, "inter_method_id_item name_idx")
if (UNLIKELY(!IsValidMemberName(descriptor))) {
ErrorStringPrintf("Invalid method name: '%s'", descriptor);
return false;
}
// Check that the proto id is valid.
if (UNLIKELY(!CheckIndex(item->proto_idx_.index_, dex_file_->NumProtoIds(),
"inter_method_id_item proto_idx"))) {
return false;
}
// Check ordering between items. This relies on the other sections being in order.
if (previous_item_ != nullptr) {
const dex::MethodId* prev_item = reinterpret_cast<const dex::MethodId*>(previous_item_);
if (UNLIKELY(prev_item->class_idx_ > item->class_idx_)) {
ErrorStringPrintf("Out-of-order method_ids");
return false;
} else if (prev_item->class_idx_ == item->class_idx_) {
if (UNLIKELY(prev_item->name_idx_ > item->name_idx_)) {
ErrorStringPrintf("Out-of-order method_ids");
return false;
} else if (prev_item->name_idx_ == item->name_idx_) {
if (UNLIKELY(prev_item->proto_idx_ >= item->proto_idx_)) {
ErrorStringPrintf("Out-of-order method_ids");
return false;
}
}
}
}
ptr_ += sizeof(dex::MethodId);
return true;
}
bool DexFileVerifier::CheckInterClassDefItem() {
const dex::ClassDef* item = reinterpret_cast<const dex::ClassDef*>(ptr_);
// Check that class_idx_ is representable as a uint16_t;
if (UNLIKELY(!IsValidTypeId(item->class_idx_.index_, item->pad1_))) {
ErrorStringPrintf("class with type idx outside uint16_t range '%x:%x'", item->pad1_,
item->class_idx_.index_);
return false;
}
// Check that superclass_idx_ is representable as a uint16_t;
if (UNLIKELY(!IsValidOrNoTypeId(item->superclass_idx_.index_, item->pad2_))) {
ErrorStringPrintf("class with superclass type idx outside uint16_t range '%x:%x'", item->pad2_,
item->superclass_idx_.index_);
return false;
}
// Check for duplicate class def.
if (defined_classes_.find(item->class_idx_) != defined_classes_.end()) {
ErrorStringPrintf("Redefinition of class with type idx: '%d'", item->class_idx_.index_);
return false;
}
defined_classes_.insert(item->class_idx_);
LOAD_STRING_BY_TYPE(class_descriptor, item->class_idx_, "inter_class_def_item class_idx")
if (UNLIKELY(!IsValidDescriptor(class_descriptor) || class_descriptor[0] != 'L')) {
ErrorStringPrintf("Invalid class descriptor: '%s'", class_descriptor);
return false;
}
// Only allow non-runtime modifiers.
if ((item->access_flags_ & ~kAccJavaFlagsMask) != 0) {
ErrorStringPrintf("Invalid class flags: '%d'", item->access_flags_);
return false;
}
if (item->interfaces_off_ != 0 &&
!CheckOffsetToTypeMap(item->interfaces_off_, DexFile::kDexTypeTypeList)) {
return false;
}
if (item->annotations_off_ != 0 &&
!CheckOffsetToTypeMap(item->annotations_off_, DexFile::kDexTypeAnnotationsDirectoryItem)) {
return false;
}
if (item->class_data_off_ != 0 &&
!CheckOffsetToTypeMap(item->class_data_off_, DexFile::kDexTypeClassDataItem)) {
return false;
}
if (item->static_values_off_ != 0 &&
!CheckOffsetToTypeMap(item->static_values_off_, DexFile::kDexTypeEncodedArrayItem)) {
return false;
}
if (item->superclass_idx_.IsValid()) {
if (header_->GetVersion() >= DexFile::kClassDefinitionOrderEnforcedVersion) {
// Check that a class does not inherit from itself directly (by having
// the same type idx as its super class).
if (UNLIKELY(item->superclass_idx_ == item->class_idx_)) {
ErrorStringPrintf("Class with same type idx as its superclass: '%d'",
item->class_idx_.index_);
return false;
}
// Check that a class is defined after its super class (if the
// latter is defined in the same Dex file).
const dex::ClassDef* superclass_def = dex_file_->FindClassDef(item->superclass_idx_);
if (superclass_def != nullptr) {
// The superclass is defined in this Dex file.
if (superclass_def > item) {
// ClassDef item for super class appearing after the class' ClassDef item.
ErrorStringPrintf("Invalid class definition ordering:"
" class with type idx: '%d' defined before"
" superclass with type idx: '%d'",
item->class_idx_.index_,
item->superclass_idx_.index_);
return false;
}
}
}
LOAD_STRING_BY_TYPE(superclass_descriptor, item->superclass_idx_,
"inter_class_def_item superclass_idx")
if (UNLIKELY(!IsValidDescriptor(superclass_descriptor) || superclass_descriptor[0] != 'L')) {
ErrorStringPrintf("Invalid superclass: '%s'", superclass_descriptor);
return false;
}
}
// Check interfaces.
const dex::TypeList* interfaces = dex_file_->GetInterfacesList(*item);
if (interfaces != nullptr) {
uint32_t size = interfaces->Size();
for (uint32_t i = 0; i < size; i++) {
if (header_->GetVersion() >= DexFile::kClassDefinitionOrderEnforcedVersion) {
// Check that a class does not implement itself directly (by having the
// same type idx as one of its immediate implemented interfaces).