constexpr uint32_t MapTypeToBitMask(DexFile::MapItemType map_item_type) { switch (map_item_type) { case DexFile::kDexTypeHeaderItem: return1 << 0; case DexFile::kDexTypeStringIdItem: return1 << 1; case DexFile::kDexTypeTypeIdItem: return1 << 2; case DexFile::kDexTypeProtoIdItem: return1 << 3; case DexFile::kDexTypeFieldIdItem: return1 << 4; case DexFile::kDexTypeMethodIdItem: return1 << 5; case DexFile::kDexTypeClassDefItem: return1 << 6; case DexFile::kDexTypeCallSiteIdItem: return1 << 7; case DexFile::kDexTypeMethodHandleItem: return1 << 8; case DexFile::kDexTypeMapList: return1 << 9; case DexFile::kDexTypeTypeList: return1 << 10; case DexFile::kDexTypeAnnotationSetRefList: return1 << 11; case DexFile::kDexTypeAnnotationSetItem: return1 << 12; case DexFile::kDexTypeClassDataItem: return1 << 13; case DexFile::kDexTypeCodeItem: return1 << 14; case DexFile::kDexTypeStringDataItem: return1 << 15; case DexFile::kDexTypeDebugInfoItem: return1 << 16; case DexFile::kDexTypeAnnotationItem: return1 << 17; case DexFile::kDexTypeEncodedArrayItem: return1 << 18; case DexFile::kDexTypeAnnotationsDirectoryItem: return1 << 19; case DexFile::kDexTypeHiddenapiClassData: return1 << 20;
} return0;
}
constexpr 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: returnfalse; 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: returntrue;
} returntrue;
}
// Fields and methods may have only one of public/protected/private.
ALWAYS_INLINE
constexpr bool CheckAtMostOneOfPublicProtectedPrivate(uint32_t flags) {
static_assert(IsPowerOfTwo(kAccPublic), "kAccPublic not marked as power of two");
static_assert(IsPowerOfTwo(kAccProtected), "kAccProtected not marked as power of two");
static_assert(IsPowerOfTwo(kAccPrivate), "kAccPrivate not marked as power of two"); return POPCOUNT(flags & (kAccPublic | kAccProtected | kAccPrivate)) <= 1;
}
} // namespace
// Note: the anonymous namespace would be nice, but we need friend access into accessors.
// Converts the pointer `ptr` into `offset`. // Returns `true` if the offset is within the bounds of the container. // TODO: Try to remove this overload. Avoid creating invalid pointers.
ALWAYS_INLINE WARN_UNUSED bool PtrToOffset(constvoid* ptr, /*out*/ size_t* offset) {
*offset = reinterpret_cast<const uint8_t*>(ptr) - offset_base_address_; return *offset <= size_;
}
// Helper functions to retrieve names from the dex file. We do not want to rely on DexFile // functionality, as we're still verifying the dex file.
std::string GetString(dex::StringIndex string_idx) { // All sources of the `string_idx` have already been checked in CheckIntraSection().
DCHECK_LT(string_idx.index_, header_->string_ids_size_); const dex::StringId& string_id =
OffsetToPtr<dex::StringId>(header_->string_ids_off_)[string_idx.index_];
// The string offset has been checked at the start of `CheckInterSection()` // to point to a string data item checked by `CheckIntraSection()`. const uint8_t* ptr = OffsetToPtr(string_id.string_data_off_);
DecodeUnsignedLeb128(&ptr); // Ignore the result. returnreinterpret_cast<constchar*>(ptr);
}
std::string GetClass(dex::TypeIndex class_idx) { // All sources of `class_idx` have already been checked in CheckIntraSection().
CHECK_LT(class_idx.index_, header_->type_ids_size_);
// The `type_id->descriptor_idx_` has already been checked in CheckIntraTypeIdItem(). // However, it may not have been checked to be a valid descriptor, so return the raw // string without converting with `PrettyDescriptor()`. return GetString(type_id.descriptor_idx_);
}
std::string GetFieldDescription(uint32_t idx) { // The `idx` has already been checked in `DexFileVerifier::CheckIntraClassDataItemFields()`.
CHECK_LT(idx, header_->field_ids_size_);
// Indexes in `*field_id` have already been checked in CheckIntraFieldIdItem().
std::string class_name = GetClass(field_id.class_idx_);
std::string field_name = GetString(field_id.name_idx_); return class_name + "." + field_name;
}
std::string GetMethodDescription(uint32_t idx) { // The `idx` has already been checked in `DexFileVerifier::CheckIntraClassDataItemMethods()`.
CHECK_LT(idx, header_->method_ids_size_);
// Indexes in `method_id` have already been checked in CheckIntraMethodIdItem().
std::string class_name = GetClass(method_id.class_idx_);
std::string method_name = GetString(method_id.name_idx_); return class_name + "." + method_name;
}
bool CheckShortyDescriptorMatch(char shorty_char, constchar* descriptor, bool is_return_type); bool CheckListSize(constvoid* start, size_t count, size_t element_size, constchar* label); // Check a list. The head is assumed to be at *ptr, and elements to be of size element_size. If // successful, the ptr will be moved forward the amount covered by the list. bool CheckList(size_t element_size, constchar* label, const uint8_t* *ptr); // Checks: // * the offset is zero (when size is zero), // * the offset falls within the area claimed by the file, // * the offset + size also falls within the area claimed by the file, and // * the alignment of the section bool CheckValidOffsetAndSize(uint32_t offset, uint32_t size, size_t alignment, constchar* label); // Checks whether the size is less than the limit.
ALWAYS_INLINE bool CheckSizeLimit(uint32_t size, uint32_t limit, constchar* label) { if (size > limit) {
ErrorStringPrintf("Size(%u) should not exceed limit(%u) for %s.", size, limit, label); returnfalse;
} returntrue;
}
ALWAYS_INLINE bool CheckIndex(uint32_t field, uint32_t limit, constchar* label) { if (UNLIKELY(field >= limit)) {
ErrorStringPrintf("Bad index for %s: %x >= %x", label, field, limit); returnfalse;
} returntrue;
}
// The encoded values, arrays and annotations are allowed to be very deeply nested, // so use heap todo-list instead of stack recursion (the work is done in LIFO order). struct ToDoItem {
uint32_t array_size = 0; // CheckArrayElement.
uint32_t annotation_size = 0; // CheckAnnotationElement.
uint32_t last_idx = kDexNoIndex; // CheckAnnotationElement.
}; using ToDoList = std::stack<ToDoItem>; bool CheckEncodedValue(); bool CheckEncodedArray(); bool CheckArrayElement(); bool CheckEncodedAnnotation(); bool CheckAnnotationElement(/*inout*/ uint32_t* last_idx); bool FlushToDoList();
bool CheckIntraTypeIdItem(); bool CheckIntraProtoIdItem(); bool CheckIntraFieldIdItem(); bool CheckIntraMethodIdItem(); bool CheckIntraClassDefItem(uint32_t class_def_index); bool CheckIntraMethodHandleItem(); bool CheckIntraTypeList(); // Check all fields of the given type, reading `encoded_field` entries from `ptr_`. // Check instance fields against duplicates with static fields. template <bool kStatic> bool CheckIntraClassDataItemFields(size_t num_fields,
ClassAccessor::Field* static_fields,
size_t num_static_fields); // Check direct or virtual methods, reading `encoded_method` entries from `ptr_`. // Check virtual methods against duplicates with direct methods. bool CheckIntraClassDataItemMethods(size_t num_methods,
ClassAccessor::Method* direct_methods,
size_t num_direct_methods); bool CheckIntraClassDataItem();
// Returns kDexNoIndex if there are no fields/methods, otherwise a 16-bit type index.
uint32_t FindFirstClassDataDefiner(const ClassAccessor& accessor);
uint32_t FindFirstAnnotationsDirectoryDefiner(const uint8_t* ptr);
// Check validity of the given access flags, interpreted for a field in the context of a class // with the given second access flags. bool CheckFieldAccessFlags(uint32_t idx,
uint32_t field_access_flags,
uint32_t class_access_flags,
std::string* error_message);
// Check validity of the given method and access flags, in the context of a class with the given // second access flags. bool CheckMethodAccessFlags(uint32_t method_index,
uint32_t method_access_flags,
uint32_t class_access_flags,
uint32_t constructor_flags_by_name, bool has_code, bool expect_direct,
std::string* error_message);
// Check validity of given method if it's a constructor or class initializer. bool CheckConstructorProperties(uint32_t method_index, uint32_t constructor_flags);
struct OffsetTypeMapEmptyFn { // Make a hash map slot empty by making the offset 0. Offset 0 is a valid dex file offset that // is in the offset of the dex file header. However, we only store data section items in the // map, and these are after the header. void MakeEmpty(std::pair<uint32_t, uint16_t>& pair) const {
pair.first = 0u;
} // Check if a hash map slot is empty. bool IsEmpty(const std::pair<uint32_t, uint16_t>& pair) const { return pair.first == 0;
}
}; struct OffsetTypeMapHashCompareFn { // Hash function for offset.
size_t operator()(const uint32_t key) const { return key;
} // std::equal function for offset. booloperator()(const uint32_t a, const uint32_t b) const { return a == b;
}
}; // Map from offset to dex file type, HashMap for performance reasons.
HashMap<uint32_t,
uint16_t,
OffsetTypeMapEmptyFn,
OffsetTypeMapHashCompareFn,
OffsetTypeMapHashCompareFn> offset_to_type_map_; const uint8_t* ptr_; constvoid* previous_item_;
std::string failure_reason_;
// Cached string indices for "interesting" entries wrt/ method names. Will be populated by // FindStringRangesForMethodNames (which is automatically called before verifying the // classdataitem section). // // Strings starting with '<' are in the range // [angle_bracket_start_index_,angle_bracket_end_index_). // angle_init_angle_index_ and angle_clinit_angle_index_ denote the indices of "<init>" and // "<clinit>", respectively. If any value is not found, the corresponding index will be larger // than any valid string index for this dex file. struct {
size_t angle_bracket_start_index;
size_t angle_bracket_end_index;
size_t angle_init_angle_index;
size_t angle_clinit_angle_index;
} init_indices_;
// A bitvector for verified type descriptors. Each bit corresponds to a type index. A set // bit denotes that the descriptor has been verified wrt/ IsValidDescriptor.
std::vector<char> verified_type_descriptors_;
// Set of type ids for which there are ClassDef elements in the dex file. Using a bitset // avoids all allocations. The bitset should be implemented as 8K of storage, which is // tight enough for all callers.
std::bitset<kTypeIdLimit + 1> defined_classes_;
// Class definition indexes, valid only if corresponding `defined_classes_[.]` is true.
std::vector<uint16_t> defined_class_indexes_;
// Used by CheckEncodedValue to avoid recursion. Field so we can reuse allocated memory.
ToDoList todo_;
};
template <typename ExtraCheckFn> bool DexFileVerifier::VerifyTypeDescriptor(dex::TypeIndex idx, constchar* error_msg,
ExtraCheckFn extra_check) { // All sources of the `idx` have already been checked in CheckIntraSection().
DCHECK_LT(idx.index_, header_->type_ids_size_);
bool DexFileVerifier::CheckShortyDescriptorMatch(char shorty_char, constchar* descriptor, bool is_return_type) { switch (shorty_char) { case'V': if (UNLIKELY(!is_return_type)) {
ErrorStringPrintf("Invalid use of void"); returnfalse;
}
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); returnfalse;
} break; case'L': if (UNLIKELY((descriptor[0] != 'L') && (descriptor[0] != '['))) {
ErrorStringPrintf("Shorty vs. type mismatch: '%c', '%s'", shorty_char, descriptor); returnfalse;
} break; default:
ErrorStringPrintf("Bad shorty character: '%c'", shorty_char); returnfalse;
} returntrue;
}
bool DexFileVerifier::CheckListSize(constvoid* start, size_t count, size_t elem_size, constchar* label) { // Check that element size is not 0.
DCHECK_NE(elem_size, 0U);
size_t offset; if (!PtrToOffset(start, &offset)) {
ErrorStringPrintf("Offset beyond end of file for %s: %zx to %zx", label, offset, size_); returnfalse;
}
// Calculate the number of elements that fit until the end of file, // rather than calculating the end of the range as that could overflow.
size_t max_elements = (size_ - offset) / elem_size; if (UNLIKELY(max_elements < count)) {
ErrorStringPrintf( "List too large for %s: %zx+%zu*%zu > %zx", label, offset, count, elem_size, size_); returnfalse;
}
returntrue;
}
bool DexFileVerifier::CheckList(size_t element_size, constchar* label, const uint8_t* *ptr) { // Check that the list is available. The first 4B are the count. if (!CheckListSize(*ptr, 1, 4U, label)) { returnfalse;
}
bool DexFileVerifier::CheckValidOffsetAndSize(uint32_t offset,
uint32_t size,
size_t alignment, constchar* label) { if (size == 0) { if (offset != 0) {
ErrorStringPrintf("Offset(%d) should be zero when size is zero for %s.", offset, label); returnfalse;
} returntrue;
}
size_t hdr_offset = PtrToOffset(header_); if (offset < hdr_offset) {
ErrorStringPrintf("Offset(%d) should be after header(%zu) for %s.", offset, hdr_offset, label); returnfalse;
} if (size_ <= offset) {
ErrorStringPrintf("Offset(%d) should be within file size(%zu) for %s.", offset, size_, label); returnfalse;
} // Check that offset + size is within the file size. Note that we use `<` to allow the section to // end at the same point as the file. Check written as a subtraction to be safe from overfow. if (size_ - offset < size) {
ErrorStringPrintf( "Section end(%d) should be within file size(%zu) for %s.", offset + size, size_, label); returnfalse;
} if (alignment != 0 && !IsAlignedParam(offset, alignment)) {
ErrorStringPrintf("Offset(%d) should be aligned by %zu for %s.", offset, alignment, label); returnfalse;
} returntrue;
}
// Check the endian. if (header_->endian_tag_ != DexFile::kDexEndianConstant) {
ErrorStringPrintf("Unexpected endian_tag: %x", header_->endian_tag_); returnfalse;
}
// Compute and verify the checksum in the header.
uint32_t adler_checksum = dex_file_->CalculateChecksum(); if (adler_checksum != header_->checksum_) { if (verify_checksum_) {
ErrorStringPrintf("Bad checksum (%08x, expected %08x)", adler_checksum, header_->checksum_); returnfalse;
} else {
LOG(WARNING) << StringPrintf( "Ignoring bad checksum (%08x, expected %08x)", adler_checksum, header_->checksum_);
}
}
if (dex_version_ >= 41) { auto headerV41 = reinterpret_cast<const DexFile::HeaderV41*>(header_);
// Container size smaller than header. if (headerV41->container_size_ <= headerV41->header_offset_) {
ErrorStringPrintf("Dex container is too small: size=%ud header_offset=%ud",
headerV41->container_size_,
headerV41->header_offset_); returnfalse;
}
// Claimed container size vs actual.
size_t actual_container_size = dex_file_->GetContainer()->Size(); if (headerV41->container_size_ > actual_container_size) {
ErrorStringPrintf("Claimed container size (%ud) exceeds actual container size (%zu)",
headerV41->container_size_,
actual_container_size); returnfalse;
}
// Check that the DEX file is within the container.
uint32_t remainder = headerV41->container_size_ - headerV41->header_offset_; if (headerV41->file_size_ > remainder) {
ErrorStringPrintf( "Header file_size(%ud) is past multi-dex size(%ud)", headerV41->file_size_, remainder); returnfalse;
}
}
// Check that all offsets are inside the file. bool ok =
CheckValidOffsetAndSize(header_->link_off_,
header_->link_size_, /* alignment= */ 0, "link") &&
CheckValidOffsetAndSize(header_->map_off_, sizeof(dex::MapList), /* 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");
// Check the validity of the size of the map list. if (!CheckListSize(item, count, sizeof(dex::MapItem), "map size")) { returnfalse;
}
// 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); returnfalse;
} if (UNLIKELY(item->offset_ >= size_)) {
ErrorStringPrintf("Map item after end of file: %x, size %zx", item->offset_, size_); returnfalse;
}
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)); returnfalse;
}
size_t alignment; switch (item_type) { case DexFile::kDexTypeClassDataItem: case DexFile::kDexTypeStringDataItem: case DexFile::kDexTypeDebugInfoItem: case DexFile::kDexTypeAnnotationItem: case DexFile::kDexTypeEncodedArrayItem:
alignment = sizeof(uint8_t); break; default:
alignment = sizeof(uint32_t); break;
}
if (!IsAlignedParam(item->offset_, alignment)) {
ErrorStringPrintf("Offset(%d) should be aligned by %zu for maplist item of type %hu.",
item->offset_,
alignment,
item->type_); returnfalse;
}
if (catch_all) {
DECODE_UNSIGNED_CHECKED_FROM(ptr_, addr); if (UNLIKELY(addr >= accessor.InsnsSizeInCodeUnits())) {
ErrorStringPrintf("Invalid handler catch_all_addr: %x", addr); returnfalse;
}
}
}
returntrue;
}
bool DexFileVerifier::CheckClassDataItemField(uint32_t idx,
uint32_t access_flags,
uint32_t class_access_flags,
dex::TypeIndex class_type_index) { // The `idx` has already been checked in `CheckIntraClassDataItemFields()`.
DCHECK_LE(idx, header_->field_ids_size_);
// Check that it's the right class.
dex::TypeIndex my_class_index =
OffsetToPtr<dex::FieldId>(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_); returnfalse;
}
// Check field access flags.
std::string error_msg; if (!CheckFieldAccessFlags(idx, access_flags, class_access_flags, &error_msg)) {
ErrorStringPrintf("%s", error_msg.c_str()); returnfalse;
}
returntrue;
}
bool DexFileVerifier::CheckClassDataItemMethod(uint32_t idx,
uint32_t access_flags,
uint32_t class_access_flags,
dex::TypeIndex class_type_index,
uint32_t code_offset, bool expect_direct) { // The `idx` has already been checked in `CheckIntraClassDataItemMethods()`.
DCHECK_LT(idx, header_->method_ids_size_);
// 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_); returnfalse;
}
// Keep processing the rest of the to-do list until we are finished or encounter an error. bool DexFileVerifier::FlushToDoList() { while (!todo_.empty()) {
ToDoItem& item = todo_.top();
DCHECK(item.array_size == 0u || item.annotation_size == 0u); if (item.array_size > 0) {
item.array_size--; if (!CheckArrayElement()) { returnfalse;
}
} elseif (item.annotation_size > 0) {
item.annotation_size--; if (!CheckAnnotationElement(&item.last_idx)) { returnfalse;
}
} else {
todo_.pop();
}
} returntrue;
}
for (const ClassAccessor::Field& field : accessor.GetStaticFields()) { if (!array_it.HasNext()) { break;
}
uint32_t index = field.GetIndex(); // The `index` has already been checked in `CheckIntraClassDataItemFields()`.
DCHECK_LT(index, header_->field_ids_size_); const dex::TypeId& type_id = dex_file_->GetTypeId(dex_file_->GetFieldId(index).type_idx_); constchar* 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]); returnfalse;
} break; case EncodedArrayValueIterator::ValueType::kByte: if (field_type != Primitive::kPrimByte) {
ErrorStringPrintf("unexpected static field initial value type: 'B' vs '%c'",
field_type_name[0]); returnfalse;
} break; case EncodedArrayValueIterator::ValueType::kShort: if (field_type != Primitive::kPrimShort) {
ErrorStringPrintf("unexpected static field initial value type: 'S' vs '%c'",
field_type_name[0]); returnfalse;
} break; case EncodedArrayValueIterator::ValueType::kChar: if (field_type != Primitive::kPrimChar) {
ErrorStringPrintf("unexpected static field initial value type: 'C' vs '%c'",
field_type_name[0]); returnfalse;
} break; case EncodedArrayValueIterator::ValueType::kInt: if (field_type != Primitive::kPrimInt) {
ErrorStringPrintf("unexpected static field initial value type: 'I' vs '%c'",
field_type_name[0]); returnfalse;
} break; case EncodedArrayValueIterator::ValueType::kLong: if (field_type != Primitive::kPrimLong) {
ErrorStringPrintf("unexpected static field initial value type: 'J' vs '%c'",
field_type_name[0]); returnfalse;
} break; case EncodedArrayValueIterator::ValueType::kFloat: if (field_type != Primitive::kPrimFloat) {
ErrorStringPrintf("unexpected static field initial value type: 'F' vs '%c'",
field_type_name[0]); returnfalse;
} break; case EncodedArrayValueIterator::ValueType::kDouble: if (field_type != Primitive::kPrimDouble) {
ErrorStringPrintf("unexpected static field initial value type: 'D' vs '%c'",
field_type_name[0]); returnfalse;
} 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]); returnfalse;
} break; default:
ErrorStringPrintf("unexpected static field initial value type: %x", array_type); returnfalse;
} if (!array_it.MaybeNext()) {
ErrorStringPrintf("unexpected encoded value type: '%c'", array_it.GetValueType()); returnfalse;
}
}
if (array_it.HasNext()) {
ErrorStringPrintf("too many static field initial values"); returnfalse;
} returntrue;
}
// Check superclass, if any. if (UNLIKELY(class_def->pad2_ != 0u)) {
uint32_t combined =
(static_cast<uint32_t>(class_def->pad2_) << 16) + class_def->superclass_idx_.index_; if (combined != 0xffffffffu) {
ErrorStringPrintf("Invalid superclass type padding/index: %x", combined); returnfalse;
}
} elseif (!CheckIndex(class_def->superclass_idx_.index_,
header_->type_ids_size_, "class_def.superclass")) { returnfalse;
}
DCHECK_LE(class_def->class_idx_.index_, kTypeIdLimit);
DCHECK_LT(kTypeIdLimit, defined_classes_.size()); if (defined_classes_[class_def->class_idx_.index_]) {
ErrorStringPrintf("Redefinition of class with type idx: '%u'", class_def->class_idx_.index_); returnfalse;
}
defined_classes_[class_def->class_idx_.index_] = true;
DCHECK_LE(class_def->class_idx_.index_, defined_class_indexes_.size());
defined_class_indexes_[class_def->class_idx_.index_] = class_def_index;
DexFile::MethodHandleType method_handle_type = static_cast<DexFile::MethodHandleType>(item->method_handle_type_); if (method_handle_type > DexFile::MethodHandleType::kLast) {
ErrorStringPrintf("Bad method handle type %x", item->method_handle_type_); returnfalse;
}
uint32_t index = item->field_or_method_idx_; switch (method_handle_type) { case DexFile::MethodHandleType::kStaticPut: case DexFile::MethodHandleType::kStaticGet: case DexFile::MethodHandleType::kInstancePut: case DexFile::MethodHandleType::kInstanceGet: if (!CheckIndex(index, header_->field_ids_size_, "method_handle_item field_idx")) { returnfalse;
} break; case DexFile::MethodHandleType::kInvokeStatic: case DexFile::MethodHandleType::kInvokeInstance: case DexFile::MethodHandleType::kInvokeConstructor: case DexFile::MethodHandleType::kInvokeDirect: case DexFile::MethodHandleType::kInvokeInterface: { if (!CheckIndex(index, header_->method_ids_size_, "method_handle_item method_idx")) { returnfalse;
} break;
}
}
// We cannot use ClassAccessor::Field yet as it could read beyond the end of the data section. const uint8_t* ptr = ptr_;
// Load the first static field for the check below.
size_t remaining_static_fields = num_static_fields; if (remaining_static_fields != 0u) {
DCHECK(static_fields != nullptr);
static_fields->Read();
}
uint32_t prev_index = 0; for (size_t i = 0; i != num_fields; ++i) {
uint32_t field_idx_diff, access_flags; if (UNLIKELY(!DecodeUnsignedLeb128Checked(&ptr, data_.end(), &field_idx_diff)) ||
UNLIKELY(!DecodeUnsignedLeb128Checked(&ptr, data_.end(), &access_flags))) {
ErrorStringPrintf("encoded_field read out of bounds"); returnfalse;
}
uint32_t curr_index = prev_index + field_idx_diff; // Check for overflow. if (!CheckIndex(curr_index, header_->field_ids_size_, "class_data_item field_idx")) { returnfalse;
} if (!CheckOrder(kTypeDescr, curr_index, prev_index)) { returnfalse;
} // Check that it falls into the right class-data list. bool is_static = (access_flags & kAccStatic) != 0; if (UNLIKELY(is_static != kStatic)) {
ErrorStringPrintf("Static/instance field not in expected list"); returnfalse;
}
// For instance fields, we cross reference the field index to make sure // it doesn't match any static fields. if (remaining_static_fields != 0) { // The static fields are already known to be in ascending index order. // So just keep up with the current index. while (true) { const uint32_t static_idx = static_fields->GetIndex(); if (static_idx > curr_index) { break;
} if (static_idx == curr_index) {
ErrorStringPrintf("Found instance field with same index as static field: %u",
curr_index); returnfalse;
}
--remaining_static_fields; if (remaining_static_fields == 0u) { break;
}
static_fields->Read();
}
}
// We cannot use ClassAccessor::Method yet as it could read beyond the end of the data section. const uint8_t* ptr = ptr_;
// Load the first direct method for the check below.
size_t remaining_direct_methods = num_direct_methods; if (remaining_direct_methods != 0u) {
DCHECK(direct_methods != nullptr);
direct_methods->Read();
}
uint32_t prev_index = 0; for (size_t i = 0; i != num_methods; ++i) {
uint32_t method_idx_diff, access_flags, code_off; if (UNLIKELY(!DecodeUnsignedLeb128Checked(&ptr, data_.end(), &method_idx_diff)) ||
UNLIKELY(!DecodeUnsignedLeb128Checked(&ptr, data_.end(), &access_flags)) ||
UNLIKELY(!DecodeUnsignedLeb128Checked(&ptr, data_.end(), &code_off))) {
ErrorStringPrintf("encoded_method read out of bounds"); returnfalse;
}
uint32_t curr_index = prev_index + method_idx_diff; // Check for overflow. if (!CheckIndex(curr_index, header_->method_ids_size_, "class_data_item method_idx")) { returnfalse;
} if (!CheckOrder(kTypeDescr, curr_index, prev_index)) { returnfalse;
}
// For virtual methods, we cross reference the method index to make sure // it doesn't match any direct methods. if (remaining_direct_methods != 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_methods->GetIndex(); if (direct_idx > curr_index) { break;
} if (direct_idx == curr_index) {
ErrorStringPrintf("Found virtual method with same index as direct method: %u",
curr_index); returnfalse;
}
--remaining_direct_methods; if (remaining_direct_methods == 0u) { break;
}
direct_methods->Read();
}
}
prev_index = curr_index;
}
ptr_ = ptr; returntrue;
}
bool DexFileVerifier::CheckIntraClassDataItem() { // We cannot use ClassAccessor yet as it could read beyond the end of the data section. const uint8_t* ptr = ptr_;
uint32_t static_fields_size, instance_fields_size, direct_methods_size, virtual_methods_size; if (UNLIKELY(!DecodeUnsignedLeb128Checked(&ptr, data_.end(), &static_fields_size)) ||
UNLIKELY(!DecodeUnsignedLeb128Checked(&ptr, data_.end(), &instance_fields_size)) ||
UNLIKELY(!DecodeUnsignedLeb128Checked(&ptr, data_.end(), &direct_methods_size)) ||
UNLIKELY(!DecodeUnsignedLeb128Checked(&ptr, data_.end(), &virtual_methods_size))) {
ErrorStringPrintf("class_data_item read out of bounds"); returnfalse;
}
ptr_ = ptr;
// Check fields. const uint8_t* static_fields_ptr = ptr_; if (!CheckIntraClassDataItemFields</*kStatic=*/ true>(static_fields_size, /*static_fields=*/ nullptr, /*num_static_fields=*/ 0u)) { returnfalse;
} // Static fields have been checked, so we can now use ClassAccessor::Field to read them again.
ClassAccessor::Field static_fields(*dex_file_, static_fields_ptr); if (!CheckIntraClassDataItemFields</*kStatic=*/ false>(instance_fields_size,
&static_fields,
static_fields_size)) { returnfalse;
}
// Check methods. const uint8_t* direct_methods_ptr = ptr_; if (!CheckIntraClassDataItemMethods(direct_methods_size, /*direct_methods=*/ nullptr, /*num_direct_methods=*/ 0u)) { returnfalse;
} // Direct methods have been checked, so we can now use ClassAccessor::Method to read them again.
ClassAccessor::Method direct_methods(*dex_file_, direct_methods_ptr); if (!CheckIntraClassDataItemMethods(virtual_methods_size, &direct_methods, direct_methods_size)) { returnfalse;
}
// 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]); returntrue;
}
size_t available_bytes = static_cast<size_t>(file_end - ptr_); if (available_bytes < size) {
ErrorStringPrintf("String data would go beyond end-of-file"); returnfalse;
} // Eagerly subtract one byte per character.
available_bytes -= size;
for (uint32_t i = 0; i < size; i++) {
CHECK_LT(i, size); // b/15014252 Prevents hitting the impossible case below
uint8_t byte = *(ptr_++);
// Switch on the high 4 bits. switch (byte >> 4) { case0x00: // 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); returnfalse;
} break; case0x01: case0x02: case0x03: case0x04: case0x05: case0x06: case0x07: // No extra checks necessary for bit pattern 0xxx. break; case0x08: case0x09: case0x0a: case0x0b: case0x0f: // 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); returnfalse; case0x0c: case0x0d: { // Bit pattern 110x has an additional byte. if (available_bytes < 1u) {
ErrorStringPrintf("String data would go beyond end-of-file"); returnfalse;
}
available_bytes -= 1u;
uint8_t byte2 = *(ptr_++); if (UNLIKELY((byte2 & 0xc0) != 0x80)) {
ErrorStringPrintf("Illegal continuation byte %x in string data", byte2); returnfalse;
}
uint16_t value = ((byte & 0x1f) << 6) | (byte2 & 0x3f); if (UNLIKELY((value != 0) && (value < 0x80))) {
ErrorStringPrintf("Illegal representation for value %x in string data", value); returnfalse;
} break;
} case0x0e: { // Bit pattern 1110 has 2 additional bytes. if (available_bytes < 2u) {
ErrorStringPrintf("String data would go beyond end-of-file"); returnfalse;
}
available_bytes -= 2u;
uint8_t byte2 = *(ptr_++); if (UNLIKELY((byte2 & 0xc0) != 0x80)) {
ErrorStringPrintf("Illegal continuation byte %x in string data", byte2); returnfalse;
}
uint8_t byte3 = *(ptr_++); if (UNLIKELY((byte3 & 0xc0) != 0x80)) {
ErrorStringPrintf("Illegal continuation byte %x in string data", byte3); returnfalse;
}
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); returnfalse;
} break;
}
}
}
if (available_bytes < 1u) {
ErrorStringPrintf("String data would go beyond end-of-file"); returnfalse;
}
available_bytes -= 1u;
if (UNLIKELY(*(ptr_++) != '\0')) {
ErrorStringPrintf("String longer than indicated size %x", size); returnfalse;
}
// Check total size. if (!CheckListSize(item, item->size_, 1u, "hiddenapi class data section")) { returnfalse;
}
// 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); returnfalse;
}
// The rest of the section depends on the class_data_item being verified first. We will finalize // verifying the hiddenapi_class_data_item in CheckInterHiddenapiClassData. const uint8_t* data_end = ptr_ + item->size_;
ptr_ = data_end; returntrue;
}
last_idx = 0; for (uint32_t i = 0; i < parameter_count; i++) { if (!CheckIndex(parameter_item->method_idx_,
header_->method_ids_size_, "parameter annotation method")) { returnfalse;
} 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_); returnfalse;
}
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); returntrue;
}
template <DexFile::MapItemType kType> bool DexFileVerifier::CheckIntraSectionIterate(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 = (PtrToOffset(ptr_) + alignment_mask) & ~alignment_mask;
// Check the padding between items. if (!CheckPadding(aligned_offset, kType)) { returnfalse;
}
// 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")) { returnfalse;
}
ptr_ += sizeof(dex::StringId); break;
} case DexFile::kDexTypeTypeIdItem: { if (!CheckIntraTypeIdItem()) { returnfalse;
} break;
} case DexFile::kDexTypeProtoIdItem: { if (!CheckIntraProtoIdItem()) { returnfalse;
} break;
} case DexFile::kDexTypeFieldIdItem: { if (!CheckIntraFieldIdItem()) { returnfalse;
} break;
} case DexFile::kDexTypeMethodIdItem: { if (!CheckIntraMethodIdItem()) { returnfalse;
} break;
} case DexFile::kDexTypeClassDefItem: { if (!CheckIntraClassDefItem(/*class_def_index=*/ i)) { returnfalse;
} break;
} case DexFile::kDexTypeCallSiteIdItem: { if (!CheckListSize(ptr_, 1, sizeof(dex::CallSiteIdItem), "call_site_ids")) { returnfalse;
}
ptr_ += sizeof(dex::CallSiteIdItem); break;
} case DexFile::kDexTypeMethodHandleItem: { if (!CheckIntraMethodHandleItem()) { returnfalse;
} break;
} case DexFile::kDexTypeTypeList: { if (!CheckIntraTypeList()) { returnfalse;
} break;
} case DexFile::kDexTypeAnnotationSetRefList: { if (!CheckList(sizeof(dex::AnnotationSetRefItem), "annotation_set_ref_list", &ptr_)) { returnfalse;
} break;
} case DexFile::kDexTypeAnnotationSetItem: { if (!CheckList(sizeof(uint32_t), "annotation_set_item", &ptr_)) { returnfalse;
} break;
} case DexFile::kDexTypeClassDataItem: { if (!CheckIntraClassDataItem()) { returnfalse;
} break;
} case DexFile::kDexTypeCodeItem: { if (!CheckIntraCodeItem()) { returnfalse;
} break;
} case DexFile::kDexTypeStringDataItem: { if (!CheckIntraStringDataItem()) { returnfalse;
} break;
} case DexFile::kDexTypeDebugInfoItem: { if (!CheckIntraDebugInfoItem()) { returnfalse;
} break;
} case DexFile::kDexTypeAnnotationItem: { if (!CheckIntraAnnotationItem()) { returnfalse;
} break;
} case DexFile::kDexTypeEncodedArrayItem: {
CHECK(todo_.empty()); if (!CheckEncodedArray() || !FlushToDoList()) { returnfalse;
} break;
} case DexFile::kDexTypeAnnotationsDirectoryItem: { if (!CheckIntraAnnotationsDirectoryItem()) { returnfalse;
} break;
} case DexFile::kDexTypeHiddenapiClassData: { if (!CheckIntraHiddenapiClassData()) { returnfalse;
} break;
} case DexFile::kDexTypeHeaderItem: case DexFile::kDexTypeMapList: break;
}
if (start_ptr == ptr_) {
ErrorStringPrintf("Unknown map item type %x", kType); returnfalse;
}
if (IsDataSectionType(kType)) { if (aligned_offset == 0u) {
ErrorStringPrintf("Item %d offset is 0", i); returnfalse;
}
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));
}
if (!PtrToOffset(ptr_, &aligned_offset)) {
ErrorStringPrintf("Item %d at ends out of bounds", i); returnfalse;
}
}
// 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); returnfalse;
}
// 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); returnfalse;
} if (UNLIKELY(count != expected_size)) {
ErrorStringPrintf("Bad size for section: got %x, expected %x", count, expected_size); returnfalse;
}
// Check the validity of the offset of the section. if (UNLIKELY((offset < data_start) || (offset > data_end))) {
ErrorStringPrintf("Bad offset for data subsection: %zx", offset); returnfalse;
}
if (!CheckIntraSectionIterate<kType>(count)) { returnfalse;
}
// FIXME: Doing this check late means we may have already read memory outside the // data section and potentially outside the file, thus risking a segmentation fault.
size_t next_offset; if (!PtrToOffset(ptr_, &next_offset) || 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_); returnfalse;
}
// Preallocate offset map to avoid some allocations. We can only guess from the list items, // not derived things.
offset_to_type_map_.reserve(
std::min(header_->class_defs_size_, 65535u) +
std::min(header_->string_ids_size_, 65535u) + 2 * std::min(header_->method_ids_size_, 65535u));
// Check the items listed in the map. for (; count != 0u; --count) { const uint8_t* initial_ptr = ptr_;
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.
size_t offset = PtrToOffset(ptr_); if (UNLIKELY(offset > section_offset)) {
ErrorStringPrintf("Section overlap or out-of-order map: %zx, %x", offset, section_offset); returnfalse;
} if (!CheckPadding(section_offset, type)) { returnfalse;
}
// Check each item based on its type. switch (type) { case DexFile::kDexTypeHeaderItem: { if (UNLIKELY(section_count != 1)) {
ErrorStringPrintf("Multiple header items"); returnfalse;
}
uint32_t expected = dex_version_ >= 41 ? PtrToOffset(dex_file_->Begin()) : 0; if (UNLIKELY(section_offset != expected)) {
ErrorStringPrintf("Header at %x, expected %x", section_offset, expected); returnfalse;
}
ptr_ += header_->header_size_; break;
}
if (ptr_ == initial_ptr) {
ErrorStringPrintf("Unknown map item type %x", type); returnfalse;
}
item++;
}
returntrue;
}
bool DexFileVerifier::CheckOffsetToTypeMap(size_t offset, uint16_t type) {
DCHECK(offset_to_type_map_.find(0) == offset_to_type_map_.end()); 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); returnfalse;
} if (UNLIKELY(it->second != type)) {
ErrorStringPrintf("Unexpected data map entry @ %zx; expected %x, found %x",
offset, type, it->second); returnfalse;
} returntrue;
}
uint32_t DexFileVerifier::FindFirstClassDataDefiner(const ClassAccessor& accessor) { // The data item and field/method indexes have already been checked in // `CheckIntraClassDataItem()` or its helper functions. if (accessor.NumFields() != 0) {
ClassAccessor::Field read_field(*dex_file_, accessor.ptr_pos_);
read_field.Read();
DCHECK_LE(read_field.GetIndex(), dex_file_->NumFieldIds()); return dex_file_->GetFieldId(read_field.GetIndex()).class_idx_.index_;
}
uint32_t DexFileVerifier::FindFirstAnnotationsDirectoryDefiner(const uint8_t* ptr) { // The annotations directory and field/method indexes have already been checked in // `CheckIntraAnnotationsDirectoryItem()`. const dex::AnnotationsDirectoryItem* item = reinterpret_cast<const dex::AnnotationsDirectoryItem*>(ptr);
// Move pointer after the header. This data has been verified in CheckIntraHiddenapiClassData.
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; 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); returnfalse;
}
// 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); returnfalse;
}
// 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); returnfalse;
}
// Parse a uleb128 value for each field and method of this class. bool failure = false; auto fn_member = [&](const ClassAccessor::BaseItem& member, constchar* 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::ApiList::FromDexFlags(decoded_flags).IsValid()) {
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) { returnfalse;
}
}
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_); returnfalse;
}
{ // Translate to index to potentially use cache. // The check in `CheckIntraIdSection()` guarantees that this index is valid.
size_t index = item - OffsetToPtr<dex::TypeId>(header_->type_ids_off_);
DCHECK_LE(index, header_->type_ids_size_); if (UNLIKELY(!VerifyTypeDescriptor(
dex::TypeIndex(static_cast<decltype(dex::TypeIndex::index_)>(index)), "Invalid type descriptor",
[](char) { returntrue; }))) { returnfalse;
}
}
// 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_); returnfalse;
}
}
if (item->parameters_off_ != 0 &&
!CheckOffsetToTypeMap(item->parameters_off_, DexFile::kDexTypeTypeList)) { returnfalse;
}
// 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_); returnfalse;
} // Check the return type and advance the shorty. constchar* return_type = dex_file_->GetTypeDescriptor(item->return_type_idx_); if (!CheckShortyDescriptorMatch(*shorty, return_type, true)) { returnfalse;
}
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")) { returnfalse;
} constchar* descriptor = it.GetDescriptor(); if (!CheckShortyDescriptorMatch(*shorty, descriptor, false)) { returnfalse;
}
it.Next();
shorty++;
} if (UNLIKELY(it.HasNext() || *shorty != '\0')) {
ErrorStringPrintf("Mismatched length for parameters and shorty"); returnfalse;
}
// 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"); returnfalse;
} elseif (prev->return_type_idx_ == item->return_type_idx_) {
DexFileParameterIterator curr_it(*dex_file_, *item);
DexFileParameterIterator prev_it(*dex_file_, *prev);
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"); returnfalse;
}
}
}
// Check that the class descriptor is valid. if (UNLIKELY(!VerifyTypeDescriptor(item->class_idx_, "Invalid descriptor for class_idx",
[](char d) { return d == 'L'; }))) { returnfalse;
}
// Check that the type descriptor is a valid field name. if (UNLIKELY(!VerifyTypeDescriptor(item->type_idx_, "Invalid descriptor for type_idx",
[](char d) { return d != 'V'; }))) { returnfalse;
}
// Check that the name is valid. constchar* field_name = dex_file_->GetStringData(item->name_idx_); if (UNLIKELY(!IsValidMemberName(field_name))) {
ErrorStringPrintf("Invalid field name: '%s'", field_name); returnfalse;
}
// 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"); returnfalse;
} elseif (prev_item->class_idx_ == item->class_idx_) { if (UNLIKELY(prev_item->name_idx_ > item->name_idx_)) {
ErrorStringPrintf("Out-of-order field_ids"); returnfalse;
} elseif (prev_item->name_idx_ == item->name_idx_) { if (UNLIKELY(prev_item->type_idx_ >= item->type_idx_)) {
ErrorStringPrintf("Out-of-order field_ids"); returnfalse;
}
}
}
}
// Check that the class descriptor is a valid reference name. if (UNLIKELY(!VerifyTypeDescriptor(item->class_idx_, "Invalid descriptor for class_idx",
[](char d) { return d == 'L' || d == '['; }))) { returnfalse;
}
// Check that the name is valid. constchar* method_name = dex_file_->GetStringData(item->name_idx_); if (UNLIKELY(!IsValidMemberName(method_name))) {
ErrorStringPrintf("Invalid method name: '%s'", method_name); returnfalse;
}
// Check that the proto id is valid. if (UNLIKELY(!CheckIndex(item->proto_idx_.index_, dex_file_->NumProtoIds(), "inter_method_id_item proto_idx"))) { returnfalse;
}
// 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"); returnfalse;
} elseif (prev_item->class_idx_ == item->class_idx_) { if (UNLIKELY(prev_item->name_idx_ > item->name_idx_)) {
ErrorStringPrintf("Out-of-order method_ids"); returnfalse;
} elseif (prev_item->name_idx_ == item->name_idx_) { if (UNLIKELY(prev_item->proto_idx_ >= item->proto_idx_)) {
ErrorStringPrintf("Out-of-order method_ids"); returnfalse;
}
}
}
}
// 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_); returnfalse;
} // 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_); returnfalse;
} // Check for duplicate class def.
if (UNLIKELY(!VerifyTypeDescriptor(item->class_idx_, "Invalid class descriptor",
[](char d) { return d == 'L'; }))) { returnfalse;
}
// Only allow non-runtime modifiers. if ((item->access_flags_ & ~kAccJavaFlagsMask) != 0) {
ErrorStringPrintf("Invalid class flags: '%d'", item->access_flags_); returnfalse;
}
if (item->interfaces_off_ != 0 &&
!CheckOffsetToTypeMap(item->interfaces_off_, DexFile::kDexTypeTypeList)) { returnfalse;
} if (item->annotations_off_ != 0 &&
!CheckOffsetToTypeMap(item->annotations_off_, DexFile::kDexTypeAnnotationsDirectoryItem)) { returnfalse;
} if (item->class_data_off_ != 0 &&
!CheckOffsetToTypeMap(item->class_data_off_, DexFile::kDexTypeClassDataItem)) { returnfalse;
} if (item->static_values_off_ != 0 &&
!CheckOffsetToTypeMap(item->static_values_off_, DexFile::kDexTypeEncodedArrayItem)) { returnfalse;
}
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_); returnfalse;
}
// Check that a class is defined after its super class (if the // latter is defined in the same Dex file).
uint16_t superclass_idx = item->superclass_idx_.index_; if (defined_classes_[superclass_idx]) { // The superclass is defined in this Dex file. if (&dex_file_->GetClassDef(defined_class_indexes_[superclass_idx]) > 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_,
superclass_idx); returnfalse;
}
}
}
if (UNLIKELY(!VerifyTypeDescriptor(item->superclass_idx_, "Invalid superclass",
[](char d) { return d == 'L'; }))) { returnfalse;
}
}
// 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). if (UNLIKELY(interfaces->GetTypeItem(i).type_idx_ == item->class_idx_)) {
ErrorStringPrintf("Class with same type idx as implemented interface: '%d'",
item->class_idx_.index_); returnfalse;
}
// Check that a class is defined after the interfaces it implements // (if they are defined in the same Dex file).
uint16_t interface_idx = interfaces->GetTypeItem(i).type_idx_.index_; if (defined_classes_[interface_idx]) { // The interface is defined in this Dex file. if (&dex_file_->GetClassDef(defined_class_indexes_[interface_idx]) > item) { // ClassDef item for interface appearing after the class' ClassDef item.
ErrorStringPrintf("Invalid class definition ordering:" " class with type idx: '%d' defined before" " implemented interface with type idx: '%d'",
item->class_idx_.index_,
interface_idx); returnfalse;
}
}
}
// Ensure that the interface refers to a class (not an array nor a primitive type). if (UNLIKELY(!VerifyTypeDescriptor(interfaces->GetTypeItem(i).type_idx_, "Invalid interface",
[](char d) { return d == 'L'; }))) { returnfalse;
}
}
/* *Ensurethattherearenoduplicates.ThisisanO(N^2)test,butin *practicethenumberofinterfacesimplementedbyanygivenclassislow.
*/ for (uint32_t i = 1; i < size; i++) {
dex::TypeIndex idx1 = interfaces->GetTypeItem(i).type_idx_; for (uint32_t j =0; j < i; j++) {
dex::TypeIndex idx2 = interfaces->GetTypeItem(j).type_idx_; if (UNLIKELY(idx1 == idx2)) {
ErrorStringPrintf("Duplicate interface: '%s'", dex_file_->GetTypeDescriptor(idx1)); returnfalse;
}
}
}
}
// Check that references in class_data_item are to the right class. if (item->class_data_off_ != 0) {
ClassAccessor accessor(*dex_file_, OffsetToPtr(item->class_data_off_));
uint32_t data_definer = FindFirstClassDataDefiner(accessor);
DCHECK(IsUint<16>(data_definer) || data_definer == kDexNoIndex) << data_definer; if (UNLIKELY((data_definer != item->class_idx_.index_) && (data_definer != kDexNoIndex))) {
ErrorStringPrintf("Invalid class_data_item"); returnfalse;
}
}
// Check that references in annotations_directory_item are to right class. if (item->annotations_off_ != 0) { // annotations_off_ is supposed to be aligned by 4. if (!IsAlignedParam(item->annotations_off_, 4)) {
ErrorStringPrintf("Invalid annotations_off_, not aligned by 4"); returnfalse;
} const uint8_t* data = OffsetToPtr(item->annotations_off_);
uint32_t defining_class = FindFirstAnnotationsDirectoryDefiner(data);
DCHECK(IsUint<16>(defining_class) || defining_class == kDexNoIndex) << defining_class; if (UNLIKELY((defining_class != item->class_idx_.index_) && (defining_class != kDexNoIndex))) {
ErrorStringPrintf("Invalid annotations_directory_item"); returnfalse;
}
}
// Check call site referenced by item is in encoded array section. if (!CheckOffsetToTypeMap(item->data_off_, DexFile::kDexTypeEncodedArrayItem)) {
DCHECK(!failure_reason_.empty()); // Error already set. returnfalse;
}
uint32_t handle_index = static_cast<uint32_t>(it.GetJavaValue().i); if (handle_index >= dex_file_->NumMethodHandles()) {
ErrorStringPrintf("CallSite has bad method handle id: %x", handle_index); returnfalse;
}
// Check target method name. if (!it.MaybeNext()) {
ErrorStringPrintf("unexpected encoded value type: '%c'", it.GetValueType()); returnfalse;
} if (!it.HasNext() ||
it.GetValueType() != EncodedArrayValueIterator::ValueType::kString) {
ErrorStringPrintf("CallSiteArray missing target method name"); returnfalse;
}
uint32_t name_index = static_cast<uint32_t>(it.GetJavaValue().i); if (name_index >= dex_file_->NumStringIds()) {
ErrorStringPrintf("CallSite has bad method name id: %x", name_index); returnfalse;
}
// Check method type. if (!it.MaybeNext()) {
ErrorStringPrintf("unexpected encoded value type: '%c'", it.GetValueType()); returnfalse;
} if (!it.HasNext() ||
it.GetValueType() != EncodedArrayValueIterator::ValueType::kMethodType) {
ErrorStringPrintf("CallSiteArray missing method type"); returnfalse;
}
uint32_t proto_index = static_cast<uint32_t>(it.GetJavaValue().i); if (proto_index >= dex_file_->NumProtoIds()) {
ErrorStringPrintf("CallSite has bad method type: %x", proto_index); returnfalse;
}
for (uint32_t i = 0; i < count; i++) { if (!CheckOffsetToTypeMap(*offsets, DexFile::kDexTypeAnnotationItem)) { returnfalse;
}
// Get the annotation from the offset and the type index for the annotation. const dex::AnnotationItem* annotation = OffsetToPtr<dex::AnnotationItem>(*offsets); const uint8_t* data = annotation->annotation_;
DECODE_UNSIGNED_CHECKED_FROM(data, idx);
if (UNLIKELY(last_idx >= idx && i != 0)) {
ErrorStringPrintf("Out-of-order entry types: %x then %x", last_idx, idx); returnfalse;
}
bool DexFileVerifier::CheckInterClassDataItem() {
ClassAccessor accessor(*dex_file_, ptr_);
uint32_t defining_class = FindFirstClassDataDefiner(accessor);
DCHECK(IsUint<16>(defining_class) || defining_class == kDexNoIndex) << defining_class; if (defining_class == kDexNoIndex) { // Empty definitions are OK and could be shared by multiple classes.
ptr_ = accessor.ptr_pos_; // Move over the empty `class_data_item`. returntrue;
} if (!defined_classes_[defining_class]) { // Should really have a class definition for this class data item.
ErrorStringPrintf("Could not find declaring class for non-empty class data item."); returnfalse;
} const dex::TypeIndex class_type_index(defining_class); const dex::ClassDef& class_def = dex_file_->GetClassDef(defined_class_indexes_[defining_class]);
for (const ClassAccessor::Field& read_field : accessor.GetFields()) { // The index has already been checked in `CheckIntraClassDataItemFields()`.
DCHECK_LE(read_field.GetIndex(), header_->field_ids_size_); const dex::FieldId& field = dex_file_->GetFieldId(read_field.GetIndex()); if (UNLIKELY(field.class_idx_ != class_type_index)) {
ErrorStringPrintf("Mismatched defining class for class_data_item field"); returnfalse;
} if (!CheckClassDataItemField(read_field.GetIndex(),
read_field.GetAccessFlags(),
class_def.access_flags_,
class_type_index)) { returnfalse;
}
}
size_t num_direct_methods = accessor.NumDirectMethods();
size_t num_processed_methods = 0u; auto methods = accessor.GetMethods(); auto it = methods.begin(); for (; it != methods.end(); ++it, ++num_processed_methods) {
uint32_t code_off = it->GetCodeItemOffset(); if (code_off != 0 && !CheckOffsetToTypeMap(code_off, DexFile::kDexTypeCodeItem)) { returnfalse;
} // The index has already been checked in `CheckIntraClassDataItemMethods()`.
DCHECK_LE(it->GetIndex(), header_->method_ids_size_); const dex::MethodId& method = dex_file_->GetMethodId(it->GetIndex()); if (UNLIKELY(method.class_idx_ != class_type_index)) {
ErrorStringPrintf("Mismatched defining class for class_data_item method"); returnfalse;
} bool expect_direct = num_processed_methods < num_direct_methods; if (!CheckClassDataItemMethod(it->GetIndex(),
it->GetAccessFlags(),
class_def.access_flags_,
class_type_index,
it->GetCodeItemOffset(),
expect_direct)) { returnfalse;
}
}
// Check static field types against initial static values in encoded array. if (!CheckStaticFieldTypes(class_def)) { returnfalse;
}
if (item->class_annotations_off_ != 0 &&
!CheckOffsetToTypeMap(item->class_annotations_off_, DexFile::kDexTypeAnnotationSetItem)) { returnfalse;
}
// 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_; for (uint32_t i = 0; i < field_count; i++) { // The index has already been checked in `CheckIntraAnnotationsDirectoryItem()`.
DCHECK_LE(field_item->field_idx_, header_->field_ids_size_); const dex::FieldId& field = dex_file_->GetFieldId(field_item->field_idx_); if (UNLIKELY(field.class_idx_.index_ != defining_class)) {
ErrorStringPrintf("Mismatched defining class for field_annotation"); returnfalse;
} if (!CheckOffsetToTypeMap(field_item->annotations_off_, DexFile::kDexTypeAnnotationSetItem)) { returnfalse;
}
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_; for (uint32_t i = 0; i < method_count; i++) { // The index has already been checked in `CheckIntraAnnotationsDirectoryItem()`.
DCHECK_LE(method_item->method_idx_, header_->method_ids_size_); const dex::MethodId& method = dex_file_->GetMethodId(method_item->method_idx_); if (UNLIKELY(method.class_idx_.index_ != defining_class)) {
ErrorStringPrintf("Mismatched defining class for method_annotation"); returnfalse;
} if (!CheckOffsetToTypeMap(method_item->annotations_off_, DexFile::kDexTypeAnnotationSetItem)) { returnfalse;
}
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_; for (uint32_t i = 0; i < parameter_count; i++) { // The index has already been checked in `CheckIntraAnnotationsDirectoryItem()`.
DCHECK_LE(parameter_item->method_idx_, header_->method_ids_size_); const dex::MethodId& parameter_method = dex_file_->GetMethodId(parameter_item->method_idx_); if (UNLIKELY(parameter_method.class_idx_.index_ != defining_class)) {
ErrorStringPrintf("Mismatched defining class for parameter_annotation"); returnfalse;
} if (!CheckOffsetToTypeMap(parameter_item->annotations_off_,
DexFile::kDexTypeAnnotationSetRefList)) { returnfalse;
}
parameter_item++;
}
bool DexFileVerifier::CheckInterSectionIterate(size_t offset,
uint32_t count,
DexFile::MapItemType type) { // Get the right alignment mask for the type of section.
size_t alignment_mask; switch (type) { case DexFile::kDexTypeClassDataItem:
alignment_mask = sizeof(uint8_t) - 1; break; default:
alignment_mask = sizeof(uint32_t) - 1; break;
}
// Iterate through the items in the section.
previous_item_ = nullptr; for (uint32_t i = 0; i < count; i++) {
uint32_t new_offset = (offset + alignment_mask) & ~alignment_mask;
ptr_ = OffsetToPtr(new_offset); const uint8_t* prev_ptr = ptr_;
if (MapTypeToBitMask(type) == 0) {
ErrorStringPrintf("Unknown map item type %x", type); returnfalse;
}
// Check depending on the section type. switch (type) { case DexFile::kDexTypeHeaderItem: case DexFile::kDexTypeMethodHandleItem: case DexFile::kDexTypeMapList: case DexFile::kDexTypeTypeList: case DexFile::kDexTypeStringDataItem: case DexFile::kDexTypeDebugInfoItem: case DexFile::kDexTypeAnnotationItem: case DexFile::kDexTypeEncodedArrayItem: break; case DexFile::kDexTypeCodeItem: { if (!CheckInterCodeItem()) { returnfalse;
} break;
} case DexFile::kDexTypeHiddenapiClassData: { if (!CheckIntraHiddenapiClassData()) { returnfalse;
} break;
} case DexFile::kDexTypeStringIdItem: { if (!CheckInterStringIdItem()) { returnfalse;
} break;
} case DexFile::kDexTypeTypeIdItem: { if (!CheckInterTypeIdItem()) { returnfalse;
} break;
} case DexFile::kDexTypeProtoIdItem: { if (!CheckInterProtoIdItem()) { returnfalse;
} break;
} case DexFile::kDexTypeFieldIdItem: { if (!CheckInterFieldIdItem()) { returnfalse;
} break;
} case DexFile::kDexTypeMethodIdItem: { if (!CheckInterMethodIdItem()) { returnfalse;
} break;
} case DexFile::kDexTypeClassDefItem: { // There shouldn't be more class definitions than type ids allow. // This is checked in `CheckIntraClassDefItem()` by checking the type // index against `kTypeIdLimit` and rejecting dulicate definitions.
DCHECK_LE(i, kTypeIdLimit); if (!CheckInterClassDefItem()) { returnfalse;
} break;
} case DexFile::kDexTypeCallSiteIdItem: { if (!CheckInterCallSiteIdItem()) { returnfalse;
} break;
} case DexFile::kDexTypeAnnotationSetRefList: { if (!CheckInterAnnotationSetRefList()) { returnfalse;
} break;
} case DexFile::kDexTypeAnnotationSetItem: { if (!CheckInterAnnotationSetItem()) { returnfalse;
} break;
} case DexFile::kDexTypeClassDataItem: { // There shouldn't be more class data than type ids allow. // This check should be redundant, since there are checks that the // class_idx_ is within range and that there is only one definition // for a given type id. if (i > kTypeIdLimit) {
ErrorStringPrintf("Too many class data items"); returnfalse;
} if (!CheckInterClassDataItem()) { returnfalse;
} break;
} case DexFile::kDexTypeAnnotationsDirectoryItem: { if (!CheckInterAnnotationsDirectoryItem()) { returnfalse;
} break;
}
}
bool DexFileVerifier::CheckInterSection() { // Eagerly verify that `StringId` offsets map to string data items to make sure // we can retrieve the string data for verifying other items (types, shorties, etc.). // After this we can safely use `DexFile` helpers such as `GetFieldId()` or `GetMethodId()` // but not `PrettyMethod()` or `PrettyField()` as descriptors have not been verified yet. const dex::StringId* string_ids = OffsetToPtr<dex::StringId>(header_->string_ids_off_); for (size_t i = 0, num_strings = header_->string_ids_size_; i != num_strings; ++i) { if (!CheckOffsetToTypeMap(string_ids[i].string_data_off_, DexFile::kDexTypeStringDataItem)) { returnfalse;
}
}
// Cross check the items listed in the map. for (uint32_t count = map->size_; count != 0u; --count) {
uint32_t section_offset = item->offset_;
uint32_t section_count = item->size_;
DexFile::MapItemType type = static_cast<DexFile::MapItemType>(item->type_);
if (type == DexFile::kDexTypeClassDataItem) {
FindStringRangesForMethodNames();
}
switch (type) { case DexFile::kDexTypeHeaderItem: case DexFile::kDexTypeMapList: case DexFile::kDexTypeTypeList: case DexFile::kDexTypeCodeItem: case DexFile::kDexTypeStringDataItem: case DexFile::kDexTypeDebugInfoItem: case DexFile::kDexTypeAnnotationItem: case DexFile::kDexTypeEncodedArrayItem: break; case DexFile::kDexTypeStringIdItem: case DexFile::kDexTypeTypeIdItem: case DexFile::kDexTypeProtoIdItem: case DexFile::kDexTypeFieldIdItem: case DexFile::kDexTypeMethodIdItem: case DexFile::kDexTypeClassDefItem: case DexFile::kDexTypeCallSiteIdItem: case DexFile::kDexTypeMethodHandleItem: case DexFile::kDexTypeAnnotationSetRefList: case DexFile::kDexTypeAnnotationSetItem: case DexFile::kDexTypeClassDataItem: case DexFile::kDexTypeAnnotationsDirectoryItem: case DexFile::kDexTypeHiddenapiClassData: { if (!CheckInterSectionIterate(section_offset, section_count, type)) { returnfalse;
} break;
} default:
ErrorStringPrintf("Unknown map item type %x", item->type_); returnfalse;
}
item++;
}
returntrue;
}
bool DexFileVerifier::Verify() { // Check the header. if (!CheckHeader()) { returnfalse;
}
// Check the map section. if (!CheckMap()) { returnfalse;
}
// Check structure within remaining sections. if (!CheckIntraSection()) { returnfalse;
}
// Check references from one section to another. if (!CheckInterSection()) { returnfalse;
}
CHECK(todo_.empty()); // No unprocessed work left over. returntrue;
}
bool DexFileVerifier::CheckFieldAccessFlags(uint32_t idx,
uint32_t field_access_flags,
uint32_t class_access_flags,
std::string* error_msg) { // Generally sort out >16-bit flags. if ((field_access_flags & ~kAccJavaFlagsMask) != 0) {
*error_msg = StringPrintf("Bad field access_flags for %s: %x(%s)",
GetFieldDescription(idx).c_str(),
field_access_flags,
PrettyJavaAccessFlags(field_access_flags).c_str()); returnfalse;
}
// Flags allowed on fields, in general. Other lower-16-bit flags are to be ignored.
constexpr uint32_t kFieldAccessFlags = kAccPublic |
kAccPrivate |
kAccProtected |
kAccStatic |
kAccFinal |
kAccVolatile |
kAccTransient |
kAccSynthetic |
kAccEnum;
// Fields may have only one of public/protected/final. if (!CheckAtMostOneOfPublicProtectedPrivate(field_access_flags)) {
*error_msg = StringPrintf("Field may have only one of public/protected/private, %s: %x(%s)",
GetFieldDescription(idx).c_str(),
field_access_flags,
PrettyJavaAccessFlags(field_access_flags).c_str()); returnfalse;
}
// Interfaces have a pretty restricted list. if ((class_access_flags & kAccInterface) != 0) { // Interface fields must be public final static.
constexpr uint32_t kPublicFinalStatic = kAccPublic | kAccFinal | kAccStatic; if ((field_access_flags & kPublicFinalStatic) != kPublicFinalStatic) {
*error_msg = StringPrintf("Interface field is not public final static, %s: %x(%s)",
GetFieldDescription(idx).c_str(),
field_access_flags,
PrettyJavaAccessFlags(field_access_flags).c_str()); if (dex_file_->SupportsDefaultMethods()) { returnfalse;
} else { // Allow in older versions, but warn.
LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
<< *error_msg;
}
} // Interface fields may be synthetic, but may not have other flags.
constexpr uint32_t kDisallowed = ~(kPublicFinalStatic | kAccSynthetic); if ((field_access_flags & kFieldAccessFlags & kDisallowed) != 0) {
*error_msg = StringPrintf("Interface field has disallowed flag, %s: %x(%s)",
GetFieldDescription(idx).c_str(),
field_access_flags,
PrettyJavaAccessFlags(field_access_flags).c_str()); if (dex_file_->SupportsDefaultMethods()) { returnfalse;
} else { // Allow in older versions, but warn.
LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
<< *error_msg;
}
} returntrue;
}
// Volatile fields may not be final.
constexpr uint32_t kVolatileFinal = kAccVolatile | kAccFinal; if ((field_access_flags & kVolatileFinal) == kVolatileFinal) {
*error_msg = StringPrintf("Fields may not be volatile and final: %s",
GetFieldDescription(idx).c_str()); returnfalse;
}
returntrue;
}
void DexFileVerifier::FindStringRangesForMethodNames() { // Use DexFile::StringId* as RandomAccessIterator. const dex::StringId* first = OffsetToPtr<dex::StringId>(header_->string_ids_off_); const dex::StringId* last = first + header_->string_ids_size_;
// Flags allowed on methods, in general. Other lower-16-bit flags are to be ignored.
constexpr uint32_t kMethodAccessFlags = kAccPublic |
kAccPrivate |
kAccProtected |
kAccStatic |
kAccFinal |
kAccSynthetic |
kAccSynchronized |
kAccBridge |
kAccVarargs |
kAccNative |
kAccAbstract |
kAccStrict;
// Methods may have only one of public/protected/final. if (!CheckAtMostOneOfPublicProtectedPrivate(method_access_flags)) {
*error_msg = StringPrintf("Method may have only one of public/protected/private, %s: %x",
GetMethodDescription(method_index).c_str(),
method_access_flags); returnfalse;
}
// Only methods named "<clinit>" or "<init>" may be marked constructor. Note: we cannot enforce // the reverse for backwards compatibility reasons. if (((method_access_flags & kAccConstructor) != 0) && !is_constructor_by_name) {
*error_msg =
StringPrintf("Method %" PRIu32 "(%s) is marked constructor, but doesn't match name",
method_index,
GetMethodDescription(method_index).c_str()); returnfalse;
}
if (is_constructor_by_name) { // Check that the static constructor (= static initializer) is named "<clinit>" and that the // instance constructor is called "<init>". bool is_static = (method_access_flags & kAccStatic) != 0; if (is_static ^ is_clinit_by_name) {
*error_msg = StringPrintf("Constructor %" PRIu32 "(%s) is not flagged correctly wrt/ static.",
method_index,
GetMethodDescription(method_index).c_str()); if (dex_file_->SupportsDefaultMethods()) { returnfalse;
} else { // Allow in older versions, but warn.
LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
<< *error_msg;
}
}
}
// Check that static and private methods, as well as constructors, are in the direct methods list, // and other methods in the virtual methods list. bool is_direct = ((method_access_flags & (kAccStatic | kAccPrivate)) != 0) ||
is_constructor_by_name; if (is_direct != expect_direct) {
*error_msg = StringPrintf("Direct/virtual method %" PRIu32 "(%s) not in expected list %d",
method_index,
GetMethodDescription(method_index).c_str(),
expect_direct); returnfalse;
}
// From here on out it is easier to mask out the bits we're supposed to ignore.
method_access_flags &= kMethodAccessFlags;
// Interfaces are special. if ((class_access_flags & kAccInterface) != 0) { // Non-static interface methods must be public or private.
uint32_t desired_flags = (kAccPublic | kAccStatic); if (dex_file_->SupportsDefaultMethods()) {
desired_flags |= kAccPrivate;
} if ((method_access_flags & desired_flags) == 0) {
*error_msg = StringPrintf("Interface virtual method %" PRIu32 "(%s) is not public",
method_index,
GetMethodDescription(method_index).c_str()); if (dex_file_->SupportsDefaultMethods()) { returnfalse;
} else { // Allow in older versions, but warn.
LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
<< *error_msg;
}
}
}
// If there aren't any instructions, make sure that's expected. if (!has_code) { // Only native or abstract methods may not have code. if ((method_access_flags & (kAccNative | kAccAbstract)) == 0) {
*error_msg = StringPrintf("Method %" PRIu32 "(%s) has no code, but is not marked native or " "abstract",
method_index,
GetMethodDescription(method_index).c_str()); returnfalse;
} // Constructors must always have code. if (is_constructor_by_name) {
*error_msg = StringPrintf("Constructor %u(%s) must not be abstract or native",
method_index,
GetMethodDescription(method_index).c_str()); if (dex_file_->SupportsDefaultMethods()) { returnfalse;
} else { // Allow in older versions, but warn.
LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
<< *error_msg;
}
} if ((method_access_flags & kAccAbstract) != 0) { // Abstract methods are not allowed to have the following flags.
constexpr uint32_t kForbidden =
kAccPrivate | kAccStatic | kAccFinal | kAccNative | kAccStrict | kAccSynchronized; if ((method_access_flags & kForbidden) != 0) {
*error_msg = StringPrintf("Abstract method %" PRIu32 "(%s) has disallowed access flags %x",
method_index,
GetMethodDescription(method_index).c_str(),
method_access_flags); returnfalse;
} // Abstract methods should be in an abstract class or interface. if ((class_access_flags & (kAccInterface | kAccAbstract)) == 0) {
LOG(WARNING) << "Method " << GetMethodDescription(method_index)
<< " is abstract, but the declaring class is neither abstract nor an "
<< "interface in dex file "
<< dex_file_->GetLocation();
}
} // Interfaces are special. if ((class_access_flags & kAccInterface) != 0) { // Interface methods without code must be abstract. if ((method_access_flags & (kAccPublic | kAccAbstract)) != (kAccPublic | kAccAbstract)) {
*error_msg = StringPrintf("Interface method %" PRIu32 "(%s) is not public and abstract",
method_index,
GetMethodDescription(method_index).c_str()); if (dex_file_->SupportsDefaultMethods()) { returnfalse;
} else { // Allow in older versions, but warn.
LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
<< *error_msg;
}
} // At this point, we know the method is public and abstract. This means that all the checks // for invalid combinations above applies. In addition, interface methods must not be // protected. This is caught by the check for only-one-of-public-protected-private.
} returntrue;
}
// When there's code, the method must not be native or abstract. if ((method_access_flags & (kAccNative | kAccAbstract)) != 0) {
*error_msg = StringPrintf("Method %" PRIu32 "(%s) has code, but is marked native or abstract",
method_index,
GetMethodDescription(method_index).c_str()); returnfalse;
}
// Instance constructors must not be synchronized and a few other flags. if (constructor_flags_by_name == kAccConstructor) { static constexpr uint32_t kInitAllowed =
kAccPrivate | kAccProtected | kAccPublic | kAccStrict | kAccVarargs | kAccSynthetic; if ((method_access_flags & ~kInitAllowed) != 0) {
*error_msg = StringPrintf("Constructor %" PRIu32 "(%s) flagged inappropriately %x",
method_index,
GetMethodDescription(method_index).c_str(),
method_access_flags); returnfalse;
}
}
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.