1 /*
2  * Copyright (C) 2011 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "dex_file_verifier.h"
18 
19 #include <inttypes.h>
20 
21 #include <limits>
22 #include <memory>
23 
24 #include "android-base/stringprintf.h"
25 
26 #include "dex_file-inl.h"
27 #include "experimental_flags.h"
28 #include "leb128.h"
29 #include "safe_map.h"
30 #include "utf-inl.h"
31 #include "utils.h"
32 
33 namespace art {
34 
35 using android::base::StringAppendV;
36 using android::base::StringPrintf;
37 
38 static constexpr uint32_t kTypeIdLimit = std::numeric_limits<uint16_t>::max();
39 
IsValidOrNoTypeId(uint16_t low,uint16_t high)40 static bool IsValidOrNoTypeId(uint16_t low, uint16_t high) {
41   return (high == 0) || ((high == 0xffffU) && (low == 0xffffU));
42 }
43 
IsValidTypeId(uint16_t low ATTRIBUTE_UNUSED,uint16_t high)44 static bool IsValidTypeId(uint16_t low ATTRIBUTE_UNUSED, uint16_t high) {
45   return (high == 0);
46 }
47 
MapTypeToBitMask(DexFile::MapItemType map_item_type)48 static uint32_t MapTypeToBitMask(DexFile::MapItemType map_item_type) {
49   switch (map_item_type) {
50     case DexFile::kDexTypeHeaderItem:               return 1 << 0;
51     case DexFile::kDexTypeStringIdItem:             return 1 << 1;
52     case DexFile::kDexTypeTypeIdItem:               return 1 << 2;
53     case DexFile::kDexTypeProtoIdItem:              return 1 << 3;
54     case DexFile::kDexTypeFieldIdItem:              return 1 << 4;
55     case DexFile::kDexTypeMethodIdItem:             return 1 << 5;
56     case DexFile::kDexTypeClassDefItem:             return 1 << 6;
57     case DexFile::kDexTypeCallSiteIdItem:           return 1 << 7;
58     case DexFile::kDexTypeMethodHandleItem:         return 1 << 8;
59     case DexFile::kDexTypeMapList:                  return 1 << 9;
60     case DexFile::kDexTypeTypeList:                 return 1 << 10;
61     case DexFile::kDexTypeAnnotationSetRefList:     return 1 << 11;
62     case DexFile::kDexTypeAnnotationSetItem:        return 1 << 12;
63     case DexFile::kDexTypeClassDataItem:            return 1 << 13;
64     case DexFile::kDexTypeCodeItem:                 return 1 << 14;
65     case DexFile::kDexTypeStringDataItem:           return 1 << 15;
66     case DexFile::kDexTypeDebugInfoItem:            return 1 << 16;
67     case DexFile::kDexTypeAnnotationItem:           return 1 << 17;
68     case DexFile::kDexTypeEncodedArrayItem:         return 1 << 18;
69     case DexFile::kDexTypeAnnotationsDirectoryItem: return 1 << 19;
70   }
71   return 0;
72 }
73 
IsDataSectionType(DexFile::MapItemType map_item_type)74 static bool IsDataSectionType(DexFile::MapItemType map_item_type) {
75   switch (map_item_type) {
76     case DexFile::kDexTypeHeaderItem:
77     case DexFile::kDexTypeStringIdItem:
78     case DexFile::kDexTypeTypeIdItem:
79     case DexFile::kDexTypeProtoIdItem:
80     case DexFile::kDexTypeFieldIdItem:
81     case DexFile::kDexTypeMethodIdItem:
82     case DexFile::kDexTypeClassDefItem:
83       return false;
84     case DexFile::kDexTypeCallSiteIdItem:
85     case DexFile::kDexTypeMethodHandleItem:
86     case DexFile::kDexTypeMapList:
87     case DexFile::kDexTypeTypeList:
88     case DexFile::kDexTypeAnnotationSetRefList:
89     case DexFile::kDexTypeAnnotationSetItem:
90     case DexFile::kDexTypeClassDataItem:
91     case DexFile::kDexTypeCodeItem:
92     case DexFile::kDexTypeStringDataItem:
93     case DexFile::kDexTypeDebugInfoItem:
94     case DexFile::kDexTypeAnnotationItem:
95     case DexFile::kDexTypeEncodedArrayItem:
96     case DexFile::kDexTypeAnnotationsDirectoryItem:
97       return true;
98   }
99   return true;
100 }
101 
CheckLoadStringByIdx(dex::StringIndex idx,const char * error_string)102 const char* DexFileVerifier::CheckLoadStringByIdx(dex::StringIndex idx, const char* error_string) {
103   if (UNLIKELY(!CheckIndex(idx.index_, dex_file_->NumStringIds(), error_string))) {
104     return nullptr;
105   }
106   return dex_file_->StringDataByIdx(idx);
107 }
108 
109 // Try to find the name of the method with the given index. We do not want to rely on DexFile
110 // infrastructure at this point, so do it all by hand. begin and header correspond to begin_ and
111 // header_ of the DexFileVerifier. str will contain the pointer to the method name on success
112 // (flagged by the return value), otherwise error_msg will contain an error string.
FindMethodName(uint32_t method_index,const uint8_t * begin,const DexFile::Header * header,const char ** str,std::string * error_msg)113 static bool FindMethodName(uint32_t method_index,
114                            const uint8_t* begin,
115                            const DexFile::Header* header,
116                            const char** str,
117                            std::string* error_msg) {
118   if (method_index >= header->method_ids_size_) {
119     *error_msg = "Method index not available for method flags verification";
120     return false;
121   }
122   uint32_t string_idx =
123       (reinterpret_cast<const DexFile::MethodId*>(begin + header->method_ids_off_) +
124           method_index)->name_idx_.index_;
125   if (string_idx >= header->string_ids_size_) {
126     *error_msg = "String index not available for method flags verification";
127     return false;
128   }
129   uint32_t string_off =
130       (reinterpret_cast<const DexFile::StringId*>(begin + header->string_ids_off_) + string_idx)->
131           string_data_off_;
132   if (string_off >= header->file_size_) {
133     *error_msg = "String offset out of bounds for method flags verification";
134     return false;
135   }
136   const uint8_t* str_data_ptr = begin + string_off;
137   uint32_t dummy;
138   if (!DecodeUnsignedLeb128Checked(&str_data_ptr, begin + header->file_size_, &dummy)) {
139     *error_msg = "String size out of bounds for method flags verification";
140     return false;
141   }
142   *str = reinterpret_cast<const char*>(str_data_ptr);
143   return true;
144 }
145 
146 // Gets constructor flags based on the |method_name|. Returns true if
147 // method_name is either <clinit> or <init> and sets
148 // |constructor_flags_by_name| appropriately. Otherwise set
149 // |constructor_flags_by_name| to zero and returns whether
150 // |method_name| is valid.
GetConstructorFlagsForMethodName(const char * method_name,uint32_t * constructor_flags_by_name)151 bool GetConstructorFlagsForMethodName(const char* method_name,
152                                       uint32_t* constructor_flags_by_name) {
153   if (method_name[0] != '<') {
154     *constructor_flags_by_name = 0;
155     return true;
156   }
157   if (strcmp(method_name + 1, "clinit>") == 0) {
158     *constructor_flags_by_name = kAccStatic | kAccConstructor;
159     return true;
160   }
161   if (strcmp(method_name + 1, "init>") == 0) {
162     *constructor_flags_by_name = kAccConstructor;
163     return true;
164   }
165   *constructor_flags_by_name = 0;
166   return false;
167 }
168 
CheckLoadStringByTypeIdx(dex::TypeIndex type_idx,const char * error_string)169 const char* DexFileVerifier::CheckLoadStringByTypeIdx(dex::TypeIndex type_idx,
170                                                       const char* error_string) {
171   if (UNLIKELY(!CheckIndex(type_idx.index_, dex_file_->NumTypeIds(), error_string))) {
172     return nullptr;
173   }
174   return CheckLoadStringByIdx(dex_file_->GetTypeId(type_idx).descriptor_idx_, error_string);
175 }
176 
CheckLoadFieldId(uint32_t idx,const char * error_string)177 const DexFile::FieldId* DexFileVerifier::CheckLoadFieldId(uint32_t idx, const char* error_string) {
178   if (UNLIKELY(!CheckIndex(idx, dex_file_->NumFieldIds(), error_string))) {
179     return nullptr;
180   }
181   return &dex_file_->GetFieldId(idx);
182 }
183 
CheckLoadMethodId(uint32_t idx,const char * err_string)184 const DexFile::MethodId* DexFileVerifier::CheckLoadMethodId(uint32_t idx, const char* err_string) {
185   if (UNLIKELY(!CheckIndex(idx, dex_file_->NumMethodIds(), err_string))) {
186     return nullptr;
187   }
188   return &dex_file_->GetMethodId(idx);
189 }
190 
CheckLoadProtoId(uint32_t idx,const char * err_string)191 const DexFile::ProtoId* DexFileVerifier::CheckLoadProtoId(uint32_t idx, const char* err_string) {
192   if (UNLIKELY(!CheckIndex(idx, dex_file_->NumProtoIds(), err_string))) {
193     return nullptr;
194   }
195   return &dex_file_->GetProtoId(idx);
196 }
197 
198 // Helper macro to load string and return false on error.
199 #define LOAD_STRING(var, idx, error)                    \
200   const char* (var) = CheckLoadStringByIdx(idx, error); \
201   if (UNLIKELY((var) == nullptr)) {                     \
202     return false;                                       \
203   }
204 
205 // Helper macro to load string by type idx and return false on error.
206 #define LOAD_STRING_BY_TYPE(var, type_idx, error)                \
207   const char* (var) = CheckLoadStringByTypeIdx(type_idx, error); \
208   if (UNLIKELY((var) == nullptr)) {                              \
209     return false;                                                \
210   }
211 
212 // Helper macro to load method id. Return last parameter on error.
213 #define LOAD_METHOD(var, idx, error_string, error_stmt)                   \
214   const DexFile::MethodId* (var)  = CheckLoadMethodId(idx, error_string); \
215   if (UNLIKELY((var) == nullptr)) {                                       \
216     error_stmt;                                                           \
217   }
218 
219 // Helper macro to load method id. Return last parameter on error.
220 #define LOAD_FIELD(var, idx, fmt, error_stmt)                 \
221   const DexFile::FieldId* (var) = CheckLoadFieldId(idx, fmt); \
222   if (UNLIKELY((var) == nullptr)) {                           \
223     error_stmt;                                               \
224   }
225 
Verify(const DexFile * dex_file,const uint8_t * begin,size_t size,const char * location,bool verify_checksum,std::string * error_msg)226 bool DexFileVerifier::Verify(const DexFile* dex_file,
227                              const uint8_t* begin,
228                              size_t size,
229                              const char* location,
230                              bool verify_checksum,
231                              std::string* error_msg) {
232   std::unique_ptr<DexFileVerifier> verifier(
233       new DexFileVerifier(dex_file, begin, size, location, verify_checksum));
234   if (!verifier->Verify()) {
235     *error_msg = verifier->FailureReason();
236     return false;
237   }
238   return true;
239 }
240 
CheckShortyDescriptorMatch(char shorty_char,const char * descriptor,bool is_return_type)241 bool DexFileVerifier::CheckShortyDescriptorMatch(char shorty_char, const char* descriptor,
242                                                 bool is_return_type) {
243   switch (shorty_char) {
244     case 'V':
245       if (UNLIKELY(!is_return_type)) {
246         ErrorStringPrintf("Invalid use of void");
247         return false;
248       }
249       FALLTHROUGH_INTENDED;
250     case 'B':
251     case 'C':
252     case 'D':
253     case 'F':
254     case 'I':
255     case 'J':
256     case 'S':
257     case 'Z':
258       if (UNLIKELY((descriptor[0] != shorty_char) || (descriptor[1] != '\0'))) {
259         ErrorStringPrintf("Shorty vs. primitive type mismatch: '%c', '%s'",
260                           shorty_char, descriptor);
261         return false;
262       }
263       break;
264     case 'L':
265       if (UNLIKELY((descriptor[0] != 'L') && (descriptor[0] != '['))) {
266         ErrorStringPrintf("Shorty vs. type mismatch: '%c', '%s'", shorty_char, descriptor);
267         return false;
268       }
269       break;
270     default:
271       ErrorStringPrintf("Bad shorty character: '%c'", shorty_char);
272       return false;
273   }
274   return true;
275 }
276 
CheckListSize(const void * start,size_t count,size_t elem_size,const char * label)277 bool DexFileVerifier::CheckListSize(const void* start, size_t count, size_t elem_size,
278                                     const char* label) {
279   // Check that size is not 0.
280   CHECK_NE(elem_size, 0U);
281 
282   const uint8_t* range_start = reinterpret_cast<const uint8_t*>(start);
283   const uint8_t* file_start = reinterpret_cast<const uint8_t*>(begin_);
284 
285   // Check for overflow.
286   uintptr_t max = 0 - 1;
287   size_t available_bytes_till_end_of_mem = max - reinterpret_cast<uintptr_t>(start);
288   size_t max_count = available_bytes_till_end_of_mem / elem_size;
289   if (max_count < count) {
290     ErrorStringPrintf("Overflow in range for %s: %zx for %zu@%zu", label,
291                       static_cast<size_t>(range_start - file_start),
292                       count, elem_size);
293     return false;
294   }
295 
296   const uint8_t* range_end = range_start + count * elem_size;
297   const uint8_t* file_end = file_start + size_;
298   if (UNLIKELY((range_start < file_start) || (range_end > file_end))) {
299     // Note: these two tests are enough as we make sure above that there's no overflow.
300     ErrorStringPrintf("Bad range for %s: %zx to %zx", label,
301                       static_cast<size_t>(range_start - file_start),
302                       static_cast<size_t>(range_end - file_start));
303     return false;
304   }
305   return true;
306 }
307 
CheckList(size_t element_size,const char * label,const uint8_t ** ptr)308 bool DexFileVerifier::CheckList(size_t element_size, const char* label, const uint8_t* *ptr) {
309   // Check that the list is available. The first 4B are the count.
310   if (!CheckListSize(*ptr, 1, 4U, label)) {
311     return false;
312   }
313 
314   uint32_t count = *reinterpret_cast<const uint32_t*>(*ptr);
315   if (count > 0) {
316     if (!CheckListSize(*ptr + 4, count, element_size, label)) {
317       return false;
318     }
319   }
320 
321   *ptr += 4 + count * element_size;
322   return true;
323 }
324 
CheckIndex(uint32_t field,uint32_t limit,const char * label)325 bool DexFileVerifier::CheckIndex(uint32_t field, uint32_t limit, const char* label) {
326   if (UNLIKELY(field >= limit)) {
327     ErrorStringPrintf("Bad index for %s: %x >= %x", label, field, limit);
328     return false;
329   }
330   return true;
331 }
332 
CheckValidOffsetAndSize(uint32_t offset,uint32_t size,size_t alignment,const char * label)333 bool DexFileVerifier::CheckValidOffsetAndSize(uint32_t offset,
334                                               uint32_t size,
335                                               size_t alignment,
336                                               const char* label) {
337   if (size == 0) {
338     if (offset != 0) {
339       ErrorStringPrintf("Offset(%d) should be zero when size is zero for %s.", offset, label);
340       return false;
341     }
342   }
343   if (size_ <= offset) {
344     ErrorStringPrintf("Offset(%d) should be within file size(%zu) for %s.", offset, size_, label);
345     return false;
346   }
347   if (alignment != 0 && !IsAlignedParam(offset, alignment)) {
348     ErrorStringPrintf("Offset(%d) should be aligned by %zu for %s.", offset, alignment, label);
349     return false;
350   }
351   return true;
352 }
353 
CheckSizeLimit(uint32_t size,uint32_t limit,const char * label)354 bool DexFileVerifier::CheckSizeLimit(uint32_t size, uint32_t limit, const char* label) {
355   if (size > limit) {
356     ErrorStringPrintf("Size(%u) should not exceed limit(%u) for %s.", size, limit, label);
357     return false;
358   }
359   return true;
360 }
361 
CheckHeader()362 bool DexFileVerifier::CheckHeader() {
363   // Check file size from the header.
364   uint32_t expected_size = header_->file_size_;
365   if (size_ != expected_size) {
366     ErrorStringPrintf("Bad file size (%zd, expected %ud)", size_, expected_size);
367     return false;
368   }
369 
370   uint32_t adler_checksum = dex_file_->CalculateChecksum();
371   // Compute and verify the checksum in the header.
372   if (adler_checksum != header_->checksum_) {
373     if (verify_checksum_) {
374       ErrorStringPrintf("Bad checksum (%08x, expected %08x)", adler_checksum, header_->checksum_);
375       return false;
376     } else {
377       LOG(WARNING) << StringPrintf(
378           "Ignoring bad checksum (%08x, expected %08x)", adler_checksum, header_->checksum_);
379     }
380   }
381 
382   // Check the contents of the header.
383   if (header_->endian_tag_ != DexFile::kDexEndianConstant) {
384     ErrorStringPrintf("Unexpected endian_tag: %x", header_->endian_tag_);
385     return false;
386   }
387 
388   if (header_->header_size_ != sizeof(DexFile::Header)) {
389     ErrorStringPrintf("Bad header size: %ud", header_->header_size_);
390     return false;
391   }
392 
393   // Check that all offsets are inside the file.
394   bool result =
395       CheckValidOffsetAndSize(header_->link_off_,
396                               header_->link_size_,
397                               0 /* unaligned */,
398                               "link") &&
399       CheckValidOffsetAndSize(header_->map_off_,
400                               header_->map_off_,
401                               4,
402                               "map") &&
403       CheckValidOffsetAndSize(header_->string_ids_off_,
404                               header_->string_ids_size_,
405                               4,
406                               "string-ids") &&
407       CheckValidOffsetAndSize(header_->type_ids_off_,
408                               header_->type_ids_size_,
409                               4,
410                               "type-ids") &&
411       CheckSizeLimit(header_->type_ids_size_, DexFile::kDexNoIndex16, "type-ids") &&
412       CheckValidOffsetAndSize(header_->proto_ids_off_,
413                               header_->proto_ids_size_,
414                               4,
415                               "proto-ids") &&
416       CheckSizeLimit(header_->proto_ids_size_, DexFile::kDexNoIndex16, "proto-ids") &&
417       CheckValidOffsetAndSize(header_->field_ids_off_,
418                               header_->field_ids_size_,
419                               4,
420                               "field-ids") &&
421       CheckValidOffsetAndSize(header_->method_ids_off_,
422                               header_->method_ids_size_,
423                               4,
424                               "method-ids") &&
425       CheckValidOffsetAndSize(header_->class_defs_off_,
426                               header_->class_defs_size_,
427                               4,
428                               "class-defs") &&
429       CheckValidOffsetAndSize(header_->data_off_,
430                               header_->data_size_,
431                               0,  // Unaligned, spec doesn't talk about it, even though size
432                                   // is supposed to be a multiple of 4.
433                               "data");
434   return result;
435 }
436 
CheckMap()437 bool DexFileVerifier::CheckMap() {
438   const DexFile::MapList* map = reinterpret_cast<const DexFile::MapList*>(begin_ +
439                                                                           header_->map_off_);
440   // Check that map list content is available.
441   if (!CheckListSize(map, 1, sizeof(DexFile::MapList), "maplist content")) {
442     return false;
443   }
444 
445   const DexFile::MapItem* item = map->list_;
446 
447   uint32_t count = map->size_;
448   uint32_t last_offset = 0;
449   uint32_t data_item_count = 0;
450   uint32_t data_items_left = header_->data_size_;
451   uint32_t used_bits = 0;
452 
453   // Sanity check the size of the map list.
454   if (!CheckListSize(item, count, sizeof(DexFile::MapItem), "map size")) {
455     return false;
456   }
457 
458   // Check the items listed in the map.
459   for (uint32_t i = 0; i < count; i++) {
460     if (UNLIKELY(last_offset >= item->offset_ && i != 0)) {
461       ErrorStringPrintf("Out of order map item: %x then %x", last_offset, item->offset_);
462       return false;
463     }
464     if (UNLIKELY(item->offset_ >= header_->file_size_)) {
465       ErrorStringPrintf("Map item after end of file: %x, size %x",
466                         item->offset_, header_->file_size_);
467       return false;
468     }
469 
470     DexFile::MapItemType item_type = static_cast<DexFile::MapItemType>(item->type_);
471     if (IsDataSectionType(item_type)) {
472       uint32_t icount = item->size_;
473       if (UNLIKELY(icount > data_items_left)) {
474         ErrorStringPrintf("Too many items in data section: %ud", data_item_count + icount);
475         return false;
476       }
477       data_items_left -= icount;
478       data_item_count += icount;
479     }
480 
481     uint32_t bit = MapTypeToBitMask(item_type);
482 
483     if (UNLIKELY(bit == 0)) {
484       ErrorStringPrintf("Unknown map section type %x", item->type_);
485       return false;
486     }
487 
488     if (UNLIKELY((used_bits & bit) != 0)) {
489       ErrorStringPrintf("Duplicate map section of type %x", item->type_);
490       return false;
491     }
492 
493     used_bits |= bit;
494     last_offset = item->offset_;
495     item++;
496   }
497 
498   // Check for missing sections in the map.
499   if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeHeaderItem)) == 0)) {
500     ErrorStringPrintf("Map is missing header entry");
501     return false;
502   }
503   if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeMapList)) == 0)) {
504     ErrorStringPrintf("Map is missing map_list entry");
505     return false;
506   }
507   if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeStringIdItem)) == 0 &&
508                ((header_->string_ids_off_ != 0) || (header_->string_ids_size_ != 0)))) {
509     ErrorStringPrintf("Map is missing string_ids entry");
510     return false;
511   }
512   if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeTypeIdItem)) == 0 &&
513                ((header_->type_ids_off_ != 0) || (header_->type_ids_size_ != 0)))) {
514     ErrorStringPrintf("Map is missing type_ids entry");
515     return false;
516   }
517   if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeProtoIdItem)) == 0 &&
518                ((header_->proto_ids_off_ != 0) || (header_->proto_ids_size_ != 0)))) {
519     ErrorStringPrintf("Map is missing proto_ids entry");
520     return false;
521   }
522   if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeFieldIdItem)) == 0 &&
523                ((header_->field_ids_off_ != 0) || (header_->field_ids_size_ != 0)))) {
524     ErrorStringPrintf("Map is missing field_ids entry");
525     return false;
526   }
527   if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeMethodIdItem)) == 0 &&
528                ((header_->method_ids_off_ != 0) || (header_->method_ids_size_ != 0)))) {
529     ErrorStringPrintf("Map is missing method_ids entry");
530     return false;
531   }
532   if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeClassDefItem)) == 0 &&
533                ((header_->class_defs_off_ != 0) || (header_->class_defs_size_ != 0)))) {
534     ErrorStringPrintf("Map is missing class_defs entry");
535     return false;
536   }
537   return true;
538 }
539 
ReadUnsignedLittleEndian(uint32_t size)540 uint32_t DexFileVerifier::ReadUnsignedLittleEndian(uint32_t size) {
541   uint32_t result = 0;
542   if (LIKELY(CheckListSize(ptr_, size, sizeof(uint8_t), "encoded_value"))) {
543     for (uint32_t i = 0; i < size; i++) {
544       result |= ((uint32_t) *(ptr_++)) << (i * 8);
545     }
546   }
547   return result;
548 }
549 
550 
551 #define DECODE_UNSIGNED_CHECKED_FROM_WITH_ERROR_VALUE(ptr, var, error_value)  \
552   uint32_t var;                                                               \
553   if (!DecodeUnsignedLeb128Checked(&(ptr), begin_ + size_, &(var))) {         \
554     return error_value;                                                       \
555   }
556 
557 #define DECODE_UNSIGNED_CHECKED_FROM(ptr, var)                        \
558   uint32_t var;                                                       \
559   if (!DecodeUnsignedLeb128Checked(&(ptr), begin_ + size_, &(var))) { \
560     ErrorStringPrintf("Read out of bounds");                          \
561     return false;                                                     \
562   }
563 
564 #define DECODE_SIGNED_CHECKED_FROM(ptr, var)                        \
565   int32_t var;                                                      \
566   if (!DecodeSignedLeb128Checked(&(ptr), begin_ + size_, &(var))) { \
567     ErrorStringPrintf("Read out of bounds");                        \
568     return false;                                                   \
569   }
570 
CheckAndGetHandlerOffsets(const DexFile::CodeItem * code_item,uint32_t * handler_offsets,uint32_t handlers_size)571 bool DexFileVerifier::CheckAndGetHandlerOffsets(const DexFile::CodeItem* code_item,
572                                                 uint32_t* handler_offsets, uint32_t handlers_size) {
573   const uint8_t* handlers_base = DexFile::GetCatchHandlerData(*code_item, 0);
574 
575   for (uint32_t i = 0; i < handlers_size; i++) {
576     bool catch_all;
577     size_t offset = ptr_ - handlers_base;
578     DECODE_SIGNED_CHECKED_FROM(ptr_, size);
579 
580     if (UNLIKELY((size < -65536) || (size > 65536))) {
581       ErrorStringPrintf("Invalid exception handler size: %d", size);
582       return false;
583     }
584 
585     if (size <= 0) {
586       catch_all = true;
587       size = -size;
588     } else {
589       catch_all = false;
590     }
591 
592     handler_offsets[i] = static_cast<uint32_t>(offset);
593 
594     while (size-- > 0) {
595       DECODE_UNSIGNED_CHECKED_FROM(ptr_, type_idx);
596       if (!CheckIndex(type_idx, header_->type_ids_size_, "handler type_idx")) {
597         return false;
598       }
599 
600       DECODE_UNSIGNED_CHECKED_FROM(ptr_, addr);
601       if (UNLIKELY(addr >= code_item->insns_size_in_code_units_)) {
602         ErrorStringPrintf("Invalid handler addr: %x", addr);
603         return false;
604       }
605     }
606 
607     if (catch_all) {
608       DECODE_UNSIGNED_CHECKED_FROM(ptr_, addr);
609       if (UNLIKELY(addr >= code_item->insns_size_in_code_units_)) {
610         ErrorStringPrintf("Invalid handler catch_all_addr: %x", addr);
611         return false;
612       }
613     }
614   }
615 
616   return true;
617 }
618 
CheckClassDataItemField(uint32_t idx,uint32_t access_flags,uint32_t class_access_flags,dex::TypeIndex class_type_index,bool expect_static)619 bool DexFileVerifier::CheckClassDataItemField(uint32_t idx,
620                                               uint32_t access_flags,
621                                               uint32_t class_access_flags,
622                                               dex::TypeIndex class_type_index,
623                                               bool expect_static) {
624   // Check for overflow.
625   if (!CheckIndex(idx, header_->field_ids_size_, "class_data_item field_idx")) {
626     return false;
627   }
628 
629   // Check that it's the right class.
630   dex::TypeIndex my_class_index =
631       (reinterpret_cast<const DexFile::FieldId*>(begin_ + header_->field_ids_off_) + idx)->
632           class_idx_;
633   if (class_type_index != my_class_index) {
634     ErrorStringPrintf("Field's class index unexpected, %" PRIu16 "vs %" PRIu16,
635                       my_class_index.index_,
636                       class_type_index.index_);
637     return false;
638   }
639 
640   // Check that it falls into the right class-data list.
641   bool is_static = (access_flags & kAccStatic) != 0;
642   if (UNLIKELY(is_static != expect_static)) {
643     ErrorStringPrintf("Static/instance field not in expected list");
644     return false;
645   }
646 
647   // Check field access flags.
648   std::string error_msg;
649   if (!CheckFieldAccessFlags(idx, access_flags, class_access_flags, &error_msg)) {
650     ErrorStringPrintf("%s", error_msg.c_str());
651     return false;
652   }
653 
654   return true;
655 }
656 
CheckClassDataItemMethod(uint32_t idx,uint32_t access_flags,uint32_t class_access_flags,dex::TypeIndex class_type_index,uint32_t code_offset,std::unordered_set<uint32_t> * direct_method_indexes,bool expect_direct)657 bool DexFileVerifier::CheckClassDataItemMethod(uint32_t idx,
658                                                uint32_t access_flags,
659                                                uint32_t class_access_flags,
660                                                dex::TypeIndex class_type_index,
661                                                uint32_t code_offset,
662                                                std::unordered_set<uint32_t>* direct_method_indexes,
663                                                bool expect_direct) {
664   DCHECK(direct_method_indexes != nullptr);
665   // Check for overflow.
666   if (!CheckIndex(idx, header_->method_ids_size_, "class_data_item method_idx")) {
667     return false;
668   }
669 
670   // Check that it's the right class.
671   dex::TypeIndex my_class_index =
672       (reinterpret_cast<const DexFile::MethodId*>(begin_ + header_->method_ids_off_) + idx)->
673           class_idx_;
674   if (class_type_index != my_class_index) {
675     ErrorStringPrintf("Method's class index unexpected, %" PRIu16 " vs %" PRIu16,
676                       my_class_index.index_,
677                       class_type_index.index_);
678     return false;
679   }
680 
681   // Check that it's not defined as both direct and virtual.
682   if (expect_direct) {
683     direct_method_indexes->insert(idx);
684   } else if (direct_method_indexes->find(idx) != direct_method_indexes->end()) {
685     ErrorStringPrintf("Found virtual method with same index as direct method: %d", idx);
686     return false;
687   }
688 
689   std::string error_msg;
690   const char* method_name;
691   if (!FindMethodName(idx, begin_, header_, &method_name, &error_msg)) {
692     ErrorStringPrintf("%s", error_msg.c_str());
693     return false;
694   }
695 
696   uint32_t constructor_flags_by_name = 0;
697   if (!GetConstructorFlagsForMethodName(method_name, &constructor_flags_by_name)) {
698     ErrorStringPrintf("Bad method name: %s", method_name);
699     return false;
700   }
701 
702   bool has_code = (code_offset != 0);
703   if (!CheckMethodAccessFlags(idx,
704                               access_flags,
705                               class_access_flags,
706                               constructor_flags_by_name,
707                               has_code,
708                               expect_direct,
709                               &error_msg)) {
710     ErrorStringPrintf("%s", error_msg.c_str());
711     return false;
712   }
713 
714   if (constructor_flags_by_name != 0) {
715     if (!CheckConstructorProperties(idx, constructor_flags_by_name)) {
716       DCHECK(FailureReasonIsSet());
717       return false;
718     }
719   }
720 
721   return true;
722 }
723 
CheckPadding(size_t offset,uint32_t aligned_offset)724 bool DexFileVerifier::CheckPadding(size_t offset, uint32_t aligned_offset) {
725   if (offset < aligned_offset) {
726     if (!CheckListSize(begin_ + offset, aligned_offset - offset, sizeof(uint8_t), "section")) {
727       return false;
728     }
729     while (offset < aligned_offset) {
730       if (UNLIKELY(*ptr_ != '\0')) {
731         ErrorStringPrintf("Non-zero padding %x before section start at %zx", *ptr_, offset);
732         return false;
733       }
734       ptr_++;
735       offset++;
736     }
737   }
738   return true;
739 }
740 
CheckEncodedValue()741 bool DexFileVerifier::CheckEncodedValue() {
742   if (!CheckListSize(ptr_, 1, sizeof(uint8_t), "encoded_value header")) {
743     return false;
744   }
745 
746   uint8_t header_byte = *(ptr_++);
747   uint32_t value_type = header_byte & DexFile::kDexAnnotationValueTypeMask;
748   uint32_t value_arg = header_byte >> DexFile::kDexAnnotationValueArgShift;
749 
750   switch (value_type) {
751     case DexFile::kDexAnnotationByte:
752       if (UNLIKELY(value_arg != 0)) {
753         ErrorStringPrintf("Bad encoded_value byte size %x", value_arg);
754         return false;
755       }
756       ptr_++;
757       break;
758     case DexFile::kDexAnnotationShort:
759     case DexFile::kDexAnnotationChar:
760       if (UNLIKELY(value_arg > 1)) {
761         ErrorStringPrintf("Bad encoded_value char/short size %x", value_arg);
762         return false;
763       }
764       ptr_ += value_arg + 1;
765       break;
766     case DexFile::kDexAnnotationInt:
767     case DexFile::kDexAnnotationFloat:
768       if (UNLIKELY(value_arg > 3)) {
769         ErrorStringPrintf("Bad encoded_value int/float size %x", value_arg);
770         return false;
771       }
772       ptr_ += value_arg + 1;
773       break;
774     case DexFile::kDexAnnotationLong:
775     case DexFile::kDexAnnotationDouble:
776       ptr_ += value_arg + 1;
777       break;
778     case DexFile::kDexAnnotationString: {
779       if (UNLIKELY(value_arg > 3)) {
780         ErrorStringPrintf("Bad encoded_value string size %x", value_arg);
781         return false;
782       }
783       uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
784       if (!CheckIndex(idx, header_->string_ids_size_, "encoded_value string")) {
785         return false;
786       }
787       break;
788     }
789     case DexFile::kDexAnnotationType: {
790       if (UNLIKELY(value_arg > 3)) {
791         ErrorStringPrintf("Bad encoded_value type size %x", value_arg);
792         return false;
793       }
794       uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
795       if (!CheckIndex(idx, header_->type_ids_size_, "encoded_value type")) {
796         return false;
797       }
798       break;
799     }
800     case DexFile::kDexAnnotationField:
801     case DexFile::kDexAnnotationEnum: {
802       if (UNLIKELY(value_arg > 3)) {
803         ErrorStringPrintf("Bad encoded_value field/enum size %x", value_arg);
804         return false;
805       }
806       uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
807       if (!CheckIndex(idx, header_->field_ids_size_, "encoded_value field")) {
808         return false;
809       }
810       break;
811     }
812     case DexFile::kDexAnnotationMethod: {
813       if (UNLIKELY(value_arg > 3)) {
814         ErrorStringPrintf("Bad encoded_value method size %x", value_arg);
815         return false;
816       }
817       uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
818       if (!CheckIndex(idx, header_->method_ids_size_, "encoded_value method")) {
819         return false;
820       }
821       break;
822     }
823     case DexFile::kDexAnnotationArray:
824       if (UNLIKELY(value_arg != 0)) {
825         ErrorStringPrintf("Bad encoded_value array value_arg %x", value_arg);
826         return false;
827       }
828       if (!CheckEncodedArray()) {
829         return false;
830       }
831       break;
832     case DexFile::kDexAnnotationAnnotation:
833       if (UNLIKELY(value_arg != 0)) {
834         ErrorStringPrintf("Bad encoded_value annotation value_arg %x", value_arg);
835         return false;
836       }
837       if (!CheckEncodedAnnotation()) {
838         return false;
839       }
840       break;
841     case DexFile::kDexAnnotationNull:
842       if (UNLIKELY(value_arg != 0)) {
843         ErrorStringPrintf("Bad encoded_value null value_arg %x", value_arg);
844         return false;
845       }
846       break;
847     case DexFile::kDexAnnotationBoolean:
848       if (UNLIKELY(value_arg > 1)) {
849         ErrorStringPrintf("Bad encoded_value boolean size %x", value_arg);
850         return false;
851       }
852       break;
853     case DexFile::kDexAnnotationMethodType: {
854       if (UNLIKELY(value_arg > 3)) {
855         ErrorStringPrintf("Bad encoded_value method type size %x", value_arg);
856         return false;
857       }
858       uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
859       if (!CheckIndex(idx, header_->proto_ids_size_, "method_type value")) {
860         return false;
861       }
862       break;
863     }
864     case DexFile::kDexAnnotationMethodHandle: {
865       if (UNLIKELY(value_arg > 3)) {
866         ErrorStringPrintf("Bad encoded_value method handle size %x", value_arg);
867         return false;
868       }
869       uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
870       if (!CheckIndex(idx, dex_file_->NumMethodHandles(), "method_handle value")) {
871         return false;
872       }
873       break;
874     }
875     default:
876       ErrorStringPrintf("Bogus encoded_value value_type %x", value_type);
877       return false;
878   }
879 
880   return true;
881 }
882 
CheckEncodedArray()883 bool DexFileVerifier::CheckEncodedArray() {
884   DECODE_UNSIGNED_CHECKED_FROM(ptr_, size);
885 
886   while (size--) {
887     if (!CheckEncodedValue()) {
888       failure_reason_ = StringPrintf("Bad encoded_array value: %s", failure_reason_.c_str());
889       return false;
890     }
891   }
892   return true;
893 }
894 
CheckEncodedAnnotation()895 bool DexFileVerifier::CheckEncodedAnnotation() {
896   DECODE_UNSIGNED_CHECKED_FROM(ptr_, anno_idx);
897   if (!CheckIndex(anno_idx, header_->type_ids_size_, "encoded_annotation type_idx")) {
898     return false;
899   }
900 
901   DECODE_UNSIGNED_CHECKED_FROM(ptr_, size);
902   uint32_t last_idx = 0;
903 
904   for (uint32_t i = 0; i < size; i++) {
905     DECODE_UNSIGNED_CHECKED_FROM(ptr_, idx);
906     if (!CheckIndex(idx, header_->string_ids_size_, "annotation_element name_idx")) {
907       return false;
908     }
909 
910     if (UNLIKELY(last_idx >= idx && i != 0)) {
911       ErrorStringPrintf("Out-of-order annotation_element name_idx: %x then %x",
912                         last_idx, idx);
913       return false;
914     }
915 
916     if (!CheckEncodedValue()) {
917       return false;
918     }
919 
920     last_idx = idx;
921   }
922   return true;
923 }
924 
FindClassIndexAndDef(uint32_t index,bool is_field,dex::TypeIndex * class_type_index,const DexFile::ClassDef ** output_class_def)925 bool DexFileVerifier::FindClassIndexAndDef(uint32_t index,
926                                            bool is_field,
927                                            dex::TypeIndex* class_type_index,
928                                            const DexFile::ClassDef** output_class_def) {
929   DCHECK(class_type_index != nullptr);
930   DCHECK(output_class_def != nullptr);
931 
932   // First check if the index is valid.
933   if (index >= (is_field ? header_->field_ids_size_ : header_->method_ids_size_)) {
934     return false;
935   }
936 
937   // Next get the type index.
938   if (is_field) {
939     *class_type_index =
940         (reinterpret_cast<const DexFile::FieldId*>(begin_ + header_->field_ids_off_) + index)->
941             class_idx_;
942   } else {
943     *class_type_index =
944         (reinterpret_cast<const DexFile::MethodId*>(begin_ + header_->method_ids_off_) + index)->
945             class_idx_;
946   }
947 
948   // Check if that is valid.
949   if (class_type_index->index_ >= header_->type_ids_size_) {
950     return false;
951   }
952 
953   // Now search for the class def. This is basically a specialized version of the DexFile code, as
954   // we should not trust that this is a valid DexFile just yet.
955   const DexFile::ClassDef* class_def_begin =
956       reinterpret_cast<const DexFile::ClassDef*>(begin_ + header_->class_defs_off_);
957   for (size_t i = 0; i < header_->class_defs_size_; ++i) {
958     const DexFile::ClassDef* class_def = class_def_begin + i;
959     if (class_def->class_idx_ == *class_type_index) {
960       *output_class_def = class_def;
961       return true;
962     }
963   }
964 
965   // Didn't find the class-def, not defined here...
966   return false;
967 }
968 
CheckOrderAndGetClassDef(bool is_field,const char * type_descr,uint32_t curr_index,uint32_t prev_index,bool * have_class,dex::TypeIndex * class_type_index,const DexFile::ClassDef ** class_def)969 bool DexFileVerifier::CheckOrderAndGetClassDef(bool is_field,
970                                                const char* type_descr,
971                                                uint32_t curr_index,
972                                                uint32_t prev_index,
973                                                bool* have_class,
974                                                dex::TypeIndex* class_type_index,
975                                                const DexFile::ClassDef** class_def) {
976   if (curr_index < prev_index) {
977     ErrorStringPrintf("out-of-order %s indexes %" PRIu32 " and %" PRIu32,
978                       type_descr,
979                       prev_index,
980                       curr_index);
981     return false;
982   }
983 
984   if (!*have_class) {
985     *have_class = FindClassIndexAndDef(curr_index, is_field, class_type_index, class_def);
986     if (!*have_class) {
987       // Should have really found one.
988       ErrorStringPrintf("could not find declaring class for %s index %" PRIu32,
989                         type_descr,
990                         curr_index);
991       return false;
992     }
993   }
994   return true;
995 }
996 
CheckStaticFieldTypes(const DexFile::ClassDef * class_def)997 bool DexFileVerifier::CheckStaticFieldTypes(const DexFile::ClassDef* class_def) {
998   if (class_def == nullptr) {
999     return true;
1000   }
1001 
1002   ClassDataItemIterator field_it(*dex_file_, ptr_);
1003   EncodedStaticFieldValueIterator array_it(*dex_file_, *class_def);
1004 
1005   for (; field_it.HasNextStaticField() && array_it.HasNext(); field_it.Next(), array_it.Next()) {
1006     uint32_t index = field_it.GetMemberIndex();
1007     const DexFile::TypeId& type_id = dex_file_->GetTypeId(dex_file_->GetFieldId(index).type_idx_);
1008     const char* field_type_name =
1009         dex_file_->GetStringData(dex_file_->GetStringId(type_id.descriptor_idx_));
1010     Primitive::Type field_type = Primitive::GetType(field_type_name[0]);
1011     EncodedArrayValueIterator::ValueType array_type = array_it.GetValueType();
1012     // Ensure this matches RuntimeEncodedStaticFieldValueIterator.
1013     switch (array_type) {
1014       case EncodedArrayValueIterator::ValueType::kBoolean:
1015         if (field_type != Primitive::kPrimBoolean) {
1016           ErrorStringPrintf("unexpected static field initial value type: 'Z' vs '%c'",
1017                             field_type_name[0]);
1018           return false;
1019         }
1020         break;
1021       case EncodedArrayValueIterator::ValueType::kByte:
1022         if (field_type != Primitive::kPrimByte) {
1023           ErrorStringPrintf("unexpected static field initial value type: 'B' vs '%c'",
1024                             field_type_name[0]);
1025           return false;
1026         }
1027         break;
1028       case EncodedArrayValueIterator::ValueType::kShort:
1029         if (field_type != Primitive::kPrimShort) {
1030           ErrorStringPrintf("unexpected static field initial value type: 'S' vs '%c'",
1031                             field_type_name[0]);
1032           return false;
1033         }
1034         break;
1035       case EncodedArrayValueIterator::ValueType::kChar:
1036         if (field_type != Primitive::kPrimChar) {
1037           ErrorStringPrintf("unexpected static field initial value type: 'C' vs '%c'",
1038                             field_type_name[0]);
1039           return false;
1040         }
1041         break;
1042       case EncodedArrayValueIterator::ValueType::kInt:
1043         if (field_type != Primitive::kPrimInt) {
1044           ErrorStringPrintf("unexpected static field initial value type: 'I' vs '%c'",
1045                             field_type_name[0]);
1046           return false;
1047         }
1048         break;
1049       case EncodedArrayValueIterator::ValueType::kLong:
1050         if (field_type != Primitive::kPrimLong) {
1051           ErrorStringPrintf("unexpected static field initial value type: 'J' vs '%c'",
1052                             field_type_name[0]);
1053           return false;
1054         }
1055         break;
1056       case EncodedArrayValueIterator::ValueType::kFloat:
1057         if (field_type != Primitive::kPrimFloat) {
1058           ErrorStringPrintf("unexpected static field initial value type: 'F' vs '%c'",
1059                             field_type_name[0]);
1060           return false;
1061         }
1062         break;
1063       case EncodedArrayValueIterator::ValueType::kDouble:
1064         if (field_type != Primitive::kPrimDouble) {
1065           ErrorStringPrintf("unexpected static field initial value type: 'D' vs '%c'",
1066                             field_type_name[0]);
1067           return false;
1068         }
1069         break;
1070       case EncodedArrayValueIterator::ValueType::kNull:
1071       case EncodedArrayValueIterator::ValueType::kString:
1072       case EncodedArrayValueIterator::ValueType::kType:
1073         if (field_type != Primitive::kPrimNot) {
1074           ErrorStringPrintf("unexpected static field initial value type: 'L' vs '%c'",
1075                             field_type_name[0]);
1076           return false;
1077         }
1078         break;
1079       default:
1080         ErrorStringPrintf("unexpected static field initial value type: %x", array_type);
1081         return false;
1082     }
1083   }
1084 
1085   if (array_it.HasNext()) {
1086     ErrorStringPrintf("too many static field initial values");
1087     return false;
1088   }
1089   return true;
1090 }
1091 
1092 template <bool kStatic>
CheckIntraClassDataItemFields(ClassDataItemIterator * it,bool * have_class,dex::TypeIndex * class_type_index,const DexFile::ClassDef ** class_def)1093 bool DexFileVerifier::CheckIntraClassDataItemFields(ClassDataItemIterator* it,
1094                                                     bool* have_class,
1095                                                     dex::TypeIndex* class_type_index,
1096                                                     const DexFile::ClassDef** class_def) {
1097   DCHECK(it != nullptr);
1098   // These calls use the raw access flags to check whether the whole dex field is valid.
1099   uint32_t prev_index = 0;
1100   for (; kStatic ? it->HasNextStaticField() : it->HasNextInstanceField(); it->Next()) {
1101     uint32_t curr_index = it->GetMemberIndex();
1102     if (!CheckOrderAndGetClassDef(true,
1103                                   kStatic ? "static field" : "instance field",
1104                                   curr_index,
1105                                   prev_index,
1106                                   have_class,
1107                                   class_type_index,
1108                                   class_def)) {
1109       return false;
1110     }
1111     DCHECK(class_def != nullptr);
1112     if (!CheckClassDataItemField(curr_index,
1113                                  it->GetRawMemberAccessFlags(),
1114                                  (*class_def)->access_flags_,
1115                                  *class_type_index,
1116                                  kStatic)) {
1117       return false;
1118     }
1119 
1120     prev_index = curr_index;
1121   }
1122 
1123   return true;
1124 }
1125 
1126 template <bool kDirect>
CheckIntraClassDataItemMethods(ClassDataItemIterator * it,std::unordered_set<uint32_t> * direct_method_indexes,bool * have_class,dex::TypeIndex * class_type_index,const DexFile::ClassDef ** class_def)1127 bool DexFileVerifier::CheckIntraClassDataItemMethods(
1128     ClassDataItemIterator* it,
1129     std::unordered_set<uint32_t>* direct_method_indexes,
1130     bool* have_class,
1131     dex::TypeIndex* class_type_index,
1132     const DexFile::ClassDef** class_def) {
1133   uint32_t prev_index = 0;
1134   for (; kDirect ? it->HasNextDirectMethod() : it->HasNextVirtualMethod(); it->Next()) {
1135     uint32_t curr_index = it->GetMemberIndex();
1136     if (!CheckOrderAndGetClassDef(false,
1137                                   kDirect ? "direct method" : "virtual method",
1138                                   curr_index,
1139                                   prev_index,
1140                                   have_class,
1141                                   class_type_index,
1142                                   class_def)) {
1143       return false;
1144     }
1145     DCHECK(class_def != nullptr);
1146     if (!CheckClassDataItemMethod(curr_index,
1147                                   it->GetRawMemberAccessFlags(),
1148                                   (*class_def)->access_flags_,
1149                                   *class_type_index,
1150                                   it->GetMethodCodeItemOffset(),
1151                                   direct_method_indexes,
1152                                   kDirect)) {
1153       return false;
1154     }
1155 
1156     prev_index = curr_index;
1157   }
1158 
1159   return true;
1160 }
1161 
CheckIntraClassDataItem()1162 bool DexFileVerifier::CheckIntraClassDataItem() {
1163   ClassDataItemIterator it(*dex_file_, ptr_);
1164   std::unordered_set<uint32_t> direct_method_indexes;
1165 
1166   // This code is complicated by the fact that we don't directly know which class this belongs to.
1167   // So we need to explicitly search with the first item we find (either field or method), and then,
1168   // as the lookup is expensive, cache the result.
1169   bool have_class = false;
1170   dex::TypeIndex class_type_index;
1171   const DexFile::ClassDef* class_def = nullptr;
1172 
1173   // Check fields.
1174   if (!CheckIntraClassDataItemFields<true>(&it,
1175                                            &have_class,
1176                                            &class_type_index,
1177                                            &class_def)) {
1178     return false;
1179   }
1180   if (!CheckIntraClassDataItemFields<false>(&it,
1181                                             &have_class,
1182                                             &class_type_index,
1183                                             &class_def)) {
1184     return false;
1185   }
1186 
1187   // Check methods.
1188   if (!CheckIntraClassDataItemMethods<true>(&it,
1189                                             &direct_method_indexes,
1190                                             &have_class,
1191                                             &class_type_index,
1192                                             &class_def)) {
1193     return false;
1194   }
1195   if (!CheckIntraClassDataItemMethods<false>(&it,
1196                                              &direct_method_indexes,
1197                                              &have_class,
1198                                              &class_type_index,
1199                                              &class_def)) {
1200     return false;
1201   }
1202 
1203   const uint8_t* end_ptr = it.EndDataPointer();
1204 
1205   // Check static field types against initial static values in encoded array.
1206   if (!CheckStaticFieldTypes(class_def)) {
1207     return false;
1208   }
1209 
1210   ptr_ = end_ptr;
1211   return true;
1212 }
1213 
CheckIntraCodeItem()1214 bool DexFileVerifier::CheckIntraCodeItem() {
1215   const DexFile::CodeItem* code_item = reinterpret_cast<const DexFile::CodeItem*>(ptr_);
1216   if (!CheckListSize(code_item, 1, sizeof(DexFile::CodeItem), "code")) {
1217     return false;
1218   }
1219 
1220   if (UNLIKELY(code_item->ins_size_ > code_item->registers_size_)) {
1221     ErrorStringPrintf("ins_size (%ud) > registers_size (%ud)",
1222                       code_item->ins_size_, code_item->registers_size_);
1223     return false;
1224   }
1225 
1226   if (UNLIKELY((code_item->outs_size_ > 5) &&
1227                (code_item->outs_size_ > code_item->registers_size_))) {
1228     /*
1229      * outs_size can be up to 5, even if registers_size is smaller, since the
1230      * short forms of method invocation allow repetitions of a register multiple
1231      * times within a single parameter list. However, longer parameter lists
1232      * need to be represented in-order in the register file.
1233      */
1234     ErrorStringPrintf("outs_size (%ud) > registers_size (%ud)",
1235                       code_item->outs_size_, code_item->registers_size_);
1236     return false;
1237   }
1238 
1239   const uint16_t* insns = code_item->insns_;
1240   uint32_t insns_size = code_item->insns_size_in_code_units_;
1241   if (!CheckListSize(insns, insns_size, sizeof(uint16_t), "insns size")) {
1242     return false;
1243   }
1244 
1245   // Grab the end of the insns if there are no try_items.
1246   uint32_t try_items_size = code_item->tries_size_;
1247   if (try_items_size == 0) {
1248     ptr_ = reinterpret_cast<const uint8_t*>(&insns[insns_size]);
1249     return true;
1250   }
1251 
1252   // try_items are 4-byte aligned. Verify the spacer is 0.
1253   if (((reinterpret_cast<uintptr_t>(&insns[insns_size]) & 3) != 0) && (insns[insns_size] != 0)) {
1254     ErrorStringPrintf("Non-zero padding: %x", insns[insns_size]);
1255     return false;
1256   }
1257 
1258   const DexFile::TryItem* try_items = DexFile::GetTryItems(*code_item, 0);
1259   if (!CheckListSize(try_items, try_items_size, sizeof(DexFile::TryItem), "try_items size")) {
1260     return false;
1261   }
1262 
1263   ptr_ = DexFile::GetCatchHandlerData(*code_item, 0);
1264   DECODE_UNSIGNED_CHECKED_FROM(ptr_, handlers_size);
1265 
1266   if (UNLIKELY((handlers_size == 0) || (handlers_size >= 65536))) {
1267     ErrorStringPrintf("Invalid handlers_size: %ud", handlers_size);
1268     return false;
1269   }
1270 
1271   std::unique_ptr<uint32_t[]> handler_offsets(new uint32_t[handlers_size]);
1272   if (!CheckAndGetHandlerOffsets(code_item, &handler_offsets[0], handlers_size)) {
1273     return false;
1274   }
1275 
1276   uint32_t last_addr = 0;
1277   while (try_items_size--) {
1278     if (UNLIKELY(try_items->start_addr_ < last_addr)) {
1279       ErrorStringPrintf("Out-of_order try_item with start_addr: %x", try_items->start_addr_);
1280       return false;
1281     }
1282 
1283     if (UNLIKELY(try_items->start_addr_ >= insns_size)) {
1284       ErrorStringPrintf("Invalid try_item start_addr: %x", try_items->start_addr_);
1285       return false;
1286     }
1287 
1288     uint32_t i;
1289     for (i = 0; i < handlers_size; i++) {
1290       if (try_items->handler_off_ == handler_offsets[i]) {
1291         break;
1292       }
1293     }
1294 
1295     if (UNLIKELY(i == handlers_size)) {
1296       ErrorStringPrintf("Bogus handler offset: %x", try_items->handler_off_);
1297       return false;
1298     }
1299 
1300     last_addr = try_items->start_addr_ + try_items->insn_count_;
1301     if (UNLIKELY(last_addr > insns_size)) {
1302       ErrorStringPrintf("Invalid try_item insn_count: %x", try_items->insn_count_);
1303       return false;
1304     }
1305 
1306     try_items++;
1307   }
1308 
1309   return true;
1310 }
1311 
CheckIntraStringDataItem()1312 bool DexFileVerifier::CheckIntraStringDataItem() {
1313   DECODE_UNSIGNED_CHECKED_FROM(ptr_, size);
1314   const uint8_t* file_end = begin_ + size_;
1315 
1316   for (uint32_t i = 0; i < size; i++) {
1317     CHECK_LT(i, size);  // b/15014252 Prevents hitting the impossible case below
1318     if (UNLIKELY(ptr_ >= file_end)) {
1319       ErrorStringPrintf("String data would go beyond end-of-file");
1320       return false;
1321     }
1322 
1323     uint8_t byte = *(ptr_++);
1324 
1325     // Switch on the high 4 bits.
1326     switch (byte >> 4) {
1327       case 0x00:
1328         // Special case of bit pattern 0xxx.
1329         if (UNLIKELY(byte == 0)) {
1330           CHECK_LT(i, size);  // b/15014252 Actually hit this impossible case with clang
1331           ErrorStringPrintf("String data shorter than indicated utf16_size %x", size);
1332           return false;
1333         }
1334         break;
1335       case 0x01:
1336       case 0x02:
1337       case 0x03:
1338       case 0x04:
1339       case 0x05:
1340       case 0x06:
1341       case 0x07:
1342         // No extra checks necessary for bit pattern 0xxx.
1343         break;
1344       case 0x08:
1345       case 0x09:
1346       case 0x0a:
1347       case 0x0b:
1348       case 0x0f:
1349         // Illegal bit patterns 10xx or 1111.
1350         // Note: 1111 is valid for normal UTF-8, but not here.
1351         ErrorStringPrintf("Illegal start byte %x in string data", byte);
1352         return false;
1353       case 0x0c:
1354       case 0x0d: {
1355         // Bit pattern 110x has an additional byte.
1356         uint8_t byte2 = *(ptr_++);
1357         if (UNLIKELY((byte2 & 0xc0) != 0x80)) {
1358           ErrorStringPrintf("Illegal continuation byte %x in string data", byte2);
1359           return false;
1360         }
1361         uint16_t value = ((byte & 0x1f) << 6) | (byte2 & 0x3f);
1362         if (UNLIKELY((value != 0) && (value < 0x80))) {
1363           ErrorStringPrintf("Illegal representation for value %x in string data", value);
1364           return false;
1365         }
1366         break;
1367       }
1368       case 0x0e: {
1369         // Bit pattern 1110 has 2 additional bytes.
1370         uint8_t byte2 = *(ptr_++);
1371         if (UNLIKELY((byte2 & 0xc0) != 0x80)) {
1372           ErrorStringPrintf("Illegal continuation byte %x in string data", byte2);
1373           return false;
1374         }
1375         uint8_t byte3 = *(ptr_++);
1376         if (UNLIKELY((byte3 & 0xc0) != 0x80)) {
1377           ErrorStringPrintf("Illegal continuation byte %x in string data", byte3);
1378           return false;
1379         }
1380         uint16_t value = ((byte & 0x0f) << 12) | ((byte2 & 0x3f) << 6) | (byte3 & 0x3f);
1381         if (UNLIKELY(value < 0x800)) {
1382           ErrorStringPrintf("Illegal representation for value %x in string data", value);
1383           return false;
1384         }
1385         break;
1386       }
1387     }
1388   }
1389 
1390   if (UNLIKELY(*(ptr_++) != '\0')) {
1391     ErrorStringPrintf("String longer than indicated size %x", size);
1392     return false;
1393   }
1394 
1395   return true;
1396 }
1397 
CheckIntraDebugInfoItem()1398 bool DexFileVerifier::CheckIntraDebugInfoItem() {
1399   DECODE_UNSIGNED_CHECKED_FROM(ptr_, dummy);
1400   DECODE_UNSIGNED_CHECKED_FROM(ptr_, parameters_size);
1401   if (UNLIKELY(parameters_size > 65536)) {
1402     ErrorStringPrintf("Invalid parameters_size: %x", parameters_size);
1403     return false;
1404   }
1405 
1406   for (uint32_t j = 0; j < parameters_size; j++) {
1407     DECODE_UNSIGNED_CHECKED_FROM(ptr_, parameter_name);
1408     if (parameter_name != 0) {
1409       parameter_name--;
1410       if (!CheckIndex(parameter_name, header_->string_ids_size_, "debug_info_item parameter_name")) {
1411         return false;
1412       }
1413     }
1414   }
1415 
1416   while (true) {
1417     uint8_t opcode = *(ptr_++);
1418     switch (opcode) {
1419       case DexFile::DBG_END_SEQUENCE: {
1420         return true;
1421       }
1422       case DexFile::DBG_ADVANCE_PC: {
1423         DECODE_UNSIGNED_CHECKED_FROM(ptr_, advance_pc_dummy);
1424         break;
1425       }
1426       case DexFile::DBG_ADVANCE_LINE: {
1427         DECODE_SIGNED_CHECKED_FROM(ptr_, advance_line_dummy);
1428         break;
1429       }
1430       case DexFile::DBG_START_LOCAL: {
1431         DECODE_UNSIGNED_CHECKED_FROM(ptr_, reg_num);
1432         if (UNLIKELY(reg_num >= 65536)) {
1433           ErrorStringPrintf("Bad reg_num for opcode %x", opcode);
1434           return false;
1435         }
1436         DECODE_UNSIGNED_CHECKED_FROM(ptr_, name_idx);
1437         if (name_idx != 0) {
1438           name_idx--;
1439           if (!CheckIndex(name_idx, header_->string_ids_size_, "DBG_START_LOCAL name_idx")) {
1440             return false;
1441           }
1442         }
1443         DECODE_UNSIGNED_CHECKED_FROM(ptr_, type_idx);
1444         if (type_idx != 0) {
1445           type_idx--;
1446           if (!CheckIndex(type_idx, header_->type_ids_size_, "DBG_START_LOCAL type_idx")) {
1447             return false;
1448           }
1449         }
1450         break;
1451       }
1452       case DexFile::DBG_END_LOCAL:
1453       case DexFile::DBG_RESTART_LOCAL: {
1454         DECODE_UNSIGNED_CHECKED_FROM(ptr_, reg_num);
1455         if (UNLIKELY(reg_num >= 65536)) {
1456           ErrorStringPrintf("Bad reg_num for opcode %x", opcode);
1457           return false;
1458         }
1459         break;
1460       }
1461       case DexFile::DBG_START_LOCAL_EXTENDED: {
1462         DECODE_UNSIGNED_CHECKED_FROM(ptr_, reg_num);
1463         if (UNLIKELY(reg_num >= 65536)) {
1464           ErrorStringPrintf("Bad reg_num for opcode %x", opcode);
1465           return false;
1466         }
1467         DECODE_UNSIGNED_CHECKED_FROM(ptr_, name_idx);
1468         if (name_idx != 0) {
1469           name_idx--;
1470           if (!CheckIndex(name_idx, header_->string_ids_size_, "DBG_START_LOCAL_EXTENDED name_idx")) {
1471             return false;
1472           }
1473         }
1474         DECODE_UNSIGNED_CHECKED_FROM(ptr_, type_idx);
1475         if (type_idx != 0) {
1476           type_idx--;
1477           if (!CheckIndex(type_idx, header_->type_ids_size_, "DBG_START_LOCAL_EXTENDED type_idx")) {
1478             return false;
1479           }
1480         }
1481         DECODE_UNSIGNED_CHECKED_FROM(ptr_, sig_idx);
1482         if (sig_idx != 0) {
1483           sig_idx--;
1484           if (!CheckIndex(sig_idx, header_->string_ids_size_, "DBG_START_LOCAL_EXTENDED sig_idx")) {
1485             return false;
1486           }
1487         }
1488         break;
1489       }
1490       case DexFile::DBG_SET_FILE: {
1491         DECODE_UNSIGNED_CHECKED_FROM(ptr_, name_idx);
1492         if (name_idx != 0) {
1493           name_idx--;
1494           if (!CheckIndex(name_idx, header_->string_ids_size_, "DBG_SET_FILE name_idx")) {
1495             return false;
1496           }
1497         }
1498         break;
1499       }
1500     }
1501   }
1502 }
1503 
CheckIntraAnnotationItem()1504 bool DexFileVerifier::CheckIntraAnnotationItem() {
1505   if (!CheckListSize(ptr_, 1, sizeof(uint8_t), "annotation visibility")) {
1506     return false;
1507   }
1508 
1509   // Check visibility
1510   switch (*(ptr_++)) {
1511     case DexFile::kDexVisibilityBuild:
1512     case DexFile::kDexVisibilityRuntime:
1513     case DexFile::kDexVisibilitySystem:
1514       break;
1515     default:
1516       ErrorStringPrintf("Bad annotation visibility: %x", *ptr_);
1517       return false;
1518   }
1519 
1520   if (!CheckEncodedAnnotation()) {
1521     return false;
1522   }
1523 
1524   return true;
1525 }
1526 
CheckIntraAnnotationsDirectoryItem()1527 bool DexFileVerifier::CheckIntraAnnotationsDirectoryItem() {
1528   const DexFile::AnnotationsDirectoryItem* item =
1529       reinterpret_cast<const DexFile::AnnotationsDirectoryItem*>(ptr_);
1530   if (!CheckListSize(item, 1, sizeof(DexFile::AnnotationsDirectoryItem), "annotations_directory")) {
1531     return false;
1532   }
1533 
1534   // Field annotations follow immediately after the annotations directory.
1535   const DexFile::FieldAnnotationsItem* field_item =
1536       reinterpret_cast<const DexFile::FieldAnnotationsItem*>(item + 1);
1537   uint32_t field_count = item->fields_size_;
1538   if (!CheckListSize(field_item, field_count, sizeof(DexFile::FieldAnnotationsItem), "field_annotations list")) {
1539     return false;
1540   }
1541 
1542   uint32_t last_idx = 0;
1543   for (uint32_t i = 0; i < field_count; i++) {
1544     if (UNLIKELY(last_idx >= field_item->field_idx_ && i != 0)) {
1545       ErrorStringPrintf("Out-of-order field_idx for annotation: %x then %x", last_idx, field_item->field_idx_);
1546       return false;
1547     }
1548     last_idx = field_item->field_idx_;
1549     field_item++;
1550   }
1551 
1552   // Method annotations follow immediately after field annotations.
1553   const DexFile::MethodAnnotationsItem* method_item =
1554       reinterpret_cast<const DexFile::MethodAnnotationsItem*>(field_item);
1555   uint32_t method_count = item->methods_size_;
1556   if (!CheckListSize(method_item, method_count, sizeof(DexFile::MethodAnnotationsItem), "method_annotations list")) {
1557     return false;
1558   }
1559 
1560   last_idx = 0;
1561   for (uint32_t i = 0; i < method_count; i++) {
1562     if (UNLIKELY(last_idx >= method_item->method_idx_ && i != 0)) {
1563       ErrorStringPrintf("Out-of-order method_idx for annotation: %x then %x",
1564                        last_idx, method_item->method_idx_);
1565       return false;
1566     }
1567     last_idx = method_item->method_idx_;
1568     method_item++;
1569   }
1570 
1571   // Parameter annotations follow immediately after method annotations.
1572   const DexFile::ParameterAnnotationsItem* parameter_item =
1573       reinterpret_cast<const DexFile::ParameterAnnotationsItem*>(method_item);
1574   uint32_t parameter_count = item->parameters_size_;
1575   if (!CheckListSize(parameter_item, parameter_count, sizeof(DexFile::ParameterAnnotationsItem),
1576                      "parameter_annotations list")) {
1577     return false;
1578   }
1579 
1580   last_idx = 0;
1581   for (uint32_t i = 0; i < parameter_count; i++) {
1582     if (UNLIKELY(last_idx >= parameter_item->method_idx_ && i != 0)) {
1583       ErrorStringPrintf("Out-of-order method_idx for annotation: %x then %x",
1584                         last_idx, parameter_item->method_idx_);
1585       return false;
1586     }
1587     last_idx = parameter_item->method_idx_;
1588     parameter_item++;
1589   }
1590 
1591   // Return a pointer to the end of the annotations.
1592   ptr_ = reinterpret_cast<const uint8_t*>(parameter_item);
1593   return true;
1594 }
1595 
CheckIntraSectionIterate(size_t offset,uint32_t section_count,DexFile::MapItemType type)1596 bool DexFileVerifier::CheckIntraSectionIterate(size_t offset, uint32_t section_count,
1597                                                DexFile::MapItemType type) {
1598   // Get the right alignment mask for the type of section.
1599   size_t alignment_mask;
1600   switch (type) {
1601     case DexFile::kDexTypeClassDataItem:
1602     case DexFile::kDexTypeStringDataItem:
1603     case DexFile::kDexTypeDebugInfoItem:
1604     case DexFile::kDexTypeAnnotationItem:
1605     case DexFile::kDexTypeEncodedArrayItem:
1606       alignment_mask = sizeof(uint8_t) - 1;
1607       break;
1608     default:
1609       alignment_mask = sizeof(uint32_t) - 1;
1610       break;
1611   }
1612 
1613   // Iterate through the items in the section.
1614   for (uint32_t i = 0; i < section_count; i++) {
1615     size_t aligned_offset = (offset + alignment_mask) & ~alignment_mask;
1616 
1617     // Check the padding between items.
1618     if (!CheckPadding(offset, aligned_offset)) {
1619       return false;
1620     }
1621 
1622     // Check depending on the section type.
1623     const uint8_t* start_ptr = ptr_;
1624     switch (type) {
1625       case DexFile::kDexTypeStringIdItem: {
1626         if (!CheckListSize(ptr_, 1, sizeof(DexFile::StringId), "string_ids")) {
1627           return false;
1628         }
1629         ptr_ += sizeof(DexFile::StringId);
1630         break;
1631       }
1632       case DexFile::kDexTypeTypeIdItem: {
1633         if (!CheckListSize(ptr_, 1, sizeof(DexFile::TypeId), "type_ids")) {
1634           return false;
1635         }
1636         ptr_ += sizeof(DexFile::TypeId);
1637         break;
1638       }
1639       case DexFile::kDexTypeProtoIdItem: {
1640         if (!CheckListSize(ptr_, 1, sizeof(DexFile::ProtoId), "proto_ids")) {
1641           return false;
1642         }
1643         ptr_ += sizeof(DexFile::ProtoId);
1644         break;
1645       }
1646       case DexFile::kDexTypeFieldIdItem: {
1647         if (!CheckListSize(ptr_, 1, sizeof(DexFile::FieldId), "field_ids")) {
1648           return false;
1649         }
1650         ptr_ += sizeof(DexFile::FieldId);
1651         break;
1652       }
1653       case DexFile::kDexTypeMethodIdItem: {
1654         if (!CheckListSize(ptr_, 1, sizeof(DexFile::MethodId), "method_ids")) {
1655           return false;
1656         }
1657         ptr_ += sizeof(DexFile::MethodId);
1658         break;
1659       }
1660       case DexFile::kDexTypeClassDefItem: {
1661         if (!CheckListSize(ptr_, 1, sizeof(DexFile::ClassDef), "class_defs")) {
1662           return false;
1663         }
1664         ptr_ += sizeof(DexFile::ClassDef);
1665         break;
1666       }
1667       case DexFile::kDexTypeCallSiteIdItem: {
1668         if (!CheckListSize(ptr_, 1, sizeof(DexFile::CallSiteIdItem), "call_site_ids")) {
1669           return false;
1670         }
1671         ptr_ += sizeof(DexFile::CallSiteIdItem);
1672         break;
1673       }
1674       case DexFile::kDexTypeMethodHandleItem: {
1675         if (!CheckListSize(ptr_, 1, sizeof(DexFile::MethodHandleItem), "method_handles")) {
1676           return false;
1677         }
1678         ptr_ += sizeof(DexFile::MethodHandleItem);
1679         break;
1680       }
1681       case DexFile::kDexTypeTypeList: {
1682         if (!CheckList(sizeof(DexFile::TypeItem), "type_list", &ptr_)) {
1683           return false;
1684         }
1685         break;
1686       }
1687       case DexFile::kDexTypeAnnotationSetRefList: {
1688         if (!CheckList(sizeof(DexFile::AnnotationSetRefItem), "annotation_set_ref_list", &ptr_)) {
1689           return false;
1690         }
1691         break;
1692       }
1693       case DexFile::kDexTypeAnnotationSetItem: {
1694         if (!CheckList(sizeof(uint32_t), "annotation_set_item", &ptr_)) {
1695           return false;
1696         }
1697         break;
1698       }
1699       case DexFile::kDexTypeClassDataItem: {
1700         if (!CheckIntraClassDataItem()) {
1701           return false;
1702         }
1703         break;
1704       }
1705       case DexFile::kDexTypeCodeItem: {
1706         if (!CheckIntraCodeItem()) {
1707           return false;
1708         }
1709         break;
1710       }
1711       case DexFile::kDexTypeStringDataItem: {
1712         if (!CheckIntraStringDataItem()) {
1713           return false;
1714         }
1715         break;
1716       }
1717       case DexFile::kDexTypeDebugInfoItem: {
1718         if (!CheckIntraDebugInfoItem()) {
1719           return false;
1720         }
1721         break;
1722       }
1723       case DexFile::kDexTypeAnnotationItem: {
1724         if (!CheckIntraAnnotationItem()) {
1725           return false;
1726         }
1727         break;
1728       }
1729       case DexFile::kDexTypeEncodedArrayItem: {
1730         if (!CheckEncodedArray()) {
1731           return false;
1732         }
1733         break;
1734       }
1735       case DexFile::kDexTypeAnnotationsDirectoryItem: {
1736         if (!CheckIntraAnnotationsDirectoryItem()) {
1737           return false;
1738         }
1739         break;
1740       }
1741       case DexFile::kDexTypeHeaderItem:
1742       case DexFile::kDexTypeMapList:
1743         break;
1744     }
1745 
1746     if (start_ptr == ptr_) {
1747       ErrorStringPrintf("Unknown map item type %x", type);
1748       return false;
1749     }
1750 
1751     if (IsDataSectionType(type)) {
1752       if (aligned_offset == 0u) {
1753         ErrorStringPrintf("Item %d offset is 0", i);
1754         return false;
1755       }
1756       DCHECK(offset_to_type_map_.Find(aligned_offset) == offset_to_type_map_.end());
1757       offset_to_type_map_.Insert(std::pair<uint32_t, uint16_t>(aligned_offset, type));
1758     }
1759 
1760     aligned_offset = ptr_ - begin_;
1761     if (UNLIKELY(aligned_offset > size_)) {
1762       ErrorStringPrintf("Item %d at ends out of bounds", i);
1763       return false;
1764     }
1765 
1766     offset = aligned_offset;
1767   }
1768 
1769   return true;
1770 }
1771 
CheckIntraIdSection(size_t offset,uint32_t count,DexFile::MapItemType type)1772 bool DexFileVerifier::CheckIntraIdSection(size_t offset,
1773                                           uint32_t count,
1774                                           DexFile::MapItemType type) {
1775   uint32_t expected_offset;
1776   uint32_t expected_size;
1777 
1778   // Get the expected offset and size from the header.
1779   switch (type) {
1780     case DexFile::kDexTypeStringIdItem:
1781       expected_offset = header_->string_ids_off_;
1782       expected_size = header_->string_ids_size_;
1783       break;
1784     case DexFile::kDexTypeTypeIdItem:
1785       expected_offset = header_->type_ids_off_;
1786       expected_size = header_->type_ids_size_;
1787       break;
1788     case DexFile::kDexTypeProtoIdItem:
1789       expected_offset = header_->proto_ids_off_;
1790       expected_size = header_->proto_ids_size_;
1791       break;
1792     case DexFile::kDexTypeFieldIdItem:
1793       expected_offset = header_->field_ids_off_;
1794       expected_size = header_->field_ids_size_;
1795       break;
1796     case DexFile::kDexTypeMethodIdItem:
1797       expected_offset = header_->method_ids_off_;
1798       expected_size = header_->method_ids_size_;
1799       break;
1800     case DexFile::kDexTypeClassDefItem:
1801       expected_offset = header_->class_defs_off_;
1802       expected_size = header_->class_defs_size_;
1803       break;
1804     default:
1805       ErrorStringPrintf("Bad type for id section: %x", type);
1806       return false;
1807   }
1808 
1809   // Check that the offset and size are what were expected from the header.
1810   if (UNLIKELY(offset != expected_offset)) {
1811     ErrorStringPrintf("Bad offset for section: got %zx, expected %x", offset, expected_offset);
1812     return false;
1813   }
1814   if (UNLIKELY(count != expected_size)) {
1815     ErrorStringPrintf("Bad size for section: got %x, expected %x", count, expected_size);
1816     return false;
1817   }
1818 
1819   return CheckIntraSectionIterate(offset, count, type);
1820 }
1821 
CheckIntraDataSection(size_t offset,uint32_t count,DexFile::MapItemType type)1822 bool DexFileVerifier::CheckIntraDataSection(size_t offset,
1823                                             uint32_t count,
1824                                             DexFile::MapItemType type) {
1825   size_t data_start = header_->data_off_;
1826   size_t data_end = data_start + header_->data_size_;
1827 
1828   // Sanity check the offset of the section.
1829   if (UNLIKELY((offset < data_start) || (offset > data_end))) {
1830     ErrorStringPrintf("Bad offset for data subsection: %zx", offset);
1831     return false;
1832   }
1833 
1834   if (!CheckIntraSectionIterate(offset, count, type)) {
1835     return false;
1836   }
1837 
1838   size_t next_offset = ptr_ - begin_;
1839   if (next_offset > data_end) {
1840     ErrorStringPrintf("Out-of-bounds end of data subsection: %zx", next_offset);
1841     return false;
1842   }
1843 
1844   return true;
1845 }
1846 
CheckIntraSection()1847 bool DexFileVerifier::CheckIntraSection() {
1848   const DexFile::MapList* map = reinterpret_cast<const DexFile::MapList*>(begin_ + header_->map_off_);
1849   const DexFile::MapItem* item = map->list_;
1850   size_t offset = 0;
1851   uint32_t count = map->size_;
1852   ptr_ = begin_;
1853 
1854   // Check the items listed in the map.
1855   while (count--) {
1856     const size_t current_offset = offset;
1857     uint32_t section_offset = item->offset_;
1858     uint32_t section_count = item->size_;
1859     DexFile::MapItemType type = static_cast<DexFile::MapItemType>(item->type_);
1860 
1861     // Check for padding and overlap between items.
1862     if (!CheckPadding(offset, section_offset)) {
1863       return false;
1864     } else if (UNLIKELY(offset > section_offset)) {
1865       ErrorStringPrintf("Section overlap or out-of-order map: %zx, %x", offset, section_offset);
1866       return false;
1867     }
1868 
1869     // Check each item based on its type.
1870     switch (type) {
1871       case DexFile::kDexTypeHeaderItem:
1872         if (UNLIKELY(section_count != 1)) {
1873           ErrorStringPrintf("Multiple header items");
1874           return false;
1875         }
1876         if (UNLIKELY(section_offset != 0)) {
1877           ErrorStringPrintf("Header at %x, not at start of file", section_offset);
1878           return false;
1879         }
1880         ptr_ = begin_ + header_->header_size_;
1881         offset = header_->header_size_;
1882         break;
1883       case DexFile::kDexTypeStringIdItem:
1884       case DexFile::kDexTypeTypeIdItem:
1885       case DexFile::kDexTypeProtoIdItem:
1886       case DexFile::kDexTypeFieldIdItem:
1887       case DexFile::kDexTypeMethodIdItem:
1888       case DexFile::kDexTypeClassDefItem:
1889         if (!CheckIntraIdSection(section_offset, section_count, type)) {
1890           return false;
1891         }
1892         offset = ptr_ - begin_;
1893         break;
1894       case DexFile::kDexTypeMapList:
1895         if (UNLIKELY(section_count != 1)) {
1896           ErrorStringPrintf("Multiple map list items");
1897           return false;
1898         }
1899         if (UNLIKELY(section_offset != header_->map_off_)) {
1900           ErrorStringPrintf("Map not at header-defined offset: %x, expected %x",
1901                             section_offset, header_->map_off_);
1902           return false;
1903         }
1904         ptr_ += sizeof(uint32_t) + (map->size_ * sizeof(DexFile::MapItem));
1905         offset = section_offset + sizeof(uint32_t) + (map->size_ * sizeof(DexFile::MapItem));
1906         break;
1907       case DexFile::kDexTypeMethodHandleItem:
1908       case DexFile::kDexTypeCallSiteIdItem:
1909         CheckIntraSectionIterate(section_offset, section_count, type);
1910         offset = ptr_ - begin_;
1911         break;
1912       case DexFile::kDexTypeTypeList:
1913       case DexFile::kDexTypeAnnotationSetRefList:
1914       case DexFile::kDexTypeAnnotationSetItem:
1915       case DexFile::kDexTypeClassDataItem:
1916       case DexFile::kDexTypeCodeItem:
1917       case DexFile::kDexTypeStringDataItem:
1918       case DexFile::kDexTypeDebugInfoItem:
1919       case DexFile::kDexTypeAnnotationItem:
1920       case DexFile::kDexTypeEncodedArrayItem:
1921       case DexFile::kDexTypeAnnotationsDirectoryItem:
1922         if (!CheckIntraDataSection(section_offset, section_count, type)) {
1923           return false;
1924         }
1925         offset = ptr_ - begin_;
1926         break;
1927     }
1928 
1929     if (offset == current_offset) {
1930         ErrorStringPrintf("Unknown map item type %x", type);
1931         return false;
1932     }
1933 
1934     item++;
1935   }
1936 
1937   return true;
1938 }
1939 
CheckOffsetToTypeMap(size_t offset,uint16_t type)1940 bool DexFileVerifier::CheckOffsetToTypeMap(size_t offset, uint16_t type) {
1941   DCHECK_NE(offset, 0u);
1942   auto it = offset_to_type_map_.Find(offset);
1943   if (UNLIKELY(it == offset_to_type_map_.end())) {
1944     ErrorStringPrintf("No data map entry found @ %zx; expected %x", offset, type);
1945     return false;
1946   }
1947   if (UNLIKELY(it->second != type)) {
1948     ErrorStringPrintf("Unexpected data map entry @ %zx; expected %x, found %x",
1949                       offset, type, it->second);
1950     return false;
1951   }
1952   return true;
1953 }
1954 
FindFirstClassDataDefiner(const uint8_t * ptr,bool * success)1955 dex::TypeIndex DexFileVerifier::FindFirstClassDataDefiner(const uint8_t* ptr, bool* success) {
1956   ClassDataItemIterator it(*dex_file_, ptr);
1957   *success = true;
1958 
1959   if (it.HasNextStaticField() || it.HasNextInstanceField()) {
1960     LOAD_FIELD(field, it.GetMemberIndex(), "first_class_data_definer field_id",
1961                *success = false; return dex::TypeIndex(DexFile::kDexNoIndex16))
1962     return field->class_idx_;
1963   }
1964 
1965   if (it.HasNextDirectMethod() || it.HasNextVirtualMethod()) {
1966     LOAD_METHOD(method, it.GetMemberIndex(), "first_class_data_definer method_id",
1967                 *success = false; return dex::TypeIndex(DexFile::kDexNoIndex16))
1968     return method->class_idx_;
1969   }
1970 
1971   return dex::TypeIndex(DexFile::kDexNoIndex16);
1972 }
1973 
FindFirstAnnotationsDirectoryDefiner(const uint8_t * ptr,bool * success)1974 dex::TypeIndex DexFileVerifier::FindFirstAnnotationsDirectoryDefiner(const uint8_t* ptr,
1975                                                                      bool* success) {
1976   const DexFile::AnnotationsDirectoryItem* item =
1977       reinterpret_cast<const DexFile::AnnotationsDirectoryItem*>(ptr);
1978   *success = true;
1979 
1980   if (item->fields_size_ != 0) {
1981     DexFile::FieldAnnotationsItem* field_items = (DexFile::FieldAnnotationsItem*) (item + 1);
1982     LOAD_FIELD(field, field_items[0].field_idx_, "first_annotations_dir_definer field_id",
1983                *success = false; return dex::TypeIndex(DexFile::kDexNoIndex16))
1984     return field->class_idx_;
1985   }
1986 
1987   if (item->methods_size_ != 0) {
1988     DexFile::MethodAnnotationsItem* method_items = (DexFile::MethodAnnotationsItem*) (item + 1);
1989     LOAD_METHOD(method, method_items[0].method_idx_, "first_annotations_dir_definer method id",
1990                 *success = false; return dex::TypeIndex(DexFile::kDexNoIndex16))
1991     return method->class_idx_;
1992   }
1993 
1994   if (item->parameters_size_ != 0) {
1995     DexFile::ParameterAnnotationsItem* parameter_items = (DexFile::ParameterAnnotationsItem*) (item + 1);
1996     LOAD_METHOD(method, parameter_items[0].method_idx_, "first_annotations_dir_definer method id",
1997                 *success = false; return dex::TypeIndex(DexFile::kDexNoIndex16))
1998     return method->class_idx_;
1999   }
2000 
2001   return dex::TypeIndex(DexFile::kDexNoIndex16);
2002 }
2003 
CheckInterStringIdItem()2004 bool DexFileVerifier::CheckInterStringIdItem() {
2005   const DexFile::StringId* item = reinterpret_cast<const DexFile::StringId*>(ptr_);
2006 
2007   // Check the map to make sure it has the right offset->type.
2008   if (!CheckOffsetToTypeMap(item->string_data_off_, DexFile::kDexTypeStringDataItem)) {
2009     return false;
2010   }
2011 
2012   // Check ordering between items.
2013   if (previous_item_ != nullptr) {
2014     const DexFile::StringId* prev_item = reinterpret_cast<const DexFile::StringId*>(previous_item_);
2015     const char* prev_str = dex_file_->GetStringData(*prev_item);
2016     const char* str = dex_file_->GetStringData(*item);
2017     if (UNLIKELY(CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(prev_str, str) >= 0)) {
2018       ErrorStringPrintf("Out-of-order string_ids: '%s' then '%s'", prev_str, str);
2019       return false;
2020     }
2021   }
2022 
2023   ptr_ += sizeof(DexFile::StringId);
2024   return true;
2025 }
2026 
CheckInterTypeIdItem()2027 bool DexFileVerifier::CheckInterTypeIdItem() {
2028   const DexFile::TypeId* item = reinterpret_cast<const DexFile::TypeId*>(ptr_);
2029 
2030   LOAD_STRING(descriptor, item->descriptor_idx_, "inter_type_id_item descriptor_idx")
2031 
2032   // Check that the descriptor is a valid type.
2033   if (UNLIKELY(!IsValidDescriptor(descriptor))) {
2034     ErrorStringPrintf("Invalid type descriptor: '%s'", descriptor);
2035     return false;
2036   }
2037 
2038   // Check ordering between items.
2039   if (previous_item_ != nullptr) {
2040     const DexFile::TypeId* prev_item = reinterpret_cast<const DexFile::TypeId*>(previous_item_);
2041     if (UNLIKELY(prev_item->descriptor_idx_ >= item->descriptor_idx_)) {
2042       ErrorStringPrintf("Out-of-order type_ids: %x then %x",
2043                         prev_item->descriptor_idx_.index_,
2044                         item->descriptor_idx_.index_);
2045       return false;
2046     }
2047   }
2048 
2049   ptr_ += sizeof(DexFile::TypeId);
2050   return true;
2051 }
2052 
CheckInterProtoIdItem()2053 bool DexFileVerifier::CheckInterProtoIdItem() {
2054   const DexFile::ProtoId* item = reinterpret_cast<const DexFile::ProtoId*>(ptr_);
2055 
2056   LOAD_STRING(shorty, item->shorty_idx_, "inter_proto_id_item shorty_idx")
2057 
2058   if (item->parameters_off_ != 0 &&
2059       !CheckOffsetToTypeMap(item->parameters_off_, DexFile::kDexTypeTypeList)) {
2060     return false;
2061   }
2062 
2063   // Check that return type is representable as a uint16_t;
2064   if (UNLIKELY(!IsValidOrNoTypeId(item->return_type_idx_.index_, item->pad_))) {
2065     ErrorStringPrintf("proto with return type idx outside uint16_t range '%x:%x'",
2066                       item->pad_, item->return_type_idx_.index_);
2067     return false;
2068   }
2069   // Check the return type and advance the shorty.
2070   LOAD_STRING_BY_TYPE(return_type, item->return_type_idx_, "inter_proto_id_item return_type_idx")
2071   if (!CheckShortyDescriptorMatch(*shorty, return_type, true)) {
2072     return false;
2073   }
2074   shorty++;
2075 
2076   DexFileParameterIterator it(*dex_file_, *item);
2077   while (it.HasNext() && *shorty != '\0') {
2078     if (!CheckIndex(it.GetTypeIdx().index_,
2079                     dex_file_->NumTypeIds(),
2080                     "inter_proto_id_item shorty type_idx")) {
2081       return false;
2082     }
2083     const char* descriptor = it.GetDescriptor();
2084     if (!CheckShortyDescriptorMatch(*shorty, descriptor, false)) {
2085       return false;
2086     }
2087     it.Next();
2088     shorty++;
2089   }
2090   if (UNLIKELY(it.HasNext() || *shorty != '\0')) {
2091     ErrorStringPrintf("Mismatched length for parameters and shorty");
2092     return false;
2093   }
2094 
2095   // Check ordering between items. This relies on type_ids being in order.
2096   if (previous_item_ != nullptr) {
2097     const DexFile::ProtoId* prev = reinterpret_cast<const DexFile::ProtoId*>(previous_item_);
2098     if (UNLIKELY(prev->return_type_idx_ > item->return_type_idx_)) {
2099       ErrorStringPrintf("Out-of-order proto_id return types");
2100       return false;
2101     } else if (prev->return_type_idx_ == item->return_type_idx_) {
2102       DexFileParameterIterator curr_it(*dex_file_, *item);
2103       DexFileParameterIterator prev_it(*dex_file_, *prev);
2104 
2105       while (curr_it.HasNext() && prev_it.HasNext()) {
2106         dex::TypeIndex prev_idx = prev_it.GetTypeIdx();
2107         dex::TypeIndex curr_idx = curr_it.GetTypeIdx();
2108         DCHECK_NE(prev_idx, dex::TypeIndex(DexFile::kDexNoIndex16));
2109         DCHECK_NE(curr_idx, dex::TypeIndex(DexFile::kDexNoIndex16));
2110 
2111         if (prev_idx < curr_idx) {
2112           break;
2113         } else if (UNLIKELY(prev_idx > curr_idx)) {
2114           ErrorStringPrintf("Out-of-order proto_id arguments");
2115           return false;
2116         }
2117 
2118         prev_it.Next();
2119         curr_it.Next();
2120       }
2121       if (!curr_it.HasNext()) {
2122         // Either a duplicate ProtoId or a ProtoId with a shorter argument list follows
2123         // a ProtoId with a longer one. Both cases are forbidden by the specification.
2124         ErrorStringPrintf("Out-of-order proto_id arguments");
2125         return false;
2126       }
2127     }
2128   }
2129 
2130   ptr_ += sizeof(DexFile::ProtoId);
2131   return true;
2132 }
2133 
CheckInterFieldIdItem()2134 bool DexFileVerifier::CheckInterFieldIdItem() {
2135   const DexFile::FieldId* item = reinterpret_cast<const DexFile::FieldId*>(ptr_);
2136 
2137   // Check that the class descriptor is valid.
2138   LOAD_STRING_BY_TYPE(class_descriptor, item->class_idx_, "inter_field_id_item class_idx")
2139   if (UNLIKELY(!IsValidDescriptor(class_descriptor) || class_descriptor[0] != 'L')) {
2140     ErrorStringPrintf("Invalid descriptor for class_idx: '%s'", class_descriptor);
2141     return false;
2142   }
2143 
2144   // Check that the type descriptor is a valid field name.
2145   LOAD_STRING_BY_TYPE(type_descriptor, item->type_idx_, "inter_field_id_item type_idx")
2146   if (UNLIKELY(!IsValidDescriptor(type_descriptor) || type_descriptor[0] == 'V')) {
2147     ErrorStringPrintf("Invalid descriptor for type_idx: '%s'", type_descriptor);
2148     return false;
2149   }
2150 
2151   // Check that the name is valid.
2152   LOAD_STRING(descriptor, item->name_idx_, "inter_field_id_item name_idx")
2153   if (UNLIKELY(!IsValidMemberName(descriptor))) {
2154     ErrorStringPrintf("Invalid field name: '%s'", descriptor);
2155     return false;
2156   }
2157 
2158   // Check ordering between items. This relies on the other sections being in order.
2159   if (previous_item_ != nullptr) {
2160     const DexFile::FieldId* prev_item = reinterpret_cast<const DexFile::FieldId*>(previous_item_);
2161     if (UNLIKELY(prev_item->class_idx_ > item->class_idx_)) {
2162       ErrorStringPrintf("Out-of-order field_ids");
2163       return false;
2164     } else if (prev_item->class_idx_ == item->class_idx_) {
2165       if (UNLIKELY(prev_item->name_idx_ > item->name_idx_)) {
2166         ErrorStringPrintf("Out-of-order field_ids");
2167         return false;
2168       } else if (prev_item->name_idx_ == item->name_idx_) {
2169         if (UNLIKELY(prev_item->type_idx_ >= item->type_idx_)) {
2170           ErrorStringPrintf("Out-of-order field_ids");
2171           return false;
2172         }
2173       }
2174     }
2175   }
2176 
2177   ptr_ += sizeof(DexFile::FieldId);
2178   return true;
2179 }
2180 
CheckInterMethodIdItem()2181 bool DexFileVerifier::CheckInterMethodIdItem() {
2182   const DexFile::MethodId* item = reinterpret_cast<const DexFile::MethodId*>(ptr_);
2183 
2184   // Check that the class descriptor is a valid reference name.
2185   LOAD_STRING_BY_TYPE(class_descriptor, item->class_idx_, "inter_method_id_item class_idx")
2186   if (UNLIKELY(!IsValidDescriptor(class_descriptor) || (class_descriptor[0] != 'L' &&
2187                                                         class_descriptor[0] != '['))) {
2188     ErrorStringPrintf("Invalid descriptor for class_idx: '%s'", class_descriptor);
2189     return false;
2190   }
2191 
2192   // Check that the name is valid.
2193   LOAD_STRING(descriptor, item->name_idx_, "inter_method_id_item name_idx")
2194   if (UNLIKELY(!IsValidMemberName(descriptor))) {
2195     ErrorStringPrintf("Invalid method name: '%s'", descriptor);
2196     return false;
2197   }
2198 
2199   // Check that the proto id is valid.
2200   if (UNLIKELY(!CheckIndex(item->proto_idx_, dex_file_->NumProtoIds(),
2201                            "inter_method_id_item proto_idx"))) {
2202     return false;
2203   }
2204 
2205   // Check ordering between items. This relies on the other sections being in order.
2206   if (previous_item_ != nullptr) {
2207     const DexFile::MethodId* prev_item = reinterpret_cast<const DexFile::MethodId*>(previous_item_);
2208     if (UNLIKELY(prev_item->class_idx_ > item->class_idx_)) {
2209       ErrorStringPrintf("Out-of-order method_ids");
2210       return false;
2211     } else if (prev_item->class_idx_ == item->class_idx_) {
2212       if (UNLIKELY(prev_item->name_idx_ > item->name_idx_)) {
2213         ErrorStringPrintf("Out-of-order method_ids");
2214         return false;
2215       } else if (prev_item->name_idx_ == item->name_idx_) {
2216         if (UNLIKELY(prev_item->proto_idx_ >= item->proto_idx_)) {
2217           ErrorStringPrintf("Out-of-order method_ids");
2218           return false;
2219         }
2220       }
2221     }
2222   }
2223 
2224   ptr_ += sizeof(DexFile::MethodId);
2225   return true;
2226 }
2227 
CheckInterClassDefItem()2228 bool DexFileVerifier::CheckInterClassDefItem() {
2229   const DexFile::ClassDef* item = reinterpret_cast<const DexFile::ClassDef*>(ptr_);
2230 
2231   // Check that class_idx_ is representable as a uint16_t;
2232   if (UNLIKELY(!IsValidTypeId(item->class_idx_.index_, item->pad1_))) {
2233     ErrorStringPrintf("class with type idx outside uint16_t range '%x:%x'", item->pad1_,
2234                       item->class_idx_.index_);
2235     return false;
2236   }
2237   // Check that superclass_idx_ is representable as a uint16_t;
2238   if (UNLIKELY(!IsValidOrNoTypeId(item->superclass_idx_.index_, item->pad2_))) {
2239     ErrorStringPrintf("class with superclass type idx outside uint16_t range '%x:%x'", item->pad2_,
2240                       item->superclass_idx_.index_);
2241     return false;
2242   }
2243   // Check for duplicate class def.
2244   if (defined_classes_.find(item->class_idx_) != defined_classes_.end()) {
2245     ErrorStringPrintf("Redefinition of class with type idx: '%d'", item->class_idx_.index_);
2246     return false;
2247   }
2248   defined_classes_.insert(item->class_idx_);
2249 
2250   LOAD_STRING_BY_TYPE(class_descriptor, item->class_idx_, "inter_class_def_item class_idx")
2251   if (UNLIKELY(!IsValidDescriptor(class_descriptor) || class_descriptor[0] != 'L')) {
2252     ErrorStringPrintf("Invalid class descriptor: '%s'", class_descriptor);
2253     return false;
2254   }
2255 
2256   // Only allow non-runtime modifiers.
2257   if ((item->access_flags_ & ~kAccJavaFlagsMask) != 0) {
2258     ErrorStringPrintf("Invalid class flags: '%d'", item->access_flags_);
2259     return false;
2260   }
2261 
2262   if (item->interfaces_off_ != 0 &&
2263       !CheckOffsetToTypeMap(item->interfaces_off_, DexFile::kDexTypeTypeList)) {
2264     return false;
2265   }
2266   if (item->annotations_off_ != 0 &&
2267       !CheckOffsetToTypeMap(item->annotations_off_, DexFile::kDexTypeAnnotationsDirectoryItem)) {
2268     return false;
2269   }
2270   if (item->class_data_off_ != 0 &&
2271       !CheckOffsetToTypeMap(item->class_data_off_, DexFile::kDexTypeClassDataItem)) {
2272     return false;
2273   }
2274   if (item->static_values_off_ != 0 &&
2275       !CheckOffsetToTypeMap(item->static_values_off_, DexFile::kDexTypeEncodedArrayItem)) {
2276     return false;
2277   }
2278 
2279   if (item->superclass_idx_.IsValid()) {
2280     if (header_->GetVersion() >= DexFile::kClassDefinitionOrderEnforcedVersion) {
2281       // Check that a class does not inherit from itself directly (by having
2282       // the same type idx as its super class).
2283       if (UNLIKELY(item->superclass_idx_ == item->class_idx_)) {
2284         ErrorStringPrintf("Class with same type idx as its superclass: '%d'",
2285                           item->class_idx_.index_);
2286         return false;
2287       }
2288 
2289       // Check that a class is defined after its super class (if the
2290       // latter is defined in the same Dex file).
2291       const DexFile::ClassDef* superclass_def = dex_file_->FindClassDef(item->superclass_idx_);
2292       if (superclass_def != nullptr) {
2293         // The superclass is defined in this Dex file.
2294         if (superclass_def > item) {
2295           // ClassDef item for super class appearing after the class' ClassDef item.
2296           ErrorStringPrintf("Invalid class definition ordering:"
2297                             " class with type idx: '%d' defined before"
2298                             " superclass with type idx: '%d'",
2299                             item->class_idx_.index_,
2300                             item->superclass_idx_.index_);
2301           return false;
2302         }
2303       }
2304     }
2305 
2306     LOAD_STRING_BY_TYPE(superclass_descriptor, item->superclass_idx_,
2307                         "inter_class_def_item superclass_idx")
2308     if (UNLIKELY(!IsValidDescriptor(superclass_descriptor) || superclass_descriptor[0] != 'L')) {
2309       ErrorStringPrintf("Invalid superclass: '%s'", superclass_descriptor);
2310       return false;
2311     }
2312   }
2313 
2314   // Check interfaces.
2315   const DexFile::TypeList* interfaces = dex_file_->GetInterfacesList(*item);
2316   if (interfaces != nullptr) {
2317     uint32_t size = interfaces->Size();
2318     for (uint32_t i = 0; i < size; i++) {
2319       if (header_->GetVersion() >= DexFile::kClassDefinitionOrderEnforcedVersion) {
2320         // Check that a class does not implement itself directly (by having the
2321         // same type idx as one of its immediate implemented interfaces).
2322         if (UNLIKELY(interfaces->GetTypeItem(i).type_idx_ == item->class_idx_)) {
2323           ErrorStringPrintf("Class with same type idx as implemented interface: '%d'",
2324                             item->class_idx_.index_);
2325           return false;
2326         }
2327 
2328         // Check that a class is defined after the interfaces it implements
2329         // (if they are defined in the same Dex file).
2330         const DexFile::ClassDef* interface_def =
2331             dex_file_->FindClassDef(interfaces->GetTypeItem(i).type_idx_);
2332         if (interface_def != nullptr) {
2333           // The interface is defined in this Dex file.
2334           if (interface_def > item) {
2335             // ClassDef item for interface appearing after the class' ClassDef item.
2336             ErrorStringPrintf("Invalid class definition ordering:"
2337                               " class with type idx: '%d' defined before"
2338                               " implemented interface with type idx: '%d'",
2339                               item->class_idx_.index_,
2340                               interfaces->GetTypeItem(i).type_idx_.index_);
2341             return false;
2342           }
2343         }
2344       }
2345 
2346       // Ensure that the interface refers to a class (not an array nor a primitive type).
2347       LOAD_STRING_BY_TYPE(inf_descriptor, interfaces->GetTypeItem(i).type_idx_,
2348                           "inter_class_def_item interface type_idx")
2349       if (UNLIKELY(!IsValidDescriptor(inf_descriptor) || inf_descriptor[0] != 'L')) {
2350         ErrorStringPrintf("Invalid interface: '%s'", inf_descriptor);
2351         return false;
2352       }
2353     }
2354 
2355     /*
2356      * Ensure that there are no duplicates. This is an O(N^2) test, but in
2357      * practice the number of interfaces implemented by any given class is low.
2358      */
2359     for (uint32_t i = 1; i < size; i++) {
2360       dex::TypeIndex idx1 = interfaces->GetTypeItem(i).type_idx_;
2361       for (uint32_t j =0; j < i; j++) {
2362         dex::TypeIndex idx2 = interfaces->GetTypeItem(j).type_idx_;
2363         if (UNLIKELY(idx1 == idx2)) {
2364           ErrorStringPrintf("Duplicate interface: '%s'", dex_file_->StringByTypeIdx(idx1));
2365           return false;
2366         }
2367       }
2368     }
2369   }
2370 
2371   // Check that references in class_data_item are to the right class.
2372   if (item->class_data_off_ != 0) {
2373     const uint8_t* data = begin_ + item->class_data_off_;
2374     bool success;
2375     dex::TypeIndex data_definer = FindFirstClassDataDefiner(data, &success);
2376     if (!success) {
2377       return false;
2378     }
2379     if (UNLIKELY((data_definer != item->class_idx_) &&
2380                  (data_definer != dex::TypeIndex(DexFile::kDexNoIndex16)))) {
2381       ErrorStringPrintf("Invalid class_data_item");
2382       return false;
2383     }
2384   }
2385 
2386   // Check that references in annotations_directory_item are to right class.
2387   if (item->annotations_off_ != 0) {
2388     // annotations_off_ is supposed to be aligned by 4.
2389     if (!IsAlignedParam(item->annotations_off_, 4)) {
2390       ErrorStringPrintf("Invalid annotations_off_, not aligned by 4");
2391       return false;
2392     }
2393     const uint8_t* data = begin_ + item->annotations_off_;
2394     bool success;
2395     dex::TypeIndex annotations_definer = FindFirstAnnotationsDirectoryDefiner(data, &success);
2396     if (!success) {
2397       return false;
2398     }
2399     if (UNLIKELY((annotations_definer != item->class_idx_) &&
2400                  (annotations_definer != dex::TypeIndex(DexFile::kDexNoIndex16)))) {
2401       ErrorStringPrintf("Invalid annotations_directory_item");
2402       return false;
2403     }
2404   }
2405 
2406   ptr_ += sizeof(DexFile::ClassDef);
2407   return true;
2408 }
2409 
CheckInterCallSiteIdItem()2410 bool DexFileVerifier::CheckInterCallSiteIdItem() {
2411   const DexFile::CallSiteIdItem* item = reinterpret_cast<const DexFile::CallSiteIdItem*>(ptr_);
2412 
2413   // Check call site referenced by item is in encoded array section.
2414   if (!CheckOffsetToTypeMap(item->data_off_, DexFile::kDexTypeEncodedArrayItem)) {
2415     ErrorStringPrintf("Invalid offset in CallSideIdItem");
2416     return false;
2417   }
2418 
2419   CallSiteArrayValueIterator it(*dex_file_, *item);
2420 
2421   // Check Method Handle
2422   if (!it.HasNext() || it.GetValueType() != EncodedArrayValueIterator::ValueType::kMethodHandle) {
2423     ErrorStringPrintf("CallSiteArray missing method handle");
2424     return false;
2425   }
2426 
2427   uint32_t handle_index = static_cast<uint32_t>(it.GetJavaValue().i);
2428   if (handle_index >= dex_file_->NumMethodHandles()) {
2429     ErrorStringPrintf("CallSite has bad method handle id: %x", handle_index);
2430     return false;
2431   }
2432 
2433   // Check target method name.
2434   it.Next();
2435   if (!it.HasNext() ||
2436       it.GetValueType() != EncodedArrayValueIterator::ValueType::kString) {
2437     ErrorStringPrintf("CallSiteArray missing target method name");
2438     return false;
2439   }
2440 
2441   uint32_t name_index = static_cast<uint32_t>(it.GetJavaValue().i);
2442   if (name_index >= dex_file_->NumStringIds()) {
2443     ErrorStringPrintf("CallSite has bad method name id: %x", name_index);
2444     return false;
2445   }
2446 
2447   // Check method type.
2448   it.Next();
2449   if (!it.HasNext() ||
2450       it.GetValueType() != EncodedArrayValueIterator::ValueType::kMethodType) {
2451     ErrorStringPrintf("CallSiteArray missing method type");
2452     return false;
2453   }
2454 
2455   uint32_t proto_index = static_cast<uint32_t>(it.GetJavaValue().i);
2456   if (proto_index >= dex_file_->NumProtoIds()) {
2457     ErrorStringPrintf("CallSite has bad method type: %x", proto_index);
2458     return false;
2459   }
2460 
2461   ptr_ += sizeof(DexFile::CallSiteIdItem);
2462   return true;
2463 }
2464 
CheckInterMethodHandleItem()2465 bool DexFileVerifier::CheckInterMethodHandleItem() {
2466   const DexFile::MethodHandleItem* item = reinterpret_cast<const DexFile::MethodHandleItem*>(ptr_);
2467 
2468   DexFile::MethodHandleType method_handle_type =
2469       static_cast<DexFile::MethodHandleType>(item->method_handle_type_);
2470   if (method_handle_type > DexFile::MethodHandleType::kLast) {
2471     ErrorStringPrintf("Bad method handle type %x", item->method_handle_type_);
2472     return false;
2473   }
2474 
2475   uint32_t index = item->field_or_method_idx_;
2476   switch (method_handle_type) {
2477     case DexFile::MethodHandleType::kStaticPut:
2478     case DexFile::MethodHandleType::kStaticGet:
2479     case DexFile::MethodHandleType::kInstancePut:
2480     case DexFile::MethodHandleType::kInstanceGet: {
2481       LOAD_FIELD(field, index, "method_handle_item field_idx", return false);
2482       break;
2483     }
2484     case DexFile::MethodHandleType::kInvokeStatic:
2485     case DexFile::MethodHandleType::kInvokeInstance:
2486     case DexFile::MethodHandleType::kInvokeConstructor: {
2487       LOAD_METHOD(method, index, "method_handle_item method_idx", return false);
2488       break;
2489     }
2490   }
2491 
2492   ptr_ += sizeof(DexFile::MethodHandleItem);
2493   return true;
2494 }
2495 
CheckInterAnnotationSetRefList()2496 bool DexFileVerifier::CheckInterAnnotationSetRefList() {
2497   const DexFile::AnnotationSetRefList* list =
2498       reinterpret_cast<const DexFile::AnnotationSetRefList*>(ptr_);
2499   const DexFile::AnnotationSetRefItem* item = list->list_;
2500   uint32_t count = list->size_;
2501 
2502   while (count--) {
2503     if (item->annotations_off_ != 0 &&
2504         !CheckOffsetToTypeMap(item->annotations_off_, DexFile::kDexTypeAnnotationSetItem)) {
2505       return false;
2506     }
2507     item++;
2508   }
2509 
2510   ptr_ = reinterpret_cast<const uint8_t*>(item);
2511   return true;
2512 }
2513 
CheckInterAnnotationSetItem()2514 bool DexFileVerifier::CheckInterAnnotationSetItem() {
2515   const DexFile::AnnotationSetItem* set = reinterpret_cast<const DexFile::AnnotationSetItem*>(ptr_);
2516   const uint32_t* offsets = set->entries_;
2517   uint32_t count = set->size_;
2518   uint32_t last_idx = 0;
2519 
2520   for (uint32_t i = 0; i < count; i++) {
2521     if (*offsets != 0 && !CheckOffsetToTypeMap(*offsets, DexFile::kDexTypeAnnotationItem)) {
2522       return false;
2523     }
2524 
2525     // Get the annotation from the offset and the type index for the annotation.
2526     const DexFile::AnnotationItem* annotation =
2527         reinterpret_cast<const DexFile::AnnotationItem*>(begin_ + *offsets);
2528     const uint8_t* data = annotation->annotation_;
2529     DECODE_UNSIGNED_CHECKED_FROM(data, idx);
2530 
2531     if (UNLIKELY(last_idx >= idx && i != 0)) {
2532       ErrorStringPrintf("Out-of-order entry types: %x then %x", last_idx, idx);
2533       return false;
2534     }
2535 
2536     last_idx = idx;
2537     offsets++;
2538   }
2539 
2540   ptr_ = reinterpret_cast<const uint8_t*>(offsets);
2541   return true;
2542 }
2543 
CheckInterClassDataItem()2544 bool DexFileVerifier::CheckInterClassDataItem() {
2545   ClassDataItemIterator it(*dex_file_, ptr_);
2546   bool success;
2547   dex::TypeIndex defining_class = FindFirstClassDataDefiner(ptr_, &success);
2548   if (!success) {
2549     return false;
2550   }
2551 
2552   for (; it.HasNextStaticField() || it.HasNextInstanceField(); it.Next()) {
2553     LOAD_FIELD(field, it.GetMemberIndex(), "inter_class_data_item field_id", return false)
2554     if (UNLIKELY(field->class_idx_ != defining_class)) {
2555       ErrorStringPrintf("Mismatched defining class for class_data_item field");
2556       return false;
2557     }
2558   }
2559   for (; it.HasNextDirectMethod() || it.HasNextVirtualMethod(); it.Next()) {
2560     uint32_t code_off = it.GetMethodCodeItemOffset();
2561     if (code_off != 0 && !CheckOffsetToTypeMap(code_off, DexFile::kDexTypeCodeItem)) {
2562       return false;
2563     }
2564     LOAD_METHOD(method, it.GetMemberIndex(), "inter_class_data_item method_id", return false)
2565     if (UNLIKELY(method->class_idx_ != defining_class)) {
2566       ErrorStringPrintf("Mismatched defining class for class_data_item method");
2567       return false;
2568     }
2569   }
2570 
2571   ptr_ = it.EndDataPointer();
2572   return true;
2573 }
2574 
CheckInterAnnotationsDirectoryItem()2575 bool DexFileVerifier::CheckInterAnnotationsDirectoryItem() {
2576   const DexFile::AnnotationsDirectoryItem* item =
2577       reinterpret_cast<const DexFile::AnnotationsDirectoryItem*>(ptr_);
2578   bool success;
2579   dex::TypeIndex defining_class = FindFirstAnnotationsDirectoryDefiner(ptr_, &success);
2580   if (!success) {
2581     return false;
2582   }
2583 
2584   if (item->class_annotations_off_ != 0 &&
2585       !CheckOffsetToTypeMap(item->class_annotations_off_, DexFile::kDexTypeAnnotationSetItem)) {
2586     return false;
2587   }
2588 
2589   // Field annotations follow immediately after the annotations directory.
2590   const DexFile::FieldAnnotationsItem* field_item =
2591       reinterpret_cast<const DexFile::FieldAnnotationsItem*>(item + 1);
2592   uint32_t field_count = item->fields_size_;
2593   for (uint32_t i = 0; i < field_count; i++) {
2594     LOAD_FIELD(field, field_item->field_idx_, "inter_annotations_directory_item field_id",
2595                return false)
2596     if (UNLIKELY(field->class_idx_ != defining_class)) {
2597       ErrorStringPrintf("Mismatched defining class for field_annotation");
2598       return false;
2599     }
2600     if (!CheckOffsetToTypeMap(field_item->annotations_off_, DexFile::kDexTypeAnnotationSetItem)) {
2601       return false;
2602     }
2603     field_item++;
2604   }
2605 
2606   // Method annotations follow immediately after field annotations.
2607   const DexFile::MethodAnnotationsItem* method_item =
2608       reinterpret_cast<const DexFile::MethodAnnotationsItem*>(field_item);
2609   uint32_t method_count = item->methods_size_;
2610   for (uint32_t i = 0; i < method_count; i++) {
2611     LOAD_METHOD(method, method_item->method_idx_, "inter_annotations_directory_item method_id",
2612                 return false)
2613     if (UNLIKELY(method->class_idx_ != defining_class)) {
2614       ErrorStringPrintf("Mismatched defining class for method_annotation");
2615       return false;
2616     }
2617     if (!CheckOffsetToTypeMap(method_item->annotations_off_, DexFile::kDexTypeAnnotationSetItem)) {
2618       return false;
2619     }
2620     method_item++;
2621   }
2622 
2623   // Parameter annotations follow immediately after method annotations.
2624   const DexFile::ParameterAnnotationsItem* parameter_item =
2625       reinterpret_cast<const DexFile::ParameterAnnotationsItem*>(method_item);
2626   uint32_t parameter_count = item->parameters_size_;
2627   for (uint32_t i = 0; i < parameter_count; i++) {
2628     LOAD_METHOD(parameter_method, parameter_item->method_idx_,
2629                 "inter_annotations_directory_item parameter method_id", return false)
2630     if (UNLIKELY(parameter_method->class_idx_ != defining_class)) {
2631       ErrorStringPrintf("Mismatched defining class for parameter_annotation");
2632       return false;
2633     }
2634     if (!CheckOffsetToTypeMap(parameter_item->annotations_off_,
2635         DexFile::kDexTypeAnnotationSetRefList)) {
2636       return false;
2637     }
2638     parameter_item++;
2639   }
2640 
2641   ptr_ = reinterpret_cast<const uint8_t*>(parameter_item);
2642   return true;
2643 }
2644 
CheckInterSectionIterate(size_t offset,uint32_t count,DexFile::MapItemType type)2645 bool DexFileVerifier::CheckInterSectionIterate(size_t offset,
2646                                                uint32_t count,
2647                                                DexFile::MapItemType type) {
2648   // Get the right alignment mask for the type of section.
2649   size_t alignment_mask;
2650   switch (type) {
2651     case DexFile::kDexTypeClassDataItem:
2652       alignment_mask = sizeof(uint8_t) - 1;
2653       break;
2654     default:
2655       alignment_mask = sizeof(uint32_t) - 1;
2656       break;
2657   }
2658 
2659   // Iterate through the items in the section.
2660   previous_item_ = nullptr;
2661   for (uint32_t i = 0; i < count; i++) {
2662     uint32_t new_offset = (offset + alignment_mask) & ~alignment_mask;
2663     ptr_ = begin_ + new_offset;
2664     const uint8_t* prev_ptr = ptr_;
2665 
2666     if (MapTypeToBitMask(type) == 0) {
2667       ErrorStringPrintf("Unknown map item type %x", type);
2668       return false;
2669     }
2670 
2671     // Check depending on the section type.
2672     switch (type) {
2673       case DexFile::kDexTypeHeaderItem:
2674       case DexFile::kDexTypeMapList:
2675       case DexFile::kDexTypeTypeList:
2676       case DexFile::kDexTypeCodeItem:
2677       case DexFile::kDexTypeStringDataItem:
2678       case DexFile::kDexTypeDebugInfoItem:
2679       case DexFile::kDexTypeAnnotationItem:
2680       case DexFile::kDexTypeEncodedArrayItem:
2681         break;
2682       case DexFile::kDexTypeStringIdItem: {
2683         if (!CheckInterStringIdItem()) {
2684           return false;
2685         }
2686         break;
2687       }
2688       case DexFile::kDexTypeTypeIdItem: {
2689         if (!CheckInterTypeIdItem()) {
2690           return false;
2691         }
2692         break;
2693       }
2694       case DexFile::kDexTypeProtoIdItem: {
2695         if (!CheckInterProtoIdItem()) {
2696           return false;
2697         }
2698         break;
2699       }
2700       case DexFile::kDexTypeFieldIdItem: {
2701         if (!CheckInterFieldIdItem()) {
2702           return false;
2703         }
2704         break;
2705       }
2706       case DexFile::kDexTypeMethodIdItem: {
2707         if (!CheckInterMethodIdItem()) {
2708           return false;
2709         }
2710         break;
2711       }
2712       case DexFile::kDexTypeClassDefItem: {
2713         // There shouldn't be more class definitions than type ids allow.
2714         // This check should be redundant, since there are checks that the
2715         // class_idx_ is within range and that there is only one definition
2716         // for a given type id.
2717         if (i > kTypeIdLimit) {
2718           ErrorStringPrintf("Too many class definition items");
2719           return false;
2720         }
2721         if (!CheckInterClassDefItem()) {
2722           return false;
2723         }
2724         break;
2725       }
2726       case DexFile::kDexTypeCallSiteIdItem: {
2727         if (!CheckInterCallSiteIdItem()) {
2728           return false;
2729         }
2730         break;
2731       }
2732       case DexFile::kDexTypeMethodHandleItem: {
2733         if (!CheckInterMethodHandleItem()) {
2734           return false;
2735         }
2736         break;
2737       }
2738       case DexFile::kDexTypeAnnotationSetRefList: {
2739         if (!CheckInterAnnotationSetRefList()) {
2740           return false;
2741         }
2742         break;
2743       }
2744       case DexFile::kDexTypeAnnotationSetItem: {
2745         if (!CheckInterAnnotationSetItem()) {
2746           return false;
2747         }
2748         break;
2749       }
2750       case DexFile::kDexTypeClassDataItem: {
2751         // There shouldn't be more class data than type ids allow.
2752         // This check should be redundant, since there are checks that the
2753         // class_idx_ is within range and that there is only one definition
2754         // for a given type id.
2755         if (i > kTypeIdLimit) {
2756           ErrorStringPrintf("Too many class data items");
2757           return false;
2758         }
2759         if (!CheckInterClassDataItem()) {
2760           return false;
2761         }
2762         break;
2763       }
2764       case DexFile::kDexTypeAnnotationsDirectoryItem: {
2765         if (!CheckInterAnnotationsDirectoryItem()) {
2766           return false;
2767         }
2768         break;
2769       }
2770     }
2771 
2772     previous_item_ = prev_ptr;
2773     offset = ptr_ - begin_;
2774   }
2775 
2776   return true;
2777 }
2778 
CheckInterSection()2779 bool DexFileVerifier::CheckInterSection() {
2780   const DexFile::MapList* map = reinterpret_cast<const DexFile::MapList*>(begin_ + header_->map_off_);
2781   const DexFile::MapItem* item = map->list_;
2782   uint32_t count = map->size_;
2783 
2784   // Cross check the items listed in the map.
2785   while (count--) {
2786     uint32_t section_offset = item->offset_;
2787     uint32_t section_count = item->size_;
2788     DexFile::MapItemType type = static_cast<DexFile::MapItemType>(item->type_);
2789     bool found = false;
2790 
2791     switch (type) {
2792       case DexFile::kDexTypeHeaderItem:
2793       case DexFile::kDexTypeMapList:
2794       case DexFile::kDexTypeTypeList:
2795       case DexFile::kDexTypeCodeItem:
2796       case DexFile::kDexTypeStringDataItem:
2797       case DexFile::kDexTypeDebugInfoItem:
2798       case DexFile::kDexTypeAnnotationItem:
2799       case DexFile::kDexTypeEncodedArrayItem:
2800         found = true;
2801         break;
2802       case DexFile::kDexTypeStringIdItem:
2803       case DexFile::kDexTypeTypeIdItem:
2804       case DexFile::kDexTypeProtoIdItem:
2805       case DexFile::kDexTypeFieldIdItem:
2806       case DexFile::kDexTypeMethodIdItem:
2807       case DexFile::kDexTypeClassDefItem:
2808       case DexFile::kDexTypeCallSiteIdItem:
2809       case DexFile::kDexTypeMethodHandleItem:
2810       case DexFile::kDexTypeAnnotationSetRefList:
2811       case DexFile::kDexTypeAnnotationSetItem:
2812       case DexFile::kDexTypeClassDataItem:
2813       case DexFile::kDexTypeAnnotationsDirectoryItem: {
2814         if (!CheckInterSectionIterate(section_offset, section_count, type)) {
2815           return false;
2816         }
2817         found = true;
2818         break;
2819       }
2820     }
2821 
2822     if (!found) {
2823       ErrorStringPrintf("Unknown map item type %x", item->type_);
2824       return false;
2825     }
2826 
2827     item++;
2828   }
2829 
2830   return true;
2831 }
2832 
Verify()2833 bool DexFileVerifier::Verify() {
2834   // Check the header.
2835   if (!CheckHeader()) {
2836     return false;
2837   }
2838 
2839   // Check the map section.
2840   if (!CheckMap()) {
2841     return false;
2842   }
2843 
2844   // Check structure within remaining sections.
2845   if (!CheckIntraSection()) {
2846     return false;
2847   }
2848 
2849   // Check references from one section to another.
2850   if (!CheckInterSection()) {
2851     return false;
2852   }
2853 
2854   return true;
2855 }
2856 
ErrorStringPrintf(const char * fmt,...)2857 void DexFileVerifier::ErrorStringPrintf(const char* fmt, ...) {
2858   va_list ap;
2859   va_start(ap, fmt);
2860   DCHECK(failure_reason_.empty()) << failure_reason_;
2861   failure_reason_ = StringPrintf("Failure to verify dex file '%s': ", location_);
2862   StringAppendV(&failure_reason_, fmt, ap);
2863   va_end(ap);
2864 }
2865 
2866 // Fields and methods may have only one of public/protected/private.
CheckAtMostOneOfPublicProtectedPrivate(uint32_t flags)2867 static bool CheckAtMostOneOfPublicProtectedPrivate(uint32_t flags) {
2868   size_t count = (((flags & kAccPublic) == 0) ? 0 : 1) +
2869                  (((flags & kAccProtected) == 0) ? 0 : 1) +
2870                  (((flags & kAccPrivate) == 0) ? 0 : 1);
2871   return count <= 1;
2872 }
2873 
2874 // Helper functions to retrieve names from the dex file. We do not want to rely on DexFile
2875 // functionality, as we're still verifying the dex file. begin and header correspond to the
2876 // underscored variants in the DexFileVerifier.
2877 
GetStringOrError(const uint8_t * const begin,const DexFile::Header * const header,dex::StringIndex string_idx)2878 static std::string GetStringOrError(const uint8_t* const begin,
2879                                     const DexFile::Header* const header,
2880                                     dex::StringIndex string_idx) {
2881   // The `string_idx` is not guaranteed to be valid yet.
2882   if (header->string_ids_size_ <= string_idx.index_) {
2883     return "(error)";
2884   }
2885 
2886   const DexFile::StringId* string_id =
2887       reinterpret_cast<const DexFile::StringId*>(begin + header->string_ids_off_)
2888           + string_idx.index_;
2889 
2890   // Assume that the data is OK at this point. String data has been checked at this point.
2891 
2892   const uint8_t* ptr = begin + string_id->string_data_off_;
2893   uint32_t dummy;
2894   if (!DecodeUnsignedLeb128Checked(&ptr, begin + header->file_size_, &dummy)) {
2895     return "(error)";
2896   }
2897   return reinterpret_cast<const char*>(ptr);
2898 }
2899 
GetClassOrError(const uint8_t * const begin,const DexFile::Header * const header,dex::TypeIndex class_idx)2900 static std::string GetClassOrError(const uint8_t* const begin,
2901                                    const DexFile::Header* const header,
2902                                    dex::TypeIndex class_idx) {
2903   // The `class_idx` is either `FieldId::class_idx_` or `MethodId::class_idx_` and
2904   // it has already been checked in `DexFileVerifier::CheckClassDataItemField()`
2905   // or `DexFileVerifier::CheckClassDataItemMethod()`, respectively, to match
2906   // a valid defining class.
2907   CHECK_LT(class_idx.index_, header->type_ids_size_);
2908 
2909   const DexFile::TypeId* type_id =
2910       reinterpret_cast<const DexFile::TypeId*>(begin + header->type_ids_off_) + class_idx.index_;
2911 
2912   // Assume that the data is OK at this point. Type id offsets have been checked at this point.
2913 
2914   return GetStringOrError(begin, header, type_id->descriptor_idx_);
2915 }
2916 
GetFieldDescriptionOrError(const uint8_t * const begin,const DexFile::Header * const header,uint32_t idx)2917 static std::string GetFieldDescriptionOrError(const uint8_t* const begin,
2918                                               const DexFile::Header* const header,
2919                                               uint32_t idx) {
2920   // The `idx` has already been checked in `DexFileVerifier::CheckClassDataItemField()`.
2921   CHECK_LT(idx, header->field_ids_size_);
2922 
2923   const DexFile::FieldId* field_id =
2924       reinterpret_cast<const DexFile::FieldId*>(begin + header->field_ids_off_) + idx;
2925 
2926   // Assume that the data is OK at this point. Field id offsets have been checked at this point.
2927 
2928   std::string class_name = GetClassOrError(begin, header, field_id->class_idx_);
2929   std::string field_name = GetStringOrError(begin, header, field_id->name_idx_);
2930 
2931   return class_name + "." + field_name;
2932 }
2933 
GetMethodDescriptionOrError(const uint8_t * const begin,const DexFile::Header * const header,uint32_t idx)2934 static std::string GetMethodDescriptionOrError(const uint8_t* const begin,
2935                                                const DexFile::Header* const header,
2936                                                uint32_t idx) {
2937   // The `idx` has already been checked in `DexFileVerifier::CheckClassDataItemMethod()`.
2938   CHECK_LT(idx, header->method_ids_size_);
2939 
2940   const DexFile::MethodId* method_id =
2941       reinterpret_cast<const DexFile::MethodId*>(begin + header->method_ids_off_) + idx;
2942 
2943   // Assume that the data is OK at this point. Method id offsets have been checked at this point.
2944 
2945   std::string class_name = GetClassOrError(begin, header, method_id->class_idx_);
2946   std::string method_name = GetStringOrError(begin, header, method_id->name_idx_);
2947 
2948   return class_name + "." + method_name;
2949 }
2950 
CheckFieldAccessFlags(uint32_t idx,uint32_t field_access_flags,uint32_t class_access_flags,std::string * error_msg)2951 bool DexFileVerifier::CheckFieldAccessFlags(uint32_t idx,
2952                                             uint32_t field_access_flags,
2953                                             uint32_t class_access_flags,
2954                                             std::string* error_msg) {
2955   // Generally sort out >16-bit flags.
2956   if ((field_access_flags & ~kAccJavaFlagsMask) != 0) {
2957     *error_msg = StringPrintf("Bad field access_flags for %s: %x(%s)",
2958                               GetFieldDescriptionOrError(begin_, header_, idx).c_str(),
2959                               field_access_flags,
2960                               PrettyJavaAccessFlags(field_access_flags).c_str());
2961     return false;
2962   }
2963 
2964   // Flags allowed on fields, in general. Other lower-16-bit flags are to be ignored.
2965   constexpr uint32_t kFieldAccessFlags = kAccPublic |
2966                                          kAccPrivate |
2967                                          kAccProtected |
2968                                          kAccStatic |
2969                                          kAccFinal |
2970                                          kAccVolatile |
2971                                          kAccTransient |
2972                                          kAccSynthetic |
2973                                          kAccEnum;
2974 
2975   // Fields may have only one of public/protected/final.
2976   if (!CheckAtMostOneOfPublicProtectedPrivate(field_access_flags)) {
2977     *error_msg = StringPrintf("Field may have only one of public/protected/private, %s: %x(%s)",
2978                               GetFieldDescriptionOrError(begin_, header_, idx).c_str(),
2979                               field_access_flags,
2980                               PrettyJavaAccessFlags(field_access_flags).c_str());
2981     return false;
2982   }
2983 
2984   // Interfaces have a pretty restricted list.
2985   if ((class_access_flags & kAccInterface) != 0) {
2986     // Interface fields must be public final static.
2987     constexpr uint32_t kPublicFinalStatic = kAccPublic | kAccFinal | kAccStatic;
2988     if ((field_access_flags & kPublicFinalStatic) != kPublicFinalStatic) {
2989       *error_msg = StringPrintf("Interface field is not public final static, %s: %x(%s)",
2990                                 GetFieldDescriptionOrError(begin_, header_, idx).c_str(),
2991                                 field_access_flags,
2992                                 PrettyJavaAccessFlags(field_access_flags).c_str());
2993       if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
2994         return false;
2995       } else {
2996         // Allow in older versions, but warn.
2997         LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
2998                      << *error_msg;
2999       }
3000     }
3001     // Interface fields may be synthetic, but may not have other flags.
3002     constexpr uint32_t kDisallowed = ~(kPublicFinalStatic | kAccSynthetic);
3003     if ((field_access_flags & kFieldAccessFlags & kDisallowed) != 0) {
3004       *error_msg = StringPrintf("Interface field has disallowed flag, %s: %x(%s)",
3005                                 GetFieldDescriptionOrError(begin_, header_, idx).c_str(),
3006                                 field_access_flags,
3007                                 PrettyJavaAccessFlags(field_access_flags).c_str());
3008       if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
3009         return false;
3010       } else {
3011         // Allow in older versions, but warn.
3012         LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
3013                      << *error_msg;
3014       }
3015     }
3016     return true;
3017   }
3018 
3019   // Volatile fields may not be final.
3020   constexpr uint32_t kVolatileFinal = kAccVolatile | kAccFinal;
3021   if ((field_access_flags & kVolatileFinal) == kVolatileFinal) {
3022     *error_msg = StringPrintf("Fields may not be volatile and final: %s",
3023                               GetFieldDescriptionOrError(begin_, header_, idx).c_str());
3024     return false;
3025   }
3026 
3027   return true;
3028 }
3029 
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_msg)3030 bool DexFileVerifier::CheckMethodAccessFlags(uint32_t method_index,
3031                                              uint32_t method_access_flags,
3032                                              uint32_t class_access_flags,
3033                                              uint32_t constructor_flags_by_name,
3034                                              bool has_code,
3035                                              bool expect_direct,
3036                                              std::string* error_msg) {
3037   // Generally sort out >16-bit flags, except dex knows Constructor and DeclaredSynchronized.
3038   constexpr uint32_t kAllMethodFlags =
3039       kAccJavaFlagsMask | kAccConstructor | kAccDeclaredSynchronized;
3040   if ((method_access_flags & ~kAllMethodFlags) != 0) {
3041     *error_msg = StringPrintf("Bad method access_flags for %s: %x",
3042                               GetMethodDescriptionOrError(begin_, header_, method_index).c_str(),
3043                               method_access_flags);
3044     return false;
3045   }
3046 
3047   // Flags allowed on fields, in general. Other lower-16-bit flags are to be ignored.
3048   constexpr uint32_t kMethodAccessFlags = kAccPublic |
3049                                           kAccPrivate |
3050                                           kAccProtected |
3051                                           kAccStatic |
3052                                           kAccFinal |
3053                                           kAccSynthetic |
3054                                           kAccSynchronized |
3055                                           kAccBridge |
3056                                           kAccVarargs |
3057                                           kAccNative |
3058                                           kAccAbstract |
3059                                           kAccStrict;
3060 
3061   // Methods may have only one of public/protected/final.
3062   if (!CheckAtMostOneOfPublicProtectedPrivate(method_access_flags)) {
3063     *error_msg = StringPrintf("Method may have only one of public/protected/private, %s: %x",
3064                               GetMethodDescriptionOrError(begin_, header_, method_index).c_str(),
3065                               method_access_flags);
3066     return false;
3067   }
3068 
3069   constexpr uint32_t kConstructorFlags = kAccStatic | kAccConstructor;
3070   const bool is_constructor_by_name = (constructor_flags_by_name & kConstructorFlags) != 0;
3071   const bool is_clinit_by_name = constructor_flags_by_name == kConstructorFlags;
3072 
3073   // Only methods named "<clinit>" or "<init>" may be marked constructor. Note: we cannot enforce
3074   // the reverse for backwards compatibility reasons.
3075   if (((method_access_flags & kAccConstructor) != 0) && !is_constructor_by_name) {
3076     *error_msg =
3077         StringPrintf("Method %" PRIu32 "(%s) is marked constructor, but doesn't match name",
3078                       method_index,
3079                       GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
3080     return false;
3081   }
3082 
3083   if (is_constructor_by_name) {
3084     // Check that the static constructor (= static initializer) is named "<clinit>" and that the
3085     // instance constructor is called "<init>".
3086     bool is_static = (method_access_flags & kAccStatic) != 0;
3087     if (is_static ^ is_clinit_by_name) {
3088       *error_msg = StringPrintf("Constructor %" PRIu32 "(%s) is not flagged correctly wrt/ static.",
3089                                 method_index,
3090                                 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
3091       if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
3092         return false;
3093       } else {
3094         // Allow in older versions, but warn.
3095         LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
3096                      << *error_msg;
3097       }
3098     }
3099   }
3100 
3101   // Check that static and private methods, as well as constructors, are in the direct methods list,
3102   // and other methods in the virtual methods list.
3103   bool is_direct = ((method_access_flags & (kAccStatic | kAccPrivate)) != 0) ||
3104                    is_constructor_by_name;
3105   if (is_direct != expect_direct) {
3106     *error_msg = StringPrintf("Direct/virtual method %" PRIu32 "(%s) not in expected list %d",
3107                               method_index,
3108                               GetMethodDescriptionOrError(begin_, header_, method_index).c_str(),
3109                               expect_direct);
3110     return false;
3111   }
3112 
3113   // From here on out it is easier to mask out the bits we're supposed to ignore.
3114   method_access_flags &= kMethodAccessFlags;
3115 
3116   // Interfaces are special.
3117   if ((class_access_flags & kAccInterface) != 0) {
3118     // Non-static interface methods must be public or private.
3119     uint32_t desired_flags = (kAccPublic | kAccStatic);
3120     if (dex_file_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
3121       desired_flags |= kAccPrivate;
3122     }
3123     if ((method_access_flags & desired_flags) == 0) {
3124       *error_msg = StringPrintf("Interface virtual method %" PRIu32 "(%s) is not public",
3125           method_index,
3126           GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
3127       if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
3128         return false;
3129       } else {
3130         // Allow in older versions, but warn.
3131         LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
3132                       << *error_msg;
3133       }
3134     }
3135   }
3136 
3137   // If there aren't any instructions, make sure that's expected.
3138   if (!has_code) {
3139     // Only native or abstract methods may not have code.
3140     if ((method_access_flags & (kAccNative | kAccAbstract)) == 0) {
3141       *error_msg = StringPrintf("Method %" PRIu32 "(%s) has no code, but is not marked native or "
3142                                 "abstract",
3143                                 method_index,
3144                                 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
3145       return false;
3146     }
3147     // Constructors must always have code.
3148     if (is_constructor_by_name) {
3149       *error_msg = StringPrintf("Constructor %u(%s) must not be abstract or native",
3150                                 method_index,
3151                                 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
3152       if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
3153         return false;
3154       } else {
3155         // Allow in older versions, but warn.
3156         LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
3157                       << *error_msg;
3158       }
3159     }
3160     if ((method_access_flags & kAccAbstract) != 0) {
3161       // Abstract methods are not allowed to have the following flags.
3162       constexpr uint32_t kForbidden =
3163           kAccPrivate | kAccStatic | kAccFinal | kAccNative | kAccStrict | kAccSynchronized;
3164       if ((method_access_flags & kForbidden) != 0) {
3165         *error_msg = StringPrintf("Abstract method %" PRIu32 "(%s) has disallowed access flags %x",
3166             method_index,
3167             GetMethodDescriptionOrError(begin_, header_, method_index).c_str(),
3168             method_access_flags);
3169         return false;
3170       }
3171       // Abstract methods should be in an abstract class or interface.
3172       if ((class_access_flags & (kAccInterface | kAccAbstract)) == 0) {
3173         LOG(WARNING) << "Method " << GetMethodDescriptionOrError(begin_, header_, method_index)
3174                      << " is abstract, but the declaring class is neither abstract nor an "
3175                      << "interface in dex file "
3176                      << dex_file_->GetLocation();
3177       }
3178     }
3179     // Interfaces are special.
3180     if ((class_access_flags & kAccInterface) != 0) {
3181       // Interface methods without code must be abstract.
3182       if ((method_access_flags & (kAccPublic | kAccAbstract)) != (kAccPublic | kAccAbstract)) {
3183         *error_msg = StringPrintf("Interface method %" PRIu32 "(%s) is not public and abstract",
3184             method_index,
3185             GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
3186         if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
3187           return false;
3188         } else {
3189           // Allow in older versions, but warn.
3190           LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
3191                        << *error_msg;
3192         }
3193       }
3194       // At this point, we know the method is public and abstract. This means that all the checks
3195       // for invalid combinations above applies. In addition, interface methods must not be
3196       // protected. This is caught by the check for only-one-of-public-protected-private.
3197     }
3198     return true;
3199   }
3200 
3201   // When there's code, the method must not be native or abstract.
3202   if ((method_access_flags & (kAccNative | kAccAbstract)) != 0) {
3203     *error_msg = StringPrintf("Method %" PRIu32 "(%s) has code, but is marked native or abstract",
3204                               method_index,
3205                               GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
3206     return false;
3207   }
3208 
3209   // Instance constructors must not be synchronized and a few other flags.
3210   if (constructor_flags_by_name == kAccConstructor) {
3211     static constexpr uint32_t kInitAllowed =
3212         kAccPrivate | kAccProtected | kAccPublic | kAccStrict | kAccVarargs | kAccSynthetic;
3213     if ((method_access_flags & ~kInitAllowed) != 0) {
3214       *error_msg = StringPrintf("Constructor %" PRIu32 "(%s) flagged inappropriately %x",
3215                                 method_index,
3216                                 GetMethodDescriptionOrError(begin_, header_, method_index).c_str(),
3217                                 method_access_flags);
3218       return false;
3219     }
3220   }
3221 
3222   return true;
3223 }
3224 
CheckConstructorProperties(uint32_t method_index,uint32_t constructor_flags)3225 bool DexFileVerifier::CheckConstructorProperties(
3226       uint32_t method_index,
3227       uint32_t constructor_flags) {
3228   DCHECK(constructor_flags == kAccConstructor ||
3229          constructor_flags == (kAccConstructor | kAccStatic));
3230 
3231   // Check signature matches expectations.
3232   const DexFile::MethodId* const method_id = CheckLoadMethodId(method_index,
3233                                                                "Bad <init>/<clinit> method id");
3234   if (method_id == nullptr) {
3235     return false;
3236   }
3237 
3238   // Check the ProtoId for the corresponding method.
3239   //
3240   // TODO(oth): the error message here is to satisfy the MethodId test
3241   // in the DexFileVerifierTest. The test is checking that the error
3242   // contains this string if the index is out of range.
3243   const DexFile::ProtoId* const proto_id = CheckLoadProtoId(method_id->proto_idx_,
3244                                                             "inter_method_id_item proto_idx");
3245   if (proto_id == nullptr) {
3246     return false;
3247   }
3248 
3249   Signature signature = dex_file_->GetMethodSignature(*method_id);
3250   if (constructor_flags == (kAccStatic | kAccConstructor)) {
3251     if (!signature.IsVoid() || signature.GetNumberOfParameters() != 0) {
3252       ErrorStringPrintf("<clinit> must have descriptor ()V");
3253       return false;
3254     }
3255   } else if (!signature.IsVoid()) {
3256     ErrorStringPrintf("Constructor %u(%s) must be void",
3257                       method_index,
3258                       GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
3259     return false;
3260   }
3261 
3262   return true;
3263 }
3264 
3265 }  // namespace art
3266